【问题标题】:Move commits from master onto a branch using git使用 git 将提交从 master 移动到分支
【发布时间】:2011-04-12 18:07:35
【问题描述】:

我正在尝试学习如何有效地使用 Git,我想知道我应该如何(好的做法/坏的做法?)解决以下案例:

假设我在 master 中有以下提交链:

  • 初始提交
  • 提交 1
  • 提交 2
  • 提交 3

然后我意识到在最后两次提交中所做的事情是完全错误的,我需要再次从 Commit 1 开始。问题:

  • 我该怎么做?
  • 我能否将 Commit 2 和 3 移至单独的分支以供将来参考(假设它们毕竟没那么糟糕)并继续从 Commit 1 在 master 上工作?

【问题讨论】:

    标签: git commit git-branch git-reset


    【解决方案1】:
    git branch tmp            # mark the current commit with a tmp branch
    git reset --hard Commit1  # revert to Commit1
    

    SO 答案“What's the difference between 'git reset' and 'git checkout' in git?”对这种操作很有指导意义

    git reset --hard HEAD~2 会做同样的事情(无需先取回 Commit1 的 SHA1)。

    由于 Commit2Commit3 仍被 Git 引用(此处为分支)引用,您仍然可以随时恢复到它们 (git checkout tmp)。


    实际上,Darien 在 cmets 中提及(关于将 Commit2Commit3 移动到另一个分支):

    不小心投错了分支,这让我动一下,做了:

    git checkout correctbranch
    git rebase tmp
    git branch -d tmp
    

    这在这里有效,因为初始分支已重置为Commit1,这意味着git rebase tmp 将在Commit1(所以这里是Commit2Commit3)之后重播每个提交到新的'correctbranch '。

    【讨论】:

    • 谢谢!只是一个观察:在 gitk 中, tmp 分支没有显示。不应该这样做吗,因为 Commit1 对两个分支都很常见?
    • @Paul:你试过“gitk --all”吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多