db_import.cljs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. #_:clj-kondo/ignore
  10. [babashka.cli :as cli]
  11. [cljs.pprint :as pprint]
  12. [clojure.set :as set]
  13. [clojure.string :as string]
  14. [datascript.core :as d]
  15. [logseq.common.graph :as common-graph]
  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. (def tx-queue (atom cljs.core/PersistentQueue.EMPTY))
  23. (def original-transact! d/transact!)
  24. (defn dev-transact! [conn tx-data tx-meta]
  25. (swap! tx-queue (fn [queue]
  26. (let [new-queue (conj queue {:tx-data tx-data :tx-meta tx-meta})]
  27. ;; Only care about last few so vary 10 as needed
  28. (if (> (count new-queue) 10)
  29. (pop new-queue)
  30. new-queue))))
  31. (original-transact! conn tx-data tx-meta))
  32. (defn- build-graph-files
  33. "Given a file graph directory, return all files including assets and adds relative paths
  34. on ::rpath since paths are absolute by default and exporter needs relative paths for
  35. some operations"
  36. [dir*]
  37. (let [dir (node-path/resolve dir*)]
  38. (->> (common-graph/get-files dir)
  39. (concat (when (fs/existsSync (node-path/join dir* "assets"))
  40. (common-graph/readdir (node-path/join dir* "assets"))))
  41. (mapv #(hash-map :path %
  42. ::rpath (node-path/relative dir* %))))))
  43. (defn- <read-file
  44. [file]
  45. (p/let [s (fsp/readFile (:path file))]
  46. (str s)))
  47. (defn- <copy-asset-file [file db-graph-dir file-graph-dir]
  48. (p/let [parent-dir (node-path/dirname
  49. (node-path/join db-graph-dir (node-path/relative file-graph-dir (:path file))))
  50. _ (fsp/mkdir parent-dir #js {:recursive true})]
  51. (fsp/copyFile (:path file) (node-path/join parent-dir (node-path/basename (:path file))))))
  52. (defn- notify-user [{:keys [continue debug]} m]
  53. (println (:msg m))
  54. (when (:ex-data m)
  55. (println "Ex-data:" (pr-str (merge (dissoc (:ex-data m) :error)
  56. (when-let [err (get-in m [:ex-data :error])]
  57. {:original-error (ex-data (.-cause err))}))))
  58. (println "\nStacktrace:")
  59. (if-let [stack (some-> (get-in m [:ex-data :error]) ex-data :sci.impl/callstack deref)]
  60. (println (string/join
  61. "\n"
  62. (map
  63. #(str (:file %)
  64. (when (:line %) (str ":" (:line %)))
  65. (when (:sci.impl/f-meta %)
  66. (str " calls #'" (get-in % [:sci.impl/f-meta :ns]) "/" (get-in % [:sci.impl/f-meta :name]))))
  67. (reverse stack))))
  68. (println (some-> (get-in m [:ex-data :error]) .-stack)))
  69. (when debug
  70. (when-let [matching-tx (seq (filter #(and (get-in m [:ex-data :path])
  71. (or (= (get-in % [:tx-meta ::gp-exporter/path]) (get-in m [:ex-data :path]))
  72. (= (get-in % [:tx-meta ::outliner-pipeline/original-tx-meta ::gp-exporter/path]) (get-in m [:ex-data :path]))))
  73. @tx-queue))]
  74. (println (str "\n" (count matching-tx)) "Tx Maps for failing path:")
  75. (pprint/pprint matching-tx))))
  76. (when (and (= :error (:level m)) (not continue))
  77. (js/process.exit 1)))
  78. (defn default-export-options
  79. [options]
  80. {;; common options
  81. :rpath-key ::rpath
  82. :notify-user (partial notify-user options)
  83. :<read-file <read-file
  84. ;; :set-ui-state prn
  85. ;; config file options
  86. ;; TODO: Add actual default
  87. :default-config {}})
  88. (defn- import-file-graph-to-db
  89. "Import a file graph dir just like UI does. However, unlike the UI the
  90. exporter receives file maps containing keys :path and ::rpath since :path
  91. are full paths"
  92. [file-graph-dir db-graph-dir conn options]
  93. (let [*files (build-graph-files file-graph-dir)
  94. config-file (first (filter #(string/ends-with? (:path %) "logseq/config.edn") *files))
  95. _ (assert config-file "No 'logseq/config.edn' found for file graph dir")
  96. options (merge options
  97. (default-export-options options)
  98. ;; asset file options
  99. {:<copy-asset (fn copy-asset [file]
  100. (<copy-asset-file file db-graph-dir file-graph-dir))})]
  101. (p/with-redefs [d/transact! dev-transact!]
  102. (gp-exporter/export-file-graph conn conn config-file *files options))))
  103. (defn- resolve-path
  104. "If relative path, resolve with $ORIGINAL_PWD"
  105. [path]
  106. (if (node-path/isAbsolute path)
  107. path
  108. (node-path/join (or js/process.env.ORIGINAL_PWD ".") path)))
  109. (defn- import-files-to-db
  110. "Import specific doc files for dev purposes"
  111. [file conn {:keys [files] :as options}]
  112. (let [doc-options (gp-exporter/build-doc-options {:macros {}} (merge options (default-export-options options)))
  113. files' (mapv #(hash-map :path %)
  114. (into [file] (map resolve-path files)))]
  115. (p/with-redefs [d/transact! dev-transact!]
  116. (p/let [_ (gp-exporter/export-doc-files conn files' <read-file doc-options)]
  117. {:import-state (:import-state doc-options)}))))
  118. (defn- get-dir-and-db-name
  119. "Gets dir and db name for use with open-db! Works for relative and absolute paths and
  120. defaults to ~/logseq/graphs/ when no '/' present in name"
  121. [graph-dir]
  122. (if (string/includes? graph-dir "/")
  123. (let [resolve-path' #(if (node-path/isAbsolute %) %
  124. ;; $ORIGINAL_PWD used by bb tasks to correct current dir
  125. (node-path/join (or js/process.env.ORIGINAL_PWD ".") %))]
  126. ((juxt node-path/dirname node-path/basename) (resolve-path' graph-dir)))
  127. [(node-path/join (os/homedir) "logseq" "graphs") graph-dir]))
  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. [dir db-name] (get-dir-and-db-name db-graph-dir)
  163. file-graph' (resolve-path file-graph)
  164. conn (outliner-cli/init-conn dir db-name {:classpath (cp/get-classpath)})
  165. directory? (.isDirectory (fs/statSync file-graph'))
  166. user-options (cond-> (merge {:all-tags false} (dissoc options :verbose :files :help :continue))
  167. ;; coerce option collection into strings
  168. (:tag-classes options)
  169. (update :tag-classes (partial mapv str))
  170. true
  171. (set/rename-keys {:all-tags :convert-all-tags? :remove-inline-tags :remove-inline-tags?}))
  172. _ (when (:verbose options) (prn :options user-options))
  173. options' (merge {:user-options user-options
  174. :graph-name db-name}
  175. (select-keys options [:files :verbose :continue :debug]))]
  176. (p/let [{:keys [import-state]}
  177. (if directory?
  178. (import-file-graph-to-db file-graph' (node-path/join dir db-name) conn options')
  179. (import-files-to-db file-graph' conn options'))]
  180. (when-let [ignored-props (seq @(:ignored-properties import-state))]
  181. (println "Ignored properties:" (pr-str ignored-props)))
  182. (when-let [ignored-files (seq @(:ignored-files import-state))]
  183. (println (count ignored-files) "ignored file(s):" (pr-str (vec ignored-files))))
  184. (when (:verbose options') (println "Transacted" (count (d/datoms @conn :eavt)) "datoms"))
  185. (println "Created graph" (str db-name "!")))))
  186. (when (= nbb/*file* (nbb/invoked-file))
  187. (-main *command-line-args*))