Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
72 changes: 46 additions & 26 deletions docs/pre-push-hook.md
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
Expand All @@ -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.
26 changes: 26 additions & 0 deletions src/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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",
Expand All @@ -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)

Expand Down
71 changes: 71 additions & 0 deletions src/git.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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}."
46 changes: 46 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading