~mika/www.m1kadev.nl

ref: 30a34b395079871509ed85c0b075c60cf02cb226 www.m1kadev.nl/kethel/lib/scripts.ex -rw-r--r-- 1.4 KiB
30a34b39 — m1ka new thought 3 months ago
                                                                                
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
require Rambo

defmodule Scripts do
  defstruct [:scripts, :project_root]

  defp ensure_file_structure(project_root) do
    File.mkdir_p!("#{project_root}/build/scripts")
  end

  defp trim_abs_path(path, project_root) do
    # ROOT + scripts/
    begin = byte_size(project_root) + byte_size("scripts/")
    # remove extension
    binary_part(path, begin, byte_size(path) - begin)
  end

  def collect(project_root) do
    %Scripts{
      scripts:
        Path.wildcard(project_root <> "/scripts/**/*.js")
        |> Task.async_stream(fn script ->
          {trim_abs_path(script, project_root), File.read!(script)}
        end)
        |> Enum.map(fn {:ok, val} -> val end),
      project_root: project_root
    }
  end

  def compile(scripts) do
    t_begin = System.monotonic_time(:millisecond)

    ensure_file_structure(scripts.project_root)

    scripts.scripts
    |> Task.async_stream(fn script -> compile_file(script, scripts.project_root) end)
    |> Enum.map(fn {:ok, val} -> val end)

    t_end = System.monotonic_time(:millisecond)
    t_end - t_begin
  end

  # data | npx lightningcss -m
  defp compile_file({path, data}, project_root) do
    {:ok, %Rambo{out: out}} = Rambo.run("npx", ["uglifyjs"], in: data)
    output_path = "#{project_root}/build/scripts#{path}"
    File.write!(output_path, out)

    IO.puts("[COMPILED] #{project_root}/scripts#{path} -> #{output_path}")
  end
end