Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: 179eab8a1a157f24541eea20c98e4f56e2e3abae (plain)
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
defmodule Mix.Tasks.Pandoc do
  use Mix.Task

  @ext ".md"

  @impl true
  def run(args) do
    switches = [runtime_config: :boolean]
    {opts, remaining_args} = OptionParser.parse_head!(args, switches: switches)

    if opts[:runtime_config] do
      Mix.Task.run("app.config")
    else
      Mix.Task.run("loadpaths")
      Application.ensure_all_started(:pandoc)
    end

    Mix.Task.reenable("pandoc")
    install_and_run(remaining_args)
  end

  defp install_and_run([profile | _args] = all) do
    IO.puts("Converting markdown...")

    profile = String.to_atom(profile)
    config = Application.get_env(:pandoc, profile)
    args = config[:args] || []
    opts = [cd: config[:cd] || File.cwd!()]

    out_path = List.last(args)
    full_out_path = [opts[:cd], out_path] |> Path.join() |> Path.expand()
    File.rm_rf!(full_out_path)
    File.mkdir_p!(full_out_path)

    opts[:cd]
    |> Path.join("*#{@ext}")
    |> Path.wildcard()
    |> Enum.each(fn path ->
      case Pandoc.run(profile, Path.basename(path)) do
        0 -> :ok
        status -> Mix.raise("`mix pandoc #{Enum.join(all, " ")}` exited with #{status}")
      end
    end)
  end

  defp install_and_run([]) do
    Mix.raise("`mix pandoc` expects the profile as argument")
  end
end