From 7e9cdf43682019fde20cae2e4cc678762f087bad Mon Sep 17 00:00:00 2001 From: zmaalick Date: Wed, 2 Dec 2026 09:19:29 +0000 Subject: [PATCH 1/4] Add check_merge_conflicts.py to simulate dependencies.yaml merges before extracting --- github_scripts/check_merge_conflicts.py | 1044 +++++++++++++++++ .../tests/test_check_merge_conflicts.py | 139 +++ 2 files changed, 1183 insertions(+) create mode 100755 github_scripts/check_merge_conflicts.py create mode 100644 github_scripts/tests/test_check_merge_conflicts.py diff --git a/github_scripts/check_merge_conflicts.py b/github_scripts/check_merge_conflicts.py new file mode 100755 index 00000000..c1ff3858 --- /dev/null +++ b/github_scripts/check_merge_conflicts.py @@ -0,0 +1,1044 @@ +#!/usr/bin/env python3 +# ----------------------------------------------------------------------------- +# (C) Crown copyright Met Office. All rights reserved. +# The file LICENCE, distributed with this code, contains details of the terms +# under which the code may be used. +# ----------------------------------------------------------------------------- +""" +Pre-flight merge conflict check for a dependencies.yaml file. + +Simulates, without a working copy, the merges that merge_sources.py / +get_git_sources.py perform in the extract task, and reports: + + * base drift: branches whose upstream base differs from the first entry + * the outcome of every merge step in the real merge order, including the + step at which the extract task would fail + * conflicted files, sorted into conflict types (auto-resolved, housekeeping, + code, other) + * a pairwise conflict table between the branches of each repository + * a suggested merge order that minimises unresolved conflicts + +Merges are simulated with `git merge-tree --write-tree` (git >= 2.38) in a +bare cache repository per dependency, so repeated runs only fetch new commits. + +Conflict resolution is modelled on the get_git_sources.py used by the suite: + + --resolver rules (default; get_git_sources.py with CONFLICT_RULES support) + Each conflicted file is resolved by the first matching `pattern=strategy` + rule (ours, theirs, union, fail): CONFLICT_RULES, then CONFLICT_IGNORES + as `ours`, defaulting to DEFAULT_RULES. One-sided files never fail. + --resolver legacy (get_git_sources.py without CONFLICT_RULES support) + Each CONFLICT_IGNORES path that exists after the merge is resolved with + `git checkout --ours`, which fails if a conflicted file under it has no + "ours" version. + +Each setting is taken from the command line, then the environment, then +[env] in the rose-app.conf of the app containing the dependencies file. + +Exit status: 0 if the extract would succeed with no base drift, 1 if it would +fail or a branch has drifted onto newer upstream code, 2 on usage/git errors. +""" + +from __future__ import annotations + +import argparse +import fnmatch +import hashlib +import json +import os +import re +import subprocess +import sys +import tempfile +from dataclasses import asdict, dataclass, field +from pathlib import Path + +import yaml + +DEFAULT_IGNORES = "dependencies.yaml,rose-stem,CONTRIBUTORS.md" +DEFAULT_RULES = "dependencies.yaml=ours,rose-stem=ours,CONTRIBUTORS.md=union" +STRATEGIES = ("ours", "theirs", "union", "fail") +DEFAULT_RELEASE_PATTERN = r"^\d{4}\.\d{2}\.\d+$" +DEFAULT_CACHE = ( + Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) + / "check_merge_conflicts" +) + +HOUSEKEEPING_PATTERNS = [ + re.compile(p) + for p in ( + r"(^|/)versions\.py$", + r"(^|/)rose-meta/", + r"(^|/)rose-stem/", + r"(^|/)CONTRIBUTORS\.md$", + r"(^|/)dependencies\.yaml$", + r"(^|/)rose-app\.conf$", + r"\.nml$", + r"(^|/)(kgo|KGO)", + r"checksum", + ) +] +CODE_SUFFIXES = { + ".f90", + ".F90", + ".f", + ".F", + ".x90", + ".X90", + ".pf", + ".py", + ".c", + ".h", + ".cpp", + ".cc", + ".inc", + ".cfg", + ".mk", +} +GIT_ENV = { + "GIT_AUTHOR_NAME": "check_merge_conflicts", + "GIT_AUTHOR_EMAIL": "check_merge_conflicts@localhost", + "GIT_COMMITTER_NAME": "check_merge_conflicts", + "GIT_COMMITTER_EMAIL": "check_merge_conflicts@localhost", + "GIT_TERMINAL_PROMPT": "0", +} + + +class GitError(Exception): + pass + + +# ----------------------------------------------------------------------------- +# Git helpers +# ----------------------------------------------------------------------------- +class Repo: + """A bare cache repository for one dependency.""" + + def __init__(self, path: Path): + self.path = path + if not (path / "HEAD").exists(): + path.mkdir(parents=True, exist_ok=True) + subprocess.run(["git", "init", "-q", "--bare", str(path)], check=True) + self._release_cache: dict[str, str | None] = {} + + def git(self, *args, check=True, input=None, env=None): + full_env = dict(os.environ, **GIT_ENV) + if env: + full_env.update(env) + result = subprocess.run( + # --git-dir works where safe.bareRepository=explicit + ["git", f"--git-dir={self.path}", *args], + capture_output=True, + text=True, + input=input, + env=full_env, + check=False, + ) + if check and result.returncode != 0: + raise GitError( + f"git {' '.join(args)} failed ({result.returncode}):\n" + f"{result.stderr.strip()}" + ) + return result + + def out(self, *args, env=None) -> str: + return self.git(*args, env=env).stdout.strip() + + def fetch(self, source: str, ref: str, dest_ref: str) -> str: + self.git("fetch", "-q", "--no-tags", source, ref or "HEAD") + sha = self.out("rev-parse", "FETCH_HEAD^{commit}") + self.git("update-ref", dest_ref, sha) + return sha + + def fetch_upstream(self, source: str) -> None: + """Fetch release tags and main from the base repository.""" + self.git( + "fetch", + "-q", + "--no-tags", + "--force", + source, + "+refs/tags/*:refs/tags/*", + ) + self.git( + "fetch", + "-q", + "--no-tags", + source, + "+main:refs/upstream/main", + check=False, + ) + + def resolve(self, ref: str) -> str | None: + res = self.git("rev-parse", "-q", "--verify", f"{ref}^{{commit}}", check=False) + return res.stdout.strip() if res.returncode == 0 else None + + def is_ancestor(self, a: str, b: str) -> bool: + return ( + self.git("merge-base", "--is-ancestor", a, b, check=False).returncode == 0 + ) + + def merge_base(self, a: str, b: str) -> str | None: + res = self.git("merge-base", a, b, check=False) + return res.stdout.strip() if res.returncode == 0 else None + + def count(self, rev_range: str) -> int: + return int(self.out("rev-list", "--count", rev_range)) + + def path_exists(self, treeish: str, path: str) -> bool: + return ( + self.git("cat-file", "-e", f"{treeish}:{path}", check=False).returncode == 0 + ) + + def newest_release(self, commit: str, pattern: re.Pattern) -> str | None: + if commit not in self._release_cache: + tags = [ + t + for t in self.out("tag", "--merged", commit).splitlines() + if pattern.match(t) + ] + self._release_cache[commit] = max(tags, key=version_key) if tags else None + return self._release_cache[commit] + + def merge_tree(self, ours: str, theirs: str) -> MergeTreeResult: + res = self.git( + "merge-tree", "--write-tree", "-z", "--name-only", ours, theirs, check=False + ) + if res.returncode not in (0, 1): + raise GitError(f"git merge-tree failed:\n{res.stderr.strip()}") + return parse_merge_tree(res.stdout) + + def commit_tree(self, tree: str, parents: list[str]) -> str: + args = ["commit-tree", tree, "-m", "simulated merge"] + for parent in parents: + args += ["-p", parent] + return self.out(*args) + + def replace_from(self, tree: str, side: str, paths: list[str]) -> str: + """Return `tree` with `paths` replaced by their version in commit + `side` (or removed if absent there).""" + if not paths: + return tree + with tempfile.TemporaryDirectory() as tmp: + env = {"GIT_INDEX_FILE": str(Path(tmp) / "index"), "GIT_WORK_TREE": tmp} + self.git("read-tree", tree, env=env) + self.git( + "update-index", + "--force-remove", + "-z", + "--stdin", + input="\0".join(paths) + "\0", + env=env, + ) + entries = self.git( + "ls-tree", "-r", "-z", side, "--", *paths, env=env + ).stdout + if entries: + self.git("update-index", "-z", "--index-info", input=entries, env=env) + return self.out("write-tree", env=env) + + +@dataclass +class MergeTreeResult: + tree: str + conflicted: list[str] + # path -> conflict kinds, e.g. "content", "modify/delete", "add/add" + kinds: dict[str, list[str]] + + +def parse_merge_tree(output: str) -> MergeTreeResult: + """Parse `git merge-tree --write-tree -z --name-only` output.""" + # Layout: \0[\0...]\0; a clean merge + # prints only \0 + head, _, messages = output.partition("\0\0") + parts = head.split("\0") + tree, conflicted = parts[0], [p for p in parts[1:] if p] + kinds: dict[str, list[str]] = {} + fields = messages.split("\0") + i = 0 + while i < len(fields) and fields[i].isdigit(): + npaths = int(fields[i]) + paths = fields[i + 1 : i + 1 + npaths] + ctype = fields[i + 1 + npaths] + message = fields[i + 2 + npaths] + i += 3 + npaths + if ctype.startswith("CONFLICT"): + match = re.search(r"CONFLICT \(([^)]+)\)", message) + kind = match.group(1) if match else ctype + for path in paths: + kinds.setdefault(path, []) + if kind not in kinds[path]: + kinds[path].append(kind) + return MergeTreeResult(tree, conflicted, kinds) + + +def version_key(tag: str) -> tuple[int, ...]: + return tuple(int(n) for n in re.findall(r"\d+", tag)) + + +# ----------------------------------------------------------------------------- +# Classification +# ----------------------------------------------------------------------------- +def under(path: str, prefix: str) -> bool: + prefix = prefix.strip().rstrip("/") + return path == prefix or path.startswith(prefix + "/") + + +def path_matches(path: str, pattern: str) -> bool: + """As get_git_sources.path_matches: globs match the whole path, plain + patterns match the file or anything under the directory.""" + if any(c in pattern for c in "*?["): + return fnmatch.fnmatchcase(path, pattern) + return under(path, pattern) + + +def parse_rules(rules: str) -> list[tuple[str, str]]: + parsed = [] + for item in rules.split(","): + item = item.strip() + if not item: + continue + pattern, sep, strategy = item.rpartition("=") + if not sep or not pattern.strip() or strategy.strip() not in STRATEGIES: + raise ValueError( + f"invalid conflict rule '{item}': expected " + f"pattern=strategy, strategy one of " + f"{', '.join(STRATEGIES)}" + ) + parsed.append((pattern.strip(), strategy.strip())) + return parsed + + +@dataclass +class Resolver: + """How the extract task resolves conflicts (see module docstring).""" + + mode: str # legacy | rules + ignores: list[str] + rules: list[tuple[str, str]] + source: str + + def strategy(self, path: str) -> str: + for pattern, strategy in self.rules: + if path_matches(path, pattern): + return strategy + return "fail" + + def is_auto(self, path: str) -> bool: + if self.mode == "legacy": + return any(under(path, ig) for ig in self.ignores if ig.strip()) + return self.strategy(path) != "fail" + + def describe(self) -> str: + if self.mode == "legacy": + return f"legacy, CONFLICT_IGNORES ({self.source}): {','.join(self.ignores)}" + rules = ",".join(f"{p}={s}" for p, s in self.rules) + return f"rules ({self.source}): {rules}" + + +def classify(path: str) -> str: + if any(p.search(path) for p in HOUSEKEEPING_PATTERNS): + return "housekeeping" + if Path(path).suffix in CODE_SUFFIXES: + return "code" + return "other" + + +# ----------------------------------------------------------------------------- +# Simulation +# ----------------------------------------------------------------------------- +@dataclass +class Entry: + index: int + source: str + ref: str + sha: str | None = None + error: str | None = None + + @property + def label(self) -> str: + owner = re.split(r"[:/]", self.source.rstrip("/")) + owner = owner[-2] if len(owner) >= 2 else self.source + return f"#{self.index} {owner}/{self.ref or 'HEAD'}" + + +@dataclass +class Drift: + base_release: str | None + branch_release: str | None + upstream_ahead: int + behind: int + status: str # ok | ahead | behind | unrelated + + +@dataclass +class StepResult: + entry: str + outcome: str # clean | auto-resolved | fail-conflict | fail-ours | error + conflicts: dict[str, list[str]] = field(default_factory=dict) + auto_resolved: list[str] = field(default_factory=list) + missing_ours: list[str] = field(default_factory=list) + kinds: dict[str, list[str]] = field(default_factory=dict) + message: str = "" + + @property + def failed(self) -> bool: + return self.outcome.startswith("fail") or self.outcome == "error" + + @property + def n_unresolved(self) -> int: + return sum(len(v) for v in self.conflicts.values()) + len(self.missing_ours) + + +def simulate_step( + repo: Repo, ours: str, entry: Entry, resolver: Resolver, on_conflict: str +) -> tuple[StepResult, str]: + """Merge entry into `ours` as get_git_sources.merge_source() would. + Returns the step result and the commit to continue from.""" + result = StepResult(entry=entry.label, outcome="clean") + mt = repo.merge_tree(ours, entry.sha) + result.kinds = {p: mt.kinds.get(p, ["content"]) for p in mt.conflicted} + if not mt.conflicted: + return result, repo.commit_tree(mt.tree, [ours, entry.sha]) + + handled: list[str] = [] + take_theirs: list[str] = [] + if resolver.mode == "legacy": + for ignore in resolver.ignores: + ignore = ignore.strip() + if not ignore or not repo.path_exists(mt.tree, ignore): + continue + for path in mt.conflicted: + if under(path, ignore) and path not in handled: + handled.append(path) + if repo.path_exists(ours, path): + result.auto_resolved.append(path) + else: + result.missing_ours.append(path) + else: + for path in mt.conflicted: + strategy = resolver.strategy(path) + if strategy != "fail": + handled.append(path) + result.auto_resolved.append(path) + if strategy == "theirs": + take_theirs.append(path) + + for path in mt.conflicted: + if path not in handled: + result.conflicts.setdefault(classify(path), []).append(path) + + if result.missing_ours: + result.outcome = "fail-ours" + result.message = ( + "`git checkout --ours` would fail: conflicted " + "file(s) under an ignored path have no version in " + "the merged-so-far source" + ) + elif result.conflicts: + result.outcome = "fail-conflict" + else: + result.outcome = "auto-resolved" + + if result.outcome == "fail-conflict" and on_conflict == "skip": + return result, ours + # Unresolved files take "ours" so later steps see this branch's + # non-conflicting changes, as a manual resolution keeping the base would. + # Union-resolved files are approximated by "ours" for later steps. + take_ours = [p for p in mt.conflicted if p not in take_theirs] + tree = repo.replace_from(mt.tree, ours, take_ours) + tree = repo.replace_from(tree, entry.sha, take_theirs) + return result, repo.commit_tree(tree, [ours, entry.sha]) + + +def simulate_sequence( + repo: Repo, base: str, entries: list[Entry], resolver: Resolver, on_conflict: str +) -> list[StepResult]: + steps = [] + head = base + for entry in entries: + if entry.sha is None: + steps.append( + StepResult( + entry=entry.label, + outcome="error", + message=entry.error or "not fetched", + ) + ) + continue + step, head = simulate_step(repo, head, entry, resolver, on_conflict) + steps.append(step) + return steps + + +def suggest_order( + repo: Repo, + base: str, + entries: list[Entry], + resolver: Resolver, + on_conflict: str, + drift_ahead: dict[str, int], +) -> list[Entry]: + """Greedy: at each step pick the remaining branch that merges with the + fewest unresolved conflicts onto the current result. Ties go to the + branch with the least upstream drift, as drift touches the most files.""" + remaining = [e for e in entries if e.sha] + order: list[Entry] = [] + head = base + while remaining: + scored = [] + for entry in remaining: + step, new_head = simulate_step(repo, head, entry, resolver, on_conflict) + scored.append( + ( + ( + step.failed, + step.n_unresolved, + drift_ahead.get(entry.label, 0), + entry.index, + ), + entry, + new_head, + ) + ) + _, best, head = min(scored, key=lambda s: s[0]) + order.append(best) + remaining.remove(best) + return order + [e for e in entries if not e.sha] + + +def check_drift( + repo: Repo, base: str, entry: Entry, pattern: re.Pattern, threshold: int +) -> Drift: + """'ahead' (drift) if the branch contains a newer release than the base + or more than `threshold` newer upstream commits; 'minor' for a few + upstream commits past the base, e.g. a branch taken from main just after + the release.""" + base_release = repo.newest_release(base, pattern) + branch_release = repo.newest_release(entry.sha, pattern) + if repo.merge_base(base, entry.sha) is None: + return Drift(base_release, branch_release, 0, 0, "unrelated") + + upstream = repo.resolve("refs/upstream/main") + ahead = 0 + if upstream: + mb = repo.merge_base(entry.sha, upstream) + if mb: + ahead = repo.count(f"{base}..{mb}") + elif ( + base_release + and branch_release + and version_key(branch_release) > version_key(base_release) + ): + ahead = repo.count(f"{base}..{branch_release}") + behind = repo.count(f"{entry.sha}..{base}") + + newer_release = bool( + base_release + and branch_release + and version_key(branch_release) > version_key(base_release) + ) + if newer_release or ahead > threshold: + status = "ahead" + elif ahead: + status = "minor" + elif behind: + status = "behind" + else: + status = "ok" + return Drift(base_release, branch_release, ahead, behind, status) + + +def pairwise( + repo: Repo, entries: list[Entry], resolver: Resolver +) -> dict[str, dict[str, int]]: + """Unresolved (not auto-resolved) conflict counts between each pair of + branches, merged directly against their own merge base.""" + table: dict[str, dict[str, int]] = {} + ok = [e for e in entries if e.sha] + for i, a in enumerate(ok): + for b in ok[i + 1 :]: + mt = repo.merge_tree(a.sha, b.sha) + n = sum(1 for p in mt.conflicted if not resolver.is_auto(p)) + table.setdefault(a.label, {})[b.label] = n + table.setdefault(b.label, {})[a.label] = n + return table + + +# ----------------------------------------------------------------------------- +# Inputs +# ----------------------------------------------------------------------------- +def load_dependencies(path: Path) -> dict[str, list[dict[str, str]]]: + data = yaml.safe_load(path.read_text()) + if not isinstance(data, dict): + raise TypeError(f"{path}: expected a mapping of repositories") + deps = {} + for name, values in data.items(): + if isinstance(values, dict): + values = [values] + if not isinstance(values, list) or not all( + isinstance(v, dict) and "source" in v and "ref" in v for v in values + ): + raise ValueError( + f"{path}: '{name}' must be a list of {{source, ref}} entries" + ) + deps[name] = values + return deps + + +def app_env(deps_file: Path) -> dict[str, str]: + """[env] settings from the rose-app.conf of the app containing the + dependencies file.""" + settings: dict[str, str] = {} + app_conf = deps_file.parent.parent / "rose-app.conf" + if app_conf.is_file(): + section = None + for line in app_conf.read_text().splitlines(): + line = line.strip() + if line.startswith("["): + section = line.strip("[]") + elif section == "env" and "=" in line: + key, value = line.split("=", 1) + settings[key.strip()] = value.strip() + return settings + + +def find_resolver(args, deps_file: Path) -> Resolver: + app_conf = app_env(deps_file) + sources = [] + + def setting(cli_value: str | None, name: str) -> str | None: + for value, origin in ( + (cli_value, f"--{name.lower().replace('_', '-')}"), + (os.environ.get(name), f"${name}"), + (app_conf.get(name), "rose-app.conf"), + ): + if value is not None: + sources.append(origin) + return value + return None + + ignores = setting(args.conflict_ignores, "CONFLICT_IGNORES") + if args.resolver == "legacy": + if ignores is None: + return Resolver( + "legacy", DEFAULT_IGNORES.split(","), [], "get_git_sources.py default" + ) + return Resolver("legacy", ignores.split(","), [], sources[0]) + + rules = parse_rules(setting(args.conflict_rules, "CONFLICT_RULES") or "") + rules += [(p.strip(), "ours") for p in (ignores or "").split(",") if p.strip()] + if not rules: + return Resolver( + "rules", [], parse_rules(DEFAULT_RULES), "get_git_sources.py default" + ) + return Resolver("rules", [], rules, ", ".join(sources)) + + +def to_url(source: str, https: bool) -> str: + if https and source.startswith("git@github.com:"): + return source.replace("git@github.com:", "https://github.com/") + return source + + +# ----------------------------------------------------------------------------- +# Reporting +# ----------------------------------------------------------------------------- +def fmt_kinds(step: StepResult, path: str) -> str: + return ", ".join(step.kinds.get(path, [])) + + +def print_repo_report(name: str, rep: dict, max_files: int) -> None: + print(f"\n{'=' * 78}\n{name}\n{'=' * 78}") + base = rep["base"] + print(f"Base: {base['label']} (release {base.get('release') or 'unknown'})") + if rep.get("tool_error"): + print(f" TOOL ERROR (check incomplete): {rep['tool_error']}") + return + if rep.get("error"): + print(f" ERROR: {rep['error']}") + return + if rep.get("local_source_warning"): + print(f" NOTE: {rep['local_source_warning']}") + + if not rep["steps"]: + print(" (single entry, nothing to merge)") + return + + print("\nBranch bases:") + for label, d in rep["drift"].items(): + if d is None: + print(f" {label:<55} not fetched") + continue + flag = { + "ok": "ok", + "ahead": ( + f"DRIFT: contains {d['upstream_ahead']} upstream " + f"commits newer than base (to ~{d['branch_release']})" + ), + "minor": ( + f"ok ({d['upstream_ahead']} upstream commits past " + f"base, still {d['branch_release']})" + ), + "behind": ( + f"older base ({d['branch_release']}, {d['behind']} commits behind base)" + ), + "unrelated": "UNRELATED history to base", + }[d["status"]] + print(f" {label:<55} {flag}") + + order = [s["entry"] for s in rep["steps"]] + print("\nMerge steps (current order):") + for step in rep["steps"]: + s = StepResult(**step) + print(f" {s.entry:<55} {s.outcome}") + if s.message: + print(f" {s.message}") + if s.failed and rep.get("pairwise", {}).get(s.entry): + earlier = [ + lbl + for lbl, n in rep["pairwise"][s.entry].items() + if n and order.index(lbl) < order.index(s.entry) + ] + if earlier: + print(f" conflicts directly with: {', '.join(earlier)}") + else: + print( + " no single earlier branch conflicts with it: " + "the conflict comes from a combination of branches" + ) + if s.auto_resolved: + print( + f" auto-resolved by the conflict resolver: " + f"{len(s.auto_resolved)} file(s)" + ) + if s.missing_ours: + print(" no 'ours' version (checkout --ours fails):") + for p in s.missing_ours[:max_files]: + print(f" {p} [{fmt_kinds(s, p)}]") + if len(s.missing_ours) > max_files: + print(f" ... {len(s.missing_ours) - max_files} more") + for ctype in ("code", "housekeeping", "other"): + paths = s.conflicts.get(ctype, []) + if not paths: + continue + print(f" {ctype}: {len(paths)} file(s)") + for p in paths[:max_files]: + print(f" {p} [{fmt_kinds(s, p)}]") + if len(paths) > max_files: + print(f" ... {len(paths) - max_files} more") + + if rep.get("pairwise"): + labels = sorted(rep["pairwise"], key=lambda lbl: int(lbl.split()[0][1:])) + print("\nPairwise unresolved conflicts (branch vs branch):") + print(" " + " " * 6 + "".join(f"{lbl.split()[0]:>6}" for lbl in labels)) + for a in labels: + row = "".join( + f"{'-' if a == b else rep['pairwise'][a].get(b, ''):>6}" for b in labels + ) + print(f" {a.split()[0]:>6}{row}") + + if rep.get("suggested_order"): + sug = rep["suggested_order"] + print( + f"\nSuggested order ({sug['unresolved']} unresolved conflict " + f"file(s), {sug['failures']} failing step(s); current order: " + f"{rep['totals']['unresolved']}, {rep['totals']['failures']}):" + ) + for label in sug["order"]: + print(f" {label}") + if any(d and d["status"] == "ahead" for d in rep["drift"].values()): + print( + " Reordering does not fix base drift: rebase drifted " + "branches onto the base release instead." + ) + elif rep.get("order_searched"): + print( + "\nNo merge order reduces the conflicts: they need resolving " + "in the branches or a conflict-resolution branch." + ) + + +def summarise(report: dict) -> int: + first_failure = None + drifted = [] + tool_errors = [] + for name, rep in report["repositories"].items(): + if rep.get("tool_error"): + tool_errors.append(name) + if rep.get("error") and not first_failure: + first_failure = (name, rep["base"]["label"], rep["error"]) + for step in rep.get("steps", []): + if ( + step["outcome"] in ("fail-conflict", "fail-ours", "error") + and not first_failure + ): + first_failure = (name, step["entry"], step["outcome"]) + for label, d in rep.get("drift", {}).items(): + if d and d["status"] in ("ahead", "unrelated"): + drifted.append(f"{name} {label}") + + print(f"\n{'=' * 78}\nSummary\n{'=' * 78}") + if first_failure: + print( + f"Extract would FAIL first at {first_failure[0]} " + f"{first_failure[1]} ({first_failure[2]})." + ) + else: + print( + "Extract would succeed: all conflicts are auto-resolved by " + "the conflict resolver." + ) + for item in drifted: + print(f"Base drift: {item} - rebase onto the base release.") + if tool_errors: + print(f"Check incomplete for: {', '.join(tool_errors)}") + return 2 + return 1 if first_failure or drifted else 0 + + +# ----------------------------------------------------------------------------- +# Main +# ----------------------------------------------------------------------------- +def check_repository( + name: str, + values: list[dict[str, str]], + args, + resolver: Resolver, + pattern: re.Pattern, +) -> dict: + entries = [ + Entry(i + 1, str(v["source"]), str(v["ref"] or "")) + for i, v in enumerate(values) + ] + base, branches = entries[0], entries[1:] + repo = Repo(args.cache_dir / f"{name}.git") + rep: dict = {"base": {"label": base.label}} + + if not base.source.endswith(".git") and "github.com" not in base.source: + rep["local_source_warning"] = ( + "base is a local clone; only committed changes are checked " + "(the extract task rsyncs uncommitted changes too)" + ) + + # Refs are namespaced per dependencies file so checks of different + # suites sharing the cache don't overwrite each other's entries + deps_key = hashlib.sha1(str(args.dependencies.resolve()).encode()).hexdigest()[:12] + for entry in entries: + ref_name = f"refs/deps/{deps_key}/{entry.index}" + if args.no_fetch: + entry.sha = repo.resolve(ref_name) + if entry.sha is None: + entry.error = "not in cache (run without --no-fetch)" + continue + try: + log(args, f"fetching {name} {entry.label}") + entry.sha = entry_sha = repo.fetch( + to_url(entry.source, args.https), entry.ref, ref_name + ) + log(args, f" -> {entry_sha[:12]}") + except GitError as err: + entry.error = str(err).splitlines()[-1] + + if base.sha is None: + rep["error"] = f"cannot fetch base: {base.error}" + return rep + if not args.no_fetch: + try: + log(args, f"fetching {name} release tags and main") + repo.fetch_upstream(to_url(base.source, args.https)) + except GitError as err: + log(args, f" warning: {err}") + + rep["base"]["release"] = repo.newest_release(base.sha, pattern) + rep["base"]["sha"] = base.sha + rep["drift"] = { + e.label: ( + asdict(check_drift(repo, base.sha, e, pattern, args.drift_threshold)) + if e.sha + else None + ) + for e in branches + } + + steps = simulate_sequence(repo, base.sha, branches, resolver, args.on_conflict) + rep["steps"] = [asdict(s) for s in steps] + rep["entries"] = { + e.label: {"source": e.source, "ref": e.ref, "sha": e.sha, "error": e.error} + for e in entries + } + rep["totals"] = { + "unresolved": sum(s.n_unresolved for s in steps), + "failures": sum(1 for s in steps if s.failed), + } + + if not args.no_pairwise and len([b for b in branches if b.sha]) > 1: + log(args, f"pairwise checks for {name}") + rep["pairwise"] = pairwise(repo, branches, resolver) + + if not args.no_suggest and rep["totals"]["failures"] and len(branches) > 1: + log(args, f"searching merge order for {name}") + order = suggest_order( + repo, + base.sha, + branches, + resolver, + args.on_conflict, + {k: d["upstream_ahead"] for k, d in rep["drift"].items() if d}, + ) + new_steps = simulate_sequence(repo, base.sha, order, resolver, args.on_conflict) + unresolved = sum(s.n_unresolved for s in new_steps) + failures = sum(1 for s in new_steps if s.failed) + rep["order_searched"] = True + if (failures, unresolved) < ( + rep["totals"]["failures"], + rep["totals"]["unresolved"], + ): + rep["suggested_order"] = { + "order": [e.label for e in order], + "unresolved": unresolved, + "failures": failures, + } + return rep + + +def log(args, message: str) -> None: + if args.verbose: + print(message, file=sys.stderr) + + +def parse_args(argv=None): + parser = argparse.ArgumentParser( + description=__doc__.split("\n\n")[0].strip(), + epilog=__doc__.split("\n\n", 1)[1], + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "dependencies", + type=Path, + help="dependencies.yaml file, or the directory containing it", + ) + parser.add_argument( + "-r", + "--repo", + action="append", + dest="repos", + help="only check this repository (repeatable)", + ) + parser.add_argument( + "--resolver", + choices=("legacy", "rules"), + default="rules", + help="conflict handling of the suite's get_git_sources.py: 'legacy' " + "(CONFLICT_IGNORES with checkout --ours) or 'rules' " + "(CONFLICT_RULES support) (default: %(default)s)", + ) + parser.add_argument( + "--conflict-ignores", help="comma-separated paths auto-resolved as 'ours'" + ) + parser.add_argument( + "--conflict-rules", + help="comma-separated pattern=strategy rules (--resolver rules)", + ) + parser.add_argument( + "--cache-dir", + type=Path, + default=DEFAULT_CACHE, + help="bare repository cache (default: %(default)s)", + ) + parser.add_argument( + "--no-fetch", + action="store_true", + help="use the cache only; do not contact remotes", + ) + parser.add_argument( + "--https", action="store_true", help="use https instead of ssh for github.com" + ) + parser.add_argument( + "--release-pattern", + default=DEFAULT_RELEASE_PATTERN, + help="regex for release tags (default: %(default)s)", + ) + parser.add_argument( + "--drift-threshold", + type=int, + default=20, + help="upstream commits past the base, without a newer release, " + "before a branch counts as drifted (default: %(default)s)", + ) + parser.add_argument( + "--on-conflict", + choices=("ours", "skip"), + default="ours", + help="how later steps continue past a failing merge: keep the " + "branch with conflicts resolved to 'ours' (default) or skip it", + ) + parser.add_argument( + "--no-pairwise", action="store_true", help="skip the pairwise conflict table" + ) + parser.add_argument( + "--no-suggest", action="store_true", help="skip the merge order search" + ) + parser.add_argument( + "--max-files", + type=int, + default=15, + help="files listed per category (default: %(default)s)", + ) + parser.add_argument("--json", type=Path, help="also write the full report as JSON") + parser.add_argument( + "-v", "--verbose", action="store_true", help="log progress to stderr" + ) + return parser.parse_args(argv) + + +def main(argv=None) -> int: + args = parse_args(argv) + if args.dependencies.is_dir(): + args.dependencies = args.dependencies / "dependencies.yaml" + try: + deps = load_dependencies(args.dependencies) + except (OSError, TypeError, ValueError, yaml.YAMLError) as err: + print(f"error: {err}", file=sys.stderr) + return 2 + if args.repos: + unknown = set(args.repos) - set(deps) + if unknown: + print( + f"error: not in {args.dependencies}: {', '.join(sorted(unknown))}", + file=sys.stderr, + ) + return 2 + deps = {k: v for k, v in deps.items() if k in args.repos} + + try: + resolver = find_resolver(args, args.dependencies) + except ValueError as err: + print(f"error: {err}", file=sys.stderr) + return 2 + pattern = re.compile(args.release_pattern) + print(f"Dependencies: {args.dependencies}") + print(f"Conflict resolver: {resolver.describe()}") + + report = { + "dependencies": str(args.dependencies), + "resolver": asdict(resolver), + "repositories": {}, + } + for name, values in deps.items(): + try: + rep = check_repository(name, values, args, resolver, pattern) + except GitError as err: + rep = {"base": {"label": name}, "tool_error": str(err)} + report["repositories"][name] = rep + print_repo_report(name, rep, args.max_files) + + status = summarise(report) + if args.json: + args.json.write_text(json.dumps(report, indent=2)) + print(f"\nJSON report: {args.json}") + return status + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/github_scripts/tests/test_check_merge_conflicts.py b/github_scripts/tests/test_check_merge_conflicts.py new file mode 100644 index 00000000..08ee9a01 --- /dev/null +++ b/github_scripts/tests/test_check_merge_conflicts.py @@ -0,0 +1,139 @@ +# ----------------------------------------------------------------------------- +# (C) Crown copyright Met Office. All rights reserved. +# The file LICENCE, distributed with this code, contains details of the terms +# under which the code may be used. +# ----------------------------------------------------------------------------- +""" +Unit tests for check_merge_conflicts +""" + +import json +import subprocess + +import pytest + +from ..check_merge_conflicts import main, parse_rules, path_matches + + +def git(loc, *args): + subprocess.run(["git", "-C", str(loc), *args], check=True, capture_output=True) + + +@pytest.fixture +def upstream(tmp_path, monkeypatch): + """ + A repository with release tags and branches: + 2026.07.1 - base release + 2026.07.3 - main: changes a.F90, deletes rose-stem/old.txt + drift - from 2026.07.1 with main (2026.07.3) merged in + rs - from 2026.07.1: changes a.F90 and rose-stem/old.txt + clean - from 2026.07.1: adds a new file + """ + + for var in ("CONFLICT_RULES", "CONFLICT_IGNORES"): + monkeypatch.delenv(var, raising=False) + for role in ("AUTHOR", "COMMITTER"): + monkeypatch.setenv(f"GIT_{role}_NAME", "Testing") + monkeypatch.setenv(f"GIT_{role}_EMAIL", "Testing") + + repo = tmp_path / "upstream" + (repo / "rose-stem").mkdir(parents=True) + git(repo, "init", "-q", "-b", "main") + (repo / "a.F90").write_text("1\n2\n3\n") + (repo / "rose-stem" / "old.txt").write_text("old\n") + git(repo, "add", ".") + git(repo, "commit", "-q", "-m", "base") + git(repo, "tag", "2026.07.1") + + (repo / "a.F90").write_text("1\nmain\n3\n") + git(repo, "rm", "-q", "rose-stem/old.txt") + git(repo, "commit", "-q", "-am", "main") + git(repo, "tag", "2026.07.3") + + git(repo, "switch", "-q", "-c", "drift", "2026.07.1") + (repo / "d.F90").write_text("d\n") + git(repo, "add", ".") + git(repo, "commit", "-q", "-m", "drift") + git(repo, "merge", "-q", "--no-edit", "main") + + git(repo, "switch", "-q", "-c", "rs", "2026.07.1") + (repo / "a.F90").write_text("1\nrs\n3\n") + (repo / "rose-stem" / "old.txt").write_text("changed\n") + git(repo, "commit", "-q", "-am", "rs") + + git(repo, "switch", "-q", "-c", "clean", "2026.07.1") + (repo / "new.F90").write_text("new\n") + git(repo, "add", ".") + git(repo, "commit", "-q", "-m", "clean") + git(repo, "switch", "-q", "main") + return repo + + +def check(tmp_path, upstream, refs, *args): + """ + Write a dependencies.yaml merging refs onto 2026.07.1 and run the check. + Returns the exit status and the JSON report for the repository. + """ + + entries = "".join( + f" - source: {upstream}\n ref: {ref}\n" for ref in ["2026.07.1", *refs] + ) + deps = tmp_path / "dependencies.yaml" + deps.write_text(f"repo:\n{entries}") + report = tmp_path / "report.json" + status = main( + [ + str(deps), + "--cache-dir", + str(tmp_path / "cache"), + "--json", + str(report), + "--conflict-ignores", + "rose-stem", + *args, + ] + ) + return status, json.loads(report.read_text())["repositories"]["repo"] + + +def test_rules(): + rules = parse_rules("*/versions.py=theirs, rose-stem=ours") + assert rules == [("*/versions.py", "theirs"), ("rose-stem", "ours")] + assert path_matches("a/rose-meta/versions.py", "*/versions.py") + assert path_matches("rose-stem/app/x.conf", "rose-stem") + assert not path_matches("rose-stemmed/x", "rose-stem") + for bad in ("rose-stem", "rose-stem=newest"): + with pytest.raises(ValueError): + parse_rules(bad) + + +def test_clean_merges_pass(tmp_path, upstream, capsys): + status, rep = check(tmp_path, upstream, ["clean", "rs"]) + assert status == 0 + assert [s["outcome"] for s in rep["steps"]] == ["clean", "clean"] + assert "Extract would succeed" in capsys.readouterr().out + + +def test_legacy_reports_drift_and_ours_failure(tmp_path, upstream): + status, rep = check(tmp_path, upstream, ["drift", "rs"], "--resolver", "legacy") + assert status == 1 + drift = rep["drift"] + assert [d["status"] for d in drift.values()] == ["ahead", "ok"] + assert next(iter(drift.values()))["branch_release"] == "2026.07.3" + + merged, failed = rep["steps"] + assert merged["outcome"] == "clean" + assert failed["outcome"] == "fail-ours" + assert failed["missing_ours"] == ["rose-stem/old.txt"] + assert failed["conflicts"] == {"code": ["a.F90"]} + + +def test_rules_resolve_one_sided_files(tmp_path, upstream): + status, rep = check(tmp_path, upstream, ["drift", "rs"]) + assert status == 1 + failed = rep["steps"][1] + assert failed["outcome"] == "fail-conflict" + assert failed["missing_ours"] == [] + assert failed["auto_resolved"] == ["rose-stem/old.txt"] + assert failed["conflicts"] == {"code": ["a.F90"]} + assert [n for row in rep["pairwise"].values() for n in row.values()] == [1, 1] From f0779b8a73127cc23f8c08351166e1f6af6f25e4 Mon Sep 17 00:00:00 2001 From: zmaalick Date: Wed, 2 Dec 2026 09:26:59 +0000 Subject: [PATCH 2/4] signed CLA --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a1560792..2912ba4b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,3 +8,4 @@ | ericaneininger | Erica Neininger | Met Office | 2026-10-05 | | t00sa | Sam Clarke-Green | Met Office | 2026-10-13 | | r-sharp | R Sharp | Met Office | 2026-10-19 | +| zmaalick | Zubair Maalick | Met Office | 2026-12-01 | From 3fdad75eb0b1cc31952c0d8bf4bfcf6d664e7814 Mon Sep 17 00:00:00 2001 From: zmaalick Date: Wed, 2 Dec 2026 10:11:40 +0000 Subject: [PATCH 3/4] Fail on release mismatches as the extract does; report other drift as a warning --- github_scripts/check_merge_conflicts.py | 74 +++++++++++++++---- .../tests/test_check_merge_conflicts.py | 31 +++++++- 2 files changed, 90 insertions(+), 15 deletions(-) diff --git a/github_scripts/check_merge_conflicts.py b/github_scripts/check_merge_conflicts.py index c1ff3858..3c2901e3 100755 --- a/github_scripts/check_merge_conflicts.py +++ b/github_scripts/check_merge_conflicts.py @@ -35,8 +35,13 @@ Each setting is taken from the command line, then the environment, then [env] in the rose-app.conf of the app containing the dependencies file. -Exit status: 0 if the extract would succeed with no base drift, 1 if it would -fail or a branch has drifted onto newer upstream code, 2 on usage/git errors. +Branches of the dependencies in --release-check (default: RELEASE_CHECK, else +lfric_apps) must be based on the same release as the first entry, as enforced +by get_git_sources.py; a branch on an older or newer release fails its merge +step. Drift in other dependencies is reported as a warning. + +Exit status: 0 if the extract would succeed, 1 if it would fail, 2 on +usage/git errors. """ from __future__ import annotations @@ -368,13 +373,14 @@ class Drift: branch_release: str | None upstream_ahead: int behind: int - status: str # ok | ahead | behind | unrelated + status: str # ok | minor | behind | ahead | older | unrelated @dataclass class StepResult: entry: str - outcome: str # clean | auto-resolved | fail-conflict | fail-ours | error + # clean | auto-resolved | fail-conflict | fail-ours | fail-release | error + outcome: str conflicts: dict[str, list[str]] = field(default_factory=dict) auto_resolved: list[str] = field(default_factory=list) missing_ours: list[str] = field(default_factory=list) @@ -538,8 +544,15 @@ def check_drift( and branch_release and version_key(branch_release) > version_key(base_release) ) + older_release = bool( + base_release + and branch_release + and version_key(branch_release) < version_key(base_release) + ) if newer_release or ahead > threshold: status = "ahead" + elif older_release: + status = "older" elif ahead: status = "minor" elif behind: @@ -680,9 +693,11 @@ def print_repo_report(name: str, rep: dict, max_files: int) -> None: f"ok ({d['upstream_ahead']} upstream commits past " f"base, still {d['branch_release']})" ), - "behind": ( - f"older base ({d['branch_release']}, {d['behind']} commits behind base)" + "older": ( + f"OLDER RELEASE: based on {d['branch_release']}, base is " + f"{d['base_release']}" ), + "behind": f"ok ({d['behind']} commits behind base, same release)", "unrelated": "UNRELATED history to base", }[d["status"]] print(f" {label:<55} {flag}") @@ -769,14 +784,22 @@ def summarise(report: dict) -> int: if rep.get("error") and not first_failure: first_failure = (name, rep["base"]["label"], rep["error"]) for step in rep.get("steps", []): - if ( - step["outcome"] in ("fail-conflict", "fail-ours", "error") - and not first_failure - ): + if StepResult(**step).failed and not first_failure: first_failure = (name, step["entry"], step["outcome"]) + mismatched = { + s["entry"] for s in rep.get("steps", []) if s["outcome"] == "fail-release" + } for label, d in rep.get("drift", {}).items(): - if d and d["status"] in ("ahead", "unrelated"): - drifted.append(f"{name} {label}") + if label in mismatched: + drifted.append( + f"Release mismatch: {name} {label} is on {d['branch_release']}, " + f"base is {d['base_release']} - remove it or rebase it." + ) + elif d and d["status"] in ("ahead", "older", "unrelated"): + drifted.append( + f"Warning, base drift: {name} {label} - rebase onto the base " + "release." + ) print(f"\n{'=' * 78}\nSummary\n{'=' * 78}") if first_failure: @@ -790,11 +813,11 @@ def summarise(report: dict) -> int: "the conflict resolver." ) for item in drifted: - print(f"Base drift: {item} - rebase onto the base release.") + print(item) if tool_errors: print(f"Check incomplete for: {', '.join(tool_errors)}") return 2 - return 1 if first_failure or drifted else 0 + return 1 if first_failure else 0 # ----------------------------------------------------------------------------- @@ -899,6 +922,22 @@ def check_repository( "unresolved": unresolved, "failures": failures, } + + if name in args.release_check: + for step in rep["steps"]: + d = rep["drift"].get(step["entry"]) + if ( + d + and d["base_release"] + and d["branch_release"] + and (d["base_release"] != d["branch_release"]) + ): + step["outcome"] = "fail-release" + step["message"] = ( + f"based on release {d['branch_release']}, base is " + f"{d['base_release']}: remove the branch or rebase it onto " + f"{d['base_release']}" + ) return rep @@ -959,6 +998,12 @@ def parse_args(argv=None): default=DEFAULT_RELEASE_PATTERN, help="regex for release tags (default: %(default)s)", ) + parser.add_argument( + "--release-check", + default=os.environ.get("RELEASE_CHECK", "lfric_apps"), + help="comma-separated dependencies whose branches must be on the base " + "release (default: %(default)s)", + ) parser.add_argument( "--drift-threshold", type=int, @@ -994,6 +1039,7 @@ def parse_args(argv=None): def main(argv=None) -> int: args = parse_args(argv) + args.release_check = [r.strip() for r in args.release_check.split(",")] if args.dependencies.is_dir(): args.dependencies = args.dependencies / "dependencies.yaml" try: diff --git a/github_scripts/tests/test_check_merge_conflicts.py b/github_scripts/tests/test_check_merge_conflicts.py index 08ee9a01..3c87383c 100644 --- a/github_scripts/tests/test_check_merge_conflicts.py +++ b/github_scripts/tests/test_check_merge_conflicts.py @@ -23,14 +23,16 @@ def git(loc, *args): def upstream(tmp_path, monkeypatch): """ A repository with release tags and branches: + 2026.07.0 - older release 2026.07.1 - base release 2026.07.3 - main: changes a.F90, deletes rose-stem/old.txt drift - from 2026.07.1 with main (2026.07.3) merged in rs - from 2026.07.1: changes a.F90 and rose-stem/old.txt clean - from 2026.07.1: adds a new file + older - from 2026.07.0: adds a new file """ - for var in ("CONFLICT_RULES", "CONFLICT_IGNORES"): + for var in ("CONFLICT_RULES", "CONFLICT_IGNORES", "RELEASE_CHECK"): monkeypatch.delenv(var, raising=False) for role in ("AUTHOR", "COMMITTER"): monkeypatch.setenv(f"GIT_{role}_NAME", "Testing") @@ -39,6 +41,10 @@ def upstream(tmp_path, monkeypatch): repo = tmp_path / "upstream" (repo / "rose-stem").mkdir(parents=True) git(repo, "init", "-q", "-b", "main") + (repo / "README").write_text("old release\n") + git(repo, "add", ".") + git(repo, "commit", "-q", "-m", "older") + git(repo, "tag", "2026.07.0") (repo / "a.F90").write_text("1\n2\n3\n") (repo / "rose-stem" / "old.txt").write_text("old\n") git(repo, "add", ".") @@ -65,6 +71,11 @@ def upstream(tmp_path, monkeypatch): (repo / "new.F90").write_text("new\n") git(repo, "add", ".") git(repo, "commit", "-q", "-m", "clean") + + git(repo, "switch", "-q", "-c", "older", "2026.07.0") + (repo / "old.F90").write_text("old\n") + git(repo, "add", ".") + git(repo, "commit", "-q", "-m", "older branch") git(repo, "switch", "-q", "main") return repo @@ -137,3 +148,21 @@ def test_rules_resolve_one_sided_files(tmp_path, upstream): assert failed["auto_resolved"] == ["rose-stem/old.txt"] assert failed["conflicts"] == {"code": ["a.F90"]} assert [n for row in rep["pairwise"].values() for n in row.values()] == [1, 1] + + +def test_release_check(tmp_path, upstream): + """ + Branches on an older or newer release fail when the repository is release + checked, and are only a warning otherwise + """ + + refs = ["older", "drift", "clean"] + status, rep = check(tmp_path, upstream, refs, "--release-check", "repo") + assert status == 1 + assert [d["status"] for d in rep["drift"].values()] == ["older", "ahead", "ok"] + outcomes = [s["outcome"] for s in rep["steps"]] + assert outcomes == ["fail-release", "fail-release", "clean"] + + status, rep = check(tmp_path, upstream, ["older", "clean"], "--no-fetch") + assert status == 0 + assert [s["outcome"] for s in rep["steps"]] == ["clean", "clean"] From 041d2d81b3af69fb8d063ef1e42217e58032f355 Mon Sep 17 00:00:00 2001 From: zmaalick Date: Thu, 3 Dec 2026 11:17:29 +0000 Subject: [PATCH 4/4] Check later branches without release-mismatched ones; fix fetch race - Run the release check before simulating. A branch failing it is reported as fail-release but not merged, so later steps, the pairwise table and the merge-order search are checked without it, as they would be once it is removed or rebased. Previously its newer upstream changes were merged in and later branches were reported as conflicting with them. - Only apply the release check with --resolver rules: the legacy get_git_sources.py has no release check, so drift is a warning there. - Fetch each entry straight into its ref instead of reading FETCH_HEAD, which concurrent runs sharing the cache could overwrite. - Fail early with a clear message if git is older than 2.38. Co-Authored-By: Claude Opus 5.5 --- github_scripts/check_merge_conflicts.py | 148 +++++++++++++----- .../tests/test_check_merge_conflicts.py | 71 +++++++++ 2 files changed, 182 insertions(+), 37 deletions(-) diff --git a/github_scripts/check_merge_conflicts.py b/github_scripts/check_merge_conflicts.py index 3c2901e3..cf424bc9 100755 --- a/github_scripts/check_merge_conflicts.py +++ b/github_scripts/check_merge_conflicts.py @@ -35,10 +35,13 @@ Each setting is taken from the command line, then the environment, then [env] in the rose-app.conf of the app containing the dependencies file. -Branches of the dependencies in --release-check (default: RELEASE_CHECK, else -lfric_apps) must be based on the same release as the first entry, as enforced -by get_git_sources.py; a branch on an older or newer release fails its merge -step. Drift in other dependencies is reported as a warning. +With --resolver rules, branches of the dependencies in --release-check +(default: RELEASE_CHECK, else lfric_apps) must be based on the same release as +the first entry, as enforced by get_git_sources.py; a branch on an older or +newer release fails its merge step, and the later steps are checked without +it, as they would be once it is removed or rebased. The legacy script has no +release check, so with --resolver legacy, and in other dependencies, drift is +reported as a warning only. Exit status: 0 if the extract would succeed, 1 if it would fail, 2 on usage/git errors. @@ -109,10 +112,34 @@ } +MIN_GIT_VERSION = (2, 38) + + class GitError(Exception): pass +def git_version_error() -> str | None: + """Return an error message if git is missing or older than + MIN_GIT_VERSION (needed for `git merge-tree --write-tree`), else None.""" + try: + output = subprocess.run( + ["git", "--version"], capture_output=True, text=True, check=True + ).stdout + except (OSError, subprocess.CalledProcessError) as err: + return f"cannot run git: {err}" + match = re.search(r"(\d+)\.(\d+)", output) + if not match: + return f"cannot determine the git version from '{output.strip()}'" + if tuple(int(n) for n in match.groups()) < MIN_GIT_VERSION: + required = ".".join(str(n) for n in MIN_GIT_VERSION) + return ( + f"git {required} or later is needed (for git merge-tree " + f"--write-tree), found '{output.strip()}'" + ) + return None + + # ----------------------------------------------------------------------------- # Git helpers # ----------------------------------------------------------------------------- @@ -150,8 +177,18 @@ def out(self, *args, env=None) -> str: return self.git(*args, env=env).stdout.strip() def fetch(self, source: str, ref: str, dest_ref: str) -> str: - self.git("fetch", "-q", "--no-tags", source, ref or "HEAD") - sha = self.out("rev-parse", "FETCH_HEAD^{commit}") + # Fetch straight into dest_ref rather than through FETCH_HEAD, which + # is shared by every run using this cache and could be overwritten by + # a concurrent run before it is read + self.git( + "fetch", + "-q", + "--no-tags", + "--no-write-fetch-head", + source, + f"+{ref or 'HEAD'}:{dest_ref}", + ) + sha = self.out("rev-parse", f"{dest_ref}^{{commit}}") self.git("update-ref", dest_ref, sha) return sha @@ -458,11 +495,30 @@ def simulate_step( def simulate_sequence( - repo: Repo, base: str, entries: list[Entry], resolver: Resolver, on_conflict: str + repo: Repo, + base: str, + entries: list[Entry], + resolver: Resolver, + on_conflict: str, + rejected: dict[str, str] | None = None, ) -> list[StepResult]: + """Simulate merging entries in order. Entries in `rejected` (label -> + message) fail the release check: the extract stops there, so they are + reported as failing but not merged, and later steps are simulated + without them, as they would be once the branch is removed or rebased.""" + rejected = rejected or {} steps = [] head = base for entry in entries: + if entry.label in rejected: + steps.append( + StepResult( + entry=entry.label, + outcome="fail-release", + message=rejected[entry.label], + ) + ) + continue if entry.sha is None: steps.append( StepResult( @@ -709,7 +765,8 @@ def print_repo_report(name: str, rep: dict, max_files: int) -> None: print(f" {s.entry:<55} {s.outcome}") if s.message: print(f" {s.message}") - if s.failed and rep.get("pairwise", {}).get(s.entry): + conflict_failure = s.failed and s.outcome not in ("fail-release", "error") + if conflict_failure and rep.get("pairwise", {}).get(s.entry): earlier = [ lbl for lbl, n in rep["pairwise"][s.entry].items() @@ -884,7 +941,28 @@ def check_repository( for e in branches } - steps = simulate_sequence(repo, base.sha, branches, resolver, args.on_conflict) + # Only get_git_sources.py with CONFLICT_RULES support (--resolver rules) + # checks releases; the legacy script merges drifted branches regardless + rejected: dict[str, str] = {} + if resolver.mode == "rules" and name in args.release_check: + for label, d in rep["drift"].items(): + if ( + d + and d["base_release"] + and d["branch_release"] + and d["base_release"] != d["branch_release"] + ): + rejected[label] = ( + f"based on release {d['branch_release']}, base is " + f"{d['base_release']}: remove the branch or rebase it onto " + f"{d['base_release']} (later steps are checked without it)" + ) + merged = [b for b in branches if b.label not in rejected] + unmerged = [b for b in branches if b.label in rejected] + + steps = simulate_sequence( + repo, base.sha, branches, resolver, args.on_conflict, rejected + ) rep["steps"] = [asdict(s) for s in steps] rep["entries"] = { e.label: {"source": e.source, "ref": e.ref, "sha": e.sha, "error": e.error} @@ -895,21 +973,29 @@ def check_repository( "failures": sum(1 for s in steps if s.failed), } - if not args.no_pairwise and len([b for b in branches if b.sha]) > 1: + if not args.no_pairwise and len([b for b in merged if b.sha]) > 1: log(args, f"pairwise checks for {name}") - rep["pairwise"] = pairwise(repo, branches, resolver) + rep["pairwise"] = pairwise(repo, merged, resolver) - if not args.no_suggest and rep["totals"]["failures"] and len(branches) > 1: + # Reordering cannot fix a release mismatch, so only search the order of + # the branches that are merged + has_conflicts = any(s.failed for s in steps if s.entry not in rejected) + if not args.no_suggest and has_conflicts and len(merged) > 1: log(args, f"searching merge order for {name}") - order = suggest_order( - repo, - base.sha, - branches, - resolver, - args.on_conflict, - {k: d["upstream_ahead"] for k, d in rep["drift"].items() if d}, + order = ( + suggest_order( + repo, + base.sha, + merged, + resolver, + args.on_conflict, + {k: d["upstream_ahead"] for k, d in rep["drift"].items() if d}, + ) + + unmerged + ) + new_steps = simulate_sequence( + repo, base.sha, order, resolver, args.on_conflict, rejected ) - new_steps = simulate_sequence(repo, base.sha, order, resolver, args.on_conflict) unresolved = sum(s.n_unresolved for s in new_steps) failures = sum(1 for s in new_steps if s.failed) rep["order_searched"] = True @@ -918,26 +1004,10 @@ def check_repository( rep["totals"]["unresolved"], ): rep["suggested_order"] = { - "order": [e.label for e in order], + "order": [e.label for e in order if e.label not in rejected], "unresolved": unresolved, "failures": failures, } - - if name in args.release_check: - for step in rep["steps"]: - d = rep["drift"].get(step["entry"]) - if ( - d - and d["base_release"] - and d["branch_release"] - and (d["base_release"] != d["branch_release"]) - ): - step["outcome"] = "fail-release" - step["message"] = ( - f"based on release {d['branch_release']}, base is " - f"{d['base_release']}: remove the branch or rebase it onto " - f"{d['base_release']}" - ) return rep @@ -1039,6 +1109,10 @@ def parse_args(argv=None): def main(argv=None) -> int: args = parse_args(argv) + version_error = git_version_error() + if version_error: + print(f"error: {version_error}", file=sys.stderr) + return 2 args.release_check = [r.strip() for r in args.release_check.split(",")] if args.dependencies.is_dir(): args.dependencies = args.dependencies / "dependencies.yaml" diff --git a/github_scripts/tests/test_check_merge_conflicts.py b/github_scripts/tests/test_check_merge_conflicts.py index 3c87383c..33caadb9 100644 --- a/github_scripts/tests/test_check_merge_conflicts.py +++ b/github_scripts/tests/test_check_merge_conflicts.py @@ -12,6 +12,7 @@ import pytest +from .. import check_merge_conflicts from ..check_merge_conflicts import main, parse_rules, path_matches @@ -166,3 +167,73 @@ def test_release_check(tmp_path, upstream): status, rep = check(tmp_path, upstream, ["older", "clean"], "--no-fetch") assert status == 0 assert [s["outcome"] for s in rep["steps"]] == ["clean", "clean"] + + +def test_release_mismatch_not_merged(tmp_path, upstream, capsys): + """ + A branch failing the release check is not merged into the simulation, so + later branches are not blamed for conflicts it brings in + """ + + status, rep = check(tmp_path, upstream, ["drift", "rs"], "--release-check", "repo") + assert status == 1 + rejected, later = rep["steps"] + assert rejected["outcome"] == "fail-release" + assert "later steps are checked without it" in rejected["message"] + # rs only conflicts with the newer release that drift brings in + assert later["outcome"] == "clean" + assert later["conflicts"] == {} + assert "pairwise" not in rep + assert "combination of branches" not in capsys.readouterr().out + + +def test_legacy_has_no_release_check(tmp_path, upstream): + """ + The legacy get_git_sources.py does not check releases, so drift is only a + warning with --resolver legacy + """ + + status, rep = check( + tmp_path, + upstream, + ["older", "clean"], + "--resolver", + "legacy", + "--release-check", + "repo", + ) + assert status == 0 + assert [d["status"] for d in rep["drift"].values()] == ["older", "ok"] + assert [s["outcome"] for s in rep["steps"]] == ["clean", "clean"] + + +def test_fetch_by_commit_hash(tmp_path, upstream): + """ + Refs given as a full commit hash are fetched + """ + + sha = subprocess.run( + ["git", "-C", str(upstream), "rev-parse", "clean"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + status, rep = check(tmp_path, upstream, [sha]) + assert status == 0 + fetched = [e["sha"] for e in rep["entries"].values() if e["ref"] == sha] + assert fetched == [sha] + + +@pytest.mark.parametrize( + "version, ok", + [("git version 2.37.9", False), ("git version 2.38.0", True), ("2.52.0", True)], +) +def test_git_version_check(monkeypatch, version, ok): + def fake_run(*args, **kwargs): + return subprocess.CompletedProcess(args, 0, stdout=version, stderr="") + + monkeypatch.setattr(check_merge_conflicts.subprocess, "run", fake_run) + error = check_merge_conflicts.git_version_error() + assert (error is None) == ok + if not ok: + assert "2.38 or later" in error