Useful git commands when handling PR

Some notes regarding useful git commands when doing / receiving code review.

Summary

Update branches (as a reviewer)

When branch can be fast-forwarded

# Fetch branches only
git fetch origin

# Fetch branches and prune remotely deleted branches
git fetch origin --prune

# Update master branch without checkout. This assumes that fast forward is possible
git fetch origin master:master # Cannot do it when "master" is the active branch

Sources:

When branch cannot be fast-forwarded

# When remote history is rewritten (git rebase)
git checkout feature/update-countries
git fetch origin feature/update-countries
git reset --hard origin/feature/update-countries

Display history

git log

# Basic
git log

# Compact
git log --oneline

# Graph
git log --graph

# Multiple branches
git log --oneline --graph master feature/update-countries

Sources:

git merge-base

# Find common ancestor
git merge-base master feature/update-countries

Sources:

Content comparison

git diff

# Compare HEAD with master branch
git diff master # same as git diff master HEAD

# Compare feature branch with master from common ancestor
git diff $(git merge-base master feature/update-countries) feature/update-countries

# Compare HEAD with master from common ancestor
git diff $(git merge-base master HEAD) HEAD
# Same as above but shortcut available from git 2.30.0
git diff --merge-base master

# Show names only
git diff --name-only master

# Show names+status only
git diff --name-status master

# Magic combo:
git diff --master-base --name-status master

# Show diff in commit range
git diff HEAD..HEAD~2

# Fun fact:
git diff HEAD~1..HEAD~2
# is the same as
git show HEAD~1

Sources:

git blame

# Show last modifications per lines
git blame --color-lines countries.json

Sources:

Others

Fixing past commit with interactive rebase

# Find starting point
git log --oneline --max-count=<N>

# Start interactive rebase
git rebase --interactive <starting point>

# Define the commits we want to edit in the text editor

# Do changes when the rebase stops at requested commit

# Amend commit and continue rebase
git commit --amend
git rebase --continue

Sources:

Cherry pick last N commits to another branch

git checkout <target branch>
git log --reverse --pretty=%h --max-count=N <source branch> | xargs git cherry-pick

Sources:

Branches management

# Display all branches, including remote references
git branch -a

# Display current branch name only
git branch --show-current

# Mass branch deletion
git branch --list <pattern> | xargs git branch -d

Sources:

Miscellaneous

Update git on Ubuntu Focal

sudo add-apt-repository ppa:git-core/ppa
sudo apt update
sudo apt install git

git --version

Source: https://git-scm.com/download/linux