export_graph.cljs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. (ns export-graph
  2. "A script that exports a graph to a sqlite.build EDN file"
  3. (:require ["fs" :as fs]
  4. ["os" :as os]
  5. ["path" :as node-path]
  6. [babashka.cli :as cli]
  7. [clojure.edn :as edn]
  8. [clojure.pprint :as pprint]
  9. [clojure.string :as string]
  10. #_:clj-kondo/ignore
  11. [logseq.db.sqlite.cli :as sqlite-cli]
  12. [logseq.db.sqlite.export :as sqlite-export]
  13. [nbb.core :as nbb]))
  14. (defn- resolve-path
  15. "If relative path, resolve with $ORIGINAL_PWD"
  16. [path]
  17. (if (node-path/isAbsolute path)
  18. path
  19. (node-path/join (or js/process.env.ORIGINAL_PWD ".") path)))
  20. (defn- get-dir-and-db-name
  21. "Gets dir and db name for use with open-db!"
  22. [graph-dir]
  23. (if (string/includes? graph-dir "/")
  24. (let [graph-dir'
  25. (node-path/join (or js/process.env.ORIGINAL_PWD ".") graph-dir)]
  26. ((juxt node-path/dirname node-path/basename) graph-dir'))
  27. [(node-path/join (os/homedir) "logseq" "graphs") graph-dir]))
  28. (def spec
  29. "Options spec"
  30. {:help {:alias :h
  31. :desc "Print help"}
  32. :include-timestamps? {:alias :t
  33. :desc "Include timestamps in export"}
  34. :file {:alias :f
  35. :desc "Saves edn to file"}
  36. :exclude-namespaces {:alias :e
  37. :coerce #{}
  38. :desc "Namespaces to exclude from properties and classes"}
  39. :export-options {:alias :E
  40. :desc "Raw options map to pass to export"}})
  41. (defn -main [args]
  42. (let [{options :opts args' :args} (cli/parse-args args {:spec spec})
  43. graph-dir (first args')
  44. _ (when (or (nil? graph-dir) (:help options))
  45. (println (str "Usage: $0 GRAPH-NAME [& ARGS] [OPTIONS]\nOptions:\n"
  46. (cli/format-opts {:spec spec})))
  47. (js/process.exit 1))
  48. [dir db-name] (get-dir-and-db-name graph-dir)
  49. conn (sqlite-cli/open-db! dir db-name)
  50. export-options (merge (select-keys options [:include-timestamps? :exclude-namespaces])
  51. (edn/read-string (:export-options options)))
  52. export-map (sqlite-export/build-export @conn {:export-type :graph :graph-options export-options})]
  53. (when (:file options)
  54. (fs/writeFileSync (resolve-path (:file options))
  55. (with-out-str (pprint/pprint export-map))))
  56. (pprint/pprint export-map)))
  57. (when (= nbb/*file* (nbb/invoked-file))
  58. (-main *command-line-args*))