Skip to content

Commit a0dcc9c

Browse files
committed
Fix formatting when requires have metadata
1 parent c832761 commit a0dcc9c

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

cljfmt/src/cljfmt/core.cljc

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -565,13 +565,23 @@
565565
(and (= :token (z/tag zloc))
566566
(= :as (z/sexpr zloc)))))
567567

568+
#?(:clj
569+
(defn- symbol-node? [zloc]
570+
(some-> zloc z/node n/symbol-node?)))
571+
572+
#?(:clj
573+
(defn- leftmost-symbol [zloc]
574+
(some-> zloc z/leftmost (z/find (comp symbol-node? skip-meta)))))
575+
568576
#?(:clj
569577
(defn- as-zloc->alias-mapping [as-zloc]
570578
(let [alias (some-> as-zloc z/right z/sexpr)
571-
current-namespace (some-> as-zloc z/leftmost z/sexpr)
579+
current-namespace (some-> as-zloc leftmost-symbol z/sexpr)
572580
grandparent-node (some-> as-zloc z/up z/up)
573581
parent-namespace (when-not (ns-require-form? grandparent-node)
574-
(first (z/child-sexprs grandparent-node)))]
582+
(when (or (z/vector? grandparent-node)
583+
(z/list? grandparent-node))
584+
(first (z/child-sexprs grandparent-node))))]
575585
(when (and (symbol? alias) (symbol? current-namespace))
576586
{(str alias) (if parent-namespace
577587
(format "%s.%s" parent-namespace current-namespace)

cljfmt/test/cljfmt/core_test.cljc

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,33 @@
257257
{:indents {'thing.core/defn [[:inner 0]]}
258258
#?@(:cljs [:alias-map {"t" "thing.core"}])})
259259
"applies custom indentation to namespaced defn")
260+
(testing "handles metadata on or comments before forms inside ns :require list"
261+
(doseq [ignore-str [""
262+
"^{:clj-kondo/ignore [:discouraged-namespace]} "
263+
"^:clj-kondo/ignore "
264+
"^{some-symbol another-symbol} "
265+
"#_{:clj-kondo/ignore [:discouraged-namespace]} "
266+
"#_:clj-kondo/ignore "
267+
"^tag "
268+
"#_old-thing "]
269+
ns-vec-str [(str ignore-str "[thing.core :as t]")
270+
(str ignore-str "[thing [core :as t]]")
271+
(str ignore-str "(thing [core :as t])")
272+
(str "[" ignore-str "thing.core :as t]")
273+
(str ignore-str " [" ignore-str "thing.core :as t]")]
274+
:let [ns-str (str "(ns example (:require " ns-vec-str "))")]]
275+
(testing ns-str
276+
(is (reformats-to?
277+
[ns-str
278+
""
279+
"(t/defn foo [x]"
280+
"(+ x 1))"]
281+
[ns-str
282+
""
283+
"(t/defn foo [x]"
284+
" (+ x 1))"]
285+
{:indents {'ns [[:block 1]], 'thing.core/defn [[:inner 0]]}
286+
#?@(:cljs [:alias-map {"t" "thing.core"}])})))))
260287
(is (reformats-to?
261288
["(comment)"
262289
"(ns thing.core)"

0 commit comments

Comments
 (0)