db_import.cljs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 ["fs" :as fs]
  6. ["fs/promises" :as fsp]
  7. ["os" :as os]
  8. ["path" :as node-path]
  9. [babashka.cli :as cli]
  10. [cljs.pprint :as pprint]
  11. [clojure.set :as set]
  12. [clojure.string :as string]
  13. [datascript.core :as d]
  14. [logseq.common.graph :as common-graph]
  15. [logseq.graph-parser.exporter :as gp-exporter]
  16. #_:clj-kondo/ignore
  17. [logseq.outliner.cli :as outliner-cli]
  18. [nbb.classpath :as cp]
  19. [nbb.core :as nbb]
  20. [promesa.core :as p]))
  21. (def last-tx-data (atom nil))
  22. (def original-transact! d/transact!)
  23. (defn dev-transact! [conn tx-data tx-meta]
  24. (reset! last-tx-data tx-data)
  25. (original-transact! conn tx-data tx-meta))
  26. (defn- build-graph-files
  27. "Given a file graph directory, return all files including assets and adds relative paths
  28. on ::rpath since paths are absolute by default and exporter needs relative paths for
  29. some operations"
  30. [dir*]
  31. (let [dir (node-path/resolve dir*)]
  32. (->> (common-graph/get-files dir)
  33. (concat (when (fs/existsSync (node-path/join dir* "assets"))
  34. (common-graph/readdir (node-path/join dir* "assets"))))
  35. (mapv #(hash-map :path %
  36. ::rpath (node-path/relative dir* %))))))
  37. (defn- <read-file
  38. [file]
  39. (p/let [s (fsp/readFile (:path file))]
  40. (str s)))
  41. (defn- <copy-asset-file [file db-graph-dir file-graph-dir]
  42. (p/let [parent-dir (node-path/dirname
  43. (node-path/join db-graph-dir (node-path/relative file-graph-dir (:path file))))
  44. _ (fsp/mkdir parent-dir #js {:recursive true})]
  45. (fsp/copyFile (:path file) (node-path/join parent-dir (node-path/basename (:path file))))))
  46. (defn- notify-user [{:keys [continue debug]} m]
  47. (println (:msg m))
  48. (when (:ex-data m)
  49. (println "Ex-data:" (pr-str (dissoc (:ex-data m) :error)))
  50. (println "Stacktrace:")
  51. (if-let [stack (some-> (get-in m [:ex-data :error]) ex-data :sci.impl/callstack deref)]
  52. (println (string/join
  53. "\n"
  54. (map
  55. #(str (:file %)
  56. (when (:line %) (str ":" (:line %)))
  57. (when (:sci.impl/f-meta %)
  58. (str " calls #'" (get-in % [:sci.impl/f-meta :ns]) "/" (get-in % [:sci.impl/f-meta :name]))))
  59. (reverse stack))))
  60. (println (some-> (get-in m [:ex-data :error]) .-stack)))
  61. (when debug
  62. (println "Last Tx Data:")
  63. (pprint/pprint @last-tx-data)))
  64. (when (and (= :error (:level m)) (not continue))
  65. (js/process.exit 1)))
  66. (defn default-export-options
  67. [options]
  68. {;; common options
  69. :rpath-key ::rpath
  70. :notify-user (partial notify-user options)
  71. :<read-file <read-file
  72. ;; :set-ui-state prn
  73. ;; config file options
  74. ;; TODO: Add actual default
  75. :default-config {}})
  76. (defn- import-file-graph-to-db
  77. "Import a file graph dir just like UI does. However, unlike the UI the
  78. exporter receives file maps containing keys :path and ::rpath since :path
  79. are full paths"
  80. [file-graph-dir db-graph-dir conn options]
  81. (let [*files (build-graph-files file-graph-dir)
  82. config-file (first (filter #(string/ends-with? (:path %) "logseq/config.edn") *files))
  83. _ (assert config-file "No 'logseq/config.edn' found for file graph dir")
  84. options (merge options
  85. (default-export-options options)
  86. ;; asset file options
  87. {:<copy-asset (fn copy-asset [file]
  88. (<copy-asset-file file db-graph-dir file-graph-dir))})]
  89. (p/with-redefs [d/transact! dev-transact!]
  90. (gp-exporter/export-file-graph conn conn config-file *files options))))
  91. (defn- resolve-path
  92. "If relative path, resolve with $ORIGINAL_PWD"
  93. [path]
  94. (if (node-path/isAbsolute path)
  95. path
  96. (node-path/join (or js/process.env.ORIGINAL_PWD ".") path)))
  97. (defn- import-files-to-db
  98. "Import specific doc files for dev purposes"
  99. [file conn {:keys [files] :as options}]
  100. (let [doc-options (gp-exporter/build-doc-options {:macros {}} (merge options (default-export-options options)))
  101. files' (mapv #(hash-map :path %)
  102. (into [file] (map resolve-path files)))]
  103. (p/with-redefs [d/transact! dev-transact!]
  104. (p/let [_ (gp-exporter/export-doc-files conn files' <read-file doc-options)]
  105. {:import-state (:import-state doc-options)}))))
  106. (def spec
  107. "Options spec"
  108. {:help {:alias :h
  109. :desc "Print help"}
  110. :verbose {:alias :v
  111. :desc "Verbose mode"}
  112. :debug {:alias :d
  113. :desc "Debug mode"}
  114. :continue {:alias :c
  115. :desc "Continue past import failures"}
  116. :all-tags {:alias :a
  117. :desc "All tags convert to classes"}
  118. :tag-classes {:alias :t
  119. :coerce []
  120. :desc "List of tags to convert to classes"}
  121. :files {:alias :f
  122. :coerce []
  123. :desc "Additional files to import"}
  124. :remove-inline-tags {:alias :r
  125. :desc "Remove inline tags"}
  126. :property-classes {:alias :p
  127. :coerce []
  128. :desc "List of properties whose values convert to classes"}
  129. :property-parent-classes
  130. {:alias :P
  131. :coerce []
  132. :desc "List of properties whose values convert to a parent class"}})
  133. (defn -main [args]
  134. (let [[file-graph db-graph-dir] args
  135. options (cli/parse-opts args {:spec spec})
  136. _ (when (or (< (count args) 2) (:help options))
  137. (println (str "Usage: $0 FILE-GRAPH DB-GRAPH [OPTIONS]\nOptions:\n"
  138. (cli/format-opts {:spec spec})))
  139. (js/process.exit 1))
  140. [dir db-name] (if (string/includes? db-graph-dir "/")
  141. (let [graph-dir' (resolve-path db-graph-dir)]
  142. ((juxt node-path/dirname node-path/basename) graph-dir'))
  143. [(node-path/join (os/homedir) "logseq" "graphs") db-graph-dir])
  144. file-graph' (resolve-path file-graph)
  145. conn (outliner-cli/init-conn dir db-name {:classpath (cp/get-classpath)})
  146. directory? (.isDirectory (fs/statSync file-graph'))
  147. user-options (cond-> (merge {:all-tags false} (dissoc options :verbose :files :help :continue))
  148. ;; coerce option collection into strings
  149. (:tag-classes options)
  150. (update :tag-classes (partial mapv str))
  151. true
  152. (set/rename-keys {:all-tags :convert-all-tags? :remove-inline-tags :remove-inline-tags?}))
  153. _ (when (:verbose options) (prn :options user-options))
  154. options' (merge {:user-options user-options
  155. :graph-name db-name}
  156. (select-keys options [:files :verbose :continue :debug]))]
  157. (p/let [{:keys [import-state]}
  158. (if directory?
  159. (import-file-graph-to-db file-graph' (node-path/join dir db-name) conn options')
  160. (import-files-to-db file-graph' conn options'))]
  161. (when-let [ignored-props (seq @(:ignored-properties import-state))]
  162. (println "Ignored properties:" (pr-str ignored-props)))
  163. (when-let [ignored-files (seq @(:ignored-files import-state))]
  164. (println (count ignored-files) "ignored file(s):" (pr-str (vec ignored-files))))
  165. (when (:verbose options') (println "Transacted" (count (d/datoms @conn :eavt)) "datoms"))
  166. (println "Created graph" (str db-name "!")))))
  167. (when (= nbb/*file* (:file (meta #'-main)))
  168. (-main *command-line-args*))