我想在HEAD
创建一个新分支,保持与我当前所在分支相同的远程跟踪分支,然后查看新分支。这是我正在尝试使用的命令:
$ git checkout --track @{upstream} -b feature/cleanup-gradle HEAD
fatal: 'HEAD' is not a commit and a branch 'feature/cleanup-gradle' cannot be created from it
我不知道为什么我得到上面的错误。有没有办法让这项工作?
显然(基于错误),而不是任何现有的Git命令。不过,您当然可以编写自己的Git命令。将下面的脚本放在可执行的位置(我使用$HOME/scripts/
进行此类操作),将其命名为git-nbranch
,确保它是可执行的,然后运行git nbranch
:
$ git nbranch
usage: git nbranch [options] newname
Create new branch but set its upstream to the current branch's upstream.
If and when this succeeds, you're on the new branch.
-s, --start ... starting commit for new branch (default HEAD)
该脚本说明了可用于编写Git命令的一些技术。
#! /bin/sh
OPTIONS_KEEPDASHDASH=
OPTIONS_STUCKLONG=
OPTIONS_SPEC="git nbranch [options] newname
Create new branch but set its upstream to the current branch's upstream.
If and when this succeeds, you're on the new branch.
--
s,start= starting commit for new branch (default HEAD)
"
# parse options (defined above) and obtain "fatal" function etc.
. git-sh-setup
start=HEAD
while :; do
case "$1" in
--) shift; break;;
-s) start="$2"; shift 2;;
esac
done
case $# in 1) ;; *) usage; esac
# optional - we can just let git checkout -b check later
#ref=$(git check-ref-format --normalize "refs/heads/$1") ||
# die "fatal: $1 is not a valid branch name"
#ref=${ref#refs/heads/} # make suitable for -b
ref="$1"
# compute settings
curbranch=$(git symbolic-ref -q --short HEAD) ||
die "fatal: not on a branch"
case "$start" in
HEAD) startrev=$(git rev-parse -q --verify HEAD) ||
die "fatal: current branch does not exist yet";;
*) startrev=$(git rev-parse -q --verify "$start"^{commit}) ||
die "fatal: $start does not name an existing commit";;
esac
remote=$(git config --get branch.$curbranch.remote) ||
die "fatal: current branch $curbranch has no remote"
merge=$(git config --get branch.$curbranch.merge) ||
die "fatal: current branch $curbranch has no upstream"
git checkout -b "$ref" "$startrev" ||
die "fatal: unable to create and switch to $ref"
git config branch."$ref".remote "$remote" &&
git config branch."$ref".merge "$merge"
只需关闭明确的HEAD
:
$ git checkout --track @{u} -b new
Branch 'new' set up to track remote branch 'next' from 'origin'.
Switched to a new branch 'new'
$
git checkout
没有指定提交或路径是一个无操作,除了选项效果,这是你想要的。也就是说,你得到的错误肯定会更好。
我创建了一个简单的别名来解决这个问题:
cob = "!f() { : git branch ; git checkout -b \"$@\" && git branch -u @{-1}@{upstream}; }; f"
用法(在跟踪master
的origin/master
上):
$ git cob topic1
结果:
Switched to a new branch 'topic1'
Branch topic1 set up to track remote branch master from origin.