db_import.cljs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. (ns db-import
  2. "Imports given file(s) to a db graph. This script is primarily for
  3. developing the import feature and for engineers who want to customize
  4. the import process"
  5. (:require [clojure.string :as string]
  6. [datascript.core :as d]
  7. ["path" :as node-path]
  8. ["os" :as os]
  9. ["fs" :as fs]
  10. [nbb.core :as nbb]
  11. [babashka.cli :as cli]
  12. [logseq.common.config :as common-config]
  13. [logseq.graph-parser.exporter :as gp-exporter]
  14. [logseq.tasks.db-graph.create-graph :as create-graph]))
  15. (defn- setup-import-options
  16. [db config user-options]
  17. {:extract-options {:date-formatter (common-config/get-date-formatter config)
  18. :user-config config
  19. :filename-format (or (:file/name-format config) :legacy)}
  20. :user-options user-options
  21. :page-tags-uuid (:block/uuid (d/entity db [:block/name "pagetags"]))
  22. :import-state (gp-exporter/new-import-state)
  23. :macros (:macros config)})
  24. (defn- import-file-graph-to-db [file-graph conn db-name]
  25. ;; TODO: Read in repo config
  26. (let [import-options (setup-import-options @conn
  27. {:file/name-format :triple-lowbar}
  28. {:graph-name db-name})
  29. ;; TODO: Read files dir and port more from import
  30. file file-graph
  31. m {:file/path file
  32. :file/content (str (fs/readFileSync file))}]
  33. (gp-exporter/add-file-to-db-graph conn (:file/path m) (:file/content m) import-options)))
  34. (def spec
  35. "Options spec"
  36. {:help {:alias :h
  37. :desc "Print help"}
  38. :verbose {:alias :v
  39. :desc "Verbose mode"}})
  40. (defn -main [args]
  41. (let [[file-graph db-graph-dir] args
  42. options (cli/parse-opts args {:spec spec})
  43. _ (when (or (< (count args) 2) (:help options))
  44. (println (str "Usage: $0 FILE-GRAPH DB-GRAPH [OPTIONS]\nOptions:\n"
  45. (cli/format-opts {:spec spec})))
  46. (js/process.exit 1))
  47. [dir db-name] (if (string/includes? db-graph-dir "/")
  48. (let [graph-dir'
  49. (node-path/join (or js/process.env.ORIGINAL_PWD ".") db-graph-dir)]
  50. ((juxt node-path/dirname node-path/basename) graph-dir'))
  51. [(node-path/join (os/homedir) "logseq" "graphs") db-graph-dir])
  52. file-graph' (node-path/join (or js/process.env.ORIGINAL_PWD ".") file-graph)
  53. conn (create-graph/init-conn dir db-name)]
  54. (import-file-graph-to-db file-graph' conn db-name)
  55. (when (:verbose options) (println "Transacted" (count (d/datoms @conn :eavt)) "datoms"))
  56. (println "Created graph" (str db-name "!"))))
  57. (when (= nbb/*file* (:file (meta #'-main)))
  58. (-main *command-line-args*))