Skip to content

Commit fc3340d

Browse files
authored
Merge pull request #352 from camsaul/fix-351
Fix formatting when requires have metadata
2 parents 95a2797 + a0dcc9c commit fc3340d

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

cljfmt/src/cljfmt/core.cljc

+12-2
Original file line numberDiff line numberDiff line change
@@ -590,13 +590,23 @@
590590
(and (= :token (z/tag zloc))
591591
(= :as (z/sexpr zloc)))))
592592

593+
#?(:clj
594+
(defn- symbol-node? [zloc]
595+
(some-> zloc z/node n/symbol-node?)))
596+
597+
#?(:clj
598+
(defn- leftmost-symbol [zloc]
599+
(some-> zloc z/leftmost (z/find (comp symbol-node? skip-meta)))))
600+
593601
#?(:clj
594602
(defn- as-zloc->alias-mapping [as-zloc]
595603
(let [alias (some-> as-zloc z/right z/sexpr)
596-
current-namespace (some-> as-zloc z/leftmost z/sexpr)
604+
current-namespace (some-> as-zloc leftmost-symbol z/sexpr)
597605
grandparent-node (some-> as-zloc z/up z/up)
598606
parent-namespace (when-not (ns-require-form? grandparent-node)
599-
(first (z/child-sexprs grandparent-node)))]
607+
(when (or (z/vector? grandparent-node)
608+
(z/list? grandparent-node))
609+
(first (z/child-sexprs grandparent-node))))]
600610
(when (and (symbol? alias) (symbol? current-namespace))
601611
{(str alias) (if parent-namespace
602612
(format "%s.%s" parent-namespace current-namespace)

cljfmt/test/cljfmt/core_test.cljc

+27
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,33 @@
290290
{:indents {'thing.core/defn [[:inner 0]]}
291291
#?@(:cljs [:alias-map {"t" "thing.core"}])})
292292
"applies custom indentation to namespaced defn")
293+
(testing "handles metadata on or comments before forms inside ns :require list"
294+
(doseq [ignore-str [""
295+
"^{:clj-kondo/ignore [:discouraged-namespace]} "
296+
"^:clj-kondo/ignore "
297+
"^{some-symbol another-symbol} "
298+
"#_{:clj-kondo/ignore [:discouraged-namespace]} "
299+
"#_:clj-kondo/ignore "
300+
"^tag "
301+
"#_old-thing "]
302+
ns-vec-str [(str ignore-str "[thing.core :as t]")
303+
(str ignore-str "[thing [core :as t]]")
304+
(str ignore-str "(thing [core :as t])")
305+
(str "[" ignore-str "thing.core :as t]")
306+
(str ignore-str " [" ignore-str "thing.core :as t]")]
307+
:let [ns-str (str "(ns example (:require " ns-vec-str "))")]]
308+
(testing ns-str
309+
(is (reformats-to?
310+
[ns-str
311+
""
312+
"(t/defn foo [x]"
313+
"(+ x 1))"]
314+
[ns-str
315+
""
316+
"(t/defn foo [x]"
317+
" (+ x 1))"]
318+
{:indents {'ns [[:block 1]], 'thing.core/defn [[:inner 0]]}
319+
#?@(:cljs [:alias-map {"t" "thing.core"}])})))))
293320
(is (reformats-to?
294321
["(comment)"
295322
"(ns thing.core)"

0 commit comments

Comments
 (0)