在git仓库中检查文件是否存在。

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

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分支是我当前所在的分支。我如何测试test和main分支中thefile.py文件的存在性?我必须切换到每个分支并执行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.html
匿名

发表评论

匿名网友

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

确定