From 605853e61c99f930cefe1b818aa193f32663d256 Mon Sep 17 00:00:00 2001 From: Muhammad Ali Siddiqui Date: Sun, 20 Sep 2026 10:00:46 +0500 Subject: [PATCH 1/2] feat: add pre-push hook commands --- src/cli.py | 26 ++++++ src/git.py | 71 +++++++++++++++ tests/test_cli.py | 46 ++++++++++ tests/test_git.py | 223 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 366 insertions(+) diff --git a/src/cli.py b/src/cli.py index 434e0e0..03ea04a 100644 --- a/src/cli.py +++ b/src/cli.py @@ -3,6 +3,7 @@ from importlib.metadata import version from checks import CheckStatus, run_checks +from git import install_pre_push_hook, uninstall_pre_push_hook from output import display_results @@ -11,6 +12,13 @@ def main() -> int: description="Check whether your Git branch is ready before pushing or opening a PR." ) + parser.add_argument( + "command", + nargs="?", + choices=["install-hook", "uninstall-hook"], + help="Install or uninstall the BeforePush pre-push hook.", + ) + parser.add_argument( "--target", default="main", @@ -25,6 +33,24 @@ def main() -> int: args = parser.parse_args() + if args.command == "install-hook": + try: + print(install_pre_push_hook()) + except RuntimeError as error: + print(f"Error: {error}", file=sys.stderr) + return 1 + + return 0 + + if args.command == "uninstall-hook": + try: + print(uninstall_pre_push_hook()) + except RuntimeError as error: + print(f"Error: {error}", file=sys.stderr) + return 1 + + return 0 + results = run_checks(args.target) display_results(results, args.target) diff --git a/src/git.py b/src/git.py index f7c88ed..b98f67b 100644 --- a/src/git.py +++ b/src/git.py @@ -1,4 +1,13 @@ import subprocess +from pathlib import Path + +BEFOREPUSH_HOOK_MARKER = "# Installed by BeforePush" + +BEFOREPUSH_HOOK_CONTENT = """#!/bin/sh +# Installed by BeforePush +beforepush +exit $? +""" def run_git_command(*args: str) -> str: @@ -28,6 +37,19 @@ def is_git_repository() -> bool: return result.returncode == 0 and result.stdout.strip() == "true" +def get_git_dir() -> Path: + """Return the path to the repository's Git directory.""" + try: + return Path(run_git_command("rev-parse", "--git-dir")).resolve() + except RuntimeError: + raise RuntimeError("Not inside a Git repository.") from None + + +def get_hooks_dir() -> Path: + """Return the repository's configured Git hooks directory.""" + return Path(run_git_command("rev-parse", "--git-path", "hooks")).resolve() + + def get_current_branch() -> str: """Get the current branch name.""" return run_git_command("branch", "--show-current") @@ -73,3 +95,52 @@ def branch_exists(name: str) -> bool: check=False, ) return result.returncode == 0 + + +def is_beforepush_hook(hook_path: Path) -> bool: + """Return whether the hook was installed by BeforePush.""" + if not hook_path.is_file(): + return False + + return BEFOREPUSH_HOOK_MARKER in hook_path.read_text(encoding="utf-8") + + +def install_pre_push_hook() -> str: + """Install the BeforePush pre-push hook.""" + hooks_dir = get_hooks_dir() + hooks_dir.mkdir(parents=True, exist_ok=True) + + hook_path = hooks_dir / "pre-push" + + if hook_path.exists(): + if is_beforepush_hook(hook_path): + return "BeforePush pre-push hook is already installed." + + return ( + f"An existing pre-push hook was found at {hook_path}. No changes were made." + ) + + hook_path.write_text(BEFOREPUSH_HOOK_CONTENT, encoding="utf-8") + + # Make the hook executable without changing unrelated permission bits. + hook_path.chmod(hook_path.stat().st_mode | 0o111) + + return f"BeforePush pre-push hook installed at {hook_path}." + + +def uninstall_pre_push_hook() -> str: + """Remove the BeforePush pre-push hook if installed.""" + hooks_dir = get_hooks_dir() + hook_path = hooks_dir / "pre-push" + + if not hook_path.exists(): + return "BeforePush pre-push hook is not installed." + + if not is_beforepush_hook(hook_path): + return ( + f"An existing pre-push hook was found at {hook_path}. It was not removed." + ) + + hook_path.unlink() + + return f"BeforePush pre-push hook removed from {hook_path}." diff --git a/tests/test_cli.py b/tests/test_cli.py index c348dac..4e089d3 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -166,3 +166,49 @@ def test_cli_version(capsys, monkeypatch): assert exc_info.value.code == 0 assert capsys.readouterr().out.strip() == (f"beforepush {version('before-push')}") + + +def test_cli_install_hook(monkeypatch, capsys): + monkeypatch.setattr( + cli, + "install_pre_push_hook", + lambda: "BeforePush pre-push hook installed.", + ) + monkeypatch.setattr( + "sys.argv", + ["beforepush", "install-hook"], + ) + + assert cli.main() == 0 + assert "installed" in capsys.readouterr().out.lower() + + +def test_cli_uninstall_hook(monkeypatch, capsys): + monkeypatch.setattr( + cli, + "uninstall_pre_push_hook", + lambda: "BeforePush pre-push hook removed.", + ) + monkeypatch.setattr( + "sys.argv", + ["beforepush", "uninstall-hook"], + ) + + assert cli.main() == 0 + assert "removed" in capsys.readouterr().out.lower() + + +def test_cli_install_hook_error(monkeypatch, capsys): + def fail_install(): + raise RuntimeError("Not inside a Git repository.") + + monkeypatch.setattr(cli, "install_pre_push_hook", fail_install) + monkeypatch.setattr( + "sys.argv", + ["beforepush", "install-hook"], + ) + + assert cli.main() == 1 + + error = capsys.readouterr().err + assert "Not inside a Git repository." in error diff --git a/tests/test_git.py b/tests/test_git.py index 6bf6272..9aefc6b 100644 --- a/tests/test_git.py +++ b/tests/test_git.py @@ -1,3 +1,5 @@ +import os +import shutil import subprocess import pytest @@ -150,3 +152,224 @@ def fake_run(*args, **kwargs): monkeypatch.setattr(subprocess, "run", fake_run) assert git.branch_exists("develop") is False + + +def test_get_git_dir(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + monkeypatch.chdir(tmp_path) + + assert git.get_git_dir() == (tmp_path / ".git").resolve() + + +def test_get_hooks_dir(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + monkeypatch.chdir(tmp_path) + + assert git.get_hooks_dir() == (tmp_path / ".git" / "hooks").resolve() + + +def test_get_hooks_dir_from_subdirectory(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + subdirectory = tmp_path / "src" / "app" + subdirectory.mkdir(parents=True) + + monkeypatch.chdir(subdirectory) + + assert git.get_git_dir() == (tmp_path / ".git").resolve() + assert git.get_hooks_dir() == (tmp_path / ".git" / "hooks").resolve() + + +def test_get_git_dir_outside_repository(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + + with pytest.raises(RuntimeError, match="Not inside a Git repository."): + git.get_git_dir() + + +def test_is_beforepush_hook(tmp_path): + hook = tmp_path / "pre-push" + + hook.write_text( + "#!/bin/sh\n# Installed by BeforePush\nbeforepush\nexit $?\n", + encoding="utf-8", + ) + + assert git.is_beforepush_hook(hook) + + +def test_is_not_beforepush_hook(tmp_path): + hook = tmp_path / "pre-push" + + hook.write_text( + "#!/bin/sh\nsome-other-tool\n", + encoding="utf-8", + ) + + assert not git.is_beforepush_hook(hook) + + +def test_install_pre_push_hook(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + monkeypatch.chdir(tmp_path) + + message = git.install_pre_push_hook() + + hook_path = tmp_path / ".git" / "hooks" / "pre-push" + + assert hook_path.exists() + assert git.is_beforepush_hook(hook_path) + assert "beforepush" in hook_path.read_text(encoding="utf-8") + assert "Installed by BeforePush" in hook_path.read_text(encoding="utf-8") + assert "installed" in message.lower() + + +def test_install_pre_push_hook_is_idempotent(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + monkeypatch.chdir(tmp_path) + + git.install_pre_push_hook() + + hook_path = tmp_path / ".git" / "hooks" / "pre-push" + original_content = hook_path.read_text(encoding="utf-8") + + message = git.install_pre_push_hook() + + assert hook_path.read_text(encoding="utf-8") == original_content + assert "already installed" in message.lower() + + +def test_uninstall_pre_push_hook(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + monkeypatch.chdir(tmp_path) + + git.install_pre_push_hook() + + hook_path = tmp_path / ".git" / "hooks" / "pre-push" + assert hook_path.exists() + + message = git.uninstall_pre_push_hook() + + assert not hook_path.exists() + assert "removed" in message.lower() + + +def test_uninstall_pre_push_hook_when_not_installed(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + monkeypatch.chdir(tmp_path) + + message = git.uninstall_pre_push_hook() + + assert "not installed" in message.lower() + + +def test_uninstall_pre_push_hook_does_not_remove_existing_hook(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + hook_path = tmp_path / ".git" / "hooks" / "pre-push" + existing_content = "#!/bin/sh\nsome-other-hook\n" + hook_path.write_text(existing_content, encoding="utf-8") + + monkeypatch.chdir(tmp_path) + + message = git.uninstall_pre_push_hook() + + assert hook_path.exists() + assert hook_path.read_text(encoding="utf-8") == existing_content + assert "not removed" in message.lower() + + +@pytest.mark.skipif(shutil.which("sh") is None, reason="sh is required") +def test_installed_hook_propagates_beforepush_exit_code(tmp_path, monkeypatch): + subprocess.run( + ["git", "init"], + cwd=tmp_path, + check=True, + capture_output=True, + text=True, + ) + + monkeypatch.chdir(tmp_path) + + git.install_pre_push_hook() + + hook_path = tmp_path / ".git" / "hooks" / "pre-push" + + fake_bin = tmp_path / "bin" + fake_bin.mkdir() + + fake_beforepush = fake_bin / "beforepush" + fake_beforepush.write_text( + "#!/bin/sh\nexit 7\n", + encoding="utf-8", + ) + fake_beforepush.chmod(fake_beforepush.stat().st_mode | 0o111) + + monkeypatch.setenv( + "PATH", + f"{fake_bin}{os.pathsep}{os.environ['PATH']}", + ) + + result = subprocess.run( + ["sh", str(hook_path)], + cwd=tmp_path, + check=False, + capture_output=True, + text=True, + ) + + assert result.returncode == 7 From 674f5ec9212f4c19aa17ba477f77f8269056aea1 Mon Sep 17 00:00:00 2001 From: Muhammad Ali Siddiqui Date: Sun, 20 Sep 2026 16:04:17 +0500 Subject: [PATCH 2/2] docs: document pre-push hook commands --- README.md | 1 + docs/pre-push-hook.md | 72 +++++++++++++++++++++++++++---------------- 2 files changed, 47 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 395cced..90e3ee9 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ A lightweight CLI that checks whether your Git branch is ready before pushing or * Detect uncommitted or untracked changes * Check upstream branch configuration * Check if the current branch is behind a target branch +* Run checks automatically before git push with a pre-push hook * Support custom target branches * Clean terminal output with Rich diff --git a/docs/pre-push-hook.md b/docs/pre-push-hook.md index be56bc6..11a7141 100644 --- a/docs/pre-push-hook.md +++ b/docs/pre-push-hook.md @@ -1,6 +1,8 @@ # Git Pre-push Hook -You can configure BeforePush to run automatically before `git push`. This allows you to check your branch before every push without running `beforepush` manually. +BeforePush can run automatically before `git push` using a Git `pre-push` hook. + +Instead of running `beforepush` manually before every push, you can let BeforePush manage the hook for you. ## How It Works @@ -10,49 +12,59 @@ When you run: git push ``` -Git runs the `pre-push` hook first. +Git runs the `pre-push` hook before the push. -The hook runs: +The BeforePush hook runs: ```bash beforepush ``` -If BeforePush exits with a non-zero status because a check fails, the push is blocked. +If BeforePush exits with a non-zero status because a check fails, the hook returns that status and Git stops the push. -## Setup +If all checks pass, the push continues normally. -From the root of your Git repository, create a file named: +## Install the Hook -```text -.git/hooks/pre-push -``` +From inside a Git repository, run: -Add: +```bash +beforepush install-hook +``` -```sh -#!/bin/sh +BeforePush creates the repository's `pre-push` hook and configures it to run BeforePush automatically. -beforepush -status=$? +After installation, you can use: -if [ $status -ne 0 ]; then - echo "BeforePush checks failed. Push aborted." - exit $status -fi +```bash +git push ``` -On macOS and Linux, make the hook executable: +and BeforePush will run automatically. + +Installing the hook again is safe. If the BeforePush hook is already installed, no changes are made. + +## Uninstall the Hook + +To remove a pre-push hook installed by BeforePush, run: ```bash -chmod +x .git/hooks/pre-push +beforepush uninstall-hook ``` -The hook is now active. +If BeforePush did not install the existing hook, it will not remove it. + +## Existing Hooks + +BeforePush does not overwrite an existing `pre-push` hook that it did not install. + +If a `pre-push` hook already exists, `beforepush install-hook` leaves it unchanged and reports that an existing hook was found. + +This prevents BeforePush from accidentally replacing hooks managed by another tool or created manually. ## Test the Hook -Make a change in your repository and run: +After installing the hook, make a change in your repository and run: ```bash git push @@ -66,16 +78,24 @@ If a check fails, the push is stopped. ## Bypass the Hook -If you need to push without running the pre-push hook, use: +If you intentionally need to push without running the `pre-push` hook, use: ```bash git push --no-verify ``` -Use this only when you intentionally want to bypass the checks. +This bypasses Git's pre-push hook for that push. ## Notes -Git hooks are local to your repository and are not included when you push the repository to GitHub. Each user who wants to use the hook needs to configure it locally. +Git hooks are local to each repository and are not included when the repository is pushed to GitHub. Each user who wants to use the BeforePush hook must install it locally. + +The `beforepush` command must be installed and available in the user's `PATH` when Git runs the hook. + +For example: + +```bash +beforepush --version +``` -The `beforepush` command must be installed and available in the user's `PATH`. +can be used to verify that the command is available.