Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

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. Without merge.

I understand that every git commit - on a logical level - is a complete and immutable project state + some metadata. So I just need branch Alpha to have the same state of files like Beta does.

It would be another commit (with different hash), and one branch tip wouldn't reference another.

like image 955
baur Avatar asked Aug 18 '18 06:08

baur


People also ask

How do I commit changes from one branch to another in git?

Open the Git tool window Alt+9 and switch to the Log tab. Locate the commit containing the changes you want to cherry pick. on the toolbar). Select the required commit.

Which of the following command allows us to point to a past committed state in the repository?

The git checkout command is used to update the state of the repository to a specific point in the projects history.


2 Answers

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 update-ref makes Alpha point at the new commit.

like image 76
ElpieKay Avatar answered Oct 09 '22 06:10

ElpieKay


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.

  • 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.

    git checkout Alpha
    git checkout -b tmp
    
  • Then we go back to an Beta HEAD commit with the right content.

    git reset --hard Beta 
    

That resets the index (and working tree) to the right content, but that also moves HEAD. However, that moves tmp HEAD, not 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)

    git reset --soft Alpha
    
  • make a new commit, on top of Alpha/tmp HEAD, which represents the right content (Beta HEAD commit content).

    git commit -m "new commit, image of an old one"
    
  • Finally, force Alpha to be where tmp is: one new commit later.

    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
like image 44
VonC Avatar answered Oct 09 '22 08:10

VonC