From 9f67807cc6ac297f6cb87211b6430c8a8ba1aa04 Mon Sep 17 00:00:00 2001 From: zmaalick Date: Tue, 1 Dec 2026 14:24:54 +0000 Subject: [PATCH 1/5] Resolve merge conflicts per file with configurable rules and shared rerere --- github_scripts/get_git_sources.py | 268 ++++++++++++++++--- github_scripts/tests/test_get_git_sources.py | 141 ++++++++++ 2 files changed, 369 insertions(+), 40 deletions(-) diff --git a/github_scripts/get_git_sources.py b/github_scripts/get_git_sources.py index e61bb9d2..bf80cbb9 100644 --- a/github_scripts/get_git_sources.py +++ b/github_scripts/get_git_sources.py @@ -6,14 +6,34 @@ """ Helper functions for cloning git sources in command line builds -Reads CONFLICT_IGNORES environment variable to get a list of comma-separated -files/directories to ignore merge conflicts in. These should be relative to the -top-level of the repo. If not set, then a default list is defined below. +Merge conflicts are resolved file by file using rules read from environment +variables. Paths are relative to the top-level of the repo: + +CONFLICT_RULES + Comma-separated `pattern=strategy` rules; the first matching rule wins. + A pattern containing `*`, `?` or `[` is a glob matched against the whole + path (`*` also matches `/`), otherwise it matches that file or everything + under that directory. Strategies: + ours - keep the version merged so far (removed if it has none) + theirs - take the version from the branch being merged (removed if it + has none) + union - keep the lines from both sides, for list-like files; if only + one side has the file, keep it + fail - leave the conflict for the user +CONFLICT_IGNORES + Comma-separated paths resolved with `ours`, checked after CONFLICT_RULES. + If neither variable is set, DEFAULT_CONFLICT_RULES is used. +CONFLICT_RERERE_CACHE + Directory for a shared `git rerere` cache. If set, conflicts that someone + has already resolved and committed in a clone using the same cache are + resolved automatically with that recorded resolution. """ +import fnmatch import os import re import subprocess +import tempfile from datetime import datetime from typing import Optional, Union from pathlib import Path @@ -63,7 +83,7 @@ def run_command( err_msg = (result.stderr or "").strip() logger.error(f"[FAIL] Command failed: {command}\nError: {err_msg}") raise SubprocessRunError( - result.returncode, command, result.stdout, result.stderr + command, result.returncode, result.stdout, result.stderr ) return result @@ -216,68 +236,236 @@ def merge_source( run_command(f"git -C {dest} fetch local {fetch}") + enable_rerere(dest, dest.name) + command = f"git -C {dest} merge --no-gpg-sign --no-edit FETCH_HEAD" result = run_command(command, check=False) if result.returncode: - unmerged_files = get_unmerged(dest) - if unmerged_files: + # A merge left in progress means conflicts, possibly all already + # resolved by rerere; anything else is a real failure + if merge_in_progress(dest): handle_merge_conflicts(source, ref, dest, dest.name) else: raise SubprocessRunError( - result.returncode, command, result.stdout, result.stderr + command, result.returncode, result.stdout, result.stderr ) # Remove the added remote run_command(f"git -C {dest} remote remove local") +CONFLICT_STRATEGIES = ("ours", "theirs", "union", "fail") +DEFAULT_CONFLICT_RULES = "dependencies.yaml=ours,rose-stem=ours,CONTRIBUTORS.md=union" + + +def parse_conflict_rules(rules: str) -> list[tuple[str, str]]: + """ + Parse comma-separated `pattern=strategy` rules into (pattern, strategy) pairs + """ + + parsed = [] + for item in rules.split(","): + item = item.strip() + if not item: + continue + pattern, sep, strategy = item.rpartition("=") + strategy = strategy.strip() + if not sep or not pattern.strip() or strategy not in CONFLICT_STRATEGIES: + raise ValueError( + f"Invalid conflict rule '{item}': expected 'pattern=strategy' with " + f"strategy one of {', '.join(CONFLICT_STRATEGIES)}" + ) + parsed.append((pattern.strip(), strategy)) + return parsed + + +def get_conflict_rules() -> list[tuple[str, str]]: + """ + Build the conflict rules from CONFLICT_RULES and CONFLICT_IGNORES, falling back + to DEFAULT_CONFLICT_RULES if neither is set + """ + + rules = parse_conflict_rules(os.environ.get("CONFLICT_RULES", "")) + ignores = os.environ.get("CONFLICT_IGNORES", "") + rules += [(p.strip(), "ours") for p in ignores.split(",") if p.strip()] + return rules or parse_conflict_rules(DEFAULT_CONFLICT_RULES) + + +def path_matches(path: str, pattern: str) -> bool: + """ + Glob patterns match the whole path; plain patterns match the file itself or + anything below that directory + """ + + if any(c in pattern for c in "*?["): + return fnmatch.fnmatchcase(path, pattern) + pattern = pattern.rstrip("/") + return path == pattern or path.startswith(pattern + "/") + + +def match_conflict_rule(path: str, rules: list[tuple[str, str]]) -> str: + """ + Return the strategy of the first rule matching path, or "fail" + """ + + for pattern, strategy in rules: + if path_matches(path, pattern): + return strategy + return "fail" + + +def run_git(loc: Path, *args: str) -> subprocess.CompletedProcess: + """ + Run a git command with arguments passed as a list, so paths are never split + """ + + result = subprocess.run( + ["git", "-C", str(loc), *args], capture_output=True, text=True, check=False + ) + if result.returncode: + raise SubprocessRunError( + f"git -C {loc} {' '.join(args)}", + result.returncode, + result.stdout, + result.stderr, + ) + return result + + +def get_unmerged_stages(loc: Path) -> dict[str, set[int]]: + """ + Return the index stages present for each unmerged path: + 1 = common ancestor, 2 = ours (merged so far), 3 = theirs (being merged) + """ + + stages: dict[str, set[int]] = {} + output = run_git(loc, "ls-files", "-u", "-z").stdout + for entry in output.split("\0"): + if not entry: + continue + info, path = entry.split("\t", 1) + stages.setdefault(path, set()).add(int(info.split()[2])) + return stages + + +def resolve_conflict(loc: Path, path: str, stages: set[int], strategy: str) -> str: + """ + Resolve one unmerged path with the given strategy and stage the result. + Returns a short description of what was done. + """ + + if strategy == "union": + if {2, 3} <= stages: + return union_merge(loc, path, stages) + # Only one side has the file (modify/delete): keep it + strategy = "ours" if 2 in stages else "theirs" + + stage = 2 if strategy == "ours" else 3 + if stage in stages: + run_git(loc, "checkout", f"--{strategy}", "--", path) + run_git(loc, "add", "-f", "--", path) + return f"kept {strategy}" + run_git(loc, "rm", "-q", "-f", "--", path) + return f"removed ({strategy} has no version)" + + +def union_merge(loc: Path, path: str, stages: set[int]) -> str: + """ + Merge both sides of path keeping the lines from each side of every conflict + """ + + with tempfile.TemporaryDirectory() as tmp: + files = {} + for stage, name in ((1, "base"), (2, "ours"), (3, "theirs")): + files[name] = Path(tmp) / name + content = b"" + if stage in stages: + content = subprocess.run( + ["git", "-C", str(loc), "show", f":{stage}:{path}"], + capture_output=True, + check=True, + ).stdout + files[name].write_bytes(content) + # Exit status is the number of conflicts (always 0 with --union), or + # negative (> 127 here) on error + merged = subprocess.run( + [ + "git", + "merge-file", + "--union", + "-p", + str(files["ours"]), + str(files["base"]), + str(files["theirs"]), + ], + capture_output=True, + check=False, + ) + if merged.returncode > 127: + raise SubprocessRunError( + "git merge-file --union", merged.returncode, "", merged.stderr + ) + (loc / path).write_bytes(merged.stdout) + run_git(loc, "add", "-f", "--", path) + return "combined both sides" + + def handle_merge_conflicts(source: str, ref: str, loc: Path, dependency: str) -> None: """ - If merge conflicts are in `rose-stem/` or `dependencies.yaml` then accept the - current changes and mark as resolved. - If others remain then raise an error - If CONFLICT_IGNORES environment variable is set, use that as a comma-separated list - of files/directories to ignore. If not set, use a default list below. - """ - - # For suites, merge conflicts in these files/directories are unimportant so accept - # the current changes - ignores = os.environ.get( - "CONFLICT_IGNORES", "dependencies.yaml,rose-stem,CONTRIBUTORS.md" - ).split(",") - need_commit = False - for filepath in ignores: - full_path = loc / filepath - if not full_path.exists(): + Resolve each conflicted file using the first matching conflict rule (see the + module docstring). Raise an error listing any files left unresolved, otherwise + commit the merge. + """ + + rules = get_conflict_rules() + unresolved = [] + for path, stages in sorted(get_unmerged_stages(loc).items()): + strategy = match_conflict_rule(path, rules) + if strategy == "fail": + unresolved.append(path) continue - logger.warning(f"Ignoring merge conflicts in {filepath}") - run_command(f"git -C {loc} checkout --ours -- {filepath}") - run_command(f"git -C {loc} add -f {filepath}") - need_commit = True - - # Check if there are any remaining merge conflicts - unmerged = get_unmerged(loc) - if unmerged: - files = "\n".join(f for f in unmerged) + action = resolve_conflict(loc, path, stages, strategy) + logger.warning(f"Resolved merge conflict in {path} ({strategy}): {action}") + + if unresolved: + files = "\n".join(unresolved) raise RuntimeError( "\nA merge conflict has been identified while merging the following branch " f"into the {dependency} source:\n\nsource: {source}\nref: {ref}\n\n" - f"with conflicting files:{files}" + f"with conflicting files:\n{files}" "\n\nThese will need changing in the source branches to be useable together" ) - # Need to commit the ignored conflict fixes - if need_commit: - run_command(f"git -C {loc} commit -m 'fix conflict'") + run_command(f"git -C {loc} commit --no-gpg-sign --no-edit") + + +def merge_in_progress(loc: Path) -> bool: + """ + Return whether a merge has been started but not committed + """ + + result = run_command(f"git -C {loc} rev-parse -q --verify MERGE_HEAD", check=False) + return result.returncode == 0 -def get_unmerged(loc: Path) -> list[str]: +def enable_rerere(loc: Path, dependency: str) -> None: """ - Return list of unmerged files in a git clone + If CONFLICT_RERERE_CACHE is set, turn on git rerere in the clone with its + resolution cache shared at $CONFLICT_RERERE_CACHE/ """ - files = run_command(f"git -C {loc} --no-pager diff --name-only --diff-filter=U") - return files.stdout.split() + cache = os.environ.get("CONFLICT_RERERE_CACHE") + if not cache: + return + shared = Path(cache) / dependency + shared.mkdir(parents=True, exist_ok=True) + rr_cache = loc / ".git" / "rr-cache" + if not rr_cache.is_symlink(): + if rr_cache.exists(): + rmtree(rr_cache) + rr_cache.symlink_to(shared.resolve()) + run_command(f"git -C {loc} config rerere.enabled true") + run_command(f"git -C {loc} config rerere.autoUpdate true") def check_existing(loc: Path) -> bool: diff --git a/github_scripts/tests/test_get_git_sources.py b/github_scripts/tests/test_get_git_sources.py index 66112be3..a6162199 100644 --- a/github_scripts/tests/test_get_git_sources.py +++ b/github_scripts/tests/test_get_git_sources.py @@ -14,6 +14,7 @@ import pytest from ..get_git_sources import ( + SubprocessRunError, validate_dependencies, determine_mirror_fetch, set_https, @@ -22,6 +23,9 @@ sync_repo, check_existing, merge_source, + get_conflict_rules, + match_conflict_rule, + run_command, ) @@ -263,3 +267,140 @@ def test_set_https(): } assert set_https(input_dict) == output_dict + + +def git(loc, *args): + return subprocess.run( + ["git", "-C", str(loc), *args], check=True, capture_output=True, text=True + ).stdout + + +@pytest.fixture +def conflicting_repos(tmp_path, monkeypatch): + """ + A clone at "dest" and a branch "theirs" in "fork" that conflict on: + rose-stem/kgo.txt - deleted in dest, modified in fork (one-sided) + CONTRIBUTORS.md - a different line added on each side + code.F90 - a different change on each side + """ + + for var in ("CONFLICT_RULES", "CONFLICT_IGNORES", "CONFLICT_RERERE_CACHE"): + monkeypatch.delenv(var, raising=False) + for role in ("AUTHOR", "COMMITTER"): + monkeypatch.setenv(f"GIT_{role}_NAME", "Testing") + monkeypatch.setenv(f"GIT_{role}_EMAIL", "Testing") + + upstream = tmp_path / "upstream" + (upstream / "rose-stem").mkdir(parents=True) + git(upstream, "init", "-q", "-b", "main") + (upstream / "rose-stem" / "kgo.txt").write_text("kgo\n") + (upstream / "CONTRIBUTORS.md").write_text("alice\n") + (upstream / "code.F90").write_text("x = 1\n") + git(upstream, "add", ".") + git(upstream, "commit", "-q", "-m", "base") + + fork = tmp_path / "fork" + git(tmp_path, "clone", "-q", str(upstream), str(fork)) + git(fork, "switch", "-q", "-c", "theirs") + (fork / "rose-stem" / "kgo.txt").write_text("new kgo\n") + (fork / "CONTRIBUTORS.md").write_text("alice\ncarol\n") + (fork / "code.F90").write_text("x = 3\n") + git(fork, "commit", "-q", "-am", "theirs") + + git(upstream, "rm", "-q", "rose-stem/kgo.txt") + (upstream / "CONTRIBUTORS.md").write_text("alice\nbob\n") + (upstream / "code.F90").write_text("x = 2\n") + git(upstream, "commit", "-q", "-am", "ours") + + def make_dest(name="dest"): + # The clone directory name is the dependency name, which keys the + # shared rerere cache, so clones go in separate parents + dest = tmp_path / name / "lfric_apps" + dest.parent.mkdir() + git(tmp_path, "clone", "-q", str(upstream), str(dest)) + return dest + + return make_dest, fork + + +def test_conflict_rules(monkeypatch): + """ + Test rule parsing and matching + """ + + monkeypatch.delenv("CONFLICT_IGNORES", raising=False) + monkeypatch.delenv("CONFLICT_RULES", raising=False) + rules = get_conflict_rules() + assert match_conflict_rule("rose-stem/site/kgo.txt", rules) == "ours" + assert match_conflict_rule("CONTRIBUTORS.md", rules) == "union" + assert match_conflict_rule("rose-stemmed/file", rules) == "fail" + + monkeypatch.setenv("CONFLICT_RULES", "*/versions.py=theirs, rose-stem/app=fail") + monkeypatch.setenv("CONFLICT_IGNORES", "rose-stem") + rules = get_conflict_rules() + assert match_conflict_rule("science/a/rose-meta/b/versions.py", rules) == "theirs" + assert match_conflict_rule("versions.py", rules) == "fail" + # First matching rule wins, CONFLICT_IGNORES come after CONFLICT_RULES + assert match_conflict_rule("rose-stem/app/x.conf", rules) == "fail" + assert match_conflict_rule("rose-stem/site/kgo.txt", rules) == "ours" + + for bad in ("rose-stem", "rose-stem=newest", "=ours"): + monkeypatch.setenv("CONFLICT_RULES", bad) + with pytest.raises(ValueError): + get_conflict_rules() + + +def test_merge_resolves_with_rules(conflicting_repos, monkeypatch): + """ + One-sided files under an "ours" path no longer crash, union keeps both sides + and unmatched conflicts are still reported + """ + + make_dest, fork = conflicting_repos + + dest = make_dest("unresolved") + with pytest.raises(RuntimeError, match="code.F90"): + merge_source(fork, "theirs", dest) + + monkeypatch.setenv( + "CONFLICT_RULES", "code.F90=theirs,rose-stem=ours,CONTRIBUTORS.md=union" + ) + dest = make_dest() + assert merge_source(fork, "theirs", dest) is None + assert not (dest / "rose-stem" / "kgo.txt").exists() + assert (dest / "CONTRIBUTORS.md").read_text() == "alice\nbob\ncarol\n" + assert (dest / "code.F90").read_text() == "x = 3\n" + assert git(dest, "status", "--porcelain") == "" + assert len(git(dest, "log", "-1", "--format=%P").split()) == 2 + + +def test_merge_reuses_shared_rerere(conflicting_repos, tmp_path, monkeypatch): + """ + A resolution committed in one clone is reused by another sharing the cache + """ + + make_dest, fork = conflicting_repos + monkeypatch.setenv("CONFLICT_RERERE_CACHE", str(tmp_path / "rerere")) + + first = make_dest("first") + with pytest.raises(RuntimeError, match="code.F90"): + merge_source(fork, "theirs", first) + (first / "code.F90").write_text("x = 5\n") + git(first, "add", "code.F90") + git(first, "commit", "-q", "--no-edit") + + second = make_dest("second") + assert merge_source(fork, "theirs", second) is None + assert (second / "code.F90").read_text() == "x = 5\n" + + +def test_subprocess_run_error_order(): + """ + The failing command and its return code are reported the right way round + """ + + command = "git -C /does/not/exist status" + with pytest.raises(SubprocessRunError) as err: + run_command(command) + assert err.value.command == command + assert err.value.returncode == 128 From 752fe55492cdec18b28a020304d5c5fb77403619 Mon Sep 17 00:00:00 2001 From: zmaalick Date: Tue, 1 Dec 2026 14:30:51 +0000 Subject: [PATCH 2/5] signed CLA --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a1560792..75813eac 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 | \ No newline at end of file From c64d0938a974bc051050037ad4902ebebf873860 Mon Sep 17 00:00:00 2001 From: zmaalick Date: Tue, 1 Dec 2026 14:56:58 +0000 Subject: [PATCH 3/5] Align CONTRIBUTORS.md table row --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 75813eac..2912ba4b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,4 +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 | \ No newline at end of file +| zmaalick | Zubair Maalick | Met Office | 2026-12-01 | From 513eeca5074a9118801ffe642a7ded328d95db1a Mon Sep 17 00:00:00 2001 From: zmaalick Date: Wed, 2 Dec 2026 08:56:52 +0000 Subject: [PATCH 4/5] Explain how to resolve unresolved merge conflicts in the error message --- github_scripts/get_git_sources.py | 103 +++++++++++++++++-- github_scripts/tests/test_get_git_sources.py | 6 +- 2 files changed, 99 insertions(+), 10 deletions(-) diff --git a/github_scripts/get_git_sources.py b/github_scripts/get_git_sources.py index bf80cbb9..c9e3b936 100644 --- a/github_scripts/get_git_sources.py +++ b/github_scripts/get_git_sources.py @@ -418,27 +418,112 @@ def handle_merge_conflicts(source: str, ref: str, loc: Path, dependency: str) -> """ rules = get_conflict_rules() - unresolved = [] + unresolved = {} for path, stages in sorted(get_unmerged_stages(loc).items()): strategy = match_conflict_rule(path, rules) if strategy == "fail": - unresolved.append(path) + unresolved[path] = stages continue action = resolve_conflict(loc, path, stages, strategy) logger.warning(f"Resolved merge conflict in {path} ({strategy}): {action}") if unresolved: - files = "\n".join(unresolved) - raise RuntimeError( - "\nA merge conflict has been identified while merging the following branch " - f"into the {dependency} source:\n\nsource: {source}\nref: {ref}\n\n" - f"with conflicting files:\n{files}" - "\n\nThese will need changing in the source branches to be useable together" - ) + raise RuntimeError(conflict_report(source, ref, loc, dependency, unresolved)) run_command(f"git -C {loc} commit --no-gpg-sign --no-edit") +def describe_conflict(stages: set[int], ref: str) -> str: + """ + Describe a conflict from the index stages present for the path + """ + + if 2 not in stages: + return f"deleted by an earlier branch, modified in {ref}" + if 3 not in stages: + return f"modified by an earlier branch, deleted in {ref}" + if 1 not in stages: + return f"added by an earlier branch and by {ref}" + return f"changed by an earlier branch and by {ref}" + + +def earlier_changes(loc: Path, path: str) -> list[str]: + """ + Return the subjects of commits already merged into the source (not in the + branch being merged) that changed path; merges of earlier dependencies.yaml + entries read "Merge branch '' of ". Best effort only. + """ + + try: + output = run_git( + loc, + "log", + "--first-parent", + "--format=%s", + "HEAD", + "^MERGE_HEAD", + "--", + path, + ).stdout + except SubprocessRunError: + return [] + return list(dict.fromkeys(line for line in output.splitlines() if line))[:3] + + +def conflict_report( + source: str, ref: str, loc: Path, dependency: str, unresolved: dict[str, set[int]] +) -> str: + """ + Build the error message for unresolved conflicts, with options to fix them + """ + + owner = re.split("[:/]", str(source).rstrip("/")) + owner = owner[-2] if len(owner) >= 2 else str(source) + lines = [ + "", + ( + "A merge conflict has been identified while merging the following branch " + f"into the {dependency} source:" + ), + "", + f"source: {source}", + f"ref: {ref}", + "", + "with conflicting files:", + ] + for path, stages in unresolved.items(): + lines.append(f" {path}") + lines.append(f" {describe_conflict(stages, ref)}") + for subject in earlier_changes(loc, path): + lines.append(f" earlier change: {subject}") + lines += [ + "", + ( + "These will need changing in the source branches to be usable together. " + "Options:" + ), + ( + f" 1. Drop the branch: if {ref} is not needed for this run, remove or " + f"comment out its entry under '{dependency}' in dependencies.yaml." + ), + ( + f" 2. Ask the branch owner ({owner}) to resolve it, e.g. by rebasing " + f"{ref} onto the same release as the first entry, or by merging in the " + "earlier branch it conflicts with (see 'earlier change' above)." + ), + ( + " 3. Create a resolution branch: start from the first entry's ref, merge " + "the entries above and this one, fix the files above, push it and use it " + "in place of this entry." + ), + ( + " 4. If keeping one side is acceptable (e.g. housekeeping files), add a " + "rule such as '=ours' to CONFLICT_RULES." + ), + ] + return "\n".join(lines) + + def merge_in_progress(loc: Path) -> bool: """ Return whether a merge has been started but not committed diff --git a/github_scripts/tests/test_get_git_sources.py b/github_scripts/tests/test_get_git_sources.py index a6162199..ff3727ff 100644 --- a/github_scripts/tests/test_get_git_sources.py +++ b/github_scripts/tests/test_get_git_sources.py @@ -359,8 +359,12 @@ def test_merge_resolves_with_rules(conflicting_repos, monkeypatch): make_dest, fork = conflicting_repos dest = make_dest("unresolved") - with pytest.raises(RuntimeError, match="code.F90"): + with pytest.raises(RuntimeError, match="code.F90") as err: merge_source(fork, "theirs", dest) + message = str(err.value) + assert "changed by an earlier branch and by theirs" in message + assert "earlier change: ours" in message + assert "Drop the branch" in message monkeypatch.setenv( "CONFLICT_RULES", "code.F90=theirs,rose-stem=ours,CONTRIBUTORS.md=union" From d05c11b47d855d0f67b73530ac488b227e4da049 Mon Sep 17 00:00:00 2001 From: zmaalick Date: Wed, 2 Dec 2026 10:11:18 +0000 Subject: [PATCH 5/5] Reject lfric_apps branches based on a different release than the base --- github_scripts/get_git_sources.py | 90 ++++++++++++++++++++ github_scripts/tests/test_get_git_sources.py | 62 ++++++++++++++ 2 files changed, 152 insertions(+) diff --git a/github_scripts/get_git_sources.py b/github_scripts/get_git_sources.py index c9e3b936..99404890 100644 --- a/github_scripts/get_git_sources.py +++ b/github_scripts/get_git_sources.py @@ -27,6 +27,10 @@ Directory for a shared `git rerere` cache. If set, conflicts that someone has already resolved and committed in a clone using the same cache are resolved automatically with that recorded resolution. + +Before merging, branches of the dependencies listed in RELEASE_CHECK +(comma-separated, default lfric_apps, empty to disable) must be based on the +same release (newest YYYY.MM.N tag they contain) as the source merged so far. """ import fnmatch @@ -236,6 +240,12 @@ def merge_source( run_command(f"git -C {dest} fetch local {fetch}") + try: + check_release(source, ref, dest) + except RuntimeError: + run_command(f"git -C {dest} remote remove local") + raise + enable_rerere(dest, dest.name) command = f"git -C {dest} merge --no-gpg-sign --no-edit FETCH_HEAD" @@ -256,6 +266,86 @@ def merge_source( CONFLICT_STRATEGIES = ("ours", "theirs", "union", "fail") DEFAULT_CONFLICT_RULES = "dependencies.yaml=ours,rose-stem=ours,CONTRIBUTORS.md=union" +DEFAULT_RELEASE_CHECK = "lfric_apps" +RELEASE_TAG = re.compile(r"^\d{4}\.\d{2}\.\d+$") + + +def release_key(tag: str) -> tuple[int, ...]: + return tuple(int(n) for n in tag.split(".")) + + +def newest_release(loc: Path, rev: str) -> Optional[str]: + """ + Return the newest release tag (YYYY.MM.N) contained in rev, or None + """ + + tags = run_git(loc, "tag", "--merged", rev).stdout.split() + releases = [t for t in tags if RELEASE_TAG.match(t)] + if not releases: + return None + return max(releases, key=release_key) + + +def check_release(source: str, ref: str, dest: Path) -> None: + """ + For dependencies listed in RELEASE_CHECK (default lfric_apps; empty to + disable), raise an error if the fetched branch (FETCH_HEAD) is based on a + different release, older or newer, than the source merged so far (HEAD). + """ + + checked = os.environ.get("RELEASE_CHECK", DEFAULT_RELEASE_CHECK).split(",") + if dest.name not in [c.strip() for c in checked]: + return + + # Release tags are not fetched with a single ref, so get them from the + # repository the base was cloned from + fetched = run_git(dest, "rev-parse", "FETCH_HEAD").stdout.strip() + run_command( + f"git -C {dest} fetch -q --no-tags --no-write-fetch-head origin " + "+refs/tags/*:refs/tags/*", + check=False, + ) + base = newest_release(dest, "HEAD") + branch = newest_release(dest, fetched) + if base is None or branch is None: + logger.warning( + f"Cannot determine the release of {ref} or of the {dest.name} base; " + "skipping the release check" + ) + return + if base == branch: + return + + relation = "an older" if release_key(branch) < release_key(base) else "a newer" + raise RuntimeError( + "\n".join( + [ + "", + ( + f"The following branch is based on {relation} {dest.name} release " + "than the base:" + ), + "", + f"source: {source}", + f"ref: {ref}", + f"branch release: {branch}", + f"base release: {base}", + "", + ( + "All branches must be based on the same release as the first " + "entry. Options:" + ), + ( + f" 1. Remove the branch: remove or comment out its entry under " + f"'{dest.name}' in dependencies.yaml." + ), + ( + f" 2. Rebase it: ask the branch owner to rebase {ref} onto {base}, " + "or use a version of the branch that is based on it." + ), + ] + ) + ) def parse_conflict_rules(rules: str) -> list[tuple[str, str]]: diff --git a/github_scripts/tests/test_get_git_sources.py b/github_scripts/tests/test_get_git_sources.py index ff3727ff..f59fa013 100644 --- a/github_scripts/tests/test_get_git_sources.py +++ b/github_scripts/tests/test_get_git_sources.py @@ -408,3 +408,65 @@ def test_subprocess_run_error_order(): run_command(command) assert err.value.command == command assert err.value.returncode == 128 + + +@pytest.fixture +def release_repos(tmp_path, monkeypatch): + """ + An upstream with releases 2026.07.0 < 2026.07.1 < 2026.07.3 and branches: + same - from 2026.07.1 + older - from 2026.07.0 + newer - from 2026.07.1 with 2026.07.3 merged in + and a function making an lfric_apps clone at 2026.07.1 + """ + + monkeypatch.delenv("RELEASE_CHECK", raising=False) + for role in ("AUTHOR", "COMMITTER"): + monkeypatch.setenv(f"GIT_{role}_NAME", "Testing") + monkeypatch.setenv(f"GIT_{role}_EMAIL", "Testing") + + upstream = tmp_path / "upstream" + upstream.mkdir() + git(upstream, "init", "-q", "-b", "main") + for tag in ("2026.07.0", "2026.07.1", "2026.07.3"): + (upstream / f"{tag}.txt").write_text(tag) + git(upstream, "add", ".") + git(upstream, "commit", "-q", "-m", tag) + git(upstream, "tag", tag) + for branch, start in (("same", "2026.07.1"), ("older", "2026.07.0")): + git(upstream, "switch", "-q", "-c", branch, start) + (upstream / f"{branch}.txt").write_text(branch) + git(upstream, "add", ".") + git(upstream, "commit", "-q", "-m", branch) + git(upstream, "switch", "-q", "-c", "newer", "same") + git(upstream, "merge", "-q", "--no-edit", "2026.07.3") + git(upstream, "switch", "-q", "main") + + def make_dest(name): + dest = tmp_path / name / "lfric_apps" + dest.parent.mkdir() + git(tmp_path, "clone", "-q", str(upstream), str(dest)) + git(dest, "checkout", "-q", "2026.07.1") + return dest + + return make_dest, upstream + + +def test_merge_checks_release(release_repos, monkeypatch): + """ + Branches based on an older or newer release than the base are rejected + """ + + make_dest, upstream = release_repos + + assert merge_source(upstream, "same", make_dest("same")) is None + for branch, relation in (("older", "an older"), ("newer", "a newer")): + dest = make_dest(branch) + with pytest.raises(RuntimeError, match=f"based on {relation} lfric_apps"): + merge_source(upstream, branch, dest) + # Nothing merged and the temporary remote removed + assert not (dest / f"{branch}.txt").exists() + assert "local" not in git(dest, "remote") + + monkeypatch.setenv("RELEASE_CHECK", "") + assert merge_source(upstream, "older", make_dest("disabled")) is None