【问题标题】:Find path to git hooks directory on the shell在 shell 上找到 git hooks 目录的路径
【发布时间】:2012-12-13 22:16:18
【问题描述】:

如何找到当前 Git 存储库的 .git/hooks 目录的完整路径?


我看到以下问题:

深入目录结构

我可能在 git 存储库目录结构的任何深处,例如

/home/user/project/.git/hooks

我在文件夹中

/home/user/project/foo/bar/baz/

子模块

较新的 git 版本将子模块元数据不放入 .git/ 而是放在主存储库中,.git 只是一个文件,例如

$ cat /home/user/project/vendor/foo/.git
gitdir: ../../.git/modules/vendor/foo

所以在这种情况下,钩子目录在

/home/user/project/.git/modules/vendor/foo/hooks

【问题讨论】:

  • 至少对于父 repo(对于子模块还不确定),确保使用 git 2.9(2016 年 6 月)或更高版本检查 git config core.hooksPath。见my answer below

标签: git


【解决方案1】:

您可以使用git rev-parse --git-dir 获取用于当前目录的存储库的路径。这将处理 gitlinks(使用文件代替 .git 目录)以及使用 $GIT_DIR 环境变量。 hooks 目录将始终在其中,因此您可以使用:

`git rev-parse --git-dir`/hooks

获取 hooks 目录的路径。

这在git rev-parse manpage中有记录

【讨论】:

  • 这个可以和git submodule foreach一起使用吗?例如,git submodule foreach cp .git/hooks/commit-msg $(git rev-parse --git-dir)/hooks 之类的东西?我看到的问题是,由于 shell 首先扩展了 git rev-parse,它评估为超级项目的 git-dir。
  • @WoodrowBarlow 可能会更好地作为一个新问题而不是评论来解决,因为这里的 cmets 在长度和格式化能力方面非常有限。但是您是否尝试过在foreach 之后的所有内容周围加上单引号?这应该会根据需要延迟评估。
  • 有效(尽管我也遇到了不同的问题)!谢谢。
  • 这已经不正确了,使用git rev-parse --git-path hooks/hook-name来查找hook的存储位置。
【解决方案2】:

除了--git-dir,你还可以使用下面的方法来查找git仓库的根目录,因为这个比较通用,我只是添加到这里来完成:

echo $(git rev-parse --show-toplevel)

然后将/.git/hooks 附加到它?不过,我还没有尝试过使用子模块。

【讨论】:

  • 这对子模块没有帮助。
【解决方案3】:

从 git 2.9(2016 年 6 月)开始,您需要查看新配置 core.hooksPath 以真正确定 hooks 文件夹。

git rev-parse --git-dir/hooks 已经不够用了。

参见Ævar Arnfjörð Bjarmason (avar)commit 867ad08commit de0824ecommit bf7d977commit 49fa52f(2016 年 5 月 4 日)。
(由 Junio C Hamano -- gitster -- 合并到 commit 6675f50,2016 年 5 月 17 日)

所以请务必检查git config core.hooksPath 是否已定义,因为它会覆盖默认的钩子文件夹位置。

git config documentation 现在包括:

core.hooksPath

默认情况下,Git 会在“$GIT_DIR/hooks”目录中查找您的钩子。
将此设置为不同的路径,例如'/etc/git/hooks',Git 会尝试在那个目录中找到你的钩子,例如'/etc/git/hooks/pre-receive' 而不是 '$GIT_DIR/hooks/pre-receive'。

路径可以是绝对路径,也可以是相对路径。相对路径被视为相对于运行挂钩的目录


Git 2.10(2016 年第三季度)使用新的 core.hooksPath 设置。

所以要获得有效 hooks 路径,您需要运行:

git rev-parse --git-path hooks

来自git rev-parseman page

--git-path <path>
    Resolve "$GIT_DIR/<path>" and takes other path relocation variables such
    as $GIT_OBJECT_DIRECTORY, $GIT_INDEX_FILE... into account. For example,
    if $GIT_OBJECT_DIRECTORY is set to /foo/bar then "git rev-parse
    --git-path objects/abc" returns /foo/bar/abc.

参见Johannes Schindelin (dscho)commit 9445b49(2016 年 8 月 16 日)。
(由 Junio C Hamano -- gitster -- 合并于 commit d05d0e9,2016 年 8 月 19 日)

【讨论】:

    【解决方案4】:

    如果您在项目目录中 你可以通过输入终端来知道当前的钩子路径

    git config core.hooksPath
    

    如果值为空,那么您可以设置 .githooks 文件夹的路径 你可以通过输入这个命令来做到这一点

    git config core.hooksPath .githooks/
    

    现在你会发现 hooks 路径改变了,你可以通过第一个命令再次确认。

    【讨论】:

    • git config core.hooksPath .git/hooks
    猜你喜欢
    • 2015-06-06
    • 2015-08-06
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多