Merge subset of commits, replay rest from one branch to another

Rewritten Issue

After making a commit to origin/main, I need to rebase the feature branch on top of it. My goal is to achieve the following structure while adding a merge commit that includes the squash of V',W',X':

A - B - C (origin/main)
    \          
     V - W - X - <squash of V',W',X'> - Y'' - Z'' (origin/feature_branch)

Currently, my structure looks like this:

A - B (origin/main)
    \
     V - W - X (origin/feature_branch)
              \
               Y - Z (feature_branch)

After rebasing my feature branch on the commit to origin/main, the structure is now:

          V' - W' - X' - Y' - Z' (feature_branch)
         / 
A - B - C (origin/main)
    \
     V - W - X (origin/feature_branch)

How can I achieve my desired structure?

To achieve the desired structure, follow these steps:

  1. Checkout the feature branch: git checkout origin/feature_branch
  2. Create a new branch from the current position of the feature branch: git branch temp_branch
  3. Reset the feature branch to the commit before the rebase: git reset --hard origin/feature_branch
  4. Cherry-pick the commits V’, W’, and X’ from the temporary branch:
    git cherry-pick V'
    git cherry-pick W'
    git cherry-pick X'
    
  5. Merge the feature branch into the main branch with squash:
    git checkout origin/main
    git merge --squash feature_branch
    
  6. Commit the changes: git commit -m "Merge squash of V', W', X'"
  7. Push the changes to the feature branch: git push origin feature_branch --force

After following these steps, your structure should look like this:

A - B - C (origin/main)
    \          
     V - W - X - <squash of V',W',X'> - Y'' - Z'' (origin/feature_branch)

Note: Be cautious when using the --force flag, as it overwrites the remote branch. Make sure you have the necessary permissions and communicate with your team before using it.