【问题标题】:Shell script for post-commit hook gives - Not a git repository error提交后挂钩的 Shell 脚本给出 - 不是 git 存储库错误
【发布时间】:2018-12-01 11:50:39
【问题描述】:

我编写了一个提交后挂钩,它需要创建虚拟环境,以便在提交发生时运行 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

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

【问题讨论】:

    标签: git shell virtualenv githooks


    【解决方案1】:

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

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

    【讨论】:

    • 在大多数情况下最好使用export 命令设置它们,尽管对于这个特定的命令,我们可以例外,因为如果它们不在环境中,我们不需要将它们在那里。
    • @torek 我同意。这只是为了测试是否有任何区别。
    最近更新 更多