提交后挂接的Shell脚本给出了-不是git仓库错误

时间:2018-06-22 04:04:57

标签: git shell virtualenv githooks

我已经编写了一个提交后钩子,该钩子需要创建虚拟环境以使python脚本在提交发生时运行。

以下是我的脚本:

#!/bin/bash
# Teamcity-build trigger

echo "Executing post-commit hook"

BASEDIR=$(dirname $(readlink -f $0))
VENV=venv
ACTIVATE=$VENV/bin/activate
STATUS=false
CIDIR=teamcity

# Username
machine=$(uname -n)

echo "Notifying Teamcity Server to execute a Build on " $machine
# Logic to check if commit is done or merged to a particular branch / master branch

cd $BASEDIR
# Change directory to parent directory, since current directory is `.git/hooks/`
cd ../..
# Go in teamcity directory
cd $CIDIR

# Check if venv folder exists, if it does not then create it
if [ ! -d "$VENV" ]; then
  # Control will enter here if $VENV doesn't exist.
  virtualenv -p python $VENV
  STATUS=true
fi

# Source virtual environment
source $ACTIVATE

# Install required dependencies if not yet installed
if [ "$STATUS" = true ]; then
    # if status is true, means need to install all the required libraries
    pip install --upgrade pip
    pip install -r requirements.txt
fi

# check current git branch
# $(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
BRANCH=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD)
if [ "$BRANCH" = "rahul" ]; then
    # if branch is master, then only proceed.
    # Start processing teamcity jobs
    python last_dir_processed.py
else
    echo "Current Branch $BRANCH, Nothing to execute."
fi

# Deactivate virtual environment
deactivate

第43行,

BRANCH=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD)

脚本试图知道当前分支的名称。

但是它给出错误为:

fatal: Not a git repository: '.git'

我在该行之前用pwd命令破解了文件夹路径,它显示.git文件夹存在。

此外,当我手动运行以下命令时,它起作用了:

git rev-parse --symbolic-full-name --abbrev-ref HEAD

这给了我一个当前的分支名称。

编辑:以下是我的目录结构:

--root_dir
    --teamcity
        -last_dir_processed.py
    --.git
        --hooks
            -post-commit

因此,理想情况下,脚本应正确执行,但仍会给出错误。不知道可能是什么原因。

1 个答案:

答案 0 :(得分:1)

请确保设置GIT_DIR and GIT_WORK_TREE environment variables,以确保任何git命令在正确的上下文中运行:

cd ../..
GIT_DIR=$(pwd)/.git
GIT_WORK_TREE=$(pwd)