| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- defmodule CvGen.Watchdog do
- use GenServer
- require Logger
- @name __MODULE__
- def start_link(_), do: GenServer.start(__MODULE__, [], name: @name)
- def force_reload(), do: GenServer.call(@name, :reload, 500)
- @impl true
- def init(_), do: {:ok, %{tpl_hash: "", json_hash: ""}, {:continue, :trigger_timer}}
- @impl true
- def handle_info(:timer_expired, state) do
- state =
- with tpl_hash <- hash("lib/templates/cv.html.heex"),
- json_hash <- hash("lib/templates/cv.json") do
- if tpl_hash != state.tpl_hash or json_hash != state.json_hash do
- Logger.info("Content has changed, reloading")
- CvGen.generate()
- %{tpl_hash: tpl_hash, json_hash: json_hash}
- else
- state
- end
- end
- {:noreply, state, {:continue, :trigger_timer}}
- end
- defp hash(path) do
- contents = File.read!(path)
- :crypto.hash(:md5, contents) |> Base.encode16()
- end
- @impl true
- def handle_call(:reload, _, _) do
- CvGen.generate()
- {:reply, :ok,
- %{tpl_hash: hash("lib/templates/cv.html.eex"), json_hash: hash("lib/templates/cv.json")},
- {:continue, :trigger_timer}}
- end
- @impl true
- def handle_continue(:trigger_timer, state) do
- Process.send_after(self(), :timer_expired, 100)
- {:noreply, state}
- end
- end
|