Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git pre-commit hooks only for a specific subfolder?

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?

like image 302
somecoolguy Avatar asked Oct 14 '14 20:10

somecoolguy


People also ask

Can you commit pre-commit hooks?

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.

How do you bypass a pre-commit hook?

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.

Where do pre-commit hooks go?

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 .

How do I manually run a pre-commit hook?

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.


2 Answers

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/
like image 161
Tomasz Bartkowiak Avatar answered Sep 20 '22 23:09

Tomasz Bartkowiak


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
like image 40
marcusljx Avatar answered Sep 17 '22 23:09

marcusljx