gpt4 book ai didi

混帐 |将旧提交移至另一个分支的过去

转载 作者:行者123 更新时间:2023-12-04 15:56:58 25 4
gpt4 key购买 nike

我过去错误地分支,一个提交留在了另一个分支的开头:

* 03431cb (HEAD -> bar) a2
| * d332e4d (foo) b2
| * 9b29ae3 b1
| * 4656a98 a1
|/
* 6ebca20 (master) root

我怎样才能把a1foo移到bar,这样bar的历史就是root -> a1 -> a2a1 不在 foo 中?是否可以通过一个 git commit 来完成?
这不是推送的,因此无需担心破坏其他人的本地存储库。

我首先考虑对 a1 进行挑选,然后更正 a2a1 之间的顺序。问题是这两个提交在我的真实案例场景中发生冲突,我必须在进行 cherry-pick 和切换顺序时纠正冲突。


mwe 在 bash 中:

#!/bin/bash
set -e

rm -rf .git

git init -b master
echo content > my-file
git add my-file
git commit -m root

git checkout -B foo
echo asd >> my-file
git add my-file
git commit -m a1
echo qwe >> my-file
git add my-file
git commit -m b1
echo zxc >> my-file
git add my-file
git commit -m b2

git checkout master
git checkout -B bar
echo jkl >> my-file
git add my-file
git commit -m a2

最佳答案

我非常喜欢语法 git rebase --onto x y z,意思是:

Starting at z, look back thru the parent chain until you are about to come to y and stop. Now rebase those commits, ie everything after y up to and including z, onto x.

换句话说,使用这种语法,您可以清楚地说明在哪里剪断链。另外,您不必在 rebase 之前切换分支。语法需要一些时间来适应,但是一旦你熟练掌握它,你会发现自己一直在使用它。

所以:

  1. 在 a1 处创建一个临时分支只是为了给它一个名字:git branch temp 4656a98
  2. 现在将 b1 和 b2 重新定位到根目录:git rebase --onto master temp foo
  3. 最后将 a2 rebase 到 a1:git rebase --onto temp master bar
  4. 现在你可以根据需要删除 temp:git branch -D temp

当然,我们可以省去两个步骤,只使用 SHA 编号 4656a98 而不是名称 temp 执行 2 和 3,但名称更好。


证明。

起始位置:

* 9a97622 (HEAD -> bar) a2
| * 83638ec (foo) b2
| * 7e7cbd0 b1
| * 931632a a1
|/
* 6976e30 (master) root

现在:

% git branch temp 931632a
% git rebase --onto master temp foo
% git rebase --onto temp master bar
% git branch -D temp

结果:

* 3a87b61 (HEAD -> bar) a2
* 931632a a1
| * bbb83d0 (foo) b2
| * 5fa70af b1
|/
* 6976e30 (master) root

我相信这就是你所说的。

关于混帐 |将旧提交移至另一个分支的过去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68522631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com