Git hook:如果创建了新分支,则向repo添加新文件

时间:2013-08-19 21:09:21

标签: git githooks git-bash

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

目前我在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: '.'

我不确定hook我应该使用这个逻辑,因为我对git并不是很了解。知道我怎么能这样做吗?

由于

1 个答案:

答案 0 :(得分:1)

如果你陷入困境,想要跑步&#34;正常&#34; 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