create_graph.cljs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. (ns create-graph
  2. "A script that creates a DB graph given a sqlite.build EDN file"
  3. (:require ["fs" :as fs]
  4. ["os" :as os]
  5. ["path" :as node-path]
  6. #_:clj-kondo/ignore
  7. [babashka.cli :as cli]
  8. [clojure.edn :as edn]
  9. [clojure.string :as string]
  10. [datascript.core :as d]
  11. [logseq.outliner.cli :as outliner-cli]
  12. [nbb.classpath :as cp]
  13. [nbb.core :as nbb]
  14. [validate-db]))
  15. (defn- resolve-path
  16. "If relative path, resolve with $ORIGINAL_PWD"
  17. [path]
  18. (if (node-path/isAbsolute path)
  19. path
  20. (node-path/join (or js/process.env.ORIGINAL_PWD ".") path)))
  21. (defn- get-dir-and-db-name
  22. "Gets dir and db name for use with open-db! Works for relative and absolute paths and
  23. defaults to ~/logseq/graphs/ when no '/' present in name"
  24. [graph-dir]
  25. (if (string/includes? graph-dir "/")
  26. (let [resolve-path' #(if (node-path/isAbsolute %) %
  27. ;; $ORIGINAL_PWD used by bb tasks to correct current dir
  28. (node-path/join (or js/process.env.ORIGINAL_PWD ".") %))]
  29. ((juxt node-path/dirname node-path/basename) (resolve-path' graph-dir)))
  30. [(node-path/join (os/homedir) "logseq" "graphs") graph-dir]))
  31. (def spec
  32. "Options spec"
  33. {:help {:alias :h
  34. :desc "Print help"}
  35. :validate {:alias :v
  36. :desc "Validate db after creation"}})
  37. (defn -main [args]
  38. (let [{options :opts args' :args} (cli/parse-args args {:spec spec})
  39. [graph-dir edn-path] args'
  40. _ (when (or (nil? graph-dir) (nil? edn-path) (:help options))
  41. (println (str "Usage: $0 GRAPH-NAME EDN-PATH [OPTIONS]\nOptions:\n"
  42. (cli/format-opts {:spec spec})))
  43. (js/process.exit 1))
  44. [dir db-name] (get-dir-and-db-name graph-dir)
  45. sqlite-build-edn (merge {:auto-create-ontology? true}
  46. (-> (resolve-path edn-path) fs/readFileSync str edn/read-string))
  47. conn (outliner-cli/init-conn dir db-name {:classpath (cp/get-classpath) :import-type :cli/create-graph})
  48. {:keys [init-tx block-props-tx] :as _txs} (outliner-cli/build-blocks-tx sqlite-build-edn)]
  49. (println "Generating" (count (filter :block/name init-tx)) "pages and"
  50. (count (filter :block/title init-tx)) "blocks ...")
  51. ;; (cljs.pprint/pprint _txs)
  52. (d/transact! conn init-tx)
  53. (d/transact! conn block-props-tx)
  54. (println "Created graph" (str db-name "!"))
  55. (when (:validate options)
  56. (validate-db/validate-db @conn db-name {:group-errors true :closed-maps true :humanize true}))))
  57. (when (= nbb/*file* (nbb/invoked-file))
  58. (-main *command-line-args*))