How do I check if a file exists in a remote?

こ雲淡風輕ζ 提交于 2019-11-30 13:45:58

问题


Is there a way to check if a file under specified, relative path exist in a remote? I'm fine with fetching the info first if it's the only option. In other words I'm looking for git-ls-files with an option to specify remote and branch. I'm only interested if the file exists (a list of files on the branch will do as well), I don't care about hashes, diffs etc.


回答1:


You can use

git cat-file -e <remote>:<filename>

which will exit with zero when the file exists. Instead of <remote> above you'd use a remote branch name (but it could in fact be any tree-ish object reference). To use such a remote branch, you'll need to have the remote repository configured and fetched (i.e. by using git remote add + git fetch).

A concrete example:

$ git cat-file -e origin/master:README && echo README exists
README exists

$ git cat-file -e origin/master:FAILME
fatal: Not a valid object name origin/master:FAILME

Two things to note:

  • Use / as path delimiter in filenames, even on e.g. Windows.
  • <filename> is a full path (such as foo/bar/README), relative to the root of the repository.



回答2:


You can use git archive to access individual files without downloading any other part of a repository:

if git archive --format=tar \
               --remote=<remote_name-or-URL> master README >/dev/null; then
  echo 'master has README'
else
  echo 'master does not have README (or other error)'
fi

The archive service (upload-archive) may not be enabled on all servers or repositories though, you will have to test it for the servers and repositories that you need to access.

If the archive service is not available, you will have to fetch objects through normal means.

If you do not already have a remote setup for the repository in question you can do a “shallow” fetch into FETCH_HEAD (this needs to be done in a Git repository, but it can be completely unrelated or even empty):

git fetch --depth=1 remote_name-or-URL master
if git rev-parse --verify --quiet FETCH_HEAD:README >/dev/null; then
  echo "repository's master has README"
else
  echo "repository's master does not have README"
fi

If you have a remote defined for the repository, then you probably just want to update it and access the file through the normal remote-tracking branches:

git fetch remote_name
if git rev-parse --verify --quiet remote_name/master:README >/dev/null; then
  echo "remote's master has README"
else
  echo "remote's master does not have README"
fi


来源:https://stackoverflow.com/questions/4135049/how-do-i-check-if-a-file-exists-in-a-remote

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!