Search code examples
gitgithubgit-rebasegit-squash

Git script to rebase and squash temporary commits


Of the few times I have squashed Git commits, it took some manual work to pick the previous commits I wanted to squash.

Is there some way to so this automatically - my goal is to squash all previous commits that have not already been pushed to a particular remote branch.

To elaborate, say I have 1 local branch called "dev" and 2 remotes, public and private. I commit and push all I want to the private remote, to a branch called "dev", let's call that private/dev. But on the public remote I want to keep things clean and tidy, and to keep one standard branch called "master", let's call that public/master. So like I said, for all the commits that have not already made it to the public remote master branch, I want to squash those into one big commit, and the push to public/master

How can I achieve that? Seems complicated.


Solution

  • You simply create a temporary branch via public/master (with public being the name of your public remote, and master - for instance - being the destination branch)

    And you use merge --squash (see "In git, what is the difference between merge --squash and rebase?")

     git checkout -b temp public/master
     git merge  --squash dev
     # since merge --squash does not produce a commit:
     git commit -m "squash dev"
     git push public temp:master
     git checkout dev
     git branch -d temp
    

    On the colon syntax, see "git push branch to a new repo with a different name" and the examples section of git push.
    It allows for pushing a local branch to a remote one with a different name.