Git checkout branch or tag from multiple remotes

时间:2017-06-15 09:24:35

标签: git github version-control bitbucket

I have a parameter passed down from an upstream build, lets say $GIT_BRANCH.

It's value can represent a git tag or git branch. I also have a $GIT_REMOTE passed down which allows me compute the source of my fetch and checkout path.

Always assume I run this before any of the following comments.

git fetch $GIT_REMOTE --tags

If $GIT_BRANCH was really a branch then its super simple git checkout remotes/$GIT_REMOTE/$GIT_BRANCH. Given the remote already exists.

If $GIT_BRANCH represented a tag you would be faced with the following error:

error: pathspec 'remotes/origin/1.1.0' did not match any file(s) known to git.

Investigating refspec will tell you there is no such thing as a "remote tag" refs/tags only.

This means if I were somehow able to tell whether or not the $GIT_BRANCH was a tag or branch i could orientate the cmd properly to simply become.

git checkout tags/$GIT_BRANCH

Anybody able to build on this? Suggest an alternative? Or even suggest a way to reliably do this based on my suggestion? I have some concerns on branch_names that clash with tag names which might introduce some edge cases.

2 个答案:

答案 0 :(得分:0)

For branch you can use git checkout remotes/$GIT_REMOTE/$GIT_BRANCH or git checkout $GIT_REMOTE/$GIT_BRANCH.

But for tags, you should use git checkout $GIT_BRANCH directly. Since you have already use git fetch $GIT_REMOTE --tags to fetch tags locally in .git/refs/tags, so you can checkout them directly.

You can use shell script to detect if the parameter $GIT_BRANCH is branch or not:

#!/bin/sh


if [ `git branch | grep $GIT_BRANCH` ]
then
    echo "it's branch"
else
    echo "it's tag"
fi

答案 1 :(得分:0)

#!/bin/bash
git fetch origin --tags
if git show-ref -q --verify "refs/tags/$GIT_BRANCH" 2>/dev/null; then
    git checkout refs/tags/$GIT_BRANCH
else
    git checkout remotes/$GIT_REMOTE/$GIT_BRANCH 
fi