db_import.cljs 9.2 KB

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