Dong Nguyen
Git

Configs

git config --global user.name "Dong Nguyen"
git config --global user.email "[email protected]"
git config --global core.editor "nano"
git config --global pull.rebase false
git config --global pull.ff only
git config --global push.autoSetupRemote true

Reset history

git checkout --orphan temp
git add *
git commit -a
git branch -D main
git branch -m main
git push -f origin main

Delete all old branches

git fetch --all --prune

# even tags
git fetch --all --tags --prune

Push a new git repo which doesn't have remote version

git remote add origin [email protected]:ndaidong/repo.git
git add -A
git commit -a -m 'Initial'
git push -u origin master

Change remote url

git remote set-url origin [email protected]:ndaidong/repo.git

Edit branch name

git branch -m old-branch new-branch

# for remote repo
git push origin --delete old-branch
git push origin new-branch

Remove branch

git branch -D branch-name

Tag

git tag -a vVERNUM -m "Some message"

View logs

git shortlog -s -n

Accidentally committed all changes to the master branch

# make sure you commit or stash your changes first, or all will be lost!
git branch feature-branch
git reset HEAD~ --hard
git checkout feature-branch

Added a wrong file in the repo

# if not committed
git reset /assets/img/misty-and-pepper.jpg

# otherwise
git reset --soft HEAD~1
git reset /assets/img/misty-and-pepper.jpg
rm /assets/img/misty-and-pepper.jpg
git commit

Spelled last commit message wrong

# if forgot to add a file to that last commit, add it now
# git add missed-file.txt
git commit --amend

Undo commit

# Don't remove staged files
git reset --soft HEAD^

# Remove staged files
git reset HEAD^

# undo commit and lose all the changes
git reset --hard HEAD^

Best practices

Rebase your feature branch often

git checkout master
git pull
git checkout feature-xyz  # name of your hypothetical feature branch
git rebase master  # may need to fix merge conflicts in feature-xyz

Also do this before merging, then:

git checkout master
git pull
git merge feature-xyz

Squash commits before merging

git rebase -i HEAD~20  # look at up to 20 commits to consider squashing
# edit commit 
git commit --amend
# force rewrite history
git push -f

7 habits for better git usage

  • everything begins with an issue
  • always check the current branch before making any changes
  • run "git pull" as often as possible
  • commit as soon as possible
  • commit should be referenced to the related issues
  • never push changes to the main branch directly
  • always keep the tree tidy by cleaning old branches

Remove all ignored

git clean -Xfd