gitgit-rebasegit-squash

How can I merge all my local commit before rebase my local branch from the main?


When I work in a team and must push my local branch to the remote main, I rebase firstly my local branch to master with this simple command:

git fetch && git rebase origin/main

But when I do that, all my local commits are applied and conflicts occur because the code of these previous commits are different to my last local state (saved in my last commit). And solving conflicts of my own commits takes a lot of (useless) time...

I’m afraid to do a mishandle, so I search for some help here. My question:

How can I merge all my local commit into one before a rebase ? And thanks that, when I rebase, there is just one commit to apply

I don't know if its the better approach, feel free to give my advise. :) Thank you!


Solution

  • #!/bin/sh
    ## Usage: ./script <branch>
    git fetch origin main
    git checkout origin/main
    git merge --squash $1
    # You’ll want to modify the commit message here
    git commit
    git branch --force $1 HEAD
    # Return
    git checkout -
    

    Testing

    I compared this with running git rebase <upstream> on a feature branch and I got the same tree ids from the two approaches.

    The squash also squashed the range that I expected it to, according to the default commit message (it is quite verbose).

    Caveat about the commit message

    The default commit message of git merge --squash is much less nice than the one you get from git rebase --interactive with squash.

    Misc.: reapplying conflicts

    If you are just tired of fixing the same merge conflicts over and over again when using git-rebase(1) then you might want to look into git-rerere(1).