Add normalize-keywords example [skip ci]

This commit is contained in:
Michiel Borkent 2021-06-19 16:32:58 +02:00
parent cacb516e48
commit 99c01b7261
2 changed files with 55 additions and 0 deletions

View file

@ -464,3 +464,20 @@ STDIN is TTY?: true
STDOUT is TTY?: true STDOUT is TTY?: true
STDERR is TTY?: false 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]
```

View file

@ -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)