Re: Testing for existence of a remote branch from a script
- From
Theodore Ts'o <tytso@mit.edu>
- Date
- Jan 6, 2025, 15:05 UTC
- Message-ID
- <20250106150549.GE1284777@mit.edu>
- In-Reply-To
- <CAFOYHZDQs-mftqLQn5HiFgBWcFN6Z-WDscJt=zVLRyGTo36=HQ@mail.gmail.com>
On Mon, Jan 06, 2025 at 05:40:36PM +1300, Chris Packham wrote:
> I look after some scripts we use at $dayjob for pushing changes though > our review system. > .. > Is there a better way of checking for the existence of a remote branch?
In gce-xfstests[1] I do this via "git ls-remote":
validate_branch_name()
{
if test -z "$GIT_REPO"
then
echo "GIT_REPO is neither found in the config file nor provided with --repo"
exit 1
fi
if [[ "$GIT_REPO" != *".git" ]]; then
GIT_REPO="$GIT_REPO.git"
fi
if ! git ls-remote "$GIT_REPO" > /dev/null; then
echo -e "Repo not found: $GIT_REPO\n"
exit 1
elif ! git ls-remote --heads --exit-code "$GIT_REPO" $1 > /dev/null; then
echo -e "$1 is not a valid branch of $GIT_REPO"
exit 1
fi
}See run-fstests/util/parse_cli[2] for this function, and a related function, validate_commit_name if you also want to accept git tags. (The validate_commit_name function isn't perfect, since I don't want to fetch the full git repo to validate a SHA hash specifier, but it's good enough to validate typo'ed tag or branch names.)
[1] https://thunk.org/gce-xfstests [2] https://github.com/tytso/xfstests-bld/blob/master/run-fstests/util/parse_cli
Cheers,
- Ted