我在一个有两个分支a和B的项目上工作。我通常在分支a上工作,并合并分支B中的内容。对于合并,我通常会这样做:

git merge origin/branchB

但是,我也希望保留分支B的本地副本,因为我可能会偶尔检查分支,而不必首先与分支a合并。为此,我会:

git checkout branchB
git pull
git checkout branchA

有没有一种方法可以在一个命令中完成上述操作,而不必来回切换分支?我应该使用gitupdate-ref吗?怎样


当前回答

另一种公认的蛮力方法是重新创建分支:

git fetch remote
git branch -f localbranch remote/remotebranch

这将丢弃本地过时的分支,并重新创建一个同名分支,因此请谨慎使用。。。

其他回答

您可以简单地git将原始分支B拉到分支A中,git将为您完成此操作。

对于许多GitFlow用户来说,最有用的命令是:

git fetch origin master:master --update-head-ok
git fetch origin dev:dev --update-head-ok

--update-headok标志允许在dev或master分支上使用相同的命令。

gitconfig中一个方便的别名:

[alias]
    f=!git fetch origin master:master --update-head-ok && git fetch origin dev:dev --update-head-ok

如果您想保持与要合并的分支相同的树(即,不是真正的“合并”),可以这样做。

# Check if you can fast-forward
if git merge-base --is-ancestor a b; then
    git update-ref refs/heads/a refs/heads/b
    exit
fi

# Else, create a "merge" commit
commit="$(git commit-tree -p a -p b -m "merge b into a" "$(git show -s --pretty=format:%T b)")"
# And update the branch to point to that commit
git update-ref refs/heads/a "$commit"

对于许多情况(例如合并),您可以只使用远程分支,而不必更新本地跟踪分支。在reflog中添加一条消息听起来有些过分,而且会让它变得更快。为了更容易恢复,请在git配置中添加以下内容

[core]
    logallrefupdates=true

然后键入

git reflog show mybranch

查看分支机构的近期历史

不,没有。需要签出目标分支,以便解决冲突(如果Git无法自动合并冲突)。

但是,如果合并是一个可以快速进行的合并,则不需要检查目标分支,因为实际上不需要合并任何内容-只需更新分支以指向新的头部引用即可。您可以使用gitbranch-f执行此操作:

git branch -f branch-b branch-a

将更新branch-b以指向branch-a的头部。

-f选项代表--force,这意味着branch-b将被覆盖。

警告:更安全的选择是使用git fetch,它只允许快进。

此方法可按如下方式使用:

git branch -f branch-b branch-b@{Upstream}

或更短

git branch -f branch-b branch-b@{U}

强制更新一个分支,而不检查它(例如,如果它们在重基之后已经分叉)