简体   繁体   English

如何使下一个git提交从另一个提交准确表示项目状态而不合并?

[英]How to make next git commit to exactly represent project state from another commit without merge?

I have two git branches: Alpha and Beta and I need to create next commit on the branch Alpha so its project state would be exactly the same like on branch Beta. 我有两个git分支:Alpha和Beta,我需要在分支Alpha上创建下一个提交,因此它的项目状态与分支Beta上的完全相同。 Without merge. 没有合并。

I understand that every git commit - on a logical level - is a complete and immutable project state + some metadata. 我理解每个git提交 - 在逻辑层面 - 是一个完整的,不可变的项目状态+一些元数据。 So I just need branch Alpha to have the same state of files like Beta does. 所以我只需要分支Alpha就可以获得像Beta那样的文件状态。

It would be another commit (with different hash), and one branch tip wouldn't reference another. 这将是另一个提交(具有不同的哈希),并且一个分支提示不会引用另一个。

But it I believe there should be a simpler and more elegant way. 但我认为应该有一种更简单,更优雅的方式。

There is a way which does not involve patches: reset --hard followed by reset --soft . 有一种方法不涉及补丁: reset --hard然后是reset --soft

  • First, mark the current HEAD of your branch: we will need to move that HEAD without modifying Alpha , so let's create a new temporary branch called ' tmp ' where Alpha is. 首先,标记分支的当前HEAD:我们需要移动该HEAD 而不修改Alpha ,所以让我们创建一个名为' tmp '的新临时分支,其中Alpha是。

     git checkout Alpha git checkout -b tmp 
  • Then we go back to an Beta HEAD commit with the right content. 然后我们回到具有正确内容的Beta HEAD提交。

     git reset --hard Beta 

That resets the index (and working tree) to the right content, but that also moves HEAD. 这会将索引(和工作树)重置为正确的内容,但这也会移动HEAD。 However, that moves tmp HEAD, not Alpha HEAD. 但是,这会移动tmp HEAD,而不是Alpha HEAD。

  • move back tmp HEAD to where mAlphaaster is, but without modifying the index or the working tree (which are representing what we need for a new commit) tmp HEAD移回到mAlphaaster所在的mAlphaaster ,但不修改索引或工作树(表示新提交所需的内容)

     git reset --soft Alpha 
  • make a new commit, on top of Alpha / tmp HEAD, which represents the right content (Beta HEAD commit content). Alpha / tmp HEAD之上创建一个新的提交,它代表正确的内容(Beta HEAD提交内容)。

     git commit -m "new commit, image of an old one" 
  • Finally, force Alpha to be where tmp is: one new commit later. 最后,强制Alphatmp位置:稍后再提交一次。

     git branch -M tmp Alpha git checkout Alpha git branch -d tmp 

Now a regular git push is enough, any collaborator can simply pull as usual, and still get the old reset content. 现在一个常规的git push就足够了,任何协作者都可以像往常一样简单地拉动,并且仍然可以获得旧的重置内容。

git push
c=$(git commit-tree Beta^{tree} -p Alpha -m 'foo')
test $c && git update-ref refs/heads/Alpha $c

git commit-tree creates a new commit, whose tree is the same with Beta's tip's and whose parent is Alpha's tip. git commit-tree创建一个新的提交,其树与Beta的提示相同,其父级是Alpha的提示。

git update-ref makes Alpha point at the new commit. git update-ref使Alpha指向新提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM