Bläddra i källkod

refactor: db ident generation with tests

Add tests for recent db ident fixes. Add check that backup keyword is valid
edn. Also generate correct keyword for cases like logseq/db-test#4 as
catch should be relied only for unexpected cases
Gabriel Horner 1 år sedan
förälder
incheckning
eff0d5e7d4

+ 18 - 12
deps/db/src/logseq/db/frontend/db_ident.cljs

@@ -52,20 +52,26 @@
               (string/replace #"\s*:\s*$" "")
               (string/replace-first #"^\d+" "")
               (string/replace " " "-")
-              (string/replace "#" "")
               ;; '/' cannot be in name - https://clojure.org/reference/reader
               (string/replace "/" "-")
-              (string/trim))]
+              (string/replace #"[#()]" "")
+              (string/trim))
+        ;; Similar check to common-util/valid-edn-keyword?. Consider merging the two use cases
+        keyword-is-valid-edn! (fn keyword-is-valid-edn! [k]
+                                (when-not (= k (edn/read-string (str k)))
+                                  (throw (ex-info "Keyword is not valid edn" {:keyword k}))))
+        k (if (seq n)
+            (keyword user-namespace n)
+            (keyword user-namespace (nano-id 8)))]
     (try
-      (when-not (seq n)
-        (throw (ex-info "name is not empty" {:n n})))
-      (let [k (keyword user-namespace n)]
-        (when-not (= k (edn/read-string (str k)))
-          (throw (ex-info "illegal keyword" {:k k})))
-        k)
+      (keyword-is-valid-edn! k)
+      k
       (catch :default _e
+        (js/console.error "Generating backup db-ident for keyword" (str k))
         (let [n (->> (filter #(re-find #"[0-9a-zA-Z-]{1}" %) (seq n))
-                     (apply str))]
-          (if (seq n)
-            (keyword user-namespace n)
-            (keyword user-namespace (nano-id 8))))))))
+                     (apply str))
+              k (if (seq n)
+                  (keyword user-namespace n)
+                  (keyword user-namespace (nano-id 8)))]
+          (keyword-is-valid-edn! k)
+          k)))))

+ 9 - 1
deps/db/test/logseq/db/frontend/db_ident_test.cljs

@@ -6,4 +6,12 @@
   (is (= "Whiteboard-Object"
          ;; Example from docs graph
          (name (db-ident/create-db-ident-from-name "user.class" "Whiteboard/Object")))
-      "ident names must not have '/' because it is a special symbol for the reader"))
+      "ident names must not have '/' because it is a special symbol for the reader")
+
+  ;; https://github.com/logseq/db-test/issues/4
+  (is (= "Deep-Neural-Networks-DNN"
+         (name (db-ident/create-db-ident-from-name "user.class" "Deep Neural Networks (DNN)")))
+      "ident names don't fail on special characters like parenthesis")
+
+  (is (seq (name (db-ident/create-db-ident-from-name "user.class" "123")))
+      "ident names can only have numbers"))