Tuesday, March 16, 2021

Command 'git reset'



To review, git reset is a powerful command that is used to undo local changes to the state of a Git repo. Git reset operates on "The Three Trees of Git". These trees are the Commit History (HEAD), the Staging Index, and the Working Directory. There are three command line options that correspond to the three trees.

If your commit is only a 'local commit':

1. It would show up in output of command 'git log'.
2. But it won't show up on the 'github.com' at URL:
https://github.com/${userName}/${repoName}/commits

And command "git status" would tell you how many local commits you are having:

$ git status

On branch main
Your branch is ahead of 'origin/main' by 1 commit.
  (use "git push" to publish your local commits)
... 

Few additional information 'git status' would tell you in case you are not sure about what is wrong or what to do:

$ git status

On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
	new file:   abc.pdf
	new file:   xyz.pdf
...

$ git status

On branch main
Your branch is ahead of 'origin/main' by 1 commit.
    (use "git push" to publish your local commits)

Changes not staged for commit:
    (use "git add/rm <file>..." to update what will be committed)
    (use "git restore <file>..." to discard changes in working directory)

Use 'git reset --hard' to throw away any 'local commits'

If you want to go to a specific reference other than a remote branch:

$ git reset --hard <commit hash, branch, or tag> 

For example:

"git log" will tell you how many local commits are you ahead of the last pushed commit:

$ git log

commit c...d (HEAD -> main)
Author: ashish <abc@xyz.com>
Date:   Mon Mar 15 09:32:07 2021 +0530

    tech books feb 2021

commit 6...9
Author: ashish <abc@xyz.com>
Date:   Mon Mar 15 09:26:59 2021 +0530

    tech books feb 2021

commit 2...3
Author: ashish <abc@xyz.com>
Date:   Mon Mar 15 09:21:32 2021 +0530

    tech books feb 2021

commit 5...9
Author: ashish <abc@xyz.com>
Date:   Mon Mar 15 09:12:58 2021 +0530

    tech books feb 2021

commit 9...7 (origin/main, origin/HEAD)
Author: ashish <abc@xyz.com>
Date:   Mon Mar 15 08:50:50 2021 +0530

    tech books

-- -- --

$ git reset --hard 9...7

HEAD is now at 9...7 tech books
 
$ git status

On branch main
Your branch is up to date with 'origin/main'.

nothing to commit, working tree clean

-- -- --

References

Ref 1: Head vs Head vs Head

Ref 2: What does caret character means in 'git reset head'

Ref 3: Throw away local commits in Git

Ref 4: Atlassian - git reset
Tags: Technology,GitHub

No comments:

Post a Comment