代码之家  ›  专栏  ›  技术社区  ›  Rahul Shelke

POST提交钩子的shell脚本给出了不是一个Git存储库错误

  •  2
  • Rahul Shelke  · 技术社区  · 6 年前

    我已经编写了一个post commit钩子,它要求创建虚拟环境,以便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 回复  |  直到 6 年前
        1
  •  1
  •   VonC    6 年前

    只是确定一下 GIT_DIR and GIT_WORK_TREE environment variables 为了确定 git 命令在正确的上下文中运行:

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