git-expert
Git version control, branching strategies, advanced operations, troubleshooting, and collaboration workflows
Git Expert Skill
You are an expert in Git version control with deep knowledge of branching strategies, advanced operations, conflict resolution, troubleshooting, and team collaboration workflows.
Core Competencies
Git Fundamentals
- Version Control: Commits, branches, tags, history management
- Collaboration: Remotes, push/pull, fetch, merge conflicts
- Branching Strategies: trunk-based, Git Flow, GitHub Flow, release branches
- Advanced Operations: rebase, cherry-pick, stash, bisect, reflog
- Repository Management: submodules, worktrees, hooks, LFS
- Troubleshooting: Conflict resolution, detached HEAD, history rewriting
Git vs GitHub
Git: Distributed version control system (local operations: commit, branch, merge) GitHub: Platform built on Git (remote hosting, PRs, Actions, Issues)
This skill focuses on Git commands and workflows. For GitHub platform features, see the github-expert skill.
Essential Git Commands
Repository Initialization
# Initialize a new Git repository
git init
# Clone an existing repository
git clone https://github.com/optum-tech-compute/ohemr-ansible-playbooks.git
# Clone with specific branch
git clone -b develop https://github.com/optum-tech-compute/repo.git
# Shallow clone (faster, less history)
git clone --depth 1 https://github.com/optum-tech-compute/repo.git
Basic Workflow
# Check repository status
git status
# Add files to staging area
git add file.txt # Add specific file
git add *.py # Add all Python files
git add . # Add all changes
git add -p # Interactive staging (patch mode)
# Commit changes
git commit -m "feat: add new feature"
# Add and commit in one step
git commit -am "fix: resolve bug" # Only for tracked files
# Amend last commit (change message or add files)
git commit --amend --no-edit # Add staged changes to last commit
git commit --amend -m "New message" # Change commit message
Viewing History
# View commit history
git log
# Compact one-line history
git log --oneline
# Graph view with branches
git log --oneline --graph --all --decorate
# Show commits by author
git log --author="John Doe"
# Show commits in date range
git log --since="2 weeks ago" --until="yesterday"
# Show commits affecting specific file
git log -- path/to/file.txt
# Show changes introduced by each commit
git log -p
# Show commit statistics
git log --stat
# Search commit messages
git log --grep="bug fix"
# Show commits that changed a specific string
git log -S "function_name"
Viewing Changes
# Show unstaged changes
git diff
# Show staged changes
git diff --cached
# Compare branches
git diff main..develop
# Compare specific commits
git diff abc123..def456
# Show changes in specific file
git diff path/to/file.txt
# Show word-level diff
git diff --word-diff
# Show changes with context
git diff -U10 # 10 lines of context
Branching and Merging
Branch Operations
# List branches
git branch # Local branches
git branch -r # Remote branches
git branch -a # All branches
# Create new branch
git branch feature/new-feature
# Create and switch to new branch
git checkout -b feature/new-feature
git switch -c feature/new-feature # Modern alternative
# Switch branches
git checkout main
git switch main # Modern alternative
# Rename branch
git branch -m old-name new-name
# Delete branch
git branch -d feature/completed # Safe delete (checks if merged)
git branch -D feature/abandoned # Force delete
# Delete remote branch
git push origin --delete feature/old-branch
Merging
# Merge branch into current branch
git merge feature/new-feature
# Merge with commit (no fast-forward)
git merge --no-ff feature/new-feature
# Merge squash (combine commits into one)
git merge --squash feature/new-feature
git commit -m "feat: implement new feature"
# Abort merge (if conflicts)
git merge --abort
Rebasing
Rebase vs Merge:
- Merge: Creates merge commit, preserves history (non-linear)
- Rebase: Rewrites history, linear history (cleaner)
When to use rebase:
- Feature branch onto main (before merging PR)
- Cleaning up local commits before pushing
- Never rebase public/shared branches!
# Rebase current branch onto main
git checkout feature/my-feature
git rebase main
# Interactive rebase (edit, squash, reorder commits)
git rebase -i HEAD~5 # Last 5 commits
git rebase -i abc123 # Since commit abc123
# Rebase commands in interactive mode:
# pick = use commit
# reword = use commit, but edit message
# edit = use commit, but stop for amending
# squash = combine with previous commit
# fixup = like squash, discard this message
# drop = remove commit
# Continue rebase after resolving conflicts
git rebase --continue
# Skip current commit during rebase
git rebase --skip
# Abort rebase
git rebase --abort
Remote Operations
Working with Remotes
# List remotes
git remote -v
# Add remote
git remote add origin https://github.com/user/repo.git
# Change remote URL
git remote set-url origin https://github.com/user/new-repo.git
# Remove remote
git remote remove origin
# Rename remote
git remote rename origin upstream
# Show remote details
git remote show origin
Pushing and Pulling
# Push to remote
git push origin main
# Push and set upstream
git push -u origin feature/new-feature
# Push force (after rebase) - DANGEROUS!
git push --force-with-lease origin <your-feature-branch> # NEVER force-push to main/master or any shared branch
# Push all branches
git push --all origin
# Push tags
git push --tags origin
# Pull changes
git pull origin main
# Pull with rebase
git pull --rebase origin main
# Fetch without merging
git fetch origin
# Fetch specific branch
git fetch origin develop
# Fetch and prune deleted remote branches
git fetch --prune origin
Advanced Operations
Stashing Changes
# Stash changes (save for later)
git stash
# Stash with message
git stash save "WIP: working on feature X"
# List stashes
git stash list
# Apply most recent stash
git stash apply
# Apply specific stash
git stash apply stash@{2}
# Apply and remove stash
git stash pop
# Show stash contents
git stash show -p stash@{0}
# Drop stash
git stash drop stash@{0}
# Clear all stashes
git stash clear
# Create branch from stash
git stash branch feature/from-stash
Cherry-Picking
# Apply specific commit to current branch
git cherry-pick abc123
# Cherry-pick multiple commits
git cherry-pick abc123 def456
# Cherry-pick without committing
git cherry-pick --no-commit abc123
# Abort cherry-pick
git cherry-pick --abort
Bisect (Binary Search for Bugs)
# Start bisect
git bisect start
# Mark current commit as bad
git bisect bad
# Mark commit as good
git bisect good abc123
# Git automatically checks out middle commit
# Test it, then mark as good or bad
git bisect good # or git bisect bad
# Git continues binary search until finding culprit
# End bisect
git bisect reset
Reflog (Recovery)
# View reflog (all ref updates)
git reflog
# Recover lost commit
git reflog
git checkout abc123 # Or git cherry-pick abc123
# Recover deleted branch
git reflog
git checkout -b recovered-branch abc123
Tagging
# List tags
git tag
# Create lightweight tag
git tag v1.0.0
# Create annotated tag (recommended)
git tag -a v1.0.0 -m "Version 1.0.0 release"
# Tag specific commit
git tag -a v0.9.0 abc123 -m "Beta release"
# Show tag details
git show v1.0.0
# Push tags to remote
git push origin v1.0.0
git push --tags # Push all tags
# Delete tag
git tag -d v1.0.0 # Local
git push origin :refs/tags/v1.0.0 # Remote
git push origin --delete v1.0.0 # Remote (alternative)
Branching Strategies
Trunk-Based Development
Single main branch, short-lived feature branches:
main (production-ready)
├── feature/quick-fix (1-2 days)
└── feature/small-feature (2-3 days)
Workflow:
- Create feature branch from main
- Develop feature (1-3 days max)
- Create PR, get reviews
- Merge to main (squash or merge commit)
- Delete feature branch
- Deploy from main
Best for:
- Fast-moving teams
- Continuous deployment
- Small, incremental changes
Git Flow
Multiple long-lived branches:
main (production releases)
├── hotfix/1.0.1
└── release/1.1.0
develop (integration)
├── feature/user-auth
└── feature/api-integration
Branches:
- main: Production-ready code, tagged releases
- develop: Integration branch for features
- feature/*: Feature branches (from develop)
- release/*: Release preparation (from develop)
- hotfix/*: Emergency fixes (from main)
Workflow:
- Feature branches from develop
- Merge features to develop
- Create release branch from develop
- Test release, apply bug fixes
- Merge release to main and develop
- Tag release on main
Best for:
- Scheduled releases
- Multiple versions in production
- Large teams
GitHub Flow
Simplified flow for continuous deployment:
main (production)
├── feature/add-login
└── bugfix/fix-header
Workflow:
- Create feature branch from main
- Develop and commit
- Open PR when ready
- Review and discuss
- Merge to main
- Deploy immediately
Best for:
- Continuous deployment
- Web applications
- Simple release process
Conflict Resolution
Understanding Merge Conflicts
Conflict markers:
<<<<<<< HEAD
Your changes
=======
Their changes
>>>>>>> feature-branch
Resolving Conflicts
# Start merge
git merge feature/conflicting-branch
# CONFLICT (content): Merge conflict in file.txt
# 1. Check which files have conflicts
git status
# 2. Open conflicted files and edit
vim file.txt
# Manually resolve conflicts, remove markers
# 3. Stage resolved files
git add file.txt
# 4. Complete merge
git commit -m "Merge branch feature/conflicting-branch"
# Alternative: Abort merge
git merge --abort
Merge Tools
# Configure merge tool
git config --global merge.tool vimdiff
# Use merge tool to resolve conflicts
git mergetool
# Common merge tools: vimdiff, kdiff3, meld, vscode
History Rewriting (Advanced)
Interactive Rebase
# Rewrite last 5 commits
git rebase -i HEAD~5
# Example: Squash commits
# Change 'pick' to 'squash' for commits to combine
pick abc123 feat: add feature X
squash def456 fix: typo in feature X
squash ghi789 fix: another typo
# Result: 3 commits become 1
Amending History
# Change last commit
git commit --amend -m "New commit message"
# Change author of last commit
git commit --amend --author="John Doe <[email protected]>"
# Change commit dates
git commit --amend --date="Mon Jan 1 00:00:00 2024 -0800"
Filter-Branch (Rewrite History)
⚠️ DANGEROUS: Only use on private branches!
# Remove file from all history
git filter-branch --tree-filter 'rm -f secrets.txt' HEAD
# Change author for all commits
git filter-branch --commit-filter '
if [ "$GIT_AUTHOR_EMAIL" = "[email protected]" ]; then
export GIT_AUTHOR_EMAIL="[email protected]"
fi
git commit-tree "$@"
' HEAD
Git Configuration
User Configuration
# Set user name and email
git config --global user.name "John Doe"
git config --global user.email "[email protected]"
# Set editor
git config --global core.editor "vim"
# Set merge tool
git config --global merge.tool "vimdiff"
# Enable color output
git config --global color.ui auto
# Set default branch name
git config --global init.defaultBranch main
Aliases
# Create aliases for common commands
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
# Complex aliases
git config --global alias.lg "log --oneline --graph --all --decorate"
git config --global alias.unstage "reset HEAD --"
git config --global alias.last "log -1 HEAD"
# Usage
git co main # git checkout main
git lg # git log --oneline --graph --all --decorate
Configuration Levels
# System-wide (all users)
git config --system core.editor vim
# Global (current user)
git config --global user.name "John Doe"
# Local (current repository)
git config --local core.filemode false
# View configuration
git config --list
git config --list --show-origin # Show where each setting is defined
Advanced Features
Git Worktrees
Work on multiple branches simultaneously. The main clone MUST stay on main.
Worktrees live inside worktrees/ under the repo root. Branch slashes become folder hyphens: feature/foo → worktrees/feature-foo.
# Ensure worktrees/ is gitignored
grep -q '^worktrees/' .gitignore || echo 'worktrees/' >> .gitignore
# List worktrees
git worktree list
# Add worktree for a new feature branch
git worktree add worktrees/feature-my-feature -b feature/my-feature main
# Add worktree for an existing branch
git worktree add worktrees/feature-existing feature/existing
# Work in worktree
cd worktrees/feature-my-feature
# Make changes, commit - ALL work happens here
# Remove worktree (from main clone)
git worktree remove worktrees/feature-my-feature
# Prune stale worktrees
git worktree prune
Git Submodules
Include external repositories:
# Add submodule
git submodule add https://github.com/vendor/lib.git vendor/lib
# Clone repo with submodules
git clone --recurse-submodules https://github.com/user/repo.git
# Initialize and update submodules
git submodule init
git submodule update
# Update submodules to latest
git submodule update --remote
# Remove submodule
git submodule deinit vendor/lib
git rm vendor/lib
# DESTRUCTIVE — only run if you are certain the submodule is fully deregistered and you have a backup
rm -rf .git/modules/vendor/lib
Git Hooks
Automate tasks with hooks:
# Hooks are scripts in .git/hooks/
# Common hooks:
# - pre-commit: Run before commit (linting, tests)
# - pre-push: Run before push (tests, security checks)
# - commit-msg: Validate commit message format
# Example pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
# Run linter before commit
npm run lint || exit 1
EOF
chmod +x .git/hooks/pre-commit
Troubleshooting
Common Issues
1. Detached HEAD state:
# You're in detached HEAD if:
git status
# HEAD detached at abc123
# Solution: Create branch
git checkout -b recovery-branch
2. Accidentally committed to wrong branch:
# Undo last commit, keep changes
git reset --soft HEAD~1
# Switch to correct branch
git checkout correct-branch
# Commit changes
git commit -m "feat: correct branch commit"
3. Pushed sensitive data:
# Remove file from last commit
git rm --cached secrets.txt
git commit --amend --no-edit
git push --force-with-lease origin <your-feature-branch> # NEVER force-push to main/master or any shared branch
# Remove from all history (use BFG Repo-Cleaner)
java -jar bfg.jar --delete-files secrets.txt
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force-with-lease origin <your-feature-branch> # NEVER force-push to main/master or any shared branch
4. Lost commits (deleted branch):
# Find lost commit
git reflog
# Recover
git checkout -b recovered-branch abc123
5. Merge conflicts too complex:
# Abort merge
git merge --abort
# Try rebase instead (linear history)
git rebase main
Best Practices
Commit Messages
Conventional Commits format:
<type>(<scope>): <subject>
<body>
<footer>
Types and their semantic-release effect:
| Type | Description | Version Bump |
|---|---|---|
feat | New feature | MINOR (1.x.0) |
fix | Bug fix | PATCH (1.0.x) |
perf | Performance improvement | PATCH (1.0.x) |
docs | Documentation changes | No release |
style | Code style (formatting, no logic) | No release |
refactor | Code refactoring | No release |
test | Add or update tests | No release |
build | Build system or dependencies | No release |
ci | CI/CD configuration | No release |
chore | Maintenance tasks | No release |
Breaking changes trigger a MAJOR bump (x.0.0):
feat(api)!: remove deprecated endpoints
BREAKING CHANGE: The /v1/users endpoint has been removed.
Use /v2/users instead.
Examples:
feat(auth): add OAuth2 login support
Implement OAuth2 authentication flow with Google and GitHub providers.
Includes token refresh and session management.
Closes #123
fix(api): resolve race condition in user creation
Add mutex lock to prevent duplicate user records when concurrent
requests arrive within the same transaction window.
Fixes #456
Branch Naming
# Format: <type>/<short-description>
feature/user-authentication
bugfix/fix-login-error
hotfix/critical-security-patch
docs/update-readme
refactor/simplify-auth-logic
Git Workflow Tips
- Commit often: Small, logical commits are easier to review and revert
- Pull before push: Avoid conflicts by staying up to date
- Use branches: Never commit directly to main
- Review before pushing: Check
git diff --cachedbefore committing - Write good commit messages: Future you will thank you
- Don't commit generated files: Use
.gitignore - Test before committing: Ensure code works before committing
.gitignore Best Practices
# .gitignore example
# Operating System
.DS_Store
Thumbs.db
# IDEs
.vscode/
.idea/
*.swp
# Dependencies
node_modules/
venv/
.venv/
# Build outputs
dist/
build/
*.o
*.pyc
# Secrets
.env
secrets.yml
*.key
*.pem
# Logs
*.log
logs/
Output Contract
Every completed work item MUST include the following structured output:
1. Conventional Commit Message
<type>(<scope>): <subject>
<body>
<footer>
The commit message MUST follow the types table in Best Practices above.
2. Summary Block
Provide a BEFORE/AFTER summary so reviewers can verify the change at a glance:
## Summary
BEFORE: <description of prior state>
AFTER: <description of new state>
3. Files Modified Table
List every file touched in a markdown table:
| File | Action | Description |
|------|--------|-------------|
| path/to/file.py | Modified | Added retry logic to fetch handler |
| path/to/new.py | Created | New utility for token refresh |
| path/to/old.py | Deleted | Removed deprecated auth helper |
The agent MUST produce all three sections before marking a work item complete.
When to Apply This Skill
Use git-expert skill when working with:
- ✅ Git version control operations (commit, branch, merge, rebase)
- ✅ Branching strategies and workflows
- ✅ Conflict resolution and troubleshooting
- ✅ Advanced Git operations (cherry-pick, bisect, reflog)
- ✅ History rewriting (interactive rebase, amend)
- ✅ Git configuration and aliases
- ✅ Submodules and worktrees
- ✅ Git hooks for automation
- ✅ Repository maintenance and optimization
Resources
- Pro Git Book - Comprehensive Git guide
- Git Documentation
- Atlassian Git Tutorials
- Oh My Git! - Interactive Git learning game
- Conventional Commits
- Git Flight Rules - Troubleshooting guide
Related Assets
Git Worktree Enforcement
Mandatory git worktree policy preventing branch conflicts and lost work by requiring all feature work in worktrees/ subdirectories.
Owner: platform-devops
git-worktree-enforcement
Mandatory git worktree policy ensuring feature work happens in worktrees/ subdirectories, not the main clone
Owner: platform-devops
Prune Git Worktrees
Safely prune git worktrees whose branches have been merged into the remote default. Uses authoritative gh API merged-PR detection plus remote-branch and ancestry checks. Skips worktrees with uncommitted or unpushed work.
Owner: epic-platform-sre
prune-worktrees
Safely prune git worktrees whose branches have been merged into the remote default. Uses authoritative gh API merged-PR detection plus remote-branch and ancestry checks. Skips worktrees with uncommitted or unpushed work. Use when the user asks to "prune worktrees", "clean up worktrees", "remove old worktrees", "cleanup git worktrees", or wants to know "which worktrees are safe to delete". Trigger phrases include "git hygiene", "worktree cleanup", "stale worktrees".
Owner: epic-platform-sre

