git.py

clew/guard/git.py

Git diff parsing for change detection.

_rev_parse_head

str | None clew.guard.git._rev_parse_head(RunCommand|None run_command)

Get the current HEAD commit SHA.

clew/guard/git.py:199

Source · 5 lines
def _rev_parse_head(run_command: RunCommand | None) -> str | None:
    result = run_git(["git", "rev-parse", "HEAD"], run_command)
    return result.strip() if result is not None else None

Activity · 2 steps
lines 200–200result = run_git(["git", "rev-parse", "HEAD"], run_command)lines 201–201return result.strip() if result is not None else None

Flows

get_branch_diff_range

str | None clew.guard.git.get_branch_diff_range(str target_branch="origin/main", RunCommand|None run_command=None)

Build a diff range string from merge-base to HEAD.

clew/guard/git.py:183

Source · 13 lines
def get_branch_diff_range(
    target_branch: str = "origin/main",
    run_command: RunCommand | None = None,
) -> str | None:
    base = get_merge_base(target_branch, run_command)
    if base is None:
        return None
    head = _rev_parse_head(run_command)
    if head and base == head:
        return None
    return f"{base}...HEAD"

Activity · 7 steps
lines 187–187base = get_merge_base(target_branch, run_command)lines 188–188◇ if base is Nonelines 189–189return Nonelines 190–190head = _rev_parse_head(run_command)lines 191–191◇ if head and base == headlines 192–192return Nonelines 193–193return f"{base}...HEAD"

Requirements

REQ-DDB-GUARD-023

Flows

get_changed_files

list[str] | None clew.guard.git.get_changed_files(str|None diff_range, bool staged, RunCommand|None run_command=None)

The files a revision range (or the index) changed.

clew/guard/git.py:113

Source · 13 lines
def get_changed_files(
    diff_range: str | None,
    staged: bool,
    run_command: RunCommand | None = None,
) -> list[str] | None:
    if diff_range and diff_range.startswith("-"):
        logger.error("Refusing diff range that looks like an option: %r", diff_range)
        return None
    cmd = ["git", "diff", "--name-only", *(["--cached"] if staged else [diff_range or "HEAD"])]
    out = run_git(cmd, run_command)
    return None if out is None else [line for line in out.splitlines() if line.strip()]

Activity · 6 steps
lines 118–118◇ if diff_range and diff_range.startswith("-")lines 119–119logger.error("Refusing diff range that looks like an option: %r", diff_range)lines 120–120return Nonelines 121–121cmd = ["git", "diff", "--name-only", *(["--cached"] if staged else [diff_range or "HEAD"])]lines 122–122out = run_git(cmd, run_command)lines 123–123return None if out is None else [line for line in out.splitlines() if line.strip()]

Requirements

REQ-DDB-GUARD-023

Flows

get_changed_lines_for_file

set[int] clew.guard.git.get_changed_lines_for_file(str file_path, RunCommand|None run_command=None)

Convenience function combining staged diff retrieval and parsing.

clew/guard/git.py:223

Source · 6 lines
def get_changed_lines_for_file(
    file_path: str,
    run_command: RunCommand | None = None,
) -> set[int]:
    diff_output = get_staged_diff(file_path, run_command)
    return parse_changed_lines(diff_output) if diff_output else set()

1 more lines, not shown

Activity · 2 steps
lines 227–227diff_output = get_staged_diff(file_path, run_command)lines 228–228return parse_changed_lines(diff_output) if diff_output else set()

Requirements

REQ-DDB-GUARD-023

get_diff

str | None clew.guard.git.get_diff(str file_path, str diff_range, RunCommand|None run_command=None)

Run git diff for a file over a given revision range.

clew/guard/git.py:96

Source · 12 lines
def get_diff(
    file_path: str,
    diff_range: str,
    run_command: RunCommand | None = None,
) -> str | None:
    if diff_range.startswith("-"):
        # git diff would parse this as an option; --output=<file> is an arbitrary write.
        logger.error("Refusing diff range that looks like an option: %r", diff_range)
        return None
    return run_git(["git", "diff", "-U0", diff_range, "--", file_path], run_command)

Activity · 4 steps
lines 101–101◇ if diff_range.startswith("-")lines 103–103logger.error("Refusing diff range that looks like an option: %r", diff_range)lines 104–104return Nonelines 105–105return run_git(["git", "diff", "-U0", diff_range, "--", file_path], run_command)

Requirements

REQ-DDB-GUARD-023

Flows

get_file_at_revision

str | None clew.guard.git.get_file_at_revision(str file_path, str revision="HEAD", RunCommand|None run_command=None)

Get a file's content as of a given revision.

clew/guard/git.py:211

Source · 8 lines
def get_file_at_revision(
    file_path: str,
    revision: str = "HEAD",
    run_command: RunCommand | None = None,
) -> str | None:
    return run_git(["git", "show", f"{revision}:./{file_path}"], run_command)

Activity · 1 steps
lines 216–216return run_git(["git", "show", f"{revision}:./{file_path}"], run_command)

Requirements

REQ-DDB-GUARD-023

Flows

get_merge_base

str | None clew.guard.git.get_merge_base(str target_branch="origin/main", RunCommand|None run_command=None)

Detect the merge-base between current HEAD and a target branch.

clew/guard/git.py:167

Source · 11 lines
def get_merge_base(
    target_branch: str = "origin/main",
    run_command: RunCommand | None = None,
) -> str | None:
    result = run_git(["git", "merge-base", target_branch, "HEAD"], run_command)
    if result is None:
        logger.warning("Could not determine merge-base against %s", target_branch)
        return None
    return result.strip()

Activity · 5 steps
lines 171–171result = run_git(["git", "merge-base", target_branch, "HEAD"], run_command)lines 172–172◇ if result is Nonelines 173–173logger.warning("Could not determine merge-base against %s", target_branch)lines 174–174return Nonelines 175–175return result.strip()

Requirements

REQ-DDB-GUARD-023

Flows

get_staged_diff

str | None clew.guard.git.get_staged_diff(str file_path, RunCommand|None run_command=None)

Run git diff cached for a single file.

clew/guard/git.py:85

Source · 7 lines
def get_staged_diff(
    file_path: str,
    run_command: RunCommand | None = None,
) -> str | None:
    return run_git(["git", "diff", "--cached", "-U0", "--", file_path], run_command)

Activity · 1 steps
lines 89–89return run_git(["git", "diff", "--cached", "-U0", "--", file_path], run_command)

Requirements

REQ-DDB-GUARD-023

Flows

git_add

bool clew.guard.git.git_add(str|list[str] paths, RunCommand|None run_command=None)

Stage files for the next git commit.

clew/guard/git.py:155

Source · 9 lines
def git_add(
    paths: str | list[str],
    run_command: RunCommand | None = None,
) -> bool:
    file_list = [paths] if isinstance(paths, str) else [str(p) for p in paths]
    # "--" so a path beginning with "-" cannot be parsed as an option.
    return run_git(["git", "add", "--", *file_list], run_command) is not None

Activity · 2 steps
lines 159–159file_list = [paths] if isinstance(paths, str) else [str(p) for p in paths]lines 161–161return run_git(["git", "add", "--", *file_list], run_command) is not None

Flows

parse_changed_lines

set[int] clew.guard.git.parse_changed_lines(str diff_output)

Extract the set of modified line numbers from a unified diff.

clew/guard/git.py:133

Source · 19 lines
def parse_changed_lines(diff_output: str) -> set[int]:
    changed: set[int] = set()
    hunk_re = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)

    for match in hunk_re.finditer(diff_output):
        start = int(match.group(1))
        count = int(match.group(2)) if match.group(2) else 1

        if count == 0:
            # Pure deletion — no new lines added
            continue

        # Convert to 0-indexed
        for line_num in range(start - 1, start - 1 + count):
            changed.add(line_num)

    return changed

Activity · 10 steps
lines 134–134changed: set[int] = set()lines 135–135hunk_re = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)lines 137–137◇ for match in hunk_re.finditer(diff_output)lines 138–138start = int(match.group(1))lines 139–139count = int(match.group(2)) if match.group(2) else 1lines 141–141◇ if count == 0lines 143–143continuelines 146–146◇ for line_num in range(start - 1, start - 1 + count)lines 147–147changed.add(line_num)lines 149–149return changed

Requirements

REQ-DDB-GUARD-023

Flows

run_git

str | None clew.guard.git.run_git(list[str] cmd, RunCommand|None run_command=None)

Run a git command through the injectable runner, returning None on failure.

clew/guard/git.py:60

Source · 21 lines
def run_git(cmd: list[str], run_command: RunCommand | None = None) -> str | None:
    runner = run_command or _default_run_command
    ## DISARMED HERE, AT THE ONE PLACE EVERY GATE GIT CALL PASSES THROUGH (1.1.0 audit, C1 —
    ## second half). A repository's own `.git/config` can name a command git then RUNS
    ## (`core.fsmonitor` on a diff, and its siblings), so a bare `["git", …]` argv is
    ## execution chosen by the tree being inspected. The gate is the worse context for that
    ## than the pipeline: it runs as the committing developer, on whatever branch they have
    ## checked out to review, before any of their own code runs.
    ##
    ## The call sites keep their readable literal lists and this rewrites them, rather than
    ## fourteen call sites each remembering a helper. An injected `run_command` gets the
    ## disarmed argv too, so a test double cannot observe an argv the real runner would not
    ## receive.
    disarmed = git_argv(*cmd[1:]) if cmd and cmd[0] == "git" else cmd
    try:
        return runner(disarmed)
    except GIT_ERRORS as e:
        logger.warning("git %s failed: %s", " ".join(cmd[1:3]), e)
        return None

Activity · 7 steps
lines 61–61runner = run_command or _default_run_commandlines 73–73disarmed = git_argv(*cmd[1:]) if cmd and cmd[0] == "git" else cmdlines 74–74trylines 75–75return runner(disarmed)lines 76–76except GIT_ERRORS as elines 77–77logger.warning("git %s failed: %s", " ".join(cmd[1:3]), e)lines 78–78return None

Requirements

REQ-DDB-GUARD-023

Flows