git/list[1] front-page[2] threads[3] people[4] search[5] about
 

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
Previous: Chris Packham
Message 7 of 7 in “Testing for existence of a remote branch from a script”
  1. Chris PackhamJan 6, 2025
  2. Torsten BögershausenJan 6, 2025
  3. Junio C HamanoJan 6, 2025
  4. Theodore Ts'oJan 6, 2025
  5. Junio C HamanoJan 6, 2025
  6. Chris PackhamJan 6, 2025
  7. Theodore Ts'oJan 6, 2025

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.