Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: bf01873920f433febe0ade717c5d1cd1d0aac907 (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
54
55
56
57
58
59
60
61
defmodule Pandoc do
  @moduledoc """
  Documentation for `Pandoc`.
  """
  use GenServer

  def start_link(args) do
    GenServer.start_link(__MODULE__, args)
  end

  def init([profile | args]) do
    IO.puts "pandoc filesystem watcher init args #{inspect(args)}"
    # inspect(Application.get_all_env(:pandoc)) |> IO.puts
    inspect(Application.get_env(:pandoc, profile)) |> IO.puts
    {:ok, watcher_pid} = FileSystem.start_link(args)
    FileSystem.subscribe(watcher_pid)
    {:ok, %{watcher_pid: watcher_pid}}
  end

  def handle_info({:file_event, watcher_pid, {path, events}}, %{watcher_pid: watcher_pid} = state) do
    case {Path.extname(path), :closed in events} do
      {".md", true} ->
        System.cmd("pandoc", [
          "--mathjax",
          path,
          "-o",
          Path.join("priv/static/posts", Path.basename(path) |> String.replace_suffix(".md", ".html") |> String.slice(11..-1//1))
        ])
      _ -> nil
    end

    {:noreply, state}
  end

  def handle_info({:file_event, watcher_pid, :stop}, %{watcher_pid: watcher_pid} = state) do
    # Your own logic when monitor stop
    {:noreply, state}
  end

  def run(profile) do
    # Application.get_env(:pandoc, a1) |> inspect(pretty: true) |> IO.puts
    Application.get_all_env(profile) |> inspect(pretty: true) |> IO.puts

    ref =
      __MODULE__.Supervisor
      |> Supervisor.start_child(
        Supervisor.child_spec({Pandoc, [profile, dirs: ["priv/posts"]]}, 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
end