Skip to content

Commit

Permalink
Merge pull request #352 from camsaul/fix-351
Browse files Browse the repository at this point in the history
Fix formatting when requires have metadata
  • Loading branch information
weavejester authored Dec 7, 2024
2 parents 95a2797 + a0dcc9c commit fc3340d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
14 changes: 12 additions & 2 deletions cljfmt/src/cljfmt/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -590,13 +590,23 @@
(and (= :token (z/tag zloc))
(= :as (z/sexpr zloc)))))

#?(:clj
(defn- symbol-node? [zloc]
(some-> zloc z/node n/symbol-node?)))

#?(:clj
(defn- leftmost-symbol [zloc]
(some-> zloc z/leftmost (z/find (comp symbol-node? skip-meta)))))

#?(:clj
(defn- as-zloc->alias-mapping [as-zloc]
(let [alias (some-> as-zloc z/right z/sexpr)
current-namespace (some-> as-zloc z/leftmost z/sexpr)
current-namespace (some-> as-zloc leftmost-symbol z/sexpr)
grandparent-node (some-> as-zloc z/up z/up)
parent-namespace (when-not (ns-require-form? grandparent-node)
(first (z/child-sexprs grandparent-node)))]
(when (or (z/vector? grandparent-node)
(z/list? grandparent-node))
(first (z/child-sexprs grandparent-node))))]
(when (and (symbol? alias) (symbol? current-namespace))
{(str alias) (if parent-namespace
(format "%s.%s" parent-namespace current-namespace)
Expand Down
27 changes: 27 additions & 0 deletions cljfmt/test/cljfmt/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,33 @@
{:indents {'thing.core/defn [[:inner 0]]}
#?@(:cljs [:alias-map {"t" "thing.core"}])})
"applies custom indentation to namespaced defn")
(testing "handles metadata on or comments before forms inside ns :require list"
(doseq [ignore-str [""
"^{:clj-kondo/ignore [:discouraged-namespace]} "
"^:clj-kondo/ignore "
"^{some-symbol another-symbol} "
"#_{:clj-kondo/ignore [:discouraged-namespace]} "
"#_:clj-kondo/ignore "
"^tag "
"#_old-thing "]
ns-vec-str [(str ignore-str "[thing.core :as t]")
(str ignore-str "[thing [core :as t]]")
(str ignore-str "(thing [core :as t])")
(str "[" ignore-str "thing.core :as t]")
(str ignore-str " [" ignore-str "thing.core :as t]")]
:let [ns-str (str "(ns example (:require " ns-vec-str "))")]]
(testing ns-str
(is (reformats-to?
[ns-str
""
"(t/defn foo [x]"
"(+ x 1))"]
[ns-str
""
"(t/defn foo [x]"
" (+ x 1))"]
{:indents {'ns [[:block 1]], 'thing.core/defn [[:inner 0]]}
#?@(:cljs [:alias-map {"t" "thing.core"}])})))))
(is (reformats-to?
["(comment)"
"(ns thing.core)"
Expand Down

0 comments on commit fc3340d

Please sign in to comment.