1

我正在编写一个 git 挂钩,它检查是否创建了新分支,如果是,则将一些预定义文件添加到该新分支的存储库中(一些配置文件)。但是,因为分支实际上正在创建过程中,所以我的逻辑失败了。

目前我正在一个post-receive钩子中执行此操作,看起来像这样:

#!/bin/sh
read oldrev newrev refname
branch=$(git rev-parse --symbolic --abbrev-ref $refname)
echo "branch is $branch"
echo "oldrev is $oldrev and newrev is $newrev" 

# if $oldrev is 0000...0000, it's a new branch
# also check if the branch is of the format "feature_<name>"
zero="0000000000000000000000000000000000000000"
if [ "$oldrev" = "$zero" ] && [[ $branch =~ feature_.+ ]]; then
    #create a temp repo
    temp_repo=`mktemp -d /tmp/repo.XXXXX`
    cd $temp_repo
    git clone $git_url
    #here i create the config file needed, called file_name
    git checkout "$branch"
    git add "$file_name"
    git commit -m "Added config file"
    git push origin $branch
fi

这适用于现有分支,但是对于新创建的分支,它会给出错误fatal: Not a git repository: '.'

我不确定我应该在哪个钩子中使用这个逻辑,因为我对git. 知道我该怎么做吗?

谢谢

4

1 回答 1

2

如果您陷入困境并想要运行“普通” git 命令,则需要取消设置GIT_DIR环境变量(在挂钩内将其设置为.)。

也就是说,在我看来这不是正确的方法。它应该可以工作,但似乎有点令人惊讶:如果我git push origin abc:feature_def必须从原点重新获取并合并以获取这个新提交的$file_name文件。要求我自己包含该文件是否更有意义,以便它已经存在于分支的提交中feature_def

如果是这样,预接收或更新挂钩将是进行检查的地方。一个简化的例子(未经测试):

#! /bin/sh
# update hook - check if new branch is named
# feature_*, and if so, require config file

refname=$1
oldrev=$2
newrev=$3

# BEGIN BOILERPLATE
NULL_SHA1=0000000000000000000000000000000000000000

# what kind of ref is it? also, get short name for branch-or-tag
case $refname in
refs/heads/*) reftype=branch; shortname=${refname#refs/heads/};;
refs/tags/*) reftype=tag; shortname=${refname#refs/tags/};;
*) reftype=other;;
esac

# what's happening to the ref?
# note: if update, there are potentially two different objtypes,
# but we only get the new one here
case $oldrev,$newrev in
$NULL_SHA1,*) action=create; objtype=$(git cat-file -t $newrev);;
*,$NULL_SHA1) action=delete; objtype=$(git cat-file -t $oldrev);;
*,*) action=update; objtype=$(git cat-file -t $newrev);;
esac
# END BOILERPLATE

# code to check a feature branch.  Top level file named xyzzy.conf must exist.
check_feature_branch()
{
    if ! git show $refname:xyzzy.conf >/dev/null 2>&1; then
        echo "new branch $branch does not contain xyzzy.conf at top level" >&2
        exit 1
    fi
}

# check whether we're creating a branch named feature_*

case $action,$reftype,$shortname in
create,branch,feature_*) check_feature_branch;;
*) ;;
esac

# if we got here it must be OK
exit 0
于 2013-08-20T00:38:03.357 回答