I currently have a single repo with two projects, each in their own subfolder: one in C# and one in Javascript. I want to have a pre-commit hook that will run jshint but only if any of the staged files are in the Javascript folder If the staged files are only from the C# folder, then the pre-commit hook won't run.
Is it that possible at all? Or is my only solution to split the two projects into their own repos?
pre-commit hooks are a mechanism of the version control system git. They let you execute code right before the commit. Confusingly, there is also a Python package called pre-commit which allows you to create and use pre-commit hooks with a way simpler interface.
Use the --no-verify option to skip git commit hooks, e.g. git commit -m "commit message" --no-verify . When the --no-verify option is used, the pre-commit and commit-msg hooks are bypassed.
All git hooks are stored in the . git/hooks/ directory under your project root. A pre-commit hook is just an executable file stored in this folder with the magic name pre-commit . Note that some code editors make the .
If you want to manually run all pre-commit hooks on a repository, run pre-commit run --all-files . To run individual hooks use pre-commit run <hook_id> . The first time pre-commit runs on a file it will automatically download, install, and run the hook.
Specify files
to include (or exclude
to exclude) specific directories, e.g. run hooks only in my_dir
:
files: ^my_dir/
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
hooks:
...
or run everywhere but inside my_dir
:
exclude: ^my_dir/
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
hooks:
...
If you have a long list of exclusions, use verbose regex:
exclude: >
(?x)^(
path/to/file1.py|
path/to/file2.py|
path/to/file3.py
)$
you can also apply these to specific hooks only, just do:
- id: my-hook
exclude: ^my_dir/
You can use git log
to find out if the latest commit in a subdir matches the latest commit at your repository root:
#!/bin/env bash
function get_commit {
git log --oneline -- $1 | head -n 1 | cut -d " " -f1
}
ROOT_COMMIT=$(get_commit)
SUBDIR_COMMIT=$(get_commit my/subdir/path)
if [ "$SUBDIR_COMMIT" == "$ROOT_COMMIT" ]; then
# do pre-commit hook stuff here
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With