简体   繁体   English

只考虑在 pre-push hook git 中推送的文件

[英]Consider only files being pushed in pre-push hook git

I want to run lint on code for pre-push without considering the local changed files the user has.我想在代码上运行 lint 以进行预推送,而不考虑用户拥有的本地更改文件。 for example change in file A is being pushed and the same got changed in the local changes I want to consider the code being pushed by user.例如,正在推送文件 A 中的更改,并且在本地更改中也发生了相同的更改,我想考虑用户推送的代码。

How to implement this using hit-hooks.如何使用命中挂钩来实现这一点。

Alternate ways I tried: Limiting the user to reset the changes in pre-push - The functionality is limited in this case我尝试过的替代方法:限制用户在预推送中重置更改-在这种情况下功能受到限制

There are several ways to get files from git storage and write them to disk, but I don't know of a direct command to say straight away "checkout files A, B and C from commit xxx to that directory on disk".有几种方法可以从 git 存储中获取文件并将它们写入磁盘,但我不知道直接命令可以直接说“将文件 A、B 和 C 从提交 xxx 签出到磁盘上的该目录”。


The simplest way is probably to use git worktree add (but this checks out all files, not just the ones you want) :最简单的方法可能是使用git worktree add (但这会检查所有文件,而不仅仅是您想要的文件):

git worktree add /tmp/myhook.xyz <commit-sha>

The most direct way is to use git --work-tree=... (or GIT_WORK_TREE=... ) to target some other directory on disk :最直接的方法是使用git --work-tree=... (或GIT_WORK_TREE=... )来定位磁盘上的其他目录:

git --work-tree=/tmp/myhook.xyz checkout <commit-sha> -- file1 file2 path/to/file3

How to use this in a pre-push hook:如何在预推挂钩中使用它:

for each pushed reference, you can :对于每个推送的引用,您可以:

  • compare the local commit and remote commit to list files that were modified,比较本地提交和远程提交以列出已修改的文件,
  • use the above trick to checkout the files from local commit in a specific destination on disk :使用上述技巧从磁盘上特定目标的本地提交中签出文件:
# pre-push:
#!/bin/bash

zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')


list_modified_files () {
        local $local_commit=$1
        local $remote_commit=$2

        if [ "$local_commit" = "$zero" ]; then
                return
        fi

        if [ "$remote_oid" = "$zero" ]; then
                git ls-tree -r --name-only $local_oid
        else
                git diff --no-renames --diff-filter=AM --name-status $remote_oid $local_oid
        fi
}



while read local_ref local_oid remote_ref remote_oid
do
        echo "'$local_ref' '$local_oid' '$remote_ref' '$remote_oid'"
        tmpdir=$(mktemp -d /tmp/myprepushhook.XXXXXX)
        list_modified_files | xargs -r git --work-tree "$tmpdir" checkout "$local_oid" --

        # run linter on files in $tmpdir ...

        rm -rf "$tmpdir"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM