git 切换分支并拉动

git switch branch and pull

我的组织不相信合并提交。因此,我们确实致力于 master 并将其挑选到一个通常稳定的分支,我将在此处命名为 stable。 (我们还有一个遥控器,origin,它简化了这里的一些命令)。

所以我现在的流程是这样的:

$ git branch
* master
  stable 
# do some work and commit it to 'master'
$ git commit -a -m "some message"
# rebase on 'origin/master' because there were commits by colleagues in the meantime
$ git fetch && git rebase origin/master
$ git push origin master
# here's the rub: switch to 'stable', which is present in the local repo and behind 'origin/stable'
$ git checkout stable
# now update (a fetch may be necessary before, depending on how busy the remote repo is), git pull would also do
$ git merge --ff-only
# cherry-pick, push etc.
$ git cherry-pick master ...

我的问题是切换到现有的本地分支然后进行更新具有冗余操作:恢复过时的文件。基本上,我要去一个地方只是为了去另一个地方,当有直接路线时:

# suppose I have pushed my changes to origin/master already
$ git branch -d stable
# some git grumbling, but origin/stable is ahead, so no commits are lost and the operation has proceeded
$ git checkout stable

当然,我可以把它做成别名。但我想知道:是否有更好的方法来切换到分支并将其更新为远程状态?也有可能我忽略了我的提案中可能存在的问题.

你现在做的很好,但是如果你想强迫你的 stable 匹配你的 origin/stable 进入你的 stable 同时,分别使用 git checkoutgit switch-B-C 选项,以及两个名称。即:

git fetch                              # if needed
git checkout -B stable origin/stable

这有点危险,因为它没有验证origin/stable是否严格领先于stable,即这个分支重置过程会导致在快进中。为确保它是快进的,而你不在它上面,你可以使用相当晦涩的序列:

git push . origin/stable:stable

或等效项:

git fetch . origin/stable:stable

您可以通过以下方式将后者与 git fetch 组合到远程:

git fetch origin stable:stable

如果对 stable 的调整 不是 快进,您将收到 rejection-due-to-non-fast-forward 错误。

(None 当当前分支 命名为 stable 时,这些工作的 None;在这种情况下,使用 git merge --ff-only origin/stable 向前移动,或出现错误。)

(我建议写一个小脚本来做你想做的事,并让它处理所有各种极端情况,比如检查你当前的分支名称。)

先获取所有变更,包括远程master分支和stable分支
git fetch --all

然后可以通过以下命令快速重置本地稳定分支
git branch -f stable origin/stable

切换分支后cherry-pick即可
git switch stable

根据我的经验,您使用的流程很奇怪。由于您使用 cherry-pick 将提交同步到稳定分支(它会在目标分支上生成新提交,尽管它们具有相同的内容),rebase 对 master 和 origin/master 操作的含义是什么? 不建议在 long-term 分支上使用 cherry-pick。