gitenv.py

clew/gitenv.py

The environment a `git` subprocess must NOT inherit.

_no_ext_diff

list[str] clew.gitenv._no_ext_diff(list[str] args)

Insert --no-ext-diff after a diff-family subcommand.

clew/gitenv.py:123

Show on the map →

Called by git_argv

Calls none

Source · 18 lines
def _no_ext_diff(args: list[str]) -> list[str]:
    """`-c diff.external=` ALONE BREAKS DIFF: git runs the empty string as the program (found
    dogfooding, round 3 P6c — every `git diff` here failed and the impact report read `[]`).
    `--no-ext-diff` forbids external diffs and drivers whatever the config says, so the empty
    key stays as defence in depth and the command works. Global options before the subcommand
    (`-C dir`, `-c k=v`) are skipped to find it.

    @brief Disable external diffs for diff-family commands.
    @return Arguments.
    """
    i = 0
    while i < len(args) and args[i].startswith("-"):
        i += 2 if args[i] in ("-C", "-c") else 1
    if i < len(args) and args[i] in _EXT_DIFF_COMMANDS:
        return [*args[: i + 1], "--no-ext-diff", *args[i + 1 :]]
    return args

Activity · 6 steps
lines 133–133i = 0lines 134–134◇ while i < len(args) and args[i].startswith("-")lines 135–135i += 2 if args[i] in ("-C", "-c") else 1lines 136–136◇ if i < len(args) and args[i] in _EXT_DIFF_COMMANDSlines 137–137return [*args[: i + 1], "--no-ext-diff", *args[i + 1 :]]lines 138–138return args

Requirements

REQ-DDB-CONFIG-001

Flows

git_argv

list[str] clew.gitenv.git_argv(*str args)

One git argv with every command-valued configuration key disarmed.

clew/gitenv.py:94

Source · 20 lines
def git_argv(*args: str) -> list[str]:
    """THE SINGLE PLACE THE RULE LIVES, so a new git call site inherits the defence instead of
    having to remember it — `tests/test_security_surface.py` asserts no site builds its own.
    `core.hooksPath=/dev/null` rather than empty, because an empty value makes git fall back to
    the repository's own hooks directory; the rest disarm by emptying.

    This is the ARGV half of the pair `git_env()` completes: `git_env` removes the overrides a
    hook EXPORTS, and this removes the commands a tree's own config FILE supplies. Neither
    substitutes for the other, and a call site needs both.

    @brief Build a git argv that cannot run commands from the inspected tree's config.
    @return The argv, ready for subprocess.
    """
    disarmed: list[str] = ["git"]
    for key in GIT_COMMAND_VALUED_KEYS:
        disarmed.extend(["-c", f"{key}=/dev/null" if key == "core.hooksPath" else f"{key}="])
    disarmed.extend(_no_ext_diff(list(args)))
    return disarmed

Activity · 5 steps
lines 107–107disarmed: list[str] = ["git"]lines 108–108◇ for key in GIT_COMMAND_VALUED_KEYSlines 109–109disarmed.extend(["-c", f"{key}=/dev/null" if key == "core.hooksPath" else f"{key}="])lines 110–110disarmed.extend(_no_ext_diff(list(args)))lines 111–111return disarmed

Requirements

REQ-DDB-CONFIG-001

Flows

git_env

dict[str, str] clew.gitenv.git_env()

The current environment with git's hook-repository overrides removed.

clew/gitenv.py:145

Source · 17 lines
def git_env() -> dict[str, str]:
    """A COPY, never a mutation of `os.environ`. This package runs inside a host process —
    a pre-commit hook, an MCP server, a test session — and clearing the variables globally
    would change how the HOST's own git commands behave, which is a far larger blast radius
    than the bug being fixed.

    Returns the full environment minus the overrides, rather than a minimal one: `PATH`,
    `HOME` and the git config variables all matter to the commands being run, and a
    hand-built environment would have to guess at them.

    @brief Build a git-safe subprocess environment.
    @return The environment without the hook overrides.
    @version 1
    """
    return {k: v for k, v in os.environ.items() if k not in GIT_HOOK_VARS}

Activity · 1 steps
lines 159–159return {k: v for k, v in os.environ.items() if k not in GIT_HOOK_VARS}

Requirements

REQ-DDB-CONFIG-001

Flows

is_work_tree_root

bool clew.gitenv.is_work_tree_root(Path path)

Whether a directory is the root of a git work tree, asked of git itself.

clew/gitenv.py:167

Source · 29 lines
def is_work_tree_root(path: Path) -> bool:
    """A `.git` DIRECTORY TEST REFUSED EVERY LINKED WORKTREE (agent C's W10): `git worktree add`
    writes `.git` as a FILE pointing at the main repository. The filesystem cannot tell that file
    from a planted one-byte `.git`, and a planted one must never make a directory indexable — so
    git is asked. A planted file is not a valid gitdir, and git says so.

    @brief Work-tree root check.
    @return Bool.
    """
    import subprocess

    directory = Path(path)
    if not directory.is_dir():
        return False
    try:
        result = subprocess.run(
            git_argv("rev-parse", "--show-toplevel"),
            cwd=directory,
            env=git_env(),
            capture_output=True,
            text=True,
            timeout=10,
            check=False,
        )
    except (OSError, subprocess.TimeoutExpired) as exc:
        logger.warning("is_work_tree_root: git could not answer for %s (%s)", directory, exc)
        return False
    top = result.stdout.strip()
    return result.returncode == 0 and bool(top) and Path(top).resolve() == directory.resolve()

1 more lines, not shown

Activity · 11 steps
lines 176–176import subprocesslines 178–178directory = Path(path)lines 179–179◇ if not directory.is_dir()lines 180–180return Falselines 181–181trylines 182–190result = subprocess.run( git_argv("rev-parse", "--show-toplevel"), cwd=directory, env=git_env(), capture_output=True, text=True, timeout=10, check=False, )lines 191–191except (OSError, subprocess.TimeoutExpired) as exclines 192–192logger.warning("is_work_tree_root: git could not answer for %s (%s)", directory, exc)lines 193–193return Falselines 194–194top = result.stdout.strip()lines 195–195return result.returncode == 0 and bool(top) and Path(top).resolve() == directory.resolve()

Requirements

REQ-DDB-CONFIG-001