Search code examples
gitgithub

Git safe restore to old commit and return to latest


I have question related to git

I need to do following :

  1. Restore repository to state as it was on some specific old commit
  2. Make branch from this state and add some changes to the branch
  3. Return to master and restore to latest state

What is correct and safe way to do so ? I think about first option

git revert <mycommit_name> 

or

git reset --soft <mycommit_name>

Thanks in advance


Solution

  • I think you're asking how you do work based off an older version.

    For example, you have commits like so...

    * C [master] - added the cool thing
    |
    * B - fixed that annoying bug
    |
    * A - did that mundane task
    

    You can see a view of your repository like this with git log --graph --decorate --all --oneline.

    Now, for whatever reason, you want to do work off commit B. Make a branch from commit B. A branch is nothing more than a label on a commit. git-branch optionally takes a starting point for the new branch.

    $ git branch B_branch B
    
    * C [master] - added the cool thing
    |
    * B [B_branch] - fixed that annoying bug
    |
    * A - did that mundane task
    

    Now you have B_branch at commit B. Switch to that branch and make some commits. They will be on top of B. master will be unaffected.

    $ git switch B_branch
    ...work work work...
    $ git commit -m 'B commit 1'
    ...work work work...
    $ git commit -m 'B commit 2'
    
    * E [B_branch] - B commit 2
    |
    * D - B commit 1
    |
    |  * C [master] - added the cool thing
    | /
    * B - fixed that annoying bug
    |
    * A - did that mundane task
    

    And when you're done, switch back to master. git switch master.