Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: f1f07f7a5ddd9be7ab4423efe98caeabf8fbfd3c (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
50
51
52
53
defmodule Pandoc do
  @moduledoc """
  Documentation for `Pandoc`.
  """

  def run(profile, ["--watch" | _]) do
    config = Application.get_env(:pandoc, profile)
    opts = [cd: config[:cd] || File.cwd!()]
    dirs = [opts[:cd], Path.join(opts[:cd], "_drafts")]

    ref =
      __MODULE__.Supervisor
      |> Supervisor.start_child(
        Supervisor.child_spec({Pandoc.Watcher, [profile, dirs: dirs]},
          restart: :transient,
          id: __MODULE__.Watcher
        )
      )
      |> case do
        {:ok, pid} -> pid
        {:error, {:already_started, pid}} -> pid
      end
      |> Process.monitor()

    receive do
      {:DOWN, ^ref, _, _, _} -> :ok
    end
  end

  def run(profile, path) do
    config = Application.get_env(:pandoc, profile)
    args = config[:args] || []

    opts = [
      cd: config[:cd] || File.cwd!(),
      into: IO.stream(:stdio, :line),
      stderr_to_stdout: true
    ]

    new_filename =
      path |> Path.basename() |> String.replace_suffix(".md", ".html") |> String.slice(11..-1//1)

    new_path = args |> List.last() |> Path.join(new_filename)
    out_path = Path.join(opts[:cd], new_path) |> Path.expand()

    if File.exists?(path) do
      args = List.replace_at(args, -1, out_path)
      "pandoc" |> System.cmd(args ++ [path], opts) |> elem(1)
    else
      File.rm(out_path)
    end
  end
end