可以使用远程URL而不是名称来检出分支吗?

5
git checkout -b <name> <remote>/<branch> 命令需要指定一个已命名的远程分支。是否有一种方法可以只给出URL就能让此命令正常工作?原因是,团队中的人对于远程(例如gitlaborigin vs origingithub)有不同的名称,并且我想在脚本中忽略这种差异。
一种可能的解决方式是在脚本开头为远程分支命名并在结尾处删除,但我更愿意避免这样做。

2
如果分支的名称是唯一的,您可以完全跳过 <remote> - Gabriele Petronella
1
也许团队应该采用一些标准的命名约定。 - larsks
4个回答

3

没有任何方法可以使用URL而不是分支的名称(以<remote>/<branch>形式或其他形式)作为git checkout -b命令的第二个参数。

从man页面中可以看到:

   git checkout -b|-B <new_branch> [<start point>]
       Specifying -b causes a new branch to be created as if git-branch(1) were
       called and then checked out. In this case you can use the --track or
       --no-track options, which will be passed to git branch. As a convenience,
       --track without -b implies branch creation; see the description of
       --track below.

       If -B is given, <new_branch> is created if it doesn’t exist; otherwise,
       it is reset. This is the transactional equivalent of

           $ git branch -f <branch> [<start point>]
           $ git checkout <branch>

       that is to say, the branch is not reset/created unless "git checkout" is
       successful.
git branch命令的第二个参数被称为起始点,它需要指向现有存储库中某个提交的内容。通过URL访问的分支(可能甚至没有获取到)将无法实现此目的。而且,没有标准的方法将分支编码到git URL中(GitHub可能有一些方法,但我认为并没有,否则golang导入会容易得多...)
如果您想使此工作正常,您需要:
  • 解析git remote -v show的输出以获取适当的远程名称
  • 执行git fetch以确保拉取相关分支(git fetch --all可能是您的朋友)
  • 将分支名称附加到远程名称上,并git checkout -b
这是一个非常简单的Bash脚本:
#!/bin/bash
#
# usage: scriptname repo branchname
#
# where repo is the URL, branchname is the branchname to create
repo="$1"
branchname="$2"
remote=$(git remote -v show | perl -n -e 'if (m,^(\w+)\s+(\S+)\b, && $2 eq '"'${repo}'"') {print "$1\n" ; exit 0}')
if [ "$remote" == "" ] ; then
    echo cannot find "${repo}" 1>&2
    exit 1
fi
git fetch --all && git checkout -b "${branchname}" "remotes/${remote}/${branchname}"

2
在仓库根目录下运行git remote,会得到以下类似内容:
$ git remote
foobar
origin

你可以解析它并将其融入你的脚本中。

好主意,但是回答含糊。它没有解释如何根据URL推断远程名称。 - Gabriele Petronella

2

其中一种可能性(由其他人提出)是根据其URL获取远程控制器的名称。

REMOTE_URL=git@github.com:foo/bar.git
REMOTE_NAME=git remote -v show | grep $REMOTE_URL | awk '{print $1}'
git checkout -b <name> $REMOTE_NAME/<branch>

此外,如果您足够幸运拥有一个独特的分支名称,您可以简单地执行以下操作:
git checkout -b <name> <branch>

Git会自动选择包含该分支的远程仓库。


除非您的URL中有正则表达式字符。使用grep -F会更好。我在perl中过度设计了这个。 - abligh
@abligh,说得好。这更像是一个概念,实际的解析可以更加稳固,具体取决于使用情况。 - Gabriele Petronella

1
可以实现,但不能仅使用git checkout命令。Gerrit使用以下命令让每个人都可以检出任何分支(它使用一些特殊的引用,但其余部分仍然适用):

git fetch <url> branch && git checkout -b name FETCH_HEAD


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接