Skip to main content

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:

  1. Switch to the target branch:

    git checkout <target-branch>
  2. 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.

  3. Apply the desired commits to the target branch:

    git cherry-pick <commit-hash>

    Repeat this step for every commit you want to include.

  4. Resolve conflicts (if any): Fix the conflicts manually. Continue the cherry-pick process:

    git cherry-pick --continue
  5. 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:

  1. Switch to the branch you want to update:

    git checkout <target-branch>
  2. Start an interactive rebase with the source branch:

    git rebase -i <source-branch>
  3. 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-Message

    Remove lines for commits you don't want to include. Alternatively, replace pick with edit to modify the commit contents.

  4. Complete the rebase process: Save and close the editor to start the rebase. Resolve conflicts if they occur:

    git rebase --continue
  5. 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.

  1. Switch to the target branch:

    git checkout <target-branch>
  2. Apply specific commits:

    git cherry-pick <commit-hash>

    Repeat this for each commit you want to include.