diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index f0cf023..f942123 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -23,16 +23,14 @@ - id: prepare-commit-msg name: prepare commit message - description: add the JIRA ID found in the branch name in case it is missing from the commit message - entry: git_message_hook - args: [--prepare] + description: add the branch JIRA ID to the subject or, with --issue-trailer, an Issue trailer + entry: git_message_hook --prepare language: python stages: [prepare-commit-msg] - id: check-commit-msg name: check commit message - description: check the commit message for a valid JIRA ID - entry: git_message_hook - args: [--check] + description: check for a valid JIRA ID in the subject or, with --issue-trailer, an Issue trailer + entry: git_message_hook --check language: python stages: [commit-msg] diff --git a/README.md b/README.md index 9c1d794..c79fd55 100644 --- a/README.md +++ b/README.md @@ -81,17 +81,78 @@ Only enable the optional PyTorch check with `--check-pytorch` when required. which can reject recipes whose constraints apply to a different platform. ### `prepare-commit-msg` -Adds the JIRA ID found in the branch name in case it is missing from the commit message. +Adds the JIRA ID found in the branch name in case it is missing from the commit +message, including during a rebase or cherry-pick. Existing JIRA IDs in replayed +commit messages are preserved. -### `check-commit-message` +### `check-commit-msg` Checks that the branch name or the commit message starts with a reference to JIRA, -and if the message meets the minimum required length for the summary line. Also checks -that the JIRA ID in the commit message is consistent with the one extracted from the -branch name (if any). +and that the message meets the minimum required length for the summary line. Also +checks that the JIRA ID in the commit message is consistent with the one extracted +from the branch name (if any), except during a rebase or cherry-pick, when replayed +commit messages may have a different JIRA ID. During a rebase, a JIRA ID is also +optional when neither the branch nor the commit message supplies one. Minimum +summary length is not enforced during rebases or cherry-picks. + +By default, the message hooks use a JIRA ID at the beginning of the commit subject. +To use an `Issue: GA-1234` footer trailer instead, enable `--issue-trailer` on both +hooks: + +```yaml +hooks: +- id: prepare-commit-msg + args: [--issue-trailer] +- id: check-commit-msg + args: [--issue-trailer] +``` + +For example, a prepared message would be: + +```text +Fix the coordinate transformation + +Explain the change here. + +Issue: GA-1234 +``` + +In this mode, preparation leaves the subject unchanged and adds the branch's JIRA +ID as an Issue trailer only when no Issue trailer already exists. Existing trailers +and the message body are retained. Trailers form the final block of +colon-separated fields, separated from the subject or body by a blank line; +indented continuation lines are supported. An ID in the subject, body, `#` template +comments, or patch text does not count as an Issue trailer. + +The hooks handle trailers directly in Python, without starting Git. They use fixed +`Issue:` syntax and do not read Git's `trailer.*` configuration settings for custom +keys, separators, insertion order, duplicate handling, or commands that generate +trailer values. No Git trailer configuration is required. Those settings still +apply when using Git's own trailer commands. + +Validation uses Issue trailers instead of subject prefixes. Each Issue trailer must +contain a valid JIRA ID, and IDs must match the branch's ID when one exists, except +during rebases or cherry-picks. As in subject mode, the branch's ID alone can +satisfy the JIRA requirement. Summary length is measured on the subject without +counting trailer text. The existing rebase and cherry-pick exceptions apply in +both modes. + +### Autosquash commits +The Git prefixes `fixup!`, `squash!`, and `amend!` identify autosquash targets, +including when those prefixes are nested. The hooks preserve the exact target +subject so that `git rebase --autosquash` can still match the original commit. In +header mode, no JIRA ID is inserted into these subjects; the branch's JIRA ID can +satisfy validation, and an existing ID after the bang prefixes is still parsed +and checked for consistency. In trailer mode, validation continues to use the +Issue trailer or branch, and a missing Issue trailer can still be added without +changing the subject. + +Autosquash targets are exempt from the minimum summary length because they can +reference short original subjects or commit hashes. JIRA presence and consistency +checks still apply, subject to the existing rebase and cherry-pick exceptions. ## Usage -Example of `.pre-commit-config.yamnl`: +Example of `.pre-commit-config.yaml`: ```yaml repos: diff --git a/mirageoscience/hooks/git_message_hook.py b/mirageoscience/hooks/git_message_hook.py index 1014afa..03acf37 100644 --- a/mirageoscience/hooks/git_message_hook.py +++ b/mirageoscience/hooks/git_message_hook.py @@ -14,12 +14,15 @@ from __future__ import annotations import argparse +import os +import pathlib import re -import shlex -import subprocess import sys +_TRAILER_LINE = re.compile(r"([A-Za-z0-9-]+)[ \t]*:[ \t]*(.*)") + + def get_jira_id(text) -> str: """Detect a JIRA issue ID at the begging of the given text. @@ -45,17 +48,16 @@ def get(): def get_message_prefix_bang(line: str) -> str: - """Capture the standard commit message prefix, if any, such as 'fixup!', 'amend!', - etc. + """Capture Git autosquash prefixes, including nested fixup!, squash!, and amend!. :return: the standard commit message prefix if found, else empty string. """ class BangPattern: - """Internal class that encapsulates the regular expression for the Bnag pattern, + """Internal class that encapsulates the regular expression for the bang pattern, making sure it gets compiled only once.""" - __pattern = re.compile(r"(\w*!\s)") + __pattern = re.compile(r"((?:(?:fixup|squash|amend)! )+)") @staticmethod def get(): @@ -67,49 +69,162 @@ def get(): return match.group(1) if match else "" -def get_branch_name() -> str | None: - """:return: the name of the current branch""" +def _get_git_dir() -> pathlib.Path | None: + """Resolve the actual git directory, handling GIT_DIR and worktrees. - git_proc = subprocess.run( - shlex.split("git branch --list"), stdout=subprocess.PIPE, text=True, check=False + In a normal repo, `.git` is a directory. + In a worktree, `.git` is a file containing "gitdir: ". + """ + git_dir = os.environ.get("GIT_DIR") + if git_dir: + return pathlib.Path(git_dir).resolve() + + for directory in (pathlib.Path.cwd(), *pathlib.Path.cwd().parents): + git_path = directory / ".git" + if not git_path.exists(): + continue + if git_path.is_dir(): + return git_path.resolve() + # worktree: .git is a file + content = git_path.read_text(encoding="utf-8").strip() + if content.startswith("gitdir:"): + git_dir_path = pathlib.Path(content[len("gitdir:") :].strip()) + if not git_dir_path.is_absolute(): + git_dir_path = git_path.parent / git_dir_path + return git_dir_path.resolve() + return None + + +def _is_rebase_in_progress() -> bool: + """Return whether Git has an active rebase state directory.""" + git_dir = _get_git_dir() + return git_dir is not None and any( + (git_dir / rebase_dir).is_dir() + for rebase_dir in ("rebase-merge", "rebase-apply") ) - if git_proc.returncode != 0: - return None - current_branch = None - # current branch is prefixed by '*' - for line in git_proc.stdout.splitlines(): - stripped = line.strip() - if stripped and stripped[0] == "*": - current_branch = stripped[1:] - break - assert current_branch is not None +def _is_replay_in_progress() -> bool: + """Return whether Git is rebasing or cherry-picking a commit.""" + git_dir = _get_git_dir() + return _is_rebase_in_progress() or ( + git_dir is not None and (git_dir / "CHERRY_PICK_HEAD").is_file() + ) - class RebasingPattern: - """Internal class that encapsulates the regular expression for the rebasing - message pattern, making sure it gets compiled only once.""" - __pattern = re.compile(r"\(.*\s(\S+)\s*\)") +def get_branch_name() -> str | None: + """:return: the name of the current branch""" + git_dir = _get_git_dir() + if git_dir is None: + return None - @staticmethod - def get(): - """:return: the compiled regular expression for the Rebasing pattern""" - return RebasingPattern.__pattern + head_file = git_dir / "HEAD" + if not head_file.exists(): + return None - match = re.match(RebasingPattern.get(), current_branch.strip()) - if match: - return match.group(1) + content = head_file.read_text(encoding="utf-8").strip() + if content.startswith("ref: refs/heads/"): + return content[len("ref: refs/heads/") :] + + # Detached HEAD or active rebase: check rebase state files + for rebase_dir in ("rebase-merge", "rebase-apply"): + head_name_file = git_dir / rebase_dir / "head-name" + if head_name_file.exists(): + ref = head_name_file.read_text(encoding="utf-8").strip() + if ref.startswith("refs/heads/"): + return ref[len("refs/heads/") :] + + return None # detached HEAD with no active rebase + + +def _get_trailer_block(lines: list[str]) -> tuple[int, int]: + """Find the final trailer paragraph before template comments or patch text.""" + end = len(lines) + for index, line in enumerate(lines): + if ( + line.rstrip("\r\n") == "---" + or line.startswith("# ------------------------ >8 ") + or line.startswith("diff --git ") + ): + end = index + break + while end and (not lines[end - 1].strip() or lines[end - 1].startswith("#")): + end -= 1 + start = end + while start and lines[start - 1].strip(): + start -= 1 + if start == 0: + return end, end + + has_trailer = False + for line in lines[start:end]: + if line.startswith("#"): + continue + if _TRAILER_LINE.fullmatch(line.rstrip("\r\n")): + has_trailer = True + elif not (has_trailer and line.startswith((" ", "\t"))): + return end, end + return (start, end) if has_trailer else (end, end) + + +def _get_commit_subject(message: str, *, issue_trailer: bool) -> tuple[str, str]: + """Return the first nonblank, non-comment subject and its autosquash prefix.""" + lines = message.splitlines(keepends=True) + if issue_trailer: + lines = lines[: _get_trailer_block(lines)[0]] + for line in lines: + if not line.startswith("#") and line.strip(): + subject = line.strip() + prefix_bang = get_message_prefix_bang(subject) + return subject[len(prefix_bang) :].strip(), prefix_bang + return "", "" + + +def _get_issue_trailers(message: str) -> list[str]: + """Read Issue values from the final block of colon-separated trailers.""" + lines = message.splitlines(keepends=True) + start, end = _get_trailer_block(lines) + issues = [] + current_issue = False + for line in lines[start:end]: + if line.startswith("#"): + continue + match = _TRAILER_LINE.fullmatch(line.rstrip("\r\n")) + if match: + current_issue = match.group(1).lower() == "issue" + if current_issue: + issues.append(match.group(2).strip()) + elif current_issue: + issues[-1] = f"{issues[-1]} {line.strip()}".strip() + return issues + + +def _prepare_issue_trailer(filepath: str, branch_jira_id: str) -> None: + """Append a missing Issue trailer without changing the commit subject.""" + message_path = pathlib.Path(filepath) + message = message_path.read_text(encoding="utf-8") + if _get_issue_trailers(message): + return - return current_branch + lines = message.splitlines(keepends=True) + start, end = _get_trailer_block(lines) + prefix = "".join(lines[:end]).rstrip("\r\n") + suffix = "".join(lines[end:]).lstrip("\r\n") + separator = "\n\n" if start == end else "\n" + message_path.write_text( + f"{prefix}{separator}Issue: {branch_jira_id}\n{suffix}", encoding="utf-8" + ) -def check_commit_message(filepath: str) -> tuple[bool, str]: +def check_commit_message( + filepath: str, *, issue_trailer: bool = False +) -> tuple[bool, str]: """Check if the branch name or the commit message starts with a reference to JIRA, and if the message meets the minimum required length for the summary line. The JIRA reference has to be at the beginning of the branch name, or of the commit - message. + message, or in an Issue trailer when issue_trailer is enabled. Summary length + is not checked for autosquash targets or during a rebase or cherry-pick. :return: a tuple telling whether the commit message is valid or not, and an error message (empty in case the message is valid). """ @@ -119,61 +234,85 @@ def check_commit_message(filepath: str) -> tuple[bool, str]: if branch_name: branch_jira_id = get_jira_id(branch_name) - message_jira_id = "" - first_line = None with open(filepath, encoding="utf-8") as message_file: - for line in message_file: - if not line.startswith("#") and len(line.strip()) > 0: - # test only the first non-comment line that is not empty - # (should we reject messages with empty first line?) - first_line = line.strip() - prefix_bang = get_message_prefix_bang(first_line) - first_line = first_line[len(prefix_bang) :].strip() - message_jira_id = get_jira_id(first_line) - break - assert first_line is not None + message = message_file.read() + first_line, prefix_bang = _get_commit_subject(message, issue_trailer=issue_trailer) + + if issue_trailer: + message_jira_ids = _get_issue_trailers(message) + if any(not value or get_jira_id(value) != value for value in message_jira_ids): + return False, "Each Issue trailer must contain a valid JIRA ID." + else: + header_jira_id = get_jira_id(first_line) + message_jira_ids = [header_jira_id] if header_jira_id else [] + message_jira_id = next( + (jira_id for jira_id in message_jira_ids if jira_id != branch_jira_id), + message_jira_ids[0] if message_jira_ids else "", + ) - if not branch_jira_id and not ( - message_jira_id or (not prefix_bang and first_line.lower().startswith("merge")) + if ( + not branch_jira_id + and not ( + message_jira_id + or (not prefix_bang and first_line.lower().startswith("merge")) + ) + and not _is_rebase_in_progress() ): return ( False, - "Either the branch name or the commit message must start with a JIRA ID.", + ( + "Either the branch name must start with a JIRA ID " + "or the commit message must contain an Issue trailer with a JIRA ID." + if issue_trailer + else "Either the branch name or the commit message must start with a JIRA ID." + ), ) - if branch_jira_id and message_jira_id and branch_jira_id != message_jira_id: + if ( + branch_jira_id + and message_jira_id + and branch_jira_id != message_jira_id + and not _is_replay_in_progress() + ): + location = "Issue trailer" if issue_trailer else "commit message" return ( False, - f"Different JIRA ID in commit message {message_jira_id} " + f"Different JIRA ID in {location} {message_jira_id} " f"and in branch name {branch_jira_id}.", ) stripped_message_line = "" if first_line: stripped_message_line = first_line.strip() - if message_jira_id: + if message_jira_id and not issue_trailer: stripped_message_line = stripped_message_line[ len(message_jira_id) + 1 : ].strip() min_required_length = 10 - if len(stripped_message_line) < min_required_length: + if ( + len(stripped_message_line) < min_required_length + and not prefix_bang + and not _is_replay_in_progress() + ): return ( False, f"First line of commit message must be at least {min_required_length} characters long, " - "beyond the JIRA ID.", + + ("in the subject." if issue_trailer else "beyond the JIRA ID."), ) return True, "" -def check_commit_msg(filepath: str) -> None: +def check_commit_msg(filepath: str, *, issue_trailer: bool = False) -> None: """To be used as the Git commit-msg hook. Exit with non-0 status if the commit message is deemed invalid. """ - (is_valid, error_message) = check_commit_message(filepath) + (is_valid, error_message) = check_commit_message( + filepath, issue_trailer=issue_trailer + ) if not is_valid: print( f"""commit-msg hook: **ERROR** {error_message} @@ -182,13 +321,26 @@ def check_commit_msg(filepath: str) -> None: sys.exit(1) -def prepare_commit_msg(filepath: str, source: str | None = None) -> None: +def prepare_commit_msg( + filepath: str, + source: str | None = None, + _commit_id: str | None = None, + *, + issue_trailer: bool = False, +) -> None: """To be used as the Git prepare-commit-msg hook. Will add the JIRA ID found in the branch name in case it is missing from the commit - message. + message. During a rebase or cherry-pick, this also handles reused commit messages + and preserves any JIRA ID already in that message. Git may supply an unused + third argument identifying the original commit. + + With issue_trailer enabled, use an Issue trailer instead of the subject line. + Autosquash target subjects are never modified. """ + source = source or os.environ.get("PRE_COMMIT_COMMIT_MSG_SOURCE") + branch_jira_id = "" branch_name = get_branch_name() if branch_name: @@ -197,30 +349,37 @@ def prepare_commit_msg(filepath: str, source: str | None = None) -> None: if not branch_jira_id: return - if source not in [None, "message", "template"]: + # Ignore unknown sources + if source not in [None, "message", "template", "commit", "merge", "squash"]: + return + + # Ignore replayed messages outside a replay + if source in ["commit", "merge", "squash"] and not _is_replay_in_progress(): + return + + if issue_trailer: + _prepare_issue_trailer(filepath, branch_jira_id) return - prefix_bang = "" with open(filepath, "r+", encoding="utf-8") as message_file: message_has_jira_id = False message_lines = message_file.readlines() for line_index, line_content in enumerate(message_lines): - if not line_content.startswith("#"): - # test only the first non-comment line + if not line_content.startswith("#") and line_content.strip(): line_content = line_content.strip() - prefix_bang = get_message_prefix_bang(line_content) - line_content = line_content[len(prefix_bang) :].strip() + if get_message_prefix_bang(line_content): + # Preserve the exact autosquash target; inserting an ID would break matching. + # Validation still checks the existing subject ID or the branch ID. + return message_jira_id = get_jira_id(line_content) if not message_jira_id: - message_lines[line_index] = ( - f"{prefix_bang}[{branch_jira_id}] {line_content}\n" - ) + message_lines[line_index] = f"[{branch_jira_id}] {line_content}\n" message_has_jira_id = True break if not message_has_jira_id: # message is empty or all lines are comments: insert JIRA ID at the very beginning - message_lines.insert(0, f"{prefix_bang}[{branch_jira_id}]\n") + message_lines.insert(0, f"[{branch_jira_id}]\n") message_file.seek(0, 0) message_file.write("".join(message_lines)) @@ -239,10 +398,15 @@ def main(): action="store_true", help="check if the commit message is valid", ) + parser.add_argument( + "--issue-trailer", + action="store_true", + help="use an Issue trailer for the JIRA ID instead of the commit subject", + ) parser.add_argument("args", nargs=argparse.REMAINDER) args = parser.parse_args() if args.prepare: - prepare_commit_msg(args.msg_file, *args.args) + prepare_commit_msg(args.msg_file, *args.args, issue_trailer=args.issue_trailer) elif args.check: - check_commit_msg(args.msg_file) + check_commit_msg(args.msg_file, issue_trailer=args.issue_trailer) diff --git a/tests/git_message_hook_test.py b/tests/git_message_hook_test.py index a6f3bce..ae668f2 100644 --- a/tests/git_message_hook_test.py +++ b/tests/git_message_hook_test.py @@ -16,9 +16,12 @@ import pytest from mirageoscience.hooks.git_message_hook import ( + _get_git_dir, check_commit_message, + get_branch_name, get_jira_id, get_message_prefix_bang, + prepare_commit_msg, ) from mirageoscience.hooks.git_message_hook import ( main as git_message_hook_main, @@ -42,10 +45,13 @@ def test_get_jira_id(): assert get_jira_id(text) == "GEOPY-1233" -def test_get_message_prefix_bang_with_bang(): +@pytest.mark.parametrize( + "prefix", ["fixup! ", "squash! ", "amend! ", "fixup! fixup! ", "amend! squash! "] +) +def test_get_message_prefix_bang_with_bang(prefix: str): """Tests if get_message_prefix_bang can extract the prefix bang from a line.""" - line = "fixup! This is a fix" - expected_prefix_bang = "fixup! " + line = f"{prefix}This is a fix" + expected_prefix_bang = prefix actual_prefix_bang = get_message_prefix_bang(line) assert actual_prefix_bang == expected_prefix_bang @@ -126,7 +132,9 @@ def test_main_calls_prepare_commit_msg(): "mirageoscience.hooks.git_message_hook.prepare_commit_msg" ) as mock_prepare_commit_msg: git_message_hook_main() - mock_prepare_commit_msg.assert_called_once_with("msg_file", *[]) + mock_prepare_commit_msg.assert_called_once_with( + "msg_file", issue_trailer=False + ) def test_main_calls_check_commit_msg(): @@ -136,7 +144,9 @@ def test_main_calls_check_commit_msg(): "mirageoscience.hooks.git_message_hook.check_commit_msg" ) as mock_check_commit_msg: git_message_hook_main() - mock_check_commit_msg.assert_called_once_with("msg_file") + mock_check_commit_msg.assert_called_once_with( + "msg_file", issue_trailer=False + ) def test_main_with_remaining_args(): @@ -146,4 +156,740 @@ def test_main_with_remaining_args(): "mirageoscience.hooks.git_message_hook.prepare_commit_msg" ) as mock_prepare_commit_msg: git_message_hook_main() - mock_prepare_commit_msg.assert_called_once_with("msg_file", "arg1", "arg2") + mock_prepare_commit_msg.assert_called_once_with( + "msg_file", "arg1", "arg2", issue_trailer=False + ) + + +class TestGetGitDir: + def test_no_git(self, tmp_path: Path, monkeypatch): + """Returns None when there is no .git entry at all.""" + monkeypatch.chdir(tmp_path) + assert _get_git_dir() is None + + def test_normal_repo(self, tmp_path: Path, monkeypatch): + """Returns the .git directory for a normal (non-worktree) repo.""" + git_dir = tmp_path / ".git" + git_dir.mkdir() + monkeypatch.chdir(tmp_path) + assert _get_git_dir() == git_dir + + def test_worktree(self, tmp_path: Path, monkeypatch): + """Follows the gitdir: pointer written by git worktree.""" + # Simulate the real git dir living elsewhere + real_git_dir = tmp_path / "main_repo" / ".git" / "worktrees" / "my-worktree" + real_git_dir.mkdir(parents=True) + + worktree_root = tmp_path / "worktree" + worktree_root.mkdir() + (worktree_root / ".git").write_text( + f"gitdir: {real_git_dir}\n", encoding="utf-8" + ) + + monkeypatch.chdir(worktree_root) + assert _get_git_dir() == real_git_dir + + def test_git_dir_environment_variable(self, tmp_path: Path, monkeypatch): + """Uses GIT_DIR when Git provides an alternate git directory.""" + git_dir = tmp_path / "alternate_git_dir" + git_dir.mkdir() + (tmp_path / ".git").mkdir() + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("GIT_DIR", str(git_dir)) + assert _get_git_dir() == git_dir + + +class TestGetBranchName: + def test_normal_repo_on_branch(self, tmp_path: Path, monkeypatch): + """Reads the branch name from HEAD in a normal repo.""" + git_dir = tmp_path / ".git" + git_dir.mkdir() + (git_dir / "HEAD").write_text("ref: refs/heads/GA-1234\n", encoding="utf-8") + monkeypatch.chdir(tmp_path) + assert get_branch_name() == "GA-1234" + + @pytest.mark.parametrize("worktree", [False, True]) + def test_nested_directory_on_branch( + self, tmp_path: Path, monkeypatch, worktree: bool + ): + """Finds the enclosing repository from a subdirectory.""" + repo_root = tmp_path / "repo" + repo_root.mkdir() + if worktree: + git_dir = tmp_path / "main_repo" / ".git" / "worktrees" / "repo" + git_dir.mkdir(parents=True) + (repo_root / ".git").write_text(f"gitdir: {git_dir}\n", encoding="utf-8") + else: + git_dir = repo_root / ".git" + git_dir.mkdir() + (git_dir / "HEAD").write_text("ref: refs/heads/GA-5678\n", encoding="utf-8") + + nested_directory = repo_root / "src" + nested_directory.mkdir() + monkeypatch.chdir(nested_directory) + monkeypatch.delenv("GIT_DIR", raising=False) + + assert get_branch_name() == "GA-5678" + + def test_normal_repo_detached_head(self, tmp_path: Path, monkeypatch): + """Returns None for a detached HEAD with no active rebase.""" + git_dir = tmp_path / ".git" + git_dir.mkdir() + (git_dir / "HEAD").write_text( + "abc123def456abc123def456abc123def456abc123\n", encoding="utf-8" + ) + monkeypatch.chdir(tmp_path) + assert get_branch_name() is None + + def test_normal_repo_rebase_merge(self, tmp_path: Path, monkeypatch): + """Returns the original branch name during an active rebase-merge.""" + git_dir = tmp_path / ".git" + git_dir.mkdir() + # HEAD points to a commit SHA during a rebase + (git_dir / "HEAD").write_text( + "abc123def456abc123def456abc123def456abc123\n", encoding="utf-8" + ) + rebase_dir = git_dir / "rebase-merge" + rebase_dir.mkdir() + (rebase_dir / "head-name").write_text("refs/heads/GA-5678\n", encoding="utf-8") + monkeypatch.chdir(tmp_path) + assert get_branch_name() == "GA-5678" + + def test_normal_repo_rebase_apply(self, tmp_path: Path, monkeypatch): + """Returns the original branch name during an active rebase-apply (git am).""" + git_dir = tmp_path / ".git" + git_dir.mkdir() + (git_dir / "HEAD").write_text( + "abc123def456abc123def456abc123def456abc123\n", encoding="utf-8" + ) + rebase_dir = git_dir / "rebase-apply" + rebase_dir.mkdir() + (rebase_dir / "head-name").write_text( + "refs/heads/feature/my-feature\n", encoding="utf-8" + ) + monkeypatch.chdir(tmp_path) + assert get_branch_name() == "feature/my-feature" + + def test_worktree_on_branch(self, tmp_path: Path, monkeypatch): + """Reads the branch name through the worktree gitdir: pointer.""" + real_git_dir = tmp_path / "main_repo" / ".git" / "worktrees" / "my-worktree" + real_git_dir.mkdir(parents=True) + (real_git_dir / "HEAD").write_text( + "ref: refs/heads/GA-9999\n", encoding="utf-8" + ) + + worktree_root = tmp_path / "worktree" + worktree_root.mkdir() + (worktree_root / ".git").write_text( + f"gitdir: {real_git_dir}\n", encoding="utf-8" + ) + + monkeypatch.chdir(worktree_root) + assert get_branch_name() == "GA-9999" + + def test_worktree_rebase_merge(self, tmp_path: Path, monkeypatch): + """Reads the rebase branch name through the worktree gitdir: pointer.""" + real_git_dir = tmp_path / "main_repo" / ".git" / "worktrees" / "my-worktree" + real_git_dir.mkdir(parents=True) + (real_git_dir / "HEAD").write_text( + "abc123def456abc123def456abc123def456abc123\n", encoding="utf-8" + ) + rebase_dir = real_git_dir / "rebase-merge" + rebase_dir.mkdir() + (rebase_dir / "head-name").write_text("refs/heads/GA-7777\n", encoding="utf-8") + + worktree_root = tmp_path / "worktree" + worktree_root.mkdir() + (worktree_root / ".git").write_text( + f"gitdir: {real_git_dir}\n", encoding="utf-8" + ) + + monkeypatch.chdir(worktree_root) + assert get_branch_name() == "GA-7777" + + def test_no_git(self, tmp_path: Path, monkeypatch): + """Returns None when there is no .git entry.""" + monkeypatch.chdir(tmp_path) + assert get_branch_name() is None + + +class TestPrepareCommitMsg: + @staticmethod + def _set_up_rebase_git_dir(tmp_path: Path, monkeypatch) -> None: + git_dir = tmp_path / "alternate_git_dir" + rebase_dir = git_dir / "rebase-merge" + rebase_dir.mkdir(parents=True) + (git_dir / "HEAD").write_text("abc123\n", encoding="utf-8") + (rebase_dir / "head-name").write_text("refs/heads/GA-5678\n", encoding="utf-8") + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("GIT_DIR", str(git_dir)) + + @pytest.mark.parametrize("source", ["commit", "squash"]) + @pytest.mark.parametrize("issue_trailer", [False, True]) + def test_rebase_commit_without_jira_gets_branch_jira( + self, tmp_path: Path, monkeypatch, source: str, issue_trailer: bool + ): + self._set_up_rebase_git_dir(tmp_path, monkeypatch) + message_file = tmp_path / "COMMIT_EDITMSG" + message_file.write_text("An original commit message\n", encoding="utf-8") + + args = ["git_message_hook", "--prepare"] + if issue_trailer: + args.append("--issue-trailer") + args.extend([str(message_file), source, "HEAD"]) + monkeypatch.setattr(sys, "argv", args) + git_message_hook_main() + + expected_message = ( + "An original commit message\n\nIssue: GA-5678\n" + if issue_trailer + else "[GA-5678] An original commit message\n" + ) + assert message_file.read_text(encoding="utf-8") == expected_message + + @pytest.mark.parametrize("issue_trailer", [False, True]) + def test_rebase_commit_with_different_jira_is_preserved( + self, tmp_path: Path, monkeypatch, issue_trailer: bool + ): + self._set_up_rebase_git_dir(tmp_path, monkeypatch) + message_file = tmp_path / "COMMIT_EDITMSG" + original_message = ( + "An original commit message\n\nIssue: GI-1234\n" + if issue_trailer + else "[GI-1234] An original commit message\n" + ) + message_file.write_text(original_message, encoding="utf-8") + + prepare_commit_msg(str(message_file), "commit", issue_trailer=issue_trailer) + + assert message_file.read_text(encoding="utf-8") == original_message + assert check_commit_message(str(message_file), issue_trailer=issue_trailer) == ( + True, + "", + ) + + @pytest.mark.parametrize("source", ["message", "commit", "merge"]) + @pytest.mark.parametrize("has_jira", [False, True]) + @pytest.mark.parametrize("issue_trailer", [False, True]) + def test_cherry_pick_message( + self, + tmp_path: Path, + monkeypatch, + source: str, + has_jira: bool, + issue_trailer: bool, + ): + git_dir = tmp_path / "alternate_git_dir" + git_dir.mkdir() + (git_dir / "HEAD").write_text("ref: refs/heads/GA-5678\n", encoding="utf-8") + (git_dir / "CHERRY_PICK_HEAD").write_text("abc123\n", encoding="utf-8") + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("GIT_DIR", str(git_dir)) + message_file = tmp_path / "COMMIT_EDITMSG" + original_message = "An original commit message\n" + if has_jira: + original_message = ( + f"{original_message}\nIssue: GI-1234\n" + if issue_trailer + else f"[GI-1234] {original_message}" + ) + message_file.write_text(original_message, encoding="utf-8") + + prepare_commit_msg(str(message_file), source, issue_trailer=issue_trailer) + + expected_message = original_message + if not has_jira: + expected_message = ( + f"{original_message}\nIssue: GA-5678\n" + if issue_trailer + else f"[GA-5678] {original_message}" + ) + assert message_file.read_text(encoding="utf-8") == expected_message + assert check_commit_message(str(message_file), issue_trailer=issue_trailer) == ( + True, + "", + ) + + @pytest.mark.parametrize("source", ["merge", "commit", "squash"]) + def test_non_replay_message_is_unchanged( + self, tmp_path: Path, monkeypatch, mock_get_branch_name, source: str + ): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("GIT_DIR", raising=False) + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + original_message = "[GI-1234] An original commit message\n" + message_file.write_text(original_message, encoding="utf-8") + args = ["git_message_hook", "--prepare", str(message_file), source] + if source == "commit": + args.append("HEAD") + monkeypatch.setattr(sys, "argv", args) + + git_message_hook_main() + + assert message_file.read_text(encoding="utf-8") == original_message + is_valid, error_message = check_commit_message(str(message_file)) + assert not is_valid + assert error_message.startswith("Different JIRA ID in commit message") + + def test_source_environment_variable_is_used( + self, tmp_path: Path, monkeypatch, mock_get_branch_name + ): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("GIT_DIR", raising=False) + monkeypatch.setenv("PRE_COMMIT_COMMIT_MSG_SOURCE", "commit") + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + original_message = "An original commit message\n" + message_file.write_text(original_message, encoding="utf-8") + + prepare_commit_msg(str(message_file)) + + assert message_file.read_text(encoding="utf-8") == original_message + + @pytest.mark.parametrize( + "operation", ["rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", None] + ) + @pytest.mark.parametrize("issue_trailer", [False, True]) + def test_missing_jira_is_only_allowed_during_rebase( + self, tmp_path: Path, monkeypatch, operation: str | None, issue_trailer: bool + ): + git_dir = tmp_path / ".git" + git_dir.mkdir() + (git_dir / "HEAD").write_text( + "ref: refs/heads/feature_branch\n", encoding="utf-8" + ) + if operation == "CHERRY_PICK_HEAD": + (git_dir / operation).write_text("abc123\n", encoding="utf-8") + elif operation: + (git_dir / operation).mkdir() + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("GIT_DIR", raising=False) + message_file = tmp_path / "COMMIT_EDITMSG" + original_message = "An original commit message\n" + message_file.write_text(original_message, encoding="utf-8") + + prepare_commit_msg( + str(message_file), "commit", "HEAD", issue_trailer=issue_trailer + ) + + assert message_file.read_text(encoding="utf-8") == original_message + is_valid, error_message = check_commit_message( + str(message_file), issue_trailer=issue_trailer + ) + if operation in ("rebase-merge", "rebase-apply"): + assert is_valid + assert error_message == "" + else: + assert not is_valid + assert error_message.startswith("Either the branch name") + + @pytest.mark.parametrize( + "operation", ["rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", None] + ) + @pytest.mark.parametrize("summary", ["123456789", "1234567890"]) + @pytest.mark.parametrize("issue_trailer", [False, True]) + def test_minimum_message_length_is_not_enforced_during_replay( + self, + tmp_path: Path, + monkeypatch, + operation: str | None, + summary: str, + issue_trailer: bool, + ): + git_dir = tmp_path / ".git" + git_dir.mkdir() + (git_dir / "HEAD").write_text("ref: refs/heads/GA-5678\n", encoding="utf-8") + if operation == "CHERRY_PICK_HEAD": + (git_dir / operation).write_text("abc123\n", encoding="utf-8") + elif operation: + (git_dir / operation).mkdir() + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("GIT_DIR", raising=False) + message_file = tmp_path / "COMMIT_EDITMSG" + message = ( + f"{summary}\n\nIssue: GA-5678\n" + if issue_trailer + else f"GA-5678 {summary}\n" + ) + message_file.write_text(message, encoding="utf-8") + + is_valid, error_message = check_commit_message( + str(message_file), issue_trailer=issue_trailer + ) + + if operation or len(summary) >= 10: + assert is_valid + assert error_message == "" + else: + assert not is_valid + assert error_message.startswith( + "First line of commit message must be at least" + ) + + +class TestIssueTrailers: + @pytest.fixture(autouse=True) + def isolate_git_dir(self, tmp_path: Path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("GIT_DIR", raising=False) + + @pytest.mark.parametrize( + "message, expected", + [ + ( + "A sufficiently long subject\n", + "A sufficiently long subject\n\nIssue: GA-5678\n", + ), + ( + "fixup! A sufficiently long subject\n\nSome body text.\n", + "fixup! A sufficiently long subject\n\nSome body text.\n\nIssue: GA-5678\n", + ), + ( + "A sufficiently long subject\n\nSigned-off-by: Example \n", + "A sufficiently long subject\n\n" + "Signed-off-by: Example \nIssue: GA-5678\n", + ), + ( + "A sufficiently long subject\n\n# Template instructions\n", + "A sufficiently long subject\n\nIssue: GA-5678\n# Template instructions\n", + ), + ( + "[GI-1234] A sufficiently long subject\n", + "[GI-1234] A sufficiently long subject\n\nIssue: GA-5678\n", + ), + ( + "A sufficiently long subject", + "A sufficiently long subject\n\nIssue: GA-5678\n", + ), + ( + "A sufficiently long subject\n\nIssue: GI-1234\n\nMore body text.\n", + "A sufficiently long subject\n\nIssue: GI-1234\n\n" + "More body text.\n\nIssue: GA-5678\n", + ), + ( + "A sufficiently long subject\n\n" + "Signed-off-by: Example \n" + " continuation\n\n# Template instructions\n", + "A sufficiently long subject\n\n" + "Signed-off-by: Example \n" + " continuation\nIssue: GA-5678\n# Template instructions\n", + ), + ( + "A sufficiently long subject\n\n---\nIssue: GI-1234\n", + "A sufficiently long subject\n\nIssue: GA-5678\n---\nIssue: GI-1234\n", + ), + ( + "A sufficiently long subject\n\n" + "# ------------------------ >8 ------------------------\n" + "Issue: GI-1234\n", + "A sufficiently long subject\n\nIssue: GA-5678\n" + "# ------------------------ >8 ------------------------\n" + "Issue: GI-1234\n", + ), + ], + ) + def test_prepare_adds_only_a_footer( + self, tmp_path: Path, mock_get_branch_name, message: str, expected: str + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + message_file.write_text(message, encoding="utf-8") + + prepare_commit_msg(str(message_file), issue_trailer=True) + prepare_commit_msg(str(message_file), issue_trailer=True) + + assert message_file.read_text(encoding="utf-8") == expected + + @pytest.mark.parametrize("value", ["GI-1234", "", "not-an-issue"]) + def test_prepare_preserves_existing_trailer( + self, tmp_path: Path, mock_get_branch_name, value: str + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + original_message = f"A sufficiently long subject\n\nIssue: {value}\n" + message_file.write_text(original_message, encoding="utf-8") + + prepare_commit_msg(str(message_file), issue_trailer=True) + + assert message_file.read_text(encoding="utf-8") == original_message + + @pytest.mark.parametrize( + "message, valid", + [ + ("A sufficiently long subject\n\nIssue: GA-5678\n", True), + ("\nA sufficiently long subject\n\nIssue: GA-5678\n", True), + ( + "# Template instructions\n\n" + "A sufficiently long subject\n\nIssue: GA-5678\n", + True, + ), + ("Issue: GA-5678\n", False), + ("# Template instructions\n\nIssue: GA-5678\n", False), + ("A sufficiently long subject\n\nissue: GA-5678\n", True), + ("A sufficiently long subject\n\nIssue: GA-5678\nIssue: GI-1234\n", True), + ("A sufficiently long subject\n\nIssue:\n GA-5678\n", True), + ( + "A sufficiently long subject\n\n" + "Issue: GA-5678\nSigned-off-by: Example \n", + True, + ), + ("[GA-5678] A sufficiently long subject\n", False), + ("A sufficiently long subject\n\nRefs: GA-5678\n", False), + ("A sufficiently long subject\n\n# Issue: GA-5678\n", False), + ("A sufficiently long subject\n\nIssue: GA-5678\n\nBody text.\n", False), + ("A sufficiently long subject\n\nIssue: not-an-issue\n", False), + ("A sufficiently long subject\n\nIssue:\n", False), + ("A sufficiently long subject\n\n---\nIssue: GA-5678\n", False), + ( + "A sufficiently long subject\n\n" + "# ------------------------ >8 ------------------------\n" + "Issue: GA-5678\n", + False, + ), + ("A sufficiently long subject\nIssue: GA-5678\n", False), + ], + ) + def test_check_uses_only_valid_issue_trailers( + self, tmp_path: Path, mock_get_branch_name, message: str, valid: bool + ): + mock_get_branch_name("feature_branch") + message_file = tmp_path / "COMMIT_EDITMSG" + message_file.write_text(message, encoding="utf-8") + + is_valid, error_message = check_commit_message( + str(message_file), issue_trailer=True + ) + + assert is_valid == valid + assert bool(error_message) != valid + + @pytest.mark.parametrize("operation", [None, "rebase-merge", "CHERRY_PICK_HEAD"]) + @pytest.mark.parametrize( + "trailers", ["Issue: GI-1234\n", "Issue: GA-5678\nIssue: GI-1234\n"] + ) + def test_mismatch_and_short_subject_during_replay( + self, tmp_path: Path, mock_get_branch_name, operation: str | None, trailers: str + ): + mock_get_branch_name("GA-5678") + git_dir = tmp_path / ".git" + git_dir.mkdir() + if operation == "CHERRY_PICK_HEAD": + (git_dir / operation).write_text("abc123\n", encoding="utf-8") + elif operation: + (git_dir / operation).mkdir() + message_file = tmp_path / "COMMIT_EDITMSG" + message_file.write_text(f"Short\n\n{trailers}", encoding="utf-8") + + is_valid, error_message = check_commit_message( + str(message_file), issue_trailer=True + ) + + if operation: + assert is_valid + assert error_message == "" + else: + assert not is_valid + assert "Different JIRA ID in Issue trailer GI-1234" in error_message + + @pytest.mark.parametrize("mode", ["--prepare", "--check"]) + def test_cli_option( + self, tmp_path: Path, monkeypatch, mock_get_branch_name, mode: str + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + message = "A sufficiently long subject\n" + if mode == "--check": + message += "\nIssue: GI-1234\n" + message_file.write_text(message, encoding="utf-8") + monkeypatch.setattr( + sys, + "argv", + ["git_message_hook", mode, "--issue-trailer", str(message_file)], + ) + + if mode == "--check": + with pytest.raises(SystemExit) as exc_info: + git_message_hook_main() + assert exc_info.value.code == 1 + else: + git_message_hook_main() + assert message_file.read_text(encoding="utf-8") == ( + "A sufficiently long subject\n\nIssue: GA-5678\n" + ) + + @pytest.mark.parametrize("message", ["", "# Template instructions\n"]) + def test_prepared_trailer_does_not_count_as_a_summary( + self, tmp_path: Path, mock_get_branch_name, message: str + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + message_file.write_text(message, encoding="utf-8") + + prepare_commit_msg(str(message_file), issue_trailer=True) + is_valid, error_message = check_commit_message( + str(message_file), issue_trailer=True + ) + + assert not is_valid + assert error_message.startswith("First line of commit message must be at least") + + def test_default_mode_does_not_use_issue_trailers( + self, tmp_path: Path, mock_get_branch_name + ): + mock_get_branch_name("feature_branch") + message_file = tmp_path / "COMMIT_EDITMSG" + message_file.write_text( + "A sufficiently long subject\n\nIssue: GA-5678\n", encoding="utf-8" + ) + + is_valid, error_message = check_commit_message(str(message_file)) + + assert not is_valid + assert error_message == ( + "Either the branch name or the commit message must start with a JIRA ID." + ) + + def test_trailer_preparation_and_check_do_not_start_subprocesses( + self, tmp_path: Path, mock_get_branch_name + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + message_file.write_text("A sufficiently long subject\n", encoding="utf-8") + + with mock.patch( + "subprocess.Popen", side_effect=AssertionError("Unexpected subprocess") + ): + prepare_commit_msg(str(message_file), issue_trailer=True) + assert check_commit_message(str(message_file), issue_trailer=True) == ( + True, + "", + ) + prepare_commit_msg(str(message_file), issue_trailer=True) + + assert message_file.read_text(encoding="utf-8") == ( + "A sufficiently long subject\n\nIssue: GA-5678\n" + ) + + +class TestBangPrefixes: + @pytest.fixture(autouse=True) + def isolate_git_dir(self, tmp_path: Path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("GIT_DIR", raising=False) + + @pytest.mark.parametrize("issue_trailer", [False, True]) + @pytest.mark.parametrize( + "prefix", ["fixup! ", "squash! ", "amend! ", "fixup! fixup! "] + ) + def test_preparation_preserves_autosquash_target( + self, tmp_path: Path, mock_get_branch_name, prefix: str, issue_trailer: bool + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + message = f"{prefix}Original target without a ticket\n" + message_file.write_text(message, encoding="utf-8") + + prepare_commit_msg(str(message_file), issue_trailer=issue_trailer) + + expected = f"{message}\nIssue: GA-5678\n" if issue_trailer else message + assert message_file.read_text(encoding="utf-8") == expected + + @pytest.mark.parametrize("issue_trailer", [False, True]) + @pytest.mark.parametrize( + "subject", + [ + "fixup! 1234abcd", + "squash! Short", + "amend! Short", + "fixup! fixup! Short", + ], + ) + def test_bang_targets_are_exempt_from_summary_length( + self, tmp_path: Path, mock_get_branch_name, subject: str, issue_trailer: bool + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + message = f"{subject}\n" + if issue_trailer: + message += "\nIssue: GA-5678\n" + message_file.write_text(message, encoding="utf-8") + + assert check_commit_message(str(message_file), issue_trailer=issue_trailer) == ( + True, + "", + ) + + @pytest.mark.parametrize("issue_trailer", [False, True]) + @pytest.mark.parametrize("branch", ["feature_branch", "GI-1234", "GA-5678"]) + def test_bang_prefix_does_not_bypass_jira_validation( + self, tmp_path: Path, mock_get_branch_name, branch: str, issue_trailer: bool + ): + mock_get_branch_name(branch) + message_file = tmp_path / "COMMIT_EDITMSG" + message = ( + "fixup! fixup! Short\n\nIssue: GI-1234\n" + if issue_trailer + else "fixup! fixup! [GI-1234] Short\n" + ) + message_file.write_text(message, encoding="utf-8") + + is_valid, error_message = check_commit_message( + str(message_file), issue_trailer=issue_trailer + ) + + if branch != "GA-5678": + assert is_valid + assert error_message == "" + else: + assert not is_valid + assert error_message.startswith("Different JIRA ID") + + @pytest.mark.parametrize("issue_trailer", [False, True]) + @pytest.mark.parametrize( + "subject", ["fixup! Merge another branch", "fixup! Original target"] + ) + def test_bang_still_requires_jira( + self, tmp_path: Path, mock_get_branch_name, issue_trailer: bool, subject: str + ): + mock_get_branch_name("feature_branch") + message_file = tmp_path / "COMMIT_EDITMSG" + message_file.write_text(f"{subject}\n", encoding="utf-8") + + is_valid, error_message = check_commit_message( + str(message_file), issue_trailer=issue_trailer + ) + + assert not is_valid + assert error_message.startswith("Either the branch name") + + @pytest.mark.parametrize("issue_trailer", [False, True]) + @pytest.mark.parametrize("subject", ["custom! X", "fixup!X", "Short"]) + def test_non_autosquash_subjects_still_require_minimum_length( + self, tmp_path: Path, mock_get_branch_name, subject: str, issue_trailer: bool + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + message = f"{subject}\n" + if issue_trailer: + message += "\nIssue: GA-5678\n" + message_file.write_text(message, encoding="utf-8") + + is_valid, error_message = check_commit_message( + str(message_file), issue_trailer=issue_trailer + ) + + assert not is_valid + assert error_message.startswith("First line of commit message must be at least") + + def test_leading_blank_and_comments_do_not_hide_bang( + self, tmp_path: Path, mock_get_branch_name + ): + mock_get_branch_name("GA-5678") + message_file = tmp_path / "COMMIT_EDITMSG" + message = "# Template comment\n\nfixup! Original target without a ticket\n" + message_file.write_text(message, encoding="utf-8") + + prepare_commit_msg(str(message_file)) + + assert message_file.read_text(encoding="utf-8") == message