I cloned the repository, did a checkout of one of the earlier commits and then did some changes. Now I want to make this as HEAD (commit/push and make it HEAD) - the newer commits will become obsolete.
How can I do this?
This is not a duplicate of How to move HEAD back to a previous location? (Detached head), because I first want to commit the changes and then mark that new commit as HEAD.
HEAD is just a reference to the commit you currently have checked out; no more, no less.
Checking out a particular commit moves HEAD to that commit. Making a new commit moves HEAD to your new commit.
In your example:
When you checked out the earlier commit of the cloned repo, you moved HEAD to that earlier commit. If you then made a new commit, HEAD was moved to this new commit. If you haven't subsequently checked out any other branches/commits, HEAD will still be there pointing to your new commit.
If I'm interpreting your scenario correctly, it sounds as though you might've directly checked out an earlier commit using git checkout <commit-hash>
or similar. If so, you would be in a detached HEAD state. This does not alter the existing commit history. Also, you generally don't want to be making new commits in this state since you'll have no way of getting back to them once you switch branches. You could add another branch in this state and commit safely from there, but it sounds as though you're actually intending to revert the changes in the remote repo, not make new changes and run them parallel to the existing history.
What you're probably looking for is either git reset --hard
or git revert
.
git reset --hard
removes commits from the current branch. So let's imagine that the earlier commit you want to work on is two commits behind the current branch tip. When you clone the repo, rather than running git checkout
on this commit, you could run git reset --hard HEAD~2
(where HEAD~2
denotes two commits earlier than where the HEAD is currently pointing). This brings the branch tip back to the earlier commit and any new commit will become the new branch tip. Be careful with this command, as it will (almost) permanently discard the original commits that came after the commit you reset to.
The alternative, git revert
, achieves a similar goal without forever discarding the original later commits. It looks at the earlier commit you want to revert to and, rather than simply rolling back to it and discarding the later commits, it creates a copy of the earlier commit and places it after the existing ones in the commit history.
I might have completely misunderstood your question, but hopefully this was somewhat useful!
A great resource explaining HEAD
, git reset
, git checkout
and git revert
can be found here.