如何编写一个提交钩子来挑选从主分支到裸存储库中其他工作树的最后一次提交?

问题描述 投票:0回答:1

我有 3 个分支,分别是

main
macos
linux
。一旦我向
main
分支提交了某些内容,我就想挑选该提交到其他两个分支。我也想在一个裸仓库中执行此操作。

❯ git clone --bare <bare-repo-url>
❯ cd my-bare-repo
❯ git worktree add main
❯ git worktree add linux
❯ git worktree add macos
❯ cd main
❯ touch README.md
❯ git add README.md
❯ git commit -m "Add README" # <- this commit should be cherry picked to the other two branches

实际上,如果我在 shell 中编写以下 2 个命令,我可以手动执行此操作:

❯ git --git-dir=<path-to-bare-repo>/worktrees/linux --work-tree=<path-to-bare-repo>/linux cherry-pick main
❯ git --git-dir=<path-to-bare-repo>/worktrees/macos --work-tree=<path-to-bare-repo>/macos cherry-pick main

但是当我为这项工作编写一个

post-commit
钩子时,不知何故它没有按预期工作。它的工作原理就像我没有提供
--git-dir
--work-tree
选项一样,并尝试从同一分支中进行挑选,并发生冲突。我该如何修复这个脚本?

#!/bin/bash
current_branch=$(git symbolic-ref --short HEAD)

# Check if committing to the main branch
if [ "$current_branch" = "main" ]; then
    gitdir=$(dirname `pwd`)
    # Update the linux branch
    git --git-dir="$gitdir/worktrees/linux" --work-tree="$gitdir/linux" cherry-pick main

    # Update the macos branch
    git --git-dir="$gitdir/worktrees/macos" --work-tree="$gitdir/macos" cherry-pick main

fi
❯ git commit -m "Add README"
error: your local changes would be overwritten by cherry-pick.
hint: commit your changes or stash them to proceed.
fatal: cherry-pick failed
error: your local changes would be overwritten by cherry-pick.
hint: commit your changes or stash them to proceed.
fatal: cherry-pick failed
[main ed96ee9] Add README
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README

我也尝试过

cd ../linux; git cherry-pick main
但也没成功。

git githooks git-bare git-worktree
1个回答
0
投票

我找到了答案。在脚本中添加

unset GIT_INDEX_FILE
后问题得到解决。

...bash
gitdir=$(dirname `pwd`)
unset GIT_INDEX_FILE
...

直接引用原答案:

这里的问题是在

post-commit
钩子中(还有
pre-commit
prepare-commit-msg
commit-msgt
GIT_INDEX_FILE
环境变量设置为
.git/index
。 (这 没有记录在 githooks 中 文档,但我已经 发布在其他地方 关于环境变量的设置和 git 中的当前目录 钩子。)

GIT_INDEX_FILE
环境变量的作用描述 在
git
手册页的环境变量部分为:

GIT_INDEX_FILE

此环境[变量]允许指定备用索引文件。如果未指定,则使用默认值

$GIT_DIR/index

...并且出于某种原因,在这种情况下,

GIT_INDEX_FILE
正在被 相对于
GIT_WORK_TREE
使用。

要使钩子按照您的预期工作,您只需取消设置

GIT_INDEX_FILE
,所以你的钩子看起来像:

 #!/bin/sh
 unset GIT_INDEX_FILE
 export GIT_WORK_TREE=/var/www/example/
 export GIT_DIR=/home/mark/test/.git/
 git checkout -f
© www.soinside.com 2019 - 2024. All rights reserved.