Skip to main content

Write pretty and concise Git hooks in Python.

Project description

❤️ Made by human

GitHooks

Write pretty and concise Git hooks in Python. GitHooks lets you write an entire Git hook directly in Python, without using YAML. It’s ideal when you want full control and all your logic contained in a single file.

Installing

You can install via pip:

pip install githooks

Old version

GitHooks was previously named SimpleGitHooks, you can install latest old version by command pip install simplegithooks but it's recommended to use the latest githooks.

Hooks

PreCommit

Write simple pre-commit Git hook in your .git/hooks/pre-commit:

#!/usr/bin/env python
from githooks import PreCommit

pre_commit = PreCommit(__file__)
pre_commit.add_ignored_file("src/githooks/pre-commit.py")
pre_commit.check_content_for("FIXME", "❌", "error")
pre_commit.check_content_for("NotImplemented", "🚧", "fail")
pre_commit.check_content_for("TODO", "⚠️", "warning", prevent=False)
pre_commit.check_command("ruff check")
print(pre_commit.results())
print(pre_commit.summary())
exit(pre_commit.rc)

Let's say you have such file in staged changes main_1.py because you've forgot to finish:

import math

def add(b, c):
    # TODO add typing
    return b + c

def divide(a, b):
    # FIXME secure dividing by zero
    return a / b

def sqrt():
    raise NotImplementedError

And when you try to commit this file using git commit -m "message" the output will be:

output_main_1a.png

What happened here? Let's focus only on checks that prevents us from commit this change:

  • by default all checks prevents commit, unless you explicitly pass prevent=False
  • check_content_for("FIXME", "❌", "error") failed because FIXME was found in main_1.py
  • check_content_for("NotImplemented", "🚧", "fail") failed because NotImplemented was found in main_1.py
  • check_command("ruff check") failed because command ruff check returned non-zero output (because of unused import math)

Then if you fix issues the code now looks more on less like this:

import math

def add(b, c):
    # TODO add typing
    return b + c

def divide(a, b):
    try:
        return a / b
    except Exception:
        return float("inf")

def sqrt(x):
    return math.sqrt(x)

The output after commit will be:

output_main_1b.png

Now check_content_for("TODO", "⚠️", "warning", prevent=False) failed because TODO was found in main_1.py, yet this is not preventing us from commit changes, so commit command was succeeded but with warning Commit allowed conditionally.

Still we can do better 😉, so let's try harder:

import math
from typing import Any

def add(b:Any, c:Any):
    return b + c

def divide(a, b):
    try:
        return a / b
    except Exception:
        return float("inf")

def sqrt(x):
    return math.sqrt(x)

Finally we reached our goal:

output_main_1c.png

PrePush

Write simple pre-push Git hook in your .git/hooks/pre-push:

#!/usr/bin/env python
import sys

from githooks import GitHook, PrePushConfig

pre_push = GitHook(__file__, PrePushConfig())
pre_push.add_ignored_files(["pre_push_example.py", "*.svg", "README.md"])
pre_push.check_command("rm -rf build/")
pre_push.check_command("rm -rf dist/")
pre_push.check_command("pytest")
print(pre_push.results())
print(pre_push.summary())
sys.exit(pre_push.rc)

You'll get similar outputs like for pre-commit.

Common config

add_ignored_files for ignoring files

pre_commit.add_ignored_file("src/obsolete.py")
pre_commit.add_ignored_files(["src/stub1.py", "src/stub2.py"])

Support for Python's pathlib.Path pattern matching

pre_commit.add_ignored_files(["pre-commit.py", "*.svg", "README.md"])

check_content_for search for lines in files that match substring

pre_commit.check_content_for("FIXME", "❌", "error")
pre_commit.check_content_for("NotImplemented", "🚧", "fail")
pre_commit.check_content_for("TODO", "⚠️", "warning", prevent=False)

check_command for checking commands execution

pre_commit.check_command("ruff check . --fix --diff", prevent=False)
pre_commit.check_command("ruff check . --fix --show-fixes")
pre_commit.check_command("ruff format .")
pre_commit.check_command("echo false && false", irrelevant=True)

Check commands which RC=0 means failure

pre_commit.check_command("true", rc_zero_succes=False)  # ❯ true (ERROR, RC!=0 SUCCESS) 🔒
pre_commit.check_command("false", rc_zero_succes=False) # ❯ false (OK, RC!=0 SUCCESS)

outputs for table-formatted color-aware outputs when using check_command

pre_commit.check_command("ruff check . --fix --diff", prevent=False)
print(pre_commit.outputs())

Example of an output:

┌─────────────────────────────────┐
│ ruff check . --fix --show-fixes │
├─────────────────────────────────┤
│ All checks passed!              │
└─────────────────────────────────┘

results for all or filtered results

All results:

print(pre_commit.results())

Filtered results:

print(pre_commit.results("error"))
print(pre_commit.results("warning"))
print(pre_commit.results("error", preventing_only=True))
print(pre_commit.results("warning", preventing_only=True))

Example of results:

Results:
  ❌ FIXME not found
  🚧 NotImplemented not found
  ⚠️ TODO not found
  ❯ ruff check . --fix --diff (OK)
  ❯ ruff check . --fix --show-fixes (OK)
  ❯ ruff format . (OK)
  ❯ mypy --explicit-package-bases --ignore-missing-imports . (OK)
  ❯ echo false && false (ERROR, irrelevant=True)
  ❯ cd . && pytest (OK)

summary for quick summary

print(pre_commit.summary())

Example of a summary:

Summary:
  (nothing prevents from proceeding)

rc for the return code of the git hook

This will finish git hook script withe the git hook result:

sys.exit(pre_commit.rc)

Possible outputs are:

🟢 Commit clean.
🟡 Commit allowed (caution).
🔴 Commit aborted.

Creating a symlink

Run githooks pre-commit --install path/to/pre_commit.py or githooks pre-push --install path/to/pre_push.py to create a symlink for you repository:

output_create_symlink.png

If a hook file already exists, an additional message e.g. WARNING: file '/home/user/project/.git/hooks/pre-commit' already exists and will be overwritten. will be shown as below:

output_create_symlink.png

Auto confirmation

Pass -y or --yes or --assume-yes to skip confirmation with typing CREATE_SYMBOLIC_LINK. You will still get final result and warning if file or symbolic link already exists.

Troubleshooting

If you pass a bad hook name you'll receive a hint if there is a typo e.g. Unknown or unsupported hook: preccomyt, did you mean: pre-commit.

In case of any problem while creating a symlink you'll get Failure, couldn't create the symbolic link. instead of success message.

Changelog

See Changelog.

License

This repository is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

githooks-1.2.4.tar.gz (14.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

githooks-1.2.4-py3-none-any.whl (13.2 kB view details)

Uploaded Python 3

File details

Details for the file githooks-1.2.4.tar.gz.

File metadata

  • Download URL: githooks-1.2.4.tar.gz
  • Upload date:
  • Size: 14.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.22 {"installer":{"name":"uv","version":"0.9.22","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for githooks-1.2.4.tar.gz
Algorithm Hash digest
SHA256 2deaf3629d541b1e9acf97d6e4cda9a18d958830d563932de8a8dfdc1425027f
MD5 b46d60247e241257e34ea455a960e149
BLAKE2b-256 5bffad3d422030dca3266b76e792312d6aa067f8565a3740965cdaebaf59a592

See more details on using hashes here.

File details

Details for the file githooks-1.2.4-py3-none-any.whl.

File metadata

  • Download URL: githooks-1.2.4-py3-none-any.whl
  • Upload date:
  • Size: 13.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.22 {"installer":{"name":"uv","version":"0.9.22","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for githooks-1.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 86ccb106c71d2d052f7b9f03643f418ccdc220a6c4b2b97c46c89d888ec3b5f5
MD5 082d158fd4b39f14c4058e88adbdc0f4
BLAKE2b-256 bb2a3e2da080ac5d45d09bd8503d749e3ce61251e319396cab29876f3c9568b2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page