Git: Managing Branches and Commits
Scenario 1: Cherry-pick Specific Commits into Another Branch
If you want to move specific commits from one branch to another branch (excluding main), you can use git cherry-pick.
Steps:
-
Switch to the target branch:
git checkout <target-branch> -
Find the commit hashes from the source branch:
git log <source-branch>Note down the commit hashes (e.g.,
abc123) that you want to move. -
Apply the desired commits to the target branch:
git cherry-pick <commit-hash>Repeat this step for every commit you want to include.
-
Resolve conflicts (if any): Fix the conflicts manually. Continue the cherry-pick process:
git cherry-pick --continue -
Verify the updates in the target branch:
git log
Tip:
If the commits are sequential, you can apply multiple commits in one step:
git cherry-pick <start-commit>^..<end-commit>
Scenario 2: Rebase a Branch without Including Recent Commits
If you have a GitOps repository with multiple stages (and no main branch), and you want to rebase a branch with an older state onto another branch without including the latest commits, you can perform a selective rebase.
Steps:
-
Switch to the branch you want to update:
git checkout <target-branch> -
Start an interactive rebase with the source branch:
git rebase -i <source-branch> -
Select the commits to keep: A text editor will open, showing the list of commits in this format:
pick <commit-hash> Commit-Message
pick <commit-hash> Commit-MessageRemove lines for commits you don't want to include. Alternatively, replace
pickwitheditto modify the commit contents. -
Complete the rebase process: Save and close the editor to start the rebase. Resolve conflicts if they occur:
git rebase --continue -
Verify the updated branch:
git log
Alternative: Cherry-pick Specific Commits
If you prefer not to use rebase, you can manually select commits to include using git cherry-pick.
-
Switch to the target branch:
git checkout <target-branch> -
Apply specific commits:
git cherry-pick <commit-hash>Repeat this for each commit you want to include.