Version Control21 min read1,599 lines

Learning state

Track this guide

Saved in this browser only. No account required.

Git Advanced Workflows Master Class

Engineering-Grade Reference Manual for Git
A comprehensive guide to Git version control, advanced workflows, and collaboration patterns


Table of Contents

  1. Git Fundamentals
  2. Repository Management
  3. Branching Strategies
  4. Committing Best Practices
  5. Merging & Rebasing
  6. Conflict Resolution
  7. Remote Operations
  8. History Manipulation
  9. Stashing & Cleaning
  10. Tags & Releases
  11. Git Hooks & Automation
  12. Advanced Search & Debug
  13. Submodules & Subtrees
  14. Collaboration Workflows
  15. Best Practices & Tips

Git Fundamentals

๐Ÿ”น Command: git config

โœ”๏ธ What It Does
Configures Git settings at system, global, or repository level.

โœ”๏ธ Syntax Examples

# Basic: Set user identity (global)
git config --global user.name "John Doe"
git config --global user.email "john@example.com"

# Real-world: Set default editor
git config --global core.editor "code --wait"

# Production: Configure line endings
git config --global core.autocrlf input  # Linux/Mac
git config --global core.autocrlf true   # Windows

# Set default branch name
git config --global init.defaultBranch main

# View all config
git config --list

# View specific config
git config user.name

# Repository-specific config (no --global)
git config user.email "work@company.com"

# Useful aliases
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
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"

โœ”๏ธ Notes, Tips & Common Mistakes

  • --global affects all repositories for current user
  • --system affects all users (requires admin)
  • Repository config overrides global config
  • Config files: ~/.gitconfig (global), .git/config (repo)

๐Ÿ”น Command: git init

โœ”๏ธ What It Does
Initializes a new Git repository.

โœ”๏ธ Syntax Examples

# Basic: Initialize in current directory
git init

# Real-world: Initialize with specific branch name
git init -b main

# Production: Initialize bare repository (for servers)
git init --bare /path/to/repo.git

โœ”๏ธ Notes, Tips & Common Mistakes

  • Creates .git directory
  • Bare repos have no working directory (used for central repos)
  • Use -b to set initial branch name (avoids master/main confusion)

๐Ÿ”น Command: git clone

โœ”๏ธ What It Does
Creates a local copy of a remote repository.

โœ”๏ธ Syntax Examples

# Basic: Clone repository
git clone https://github.com/user/repo.git

# Real-world: Clone to specific directory
git clone https://github.com/user/repo.git my-project

# Production: Shallow clone (faster, less history)
git clone --depth 1 https://github.com/user/repo.git

# Clone specific branch
git clone -b develop https://github.com/user/repo.git

# Clone with submodules
git clone --recursive https://github.com/user/repo.git

โœ”๏ธ Notes, Tips & Common Mistakes

  • --depth 1 creates shallow clone (saves time/space)
  • Use SSH URLs for authentication: git@github.com:user/repo.git
  • --recursive initializes submodules automatically

Repository Management

๐Ÿ”น Command: git status

โœ”๏ธ What It Does
Shows the working tree status (modified, staged, untracked files).

โœ”๏ธ Syntax Examples

# Basic: Show status
git status

# Real-world: Short format
git status -s

# Production: Show branch and tracking info
git status -sb

# Show ignored files
git status --ignored

โœ”๏ธ Status Codes (short format)

  • ?? - Untracked
  • A - Added (staged)
  • M - Modified
  • D - Deleted
  • R - Renamed
  • MM - Modified, staged, then modified again

๐Ÿ”น Command: git add

โœ”๏ธ What It Does
Stages changes for commit.

โœ”๏ธ Syntax Examples

# Basic: Add specific file
git add file.txt

# Real-world: Add all changes
git add .

# Production: Add interactively (choose hunks)
git add -p

# Add all tracked files (ignores new files)
git add -u

# Add all files including untracked
git add -A

โœ”๏ธ Notes, Tips & Common Mistakes

  • . adds everything in current directory
  • -p (patch mode) lets you stage parts of files
  • -u only stages modified/deleted, not new files
  • -A stages everything (new, modified, deleted)

๐Ÿ”น Command: git diff

โœ”๏ธ What It Does
Shows differences between commits, working tree, and staging area.

โœ”๏ธ Syntax Examples

# Basic: Show unstaged changes
git diff

# Real-world: Show staged changes
git diff --staged
# or
git diff --cached

# Production: Compare branches
git diff main..feature-branch

# Compare specific files
git diff HEAD~1 HEAD -- file.txt

# Show word-level diff
git diff --word-diff

# Show stat summary
git diff --stat

# Compare with remote
git diff main origin/main

โœ”๏ธ Notes, Tips & Common Mistakes

  • No arguments shows unstaged changes
  • --staged shows what will be committed
  • .. compares branches
  • HEAD~1 means one commit before HEAD

Branching Strategies

๐Ÿ”น Command: git branch

โœ”๏ธ What It Does
Lists, creates, or deletes branches.

โœ”๏ธ Syntax Examples

# Basic: List local branches
git branch

# Real-world: List all branches (including remote)
git branch -a

# Production: Create new branch
git branch feature/new-feature

# Create and switch to branch
git checkout -b feature/new-feature
# or (modern)
git switch -c feature/new-feature

# Delete branch
git branch -d feature/old-feature

# Force delete unmerged branch
git branch -D feature/abandoned

# Rename current branch
git branch -m new-name

# Show merged branches
git branch --merged

# Show unmerged branches
git branch --no-merged

# Delete remote branch
git push origin --delete feature/old-feature

โœ”๏ธ Notes, Tips & Common Mistakes

  • -d safe delete (prevents deleting unmerged)
  • -D force delete (use carefully)
  • -a shows remote-tracking branches
  • Delete remote branches with git push origin --delete

๐Ÿ”น Command: git checkout / git switch

โœ”๏ธ What It Does
Switches branches or restores files. git switch is the modern alternative for branch switching.

โœ”๏ธ Syntax Examples

# Basic: Switch branch (old way)
git checkout main

# Real-world: Switch branch (new way)
git switch main

# Production: Create and switch to new branch
git switch -c feature/new-feature

# Checkout specific commit (detached HEAD)
git checkout abc123

# Restore file from specific commit
git checkout HEAD~1 -- file.txt

# Discard local changes to file
git checkout -- file.txt
# or (modern)
git restore file.txt

# Switch to previous branch
git switch -

โœ”๏ธ Notes, Tips & Common Mistakes

  • git switch is clearer for branch operations
  • git restore is clearer for file operations
  • -- separates branch names from file paths
  • - switches to previous branch

โœ”๏ธ GitFlow

main (production)
  โ””โ”€โ”€ develop (integration)
      โ”œโ”€โ”€ feature/user-auth
      โ”œโ”€โ”€ feature/payment
      โ””โ”€โ”€ release/v1.2.0
          โ””โ”€โ”€ hotfix/critical-bug

Branches:

  • main - Production-ready code
  • develop - Integration branch
  • feature/* - New features
  • release/* - Release preparation
  • hotfix/* - Emergency fixes

โœ”๏ธ GitHub Flow (Simpler)

main (production)
  โ”œโ”€โ”€ feature/add-login
  โ”œโ”€โ”€ feature/update-ui
  โ””โ”€โ”€ bugfix/fix-crash

Workflow:

  1. Create feature branch from main
  2. Make changes and commit
  3. Open pull request
  4. Review and merge to main
  5. Deploy from main

โœ”๏ธ Trunk-Based Development

main (trunk)
  โ”œโ”€โ”€ feature-flag-1
  โ””โ”€โ”€ feature-flag-2

Characteristics:

  • Short-lived branches (< 1 day)
  • Frequent merges to main
  • Feature flags for incomplete features
  • Continuous integration

Committing Best Practices

๐Ÿ”น Command: git commit

โœ”๏ธ What It Does
Records staged changes to the repository.

โœ”๏ธ Syntax Examples

# Basic: Commit with message
git commit -m "Add user authentication"

# Real-world: Commit with detailed message
git commit -m "Add user authentication" -m "- Implement JWT tokens
- Add login/logout endpoints
- Add password hashing with bcrypt"

# Production: Commit all tracked changes (skip staging)
git commit -am "Fix typo in README"

# Amend last commit (change message or add files)
git commit --amend

# Amend without changing message
git commit --amend --no-edit

# Empty commit (useful for CI triggers)
git commit --allow-empty -m "Trigger CI build"

# Sign commit with GPG
git commit -S -m "Signed commit"

โœ”๏ธ Commit Message Best Practices

<type>(<scope>): <subject>

<body>

<footer>

Types:

  • feat - New feature
  • fix - Bug fix
  • docs - Documentation
  • style - Formatting
  • refactor - Code restructuring
  • test - Adding tests
  • chore - Maintenance

Example:

feat(auth): add JWT authentication

- Implement token generation and validation
- Add middleware for protected routes
- Update user model with password hashing

Closes #123

โœ”๏ธ Notes, Tips & Common Mistakes

  • Write clear, descriptive messages
  • Use present tense ("Add feature" not "Added feature")
  • First line should be < 50 characters
  • Separate subject from body with blank line
  • --amend rewrites history (don't use on pushed commits)

Merging & Rebasing

๐Ÿ”น Command: git merge

โœ”๏ธ What It Does
Integrates changes from one branch into another.

โœ”๏ธ Syntax Examples

# Basic: Merge branch into current branch
git merge feature/new-feature

# Real-world: Merge with no fast-forward (creates merge commit)
git merge --no-ff feature/new-feature

# Production: Merge with squash (combine all commits)
git merge --squash feature/new-feature

# Abort merge in case of conflicts
git merge --abort

# Continue merge after resolving conflicts
git merge --continue

โœ”๏ธ Merge Strategies

Fast-Forward (default when possible):

main:     A---B
               \
feature:        C---D

After merge:
main:     A---B---C---D

No Fast-Forward (--no-ff):

main:     A---B---------M
               \       /
feature:        C---D

Squash:

main:     A---B---S
               \
feature:        C---D---E
(S contains all changes from C, D, E)

โœ”๏ธ Notes, Tips & Common Mistakes

  • --no-ff preserves branch history
  • --squash creates cleaner history but loses individual commits
  • Always pull before merging
  • Use --abort if merge goes wrong

๐Ÿ”น Command: git rebase

โœ”๏ธ What It Does
Reapplies commits on top of another base commit. Creates linear history.

โœ”๏ธ Syntax Examples

# Basic: Rebase current branch onto main
git rebase main

# Real-world: Interactive rebase (edit last 3 commits)
git rebase -i HEAD~3

# Production: Rebase and preserve merge commits
git rebase -p main

# Abort rebase
git rebase --abort

# Continue after resolving conflicts
git rebase --continue

# Skip problematic commit
git rebase --skip

โœ”๏ธ Interactive Rebase Commands

pick abc123 Add feature
reword def456 Fix bug
edit ghi789 Update docs
squash jkl012 Fix typo
fixup mno345 Another typo fix
drop pqr678 Remove debug code

Commands:

  • pick - Use commit as-is
  • reword - Use commit, edit message
  • edit - Use commit, stop for amending
  • squash - Combine with previous, edit message
  • fixup - Combine with previous, keep previous message
  • drop - Remove commit

โœ”๏ธ Rebase vs Merge

Use Rebase When:

  • Cleaning up local commits before pushing
  • Keeping linear history
  • Working on feature branches

Use Merge When:

  • Integrating completed features
  • Working on public/shared branches
  • Preserving exact history

โœ”๏ธ Notes, Tips & Common Mistakes

  • NEVER rebase public/shared branches
  • Rebase rewrites history (changes commit hashes)
  • Use interactive rebase to clean up commits
  • git pull --rebase keeps linear history

Conflict Resolution

๐Ÿ”น Understanding Conflicts

โœ”๏ธ Conflict Markers

<<<<<<< HEAD
Current branch content
=======
Incoming branch content
>>>>>>> feature-branch

โœ”๏ธ Resolution Process

# 1. Start merge or rebase
git merge feature-branch
# Conflict occurs

# 2. Check which files have conflicts
git status

# 3. Open conflicted files and resolve
# Edit files, remove conflict markers

# 4. Stage resolved files
git add resolved-file.txt

# 5. Complete merge
git commit
# or for rebase
git rebase --continue

โœ”๏ธ Conflict Resolution Tools

# Use merge tool
git mergetool

# Accept all changes from current branch
git checkout --ours file.txt

# Accept all changes from incoming branch
git checkout --theirs file.txt

# Show conflict in 3-way diff
git diff --ours
git diff --theirs
git diff --base

โœ”๏ธ Notes, Tips & Common Mistakes

  • Test code after resolving conflicts
  • Don't blindly accept one side
  • Use git diff to review changes
  • Configure merge tool: git config --global merge.tool vimdiff

Remote Operations

๐Ÿ”น Command: git remote

โœ”๏ธ What It Does
Manages remote repository connections.

โœ”๏ธ Syntax Examples

# Basic: List remotes
git remote

# Real-world: List with URLs
git remote -v

# Production: Add remote
git remote add origin https://github.com/user/repo.git

# Add upstream (for forks)
git remote add upstream https://github.com/original/repo.git

# Change remote URL
git remote set-url origin git@github.com:user/repo.git

# Remove remote
git remote remove origin

# Rename remote
git remote rename origin upstream

# Show remote details
git remote show origin

๐Ÿ”น Command: git fetch

โœ”๏ธ What It Does
Downloads objects and refs from remote repository without merging.

โœ”๏ธ Syntax Examples

# Basic: Fetch from origin
git fetch

# Real-world: Fetch from specific remote
git fetch upstream

# Production: Fetch all remotes
git fetch --all

# Fetch and prune deleted branches
git fetch --prune

# Fetch specific branch
git fetch origin main

# Fetch tags
git fetch --tags

โœ”๏ธ Notes, Tips & Common Mistakes

  • Fetch doesn't modify working directory
  • Use --prune to remove stale remote-tracking branches
  • Fetch before merge/rebase

๐Ÿ”น Command: git pull

โœ”๏ธ What It Does
Fetches and merges changes from remote branch. Equivalent to git fetch + git merge.

โœ”๏ธ Syntax Examples

# Basic: Pull from tracking branch
git pull

# Real-world: Pull with rebase (linear history)
git pull --rebase

# Production: Pull from specific remote/branch
git pull origin main

# Pull and prune
git pull --prune

# Set default to rebase
git config --global pull.rebase true

โœ”๏ธ Notes, Tips & Common Mistakes

  • git pull = git fetch + git merge
  • git pull --rebase = git fetch + git rebase
  • Always commit or stash before pulling
  • Use --rebase for cleaner history

๐Ÿ”น Command: git push

โœ”๏ธ What It Does
Uploads local commits to remote repository.

โœ”๏ธ Syntax Examples

# Basic: Push to tracking branch
git push

# Real-world: Push and set upstream
git push -u origin feature-branch

# Production: Force push (rewritten history)
git push --force-with-lease

# DANGEROUS: Force push (use with extreme caution)
git push --force

# Push all branches
git push --all

# Push tags
git push --tags

# Delete remote branch
git push origin --delete feature-branch

# Push to different branch name
git push origin local-branch:remote-branch

โœ”๏ธ Notes, Tips & Common Mistakes

  • -u sets upstream tracking
  • --force-with-lease safer than --force
  • Never force push to shared branches
  • Push tags separately with --tags

History Manipulation

๐Ÿ”น Command: git log

โœ”๏ธ What It Does
Shows commit history.

โœ”๏ธ Syntax Examples

# Basic: Show commit history
git log

# Real-world: One line per commit
git log --oneline

# Production: Graph view with branches
git log --graph --oneline --all

# Show last N commits
git log -n 5

# Show commits by author
git log --author="John Doe"

# Show commits since date
git log --since="2 weeks ago"

# Show commits affecting specific file
git log -- path/to/file.txt

# Show commits with diffs
git log -p

# Show stat summary
git log --stat

# Custom format
git log --pretty=format:"%h - %an, %ar : %s"

# Show commits between branches
git log main..feature-branch

# Show commits in one branch but not another
git log main...feature-branch

โœ”๏ธ Useful Aliases

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

# Save as 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"

# Use with: git lg

๐Ÿ”น Command: git reset

โœ”๏ธ What It Does
Resets current HEAD to specified state. Use with caution!

โœ”๏ธ Syntax Examples

# Basic: Unstage file (keep changes)
git reset file.txt

# Real-world: Undo last commit (keep changes)
git reset --soft HEAD~1

# Production: Undo last commit (discard changes)
git reset --hard HEAD~1

# Reset to specific commit
git reset --hard abc123

# Mixed reset (default, unstage but keep changes)
git reset HEAD~1

โœ”๏ธ Reset Modes

--soft: Moves HEAD, keeps staging and working directory

Use when: You want to recommit with different message

--mixed (default): Moves HEAD, unstages, keeps working directory

Use when: You want to unstage changes

--hard: Moves HEAD, clears staging and working directory

Use when: You want to discard all changes (DANGEROUS)

โœ”๏ธ Notes, Tips & Common Mistakes

  • --hard permanently deletes uncommitted changes
  • Don't reset public commits
  • Use git reflog to recover from mistakes

๐Ÿ”น Command: git revert

โœ”๏ธ What It Does
Creates new commit that undoes changes from previous commit. Safe for public branches.

โœ”๏ธ Syntax Examples

# Basic: Revert last commit
git revert HEAD

# Real-world: Revert specific commit
git revert abc123

# Production: Revert without committing
git revert --no-commit abc123

# Revert merge commit
git revert -m 1 merge-commit-hash

# Revert range of commits
git revert HEAD~3..HEAD

โœ”๏ธ Notes, Tips & Common Mistakes

  • Safe for public branches (doesn't rewrite history)
  • Creates new commit (opposite of reverted commit)
  • Use for undoing public commits
  • -m 1 specifies parent for merge commits

๐Ÿ”น Command: git reflog

โœ”๏ธ What It Does
Shows reference log (history of HEAD movements). Lifesaver for recovering lost commits.

โœ”๏ธ Syntax Examples

# Basic: Show reflog
git reflog

# Real-world: Show last 10 entries
git reflog -10

# Production: Recover lost commit
git reflog
# Find commit hash
git checkout abc123
# or
git reset --hard abc123

โœ”๏ธ Notes, Tips & Common Mistakes

  • Reflog is local only (not pushed)
  • Entries expire after 90 days (default)
  • Use to recover from git reset --hard
  • Shows all HEAD movements

Stashing & Cleaning

๐Ÿ”น Command: git stash

โœ”๏ธ What It Does
Temporarily saves uncommitted changes.

โœ”๏ธ Syntax Examples

# Basic: Stash changes
git stash

# Real-world: Stash with message
git stash save "WIP: working on feature"
# or (modern)
git stash push -m "WIP: working on feature"

# Production: Stash including untracked files
git stash -u

# Stash including ignored files
git stash -a

# List stashes
git stash list

# Apply most recent stash
git stash apply

# Apply and remove stash
git stash pop

# Apply specific stash
git stash apply stash@{2}

# Show stash contents
git stash show -p stash@{0}

# Drop specific stash
git stash drop stash@{0}

# Clear all stashes
git stash clear

# Create branch from stash
git stash branch new-branch stash@{0}

โœ”๏ธ Notes, Tips & Common Mistakes

  • pop = apply + drop
  • Use -u to include untracked files
  • Stashes are numbered from 0
  • stash@{0} is most recent

๐Ÿ”น Command: git clean

โœ”๏ธ What It Does
Removes untracked files from working directory. Dangerous - files are permanently deleted!

โœ”๏ธ Syntax Examples

# Basic: Dry run (show what would be deleted)
git clean -n

# Real-world: Remove untracked files
git clean -f

# Production: Remove untracked files and directories
git clean -fd

# Remove ignored files too
git clean -fdx

# Interactive mode
git clean -i

โœ”๏ธ Notes, Tips & Common Mistakes

  • ALWAYS run with -n first (dry run)
  • -f required for safety
  • -d removes directories
  • -x removes ignored files (careful with build artifacts)

Tags & Releases

๐Ÿ”น Command: git tag

โœ”๏ธ What It Does
Creates, lists, and manages tags (typically for releases).

โœ”๏ธ Syntax Examples

# Basic: List tags
git tag

# Real-world: Create lightweight tag
git tag v1.0.0

# Production: Create annotated tag (recommended)
git tag -a v1.0.0 -m "Release version 1.0.0"

# Tag specific commit
git tag -a v1.0.0 abc123 -m "Release 1.0.0"

# Push tag to remote
git push origin v1.0.0

# Push all tags
git push --tags

# Delete local tag
git tag -d v1.0.0

# Delete remote tag
git push origin --delete v1.0.0

# Show tag details
git show v1.0.0

# Checkout tag
git checkout v1.0.0

# List tags matching pattern
git tag -l "v1.*"

โœ”๏ธ Semantic Versioning

v<MAJOR>.<MINOR>.<PATCH>

MAJOR: Breaking changes
MINOR: New features (backward compatible)
PATCH: Bug fixes

Examples:
v1.0.0 - Initial release
v1.1.0 - New feature added
v1.1.1 - Bug fix
v2.0.0 - Breaking change

โœ”๏ธ Notes, Tips & Common Mistakes

  • Use annotated tags for releases (-a)
  • Follow semantic versioning
  • Tags must be pushed separately
  • Lightweight tags are just pointers

Git Hooks & Automation

๐Ÿ”น Understanding Git Hooks

โœ”๏ธ What They Are
Scripts that run automatically at specific Git events.

โœ”๏ธ Hook Locations
.git/hooks/ directory

โœ”๏ธ Common Hooks

pre-commit - Before commit is created

#!/bin/sh
# .git/hooks/pre-commit

# Run linter
npm run lint
if [ $? -ne 0 ]; then
    echo "Linting failed. Commit aborted."
    exit 1
fi

# Run tests
npm test

commit-msg - Validate commit message

#!/bin/sh
# .git/hooks/commit-msg

commit_msg=$(cat "$1")

# Enforce conventional commits
if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .+"; then
    echo "Invalid commit message format"
    echo "Use: <type>(<scope>): <subject>"
    exit 1
fi

pre-push - Before push to remote

#!/bin/sh
# .git/hooks/pre-push

# Run full test suite
npm run test:all
if [ $? -ne 0 ]; then
    echo "Tests failed. Push aborted."
    exit 1
fi

โœ”๏ธ Managing Hooks with Husky

# Install husky
npm install --save-dev husky

# Initialize husky
npx husky init

# Add pre-commit hook
npx husky add .husky/pre-commit "npm test"

# Add commit-msg hook
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'

Advanced Search & Debug

๐Ÿ”น Command: git grep

โœ”๏ธ What It Does
Searches for text in tracked files.

โœ”๏ธ Syntax Examples

# Basic: Search for text
git grep "function"

# Real-world: Search with line numbers
git grep -n "TODO"

# Production: Search in specific files
git grep "API_KEY" -- "*.js"

# Case-insensitive search
git grep -i "error"

# Show function/class containing match
git grep -p "import"

# Count matches per file
git grep -c "console.log"

๐Ÿ”น Command: git bisect

โœ”๏ธ What It Does
Binary search to find commit that introduced a bug.

โœ”๏ธ Syntax Examples

# Start bisect
git bisect start

# Mark current commit as bad
git bisect bad

# Mark known good commit
git bisect good abc123

# Git checks out middle commit
# Test the code

# Mark as good or bad
git bisect good
# or
git bisect bad

# Repeat until bug is found

# End bisect
git bisect reset

# Automated bisect with script
git bisect start HEAD v1.0.0
git bisect run npm test

โœ”๏ธ Notes, Tips & Common Mistakes

  • Requires known good and bad commits
  • Binary search is efficient (log n)
  • Can automate with test script
  • git bisect reset returns to original state

๐Ÿ”น Command: git blame

โœ”๏ธ What It Does
Shows who last modified each line of a file.

โœ”๏ธ Syntax Examples

# Basic: Show blame for file
git blame file.txt

# Real-world: Show with email
git blame -e file.txt

# Production: Show specific line range
git blame -L 10,20 file.txt

# Show blame before specific commit
git blame abc123^ -- file.txt

# Ignore whitespace changes
git blame -w file.txt

Submodules & Subtrees

๐Ÿ”น Git Submodules

โœ”๏ธ What They Are
Repositories embedded within another repository.

โœ”๏ธ Syntax Examples

# Add submodule
git submodule add https://github.com/user/lib.git libs/lib

# Clone repo with submodules
git clone --recursive https://github.com/user/repo.git

# Initialize submodules after clone
git submodule init
git submodule update

# Update submodules to latest
git submodule update --remote

# Remove submodule
git submodule deinit libs/lib
git rm libs/lib
rm -rf .git/modules/libs/lib

โœ”๏ธ Notes, Tips & Common Mistakes

  • Submodules point to specific commits
  • Use --recursive when cloning
  • Update submodules separately
  • Consider alternatives (npm packages, subtrees)

๐Ÿ”น Git Subtrees

โœ”๏ธ What They Are
Alternative to submodules, merges external repo into subdirectory.

โœ”๏ธ Syntax Examples

# Add subtree
git subtree add --prefix=libs/lib https://github.com/user/lib.git main --squash

# Pull updates
git subtree pull --prefix=libs/lib https://github.com/user/lib.git main --squash

# Push changes back
git subtree push --prefix=libs/lib https://github.com/user/lib.git main

โœ”๏ธ Subtrees vs Submodules

Submodules:

  • Separate repositories
  • Points to specific commit
  • Requires initialization
  • Better for independent projects

Subtrees:

  • Merged into main repo
  • Simpler for contributors
  • No special commands needed
  • Better for tightly coupled code

Collaboration Workflows

๐Ÿ”น Fork & Pull Request Workflow

# 1. Fork repository on GitHub

# 2. Clone your fork
git clone https://github.com/yourusername/repo.git
cd repo

# 3. Add upstream remote
git remote add upstream https://github.com/original/repo.git

# 4. Create feature branch
git checkout -b feature/new-feature

# 5. Make changes and commit
git add .
git commit -m "feat: add new feature"

# 6. Push to your fork
git push origin feature/new-feature

# 7. Create pull request on GitHub

# 8. Keep fork updated
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

๐Ÿ”น Code Review Best Practices

Before Creating PR:

  • Code is tested and working
  • Commits are clean and logical
  • Commit messages are clear
  • Code follows project style
  • Documentation is updated
  • No debugging code left

PR Description Should Include:

  • What changed and why
  • How to test
  • Screenshots (for UI changes)
  • Related issues/tickets

During Review:

  • Respond to feedback promptly
  • Make requested changes in new commits
  • Don't force push during review
  • Squash commits before merge (if required)

Best Practices & Tips

โœ… Commit Practices

  1. Commit often, push less frequently
  2. Write meaningful commit messages
  3. Keep commits atomic (one logical change)
  4. Don't commit generated files
  5. Use .gitignore properly

โœ… Branch Practices

  1. Use descriptive branch names (feature/user-auth, not fix)
  2. Delete merged branches
  3. Keep branches short-lived
  4. Regularly sync with main/develop
  5. Don't commit directly to main

โœ… Security Practices

  1. Never commit secrets (API keys, passwords)
  2. Use .gitignore for sensitive files
  3. Scan for secrets (git-secrets, truffleHog)
  4. Sign commits with GPG (for critical projects)
  5. Use SSH keys instead of passwords

โœ… .gitignore Best Practices

# Dependencies
node_modules/
vendor/

# Environment files
.env
.env.local
*.env

# Build outputs
dist/
build/
*.log

# IDE files
.vscode/
.idea/
*.swp

# OS files
.DS_Store
Thumbs.db

# Secrets
*.pem
*.key
secrets/

โœ… Useful Git Aliases

# Add to ~/.gitconfig

[alias]
    # Shortcuts
    co = checkout
    br = branch
    ci = commit
    st = status
    
    # Useful commands
    unstage = reset HEAD --
    last = log -1 HEAD
    visual = log --graph --oneline --all
    
    # Undo
    undo = reset --soft HEAD~1
    amend = commit --amend --no-edit
    
    # Cleanup
    cleanup = !git branch --merged | grep -v '\\*\\|main\\|develop' | xargs -n 1 git branch -d
    
    # Pretty log
    lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

Quick Reference Card

Essential Commands

# Setup
git config --global user.name "Name"
git config --global user.email "email@example.com"

# Repository
git init
git clone <url>
git status
git diff

# Staging
git add <file>
git add .
git add -p

# Committing
git commit -m "message"
git commit --amend

# Branching
git branch
git checkout -b <branch>
git switch -c <branch>
git merge <branch>
git rebase <branch>

# Remote
git remote -v
git fetch
git pull
git push
git push -u origin <branch>

# History
git log
git log --oneline --graph
git reflog

# Undo
git reset --soft HEAD~1
git reset --hard HEAD~1
git revert <commit>

# Stash
git stash
git stash pop
git stash list

# Tags
git tag -a v1.0.0 -m "Release 1.0.0"
git push --tags

Emergency Commands

# Undo last commit (keep changes)
git reset --soft HEAD~1

# Discard all local changes
git reset --hard HEAD

# Recover deleted branch
git reflog
git checkout -b <branch> <commit-hash>

# Remove file from last commit
git reset --soft HEAD~1
git reset HEAD <file>
git commit -c ORIG_HEAD

# Undo git add
git reset HEAD <file>

# Abort merge
git merge --abort

# Abort rebase
git rebase --abort

๐ŸŽ“ Git Advanced Workflows Master Class Complete
This comprehensive guide covers everything from basic Git commands to advanced workflows and collaboration patterns. Master these concepts to become proficient in version control and team collaboration.