1
0

db_import.cljs 9.6 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 :as ldb]
  16. [logseq.db.common.sqlite-cli :as sqlite-cli]
  17. [logseq.db.frontend.asset :as db-asset]
  18. [logseq.graph-parser.exporter :as gp-exporter]
  19. [logseq.outliner.cli :as outliner-cli]
  20. [logseq.outliner.pipeline :as outliner-pipeline]
  21. [nbb.classpath :as cp]
  22. [nbb.core :as nbb]
  23. [promesa.core :as p]))
  24. (def tx-queue (atom cljs.core/PersistentQueue.EMPTY))
  25. (def original-transact! ldb/transact!)
  26. (defn dev-transact! [conn tx-data tx-meta]
  27. (swap! tx-queue (fn [queue]
  28. (let [new-queue (conj queue {:tx-data tx-data :tx-meta tx-meta})]
  29. ;; Only care about last few so vary 10 as needed
  30. (if (> (count new-queue) 10)
  31. (pop new-queue)
  32. new-queue))))
  33. (original-transact! conn tx-data tx-meta))
  34. (defn- build-graph-files
  35. "Given a file graph directory, return all files including assets and adds relative paths
  36. on ::rpath since paths are absolute by default and exporter needs relative paths for
  37. some operations"
  38. [dir*]
  39. (let [dir (node-path/resolve dir*)]
  40. (->> (common-graph/get-files dir)
  41. (concat (when (fs/existsSync (node-path/join dir* "assets"))
  42. (common-graph/readdir (node-path/join dir* "assets"))))
  43. (mapv #(hash-map :path %
  44. ::rpath (node-path/relative dir* %))))))
  45. (defn- <read-file
  46. [file]
  47. (p/let [s (fsp/readFile (:path file))]
  48. (str s)))
  49. (defn- exceed-limit-size?
  50. "Asset size no more than 100M"
  51. [^js buffer]
  52. (> (.-length buffer) (* 100 1024 1024)))
  53. (defn- <read-and-copy-asset [db-graph-dir file assets buffer-handler]
  54. (p/let [buffer (fs/readFileSync (:path file))
  55. checksum (db-asset/<get-file-array-buffer-checksum buffer)
  56. asset-id (d/squuid)
  57. asset-name (gp-exporter/asset-path->name (:path file))
  58. asset-type (db-asset/asset-path->type (:path file))]
  59. (if (exceed-limit-size? buffer)
  60. (js/console.log (str "Skipped copying asset " (pr-str (:path file)) " because it is larger than the 100M max."))
  61. (p/let [parent-dir (node-path/join db-graph-dir common-config/local-assets-dir)
  62. {:keys [with-edn-content pdf-annotation?]} (buffer-handler buffer)]
  63. (fsp/mkdir parent-dir #js {:recursive true})
  64. (swap! assets assoc asset-name
  65. (with-edn-content
  66. {:size (.-length buffer)
  67. :type asset-type
  68. :path (:path file)
  69. :checksum checksum
  70. :asset-id asset-id}))
  71. (when-not pdf-annotation?
  72. (fsp/copyFile (:path file) (node-path/join parent-dir (str asset-id "." asset-type))))))))
  73. (defn- notify-user [{:keys [continue debug]} m]
  74. (println (:msg m))
  75. (when (:ex-data m)
  76. (println "Ex-data:" (pr-str (merge (dissoc (:ex-data m) :error)
  77. (when-let [err (get-in m [:ex-data :error])]
  78. {:original-error (ex-data (.-cause err))}))))
  79. (println "\nStacktrace:")
  80. (if-let [stack (some-> (get-in m [:ex-data :error]) ex-data :sci.impl/callstack deref)]
  81. (println (string/join
  82. "\n"
  83. (map
  84. #(str (:file %)
  85. (when (:line %) (str ":" (:line %)))
  86. (when (:sci.impl/f-meta %)
  87. (str " calls #'" (get-in % [:sci.impl/f-meta :ns]) "/" (get-in % [:sci.impl/f-meta :name]))))
  88. (reverse stack))))
  89. (println (some-> (get-in m [:ex-data :error]) .-stack)))
  90. (when debug
  91. (when-let [matching-tx (seq (filter #(and (get-in m [:ex-data :path])
  92. (= (get-in % [: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*))