Tesuji
Tesuji

Reputation: 1675

How to reset head of master branch to a previous commit with GitPython

I want to essentially revert changes in my master branch. I am able to find my history of commits by doing:

import git
repo = git.Repo('repos/my-repo')
commits = repo.iter_commits('master',max_count=10)

but I am unsure as to how to point the head to, lets say, a commit where the message contains "reset to me". I am aware of repo.git.reset('--hard'), but I don't know how to properly use it. Thank you

Upvotes: 1

Views: 825

Answers (1)

Krantisinh
Krantisinh

Reputation: 1729

If you know the commit number as in Latest Commit = 1, Second = 2, etc. then you can use ~ operator along with HEAD to point to the commit. HEAD~1 = Latest commit, HEAD~2 = second latest commit.

Hence to remove the latest commit, you can use:

import git
repo = git.Repo('repos/my-repo')
repo.head.reset('--hard HEAD~1', index=True, working_tree=True)

Refer this question to learn more about how to identify a commit.

Upvotes: 1

Related Questions