git-advanced
Advanced Git operations and workflows including interactive rebasing, conflict resolution, history manipulation, bisecting for bugs, cherry-picking, reflog recovery, and branch management strategies. Use for: (1) Interactive rebasing and commit cleanup, (2) Complex merge conflict resolution, (3) Git bisect for bug hunting, (4) History rewriting and cleanup, (5) Branch strategy implementation (Git Flow, trunk-based), (6) Recovering lost commits with reflog
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install benchflow-ai-skillsbench-git-advanced
Repository
Skill path: registry/terminal_bench_2.0/full_batch_reviewed/terminal_bench_2_0_merge-diff-arc-agi-task/environment/skills/git-advanced
Advanced Git operations and workflows including interactive rebasing, conflict resolution, history manipulation, bisecting for bugs, cherry-picking, reflog recovery, and branch management strategies. Use for: (1) Interactive rebasing and commit cleanup, (2) Complex merge conflict resolution, (3) Git bisect for bug hunting, (4) History rewriting and cleanup, (5) Branch strategy implementation (Git Flow, trunk-based), (6) Recovering lost commits with reflog
Open repositoryBest for
Primary workflow: Ship Full Stack.
Technical facets: Full Stack.
Target audience: everyone.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: benchflow-ai.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install git-advanced into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/benchflow-ai/SkillsBench before adding git-advanced to shared team environments
- Use git-advanced for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: git-advanced
description: "Advanced Git operations and workflows including interactive rebasing, conflict resolution, history manipulation, bisecting for bugs, cherry-picking, reflog recovery, and branch management strategies. Use for: (1) Interactive rebasing and commit cleanup, (2) Complex merge conflict resolution, (3) Git bisect for bug hunting, (4) History rewriting and cleanup, (5) Branch strategy implementation (Git Flow, trunk-based), (6) Recovering lost commits with reflog"
---
# Advanced Git Operations
## Overview
Master advanced Git workflows for complex version control scenarios. This skill covers sophisticated operations beyond basic commits and merges, including interactive rebasing, advanced conflict resolution, history manipulation, and strategic branch management.
Use this skill when you need to:
- Clean up messy commit history before code review
- Resolve complex merge conflicts strategically
- Hunt down bugs with binary search (bisect)
- Recover lost commits or undo mistakes
- Implement team branching strategies
- Rewrite history safely
## Core Capabilities
### Interactive Rebasing
- Reorder commits for logical history
- Squash multiple commits into one
- Edit commit messages retroactively
- Split commits into smaller pieces
- Remove unwanted commits from history
### Conflict Resolution
- Strategic merge conflict handling
- Three-way merge understanding
- Ours vs theirs strategy selection
- Conflict marker interpretation
- Partial file staging during conflicts
### Git Bisect
- Binary search for bug introduction
- Automated bisect with scripts
- Good/bad commit identification
- Efficient debugging of regressions
### History Manipulation
- Amend commits safely
- Filter-branch operations
- BFG Repo-Cleaner for large files
- Rewrite history with caution
- Preserve attribution and dates
### Branch Strategies
- Git Flow workflow
- Trunk-based development
- Feature branch workflows
- Release branch management
- Hotfix procedures
## Quick Command Reference
### Interactive Rebase
```bash
# Rebase last 5 commits interactively
git rebase -i HEAD~5
# Rebase onto main branch
git rebase -i main
# Continue after resolving conflicts
git rebase --continue
# Abort and return to original state
git rebase --abort
```
### Conflict Resolution
```bash
# Accept ours (current branch)
git checkout --ours <file>
# Accept theirs (incoming branch)
git checkout --theirs <file>
# List conflicted files
git diff --name-only --diff-filter=U
# Mark as resolved
git add <file>
```
### Git Bisect
```bash
# Start bisect session
git bisect start
git bisect bad
git bisect good <commit-hash>
# Automate with test script
git bisect run ./test-script.sh
# End bisect session
git bisect reset
```
### Cherry-Pick
```bash
# Apply specific commit
git cherry-pick <commit-hash>
# Cherry-pick without committing
git cherry-pick -n <commit-hash>
# Cherry-pick range of commits
git cherry-pick A^..B
```
### Reflog Recovery
```bash
# View reflog history
git reflog
# Recover lost commit
git checkout -b recovery <commit-hash>
# Reset to previous state
git reset --hard HEAD@{2}
```
## Core Workflows
### 1. Interactive Rebase Workflow
**When to Use:**
- Clean up messy commit history before pushing
- Combine "WIP" or "fix typo" commits
- Reorder commits for logical progression
- Split large commits into focused changes
**Steps:**
```bash
# 1. Start interactive rebase for last N commits
git rebase -i HEAD~5
# Interactive editor opens with commit list
# Modify commands to reorganize history
```
**Rebase Commands:**
- `pick` (p): Keep commit as-is
- `reword` (r): Keep commit, edit message
- `edit` (e): Keep commit, stop to amend
- `squash` (s): Combine with previous commit, keep message
- `fixup` (f): Combine with previous commit, discard message
- `drop` (d): Remove commit entirely
**Example:**
```bash
# Before
pick abc1234 Add feature X
pick def5678 Fix typo
pick ghi9012 WIP commit
pick jkl3456 Update documentation
# After cleanup
pick abc1234 Add feature X
fixup def5678 Fix typo
drop ghi9012 WIP commit
reword jkl3456 Update documentation
```
**Safety Tips:**
- Never rebase commits already pushed to shared branches
- Create backup branch: `git branch backup`
- Use `git reflog` if something goes wrong
- Force push carefully: `git push --force-with-lease`
For detailed examples and advanced techniques, see `examples/interactive_rebase.md`.
### 2. Conflict Resolution Workflow
**Understanding Conflict Markers:**
```
<<<<<<< HEAD (Current Change)
Your code from current branch
=======
Their code from merging branch
>>>>>>> branch-name (Incoming Change)
```
**Resolution Process:**
```bash
# 1. Identify conflicts
git status
# 2. Choose resolution strategy:
# Strategy A: Manual resolution
vim <file> # Edit between markers
git add <file>
# Strategy B: Accept one side
git checkout --ours <file> # Keep yours
git checkout --theirs <file> # Keep theirs
git add <file>
# Strategy C: Use merge tool
git mergetool
# 3. Continue operation
git merge --continue
# or
git rebase --continue
```
**Three-Way Diff:**
```bash
# Show what YOU changed
git diff --ours <file>
# Show what THEY changed
git diff --theirs <file>
# Show common ancestor
git diff --base <file>
```
For common conflict patterns and solutions, see `examples/conflict_resolution.md`.
### 3. Git Bisect for Bug Hunting
**Scenario:** Bug exists in current version, find which commit introduced it.
**Manual Bisect:**
```bash
# 1. Start bisect
git bisect start
# 2. Mark current state as bad
git bisect bad
# 3. Mark known good commit
git bisect good v1.0.0
# 4. Test the code (Git checks out middle commit)
# Run app, check if bug exists
# 5. Mark result
git bisect bad # If bug exists
git bisect good # If bug doesn't exist
# Repeat until Git finds first bad commit
# 6. End bisect
git bisect reset
```
**Automated Bisect:**
```bash
# Create test script (test.sh)
#!/bin/bash
npm test
exit $?
# Run automated bisect
git bisect start
git bisect bad
git bisect good v1.0.0
git bisect run ./test.sh
# Git automatically finds bad commit
git bisect reset
```
### 4. Branch Management
**Quick Cleanup:**
```bash
# Use helper script
bash scripts/git_helper.sh cleanup-branches
# Or manual cleanup
git branch --merged main | grep -v "\*\|main\|develop" | xargs git branch -d
git fetch --prune
```
**Stale Branch Detection:**
```bash
# Show branches with last commit date
for branch in $(git branch -r | grep -v HEAD); do
echo -e "$(git show --format="%ci %cr" $branch | head -n 1)\t$branch"
done | sort -r
```
For detailed branch management strategies, see `references/branch-management.md`.
### 5. Reflog Recovery
**Recover Deleted Branch:**
```bash
# View reflog
git reflog
# Find commit where branch was deleted
# Restore branch
git checkout -b feature-x <commit-hash>
```
**Undo Bad Reset:**
```bash
# Accidentally ran: git reset --hard HEAD~5
# View reflog
git reflog
# Restore previous state
git reset --hard HEAD@{1}
```
**Recover Lost Commits:**
```bash
# Find dangling commits
git fsck --lost-found
# Cherry-pick recovered commit
git cherry-pick <lost-commit-hash>
```
For comprehensive recovery techniques, see `references/reflog-recovery.md`.
## Branch Strategy Implementation
This skill supports implementing various branching strategies. Choose based on your team's needs:
### Git Flow
**Best for:** Projects with scheduled releases, multiple production versions
**Branch Types:**
- `main`: Production-ready code
- `develop`: Integration branch
- `feature/*`: New features
- `release/*`: Release preparation
- `hotfix/*`: Production fixes
**Quick Start:**
```bash
# Feature development
git checkout develop
git checkout -b feature/user-auth
# Work on feature
git checkout develop
git merge --no-ff feature/user-auth
```
### Trunk-Based Development
**Best for:** Continuous deployment, fast-moving teams
**Principles:**
- Single main branch
- Short-lived feature branches (< 1 day)
- Frequent integration
- Feature flags for incomplete work
**Quick Start:**
```bash
# Create short-lived branch
git checkout main
git checkout -b feature/quick-fix
# Work and merge same day
git checkout main
git merge feature/quick-fix
```
For complete branch strategy workflows, see `examples/branch_strategies.md`.
## Best Practices
### Before Rebase
- Create backup branch: `git branch backup`
- Ensure working directory is clean: `git status`
- Know your commit history: `git log --oneline`
- Never rebase public/shared branches
### During Conflicts
- Understand both sides of the conflict
- Test thoroughly after resolution
- Use meaningful merge commit messages
- Document complex resolutions
### Branch Management
- Delete merged branches promptly
- Use descriptive branch names: `feature/user-login`
- Keep branches focused and short-lived
- Sync with main branch regularly
### History Hygiene
- Squash "fixup" commits before pushing
- Write clear, descriptive commit messages
- Keep commits atomic (one logical change)
- Use conventional commit format when possible
For comprehensive best practices, see `references/best-practices.md`.
## Troubleshooting
### Rebase Conflicts
```bash
# If conflicts are too complex
git rebase --abort
# Start over with different approach
git merge --no-ff <branch>
```
### Lost Commits
```bash
# Always check reflog first
git reflog
# Find and recover
git checkout -b recovery <commit-hash>
```
### Detached HEAD State
```bash
# Create branch from detached HEAD
git checkout -b new-branch-name
# Or go back to branch
git checkout main
```
### Failed Push After Rebase
```bash
# Only if you're certain and branch is not shared
git push --force-with-lease
# Safer: Create new branch
git checkout -b feature-v2
git push origin feature-v2
```
For detailed troubleshooting, see `references/troubleshooting.md`.
## Additional Resources
### Detailed Guides
- `examples/interactive_rebase.md`: Step-by-step rebase examples with scenarios
- `examples/conflict_resolution.md`: Common conflict patterns and solutions
- `examples/branch_strategies.md`: Complete Git Flow and trunk-based workflows
### Reference Documentation
- `references/branch-management.md`: Branch cleanup automation and strategies
- `references/reflog-recovery.md`: Recovery techniques and history rewriting
- `references/best-practices.md`: Comprehensive best practices and quality standards
- `references/troubleshooting.md`: Common issues and emergency recovery
### Helper Scripts
- `scripts/git_helper.sh`: Branch cleanup and conflict resolution utilities
## Quick Reference Commands
### Must-Know Commands
```bash
# Interactive rebase
git rebase -i HEAD~N
# Abort operations
git rebase --abort
git merge --abort
git cherry-pick --abort
# View history
git log --oneline --graph --all
git reflog
# Conflict resolution
git checkout --ours <file>
git checkout --theirs <file>
# Recovery
git fsck --lost-found
git reflog
# Cleanup
git branch --merged | xargs git branch -d
git fetch --prune
```
### Safety First
1. Always backup before history rewrite: `git branch backup`
2. Never force push to shared branches: Use `--force-with-lease`
3. Test after conflicts: Don't assume resolution is correct
4. Document complex operations: Leave comments in merge commits
5. Use reflog: It's your safety net for 30+ days
---
Master these advanced Git operations to maintain clean history, resolve conflicts efficiently, and manage complex development workflows with confidence.
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### scripts/git_helper.sh
```bash
#!/bin/bash
# Git Advanced Helper Script
# Utilities for branch cleanup, conflict resolution, and history management
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Helper functions
print_header() {
echo -e "\n${BLUE}==== $1 ====${NC}\n"
}
print_success() {
echo -e "${GREEN}✓ $1${NC}"
}
print_warning() {
echo -e "${YELLOW}⚠ $1${NC}"
}
print_error() {
echo -e "${RED}✗ $1${NC}"
}
confirm() {
read -p "$1 (y/n): " -n 1 -r
echo
[[ $REPLY =~ ^[Yy]$ ]]
}
# Check if we're in a git repository
check_git_repo() {
if ! git rev-parse --git-dir > /dev/null 2>&1; then
print_error "Not a git repository!"
exit 1
fi
}
# Branch cleanup function
cleanup_branches() {
print_header "Branch Cleanup Utility"
check_git_repo
# Get current branch
current_branch=$(git branch --show-current)
print_warning "Current branch: $current_branch"
# Show merged branches
echo -e "\n${YELLOW}Merged branches (safe to delete):${NC}"
git branch --merged | grep -v "\*\|main\|master\|develop\|development"
if confirm "Delete all merged branches?"; then
git branch --merged | grep -v "\*\|main\|master\|develop\|development" | xargs -r git branch -d
print_success "Merged branches deleted"
fi
# Show stale branches
echo -e "\n${YELLOW}Branches with no commits in last 30 days:${NC}"
for branch in $(git for-each-ref --format='%(refname:short)' refs/heads/); do
if [ "$branch" != "$current_branch" ] && [ "$branch" != "main" ] && [ "$branch" != "master" ] && [ "$branch" != "develop" ]; then
last_commit=$(git log -1 --format="%cr" "$branch")
echo " $branch - Last commit: $last_commit"
fi
done
# Prune remote branches
if confirm "Prune remote tracking branches?"; then
git fetch --prune
print_success "Remote branches pruned"
fi
# Show branch count
total_branches=$(git branch | wc -l)
print_success "Total local branches: $total_branches"
}
# Conflict resolution helper
resolve_conflicts() {
print_header "Conflict Resolution Helper"
check_git_repo
# Check if there are conflicts
if ! git diff --name-only --diff-filter=U | grep -q .; then
print_success "No conflicts found!"
return 0
fi
# List conflicted files
echo -e "${YELLOW}Conflicted files:${NC}"
git diff --name-only --diff-filter=U | while read file; do
echo " - $file"
done
echo -e "\n${BLUE}Resolution options:${NC}"
echo " 1. Accept ours (current branch)"
echo " 2. Accept theirs (incoming branch)"
echo " 3. Manual resolution (open merge tool)"
echo " 4. Show conflict diff"
echo " 5. Exit"
read -p "Choose option (1-5): " option
conflicted_files=$(git diff --name-only --diff-filter=U)
case $option in
1)
for file in $conflicted_files; do
git checkout --ours "$file"
git add "$file"
print_success "Accepted 'ours' for $file"
done
;;
2)
for file in $conflicted_files; do
git checkout --theirs "$file"
git add "$file"
print_success "Accepted 'theirs' for $file"
done
;;
3)
git mergetool
;;
4)
for file in $conflicted_files; do
echo -e "\n${YELLOW}=== $file ===${NC}"
echo -e "\n${BLUE}Changes from 'ours':${NC}"
git diff --ours "$file"
echo -e "\n${BLUE}Changes from 'theirs':${NC}"
git diff --theirs "$file"
done
;;
5)
print_warning "Exiting without resolving conflicts"
exit 0
;;
*)
print_error "Invalid option"
exit 1
;;
esac
# Check if all conflicts resolved
if ! git diff --name-only --diff-filter=U | grep -q .; then
print_success "All conflicts resolved!"
if confirm "Continue merge/rebase?"; then
if git status | grep -q "rebase in progress"; then
git rebase --continue
elif git status | grep -q "merge in progress"; then
git merge --continue
elif git status | grep -q "cherry-pick in progress"; then
git cherry-pick --continue
fi
fi
else
print_warning "Some conflicts still remain"
fi
}
# Interactive rebase helper
rebase_helper() {
print_header "Interactive Rebase Helper"
check_git_repo
current_branch=$(git branch --show-current)
print_warning "Current branch: $current_branch"
echo -e "\n${BLUE}Rebase options:${NC}"
echo " 1. Rebase last N commits"
echo " 2. Rebase onto another branch"
echo " 3. Abort current rebase"
echo " 4. Continue rebase"
echo " 5. Skip current commit"
read -p "Choose option (1-5): " option
case $option in
1)
read -p "Number of commits to rebase: " num_commits
if ! [[ "$num_commits" =~ ^[0-9]+$ ]]; then
print_error "Invalid number"
exit 1
fi
print_warning "Starting interactive rebase of last $num_commits commits"
git rebase -i HEAD~"$num_commits"
;;
2)
read -p "Branch to rebase onto: " target_branch
if ! git rev-parse --verify "$target_branch" >/dev/null 2>&1; then
print_error "Branch '$target_branch' does not exist"
exit 1
fi
print_warning "Rebasing $current_branch onto $target_branch"
git rebase -i "$target_branch"
;;
3)
if confirm "Abort current rebase?"; then
git rebase --abort
print_success "Rebase aborted"
fi
;;
4)
git rebase --continue
print_success "Continuing rebase"
;;
5)
if confirm "Skip current commit in rebase?"; then
git rebase --skip
print_success "Commit skipped"
fi
;;
*)
print_error "Invalid option"
exit 1
;;
esac
}
# Branch history visualizer
show_history() {
print_header "Branch History Visualization"
check_git_repo
echo -e "${YELLOW}Graph view of last 20 commits:${NC}"
git log --oneline --graph --all -20 --decorate --color
echo -e "\n${YELLOW}Recent commits on current branch:${NC}"
git log --oneline -10 --color
echo -e "\n${YELLOW}Reflog (recent HEAD positions):${NC}"
git reflog -10 --color
}
# Find large files in history
find_large_files() {
print_header "Large Files in Git History"
check_git_repo
echo -e "${YELLOW}Finding large files in repository history...${NC}\n"
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 -n 20 |
while read hash size path; do
size_mb=$(echo "scale=2; $size / 1048576" | bc)
echo " $size_mb MB - $path"
done
echo -e "\n${BLUE}To remove large files from history:${NC}"
echo " git filter-branch --tree-filter 'rm -f <file>' HEAD"
echo " or use BFG Repo-Cleaner (faster): java -jar bfg.jar --delete-files <file>"
}
# Backup current branch
backup_branch() {
print_header "Create Branch Backup"
check_git_repo
current_branch=$(git branch --show-current)
backup_name="${current_branch}-backup-$(date +%Y%m%d-%H%M%S)"
git branch "$backup_name"
print_success "Created backup branch: $backup_name"
}
# Stash helper
stash_helper() {
print_header "Stash Management"
check_git_repo
echo -e "${BLUE}Stash options:${NC}"
echo " 1. Create new stash"
echo " 2. List all stashes"
echo " 3. Apply latest stash"
echo " 4. Pop latest stash"
echo " 5. Drop a stash"
echo " 6. Clear all stashes"
read -p "Choose option (1-6): " option
case $option in
1)
read -p "Stash message: " message
git stash push -m "$message"
print_success "Stash created"
;;
2)
git stash list
;;
3)
git stash apply
print_success "Stash applied (kept in stash list)"
;;
4)
git stash pop
print_success "Stash popped (removed from list)"
;;
5)
git stash list
read -p "Stash number to drop (e.g., 0): " stash_num
git stash drop "stash@{$stash_num}"
print_success "Stash dropped"
;;
6)
if confirm "Clear ALL stashes?"; then
git stash clear
print_success "All stashes cleared"
fi
;;
*)
print_error "Invalid option"
exit 1
;;
esac
}
# Main menu
show_menu() {
echo -e "\n${GREEN}╔════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Git Advanced Helper Script ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════╝${NC}\n"
echo -e "${BLUE}Available commands:${NC}"
echo " 1. cleanup-branches - Clean up merged and stale branches"
echo " 2. resolve-conflicts - Help resolve merge conflicts"
echo " 3. rebase-helper - Interactive rebase assistance"
echo " 4. show-history - Visualize branch history"
echo " 5. find-large-files - Find large files in history"
echo " 6. backup-branch - Create backup of current branch"
echo " 7. stash-helper - Manage stashes"
echo " 8. exit - Exit"
echo ""
}
# Main script
main() {
if [ $# -eq 0 ]; then
# Interactive mode
while true; do
show_menu
read -p "Choose a command (1-8): " cmd
case $cmd in
1|cleanup-branches)
cleanup_branches
;;
2|resolve-conflicts)
resolve_conflicts
;;
3|rebase-helper)
rebase_helper
;;
4|show-history)
show_history
;;
5|find-large-files)
find_large_files
;;
6|backup-branch)
backup_branch
;;
7|stash-helper)
stash_helper
;;
8|exit)
print_success "Goodbye!"
exit 0
;;
*)
print_error "Invalid command"
;;
esac
done
else
# Direct command mode
case $1 in
cleanup-branches)
cleanup_branches
;;
resolve-conflicts)
resolve_conflicts
;;
rebase-helper)
rebase_helper
;;
show-history)
show_history
;;
find-large-files)
find_large_files
;;
backup-branch)
backup_branch
;;
stash-helper)
stash_helper
;;
*)
echo "Usage: $0 [cleanup-branches|resolve-conflicts|rebase-helper|show-history|find-large-files|backup-branch|stash-helper]"
exit 1
;;
esac
fi
}
# Run main function
main "$@"
```
### examples/interactive_rebase.md
```markdown
# Interactive Rebase Workflow Guide
## Overview
Interactive rebasing is one of the most powerful features in Git for cleaning up commit history before sharing your work. This guide provides practical examples and workflows for common rebase scenarios.
## Basic Interactive Rebase
### Scenario 1: Squash Multiple "WIP" Commits
**Starting History:**
```
abc1234 WIP: still working on feature
def5678 WIP: almost done
ghi9012 WIP: testing changes
jkl3456 Add user authentication feature
```
**Goal:** Combine all WIP commits into one clean commit.
**Steps:**
```bash
# Start interactive rebase for last 4 commits
git rebase -i HEAD~4
# Editor opens with:
pick jkl3456 Add user authentication feature
pick ghi9012 WIP: testing changes
pick def5678 WIP: almost done
pick abc1234 WIP: still working on feature
# Change to:
pick jkl3456 Add user authentication feature
squash ghi9012 WIP: testing changes
squash def5678 WIP: almost done
squash abc1234 WIP: still working on feature
# Save and close editor
# New editor opens for combined commit message
# Edit to single clean message:
Add user authentication feature
Implemented JWT-based authentication with:
- Login endpoint
- Token validation middleware
- Session management
- Password hashing with bcrypt
```
**Result:**
```
mno7890 Add user authentication feature
```
### Scenario 2: Reorder Commits Logically
**Starting History:**
```
aaa1111 Update documentation
bbb2222 Add tests for feature X
ccc3333 Implement feature X
ddd4444 Fix typo in README
```
**Goal:** Reorder so feature, tests, and docs are together.
**Steps:**
```bash
git rebase -i HEAD~4
# Change order:
pick ccc3333 Implement feature X
pick bbb2222 Add tests for feature X
pick aaa1111 Update documentation
pick ddd4444 Fix typo in README
```
**Result:**
```
ccc3333 Implement feature X
bbb2222 Add tests for feature X
aaa1111 Update documentation
ddd4444 Fix typo in README
```
### Scenario 3: Edit a Commit in the Middle
**Starting History:**
```
111aaaa Add feature A
222bbbb Add feature B (forgot to add file)
333cccc Add feature C
```
**Goal:** Add forgotten file to feature B commit.
**Steps:**
```bash
git rebase -i HEAD~3
# Mark commit for editing:
pick 111aaaa Add feature A
edit 222bbbb Add feature B
pick 333cccc Add feature C
# Git stops at 222bbbb
# Add the forgotten file
git add forgotten-file.js
git commit --amend --no-edit
# Continue rebase
git rebase --continue
```
### Scenario 4: Split a Large Commit
**Starting History:**
```
xyz9999 Implement user management and email notifications
```
**Goal:** Split into two focused commits.
**Steps:**
```bash
git rebase -i HEAD~1
# Mark for editing:
edit xyz9999 Implement user management and email notifications
# Git stops at the commit
# Reset to previous commit but keep changes
git reset HEAD~
# Stage and commit user management
git add src/user-manager.js tests/user-manager.test.js
git commit -m "Implement user management module"
# Stage and commit email notifications
git add src/email-notifier.js tests/email-notifier.test.js
git commit -m "Add email notification system"
# Continue rebase
git rebase --continue
```
**Result:**
```
aaa1111 Implement user management module
bbb2222 Add email notification system
```
## Advanced Rebase Techniques
### Using Fixup for Quick Fixes
**Workflow:**
```bash
# Make initial commit
git add feature.js
git commit -m "Add new feature"
# Continue working, find a typo in feature.js
git add feature.js
git commit --fixup HEAD # or commit hash
# Later, before pushing:
git rebase -i --autosquash HEAD~2
# Automatically arranges fixup commits
```
### Exec Command for Testing
**Ensure all commits pass tests:**
```bash
git rebase -i HEAD~5
# Add exec commands:
pick aaa1111 Add feature A
exec npm test
pick bbb2222 Add feature B
exec npm test
pick ccc3333 Add feature C
exec npm test
# Rebase stops if any test fails
# Fix the issue, amend, and continue
```
### Rebase with Conflict Resolution
**When conflicts occur during rebase:**
```bash
git rebase -i main
# Conflict in some-file.js
# Output: CONFLICT (content): Merge conflict in some-file.js
# Resolve conflict
vim some-file.js # Edit and resolve markers
# Stage resolved file
git add some-file.js
# Continue rebase
git rebase --continue
# Repeat for any additional conflicts
# If rebase becomes too complex:
git rebase --abort # Start over
```
## Rebase Strategies by Scenario
### Before Pull Request
**Goal:** Clean history before code review.
```bash
# Fetch latest main
git fetch origin main
# Interactive rebase onto main
git rebase -i origin/main
# Common cleanup:
# 1. Squash WIP/fixup commits
# 2. Reword unclear messages
# 3. Reorder related commits
# 4. Drop debug commits
```
### After Code Review Feedback
**Goal:** Incorporate review changes cleanly.
```bash
# Make changes based on feedback
git add .
git commit --fixup <original-commit-hash>
# Before pushing updates:
git rebase -i --autosquash origin/main
```
### Syncing Feature Branch with Main
**Goal:** Keep feature branch up to date.
```bash
# Fetch latest main
git fetch origin main
# Rebase feature onto main
git checkout feature-branch
git rebase origin/main
# Resolve any conflicts
# Force push to update PR
git push --force-with-lease origin feature-branch
```
## Best Practices
### DO:
- ✅ Rebase local commits before pushing
- ✅ Create backup branch: `git branch backup`
- ✅ Use descriptive commit messages after squashing
- ✅ Test after rebasing
- ✅ Use `--force-with-lease` instead of `--force`
### DON'T:
- ❌ Rebase commits already pushed to shared branches
- ❌ Rebase main/master branches
- ❌ Rebase without backing up
- ❌ Force push to branches others are working on
- ❌ Rebase if you don't understand the consequences
## Troubleshooting
### Rebase Conflicts Are Too Complex
```bash
# Abort and try merge instead
git rebase --abort
git merge main
```
### Made a Mistake During Rebase
```bash
# Check reflog
git reflog
# Find state before rebase started
# Example: abc1234 HEAD@{5}: rebase -i (start)
# Reset to that state
git reset --hard HEAD@{5}
```
### Want to Undo Last Rebase
```bash
# Immediately after rebase
git reflog
# Find ORIG_HEAD
git reset --hard ORIG_HEAD
```
### Rebase in Progress, Not Sure How to Continue
```bash
# Check status
git status
# Options:
git rebase --continue # After resolving conflicts
git rebase --skip # Skip current commit
git rebase --abort # Cancel rebase
```
## Rebase Commands Quick Reference
### Rebase Actions:
- `pick` (p) - Use commit as-is
- `reword` (r) - Use commit, edit message
- `edit` (e) - Use commit, stop for amending
- `squash` (s) - Combine with previous, keep both messages
- `fixup` (f) - Combine with previous, discard this message
- `drop` (d) - Remove commit
- `exec` (x) - Run shell command
### Useful Flags:
- `-i` - Interactive mode
- `--autosquash` - Auto-arrange fixup/squash commits
- `--continue` - Continue after resolving conflicts
- `--skip` - Skip current commit
- `--abort` - Cancel rebase
- `--onto` - Rebase onto different base
## Example: Complete Feature Branch Cleanup
**Starting point:**
```bash
git log --oneline
abc1234 Fix linting errors
def5678 WIP: debugging
ghi9012 Add tests
jkl3456 WIP: implement feature
mno7890 Initial feature structure
pqr1234 Update README
```
**Cleanup process:**
```bash
# 1. Create backup
git branch backup-feature
# 2. Start interactive rebase
git rebase -i HEAD~6
# 3. Reorganize:
pick mno7890 Initial feature structure
squash jkl3456 WIP: implement feature
pick ghi9012 Add tests
drop def5678 WIP: debugging
fixup abc1234 Fix linting errors
pick pqr1234 Update README
# 4. Edit commit messages when prompted
# 5. Verify result
git log --oneline
# Result:
zzz9999 Implement user authentication feature
yyy8888 Add comprehensive tests for authentication
xxx7777 Update README with authentication docs
# 6. Force push (if already on remote)
git push --force-with-lease origin feature-branch
```
---
**Remember:** Interactive rebase is a powerful tool. Use it to create clean, logical commit history that tells a clear story of your changes.
```
### examples/conflict_resolution.md
```markdown
# Git Conflict Resolution Patterns
## Overview
Merge conflicts are inevitable in collaborative development. This guide covers common conflict patterns, resolution strategies, and best practices for handling conflicts efficiently and safely.
## Understanding Conflict Markers
### Basic Conflict Structure
```
<<<<<<< HEAD (Current Change)
This is the code from your current branch
=======
This is the code from the branch you're merging
>>>>>>> feature-branch (Incoming Change)
```
### Anatomy of Conflict Markers
- `<<<<<<< HEAD`: Start of your changes (current branch)
- `=======`: Separator between the two versions
- `>>>>>>> branch-name`: End of incoming changes
- Everything between `<<<<<<<` and `=======` is YOUR code
- Everything between `=======` and `>>>>>>>` is THEIR code
## Common Conflict Patterns
### Pattern 1: Simple Line Modification
**Scenario:** Same line modified in both branches.
**Conflict:**
```javascript
<<<<<<< HEAD
const API_URL = 'https://api.production.com';
=======
const API_URL = 'https://api.staging.com';
>>>>>>> feature-branch
```
**Resolution Options:**
**Option A - Keep Yours:**
```javascript
const API_URL = 'https://api.production.com';
```
**Option B - Keep Theirs:**
```javascript
const API_URL = 'https://api.staging.com';
```
**Option C - Combine (Best):**
```javascript
const API_URL = process.env.NODE_ENV === 'production'
? 'https://api.production.com'
: 'https://api.staging.com';
```
**Commands:**
```bash
# Accept yours
git checkout --ours src/config.js
# Accept theirs
git checkout --theirs src/config.js
# Manual resolution
vim src/config.js # Edit manually
git add src/config.js
```
### Pattern 2: Adjacent Line Changes
**Scenario:** Changes on adjacent lines.
**Conflict:**
```python
def calculate_total(items):
<<<<<<< HEAD
subtotal = sum(item.price for item in items)
tax = subtotal * 0.08
=======
subtotal = sum(item.price * item.quantity for item in items)
shipping = 5.99
>>>>>>> feature-branch
return subtotal + tax
```
**Resolution (Combine Both):**
```python
def calculate_total(items):
subtotal = sum(item.price * item.quantity for item in items)
tax = subtotal * 0.08
shipping = 5.99
return subtotal + tax + shipping
```
### Pattern 3: Function Signature Change
**Scenario:** Function modified in different ways.
**Conflict:**
```javascript
<<<<<<< HEAD
function createUser(username, email, role) {
return {
username,
email,
role,
createdAt: new Date()
};
}
=======
function createUser(username, email) {
return {
id: generateId(),
username,
email,
createdAt: new Date()
};
}
>>>>>>> feature-branch
```
**Resolution (Merge Features):**
```javascript
function createUser(username, email, role = 'user') {
return {
id: generateId(),
username,
email,
role,
createdAt: new Date()
};
}
```
### Pattern 4: Import Conflicts
**Scenario:** Different imports added.
**Conflict:**
```javascript
import React from 'react';
<<<<<<< HEAD
import { useState, useEffect } from 'react';
import axios from 'axios';
=======
import { useState, useCallback } from 'react';
import { api } from './api';
>>>>>>> feature-branch
```
**Resolution:**
```javascript
import React from 'react';
import { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import { api } from './api';
```
### Pattern 5: File Deleted vs Modified
**Scenario:** One branch deleted file, other modified it.
**Conflict Output:**
```
CONFLICT (modify/delete): src/old-component.js deleted in HEAD and modified in feature-branch.
```
**Resolution:**
```bash
# Keep deletion (remove file)
git rm src/old-component.js
# Keep modification (restore file)
git checkout feature-branch -- src/old-component.js
git add src/old-component.js
# Commit resolution
git commit
```
### Pattern 6: Rename Conflicts
**Scenario:** File renamed differently in each branch.
**Conflict:**
```
CONFLICT (rename/rename):
Rename src/utils.js -> src/helpers.js in HEAD
Rename src/utils.js -> src/utilities.js in feature-branch
```
**Resolution:**
```bash
# Choose one name
git mv src/helpers.js src/utilities.js
git add src/utilities.js
# Or keep both
git add src/helpers.js src/utilities.js
# Then update imports accordingly
```
## Resolution Strategies
### Strategy 1: Accept All Ours
**When to Use:**
- Your branch is correct
- Incoming changes should be discarded
- Emergency hotfix takes precedence
**Commands:**
```bash
# For all conflicts
git checkout --ours .
git add .
# For specific file
git checkout --ours path/to/file.js
git add path/to/file.js
```
### Strategy 2: Accept All Theirs
**When to Use:**
- Main/develop is correct
- Your changes are outdated
- Rebasing onto updated base
**Commands:**
```bash
# For all conflicts
git checkout --theirs .
git add .
# For specific file
git checkout --theirs path/to/file.js
git add path/to/file.js
```
### Strategy 3: Manual Merge
**When to Use:**
- Need to combine both changes
- Complex logic requires understanding
- Most common scenario
**Process:**
```bash
# 1. Identify conflicts
git status
git diff --name-only --diff-filter=U
# 2. Open file in editor
vim path/to/conflicted-file.js
# 3. Find conflict markers
/<<<<<< # Search in vim
# 4. Edit to combine changes
# Remove markers, keep/combine code
# 5. Test the resolution
npm test
# 6. Stage resolved file
git add path/to/conflicted-file.js
# 7. Verify no conflicts remain
git diff --check
# 8. Continue merge
git merge --continue
# or
git rebase --continue
```
### Strategy 4: Use Merge Tool
**Configure Merge Tool:**
```bash
# One-time setup
git config --global merge.tool vimdiff
# or: meld, kdiff3, p4merge, opendiff
git config --global mergetool.prompt false
git config --global mergetool.keepBackup false
```
**Use Merge Tool:**
```bash
# Launch for all conflicts
git mergetool
# Launch for specific file
git mergetool path/to/file.js
# After resolving, clean up
git clean -f *.orig # Remove backup files
```
### Strategy 5: Three-Way Diff
**Understand All Perspectives:**
```bash
# Show what YOU changed
git diff --ours path/to/file.js
# Show what THEY changed
git diff --theirs path/to/file.js
# Show common ancestor (base)
git diff --base path/to/file.js
# All three in sequence
git show :1:path/to/file.js # Base
git show :2:path/to/file.js # Ours
git show :3:path/to/file.js # Theirs
```
## Workflow Examples
### Example 1: Merge Conflict During Pull
**Scenario:**
```bash
git pull origin main
# Auto-merging src/app.js
# CONFLICT (content): Merge conflict in src/app.js
```
**Resolution:**
```bash
# 1. Check what's conflicted
git status
# 2. View the conflict
git diff src/app.js
# 3. Edit file manually
vim src/app.js
# Resolve conflicts, remove markers
# 4. Test changes
npm test
# 5. Stage resolved file
git add src/app.js
# 6. Complete merge
git commit # Or git merge --continue
# 7. Push
git push origin feature-branch
```
### Example 2: Rebase Conflict Resolution
**Scenario:**
```bash
git rebase main
# CONFLICT (content): Merge conflict in src/api.js
```
**Resolution:**
```bash
# 1. Check status
git status
# rebase in progress; onto abc1234
# 2. View conflict
git diff src/api.js
# 3. Resolve conflict
vim src/api.js
# 4. Stage resolution
git add src/api.js
# 5. Continue rebase
git rebase --continue
# 6. Repeat for each conflict until done
# 7. Force push (use with caution)
git push --force-with-lease origin feature-branch
```
### Example 3: Cherry-Pick Conflict
**Scenario:**
```bash
git cherry-pick abc1234
# CONFLICT (content): Merge conflict in src/utils.js
```
**Resolution:**
```bash
# 1. Resolve conflict
vim src/utils.js
# 2. Stage
git add src/utils.js
# 3. Continue cherry-pick
git cherry-pick --continue
# Or abort if too complex
git cherry-pick --abort
```
## Advanced Conflict Scenarios
### Multiple File Conflicts
**Handle Systematically:**
```bash
# List all conflicts
git diff --name-only --diff-filter=U > conflicts.txt
# Process each file
while read file; do
echo "Resolving $file"
# Edit file
vim "$file"
# Stage after manual resolution
git add "$file"
done < conflicts.txt
# Verify all resolved
git diff --name-only --diff-filter=U
# Should be empty
# Continue operation
git merge --continue
```
### Conflict in Binary Files
**Scenario:** Images, PDFs, or compiled files conflict.
```bash
# Check which version you want
git checkout --ours path/to/image.png
# or
git checkout --theirs path/to/image.png
# Stage decision
git add path/to/image.png
```
### Whitespace Conflicts
**Prevent Whitespace Conflicts:**
```bash
# During merge
git merge -Xignore-space-change feature-branch
# During rebase
git rebase -Xignore-space-change main
# Configure globally
git config --global merge.renormalize true
```
## Best Practices
### Before Merging
```bash
# 1. Ensure working directory is clean
git status
# 2. Fetch latest changes
git fetch origin
# 3. Review what you're merging
git log HEAD..origin/main
# 4. Create backup branch
git branch backup-$(date +%Y%m%d-%H%M%S)
# 5. Attempt merge
git merge origin/main
```
### During Conflict Resolution
1. **Understand Both Changes**
- Read the code carefully
- Understand the intent of each change
- Check commit messages for context
2. **Test Thoroughly**
- Run tests after resolving
- Manual testing of affected features
- Lint and format code
3. **Document Complex Resolutions**
```bash
git commit -m "Merge main into feature-branch
Resolved conflicts in:
- src/api.js: Combined pagination and filtering
- src/utils.js: Kept new helper functions from both branches
All tests passing."
```
### After Resolution
```bash
# 1. Verify no conflicts remain
git diff --check
# 2. Run full test suite
npm test
# 3. Review changes
git diff HEAD~1
# 4. Push with confidence
git push origin feature-branch
```
## Common Mistakes to Avoid
### ❌ Don't: Remove Conflict Markers Without Understanding
```javascript
// BAD: Just deleted markers without reading
function calculate() {
return value;
}
```
### ✅ Do: Understand and Integrate Both Changes
```javascript
// GOOD: Combined both improvements
function calculate(items) {
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
const tax = subtotal * TAX_RATE;
return subtotal + tax;
}
```
### ❌ Don't: Accept All Ours/Theirs Without Reviewing
```bash
# BAD: Blindly accepting
git checkout --ours .
git add .
git commit -m "Resolved conflicts"
```
### ✅ Do: Review Each Conflict
```bash
# GOOD: Selective resolution
git diff --name-only --diff-filter=U | while read file; do
echo "Reviewing $file"
git diff "$file"
# Decide per file
done
```
## Conflict Prevention
### 1. Frequent Integration
```bash
# Regularly sync with main
git fetch origin
git merge origin/main
# or
git rebase origin/main
```
### 2. Small, Focused Commits
```bash
# Better: Small commits
git add src/auth.js
git commit -m "Add login function"
git add tests/auth.test.js
git commit -m "Add login tests"
```
### 3. Communication
- Coordinate on shared files
- Use feature flags for large changes
- Split work across different files/modules
### 4. Code Review
- Review PRs quickly
- Merge frequently
- Avoid long-lived branches
## Troubleshooting
### Conflict Resolution Went Wrong
```bash
# Abort and start over
git merge --abort
# or
git rebase --abort
# Check reflog for previous state
git reflog
git reset --hard HEAD@{1}
```
### Accidentally Committed Conflict Markers
```bash
# Check last commit
git show
# If conflict markers present
git reset HEAD~1
# Fix files
git add .
git commit
```
### Need Help Understanding Conflict
```bash
# Show commit that introduced change
git log --all --full-history -- path/to/file.js
# Show who changed the line
git blame path/to/file.js
# See change in context
git show <commit-hash>
```
---
**Remember:** Conflicts are normal. Take time to understand both changes, test thoroughly, and document complex resolutions. When in doubt, consult with the other developer.
```
### references/branch-management.md
```markdown
# Branch Cleanup and Management
## Overview
Effective branch management prevents repository clutter and maintains a clean, navigable history. This guide covers both automated and manual approaches to branch cleanup.
## Using Helper Script
```bash
# Run branch cleanup helper
bash scripts/git_helper.sh cleanup-branches
```
## Manual Cleanup
### List All Branches
```bash
# List all branches
git branch -a
# List merged branches
git branch --merged main
# Delete merged local branches
git branch -d feature/completed
# Force delete unmerged branch
git branch -D feature/abandoned
# Delete remote branch
git push origin --delete feature/old
# Prune deleted remote branches
git fetch --prune
# Remove all merged branches (except main/develop)
git branch --merged | grep -v "\*\|main\|develop" | xargs -n 1 git branch -d
```
## Stale Branch Detection
### Show Branches with Last Commit Date
```bash
for branch in $(git branch -r | grep -v HEAD); do
echo -e "$(git show --format="%ci %cr %an" $branch | head -n 1)\t$branch"
done | sort -r
```
### Archive Old Branches as Tags
```bash
# Archive old branches as tags
git tag archive/feature-x feature/feature-x
git branch -D feature/feature-x
git push origin --delete feature/feature-x
```
## Branch Cleanup Strategies
### By Merge Status
```bash
# List branches merged into main
git branch --merged main
# Delete all merged branches
git branch --merged main | grep -v "^\*\|main\|develop" | xargs git branch -d
```
### By Age
```bash
# Find branches older than 30 days
git for-each-ref --sort=-committerdate refs/heads/ \
--format='%(committerdate:short) %(refname:short)' | \
awk -v date="$(date -d '30 days ago' +%Y-%m-%d)" '$1 < date {print $2}'
```
### By Author
```bash
# List your branches
git branch -r --format='%(authorname) %(refname:short)' | grep "Your Name"
# Delete your old feature branches
git branch | grep "feature/your-" | xargs git branch -d
```
## Automation Scripts
### Weekly Cleanup Script
```bash
#!/bin/bash
# weekly-branch-cleanup.sh
echo "Starting weekly branch cleanup..."
# Fetch latest
git fetch --prune
# List merged branches
echo "Merged branches:"
git branch --merged main | grep -v "^\*\|main\|develop"
# Prompt for confirmation
read -p "Delete these branches? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
git branch --merged main | grep -v "^\*\|main\|develop" | xargs git branch -d
echo "Cleanup complete"
else
echo "Cleanup cancelled"
fi
```
### Archive Old Branches
```bash
#!/bin/bash
# archive-old-branches.sh
# Archive branches older than 90 days
git for-each-ref --sort=-committerdate refs/heads/ \
--format='%(committerdate:short) %(refname:short)' | \
awk -v date="$(date -d '90 days ago' +%Y-%m-%d)" '$1 < date {print $2}' | \
while read branch; do
echo "Archiving $branch"
git tag archive/$branch $branch
git branch -D $branch
done
# Push archive tags
git push origin --tags
```
## Best Practices
### Regular Maintenance
- Clean up merged branches immediately after merge
- Archive old branches as tags before deletion
- Use descriptive branch names for easier identification
- Coordinate with team before deleting shared branches
### Protection Rules
- Protect main/master branches from deletion
- Protect active development branches (develop, staging)
- Protect release branches until officially deprecated
- Archive instead of delete for audit trail
### Naming Conventions
```bash
# Good branch names
feature/user-authentication
bugfix/login-redirect
hotfix/security-patch-v1.2.1
release/v2.0.0
experiment/new-search-algorithm
# Bad branch names
temp
fix
test-branch
johns-branch
```
## Recovery
### Restore Deleted Branch
```bash
# Find deleted branch in reflog
git reflog | grep "branch-name"
# Restore from commit hash
git checkout -b branch-name <commit-hash>
```
### Restore Deleted Remote Branch
```bash
# Find branch in old remote tracking
git branch -r --contains <commit-hash>
# Recreate and push
git checkout -b branch-name <commit-hash>
git push -u origin branch-name
```
---
**Remember:** Regular branch cleanup keeps your repository navigable and prevents accumulation of stale branches. Archive important history as tags before deletion.
```
### references/reflog-recovery.md
```markdown
# Reflog Recovery and History Rewriting
## Overview
Git reflog is your safety net for recovering lost commits and undoing mistakes. This guide covers recovery techniques and safe history rewriting practices.
## Reflog Recovery
### Understanding Reflog
The reflog records every change to HEAD and branch tips for 30-90 days (configurable). It's your time machine for Git operations.
```bash
# View reflog history
git reflog
# View reflog for specific branch
git reflog show branch-name
# View reflog with dates
git reflog --date=iso
```
### Recover Deleted Branch
**Scenario:** Accidentally deleted a branch.
```bash
# View reflog
git reflog
# Find commit where branch was deleted
# Output shows: abc1234 HEAD@{5}: checkout: moving from feature-x to main
# Restore branch
git checkout -b feature-x abc1234
```
### Undo Bad Reset
**Scenario:** Ran `git reset --hard HEAD~5` and lost commits.
```bash
# Accidentally ran: git reset --hard HEAD~5
# View reflog
git reflog
# Find state before reset
# Output: def5678 HEAD@{1}: reset: moving to HEAD~5
# Restore previous state
git reset --hard HEAD@{1}
```
**Alternative approach:**
```bash
# Find exact commit before reset
git reflog | grep "reset"
# Reset to specific reflog entry
git reset --hard HEAD@{3}
```
### Recover Lost Commits
**Scenario:** Made commits on detached HEAD and lost them.
```bash
# Find dangling commits
git fsck --lost-found
# Or use reflog
git reflog show --all
# View commit content
git show <lost-commit-hash>
# Cherry-pick recovered commit
git cherry-pick <lost-commit-hash>
# Or create new branch from lost commit
git checkout -b recovered-work <lost-commit-hash>
```
### Recover Dropped Stash
**Scenario:** Accidentally dropped a stash.
```bash
# Find dropped stashes
git fsck --unreachable | grep commit
# View stash content
git show <commit-hash>
# Apply recovered stash
git stash apply <commit-hash>
# Or use reflog
git reflog show stash
git stash apply stash@{5}
```
## Safe History Rewriting
### Amend Last Commit
**Change Last Commit Message:**
```bash
# Change last commit message
git commit --amend -m "New message"
```
**Add Forgotten File:**
```bash
# Add forgotten file to last commit
git add forgotten-file.txt
git commit --amend --no-edit
```
**Change Author:**
```bash
# Change author of last commit
git commit --amend --author="Name <[email protected]>"
```
### Filter Branch Operations
**Remove File from Entire History:**
```bash
# Remove file from entire history
git filter-branch --tree-filter 'rm -f passwords.txt' HEAD
# More efficient with index-filter
git filter-branch --index-filter 'git rm --cached --ignore-unmatch passwords.txt' HEAD
```
**Change Author in History:**
```bash
git filter-branch --env-filter '
if [ "$GIT_COMMITTER_EMAIL" = "[email protected]" ]; then
export GIT_COMMITTER_NAME="New Name"
export GIT_COMMITTER_EMAIL="[email protected]"
export GIT_AUTHOR_NAME="New Name"
export GIT_AUTHOR_EMAIL="[email protected]"
fi
' -- --all
```
### BFG Repo-Cleaner (Better Alternative)
**Remove Sensitive Data:**
```bash
# Download BFG Repo-Cleaner
# https://rtyley.github.io/bfg-repo-cleaner/
# Remove specific file
java -jar bfg.jar --delete-files passwords.txt
# Remove files larger than 100M
java -jar bfg.jar --strip-blobs-bigger-than 100M
# Replace sensitive strings
java -jar bfg.jar --replace-text passwords.txt
# Clean up
git reflog expire --expire=now --all
git gc --prune=now --aggressive
```
**Example: Remove API Keys:**
```bash
# Create replacement file (replacements.txt)
# API_KEY=.* ==> API_KEY=REMOVED
java -jar bfg.jar --replace-text replacements.txt
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force
```
## Advanced Recovery Scenarios
### Recover After Force Push
**Scenario:** Someone force-pushed and overwrote your work.
```bash
# Check reflog of remote tracking branch
git reflog show origin/main
# Find commit before force push
# Reset local branch to that commit
git reset --hard origin/main@{1}
# Create backup branch
git branch backup-recovery
# Push to new branch
git push origin backup-recovery
```
### Recover Entire Repository State
**Scenario:** Need to restore repository to exact state from 2 days ago.
```bash
# Find reflog entry from 2 days ago
git reflog --date=iso | grep "2 days ago"
# Reset to that state
git reset --hard HEAD@{yesterday}
# Or specific reflog entry
git reset --hard HEAD@{10}
```
### Recover from Corrupted Repository
```bash
# Check repository integrity
git fsck --full
# Attempt recovery
git fsck --lost-found
# Restore from backup (if available)
# Or clone fresh and apply recent work
```
## History Rewriting Best Practices
### Before Rewriting
1. **Create backup branch:**
```bash
git branch backup-before-rewrite
```
2. **Ensure working directory is clean:**
```bash
git status
```
3. **Know your commit history:**
```bash
git log --oneline --graph --all
```
### During Rewriting
1. **Never rewrite public/shared branches**
2. **Use --force-with-lease instead of --force:**
```bash
git push --force-with-lease origin feature-branch
```
3. **Test thoroughly after rewriting:**
```bash
npm test
git log --oneline
git diff main
```
### After Rewriting
1. **Communicate with team about force push**
2. **Verify commit signatures (if using GPG)**
3. **Check CI/CD pipeline status**
4. **Monitor for issues**
## Reflog Configuration
### Extend Reflog Retention
```bash
# Keep reflog entries for 180 days (default is 90)
git config gc.reflogExpire 180
# Keep unreachable reflog entries for 60 days (default is 30)
git config gc.reflogExpireUnreachable 60
# Apply globally
git config --global gc.reflogExpire 180
git config --global gc.reflogExpireUnreachable 60
```
### Disable Garbage Collection Temporarily
```bash
# Disable automatic gc
git config gc.auto 0
# Run manual gc when needed
git gc --prune=now
```
## Emergency Recovery Commands
```bash
# Abort ongoing operations
git merge --abort
git rebase --abort
git cherry-pick --abort
# View reflog
git reflog
# Reset to previous state
git reset --hard HEAD@{1}
# Find lost commits
git fsck --lost-found
# Recover specific commit
git checkout -b recovery <commit-hash>
# Create patch from lost commit
git format-patch -1 <commit-hash>
git apply patch-file.patch
```
## Common Recovery Scenarios
### Scenario 1: Committed to Wrong Branch
```bash
# Move commit to correct branch
git checkout correct-branch
git cherry-pick wrong-branch
# Remove from wrong branch
git checkout wrong-branch
git reset --hard HEAD~1
```
### Scenario 2: Need to Split Recent Commits
```bash
# Reset but keep changes
git reset HEAD~3
# Stage and commit selectively
git add file1.js
git commit -m "Feature A"
git add file2.js
git commit -m "Feature B"
```
### Scenario 3: Merge Gone Wrong
```bash
# Abort if still in progress
git merge --abort
# Or reset if already committed
git reflog
git reset --hard HEAD@{1}
```
---
**Remember:** Reflog is temporary (30-90 days). For long-term backup, use branches and tags. Always create a backup branch before risky operations.
```
### examples/branch_strategies.md
```markdown
# Git Branch Strategies
## Overview
Choosing the right branching strategy is crucial for team productivity and code quality. This guide covers the most popular branching workflows with practical examples and best practices.
## Table of Contents
1. [Git Flow](#git-flow)
2. [Trunk-Based Development](#trunk-based-development)
3. [GitHub Flow](#github-flow)
4. [GitLab Flow](#gitlab-flow)
5. [Feature Branch Workflow](#feature-branch-workflow)
6. [Comparison and Selection Guide](#comparison-and-selection-guide)
## Git Flow
### Overview
Git Flow is a robust branching model for projects with scheduled releases. It defines strict branch roles and merge patterns.
### Branch Types
**Permanent Branches:**
- `main` (or `master`): Production-ready code
- `develop`: Integration branch for features
**Temporary Branches:**
- `feature/*`: New feature development
- `release/*`: Release preparation
- `hotfix/*`: Emergency production fixes
### Complete Git Flow Example
#### 1. Initial Setup
```bash
# Create and push develop branch
git checkout -b develop main
git push -u origin develop
# Set up branch protection rules (on GitHub/GitLab)
# - main: Require PR reviews, no direct commits
# - develop: Require PR reviews
```
#### 2. Feature Development
```bash
# Start new feature
git checkout develop
git pull origin develop
git checkout -b feature/user-authentication
# Work on feature
git add src/auth.js
git commit -m "Add login endpoint"
git add src/auth.js
git commit -m "Add JWT token generation"
git add tests/auth.test.js
git commit -m "Add authentication tests"
# Push feature branch
git push -u origin feature/user-authentication
# Create Pull Request to develop
# After review and approval, merge to develop
```
**Merge Feature to Develop:**
```bash
# Option A: Via PR (recommended)
# Use GitHub/GitLab UI
# Option B: Manually
git checkout develop
git pull origin develop
git merge --no-ff feature/user-authentication
git push origin develop
git branch -d feature/user-authentication
git push origin --delete feature/user-authentication
```
#### 3. Release Process
```bash
# Create release branch from develop
git checkout develop
git pull origin develop
git checkout -b release/v1.2.0
# Prepare release
# - Update version numbers
# - Update CHANGELOG.md
# - Final bug fixes only
# Version bump
npm version minor # Updates package.json to 1.2.0
git add package.json package-lock.json
git commit -m "Bump version to 1.2.0"
# Update changelog
git add CHANGELOG.md
git commit -m "Update changelog for v1.2.0"
# Push release branch
git push -u origin release/v1.2.0
# Merge to main (via PR or manually)
git checkout main
git pull origin main
git merge --no-ff release/v1.2.0
git tag -a v1.2.0 -m "Release version 1.2.0"
git push origin main --tags
# Merge back to develop
git checkout develop
git pull origin develop
git merge --no-ff release/v1.2.0
git push origin develop
# Delete release branch
git branch -d release/v1.2.0
git push origin --delete release/v1.2.0
```
#### 4. Hotfix Process
```bash
# Create hotfix from main
git checkout main
git pull origin main
git checkout -b hotfix/security-patch
# Fix critical issue
git add src/security.js
git commit -m "Fix XSS vulnerability in user input"
# Bump patch version
npm version patch # 1.2.0 -> 1.2.1
git add package.json
git commit -m "Bump version to 1.2.1"
# Merge to main
git checkout main
git merge --no-ff hotfix/security-patch
git tag -a v1.2.1 -m "Hotfix v1.2.1 - Security patch"
git push origin main --tags
# Merge to develop
git checkout develop
git merge --no-ff hotfix/security-patch
git push origin develop
# Delete hotfix branch
git branch -d hotfix/security-patch
git push origin --delete hotfix/security-patch
```
### Git Flow Advantages
✅ Clear separation of concerns
✅ Supports multiple versions in production
✅ Explicit release preparation
✅ Easy to track feature progress
### Git Flow Disadvantages
❌ Complex for continuous deployment
❌ High ceremony for simple projects
❌ Multiple long-lived branches to maintain
❌ Can slow down fast-moving teams
## Trunk-Based Development
### Overview
Trunk-based development focuses on a single main branch with short-lived feature branches and frequent integration.
### Core Principles
1. **Single Source of Truth**: `main` is always deployable
2. **Short-lived Branches**: Feature branches live < 1 day
3. **Frequent Integration**: Merge to main multiple times per day
4. **Feature Flags**: Hide incomplete features
5. **Continuous Integration**: Automated tests on every commit
### Workflow Example
#### Daily Development Flow
```bash
# Morning: Start with latest main
git checkout main
git pull origin main
# Create short-lived feature branch
git checkout -b feature/quick-improvement
# Work for a few hours
git add src/component.js
git commit -m "Refactor data loading logic"
# Push and create PR
git push -u origin feature/quick-improvement
# After quick review (same day)
# Merge to main via PR
# Automated tests run
# Auto-deploy to staging
# Delete branch immediately
git checkout main
git pull origin main
git branch -d feature/quick-improvement
```
#### Feature Flag Usage
```javascript
// Use feature flags for incomplete work
import { isFeatureEnabled } from './featureFlags';
function UserDashboard() {
if (isFeatureEnabled('newDashboard')) {
return <NewDashboard />; // Work in progress
}
return <OldDashboard />; // Stable version
}
// Deploy to main with flag off
// Enable flag when ready
```
#### Direct Commit to Main (Small Changes)
```bash
# For very small changes (typos, config)
git checkout main
git pull origin main
# Make small fix
git add README.md
git commit -m "Fix typo in documentation"
# Push directly (if allowed)
git push origin main
# Or create quick PR for review
```
### Trunk-Based Advantages
✅ Simple and fast
✅ Always ready to deploy
✅ Encourages small changes
✅ No merge conflicts from long-lived branches
✅ Supports continuous deployment
### Trunk-Based Disadvantages
❌ Requires discipline
❌ Needs robust CI/CD
❌ Feature flags add complexity
❌ Challenging for large teams without coordination
## GitHub Flow
### Overview
Simplified workflow optimized for continuous deployment. Main branch is always deployable, features developed in branches.
### Workflow Steps
1. Create branch from `main`
2. Add commits
3. Open Pull Request
4. Discuss and review
5. Deploy to production
6. Merge to `main`
### Complete Example
```bash
# 1. Create feature branch
git checkout main
git pull origin main
git checkout -b feature/add-search
# 2. Implement feature
git add src/search.js
git commit -m "Add search functionality"
git add tests/search.test.js
git commit -m "Add search tests"
git add docs/search.md
git commit -m "Document search API"
# 3. Push and create PR
git push -u origin feature/add-search
# Create PR on GitHub
# - Add description
# - Request reviews
# - Link related issues
# 4. Review process
# - Reviewers comment
# - Make changes based on feedback
git add src/search.js
git commit -m "Address review feedback"
git push origin feature/add-search
# 5. Deploy from PR branch (optional)
# Some teams deploy PR branch to staging for testing
# 6. After approval, deploy to production
# Then merge PR on GitHub
# 7. Cleanup
git checkout main
git pull origin main
git branch -d feature/add-search
```
### GitHub Flow Advantages
✅ Very simple
✅ Fast feedback loop
✅ Always ready to ship
✅ Great for web applications
### GitHub Flow Disadvantages
❌ No formal release process
❌ Challenging for multiple versions
❌ Requires continuous deployment
❌ Less suitable for traditional release cycles
## GitLab Flow
### Overview
Combines feature branches with environment branches for staged deployments.
### Branch Structure
- `main`: Development integration
- `production`: Production code
- `staging`: Staging environment (optional)
- `feature/*`: Feature development
### Workflow Example
```bash
# 1. Feature development
git checkout main
git pull origin main
git checkout -b feature/notification-system
# Implement feature
git add src/notifications.js
git commit -m "Implement notification system"
# 2. Merge to main
# Create merge request to main
# After review, merge
# 3. Deploy to staging
git checkout staging
git merge main
git push origin staging
# Automated deployment to staging environment
# 4. Test on staging
# QA team tests
# If issues found, fix in new branch from main
# 5. Deploy to production
git checkout production
git merge staging
git tag -a v1.3.0 -m "Release v1.3.0"
git push origin production --tags
# Automated deployment to production
# 6. Hotfix process (if needed)
git checkout production
git checkout -b hotfix/critical-bug
# Fix bug
git commit -am "Fix critical bug"
# Merge to production
git checkout production
git merge hotfix/critical-bug
git push origin production
# Backport to main
git checkout main
git merge hotfix/critical-bug
git push origin main
```
### GitLab Flow Advantages
✅ Supports multiple environments
✅ Clear deployment pipeline
✅ Works with both continuous and scheduled releases
✅ Flexible for different workflows
### GitLab Flow Disadvantages
❌ More complex than GitHub Flow
❌ Environment branches can drift
❌ Requires discipline in backporting
## Feature Branch Workflow
### Overview
Simple workflow where all feature development happens in dedicated branches merged to main.
### Basic Example
```bash
# Create feature branch
git checkout -b feature/analytics-dashboard main
# Develop feature
git add src/analytics.js
git commit -m "Add analytics tracking"
git add src/dashboard.js
git commit -m "Create analytics dashboard UI"
# Rebase on main to stay updated
git fetch origin
git rebase origin/main
# Push and create PR
git push -u origin feature/analytics-dashboard
# After review and approval
# Merge via PR (squash or merge commit)
# Delete branch
git branch -d feature/analytics-dashboard
```
## Comparison and Selection Guide
### Git Flow
**Best For:**
- Projects with scheduled releases
- Multiple production versions
- Enterprise software
- Products with support for old versions
**Team Size:** Medium to Large
### Trunk-Based Development
**Best For:**
- Continuous deployment
- Fast-moving teams
- Web applications
- Modern DevOps practices
**Team Size:** Small to Medium (with discipline)
### GitHub Flow
**Best For:**
- Web applications
- SaaS products
- Continuous deployment
- Simple, fast iteration
**Team Size:** Small to Medium
### GitLab Flow
**Best For:**
- Multiple environments
- Staged deployments
- Hybrid approach needs
- Organizations with both CD and scheduled releases
**Team Size:** Any
## Best Practices for All Strategies
### 1. Branch Naming Conventions
```bash
# Features
feature/user-authentication
feature/payment-integration
feat/JIRA-123-add-export
# Bugs
bugfix/login-error
fix/memory-leak
bug/JIRA-456-fix-crash
# Hotfixes
hotfix/security-patch
hotfix/critical-data-loss
# Releases
release/v1.2.0
release/2023-Q4
# Experiments
experiment/new-algorithm
poc/machine-learning
```
### 2. Commit Message Format
```bash
# Use conventional commits
git commit -m "feat: add user authentication"
git commit -m "fix: resolve memory leak in cache"
git commit -m "docs: update API documentation"
git commit -m "refactor: simplify data loading logic"
git commit -m "test: add unit tests for payment module"
# Include ticket numbers
git commit -m "feat(auth): add SSO support [JIRA-123]"
```
### 3. Pull Request Best Practices
```markdown
## Description
Brief description of changes
## Type of Change
- [ ] Bug fix
- [x] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
- Unit tests added/updated
- Integration tests passing
- Manual testing completed
## Screenshots (if applicable)
[Add screenshots]
## Checklist
- [x] Code follows style guidelines
- [x] Self-review completed
- [x] Comments added for complex code
- [x] Documentation updated
- [x] No new warnings
- [x] Tests added/updated
```
### 4. Branch Protection Rules
```yaml
# GitHub/GitLab Settings
main:
require_pull_request: true
required_approvals: 2
dismiss_stale_reviews: true
require_code_owner_reviews: true
require_status_checks: true
status_checks:
- continuous-integration
- code-quality
- security-scan
enforce_admins: true
develop:
require_pull_request: true
required_approvals: 1
require_status_checks: true
```
### 5. Automation
```yaml
# Example CI/CD Pipeline
on:
pull_request:
branches: [main, develop]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run tests
run: npm test
- name: Run linting
run: npm run lint
- name: Security scan
run: npm audit
deploy-staging:
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
steps:
- name: Deploy to staging
run: ./deploy-staging.sh
deploy-production:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Deploy to production
run: ./deploy-production.sh
```
## Migration Between Strategies
### From Git Flow to Trunk-Based
```bash
# 1. Merge all feature branches to develop
# 2. Merge develop to main
git checkout main
git merge develop
# 3. Make main the primary branch
# 4. Archive develop branch
git branch -m develop develop-archived
git push origin :develop
# 5. Adopt feature flags for incomplete work
# 6. Shorten branch lifecycles to < 1 day
```
### From GitHub Flow to GitLab Flow
```bash
# 1. Create environment branches
git checkout -b staging main
git push -u origin staging
git checkout -b production main
git push -u origin production
# 2. Update deployment pipelines
# 3. Set up branch protection
# 4. Update team processes
```
## Troubleshooting Common Issues
### Long-Lived Branch Conflicts
```bash
# Regularly sync with base branch
git fetch origin
git rebase origin/main
# Or merge if rebase is risky
git merge origin/main
```
### Accidentally Committed to Wrong Branch
```bash
# Move commit to correct branch
git checkout correct-branch
git cherry-pick <commit-hash>
# Remove from wrong branch
git checkout wrong-branch
git reset --hard HEAD~1
```
### Need to Deploy Specific Features
```bash
# Use feature flags instead of branches
# Or cherry-pick specific commits
git checkout release-branch
git cherry-pick <feature-commit-1>
git cherry-pick <feature-commit-2>
```
---
**Choosing the right strategy depends on:**
- Team size and distribution
- Release cadence
- Product type (web app vs. desktop vs. embedded)
- CI/CD maturity
- Team discipline and experience
Start simple and evolve as needs change.
```
### references/best-practices.md
```markdown
# Git Advanced Operations Best Practices
## Overview
Follow these best practices to maintain clean Git history, avoid common pitfalls, and work effectively with advanced Git operations.
## Before Rebase
### Pre-Rebase Checklist
```bash
# 1. Create backup branch
git branch backup-$(date +%Y%m%d-%H%M%S)
# 2. Ensure working directory is clean
git status
# Should show: nothing to commit, working tree clean
# 3. Know your commit history
git log --oneline --graph -10
# 4. Verify you're not on a shared branch
git branch -vv
```
### Safety Measures
- **Never rebase public/shared branches** - Only rebase local commits
- **Check for remote tracking** - Ensure branch isn't being used by others
- **Use backup branches** - Quick recovery if something goes wrong
- **Understand the commits** - Know what you're rebasing
```bash
# Good: Rebasing local feature branch
git checkout feature/my-work
git rebase main
# Bad: Rebasing shared branch
git checkout develop
git rebase main # Don't do this if others are using develop!
```
## During Conflicts
### Conflict Resolution Guidelines
1. **Understand both sides of the conflict**
```bash
# View what you changed
git diff --ours path/to/file.js
# View what they changed
git diff --theirs path/to/file.js
# View common ancestor
git diff --base path/to/file.js
```
2. **Test thoroughly after resolution**
```bash
# Run tests
npm test
# Run linter
npm run lint
# Manual testing
npm start
```
3. **Use meaningful merge commit messages**
```bash
git commit -m "Merge main into feature-branch
Resolved conflicts in:
- src/api.js: Combined pagination and filtering features
- src/utils.js: Kept new helper functions from both branches
- tests/api.test.js: Merged test suites
All tests passing."
```
4. **Document complex resolutions**
- Add comments explaining non-obvious choices
- Reference related issues or discussions
- Explain why you chose one approach over another
### Conflict Prevention
```bash
# Sync frequently with base branch
git fetch origin
git rebase origin/main # or merge
# Commit small, focused changes
git add specific-file.js
git commit -m "Focused change description"
# Communicate with team
# - Coordinate on shared files
# - Review PRs quickly
# - Merge frequently
```
## Branch Management
### Branch Lifecycle
```bash
# 1. Create from up-to-date base
git checkout main
git pull origin main
git checkout -b feature/new-feature
# 2. Work and commit regularly
git add .
git commit -m "Clear, descriptive message"
# 3. Sync with base branch regularly
git fetch origin
git rebase origin/main
# 4. Clean up before merging
git rebase -i origin/main # Squash, reorder, cleanup
# 5. Merge promptly after approval
# (via PR or command line)
# 6. Delete branch immediately after merge
git checkout main
git pull origin main
git branch -d feature/new-feature
git push origin --delete feature/new-feature
```
### Branch Naming Best Practices
```bash
# Use descriptive, categorized names
feature/user-authentication
feature/payment-integration
bugfix/login-redirect
fix/memory-leak
hotfix/security-patch
release/v1.2.0
experiment/new-algorithm
# Include ticket numbers when relevant
feature/JIRA-123-add-export
bugfix/GH-456-fix-crash
# Avoid generic names
temp
test
fix
my-branch
```
### Keep Branches Focused and Short-Lived
- **Focused**: One feature or bug fix per branch
- **Short-lived**: Merge within days, not weeks
- **Synced**: Regularly update from base branch
- **Clean**: Squash/cleanup before merging
## History Hygiene
### Commit Quality Standards
```bash
# Write clear, descriptive commit messages
git commit -m "Add user authentication with JWT tokens
Implemented:
- Login endpoint with email/password
- JWT token generation and validation
- Refresh token mechanism
- Password hashing with bcrypt
Tests added for all authentication flows."
# Use conventional commit format
git commit -m "feat: add user authentication"
git commit -m "fix: resolve memory leak in cache"
git commit -m "docs: update API documentation"
git commit -m "refactor: simplify data loading logic"
git commit -m "test: add unit tests for payment module"
```
### Atomic Commits
```bash
# Good: Atomic commits (one logical change each)
git add src/auth.js
git commit -m "Add login function"
git add tests/auth.test.js
git commit -m "Add login tests"
git add docs/auth.md
git commit -m "Document authentication API"
# Bad: Large, unfocused commit
git add .
git commit -m "Add auth and fix bugs and update docs"
```
### Pre-Push Cleanup
```bash
# Before pushing, clean up your commits
git rebase -i origin/main
# Squash "fixup" commits
pick abc1234 Add feature
fixup def5678 Fix typo
fixup ghi9012 Fix linting
# Reword unclear messages
reword jkl3456 WIP commit # Change to descriptive message
# Drop debug commits
drop mno7890 Add console.log debugging
```
## Force Push Safety
### When to Force Push
✅ **Safe scenarios:**
- Your own feature branch
- After rebasing local commits
- Cleaning up commit history before merge
- Branch is not being used by others
❌ **Never force push to:**
- main/master branch
- develop branch
- Branches others are working on
- Already released commits
### Force Push Best Practices
```bash
# Use --force-with-lease instead of --force
git push --force-with-lease origin feature-branch
# What --force-with-lease does:
# - Checks if remote branch has unexpected commits
# - Prevents overwriting others' work
# - Fails safely if remote changed
# Verify what you're pushing
git log origin/feature-branch..HEAD
git diff origin/feature-branch
# Communicate before force pushing
# - Notify team members
# - Ensure no one is working on the branch
# - Coordinate timing
```
## Code Review Integration
### Preparing for Review
```bash
# 1. Clean up commit history
git rebase -i origin/main
# 2. Ensure tests pass
npm test
# 3. Run linting
npm run lint
# 4. Self-review changes
git diff origin/main
# 5. Write detailed PR description
```
### Addressing Review Feedback
```bash
# Option 1: Fixup commits (then squash before merge)
git add src/auth.js
git commit --fixup abc1234
# Later, before final merge
git rebase -i --autosquash origin/main
# Option 2: Regular commits (if history preservation matters)
git add src/auth.js
git commit -m "Address review feedback: improve error handling"
# Option 3: Amend last commit (if feedback is immediate)
git add src/auth.js
git commit --amend --no-edit
git push --force-with-lease origin feature-branch
```
## Collaboration Patterns
### Working on Shared Branch
```bash
# Pull before starting work
git pull --rebase origin feature-branch
# Push frequently
git push origin feature-branch
# Communicate changes
# - Announce major refactors
# - Coordinate on conflicts
# - Use feature flags for breaking changes
```
### Reviewing Others' Work
```bash
# Fetch and checkout PR branch
git fetch origin pull/123/head:pr-123
git checkout pr-123
# Test locally
npm install
npm test
# Review changes
git diff main..pr-123
git log main..pr-123
# Leave inline comments on GitHub/GitLab
```
## Emergency Procedures
### Undo Last Operation
```bash
# Check reflog first
git reflog
# Reset to previous state
git reset --hard HEAD@{1}
# Or abort ongoing operation
git rebase --abort
git merge --abort
git cherry-pick --abort
```
### Recover Lost Work
```bash
# Find lost commits
git fsck --lost-found
git reflog
# Recover specific commit
git checkout -b recovery <commit-hash>
# Or cherry-pick
git cherry-pick <commit-hash>
```
### Fix Broken Branch
```bash
# If branch is in bad state
# Option 1: Reset to known good state
git reset --hard origin/main
# Option 2: Start fresh
git checkout main
git checkout -b feature/new-attempt
# Cherry-pick good commits from broken branch
git cherry-pick <good-commit-1>
git cherry-pick <good-commit-2>
```
## Performance Optimization
### Repository Maintenance
```bash
# Clean up repository
git gc --aggressive --prune=now
# Remove unreachable objects
git prune
# Optimize pack files
git repack -a -d --depth=250 --window=250
# Verify repository integrity
git fsck --full
```
### Large Repository Handling
```bash
# Shallow clone for large repos
git clone --depth 1 https://github.com/user/repo.git
# Fetch only specific branches
git clone --single-branch --branch main https://github.com/user/repo.git
# Use sparse checkout
git sparse-checkout init
git sparse-checkout set src/ tests/
```
## Quality Checklist
### Before Committing
- [ ] Code compiles/runs without errors
- [ ] Tests pass locally
- [ ] Linting passes
- [ ] Commit message is clear and descriptive
- [ ] Commit is focused (one logical change)
- [ ] No debug code or console.logs
- [ ] No commented-out code
### Before Pushing
- [ ] Commits are clean and logical
- [ ] No sensitive data in commits
- [ ] Branch is up to date with base
- [ ] All tests pass
- [ ] Self-reviewed changes
- [ ] Ready for code review
### Before Merging
- [ ] PR approved by required reviewers
- [ ] All CI checks pass
- [ ] No merge conflicts
- [ ] Documentation updated
- [ ] Changelog updated (if applicable)
- [ ] Version bumped (if applicable)
---
**Remember:** Good Git hygiene prevents problems. Invest time in clean commits and clear history - your future self and teammates will thank you.
```
### references/troubleshooting.md
```markdown
# Git Advanced Operations Troubleshooting
## Overview
Common issues and solutions for advanced Git operations. This guide helps you quickly resolve problems with rebasing, merging, conflicts, and more.
## Rebase Issues
### Rebase Conflicts Too Complex
**Problem:** Multiple conflicts during rebase, becoming unmanageable.
**Solution:**
```bash
# Abort rebase
git rebase --abort
# Try merge instead (preserves history differently)
git merge main
# Or try interactive rebase with smaller chunks
git rebase -i HEAD~5 # Start with fewer commits
```
**Prevention:**
```bash
# Rebase more frequently to avoid large divergence
git fetch origin
git rebase origin/main # Do this daily
# Keep feature branches short-lived
# Merge within a few days, not weeks
```
### Rebase Stops at Every Commit
**Problem:** Rebase requires manual intervention for many commits.
**Solution:**
```bash
# Use rerere (reuse recorded resolution)
git config --global rerere.enabled true
# Git will remember conflict resolutions
# and apply them automatically in subsequent commits
# Or use merge strategy during rebase
git rebase -X ours origin/main # Prefer your changes
git rebase -X theirs origin/main # Prefer their changes
```
### Can't Continue Rebase
**Problem:** `git rebase --continue` says nothing to commit.
**Solution:**
```bash
# The conflict was already resolved, skip this commit
git rebase --skip
# Or check if changes need staging
git status
git add <resolved-files>
git rebase --continue
```
### Detached HEAD After Rebase
**Problem:** Ended up in detached HEAD state.
**Solution:**
```bash
# Create branch from current state
git checkout -b recovered-branch
# Or return to original branch
git checkout feature-branch
# Check reflog to understand what happened
git reflog
```
## Merge Conflicts
### Conflict Markers Left in Code
**Problem:** Accidentally committed conflict markers.
**Solution:**
```bash
# Check last commit
git show
# If conflict markers present
git reset HEAD~1
# Fix files (remove markers)
vim src/file.js
# Re-commit
git add src/file.js
git commit -m "Fix: Remove conflict markers"
```
**Prevention:**
```bash
# Search for conflict markers before committing
git diff --check
# Or use pre-commit hook
# .git/hooks/pre-commit
#!/bin/sh
if git diff --cached | grep -q '^<<<<<<<'; then
echo "Error: Conflict markers found"
exit 1
fi
```
### Merge Went Wrong
**Problem:** Merged but result is broken.
**Solution:**
```bash
# If merge not committed yet
git merge --abort
# If already committed
git reflog
git reset --hard HEAD@{1} # State before merge
# Or revert the merge commit
git revert -m 1 <merge-commit-hash>
```
### Binary File Conflict
**Problem:** Can't merge binary files (images, PDFs).
**Solution:**
```bash
# Choose one version
git checkout --ours path/to/image.png
# or
git checkout --theirs path/to/image.png
# Stage decision
git add path/to/image.png
# Continue merge
git merge --continue
```
## Lost Commits
### Can't Find Recent Commits
**Problem:** Commits disappeared after reset or rebase.
**Solution:**
```bash
# Check reflog
git reflog
# Find lost commits
# Look for: abc1234 HEAD@{5}: commit: Your message
# Recover commit
git checkout -b recovery abc1234
# Or cherry-pick it
git cherry-pick abc1234
```
### Deleted Branch with Important Work
**Problem:** Deleted branch before merging.
**Solution:**
```bash
# Find branch in reflog
git reflog | grep "branch-name"
# Look for: checkout: moving from branch-name to main
# Get commit hash before deletion
git reflog show --all | grep "branch-name"
# Recreate branch
git checkout -b branch-name <commit-hash>
```
### Lost Stash
**Problem:** Dropped stash accidentally.
**Solution:**
```bash
# Find dropped stashes
git fsck --unreachable | grep commit
# View stash content
git show <commit-hash>
# Apply if it's the right one
git stash apply <commit-hash>
# Or check stash reflog
git reflog show stash
git stash apply stash@{5}
```
## Force Push Problems
### Force Push Rejected
**Problem:** `git push --force-with-lease` rejected.
**Solution:**
```bash
# Check what changed on remote
git fetch origin
git log HEAD..origin/feature-branch
# If remote has new commits from others
# Don't force push! Merge or rebase first
git rebase origin/feature-branch
# If you're certain, use regular force push (risky)
git push --force origin feature-branch
```
### Overwrote Someone's Work
**Problem:** Force pushed and lost colleague's commits.
**Solution:**
```bash
# Contact colleague to get their commit hashes
# Or check reflog of remote tracking branch
git reflog show origin/feature-branch
# Reset to before your force push
git reset --hard origin/feature-branch@{1}
# Cherry-pick your commits on top
git cherry-pick <your-commit-1>
git cherry-pick <your-commit-2>
# Push normally
git push origin feature-branch
```
## Cherry-Pick Issues
### Cherry-Pick Conflict
**Problem:** Conflict when cherry-picking.
**Solution:**
```bash
# Resolve conflict manually
vim conflicted-file.js
# Stage resolved file
git add conflicted-file.js
# Continue cherry-pick
git cherry-pick --continue
# Or skip this commit
git cherry-pick --skip
# Or abort
git cherry-pick --abort
```
### Cherry-Picked Wrong Commit
**Problem:** Picked wrong commit.
**Solution:**
```bash
# Undo last commit (cherry-picked one)
git reset --hard HEAD~1
# Cherry-pick correct commit
git cherry-pick <correct-commit-hash>
```
## Bisect Problems
### Bisect Can't Find Bad Commit
**Problem:** Bisect reports all commits as bad or good.
**Solution:**
```bash
# Reset bisect
git bisect reset
# Start over with correct good/bad markers
git bisect start
git bisect bad HEAD
git bisect good <earlier-commit>
# Or check if issue is environmental
# Ensure you're testing correctly at each step
```
### Bisect Test Script Fails
**Problem:** Automated bisect script has errors.
**Solution:**
```bash
# Make script more robust
#!/bin/bash
set -e # Exit on error
# Setup environment
npm install 2>/dev/null || true
# Run test
npm test
# Return appropriate exit code
if [ $? -eq 0 ]; then
exit 0 # Good commit
else
exit 1 # Bad commit
fi
```
## Submodule Issues
### Submodule in Detached HEAD
**Problem:** Submodule stuck in detached HEAD state.
**Solution:**
```bash
# Navigate to submodule
cd path/to/submodule
# Checkout a branch
git checkout main
# Or update submodule to tracked commit
cd ..
git submodule update --init --recursive
```
### Submodule Update Conflicts
**Problem:** Conflicts when updating submodules.
**Solution:**
```bash
# Resolve submodule pointer conflict
git checkout --ours path/to/submodule # Use your version
# or
git checkout --theirs path/to/submodule # Use their version
# Update submodule
cd path/to/submodule
git checkout <commit-hash>
# Stage resolution
cd ..
git add path/to/submodule
git merge --continue
```
## Large File Problems
### Accidentally Committed Large File
**Problem:** Committed large file, now repo is huge.
**Solution:**
```bash
# Remove file from last commit (not pushed yet)
git rm --cached large-file.bin
git commit --amend --no-edit
# If already pushed, use BFG Repo-Cleaner
java -jar bfg.jar --strip-blobs-bigger-than 100M
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force
```
### Repository Too Large
**Problem:** Clone/fetch is very slow due to size.
**Solution:**
```bash
# Shallow clone
git clone --depth 1 https://github.com/user/repo.git
# Or partial clone (Git 2.22+)
git clone --filter=blob:none https://github.com/user/repo.git
# Clean up existing repo
git gc --aggressive --prune=now
git repack -a -d --depth=250 --window=250
```
## Performance Issues
### Git Commands Are Slow
**Problem:** All Git operations taking too long.
**Solution:**
```bash
# Run garbage collection
git gc --aggressive
# Remove unreachable objects
git prune
# Check for repository corruption
git fsck --full
# Optimize configuration
git config core.preloadindex true
git config core.fscache true
git config gc.auto 256
```
### Diff Takes Forever
**Problem:** `git diff` or `git log` is very slow.
**Solution:**
```bash
# Limit diff context
git diff -U3 # Only 3 lines of context
# Skip binary files
git diff --no-binary
# Use specific paths
git diff -- src/ # Only src directory
# Cache git status
git config core.untrackedCache true
```
## Authentication Issues
### Permission Denied (publickey)
**Problem:** Can't push due to SSH key issues.
**Solution:**
```bash
# Check SSH key
ssh -T [email protected]
# Add SSH key to agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
# Or use HTTPS instead
git remote set-url origin https://github.com/user/repo.git
```
### Remote Rejected
**Problem:** Remote rejects push.
**Solution:**
```bash
# Pull first (if behind)
git pull --rebase origin main
# Check branch protection rules
# May need to create PR instead of direct push
# Verify remote URL
git remote -v
# Check for hooks rejecting push
# Contact repository admin if needed
```
## Emergency Recovery
### Repository Corrupted
**Problem:** Git reports corrupted objects.
**Solution:**
```bash
# Check repository integrity
git fsck --full
# Attempt recovery
git reflog expire --expire=now --all
git gc --prune=now
# If still corrupted, clone fresh and apply recent work
git clone https://github.com/user/repo.git repo-fresh
cd repo-fresh
# Manually copy uncommitted work from corrupted repo
```
### Lost All Changes
**Problem:** Accidentally ran destructive command.
**Solution:**
```bash
# Check reflog immediately
git reflog
# Find last good state
# Look for: abc1234 HEAD@{10}: commit: Last good commit
# Reset to that state
git reset --hard HEAD@{10}
# If reflog doesn't help
git fsck --lost-found
# Check .git/lost-found/ directory
```
### Need to Undo Everything
**Problem:** Repository is in unknown state, need to start over.
**Solution:**
```bash
# Save current state just in case
git stash
git branch backup-$(date +%Y%m%d-%H%M%S)
# Reset to remote state
git fetch origin
git reset --hard origin/main
# Clean all untracked files
git clean -fdx # Be careful with this!
# Or clone fresh
cd ..
git clone https://github.com/user/repo.git repo-fresh
```
## Quick Reference: Abort Commands
```bash
# Abort ongoing operations
git merge --abort # Abort merge
git rebase --abort # Abort rebase
git cherry-pick --abort # Abort cherry-pick
git bisect reset # End bisect session
git am --abort # Abort patch application
# Reset to previous state
git reset --hard HEAD@{1} # Undo last operation
git reflog # View history of HEAD changes
# Clean up
git clean -fd # Remove untracked files/dirs
git checkout . # Discard all changes
git restore . # Discard all changes (Git 2.23+)
```
## Prevention Checklist
Before risky operations:
- [ ] Create backup branch: `git branch backup`
- [ ] Ensure working tree is clean: `git status`
- [ ] Know your reflog: `git reflog | head -20`
- [ ] Verify you're on right branch: `git branch`
- [ ] Check remote status: `git fetch && git status`
---
**Remember:** Most Git operations can be undone. Check reflog first, and don't panic. Take time to understand the problem before attempting fixes.
```