The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add merge tool for ratchet conflicts (#81341)
Chris Truter7f73a7464ccd
diff --git a/.claude/skills/clojure-write/SKILL.md b/.claude/skills/clojure-write/SKILL.mdindex 28badaf5f17..69bb6b4bc9d 100644--- a/.claude/skills/clojure-write/SKILL.md+++ b/.claude/skills/clojure-write/SKILL.md@@ -125,3 +125,6 @@ breakage keeps happening, *that* is the signal a comment was warranted.or `:model/X` reference, or a new module), run `./bin/mage fix-modules-config` to regenerate`.clj-kondo/config/modules/config.edn`, then run `./bin/mage project-tests modules`. The fixer is a no-op whennothing drifted; see "Module Boundaries" in the project `CLAUDE.md`.+- If `.clj-kondo/ratchets.edn` conflicts during a merge, rebase, or restack, run+ `./bin/merge-kondo-ratchets`. It preserves one-sided changes, chooses the policy that allows fewer+ suppressions when both sides change the same entry, and stops when the conflict needs a human decision.diff --git a/CLAUDE.md b/CLAUDE.mdindex 37d5e0bfa02..2c269be7bed 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -122,6 +122,7 @@ a comment, the fixer drops its exemption.Introducing a new linter: `./bin/mage kondo-insert-ignores :the-linter` inserts an ignore at every site itflags, then `./bin/mage fix-kondo-ratchets --seed :the-linter` records the budget — no big-bang cleanup.+To burn debt down, `./bin/mage kondo-redundant-ignores` lists ignores that are no longer needed (slow:full kondo run). Kondo's redundancy report can't see hook-linter warnings, so `--fix` re-lints afterremoving, puts any still-working ignore back exactly as it was, and stamps it with a `[kondo-keep]`@@ -132,6 +133,11 @@ comments (a marker trailing on a code line is left for a hand fix). `[kondo-keepby hand to protect an ignore whose exact form matters — it only counts on the line directly above theignore, or trailing on the ignore's own line.+If `.clj-kondo/ratchets.edn` conflicts during a merge, rebase, or restack, run+`./bin/merge-kondo-ratchets`. A change on one side wins over an unchanged base. When both sides change+the same policy, the tool chooses the smaller budget, a numeric budget over `:unlimited`, or a removed+entry over either. A file deleted on one side and changed on the other is left for you to resolve.+## Tool PreferencesIf `clojure-mcp` tools are available, prefer them over shell-based alternatives for Clojure development.diff --git a/bb.edn b/bb.ednindex ce9eb4a4786..638c710a102 100644--- a/bb.edn+++ b/bb.edn@@ -303,6 +303,29 @@:requires [[dev.kondo-ratchet]]:task (task! (dev.kondo-ratchet/fix! (:options parsed)))}+ merge-kondo-ratchets+ {:doc "Three-way merge conflicting .clj-kondo/ratchets.edn files."+ :examples [["./bin/mage merge-kondo-ratchets BASE OURS THEIRS OUTPUT"+ "Merge three ratchet-file stages into OUTPUT"]]+ :arg-schema [:tuple+ [:string {:name "base" :description "Merge base's ratchets file"}]+ [:string {:name "ours" :description "Git stage 2: the branch being merged or rebased onto"}]+ [:string {:name "theirs" :description "Git stage 3: the commits being applied to it"}]+ [:string {:name "output" :description "Path to write the merged ratchets file"}]]+ :requires [[dev.kondo-ratchet]]+ :task (task!+ (let [[base-path ours-path theirs-path output-path] (:arguments parsed)+ ;; Every stage goes through the reader that validates the checked-in file.+ read-stage (fn [path]+ (binding [dev.kondo-ratchet/*ratchets-file* path]+ (dev.kondo-ratchet/read-ratchets)))+ [base ours theirs] (map read-stage [base-path ours-path theirs-path])+ merged (dev.kondo-ratchet/merge-ratchets base ours theirs)]+ (spit output-path (if (dev.kondo-ratchet/disabled? merged)+ (slurp ours-path)+ (dev.kondo-ratchet/render merged)))+ (println (str "merged ratchets into " output-path))))}+check-kondo-ratchets{:doc "Fail when suppressions exceed a bounded budget or the ratchets file isn't normalized (babashka only, no JVM).":examples [["./bin/mage check-kondo-ratchets" "Exit 1 when a policy is exceeded, the file is missing, or its formatting is not normalized"]]diff --git a/bin/merge-kondo-ratchets b/bin/merge-kondo-ratchetsnew file mode 100755index 00000000000..cb261e4c4e9--- /dev/null+++ b/bin/merge-kondo-ratchets@@ -0,0 +1,48 @@+#!/usr/bin/env bash+#+# Resolve a conflicted .clj-kondo/ratchets.edn and stage the result.+# This script only reads the index stages; `./bin/mage merge-kondo-ratchets` merges the policies.++set -euo pipefail++bin_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)+cd -- "$(git rev-parse --show-toplevel)"++ratchets_file=.clj-kondo/ratchets.edn++# One "<mode> <sha> <stage>\t<path>" line per unmerged stage: 1 = base, 2 = ours, 3 = theirs.+stages=$(git ls-files -u -- "$ratchets_file" | awk '{ print $3 }')++has_stage() {+ grep -qx -- "$1" <<< "$stages"+}++if [ -z "$stages" ]; then+ echo "$ratchets_file is not conflicted" >&2+ exit 1+fi++if ! has_stage 2 || ! has_stage 3; then+ echo "$ratchets_file was deleted on one side and changed on the other; resolve it by hand" >&2+ exit 1+fi++tmp_dir=$(mktemp -d)+trap 'rm -rf -- "$tmp_dir"' EXIT++git show ":2:$ratchets_file" > "$tmp_dir/ours"+git show ":3:$ratchets_file" > "$tmp_dir/theirs"+if has_stage 1; then+ git show ":1:$ratchets_file" > "$tmp_dir/base"+else+ # Both sides added the file, so every policy is a one-sided change against an empty base.+ printf '{}\n' > "$tmp_dir/base"+fi++"$bin_dir/mage" merge-kondo-ratchets \+ "$tmp_dir/base" \+ "$tmp_dir/ours" \+ "$tmp_dir/theirs" \+ "$PWD/$ratchets_file"+git add -- "$ratchets_file"+echo "staged merged $ratchets_file"diff --git a/dev/src/dev/kondo_ratchet.clj b/dev/src/dev/kondo_ratchet.cljindex 202a458b604..f124382ac4c 100644--- a/dev/src/dev/kondo_ratchet.clj+++ b/dev/src/dev/kondo_ratchet.clj@@ -15,7 +15,7 @@(set! *warn-on-reflection* true)(def ^:dynamic *ratchets-file*- "The budgets file, relative to the repo root."+ "The budgets file, relative to the repo root. Rebind it to read a file elsewhere, such as a merge stage."".clj-kondo/ratchets.edn")(defn- read-ratchets-form@@ -37,37 +37,55 @@{:file *ratchets-file*})))form)))+(def ^:private empty-policies+ {:ignore-counts {}, :config-counts {}, :comment-exempt #{}})++(defn validate-policies+ "`ratchets` when each policy field it carries has the right shape: `:ignore-counts` maps linters to a+ non-negative integer or `:unlimited`, `:config-counts` maps linters to a non-negative integer, and+ `:comment-exempt` is a set. Every linter named anywhere must be a keyword.+ Throws otherwise, so a malformed file can never be read as a set of removals."+ [ratchets]+ (let [{:keys [ignore-counts config-counts comment-exempt]} (merge empty-policies ratchets)]+ (when-not (map? ignore-counts)+ (throw (ex-info ":ignore-counts must be a map of linter policies"+ {:ignore-counts ignore-counts})))+ (doseq [[linter policy] ignore-counts]+ (when-not (or (= policy :unlimited)+ (and (integer? policy) (not (neg? policy))))+ (throw (ex-info (format "%s has invalid policy %s; expected a non-negative integer or :unlimited"+ linter (pr-str policy))+ {:linter linter, :policy policy}))))+ (when-not (map? config-counts)+ (throw (ex-info ":config-counts must be a map of linter budgets"+ {:config-counts config-counts})))+ (doseq [[linter budget] config-counts]+ (when-not (and (integer? budget) (not (neg? budget)))+ (throw (ex-info (format "%s has invalid config budget %s; expected a non-negative integer"+ linter (pr-str budget))+ {:linter linter, :budget budget}))))+ (when-not (set? comment-exempt)+ (throw (ex-info ":comment-exempt must be a set of linters"+ {:comment-exempt comment-exempt})))+ ;; the merge keys on (str linter) and renders the same way, so a non-keyword name would be rewritten+ ;; as a keyword, collide with one, or produce a file that no longer reads back+ (doseq [linter (concat (keys ignore-counts) (keys config-counts) comment-exempt)]+ (when-not (keyword? linter)+ (throw (ex-info (format "%s is not a linter name; policies and exemptions are keyed by keyword"+ (pr-str linter))+ {:linter linter}))))+ ratchets))+(defn read-ratchets"Parsed contents of [[*ratchets-file*]], with empty defaults for omitted keys.- Throws when the file is missing; only an explicit `{:disabled true}` opts out of enforcement."+ Throws when the file is missing or a policy field is malformed (see [[validate-policies]]); only an+ explicit `{:disabled true}` opts out of enforcement."[](let [file (io/file *ratchets-file*)](when-not (.exists file)(throw (ex-info (str *ratchets-file* " is missing -- only {:disabled true} opts out of enforcement"){:file *ratchets-file*})))- (let [ratchets (merge {:ignore-counts {}, :config-counts {}, :comment-exempt #{}}- (read-ratchets-form file))]- (when-not (map? (:ignore-counts ratchets))- (throw (ex-info ":ignore-counts must be a map of linter policies"- {:ignore-counts (:ignore-counts ratchets)})))- (doseq [[linter policy] (:ignore-counts ratchets)]- (when-not (or (= policy :unlimited)- (and (integer? policy) (not (neg? policy))))- (throw (ex-info (format "%s has invalid policy %s; expected a non-negative integer or :unlimited"- linter (pr-str policy))- {:linter linter, :policy policy}))))- (when-not (map? (:config-counts ratchets))- (throw (ex-info ":config-counts must be a map of linter budgets"- {:config-counts (:config-counts ratchets)})))- (doseq [[linter budget] (:config-counts ratchets)]- (when-not (and (integer? budget) (not (neg? budget)))- (throw (ex-info (format "%s has invalid config budget %s; expected a non-negative integer"- linter (pr-str budget))- {:linter linter, :budget budget}))))- (when-not (set? (:comment-exempt ratchets))- (throw (ex-info ":comment-exempt must be a set of linters"- {:comment-exempt (:comment-exempt ratchets)})))- ratchets)))+ (validate-policies (merge empty-policies (read-ratchets-form file)))))(defn disabled?"Whether `ratchets` (default: [[read-ratchets]]) explicitly disables the ratchets."@@ -571,6 +589,88 @@"}"))"}\n")))+(def ^:private absent+ "Stands in for a policy map entry that a stage doesn't have."+ ::absent)++(defn- stricter+ "The policy allowing fewer suppressions: a missing entry allows none, and any integer bound is stricter+ than `:unlimited`."+ [a b]+ (cond+ (or (= a absent) (= b absent)) absent+ (= a :unlimited) b+ (= b :unlimited) a+ :else (min a b)))++(defn- merge-counts+ "Three-way merge a policy map. A one-sided change wins over an unchanged base.+ Concurrent changes take the [[stricter]] policy, so budgets can only tighten through a merge."+ [base ours theirs]+ (sorted-by-str+ (for [linter (into (set (keys base)) (concat (keys ours) (keys theirs)))+ :let [base-value (get base linter absent)+ ours-value (get ours linter absent)+ theirs-value (get theirs linter absent)+ merged (cond+ (= ours-value theirs-value) ours-value+ (= ours-value base-value) theirs-value+ (= theirs-value base-value) ours-value+ :else (stricter ours-value theirs-value))]+ :when (not= merged absent)]+ [linter merged])))++(defn- merge-exemptions+ "Three-way merge the `:comment-exempt` set: the side that changed a linter's membership wins.+ Independent of the count policies, since a justification exemption says nothing about how many ignores+ a linter may have."+ [base ours theirs]+ (into #{}+ (filter (fn [linter]+ (let [ours? (contains? ours linter)+ theirs? (contains? theirs linter)]+ (if (= ours? theirs?)+ ours?+ (not (contains? base linter))))))+ (into (set base) (concat ours theirs))))++(def ^:private merge-fields+ #{:ignore-counts :config-counts :comment-exempt})++(defn- validate-merge-shape+ "`ratchets` when it contains only the policy fields and `:disabled`, and each policy field passes+ [[validate-policies]]; throws otherwise."+ [ratchets]+ (when-not (map? ratchets)+ (throw (ex-info (str "a ratchet stage must be a map of policies, not " (pr-str ratchets))+ {:stage ratchets})))+ (let [unexpected (set (keys (apply dissoc ratchets :disabled merge-fields)))]+ (when (seq unexpected)+ (throw (ex-info (str "unsupported ratchet fields: " (pr-str unexpected))+ {:fields unexpected}))))+ (validate-policies ratchets))++(defn merge-ratchets+ "Three-way merge ratchets from `base`, the target branch (`ours`), and the incoming branch (`theirs`).+ Every stage is validated first, even when a disabled stage decides the result: a target that+ explicitly disables ratchets stays disabled, and an incoming disabled form leaves `ours` as it is.+ Otherwise `:ignore-counts` and `:config-counts` merge with [[merge-counts]] and `:comment-exempt`+ with [[merge-exemptions]]."+ [base ours theirs]+ (let [[base ours theirs] (map validate-merge-shape [base ours theirs])]+ (cond+ (disabled? ours) {:disabled true}+ (disabled? theirs) ours+ :else {:ignore-counts (merge-counts (:ignore-counts base {})+ (:ignore-counts ours {})+ (:ignore-counts theirs {}))+ :config-counts (merge-counts (:config-counts base {})+ (:config-counts ours {})+ (:config-counts theirs {}))+ :comment-exempt (merge-exemptions (:comment-exempt base #{})+ (:comment-exempt ours #{})+ (:comment-exempt theirs #{}))})))+(defn lowered-counts"`recorded` with each bounded budget lowered to its actual count; bounded entries with no ignores go.An `:unlimited` policy is kept as written, even at zero: it records a decision about the linter, not a count.diff --git a/dev/test/metabase/core/kondo_ratchet_test.clj b/dev/test/metabase/core/kondo_ratchet_test.cljindex c213f22c92e..33c77787f8e 100644--- a/dev/test/metabase/core/kondo_ratchet_test.clj+++ b/dev/test/metabase/core/kondo_ratchet_test.clj@@ -329,6 +329,17 @@(kondo-ratchet/read-ratchets))(str "a config budget is always a plain count, so " (pr-str value) " is rejected"))))))+(deftest read-ratchets-validates-field-shapes-test+ (doseq [[field message] [[:ignore-counts #":ignore-counts must be a map"]+ [:config-counts #":config-counts must be a map"]+ [:comment-exempt #":comment-exempt must be a set"]]]+ (let [file (doto (java.io.File/createTempFile "kondo-ratchets" ".edn")+ (spit (pr-str {field []})))]+ (binding [kondo-ratchet/*ratchets-file* (.getPath file)]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (kondo-ratchet/read-ratchets))+ (str "an empty vector under " field " is not an empty policy map"))))))+(deftest ^:parallel lowered-counts-test(is (= {:empty-unbounded :unlimited:lower 3@@ -645,6 +656,138 @@(kondo-ratchet/config-drift {:gone 2, :same 5, :up 1}{:same 5, :new 1, :up 3}))))+(defn- merge-policies+ "[[kondo-ratchet/merge-ratchets]] over `:ignore-counts` maps alone, so a test reads as the three stages."+ [base ours theirs]+ (:ignore-counts (kondo-ratchet/merge-ratchets {:ignore-counts base}+ {:ignore-counts ours}+ {:ignore-counts theirs})))++(deftest ^:parallel merge-ratchets-one-sided-changes-test+ (testing "a change on one side wins over the unchanged base, whether it adds, lowers, or removes a policy"+ (is (= {:ours-add 2, :ours-lower 3, :theirs-add 3, :theirs-raise 9, :theirs-unlimited :unlimited}+ (merge-policies {:ours-lower 5, :ours-drop 4, :theirs-raise 5, :theirs-unlimited 1}+ {:ours-add 2, :ours-lower 3, :theirs-raise 5, :theirs-unlimited 1}+ {:ours-lower 5+ :ours-drop 4+ :theirs-add 3+ :theirs-raise 9+ :theirs-unlimited :unlimited}))))+ (testing "the same change on both sides is not a conflict"+ (is (= {:both 2}+ (merge-policies {:both 5, :both-drop 1} {:both 2} {:both 2})))))++(deftest ^:parallel merge-ratchets-concurrent-changes-take-the-stricter-policy-test+ (testing "concurrent finite budgets resolve to the smaller number"+ (is (= {:a 4} (merge-policies {:a 9} {:a 6} {:a 4})))+ (is (= {:a 4} (merge-policies {:a 9} {:a 4} {:a 6}))))+ (testing "a finite budget is stricter than :unlimited, whichever side chose it"+ (is (= {:a 4} (merge-policies {:a 9} {:a :unlimited} {:a 4})))+ (is (= {:a 4} (merge-policies {:a 9} {:a 4} {:a :unlimited})))+ (is (= {:a 2} (merge-policies {:a :unlimited} {:a 2} {:a 7}))))+ (testing "a removed policy allows nothing, so it is stricter than any concurrent change"+ (is (= {} (merge-policies {:a 5} {} {:a 4})))+ (is (= {} (merge-policies {:a 5} {:a :unlimited} {})))))++(deftest ^:parallel merge-ratchets-config-counts-test+ (is (= {:config-counts {:lowered 1, :ours-add 2, :theirs-add 3}}+ (select-keys (kondo-ratchet/merge-ratchets {:config-counts {:lowered 4, :dropped 1}}+ {:config-counts {:lowered 2, :ours-add 2}}+ {:config-counts {:lowered 1, :dropped 1, :theirs-add 3}})+ [:config-counts]))))++(deftest ^:parallel merge-ratchets-absent-base-test+ (testing "with no base stage, each policy is a one-sided addition and shared linters take the stricter"+ (is (= {:ignore-counts {:ours 2, :shared 3, :theirs 3}+ :config-counts {}+ :comment-exempt #{:ours :theirs}}+ (kondo-ratchet/merge-ratchets+ {}+ {:ignore-counts {:ours 2, :shared :unlimited}, :comment-exempt #{:ours}}+ {:ignore-counts {:theirs 3, :shared 3}, :comment-exempt #{:theirs}})))))++(deftest ^:parallel merge-ratchets-comment-exempt-test+ (testing "exemptions follow the side that changed them"+ (is (= #{:kept :ours-add :theirs-add}+ (:comment-exempt (kondo-ratchet/merge-ratchets+ {:comment-exempt #{:kept :ours-drop :theirs-drop}}+ {:comment-exempt #{:kept :theirs-drop :ours-add}}+ {:comment-exempt #{:kept :ours-drop :theirs-add}})))))+ (testing "exemptions merge independently of the same linter's count policy"+ (is (= {:ignore-counts {:a 3}+ :config-counts {}+ :comment-exempt #{:a}}+ (kondo-ratchet/merge-ratchets+ {:ignore-counts {:a 5}, :comment-exempt #{}}+ {:ignore-counts {:a 3}, :comment-exempt #{}}+ {:ignore-counts {:a :unlimited}, :comment-exempt #{:a}})))))++(deftest ^:parallel merge-ratchets-render-round-trip-test+ (let [merged (kondo-ratchet/merge-ratchets+ {:ignore-counts {:a 5, :equal :unlimited, :old :unlimited, :one-sided 2}}+ {:ignore-counts {:a 4, :equal :unlimited, :one-sided :unlimited}}+ {:ignore-counts {:a 3+ :equal :unlimited+ :old :unlimited+ :one-sided 2+ :new 2+ :new-unlimited :unlimited}})]+ (is (= {:ignore-counts {:a 3+ :equal :unlimited+ :one-sided :unlimited+ :new 2+ :new-unlimited :unlimited}+ :config-counts {}+ :comment-exempt #{}}+ merged+ (edn/read-string (kondo-ratchet/render merged)))+ "rendering the merged policies preserves bounded and unlimited linters")))++(deftest ^:parallel merge-ratchets-disabled-stages-test+ (testing "a target that disables ratchets stays disabled"+ (is (= {:disabled true}+ (kondo-ratchet/merge-ratchets {:ignore-counts {:a 1}} {:disabled true} {:ignore-counts {:a 1}}))))+ (testing "an incoming disabled form leaves the target as it is"+ (is (= {:ignore-counts {:a 1}, :config-counts {}, :comment-exempt #{}}+ (kondo-ratchet/merge-ratchets+ {:ignore-counts {:a 1}}+ {:ignore-counts {:a 1}, :config-counts {}, :comment-exempt #{}}+ {:disabled true}))))+ (testing "every stage is validated before a disabled stage decides the result"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"unsupported ratchet fields: #\{:budgets\}"+ (kondo-ratchet/merge-ratchets {:ignore-counts {:a 1}}+ {:disabled true}+ {:budgets {:a 1}})))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"unsupported ratchet fields: #\{:budgets\}"+ (kondo-ratchet/merge-ratchets {:budgets {:a 1}}+ {:ignore-counts {:a 1}}+ {:disabled true})))))++(deftest ^:parallel merge-ratchets-malformed-stage-test+ (testing "an unknown field"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"unsupported ratchet fields: #\{:extra\}"+ (kondo-ratchet/merge-ratchets+ {:ignore-counts {:a 1}}+ {:ignore-counts {:a 1}, :extra 1}+ {:ignore-counts {:a 1}}))))+ (testing "a malformed policy field is an error, never an empty set of policies"+ (doseq [[stage message] [[nil #"stage must be a map of policies"]+ [[:a 1] #"stage must be a map of policies"]+ [{:config-counts []} #":config-counts must be a map"]+ [{:comment-exempt []} #":comment-exempt must be a set"]+ [{:ignore-counts {:a -1}} #"non-negative integer or :unlimited"]+ [{:config-counts {:a :never}} #"expected a non-negative integer"]]+ :let [well-formed {:ignore-counts {:a 1}, :config-counts {:a 1}, :comment-exempt #{:a}}]]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (kondo-ratchet/merge-ratchets well-formed well-formed stage))+ (str (pr-str stage) " as the incoming stage"))+ (is (thrown-with-msg? clojure.lang.ExceptionInfo message+ (kondo-ratchet/merge-ratchets stage well-formed {:disabled true}))+ (str (pr-str stage) " as the base, even when the incoming stage is disabled")))))+(deftest ^:parallel change-report-test(let [occurrences (concat (for [[linter n] {:lower 3, :over 7, :new 9, :same 4, :free 2}i (range n)]diff --git a/mage/test/mage/core_test.clj b/mage/test/mage/core_test.cljindex ba3774e6eb8..8a32aba60e4 100644--- a/mage/test/mage/core_test.clj+++ b/mage/test/mage/core_test.clj@@ -13,6 +13,7 @@[mage.doctor-test][mage.fix-unused-requires-test][mage.kondo-ratchet-test]+ [mage.merge-kondo-ratchets-test][mage.merge-yaml-migrations-test :as merge-yaml-migrations-test][mage.modules-test][mage.project-tests-test]@@ -26,6 +27,7 @@mage.doctor-test/keep-memage.fix-unused-requires-test/keep-memage.kondo-ratchet-test/keep-me+ mage.merge-kondo-ratchets-test/keep-memage.util-test/keep-memage.modules-test/keep-memage.project-tests-test/keep-mediff --git a/mage/test/mage/merge_kondo_ratchets_test.clj b/mage/test/mage/merge_kondo_ratchets_test.cljnew file mode 100644index 00000000000..3642aea0984--- /dev/null+++ b/mage/test/mage/merge_kondo_ratchets_test.clj@@ -0,0 +1,217 @@+(ns mage.merge-kondo-ratchets-test+ "`bin/merge-kondo-ratchets` against real merge conflicts in temporary repositories."+ {:clj-kondo/config (quote {:lint-as {mage.merge-kondo-ratchets-test/with-conflict clojure.core/let}})}+ (:require+ [babashka.fs :as fs]+ [babashka.process :as p]+ [clojure.edn :as edn]+ [clojure.string :as str]+ [clojure.test :refer [deftest is testing]]+ [mage.util :as u]))++;; Referenced by core_test.clj to ensure namespace is loaded+(def keep-me :loaded)++(def ^:private script+ (str u/project-root-directory "/bin/merge-kondo-ratchets"))++(def ^:private ratchets-file+ ".clj-kondo/ratchets.edn")++;; Keep the user's git configuration (hooks, merge drivers) out of the temporary repositories.+(def ^:private git-env+ {"GIT_CONFIG_GLOBAL" "/dev/null"+ "GIT_CONFIG_NOSYSTEM" "1"+ "GIT_AUTHOR_NAME" "merge test"+ "GIT_AUTHOR_EMAIL" "[email protected]"+ "GIT_COMMITTER_NAME" "merge test"+ "GIT_COMMITTER_EMAIL" "[email protected]"})++(defn- run+ "Run `args` in `dir` and return `{:exit _, :out _, :err _}` without throwing."+ [dir & args]+ (-> (apply p/shell {:dir (str dir), :out :string, :err :string, :continue true, :extra-env git-env} args)+ (select-keys [:exit :out :err])))++(defn- git [dir & args]+ (let [{:keys [exit err] :as result} (apply run dir "git" args)]+ (when-not (zero? exit)+ (throw (ex-info (str "git " (str/join " " args) " failed: " err) result)))+ (str/trim-newline (:out result))))++(defn- write-files!+ "Write `path->content` under `dir`; a nil content deletes the path."+ [dir path->content]+ (doseq [[path content] path->content+ :let [f (fs/path dir path)]]+ (if (nil? content)+ (fs/delete-if-exists f)+ (do (fs/create-dirs (fs/parent f))+ (spit (str f) content)))))++(defn- commit-all! [dir message]+ (git dir "add" "-A")+ (git dir "commit" "-q" "--allow-empty" "-m" message))++(defn- conflicted-repo!+ "A repository whose `main` branch is mid-merge of `theirs`, from a root commit holding `base`, with each+ side's files committed on top. Returns the repository directory."+ [dir {:keys [base ours theirs]}]+ (git dir "init" "-q" "-b" "main")+ (write-files! dir (merge {"app.txt" "base\n"} base))+ (commit-all! dir "base")+ (git dir "checkout" "-q" "-b" "theirs")+ (write-files! dir (merge {"app.txt" "theirs\n"} theirs))+ (commit-all! dir "theirs")+ (git dir "checkout" "-q" "main")+ (write-files! dir (merge {"app.txt" "ours\n"} ours))+ (commit-all! dir "ours")+ (let [{:keys [exit]} (run dir "git" "merge" "-q" "theirs")]+ (assert (= 1 exit) "the merge must conflict"))+ dir)++(defmacro ^:private with-conflict+ "Bind `sym` to a [[conflicted-repo!]] built from `stages`, deleting it afterwards."+ [[sym stages] & body]+ `(let [dir# (fs/create-temp-dir {:prefix "merge-kondo-ratchets-"})]+ (try+ (let [~sym (conflicted-repo! dir# ~stages)]+ ~@body)+ (finally+ (fs/delete-tree dir#)))))++(defn- status+ "`git status --porcelain` lines, so a test can see what is staged and what is still unmerged."+ [dir]+ (set (str/split-lines (git dir "status" "--porcelain"))))++(defn- ratchets-text [dir]+ (slurp (str (fs/path dir ratchets-file))))++(defn- ratchets-policies+ "The merged file's policy map; the reader skips its comment header."+ [dir]+ (edn/read-string (ratchets-text dir)))++(defn- ratchets+ "Ratchets file text for the given policies."+ [ignore-counts config-counts comment-exempt]+ (str "{:ignore-counts " (pr-str ignore-counts)+ "\n :config-counts " (pr-str config-counts)+ "\n :comment-exempt " (pr-str comment-exempt) "}\n"))++(def ^:private base-ratchets+ (ratchets {:a 5, :b :unlimited, :ours-drop 2} {:c 2} #{:b}))++(deftest resolves-concurrent-changes-test+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file (ratchets {:a 5, :b 3} {:c 1} #{})}+ :theirs {ratchets-file (ratchets {:a 4, :b :unlimited, :ours-drop 1} {:c 2} #{:b})}}]+ (let [{:keys [exit out]} (run dir script)]+ (is (= 0 exit))+ (is (str/includes? out "staged merged .clj-kondo/ratchets.edn")))+ (testing "the finite budget beats :unlimited, one-sided changes win, and a concurrent removal stays gone"+ (is (= {:ignore-counts {:a 4, :b 3}+ :config-counts {:c 1}+ :comment-exempt #{}}+ (ratchets-policies dir))))+ (testing "only the ratchets file is staged; the other conflict is left alone"+ (is (= #{"M .clj-kondo/ratchets.edn" "UU app.txt"}+ (status dir))))))++(deftest runs-from-a-subdirectory-test+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file "{:ignore-counts {:a 3}}\n", "sub/dir/file.txt" "x\n"}+ :theirs {ratchets-file "{:ignore-counts {:a 4}}\n"}}]+ (is (= 0 (:exit (run (fs/path dir "sub/dir") script))))+ (is (= {:a 3} (:ignore-counts (ratchets-policies dir))))+ (is (contains? (status dir) "M .clj-kondo/ratchets.edn"))))++(deftest both-sides-added-test+ (with-conflict [dir {:ours {ratchets-file "{:ignore-counts {:a 3, :shared :unlimited}}\n"}+ :theirs {ratchets-file "{:ignore-counts {:b 4, :shared 2}}\n"}}]+ (is (= 0 (:exit (run dir script))))+ (is (= {:ignore-counts {:a 3, :b 4, :shared 2}+ :config-counts {}+ :comment-exempt #{}}+ (ratchets-policies dir)))+ (is (= #{"M .clj-kondo/ratchets.edn" "UU app.txt"}+ (status dir)))))++(deftest keeps-a-disabled-target-verbatim-test+ (let [disabled ";; release branch\n{:disabled true}\n"]+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file disabled}+ :theirs {ratchets-file "{:ignore-counts {:a 4}}\n"}}]+ (is (= 0 (:exit (run dir script))))+ (is (= disabled (ratchets-text dir)))+ (is (= #{"UU app.txt"} (status dir))+ "resolved, and identical to the target branch so nothing shows as changed"))))++(defn- refused+ "Everything one refused run prints, having first checked that it failed and left the conflict untouched.+ Both streams, because mage reports task exceptions on stdout."+ [dir note]+ ;; Git's unmerged status describes the index, not the worktree contents: UU means both sides+ ;; modified the path; DU and UD mean one side deleted it. Rewriting the file therefore does not+ ;; change its status. To prove a refused run changed nothing, snapshot the file contents and every+ ;; unmerged index stage as well as the porcelain status.+ (let [snapshot #(let [f (fs/path dir ratchets-file)]+ [(status dir)+ (when (fs/exists? f) (slurp (str f)))+ (git dir "ls-files" "--stage" "--unmerged" "--" ratchets-file)])+ before (snapshot)+ {:keys [exit out err]} (run dir script)]+ (is (pos? exit) note)+ (is (= before (snapshot)) note)+ (str out err)))++(deftest delete-versus-modify-is-left-for-a-human-test+ (testing "deleted on the target branch"+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file nil}+ :theirs {ratchets-file "{:ignore-counts {:a 4}}\n"}}]+ (is (str/includes? (refused dir nil) "deleted on one side and changed on the other"))+ (is (contains? (status dir) "DU .clj-kondo/ratchets.edn"))))+ (testing "deleted on the incoming branch"+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file "{:ignore-counts {:a 4}}\n"}+ :theirs {ratchets-file nil}}]+ (refused dir nil)+ (is (contains? (status dir) "UD .clj-kondo/ratchets.edn")))))++(deftest malformed-stage-is-left-unresolved-test+ (testing "an invalid policy"+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file "{:ignore-counts {:a 3}}\n"}+ :theirs {ratchets-file "{:ignore-counts {:a :sometimes}}\n"}}]+ (is (str/includes? (refused dir nil) ":a has invalid policy :sometimes"))))+ (testing "a policy field of the wrong shape is not read as an empty set of policies"+ (doseq [[stage message] [["{:ignore-counts {:a 3}, :config-counts []}\n" ":config-counts must be a map"]+ ["{:ignore-counts {:a 3}, :comment-exempt []}\n" ":comment-exempt must be a set"]+ ;; the merge keys on (str linter), so "a" would be staged as :a+ ["{:ignore-counts {\"a\" 3}}\n" "is not a linter name"]]]+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file stage}+ :theirs {ratchets-file "{:ignore-counts {:a 4}}\n"}}]+ (is (str/includes? (refused dir stage) message) stage))))+ (testing "a stage that is not exactly one map is not read as an empty set of policies"+ (doseq [[stage message] [["" "is empty"]+ ["{:ignore-counts {:a 1}} {:ignore-counts {:a 2}}\n" "holds more than one form"]+ ["[:a 1]\n" "must hold a map of policies"]+ ["#=(java.lang.Runtime/getRuntime)\n" "No dispatch macro"]]]+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file stage}+ :theirs {ratchets-file "{:ignore-counts {:a 4}}\n"}}]+ (is (str/includes? (refused dir (pr-str stage)) message) (pr-str stage)))))+ (testing "an unknown field, even when the target is disabled"+ (with-conflict [dir {:base {ratchets-file base-ratchets}+ :ours {ratchets-file "{:disabled true}\n"}+ :theirs {ratchets-file "{:budgets {:a 3}}\n"}}]+ (is (str/includes? (refused dir nil) "unsupported ratchet fields: #{:budgets}")))))++(deftest refuses-an-unconflicted-file-test+ (with-conflict [dir {:base {ratchets-file base-ratchets}}]+ (let [{:keys [exit err]} (run dir script)]+ (is (= 1 exit))+ (is (str/includes? err "is not conflicted")))))