3

I will develop my app in branch dev and provide the "best so far" (a release on GitHub) on a branch public.

The branch dev will have commits c964dea, 06cf8ee, 396b4a3 and 9be7fdb. I would like to squash them into a single commit on branch public (leaving them as-it on the branch dev).

Is this possible?

I saw many questions and answers about squashing commits, but none of tehem seemed to address the problem of "squashing to another branch".

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • Conceptually, just squash into one commit- then cherry-pick the commit onto the target branch. Or cherry-pick the 4 commits to the target branch and then squash. There may be a one liner for this but I can't think of it at the moment. – TTT Sep 20 '21 at 18:55
  • I'm pretty sure this is what you want: [Cherry-pick and squash a range of commits into a subdirectory or subtree](https://stackoverflow.com/questions/35123108/cherry-pick-and-squash-a-range-of-commits-into-a-subdirectory-or-subtree) – TTT Sep 20 '21 at 18:59
  • @TTT well not exactly - I want to do that to another branch. Calum's answer is on spot (I need to test that with back-and-forth branches but I thnk it will be fine) – WoJ Sep 22 '21 at 09:13
  • Yeah- The question I linked to is slightly different. I should have mentioned that the accepted answer is probably what you want. Basically if you use -n parameter with cherry-pick you can avoid the additional rebase afterwards. But if Calum's answer here is correct, then maybe `public` didn't exist yet. (I just assumed branch `public` already existed which is why cherry-pick with `-n` would be slightly faster). – TTT Sep 22 '21 at 14:05

2 Answers2

1

Create and switch to a new branch from dev.

git switch -c <new-branch>

It'll be identical to dev at this point but now you can squash the commits without changing dev. Start an interactive rebase.

git rebase -i <first-commit>

Then set all the commits to squash.

Calum Halpin
  • 1,945
  • 1
  • 10
  • 20
1

you probably want first to cherry pick individual commits, if they are not in sequence by running :

git cherry-pick <commitSHA>

You will have a sequence of cherry-picked commits on your feature branch. after that you want to do interactive rebase on your branch from all the commits you cherry-picked.

git rebase -i HEAD~<n+1>

where n is going to be the number of cherry-picked commits. mark all the commits with s except the last one. s, squash = use commit, but meld into previous commit

if all your commits that you want to cherry-pick are in sequence, then it is easier :

git cherry-pick A^..B

where A and B are first and last commits to be cherry-picked. After that rebase them.

Dmitry
  • 353
  • 2
  • 8