在 Git 存储库中检查文件是否存在。

huangapple go评论78阅读模式
英文:

Testing for presence of a file in a git repo

问题

我正在编写代码来比较git/GitHub中多个分支上文件的最新版本,并部署在执行服务器上。

dev分支
test分支
main分支

\\devsrv\prod\src\thefile.py
\\testsrv\prod\src\thefile.py
\\prodsrv\prod\src\thefile.py

使用git diff,这会比较dev和test分支上thefile.py的最新版本。

git diff --exit-code origin/dev..origin/test -- C:\src\therepo\src\thefile.py
git diff --exit-code origin/dev..origin/main -- C:\src\therepo\src\thefile.py

然而,git diff似乎不会指示文件是否尚不存在于test或main分支中。

dev分支是我的当前分支。我如何测试thefile.py在test和main分支中是否存在?我必须切换到每个分支并执行git pull吗?

英文:

I am working on code to compare the head version of files across multiple branches in git/GitHub and deployed on execution servers.

dev branch
test branch
main branch

\\devsrv\prod\src\thefile.py
\\testsrv\prod\src\thefile.py
\\prodsrv\prod\src\thefile.py

Using git diff, this compares the head version of thefile.py on the dev and test branches.

git diff --exit-code origin/dev..origin/test -- C:\src\therepo\src\thefile.py
git diff --exit-code origin/dev..origin/main -- C:\src\therepo\src\thefile.py

However, git diff does not appear to indicate if the file does not yet exist in the test or main branch.

The dev branch is my current branch. How can I test for the file existence of thefile.py in the test and main branches? Must I git switch and git pull to each branch?

答案1

得分: 2

如果您希望要求这些文件在两个分支中都存在,请直接引用它们。

git diff --exit-code origin/dev:src/file.py origin/test:src/file.py

如果它们都存在但不同,这将返回代码1;如果其中一个或两者都不存在,返回代码128;如果它们都存在且相同,返回代码0。

要在特定对象不存在时退出,您可以使用 git rev-parse,我在这里显示的方式看起来有点奇怪,但会在检查所有规范之前检查是否存在任何错误:

git rev-parse origin/dev:src/file.py &>/dev/null;  ((rc+=$?))
git rev-parse origin/test:src/file.py &>/dev/null; ((rc+=$?))
git rev-parse origin/main:src/file.py &>/dev/null; ((rc+=$?))
(( rc!=0 )) && exit 1
英文:

If you want to require that the files exist in both tips, reference them directly.

git diff --exit-code origin/dev:src/file.py origin/test:src/file.py

That'll get you return code 1 if they both exist but differ, 128 if either or both doesn't exist, 0 if they both exist and are identical.


To bail if a specific object doesn't exist you can use git rev-parse, the way I'm showing here looks weird but will vet all the specs before bailing if any are bad:

git rev-parse origin/dev:src/file.py >/dev/null;  ((rc+=$?))
git rev-parse origin/test:src/file.py >/dev/null; ((rc+=$?))
git rev-parse origin/main:src/file.py >/dev/null; ((rc+=$?))
(( rc!=0 )) && exit 1

huangapple
  • 本文由 发表于 2023年8月9日 11:13:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864333-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定