英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论