Skip to content

Git Productivity - LazyGit, TUI & Aliases

ROLE: HPN (Workflow Optimization).
AUDIENCE: Engineers muốn tăng tốc Git workflow 10x.

Bạn dùng Git mỗi ngày. Nhưng bạn có đang dùng nó hiệu quả? Module này giới thiệu các tools và configurations biến bạn thành Git power user.


🎯 Mục tiêu

Sau module này, bạn sẽ:

  • Dùng LazyGit/Tig để browse và stage nhanh hơn 10x
  • Setup HPN Standard Aliases cho commands phổ biến
  • Configure beautiful diffs với delta hoặc diff-so-fancy

🖥️ Terminal UIs (TUI)

Tại Sao Dùng TUI?

TaskCommand LineTUI
Stage single linegit add -p → navigate hunksClick/select line
View commit diffgit show abc123Navigate with arrows
Interactive rebaseMental model of commit orderVisual drag & drop
Branch switchinggit branch, git switchSee all, select one

LazyGit - The Modern Choice

bash
# Install
# macOS
brew install lazygit

# Windows
winget install lazygit
# or
scoop install lazygit

# Ubuntu
sudo add-apt-repository ppa:lazygit-team/release
sudo apt update
sudo apt install lazygit

# Run
lazygit
# or shortcut (add to shell config)
alias lg='lazygit'

Key Features:

  • Real-time diff preview
  • Stage/unstage individual lines (hunks)
  • Interactive rebase with visual reorder
  • Cherry-pick across branches visually
  • Built-in merge conflict resolution

Essential Keybindings:

KeyAction
spaceStage/unstage file or hunk
aStage all
cCommit
pPull
PPush
?Help
qQuit
[/]Switch panels
enterView file/diff
dDrop/delete
┌─────────────────────────────────────────────────────────────┐
│ LazyGit Layout                                              │
├──────────────┬──────────────────────────────────────────────┤
│   Status     │                                              │
│   Files      │              Diff Preview                    │
│   Branches   │                                              │
│   Commits    │                                              │
│   Stash      │                                              │
└──────────────┴──────────────────────────────────────────────┘

Tig - The Classic

bash
# Install
# macOS
brew install tig

# Ubuntu
sudo apt install tig

# Windows (via Git Bash or WSL)
# Included in Git for Windows or install via package manager

# Run
tig           # Interactive log
tig status    # Interactive status
tig blame     # Interactive blame
tig refs      # Browse references

Tig Modes:

CommandMode
tigMain view (log)
tig statusStatus view
tig blame fileBlame view
tig refsRefs view
tig stashStash view

Navigation:

KeyAction
j/kMove down/up
enterOpen/expand
qBack/quit
uStage/unstage file
!Revert file
/Search
rRefresh

LazyGit vs Tig

FeatureLazyGitTig
UI StyleModern panelsClassic ncurses
Learning curveLowerHigher
Line-by-line staging✅ Excellent✅ Good
Interactive rebase✅ Visual❌ Limited
CustomizationConfig file.tigrc
SpeedFastVery fast
MemoryHigherLower

HPN RECOMMENDATION

Dùng LazyGit cho daily work - intuitive hơn, visual rebase tuyệt vời. Dùng Tig khi cần browse large repos nhanh hoặc trên remote servers.


🚀 HPN Standard Aliases

The Power of Aliases

Thay vì gõ git log --oneline --graph --all --decorate, gõ git lg.

Setup Aliases

bash
# Method 1: Git config
git config --global alias.lg "log --oneline --graph --all --decorate"

# Method 2: Edit ~/.gitconfig directly
[alias]
    lg = log --oneline --graph --all --decorate

HPN Standard Alias Collection

Thêm vào ~/.gitconfig:

ini
[alias]
    # ═══════════════════════════════════════════
    # STATUS & LOG
    # ═══════════════════════════════════════════
    
    # Short status
    s = status -sb
    
    # Beautiful log graph
    lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
    
    # Log with stats
    ll = log --pretty=format:'%C(yellow)%h%Cred%d %Creset%s%Cblue [%cn]' --decorate --numstat
    
    # Log today's commits
    today = log --since=midnight --author='Your Name' --oneline
    
    # Last commit
    last = log -1 HEAD --stat
    
    # What the f*** happened? (Show state)
    wtf = !git reflog | head -20
    
    # ═══════════════════════════════════════════
    # BRANCHING
    # ═══════════════════════════════════════════
    
    # List branches sorted by last commit
    b = branch --sort=-committerdate --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - 
      %(color:red)%(objectname:short)%(color:reset) - 
      %(contents:subject) - 
      %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'
    
    # Create and switch to branch
    cob = checkout -b
    
    # Switch branch (modern)
    sw = switch
    
    # Delete merged branches (except main/master/develop)
    cleanup = "!git branch --merged | grep -v '\\*\\|main\\|master\\|develop' | xargs -n 1 git branch -d"
    
    # ═══════════════════════════════════════════
    # COMMITTING
    # ═══════════════════════════════════════════
    
    # Add all and commit
    ac = !git add -A && git commit -m
    
    # Amend without editing message
    amend = commit --amend --no-edit
    
    # Amend with new message
    reword = commit --amend
    
    # Undo last commit (keep changes staged)
    undo = reset --soft HEAD^
    
    # Discard all local changes
    nuke = !git reset --hard HEAD && git clean -fd
    
    # ═══════════════════════════════════════════
    # DIFFING
    # ═══════════════════════════════════════════
    
    # Diff staged changes
    ds = diff --staged
    
    # Diff with word-level highlighting
    dw = diff --word-diff
    
    # Show changed files between branches
    files = diff --name-only
    
    # ═══════════════════════════════════════════
    # REMOTE
    # ═══════════════════════════════════════════
    
    # Pull with rebase
    pr = pull --rebase
    
    # Push and set upstream
    pushu = push -u origin HEAD
    
    # Force push safely
    pushf = push --force-with-lease
    
    # Fetch and prune
    fp = fetch --prune
    
    # ═══════════════════════════════════════════
    # STASHING
    # ═══════════════════════════════════════════
    
    # Stash with message
    ss = stash push -m
    
    # Pop last stash
    sp = stash pop
    
    # List stashes
    sl = stash list
    
    # ═══════════════════════════════════════════
    # UTILITIES
    # ═══════════════════════════════════════════
    
    # Find commits by message
    find = log --all --grep
    
    # Find commits by content
    search = log --all -S
    
    # Who worked on this file
    who = shortlog -sn --
    
    # Contributors stats
    stats = shortlog -sn --all --no-merges
    
    # Aliases list
    aliases = config --get-regexp alias

Example Usage

bash
# Status
git s
#  M src/main.py
# ?? new-file.txt

# Beautiful log
git lg
# * a1b2c3d - (HEAD -> main) feat: add login (2 hours ago) <HPN>
# * d4e5f6g - fix: resolve bug (3 hours ago) <HPN>
# * g7h8i9j - (origin/main) initial commit (1 day ago) <HPN>

# What happened?
git wtf
# a1b2c3d HEAD@{0}: commit: feat: add login
# d4e5f6g HEAD@{1}: commit: fix: resolve bug
# g7h8i9j HEAD@{2}: clone: from github.com/...

# Quick commit
git ac "feat: add user profile"

# Undo last commit
git undo

# Safe force push
git pushf

🎨 Beautiful Diffs with Delta

The Problem

Default git diff output:

  • No syntax highlighting
  • Hard to read
  • No line numbers
  • Plain text

Solution: Delta

bash
# Install
# macOS
brew install git-delta

# Windows
winget install dandavison.delta
# or
scoop install delta

# Ubuntu
# Download from https://github.com/dandavison/delta/releases
dpkg -i delta_xxx_amd64.deb

Configure Delta

Add to ~/.gitconfig:

ini
[core]
    pager = delta

[interactive]
    diffFilter = delta --color-only

[delta]
    navigate = true          # Use n and N to move between diff sections
    light = false            # Set to true for light terminal backgrounds
    side-by-side = true      # Side-by-side view
    line-numbers = true      # Show line numbers
    syntax-theme = Dracula   # Color theme

[merge]
    conflictstyle = diff3

[diff]
    colorMoved = default

Delta Themes

bash
# List available themes
delta --list-syntax-themes

# Popular themes:
# - Dracula
# - OneHalfDark
# - Nord
# - Monokai Extended
# - gruvbox-dark

Side-by-Side vs Unified

ini
# Side-by-side (better for small changes)
[delta]
    side-by-side = true

# Unified (better for large changes)
[delta]
    side-by-side = false

Alternative: diff-so-fancy

bash
# Install
npm install -g diff-so-fancy

# Or
brew install diff-so-fancy

# Configure
git config --global core.pager "diff-so-fancy | less --tabs=4 -RFX"
git config --global interactive.diffFilter "diff-so-fancy --patch"

# Colors
git config --global color.ui true
git config --global color.diff-highlight.oldNormal    "red bold"
git config --global color.diff-highlight.oldHighlight "red bold 52"
git config --global color.diff-highlight.newNormal    "green bold"
git config --global color.diff-highlight.newHighlight "green bold 22"

Delta vs diff-so-fancy

FeatureDeltadiff-so-fancy
Syntax highlighting✅ Full❌ Limited
Side-by-side✅ Yes❌ No
Line numbers✅ Yes❌ No
SpeedFastVery fast
DependenciesRust binaryNode.js
ThemesManyLimited

HPN RECOMMENDATION

Dùng Delta - More features, better highlighting, side-by-side mode.


📊 Complete HPN Git Setup

~/.gitconfig Template

ini
[user]
    name = Your Name
    email = your.email@example.com
    signingkey = YOUR_GPG_KEY

[core]
    editor = code --wait
    pager = delta
    excludesFile = ~/.gitignore_global
    autocrlf = input

[init]
    defaultBranch = main

[pull]
    rebase = true

[push]
    autoSetupRemote = true
    default = current

[fetch]
    prune = true

[commit]
    gpgsign = true

[rerere]
    enabled = true

[interactive]
    diffFilter = delta --color-only

[delta]
    navigate = true
    light = false
    side-by-side = true
    line-numbers = true
    syntax-theme = Dracula

[merge]
    conflictstyle = diff3
    tool = code

[diff]
    colorMoved = default
    tool = code

[difftool "code"]
    cmd = code --wait --diff $LOCAL $REMOTE

[mergetool "code"]
    cmd = code --wait $MERGED

# Include all aliases from above
[alias]
    s = status -sb
    lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
    # ... (all other aliases)

Shell Config (Zsh/Bash)

bash
# ~/.zshrc or ~/.bashrc

# LazyGit shortcut
alias lg='lazygit'

# Quick git
alias g='git'
alias gs='git status -sb'
alias gp='git pull --rebase'
alias gpu='git push -u origin HEAD'

# Auto-complete for aliases (Zsh)
# Already works if using oh-my-zsh git plugin

💡 Key Takeaways

HPN'S INSIGHT

"Mỗi giây tiết kiệm được từ aliases và TUI, nhân với hàng trăm lần dùng mỗi ngày = hàng giờ mỗi tuần."

  1. LazyGit là game-changer: Visual staging, rebase, cherry-pick
  2. Aliases save time: git lg thay vì 50 ký tự
  3. Delta makes diffs readable: Syntax highlighting, side-by-side
  4. Invest 30 minutes to setup: Reap benefits forever

The 80/20 Setup

Nếu chỉ có 5 phút, setup 3 thứ này:

bash
# 1. LazyGit
brew install lazygit  # hoặc package manager của bạn

# 2. Beautiful log alias
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

# 3. Short status alias
git config --global alias.s "status -sb"

MUSCLE MEMORY

Bạn sẽ mất vài ngày để quen với TUI và aliases. Sau đó, quay lại vanilla git sẽ thấy cực kỳ chậm.