I want to take the time to clarify some important Git commands. Even though, I know it. But, if you don’t touch it for a period of time, you will get unfamiliar with it. So I think it is a good way for me to document my memory and research it for future reference.
Git Reset
I was running into this situation in which I didn’t mean to include all the node_modules’s files onto the stage. How could I undo my git commit here?
I had two options -> Hard reset | Soft reset.
(1). Run git reset –soft HEAD~1 will undo your previous commit but save your created files.
(2). Run git reset –hard HEAD~1 will undo your previous commit and also delete your created files( So we need to double-check before we run this line ).
Extra: For any reason, you want to undo our ‘git add’, just run git reset <file name> or git reset to unstaged all previous changes.
Git Push
I went down this issue a little further. If we accidentally ran a git push to our git repository and we want to undo our push action. We could do git push -f origin last_know_good_commit:branch_name to rewind our pushed files. In my case, I ran git push -f origin with my last good commit id which was the commit called ‘first commit’ and my branch name. After I rewound my push action, I could follow the ‘reset’ methods to unstaged my commit and undo my ‘git add’.
However, during ‘git pull’ from the remote repo, we might face this kind of issue(below). After research, I figured out that it is a Git’s pre-configured template that opens through the default editor(vi/vim).
To quit this window, we need to type ‘:wq‘ + Enter. ‘:wq‘ stands for write and quit. Otherwise, we can press ‘i‘(insert) -> write your message => press ‘esc‘(escape) to quit the editor. TBH, I feel it is a none sense part, but somehow we have to deal with it. So whatever…
Branch conflict
Git pull = Git fetch + Git merge.
You can fetch your remote repo’s metadata but it will not show in your code. You have to do git merge FETCH_HEAD to merge those changes. Merge always goes on the local repo, whereas, Pull and Fetch go between local and remote.
Conflict happens during git merge. Merge always happens from the higher commitment towards the lower one.
Rebase?
In the graph above, I am on my local sub-branch commit( purple line ). I have noticed that the remote master has something new added. So I ‘git pull’ the updated remote branch to my local master( ‘3’ ). The issue is that the HEAD of my current sub-branch in local is still pointing to ‘2’ and I need to reassign it to a new base( ‘3’ ). I check out my sub-branch and do ‘git rebase master'( master step 2 ). In master step 3, I want to combine the sub-branch with the local master. So, I get back to the local master and run ‘git rebase <name of sub branch>’ to put the sub-branches commits right after the current branch. Eventually, I can git push all the changes back to the remote.