Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top