在git pre-receive hook中访问已更改的文件路径

aBa*_*boy 6 git git-remote githooks

我正在远程仓库上编写一个git预接收挂钩,以确保推送的代码符合我们公司的内部指南.

我能够找到在触发预接收挂钩时要检查的所有文件,但是,我没有这些文件的路径来使用普通文件操作打开它们(例如cat git_working_directory/file_name会抛出No such file or directory错误).验证代码的应用程序需要将文件路径作为参数,以便它可以打开文件并运行其检查.

考虑这种情况:开发人员创建了一个新文件并将其推送到服务器并触发了预接收挂钩.在此阶段,新文件未保存到远程工作目录,因为预接收挂钩仍在运行.

我想知道是否有一个临时位置,文件一旦被推送就保存在git中,以便我可以将该目录传递给应用程序来运行检查?

更新:

我可以结账到临时位置并在那里运行检查,这可能是一个选项,但考虑到开发人员经常推动的事实,有时甚至在同一时间和回购非常大,这个选项似乎不可行.我正在寻找一个解决方案,我可以使用文件的路径,如果它以某种方式可用.

joo*_*zek 5

我想知道是否有一个临时位置,文件一旦被推送就保存在git中,以便我可以将该目录传递给应用程序来运行检查?

不,没有这样的地方.这些文件存储为blob,可以缩减为增量和/或压缩,因此不能保证它们在"准备消费"状态下可用.

检查标准的应用程序需要将文件路径作为参数,以便它可以打开文件并运行其检查.

如果您使用的是Linux,则只需指向/dev/stdin输入文件并将文件放入管道即可.

#!/bin/sh
while read oldrev newrev refname; do
 git diff --name-only $oldrev $newrev | while read file; do
   git show $newrev:$file | validate /dev/stdin || exit 1
     done
done
Run Code Online (Sandbox Code Playgroud)


lar*_*sks 1

您可能需要编写pre-receive钩子来检查临时位置中的文件。一般来说,这意味着您将git clone裸存储库放入临时目录中,然后检查特定的提交并运行检查。例如,类似:

#!/bin/sh

REPO=$PWD

check_files_in () {
  rev=$1

  # create a temporary working directory
  workdir=$(mktemp -d gitXXXXXX)
  (
    # arrange to clean up the workding directory
    # when the subshell exits
    trap "cd /; rm -rf $workdir" EXIT

    # unset GIT_DIR because it would confuse things
    unset GIT_DIR

    # clone the repository
    cd $workdir
    git clone $REPO check

    # checkout the specific revision we're checking
    cd check
    git checkout $rev

    # perform some sort of validation.  The exit code of this 
    # command will be the exit code of this function, so
    # returning an error will reject the push.
    run-validation-scripts
  )
}

while read oldrev newrev refname; do
  check_files_in $newrev || exit 1
done
Run Code Online (Sandbox Code Playgroud)