From 99c01b72616370807bc7691773f04f6b316a5745 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Sat, 19 Jun 2021 16:32:58 +0200 Subject: [PATCH] Add normalize-keywords example [skip ci] --- examples/README.md | 17 +++++++++++++++ examples/normalize-keywords.clj | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 examples/normalize-keywords.clj diff --git a/examples/README.md b/examples/README.md index 37553d7a..e03d01d0 100644 --- a/examples/README.md +++ b/examples/README.md @@ -464,3 +464,20 @@ STDIN is TTY?: true STDOUT is TTY?: true STDERR is TTY?: false ``` + +## [normalize-keywords.clj](normalize-keywords.clj) + +Provide a Clojure file to the script and it will print the Clojure file with +auto-resolved keywords normalized to fully qualified ones: `::set/foo` becomes `:clojure.set/foo`. + +``` clojure +$ cat /tmp/test.clj +(ns test (:require [clojure.set :as set])) + +[::set/foo ::bar] + +$ bb examples/normalize-keywords.clj /tmp/test.clj +(ns test (:require [clojure.set :as set])) + +[:clojure.set/foo :test/bar] +``` diff --git a/examples/normalize-keywords.clj b/examples/normalize-keywords.clj new file mode 100644 index 00000000..b4b455c7 --- /dev/null +++ b/examples/normalize-keywords.clj @@ -0,0 +1,38 @@ +(ns normalize-keywords + (:require [babashka.pods :as pods] + [rewrite-clj.node :as node] + [rewrite-clj.zip :as z])) + +(pods/load-pod 'borkdude/clj-kondo "2021.06.18") + +(require '[pod.borkdude.clj-kondo :as clj-kondo]) + +(def code (first *command-line-args*)) + +(def findings + (->> (with-in-str code + (clj-kondo/run! {:lint [code] + :config {:output {:analysis {:keywords true}}}})) + :analysis + :keywords + (filter (some-fn :alias :auto-resolved)))) + +(defn finding->keyword [{:keys [:ns :name]}] + (keyword (str ns) (str name))) + +(defn remove-locs [zloc findings] + (loop [zloc zloc + findings (seq findings)] + (if findings + (let [{:keys [:row :col] :as finding} (first findings) + node (z/node zloc) + m (meta node)] + (if (and (= row (:row m)) + (= col (:col m))) + (let [k (finding->keyword finding) + zloc (z/replace zloc (node/coerce k))] + (recur zloc (next findings))) + (recur (z/next zloc) findings))) + (println (str (z/root zloc)))))) + +(remove-locs (z/of-file code) findings)