Git Workflow Mastery: Advanced Techniques for Team Collaboration
Git is more than just version control—it’s the foundation of modern software collaboration. Let’s explore advanced Git techniques that will make you and your team more productive.
Advanced Branching Strategies
Git Flow vs GitHub Flow vs GitLab Flow
# Git Flow - Feature branch workflow
git checkout develop
git checkout -b feature/user-authentication
# Work on feature
git checkout develop
git merge --no-ff feature/user-authentication
git branch -d feature/user-authentication
# Create release branch
git checkout -b release/1.2.0 develop
# Bug fixes only
git checkout main
git merge --no-ff release/1.2.0
git tag -a v1.2.0 -m "Release version 1.2.0"
git checkout develop
git merge --no-ff release/1.2.0
# GitHub Flow - Simplified workflow
git checkout main
git checkout -b feature/new-feature
# Work and push regularly
git push origin feature/new-feature
# Create PR, review, merge to main
git checkout main
git pull origin main
git branch -d feature/new-feature
Advanced Branch Management
# Interactive rebase to clean up history
git rebase -i HEAD~3
# Squash commits during merge
git merge --squash feature-branch
git commit -m "Add complete feature X"
# Cherry-pick specific commits
git cherry-pick abc123def456
# Create and switch to branch in one command
git checkout -b feature/new-feature
# Push new branch and set upstream
git push -u origin feature/new-feature
# Delete remote branch
git push origin --delete feature/old-feature
# Rename current branch
git branch -m new-branch-name
# List branches with last commit info
git branch -v
git branch -vv # Show tracking branches
Powerful Git Commands
Advanced Commit Techniques
# Amend last commit (change message or add files)
git commit --amend -m "Updated commit message"
# Commit only part of a file
git add -p filename.js
# Commit with detailed message
git commit -m "feat: add user authentication
- Add JWT token generation
- Implement login/logout endpoints
- Add password hashing with bcrypt
- Update user model with auth fields
Closes #123"
# Commit and skip pre-commit hooks
git commit --no-verify -m "Quick fix"
# Create empty commit (useful for triggering CI)
git commit --allow-empty -m "Trigger deployment"
Stash Management
# Stash with message
git stash push -m "Work in progress on feature X"
# Stash specific files
git stash push -m "Partial work" -- file1.js file2.js
# List all stashes
git stash list
# Apply specific stash
git stash apply stash@{2}
# Pop latest stash (apply and remove)
git stash pop
# Create branch from stash
git stash branch feature/from-stash stash@{1}
# Clear all stashes
git stash clear
Advanced Log and History
# Beautiful log with graph
git log --oneline --graph --decorate --all
# Log with file changes
git log --stat
# Log for specific file
git log --follow -- filename.js
# Log between dates
git log --since="2024-01-01" --until="2024-02-01"
# Log by author
git log --author="John Doe"
# Find commits that introduced/removed text
git log -S "function searchUsers" --source --all
# Show commits that touched specific lines
git log -L 10,20:filename.js
# Blame with commit details
git blame -w -C filename.js
Conflict Resolution Mastery
Advanced Merge Strategies
# Merge with strategy
git merge -X theirs feature-branch # Prefer their changes
git merge -X ours feature-branch # Prefer our changes
# Merge without commit (review first)
git merge --no-commit --no-ff feature-branch
# Abort merge
git merge --abort
# Continue merge after resolving conflicts
git merge --continue
# Three-way merge tool
git mergetool
# Configure merge tool (VS Code)
git config --global merge.tool vscode
git config --global mergetool.vscode.cmd 'code --wait $MERGED'
Rebase Strategies
# Interactive rebase to edit history
git rebase -i HEAD~5
# Rebase onto different branch
git rebase --onto main feature-base feature-branch
# Rebase and preserve merge commits
git rebase --preserve-merges main
# Abort rebase
git rebase --abort
# Continue rebase after resolving conflicts
git rebase --continue
# Skip problematic commit during rebase
git rebase --skip
Team Collaboration Workflows
Code Review Best Practices
# Create feature branch
git checkout -b feature/user-profile-update
# Make atomic commits
git add user-controller.js
git commit -m "Add user profile update endpoint"
git add user-model.js
git commit -m "Add validation for profile fields"
git add user-routes.js
git commit -m "Wire up profile update route"
# Push and create PR
git push -u origin feature/user-profile-update
# Address review feedback
git add .
git commit -m "Address PR feedback: add error handling"
# Squash commits before merge (if needed)
git rebase -i HEAD~4
Collaborative Conflict Resolution
# Fetch latest changes before starting work
git fetch origin
git checkout main
git pull origin main
git checkout -b feature/new-work
# Regularly sync with main
git fetch origin
git rebase origin/main
# If conflicts occur during rebase
# 1. Resolve conflicts in files
# 2. Stage resolved files
git add resolved-file.js
# 3. Continue rebase
git rebase --continue
# Force push after rebase (be careful!)
git push --force-with-lease origin feature/new-work
Git Hooks and Automation
Pre-commit Hooks
#!/bin/sh
# .git/hooks/pre-commit
# Run linting
npm run lint
if [ $? -ne 0 ]; then
echo "Linting failed. Please fix errors before committing."
exit 1
fi
# Run tests
npm test
if [ $? -ne 0 ]; then
echo "Tests failed. Please fix tests before committing."
exit 1
fi
# Check for debugging statements
if grep -r "console.log\|debugger" src/; then
echo "Found debugging statements. Please remove before committing."
exit 1
fi
echo "Pre-commit checks passed!"
Commit Message Validation
#!/bin/sh
# .git/hooks/commit-msg
commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}'
if ! grep -qE "$commit_regex" "$1"; then
echo "Invalid commit message format!"
echo "Format: type(scope): description"
echo "Types: feat, fix, docs, style, refactor, test, chore"
echo "Example: feat(auth): add user login functionality"
exit 1
fi
Automated Workflows with Husky
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"pre-push": "npm test"
}
},
"lint-staged": {
"*.{js,ts,jsx,tsx}": [
"eslint --fix",
"prettier --write",
"git add"
],
"*.{css,scss,md}": [
"prettier --write",
"git add"
]
}
}
Advanced Git Configuration
Global Git Configuration
# User configuration
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Editor configuration
git config --global core.editor "code --wait"
# Merge tool
git config --global merge.tool vscode
# Default branch name
git config --global init.defaultBranch main
# Auto-correct typos
git config --global help.autocorrect 1
# Colorful output
git config --global color.ui auto
# Better diff algorithm
git config --global diff.algorithm patience
# Reuse recorded resolution
git config --global rerere.enabled true
# Push current branch by default
git config --global push.default current
# Automatically prune deleted remote branches
git config --global fetch.prune true
Useful Git Aliases
# Add to ~/.gitconfig
[alias]
# Short status
s = status -s
# Pretty log
lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
# Show branches
br = branch -v
# Quick commit
cm = commit -m
# Amend last commit
amend = commit --amend --no-edit
# Undo last commit (keep changes)
undo = reset --soft HEAD^
# Discard changes
discard = checkout --
# Clean up merged branches
cleanup = "!git branch --merged | grep -v '\\*\\|main\\|develop' | xargs -n 1 git branch -d"
# Find commits by message
find = "!f() { git log --all --grep=\"$1\" --oneline; }; f"
# Show file history
filelog = log -u
# Show what changed in last commit
last = log -1 HEAD --stat
# Sync with remote
sync = "!git fetch origin && git rebase origin/main"
Git Troubleshooting
Common Issues and Solutions
# Accidentally committed to wrong branch
git reset --soft HEAD^
git stash
git checkout correct-branch
git stash pop
git commit
# Remove file from Git but keep locally
git rm --cached filename.txt
# Recover deleted branch
git reflog
git checkout -b recovered-branch abc123
# Fix "detached HEAD" state
git checkout main
git branch temp-branch abc123 # Save work if needed
# Remove sensitive data from history
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch secrets.txt' \
--prune-empty --tag-name-filter cat -- --all
# Or use BFG Repo-Cleaner (faster)
java -jar bfg.jar --delete-files secrets.txt
# Reset to remote state (destructive!)
git fetch origin
git reset --hard origin/main
# Find large files in repository
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort --numeric-sort --key=2 | tail -10
Mastering Git is about understanding not just the commands, but the underlying concepts of distributed version control. These advanced techniques will help you navigate complex development scenarios and collaborate more effectively with your team.