19

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?

4

4 回答 4

8

指定files包含(或exclude排除)特定目录,例如仅在以下位置运行挂钩my_dir

files: ^my_dir/
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    hooks:
        ...

或到处跑,但在里面my_dir

exclude: ^my_dir/
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    hooks:
        ...

如果您有很长的排除列表,请使用详细的正则表达式:

exclude: >
  (?x)^(
      path/to/file1.py|
      path/to/file2.py|
      path/to/file3.py
  )$

您也可以仅将这些应用于特定的钩子,只需执行以下操作:

-   id: my-hook
    exclude: ^my_dir/
于 2020-08-21T10:11:16.617 回答
2

您可以使用git log来确定子目录中的最新提交是否与存储库根目录中的最新提交匹配:

#!/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
于 2018-07-27T03:31:54.000 回答
0

Git 挂钩是 Git 在执行特定操作之前或之后运行的脚本。

如果您编写脚本并将其另存为,<repository_name>/.git/hooks/pre-commit那么 git 将在提交之前运行它。因此,为您正在使用的操作系统编写一个简单的脚本,针对该子文件夹运行 jshint 并将其保存到该路径。

Git 不会使用任何参数运行您的预提交挂钩。您可以使用 git 命令来确定存储库的状态(作为提交的一部分添加的更改仍然只是暂存并通过 --cached 访问)。如果您进行任何更改并希望它们成为提交的一部分,则需要在脚本退出之前添加它们。

您正在使用 C#,因此您应该知道 Windows 上的 git 挂钩有点古怪:在 Windows 上执行 Git 挂钩

于 2015-03-23T13:55:57.770 回答
0

如果您使用比 v1.1.0 更新的预提交,那么您可以将一个exclude字段添加到.pre-commit-config.yaml位于您的 repo 根文件夹中的字段。

就像下面这样:

exclude: '^(?!javascript/)'

在此处查看文档

于 2019-11-13T16:11:42.140 回答