Search code examples
gitgithubversion-controlversionbranch

GitHub: create a branch off an older version of main branch


I currently work for a company that has a main branch, development branch, and individual task branches (see link) Our Branches Workflow. Changes were recently made to the main branch which caused a series of broken functions, which came from a push from dev branch. Some parts of our main branch works better than the old one though.

Because both team branches aren't fully functional, is there a way to create a branch off of an older version of main? Also, where can I view older versions of a branch in GitHub?

We could technically restore an old version of main and make a branch, but that would destroy some good code that has been pushed recently.


Solution

  • Also, where can I view older versions of a branch in GitHub?

    Viewing older versions of a branch is all about exploring the commit history.

    Commands you need:

    1. git branch [New_Name] [Commit_Hash] - Create a new branch based on a specific point in history.
    2. git cherry-pick [Commit_Hash] - Apply changes from a specific commit (from a different branch) to the current branch. git-cherry-pick

    One for to go back, and the other one to pick the good commits that you want to keep.


    A simplified scenario to explain the overall process:

    1. git switch main.

    2. git log --oneline - To see the commit history of the main branch.

      4888ee1 (HEAD -> main) Merge branch 'dev'
      1a2ae1c (dev) 3rd commit (dev)
      827bd7e 2nd commit (dev)
      940b5cf 1st commit (dev)
      3d7367c 2nd commit (main)
      90aef92 1st commit (main)
      
    3. We want to go the "2nd commit (main)" state of the main branch. So, git branch main_fix 3d7367c.

    4. git switch main_fix and then git log --oneline:

      3d7367c 2nd commit (main)
      90aef92 1st commit (main)
      
    5. Some parts of our main branch works better than the old one

      Lets say "2nd commit (dev)" was the good one. So, git cherry-pick 827bd7e, then resolve conflicts (pick what you want to keep), and git add . and finally git cherry-pick --continue.

    6. git log --oneline:

      5187548 (HEAD -> main_fix) 2nd commit (dev)
      3d7367c 2nd commit (main)
      90aef92 1st commit (main)
      

    Extra: Sometimes, the official docs can be too confusing. Here is a simplified version of Git if you want.