db_import.cljs 8.6 KB

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