db_import.cljs 9.7 KB

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