-
Notifications
You must be signed in to change notification settings - Fork 0
/
live_builder.exs
54 lines (40 loc) · 1.52 KB
/
live_builder.exs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
defmodule BuildLiveFile do
def sort_modules(files), do: sort_modules([], files, [])
def sort_modules(sorted, [%{file: file, deps: []} = _module | remaining], depending) do
sort_modules([file | sorted], remaining, depending)
end
def sort_modules(sorted, [%{file: file, deps: deps} = module | remaining], depending) do
previous_sorted_deps =
sorted
|> Enum.with_index()
|> Enum.filter(fn {f, _i} -> f in deps end)
case previous_sorted_deps do
[] = _any_dep_not_found ->
sort_modules(sorted, remaining, [module | depending])
_ ->
last_dep_index =
previous_sorted_deps
|> Enum.map(&elem(&1, 1))
|> List.last()
first_slice = Enum.slice(sorted, 0, last_dep_index + 1)
last_slice = Enum.slice(sorted, last_dep_index + 1, length(sorted))
sorted = first_slice ++ [file] ++ last_slice
sort_modules(sorted, remaining, depending)
end
end
def sort_modules(sorted, [], [_ | _] = depending),
do: sort_modules(sorted, depending, [])
def sort_modules(sorted, [], []), do: sorted
def read_files(sorted_files) do
Enum.map(sorted_files, fn file -> File.read!(file) end)
end
def write_files(files_content, commands) do
File.write("live.exs", Enum.join(files_content ++ commands, "\n"))
end
end
{:ok, spec_file} = File.read(".live.json")
decoded = Jason.decode!(spec_file, keys: :atoms)
decoded.files
|> BuildLiveFile.sort_modules()
|> BuildLiveFile.read_files()
|> BuildLiveFile.write_files(decoded.commands)