watchdog.ex 981 B

12345678910111213141516171819202122232425262728293031323334353637
  1. defmodule CvGen.Watchdog do
  2. use GenServer
  3. require Logger
  4. def start_link(_), do: GenServer.start(__MODULE__, [])
  5. @impl true
  6. def init(_), do: {:ok, %{tpl_hash: "", json_hash: ""}, {:continue, :trigger_timer}}
  7. @impl true
  8. def handle_info(:timer_expired, state) do
  9. state =
  10. with tpl_hash <- hash("lib/templates/cv.html.eex"),
  11. json_hash <- hash("lib/templates/cv.json") do
  12. if tpl_hash != state.tpl_hash or json_hash != state.json_hash do
  13. Logger.info("Content has changed, reloading")
  14. CvGen.generate()
  15. %{tpl_hash: tpl_hash, json_hash: json_hash}
  16. else
  17. state
  18. end
  19. end
  20. {:noreply, state, {:continue, :trigger_timer}}
  21. end
  22. defp hash(path) do
  23. contents = File.read!(path)
  24. :crypto.hash(:md5, contents) |> Base.encode16()
  25. end
  26. @impl true
  27. def handle_continue(:trigger_timer, state) do
  28. Process.send_after(self(), :timer_expired, 100)
  29. {:noreply, state}
  30. end
  31. end