Git: Delete last x commits on github/gitlab

Hi,

this post describes if something went wrong and you want to delete the last n commits on gitlab.

Make a fresh clone of your repository

michael@debdev ~ # git clone git@gitlab.com:MyUser/MyProject
michael@debdev ~ # cd MyProject

Determine the last commit you want to preserve/your HEAD should be

michael@debdev ~/MyProject # git log 
commit f526d79a10fbdc702e3c7c6b148a53289868731b (HEAD -> main, origin/main, origin/HEAD)
Author: michael@debdev
Date:   Thu Jul 4 18:48:38 2024 +0200

    Doc update

commit dc67e928afc7092daa21b33fa8193a96b76375fe
Author: michael@debdev
Date:   Thu Jul 4 18:40:10 2024 +0200

    New File

commit 3023fb10bcde2faf390eb9b4f69b538711daba40
Author: michael@debdev
Date:   Thu Jul 4 18:24:58 2024 +0200
    Fixes

....
....

In the case commit 3023fb10bcde2faf390eb9b4f69b538711daba40

michael@debdev ~/MyProject # git reset --hard dc67e928afc7092daa21b33fa8193a96b76375fe

Then push it pack with -f switch

michael@debdev ~/MyProject # git push -f origin main

If an error

remote: GitLab: You are not allowed to force push code to a protected branch on this project.

occure then your respository is protected. Unprotect it

gitlab unprotect repository
gitlab unprotect repository

push the repository and reprotect the repository.

Michael

Advertisment to support michlstechblog.info

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.