gitbitbucketsourcetree

How to squash commits on Bitbucket after they have been pushed?


I am currently working on a project with multiple others. The problem is that we created a fork of an existed project and need to squash all our commits from after the forking process to a single commit for a pull-request on Bitbucket.

Is there any way (preferably using SourceTree, otherwise terminal) to squash already pushed commits to a single commit, such that the history within Bitbucket of all the commits are also only that one commit plus the commits which were already there before we forked the project?

Take as example just a simple project with a few files in only a master branch.


Solution

  • Found a nice summary of the posted answers. This one is a bit more clear: squash pushed commits. It will require creating a second branch upon the creation of the fork. This second branch can have as many pushes to the remote server as needed.

    1. Create a new personal branch that will be squashed.

      # Start with the existing personal branch that contains all of your commits.
      $ git checkout {ExistingBranchName}
      # Create a new personal branch that will be squashed.
      $ git checkout -b {BranchName}
      
    2. Identify the first commit where your personal branch diverged from an existing CEF branch.

      # Replace {BranchName} with your new branch name.
      # Replace "master" with a different CEF branch as appropriate
      # (e.g. "2272", "2171", etc).
      $ git merge-base {BranchName} master
      
    3. Start an interactive rebase using the commit hash returned from step 2.

      $ git rebase --interactive {hash}
      

      This will launch a text editor with a list of all commits in your personal branch. It should look something like this:

      pick 59d2a23 Initial implementation
      pick 752ae4c Add more features
      pick cd302a3 Fix something
      pick 5410de3 Fix something else
      
    4. Change all but the first line to say squash instead of pick. The contents should now look like this:

      pick 59d2a23 Initial implementation
      squash 752ae4c Add more features
      squash cd302a3 Fix something
      squash 5410de3 Fix something else
      
    5. Save the changes and close the file (Can be done by pressing esc and type: :wq.

      A new file will now open containing the commit messages from all of the commits. Reword the commit message then save the changes and close the file.

    6. Push the modifications to your personal remote repository.

      # If the branch has already been pushed to the remote repository
      # you will need to add the  `--force` argument.
      git push origin {BranchName}
      # or git push origin {BranchName} --force