Skip to content

Instantly share code, notes, and snippets.

@borkdude
Last active December 25, 2023 21:12
Show Gist options
  • Save borkdude/77369ba1b2d0fbd2608a8d12f518ade3 to your computer and use it in GitHub Desktop.
Save borkdude/77369ba1b2d0fbd2608a8d12f518ade3 to your computer and use it in GitHub Desktop.
Rewrite if with rewrite-clj and babashka
#!/usr/bin/env bb
(require '[rewrite-clj.zip :as z])
(def code "(defn foo [] (if true :a :b))")
(defn rewrite-if [code]
(let [zip (z/of-string code)]
(loop [zloc zip]
(if (z/end? zloc)
(z/root zloc)
(let [zloc (z/next zloc)]
(if (= :list (z/tag zloc))
(let [list-zloc (z/down zloc)]
(if (= 'if (z/sexpr list-zloc))
(let [cond-zloc (z/right list-zloc)]
(if (= true (z/sexpr cond-zloc))
(let [then-node (-> cond-zloc z/right z/node)]
(recur (z/replace zloc then-node)))
(recur zloc)))
(recur zloc)))
(recur zloc)))))))
(str (rewrite-if code)) ;;=> "(defn foo [] :a)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment