How to remove previous commits and keep the ones that are my changes?

I have a single branch (called my-working-branch) that I worked on that have several commits of my changes. When I committed and push my changes to master, thus created a pull request for the reviewer to merge, inside the pull request I saw my commits which I want to keep and merge to master along with so many other previously committed changes before mine that I've never changed and was committed by a different author. I am using Bitbucket and so some commits are greyed out with an "M" assuming meaning that commit was merged in master already and some without an "M" and isn't greyed out assuming not merged like my commits from my-working-branch.

Now that you understand my situation, what I want to do is keep the first four recent commits that I have in the pull request and remove all of the other commits within my-working-branch (no one else worked on this branch and made changes to it except me) that seems to be added in a previous date that shows within my pull request I created. I've looked at other stackoverflow questions regarding using the rebase command but since from what I understand it's a destructive command and would rewrite history. I would be fine using it if this only affects my local branch and the pull request to reflect that but I wanted to be absolutely sure this is the right direction to go in as in squashing all those previous commits and keep only the first recent four commits that I have changed which should keep changes to just those four commits and the rest not shown in the pull request to then merge to master.

What would be the appropriate action in this situation?

For example: (d74981d0dcd..041727236cb first four commits to keep and the rest after that I want to remove from the pull request)

enter image description here

1 answer

  • answered 2019-01-11 05:40 VonC

    regarding using the rebase command but since from what I understand it's a destructive command and would rewrite history

    That does not matter here, since you are the only one working on that PR branch.

    Note: you don't push a PR branch to master, but to the same PR branch on the remote side, and make a PR from that branch, not from master.

    Add the remote "upstream" to reference your original repo, and rebase your branch on top of the upstream/master

    git remote add upstream /url/original/repo
    git fetch upstream
    git checkout my-working-branch
    git rebase upstream/master
    git push --force -u origin my-working-branch

    If you already have a PR from your origin/master branch then do instead

    git push --force origin my-working-branch:master

    The rebase option would be:

    git rebase -i --onto upstream/master

    That will:

    • checkout my-working-branch,
    • reset it to upstream/master, and
    • replay all commits after 2f1 (2f1 excluded), up to my-working-branch HEAD which was d74.