Skip to content

Instantly share code, notes, and snippets.

@boolfalse
Created March 7, 2022 23:10
Show Gist options
  • Save boolfalse/e6dad72276b2a3703fb53a1730314bd5 to your computer and use it in GitHub Desktop.
Save boolfalse/e6dad72276b2a3703fb53a1730314bd5 to your computer and use it in GitHub Desktop.
GitHub: Clean-up latest pushed commits on the master branch

Problem:

Let's assume, that we have a GitHub repository, and there we have some commits. Also in the table below we have a list of all commits, which are done by the project's developers. Here are project's developers: USER_1, USER_2, USER_3, USER_4, and COLLABORATOR sequentially.

BRANCH master HASH USER
commit 9 hash999 COLLABORATOR
commit 8 hash888 COLLABORATOR
commit 7 hash777 COLLABORATOR
commit 6 hash666 COLLABORATOR
commit 5 hash555 COLLABORATOR
commit 4 hash444 USER_4
commit 3 hash333 USER_4
commit 2 hash222 USER_4
commit 1 hash111 USER_4

As we can see, "hash111"-"hash444" commits are done by some different users (USER_1, USER_2, USER_3, USER_4), and "hash555"-"hash999" commits are done by COLLABORATOR.

  • We know that:

"master" branch is the default branch of the project. no one can delete "master" branch. COLLABORATOR is just a simple collaborator of the project.

  • Our goal is to clean up all the latest commits "hash555"-"hash999", which are done by COLLABORATOR on the "master" branch.

Solution:

# make sure, that you are on the "master" branch
git checkout master

# set up the user config data
git config user.email "correct.email@gmail.com"
git config user.name "correct_username"

# remove all the commits on local which are done by COLLABORATOR
git reset --soft hash444
git reset
git checkout .

# create a new temporary branch and switch to it with current HEAD
git checkout -b temp
BRANCH master BRANCH temp HASH USER
commit 9 hash999 COLLABORATOR
commit 8 hash888 COLLABORATOR
commit 7 hash777 COLLABORATOR
commit 6 hash666 COLLABORATOR
commit 5 hash555 COLLABORATOR
commit 4 commit 4 hash444 USER_4
commit 3 commit 3 hash333 USER_4
commit 2 commit 2 hash222 USER_4
commit 1 commit 1 hash111 USER_4
# make some changes to that temporary branch and commit them
git add .
git commit -m "temp changes"
git push origin temp

# switch back to the "master" branch and rebase the temporary branch on it
git checkout master
git rebase temp
git push origin master

# remove the temporary branch from the remote and local
git push origin temp --delete
git branch -d temp

# see the result
git log --graph --oneline --decorate --all

Author:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment