watcher_handler.cljs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. (ns frontend.fs.watcher-handler
  2. (:require [clojure.core.async :as async]
  3. [lambdaisland.glogi :as log]
  4. [frontend.handler.file :as file-handler]
  5. [frontend.handler.page :as page-handler]
  6. [frontend.handler.notification :as notification]
  7. [frontend.handler.route :as route-handler]
  8. [cljs-time.coerce :as tc]
  9. [frontend.config :as config]
  10. [frontend.db :as db]
  11. [frontend.state :as state]
  12. [clojure.string :as string]))
  13. (defn handle-changed!
  14. [type {:keys [dir path content stat] :as payload}]
  15. (when dir
  16. (let [repo (config/get-local-repo dir)
  17. {:keys [mtime]} stat]
  18. (cond
  19. (= "add" type)
  20. (let [db-content (db/get-file path)]
  21. (when (and (not= content db-content)
  22. ;; Avoid file overwrites
  23. ;; 1. create a new page which writes a new file
  24. ;; 2. add some new content
  25. ;; 3. file watcher notified it with the old content
  26. ;; 4. old content will overwrites the new content in step 2
  27. (not (and db-content
  28. (string/starts-with? db-content content))))
  29. (file-handler/alter-file repo path content {:re-render-root? true})))
  30. (and (= "change" type)
  31. (nil? (db/get-file path)))
  32. (println "Can't get file in the db: " path)
  33. (and (= "change" type)
  34. (not= content (db/get-file path))
  35. (when-let [last-modified-at (db/get-file-last-modified-at repo path)]
  36. (> mtime last-modified-at)))
  37. (file-handler/alter-file repo path content {:re-render-root? true})
  38. (= "unlink" type)
  39. (when-let [page-name (db/get-file-page path)]
  40. (page-handler/delete!
  41. page-name
  42. (fn []
  43. (notification/show! (str "Page " page-name " was deleted on disk.")
  44. :success)
  45. (when (= (state/get-current-page) page-name)
  46. ;; redirect to home
  47. (route-handler/redirect-to-home!)))))
  48. (contains? #{"add" "change" "unlink"} type)
  49. nil
  50. :else
  51. (log/error :fs/watcher-no-handler {:type type
  52. :payload payload})))))