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 | diff --git a/github_scripts/get_git_sources.py b/github_scripts/get_git_sources.py index e61bb9d2..b0e06078 100644 --- a/github_scripts/get_git_sources.py +++ b/github_scripts/get_git_sources.py @@ -6,14 +6,50 @@ """ 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. + +Before merging, the release (newest YYYY.MM.N tag contained) of each branch of +the dependencies listed in RELEASE_CHECK (comma-separated, default lfric_apps, +empty to disable) is compared with the first entry's. A branch containing a +newer release, or based on a release from an older year and month, is +rejected; one on an older patch release of the same year and month is merged +with a warning. + +With the local mirrors, a fork's ref is fetched as / (branches) and, +if not found, as the tag refs/tags/, as the mirrors keep fork tags +without the user. + +clone_and_merge() fetches every branch and checks its release before merging +any, then leaves out branches that cannot be fetched, are on a different +release or have unresolved conflicts, and merges the rest, so a single run +reports every problem (as one MergeProblemsError). """ +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 +99,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 @@ -108,42 +144,142 @@ def datetime_str() -> str: return datetime.now().strftime("%Y-%m-%d %H:%M:%S") +class ReleaseMismatchError(RuntimeError): + """A branch is based on a different release than the base""" + + +class MergeConflictError(RuntimeError): + """A branch has merge conflicts that the conflict rules do not resolve""" + + +class MergeProblemsError(RuntimeError): + """ + Every problem found while merging the sources of one dependency: branches + that could not be fetched, are on a different release, or conflict + """ + + def __init__(self, dependency: str, problems: list[str]): + self.dependency = dependency + self.problems = problems + lines = [ + "", + f"{len(problems)} problem(s) found merging the {dependency} sources.", + ] + if len(problems) > 1: + lines.append( + "Branches with a problem are left out, so each later branch is " + "checked against the branches above it that merged." + ) + for n, problem in enumerate(problems, 1): + lines += ["", f"--- Problem {n} of {len(problems)} " + "-" * 40, problem] + super().__init__("\n".join(lines)) + + def clone_and_merge( - opts: Union[list, dict], loc: Path, use_mirrors: bool, mirror_loc: Path -) -> None: + opts: Union[list, dict], + loc: Path, + use_mirrors: bool, + mirror_loc: Path, + warnings: list[str] | None = None, +) -> list[dict[str, str]]: """ Wrapper script for calling get_source and merge_source for a single dependency + Every later entry is fetched and, for dependencies in RELEASE_CHECK, has its + release checked before anything is merged. Entries that cannot be fetched, + are on a different release or have unresolved conflicts are left out and + the rest are still merged, so that one run reports every problem, raised + together as a MergeProblemsError. + opts: dict or list of dicts for a dependency in the dependencies file loc: path to location to clone to use_mirrors: bool, use local git mirrors if true mirror_loc: path to local git mirrors + warnings: if given, warnings that do not stop the merge (branches on an + older patch release) are appended to it as well as logged + + Returns the entries with each ref replaced by the commit merged, except a + first entry synced from a local working copy, which is kept as it is. """ if not isinstance(opts, list): opts = [opts] - - for i, values in enumerate(opts): + for values in opts: if values["ref"] is None: values["ref"] = "" - # Clone the first provided source - if i == 0: - get_source( - values["source"], - values["ref"], - loc, - use_mirrors, - mirror_loc, + # Clone the first provided source + first, later = opts[0], opts[1:] + get_source(first["source"], first["ref"], loc, use_mirrors, mirror_loc) + pinned = [dict(first)] + if ".git" in first["source"]: + pinned[0]["ref"] = run_git(loc, "rev-parse", "HEAD").stdout.strip() + + # Fetch every later source and check its release before merging any + problems = [] + fetched = {} + for i, values in enumerate(later): + try: + fetched[i] = fetch_source( + values["source"], values["ref"], loc, use_mirrors, mirror_loc ) - # For all other sources, attempt to merge into the first - else: - merge_source( - values["source"], - values["ref"], - loc, - use_mirrors, - mirror_loc, + except SubprocessRunError as err: + problems.append(fetch_failure(values, err)) + if release_checked(loc.name) and fetched: + fetch_release_tags(loc) + for i, sha in list(fetched.items()): + try: + warning = check_release(later[i]["source"], later[i]["ref"], loc, sha) + except ReleaseMismatchError as err: + problems.append(str(err).strip("\n")) + del fetched[i] + continue + if warning: + logger.warning(warning) + if warnings is not None: + warnings.append(warning) + + # For all other sources, attempt to merge into the first + for i, values in enumerate(later): + if i not in fetched: + continue + try: + sha = merge_source( + values["source"], values["ref"], loc, use_mirrors, mirror_loc ) + except MergeConflictError as err: + problems.append(str(err).strip("\n")) + run_command(f"git -C {loc} merge --abort", check=False) + continue + pinned.append({**values, "ref": sha}) + + if problems: + raise MergeProblemsError(loc.name, problems) + return pinned + + +def fetch_failure(values: dict, err: SubprocessRunError) -> str: + """ + Describe a dependencies.yaml entry that could not be fetched + """ + + lines = (err.stderr or "").strip().splitlines() + # Prefer git's "fatal:" line over the generic advice that follows it + reason = [line for line in lines if line.startswith("fatal:")] or lines[-1:] + return "\n".join( + [ + "The following branch could not be fetched:", + "", + f"source: {values['source']}", + f"ref: {values['ref']}", + "", + f"git reported: {reason[0] if reason else err.returncode}", + *[line for line in lines if line.startswith("(also tried")], + ( + "Check the source and ref in dependencies.yaml, and that you can " + "access the repository." + ), + ] + ) def get_source( @@ -175,23 +311,13 @@ def get_source( sync_repo(source, ref, dest) -def merge_source( - source: Union[Path, str], - ref: str, - dest: Path, - use_mirrors: bool = False, - mirror_loc: Path = Path(""), -) -> None: +def remote_location( + source: Path | str, ref: str, use_mirrors: bool, mirror_loc: Path +) -> tuple[Path | str, str]: """ - Merge git source into a local git clone. Assumes dest is a git clone that this - source can be merged into. + Return the remote to fetch a source from and the ref to fetch """ - logger.info( - f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Merging " - f"{source} at ref {ref} into {dest.name}" - ) - if not any( [g for g in ["https:", "git@", "localmirrors:"] if str(source).startswith(g)] ): @@ -211,73 +337,510 @@ def merge_source( # Not using a clone or the mirrors remote_path = source fetch = ref + return remote_path, fetch - run_command(f"git -C {dest} remote add local {remote_path}") - run_command(f"git -C {dest} fetch local {fetch}") +def fetch_from_local_remote( + source: Path | str, + ref: str, + dest: Path, + use_mirrors: bool, + mirror_loc: Path, +) -> str: + """ + Fetch a source into dest's FETCH_HEAD through a temporary remote "local" + and return the commit fetched. The caller must remove the remote. + """ + + remote_path, fetch = remote_location(source, ref, use_mirrors, mirror_loc) + # Remove a remote left behind by an interrupted run + run_command(f"git -C {dest} remote remove local", check=False) + run_command(f"git -C {dest} remote add local {remote_path}") - command = f"git -C {dest} merge --no-gpg-sign --no-edit FETCH_HEAD" + command = f"git -C {dest} fetch local {fetch}" result = run_command(command, check=False) + if result.returncode and fetch != ref: + # The mirrors keep fork branches as / but fork tags + # without the user, as refs/tags/, so try the ref as a tag + tag = run_command(f"git -C {dest} fetch local refs/tags/{ref}", check=False) + if not tag.returncode: + logger.info(f"{fetch} is not in the mirror; using the tag {ref}") + result = tag if result.returncode: - unmerged_files = get_unmerged(dest) - if unmerged_files: - handle_merge_conflicts(source, ref, dest, dest.name) - else: - raise SubprocessRunError( - result.returncode, command, result.stdout, result.stderr + stderr = result.stderr + if fetch != ref: + stderr = f"{stderr}\n(also tried the tag refs/tags/{ref})" + logger.error(f"[FAIL] Command failed: {command}") + raise SubprocessRunError(command, result.returncode, result.stdout, stderr) + return run_git(dest, "rev-parse", "FETCH_HEAD^{commit}").stdout.strip() + + +def fetch_source( + source: Path | str, + ref: str, + dest: Path, + use_mirrors: bool = False, + mirror_loc: Path = Path(""), +) -> str: + """ + Fetch a source into dest without merging it and return the commit fetched + """ + + try: + return fetch_from_local_remote(source, ref, dest, use_mirrors, mirror_loc) + finally: + run_command(f"git -C {dest} remote remove local", check=False) + + +def merge_source( + source: Union[Path, str], + ref: str, + dest: Path, + use_mirrors: bool = False, + mirror_loc: Path = Path(""), +) -> str: + """ + Merge git source into a local git clone. Assumes dest is a git clone that this + source can be merged into. Returns the commit merged. + Raises MergeConflictError, leaving the merge in progress, if conflicts + remain after applying the conflict rules. + """ + + logger.info( + f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Merging " + f"{source} at ref {ref} into {dest.name}" + ) + + try: + sha = fetch_from_local_remote(source, ref, dest, use_mirrors, mirror_loc) + + 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: + # 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( + command, result.returncode, result.stdout, result.stderr + ) + finally: + # Remove the added remote + run_command(f"git -C {dest} remote remove local", check=False) + return sha + + +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 release_checked(dependency: str) -> bool: + """ + Return whether branches of dependency must be on the base release: it is + listed in RELEASE_CHECK (default lfric_apps; empty to disable) + """ + + checked = os.environ.get("RELEASE_CHECK", DEFAULT_RELEASE_CHECK).split(",") + return dependency in [c.strip() for c in checked] + + +def fetch_release_tags(dest: Path) -> None: + """ + Release tags are not fetched with a single ref, so get them from the + repository the base was cloned from + """ + + result = run_command( + f"git -C {dest} fetch -q --no-tags --no-write-fetch-head origin " + "+refs/tags/*:refs/tags/*", + check=False, + ) + if result.returncode: + logger.warning( + f"Could not fetch release tags for {dest.name} from origin; the " + "release check uses the tags already in the clone\n" + f"{(result.stderr or '').strip()}" + ) + + +def check_release(source: str, ref: str, dest: Path, rev: str) -> str | None: + """ + Check the release that commit rev of the branch is based on against the + source merged so far (HEAD). Call fetch_release_tags first. + + Raises ReleaseMismatchError if the branch contains a newer release, which + would bring newer upstream changes into the base, or is based on a release + from an older year and month. Returns a warning if it is only on an older + patch release (same YYYY.MM), which usually merges cleanly; else None. + """ + + base = newest_release(dest, "HEAD") + branch = newest_release(dest, rev) + 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 None + if base == branch: + return None + + older = release_key(branch) < release_key(base) + if older and release_key(branch)[:2] == release_key(base)[:2]: + return ( + f"{dest.name} {ref} ({source}) is based on the older patch release " + f"{branch}; the base is {base}. It is merged, but rebasing it onto " + f"{base} is recommended." + ) + + relation = "an older" if older else "a newer" + raise ReleaseMismatchError( + "\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]]: + """ + 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 - # Remove the added remote - run_command(f"git -C {dest} remote remove local") + +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[path] = stages 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) - 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}" - "\n\nThese will need changing in the source branches to be useable together" + action = resolve_conflict(loc, path, stages, strategy) + logger.warning(f"Resolved merge conflict in {path} ({strategy}): {action}") + + if unresolved: + raise MergeConflictError( + conflict_report(source, ref, loc, dependency, unresolved) ) - # 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 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 + """ + + 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/merge_sources.py b/github_scripts/merge_sources.py index 9f884911..ea206947 100755 --- a/github_scripts/merge_sources.py +++ b/github_scripts/merge_sources.py @@ -6,17 +6,39 @@ # ----------------------------------------------------------------------------- """ Script to clone and merge git sources + +With --check, the sources are merged into a scratch directory (deleted +afterwards unless --path is given) to find, before a suite is run, every +problem its extract task would hit: branches that cannot be fetched, are on a +different release than the first entry (see RELEASE_CHECK) or conflict. The +same merge code is used as in the extract task, so a clean check means a +clean extract of the same commits. Use --pin to write a copy of the +dependencies file with each ref pinned to the commit checked, so that the +suite merges exactly those commits. + +Exit status: 0 if every source merged, 1 if any problem was found. """ import argparse +import copy import os +import shutil +import sys +import tempfile import yaml from pathlib import Path -from get_git_sources import clone_and_merge, set_https, validate_dependencies +from get_git_sources import ( + MergeProblemsError, + clone_and_merge, + set_https, + validate_dependencies, +) import logging +logger = logging.getLogger(__name__) -def parse_args(): + +def parse_args(argv=None): """ Parse arguments """ @@ -54,37 +76,113 @@ def parse_args(): help="If true, https github sources will be used, requiring github " "authentication via Personal Access Tokens", ) - args = parser.parse_args() + parser.add_argument( + "--check", + action="store_true", + help="Check the dependencies before running a suite: merge into a " + "scratch directory, deleted afterwards unless --path is given, and " + "report every problem found", + ) + parser.add_argument( + "--pin", + type=Path, + help="If every source merges, write a copy of the dependencies file to " + "this path with each ref replaced by the commit merged", + ) + args = parser.parse_args(argv) args.dependencies = args.dependencies.resolve() if args.dependencies.is_dir(): args.dependencies = args.dependencies / "dependencies.yaml" - if not args.path: + args.scratch = args.check and not args.path + if args.scratch: + args.path = Path(tempfile.mkdtemp(prefix="merge_check_")) + elif not args.path: args.path = Path(os.getenv("CYLC_WORKFLOW_SHARE_DIR", __file__)) / "source" args.path = args.path.resolve() return args -def main(): +def merge_all(args) -> int: """ - Main Function + Clone and merge every dependency, reporting the problems of all of them. + Returns the exit status. """ - args = parse_args() - - logging.basicConfig(level=logging.INFO) - dependencies = yaml.safe_load(args.dependencies.read_text()) validate_dependencies(dependencies) + original = copy.deepcopy(dependencies) if args.tokens: dependencies = set_https(dependencies) + problems = [] + warnings = [] + pinned = {} for dependency, sources in dependencies.items(): dest = args.path / dependency - clone_and_merge(sources, dest, args.mirrors, args.mirror_loc) + try: + merged = clone_and_merge( + sources, dest, args.mirrors, args.mirror_loc, warnings + ) + except MergeProblemsError as err: + problems.append(err) + continue + # Pin the refs, keeping the sources as written (not converted to https) + entries = original[dependency] + if isinstance(entries, dict): + entries = [entries] + pinned[dependency] = [ + {**entry, "ref": m["ref"]} for entry, m in zip(entries, merged) + ] + + if problems: + print("\n".join(str(p) for p in problems), file=sys.stderr) + if warnings: + print( + "\nWarnings:\n" + "\n".join(f" - {w}" for w in warnings), + file=sys.stderr, + ) + + if problems: + print( + f"\nMerge {'check' if args.check else 'of sources'} FAILED for: " + + ", ".join(p.dependency for p in problems), + file=sys.stderr, + ) + if args.pin: + print( + f"Not writing {args.pin}: fix the problems above first", file=sys.stderr + ) + return 1 + + if args.pin: + args.pin.write_text(yaml.safe_dump(pinned, sort_keys=False)) + print(f"Pinned dependencies written to {args.pin}") + if args.check: + print( + "Merge check passed: every source merges" + + ("" if args.scratch else f" (sources in {args.path})") + ) + return 0 + + +def main(argv=None) -> int: + """ + Main Function + """ + + args = parse_args(argv) + + logging.basicConfig(level=logging.INFO) + + try: + return merge_all(args) + finally: + if args.scratch: + shutil.rmtree(args.path, ignore_errors=True) if __name__ == "__main__": - main() + sys.exit(main()) diff --git a/github_scripts/tests/test_get_git_sources.py b/github_scripts/tests/test_get_git_sources.py index 66112be3..55ea93be 100644 --- a/github_scripts/tests/test_get_git_sources.py +++ b/github_scripts/tests/test_get_git_sources.py @@ -8,12 +8,19 @@ """ import os +import re import subprocess +import sys from shlex import split from pathlib import Path import pytest +import yaml from ..get_git_sources import ( + MergeConflictError, + MergeProblemsError, + SubprocessRunError, + clone_and_merge, validate_dependencies, determine_mirror_fetch, set_https, @@ -22,6 +29,9 @@ sync_repo, check_existing, merge_source, + get_conflict_rules, + match_conflict_rule, + run_command, ) @@ -120,20 +130,18 @@ def test_merge_sources(setup_sources): target_clone = setup_sources / "SimSys_Scripts" - # Test Remote Source merges cleanly - assert ( - merge_source( - "https://github.com/MetOffice/SimSys_Scripts.git", - "main", - target_clone, - ) - is None + # Test Remote Source merges cleanly, returning the commit merged + sha = merge_source( + "https://github.com/MetOffice/SimSys_Scripts.git", + "main", + target_clone, ) + assert re.fullmatch(r"[0-9a-f]{40}", sha) # Test Local Source Merges Cleanly - assert ( - merge_source(setup_sources / "merge0", "merge0", target_clone, "SimSys_Scripts") - is None + sha = merge_source( + setup_sources / "merge0", "merge0", target_clone, "SimSys_Scripts" ) + assert sha == git(setup_sources / "merge0", "rev-parse", "merge0").strip() # Test Local Source Doesn't Merge with pytest.raises(RuntimeError): merge_source(setup_sources / "merge1", "merge1", target_clone, "SimSys_Scripts") @@ -263,3 +271,364 @@ 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(MergeConflictError, 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" + ) + dest = make_dest() + assert ( + merge_source(fork, "theirs", dest) == git(fork, "rev-parse", "theirs").strip() + ) + 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") + merge_source(fork, "theirs", second) + 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 + + +@pytest.fixture +def release_repos(tmp_path, monkeypatch): + """ + An upstream with releases 2026.03.0 < 2026.07.0 < 2026.07.1 < 2026.07.3 and + branches: + same - from 2026.07.1 + older - from 2026.03.0 (older year and month) + older_patch - from 2026.07.0 (older patch release) + 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.03.0", "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.03.0"), + ("older_patch", "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 deps(upstream, *refs): + """ + dependencies.yaml entries merging refs of upstream onto 2026.07.1 + """ + + return [{"source": str(upstream), "ref": ref} for ref in ("2026.07.1", *refs)] + + +def test_merge_checks_release(release_repos, tmp_path, monkeypatch): + """ + Branches based on an older or newer release than the base are rejected, + and both are reported by one run + """ + + _, upstream = release_repos + + dest = tmp_path / "same" / "lfric_apps" + pinned = clone_and_merge(deps(upstream, "same"), dest, False, Path("")) + # A first entry synced from a local working copy keeps its ref, as + # pinning it would drop uncommitted changes + assert [p["ref"] for p in pinned] == [ + "2026.07.1", + git(upstream, "rev-parse", "same").strip(), + ] + + dest = tmp_path / "mismatch" / "lfric_apps" + with pytest.raises(MergeProblemsError) as err: + clone_and_merge(deps(upstream, "older", "newer", "same"), dest, False, Path("")) + message = str(err.value) + assert "2 problem(s) found merging the lfric_apps sources" in message + assert "based on an older lfric_apps release" in message + assert "based on a newer lfric_apps release" in message + # Rejected branches are not merged, later ones still are + assert not (dest / "older.txt").exists() + assert not (dest / "newer.txt").exists() + assert (dest / "same.txt").exists() + assert "local" not in git(dest, "remote") + + # An older patch release of the same year and month only warns + dest = tmp_path / "patch" / "lfric_apps" + warnings = [] + clone_and_merge(deps(upstream, "older_patch"), dest, False, Path(""), warnings) + assert (dest / "older_patch.txt").exists() + assert len(warnings) == 1 + assert "older patch release 2026.07.0; the base is 2026.07.1" in warnings[0] + + monkeypatch.setenv("RELEASE_CHECK", "") + dest = tmp_path / "disabled" / "lfric_apps" + clone_and_merge(deps(upstream, "older"), dest, False, Path("")) + assert (dest / "older.txt").exists() + + +def test_merge_reports_every_problem(release_repos, tmp_path): + """ + A branch that cannot be fetched, one on another release and one that + conflicts are all reported by one run; the merge continues past each and + is left clean + """ + + _, upstream = release_repos + for branch in ("c1", "c2"): + git(upstream, "switch", "-q", "-c", branch, "2026.07.1") + (upstream / "shared.txt").write_text(f"{branch}\n") + git(upstream, "add", ".") + git(upstream, "commit", "-q", "-m", branch) + git(upstream, "switch", "-q", "main") + + dest = tmp_path / "all" / "lfric_apps" + refs = ("no_such_branch", "older", "c1", "c2", "same") + with pytest.raises(MergeProblemsError) as err: + clone_and_merge(deps(upstream, *refs), dest, False, Path("")) + problems = err.value.problems + assert len(problems) == 3 + assert "could not be fetched" in problems[0] and "no_such_branch" in problems[0] + assert "based on an older lfric_apps release" in problems[1] + assert "ref: c2" in problems[2] and "shared.txt" in problems[2] + # c1 and same merged; c2 aborted, leaving a clean clone + assert (dest / "shared.txt").read_text() == "c1\n" + assert (dest / "same.txt").exists() + assert git(dest, "status", "--porcelain") == "" + assert "local" not in git(dest, "remote") + + +def test_merge_sources_check_and_pin(release_repos, tmp_path): + """ + merge_sources.py --check reports problems with exit status 1, and writes + a pinned dependencies file only when every source merges + """ + + _, upstream = release_repos + script = Path(__file__).parents[1] / "merge_sources.py" + pin = tmp_path / "pinned.yaml" + + def check(*refs): + deps_file = tmp_path / "dependencies.yaml" + deps_file.write_text(yaml.safe_dump({"lfric_apps": deps(upstream, *refs)})) + return subprocess.run( + [ + sys.executable, + str(script), + "-d", + str(deps_file), + "--check", + "--pin", + str(pin), + ], + capture_output=True, + text=True, + check=False, + ) + + result = check("older", "same") + assert result.returncode == 1 + assert "based on an older lfric_apps release" in result.stderr + assert "Merge check FAILED for: lfric_apps" in result.stderr + assert not pin.exists() + + result = check("older_patch", "same") + assert result.returncode == 0, result.stderr + assert "Merge check passed" in result.stdout + assert "Warnings:" in result.stderr + assert "older patch release 2026.07.0" in result.stderr + + result = check("same") + assert result.returncode == 0, result.stderr + pinned = yaml.safe_load(pin.read_text())["lfric_apps"] + assert pinned == [ + {"source": str(upstream), "ref": "2026.07.1"}, + {"source": str(upstream), "ref": git(upstream, "rev-parse", "same").strip()}, + ] + + +def test_merge_fork_tag_from_mirror(release_repos, tmp_path): + """ + With the mirrors, fork branches are fetched as / and fork + tags, which the mirrors keep without the user, as refs/tags/ + """ + + _, upstream = release_repos + git(upstream, "tag", "fork_tag", "same") + git(upstream, "branch", "fork_branch", "older_patch") + + # Lay the mirror out as the Met Office mirrors are + mirror_loc = tmp_path / "mirrors" + mirror = mirror_loc / "MetOffice" / "lfric_apps.git" + git(tmp_path, "clone", "-q", "--bare", str(upstream), str(mirror)) + git(mirror, "update-ref", "refs/remotes/someone/fork_branch", "fork_branch") + git(mirror, "branch", "-D", "fork_branch") + + fork = "git@github.com:someone/lfric_apps.git" + opts = [ + {"source": "git@github.com:MetOffice/lfric_apps.git", "ref": "2026.07.1"}, + {"source": fork, "ref": "fork_tag"}, + {"source": fork, "ref": "fork_branch"}, + ] + dest = tmp_path / "mirrored" / "lfric_apps" + pinned = clone_and_merge(opts, dest, True, mirror_loc) + assert (dest / "same.txt").exists() + assert (dest / "older_patch.txt").exists() + assert pinned[1]["ref"] == git(upstream, "rev-parse", "same").strip() + + # A ref that is neither says both were tried + opts[1]["ref"] = "no_such_ref" + dest = tmp_path / "missing" / "lfric_apps" + with pytest.raises(MergeProblemsError) as err: + clone_and_merge(opts[:2], dest, True, mirror_loc) + assert "someone/no_such_ref" in str(err.value) + assert "(also tried the tag refs/tags/no_such_ref)" in str(err.value)