Git tips
Contents
1 Create a new repo in VSC and push it to GitHub
# first, create a repo on the Github webpage
# then, add the repo in VSC
git remote add origin https://github.com/XiaomoWu/<your-repo>.git
# create the main branch in VSC
git branch -M main
# push the main branch to Github
git push -u origin main
2 Go back to a previous commit and start new from there
Stash or commit your working tree
git checkout [commit]
.- You’ll be on a detached HEAD now (i.e., leaving the main branch).
git switch -c [new-branch-name]
- If you want to make new edits, it’s recommend to create a new branch. As show below, I was first at C4, and then
switch
ed to Commit 2. From there, I create a new branch “test”. This is the resulting commit graph: switch
is a newly introduced command. It’s the same ascheckout
but it’s used on “branches”.
- If you want to make new edits, it’s recommend to create a new branch. As show below, I was first at C4, and then
(option)
git restore .
- If you’re on a test branch but want to discard all changes (e.g., you want to go to the latest commit without saving current changes), use the
restore
command.
- If you’re on a test branch but want to discard all changes (e.g., you want to go to the latest commit without saving current changes), use the
git merge main
.- When you’re happy with your test branch, it’s time to merge it to the main. First, make sure you’re on the main branch. And then run the merge command. After resolving all conflicts, you can commit.
- In the following figure, the last commit in test is “commit test”. I merge it to main and here’s the results.
Why not use "reset" or "revert"?
revert
- revert does not take you to a previous commit. It only revert the required single commit.
- For example, if your commit history is c1->c2->c3 (HEAD) and you revert c2, you may still keep changes introduced by c3!
- After reverting the given commit, it will compare your current state with the PARENT of that commit whose changes you are reverting. If current state and that PARENT conflict, git will indicate that.
- The revert command requires “your working tree to be clean (no modifications from the HEAD commit)” (see documentation here).
reset
- reset does take you to a previous commit, but you lose all the commits after the reset point.
- Even if you use
--soft
instead of--hard
, you’ll still lose commits. The difference is that--soft
will leave the changes to your work tree. - You may find yourself not losing commits after using
reset
, but that’s only because you aren’t on the main branch when youreset
.
- Even if you use
switch
- Unlike revert or reset, switch lands you on a totally detached branch. Whatever do you there has no impact on any existing commit. That’s why we use switch.
- If we need to keep our changes, just create a new branch and merge it to main.