Initial commit
This commit is contained in:
715
skills/git-advanced/SKILL.md
Normal file
715
skills/git-advanced/SKILL.md
Normal file
@@ -0,0 +1,715 @@
|
||||
---
|
||||
name: git-advanced
|
||||
description: Advanced git operations including complex rebase strategies, interactive staging, commit surgery, and history manipulation. Use when user needs to perform complex git operations like rewriting history or advanced merging.
|
||||
---
|
||||
|
||||
# Git Advanced Operations Skill
|
||||
|
||||
This skill provides comprehensive guidance on advanced git operations, sophisticated rebase strategies, commit surgery techniques, and complex history manipulation for experienced git users.
|
||||
|
||||
## When to Use
|
||||
|
||||
Activate this skill when:
|
||||
- Performing complex interactive rebases
|
||||
- Rewriting commit history
|
||||
- Splitting or combining commits
|
||||
- Advanced merge strategies
|
||||
- Cherry-picking across branches
|
||||
- Commit message editing in history
|
||||
- Author information changes
|
||||
- Complex conflict resolution
|
||||
|
||||
## Interactive Rebase Strategies
|
||||
|
||||
### Basic Interactive Rebase
|
||||
|
||||
```bash
|
||||
# Rebase last 5 commits
|
||||
git rebase -i HEAD~5
|
||||
|
||||
# Rebase from specific commit
|
||||
git rebase -i abc123^
|
||||
|
||||
# Rebase entire branch
|
||||
git rebase -i main
|
||||
```
|
||||
|
||||
### Rebase Commands
|
||||
|
||||
```bash
|
||||
# Interactive rebase editor commands:
|
||||
# p, pick = use commit
|
||||
# r, reword = use commit, but edit commit message
|
||||
# e, edit = use commit, but stop for amending
|
||||
# s, squash = use commit, but meld into previous commit
|
||||
# f, fixup = like squash, but discard commit message
|
||||
# x, exec = run command (the rest of the line) using shell
|
||||
# d, drop = remove commit
|
||||
```
|
||||
|
||||
### Squashing Commits
|
||||
|
||||
```bash
|
||||
# Example: Squash last 3 commits
|
||||
git rebase -i HEAD~3
|
||||
|
||||
# In editor:
|
||||
pick abc123 feat: add user authentication
|
||||
squash def456 fix: resolve login bug
|
||||
squash ghi789 style: format code
|
||||
|
||||
# Squash all commits in feature branch
|
||||
git rebase -i main
|
||||
# Mark all except first as 'squash'
|
||||
```
|
||||
|
||||
### Fixup Workflow
|
||||
|
||||
```bash
|
||||
# Create fixup commit automatically
|
||||
git commit --fixup=abc123
|
||||
|
||||
# Autosquash during rebase
|
||||
git rebase -i --autosquash main
|
||||
|
||||
# Set autosquash as default
|
||||
git config --global rebase.autosquash true
|
||||
|
||||
# Example workflow:
|
||||
git log --oneline -5
|
||||
# abc123 feat: add authentication
|
||||
# def456 feat: add authorization
|
||||
git commit --fixup=abc123
|
||||
git rebase -i --autosquash HEAD~3
|
||||
```
|
||||
|
||||
### Reordering Commits
|
||||
|
||||
```bash
|
||||
# Interactive rebase
|
||||
git rebase -i HEAD~5
|
||||
|
||||
# In editor, change order:
|
||||
pick def456 feat: add database migration
|
||||
pick abc123 feat: add user model
|
||||
pick ghi789 feat: add API endpoints
|
||||
|
||||
# Reorder by moving lines:
|
||||
pick abc123 feat: add user model
|
||||
pick def456 feat: add database migration
|
||||
pick ghi789 feat: add API endpoints
|
||||
```
|
||||
|
||||
### Splitting Commits
|
||||
|
||||
```bash
|
||||
# Start interactive rebase
|
||||
git rebase -i HEAD~3
|
||||
|
||||
# Mark commit to split with 'edit'
|
||||
edit abc123 feat: add user and role features
|
||||
|
||||
# When rebase stops:
|
||||
git reset HEAD^
|
||||
|
||||
# Stage and commit parts separately
|
||||
git add user.go
|
||||
git commit -m "feat: add user management"
|
||||
|
||||
git add role.go
|
||||
git commit -m "feat: add role management"
|
||||
|
||||
# Continue rebase
|
||||
git rebase --continue
|
||||
```
|
||||
|
||||
### Editing Old Commits
|
||||
|
||||
```bash
|
||||
# Start interactive rebase
|
||||
git rebase -i HEAD~5
|
||||
|
||||
# Mark commit with 'edit'
|
||||
edit abc123 feat: add authentication
|
||||
|
||||
# When rebase stops, make changes
|
||||
git add modified-file.go
|
||||
git commit --amend --no-edit
|
||||
|
||||
# Or change commit message
|
||||
git commit --amend
|
||||
|
||||
# Continue rebase
|
||||
git rebase --continue
|
||||
```
|
||||
|
||||
## Commit Surgery
|
||||
|
||||
### Amending Commits
|
||||
|
||||
```bash
|
||||
# Amend last commit (add changes)
|
||||
git add forgotten-file.go
|
||||
git commit --amend --no-edit
|
||||
|
||||
# Amend commit message
|
||||
git commit --amend -m "fix: correct typo in feature"
|
||||
|
||||
# Amend author information
|
||||
git commit --amend --author="John Doe <john@example.com>"
|
||||
|
||||
# Amend date
|
||||
git commit --amend --date="2024-03-15 10:30:00"
|
||||
```
|
||||
|
||||
### Changing Commit Messages
|
||||
|
||||
```bash
|
||||
# Change last commit message
|
||||
git commit --amend
|
||||
|
||||
# Change older commit messages
|
||||
git rebase -i HEAD~5
|
||||
# Mark commits with 'reword'
|
||||
|
||||
# Change commit message without opening editor
|
||||
git commit --amend -m "new message" --no-edit
|
||||
```
|
||||
|
||||
### Changing Multiple Authors
|
||||
|
||||
```bash
|
||||
# Filter-branch (legacy method, use filter-repo instead)
|
||||
git filter-branch --env-filter '
|
||||
if [ "$GIT_COMMITTER_EMAIL" = "old@example.com" ]; then
|
||||
export GIT_COMMITTER_NAME="New Name"
|
||||
export GIT_COMMITTER_EMAIL="new@example.com"
|
||||
fi
|
||||
if [ "$GIT_AUTHOR_EMAIL" = "old@example.com" ]; then
|
||||
export GIT_AUTHOR_NAME="New Name"
|
||||
export GIT_AUTHOR_EMAIL="new@example.com"
|
||||
fi
|
||||
' --tag-name-filter cat -- --branches --tags
|
||||
|
||||
# Modern method with git-filter-repo
|
||||
git filter-repo --email-callback '
|
||||
return email.replace(b"old@example.com", b"new@example.com")
|
||||
'
|
||||
```
|
||||
|
||||
### Removing Files from History
|
||||
|
||||
```bash
|
||||
# Remove file from all history
|
||||
git filter-branch --tree-filter 'rm -f passwords.txt' HEAD
|
||||
|
||||
# Better performance with index-filter
|
||||
git filter-branch --index-filter 'git rm --cached --ignore-unmatch passwords.txt' HEAD
|
||||
|
||||
# Modern method with git-filter-repo (recommended)
|
||||
git filter-repo --path passwords.txt --invert-paths
|
||||
|
||||
# Remove large files
|
||||
git filter-repo --strip-blobs-bigger-than 10M
|
||||
```
|
||||
|
||||
### BFG Repo-Cleaner
|
||||
|
||||
```bash
|
||||
# Install BFG
|
||||
# brew install bfg (macOS)
|
||||
# apt-get install bfg (Ubuntu)
|
||||
|
||||
# Remove files by name
|
||||
bfg --delete-files passwords.txt
|
||||
|
||||
# Remove large files
|
||||
bfg --strip-blobs-bigger-than 50M
|
||||
|
||||
# Replace passwords in history
|
||||
bfg --replace-text passwords.txt
|
||||
|
||||
# After BFG cleanup
|
||||
git reflog expire --expire=now --all
|
||||
git gc --prune=now --aggressive
|
||||
```
|
||||
|
||||
## Advanced Cherry-Picking
|
||||
|
||||
### Basic Cherry-Pick
|
||||
|
||||
```bash
|
||||
# Cherry-pick single commit
|
||||
git cherry-pick abc123
|
||||
|
||||
# Cherry-pick multiple commits
|
||||
git cherry-pick abc123 def456 ghi789
|
||||
|
||||
# Cherry-pick range of commits
|
||||
git cherry-pick abc123..ghi789
|
||||
|
||||
# Cherry-pick without committing (stage only)
|
||||
git cherry-pick -n abc123
|
||||
```
|
||||
|
||||
### Cherry-Pick with Conflicts
|
||||
|
||||
```bash
|
||||
# When conflicts occur
|
||||
git cherry-pick abc123
|
||||
# CONFLICT: resolve conflicts
|
||||
|
||||
# After resolving conflicts
|
||||
git add resolved-file.go
|
||||
git cherry-pick --continue
|
||||
|
||||
# Or abort cherry-pick
|
||||
git cherry-pick --abort
|
||||
|
||||
# Skip current commit
|
||||
git cherry-pick --skip
|
||||
```
|
||||
|
||||
### Cherry-Pick Options
|
||||
|
||||
```bash
|
||||
# Edit commit message during cherry-pick
|
||||
git cherry-pick -e abc123
|
||||
|
||||
# Sign-off cherry-picked commit
|
||||
git cherry-pick -s abc123
|
||||
|
||||
# Keep original author date
|
||||
git cherry-pick --ff abc123
|
||||
|
||||
# Apply changes without commit attribution
|
||||
git cherry-pick -n abc123
|
||||
git commit --author="New Author <new@example.com>"
|
||||
```
|
||||
|
||||
### Mainline Selection for Merge Commits
|
||||
|
||||
```bash
|
||||
# Cherry-pick merge commit (specify parent)
|
||||
git cherry-pick -m 1 abc123
|
||||
|
||||
# -m 1 = use first parent (main branch)
|
||||
# -m 2 = use second parent (merged branch)
|
||||
|
||||
# Example workflow:
|
||||
git log --graph --oneline
|
||||
# * abc123 Merge pull request #123
|
||||
# |\
|
||||
# | * def456 feat: feature commit
|
||||
# * | ghi789 fix: main branch commit
|
||||
|
||||
# To cherry-pick the merge keeping main branch changes:
|
||||
git cherry-pick -m 1 abc123
|
||||
```
|
||||
|
||||
## Advanced Merging
|
||||
|
||||
### Merge Strategies
|
||||
|
||||
```bash
|
||||
# Recursive merge (default)
|
||||
git merge -s recursive branch-name
|
||||
|
||||
# Ours (keep our changes on conflict)
|
||||
git merge -s ours branch-name
|
||||
|
||||
# Theirs (keep their changes on conflict)
|
||||
git merge -s theirs branch-name
|
||||
|
||||
# Octopus (merge 3+ branches)
|
||||
git merge -s octopus branch1 branch2 branch3
|
||||
|
||||
# Subtree merge
|
||||
git merge -s subtree branch-name
|
||||
```
|
||||
|
||||
### Merge Strategy Options
|
||||
|
||||
```bash
|
||||
# Ours (resolve conflicts with our version)
|
||||
git merge -X ours branch-name
|
||||
|
||||
# Theirs (resolve conflicts with their version)
|
||||
git merge -X theirs branch-name
|
||||
|
||||
# Ignore whitespace
|
||||
git merge -X ignore-space-change branch-name
|
||||
git merge -X ignore-all-space branch-name
|
||||
|
||||
# Patience algorithm (better conflict detection)
|
||||
git merge -X patience branch-name
|
||||
|
||||
# Renormalize line endings
|
||||
git merge -X renormalize branch-name
|
||||
```
|
||||
|
||||
### Three-Way Merge
|
||||
|
||||
```bash
|
||||
# Standard three-way merge
|
||||
git merge feature-branch
|
||||
|
||||
# With custom merge message
|
||||
git merge feature-branch -m "Merge feature: add authentication"
|
||||
|
||||
# No fast-forward (always create merge commit)
|
||||
git merge --no-ff feature-branch
|
||||
|
||||
# Fast-forward only (fail if merge commit needed)
|
||||
git merge --ff-only feature-branch
|
||||
|
||||
# Squash merge (combine all commits)
|
||||
git merge --squash feature-branch
|
||||
git commit -m "feat: add complete authentication system"
|
||||
```
|
||||
|
||||
## Advanced Conflict Resolution
|
||||
|
||||
### Understanding Conflict Markers
|
||||
|
||||
```
|
||||
<<<<<<< HEAD (Current Change)
|
||||
int result = add(a, b);
|
||||
=======
|
||||
int sum = calculate(a, b);
|
||||
>>>>>>> feature-branch (Incoming Change)
|
||||
```
|
||||
|
||||
### Conflict Resolution Tools
|
||||
|
||||
```bash
|
||||
# Use mergetool
|
||||
git mergetool
|
||||
|
||||
# Specify merge tool
|
||||
git mergetool --tool=vimdiff
|
||||
git mergetool --tool=meld
|
||||
git mergetool --tool=kdiff3
|
||||
|
||||
# Configure default merge tool
|
||||
git config --global merge.tool vimdiff
|
||||
git config --global mergetool.vimdiff.cmd 'vimdiff "$LOCAL" "$MERGED" "$REMOTE"'
|
||||
|
||||
# Check out specific version
|
||||
git checkout --ours file.go # Keep our version
|
||||
git checkout --theirs file.go # Keep their version
|
||||
git checkout --merge file.go # Recreate conflict markers
|
||||
```
|
||||
|
||||
### Rerere (Reuse Recorded Resolution)
|
||||
|
||||
```bash
|
||||
# Enable rerere
|
||||
git config --global rerere.enabled true
|
||||
|
||||
# Rerere will automatically resolve previously seen conflicts
|
||||
git merge feature-branch
|
||||
# Conflict occurs and is resolved
|
||||
git add file.go
|
||||
git commit
|
||||
|
||||
# Later, same conflict:
|
||||
git merge another-branch
|
||||
# Rerere automatically applies previous resolution
|
||||
|
||||
# View rerere cache
|
||||
git rerere status
|
||||
git rerere diff
|
||||
|
||||
# Clear rerere cache
|
||||
git rerere forget file.go
|
||||
git rerere clear
|
||||
```
|
||||
|
||||
## Interactive Staging
|
||||
|
||||
### Partial File Staging
|
||||
|
||||
```bash
|
||||
# Interactive staging
|
||||
git add -p file.go
|
||||
|
||||
# Patch commands:
|
||||
# y - stage this hunk
|
||||
# n - do not stage this hunk
|
||||
# q - quit (do not stage this and remaining hunks)
|
||||
# a - stage this and all remaining hunks
|
||||
# d - do not stage this and all remaining hunks
|
||||
# s - split the current hunk into smaller hunks
|
||||
# e - manually edit the current hunk
|
||||
```
|
||||
|
||||
### Interactive Add
|
||||
|
||||
```bash
|
||||
# Interactive mode
|
||||
git add -i
|
||||
|
||||
# Commands:
|
||||
# 1: status - show paths with changes
|
||||
# 2: update - stage paths
|
||||
# 3: revert - unstage paths
|
||||
# 4: add untracked - stage untracked files
|
||||
# 5: patch - partial staging
|
||||
# 6: diff - show staged changes
|
||||
# 7: quit - exit
|
||||
```
|
||||
|
||||
### Partial Commits
|
||||
|
||||
```bash
|
||||
# Stage part of file interactively
|
||||
git add -p file.go
|
||||
|
||||
# Create commit with partial changes
|
||||
git commit -m "feat: add validation logic"
|
||||
|
||||
# Stage remaining changes
|
||||
git add file.go
|
||||
git commit -m "feat: add error handling"
|
||||
```
|
||||
|
||||
## Advanced Reset Operations
|
||||
|
||||
### Reset Modes
|
||||
|
||||
```bash
|
||||
# Soft reset (keep changes staged)
|
||||
git reset --soft HEAD~1
|
||||
|
||||
# Mixed reset (keep changes unstaged, default)
|
||||
git reset --mixed HEAD~1
|
||||
git reset HEAD~1
|
||||
|
||||
# Hard reset (discard all changes)
|
||||
git reset --hard HEAD~1
|
||||
|
||||
# Reset to specific commit
|
||||
git reset --hard abc123
|
||||
```
|
||||
|
||||
### Reset vs Revert
|
||||
|
||||
```bash
|
||||
# Reset (rewrites history, use for local changes)
|
||||
git reset --hard HEAD~3
|
||||
|
||||
# Revert (creates new commit, safe for shared history)
|
||||
git revert HEAD
|
||||
git revert HEAD~3
|
||||
git revert abc123..def456
|
||||
```
|
||||
|
||||
## Advanced Branch Operations
|
||||
|
||||
### Branch from Specific Commit
|
||||
|
||||
```bash
|
||||
# Create branch from commit
|
||||
git branch new-branch abc123
|
||||
git checkout new-branch
|
||||
|
||||
# Or in one command
|
||||
git checkout -b new-branch abc123
|
||||
|
||||
# Create branch from remote commit
|
||||
git checkout -b local-branch origin/remote-branch
|
||||
```
|
||||
|
||||
### Orphan Branches
|
||||
|
||||
```bash
|
||||
# Create orphan branch (no parent)
|
||||
git checkout --orphan new-root
|
||||
git rm -rf .
|
||||
|
||||
# Useful for gh-pages, documentation, etc.
|
||||
echo "# Documentation" > README.md
|
||||
git add README.md
|
||||
git commit -m "docs: initialize documentation"
|
||||
```
|
||||
|
||||
### Branch Tracking
|
||||
|
||||
```bash
|
||||
# Set upstream branch
|
||||
git branch -u origin/main
|
||||
|
||||
# Push and set upstream
|
||||
git push -u origin feature-branch
|
||||
|
||||
# Change upstream
|
||||
git branch -u origin/develop
|
||||
|
||||
# View tracking information
|
||||
git branch -vv
|
||||
```
|
||||
|
||||
## Advanced Stash Operations
|
||||
|
||||
### Stash Specific Files
|
||||
|
||||
```bash
|
||||
# Stash specific files
|
||||
git stash push -m "WIP: feature work" file1.go file2.go
|
||||
|
||||
# Stash with pathspec
|
||||
git stash push -p
|
||||
|
||||
# Stash untracked files
|
||||
git stash -u
|
||||
|
||||
# Stash including ignored files
|
||||
git stash -a
|
||||
```
|
||||
|
||||
### Stash to Branch
|
||||
|
||||
```bash
|
||||
# Create branch from stash
|
||||
git stash branch new-branch stash@{0}
|
||||
|
||||
# Creates new branch and applies stash
|
||||
git stash branch feature-work
|
||||
```
|
||||
|
||||
### Partial Stash Application
|
||||
|
||||
```bash
|
||||
# Apply specific files from stash
|
||||
git checkout stash@{0} -- file.go
|
||||
|
||||
# Apply stash without dropping
|
||||
git stash apply stash@{0}
|
||||
|
||||
# Apply and drop
|
||||
git stash pop stash@{0}
|
||||
```
|
||||
|
||||
## Submodule Management
|
||||
|
||||
### Advanced Submodule Operations
|
||||
|
||||
```bash
|
||||
# Update submodule to specific commit
|
||||
cd submodule-dir
|
||||
git checkout abc123
|
||||
cd ..
|
||||
git add submodule-dir
|
||||
git commit -m "chore: update submodule to version 1.2.3"
|
||||
|
||||
# Update all submodules to latest
|
||||
git submodule update --remote --merge
|
||||
|
||||
# Update specific submodule
|
||||
git submodule update --remote --merge path/to/submodule
|
||||
|
||||
# Run command in all submodules
|
||||
git submodule foreach 'git checkout main'
|
||||
git submodule foreach 'git pull'
|
||||
|
||||
# Clone with submodules at specific depth
|
||||
git clone --recurse-submodules --depth 1 repo-url
|
||||
```
|
||||
|
||||
### Submodule to Subtree Migration
|
||||
|
||||
```bash
|
||||
# Remove submodule
|
||||
git submodule deinit path/to/submodule
|
||||
git rm path/to/submodule
|
||||
rm -rf .git/modules/path/to/submodule
|
||||
|
||||
# Add as subtree
|
||||
git subtree add --prefix=path/to/submodule \
|
||||
https://github.com/user/repo.git main --squash
|
||||
|
||||
# Update subtree
|
||||
git subtree pull --prefix=path/to/submodule \
|
||||
https://github.com/user/repo.git main --squash
|
||||
```
|
||||
|
||||
## Advanced Log and History
|
||||
|
||||
### Custom Log Formatting
|
||||
|
||||
```bash
|
||||
# One-line format with custom fields
|
||||
git log --pretty=format:"%h - %an, %ar : %s"
|
||||
|
||||
# Full custom format
|
||||
git log --pretty=format:"%C(yellow)%h%C(reset) %C(blue)%ad%C(reset) %C(green)%an%C(reset) %s" --date=short
|
||||
|
||||
# Aliases for common formats
|
||||
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"
|
||||
```
|
||||
|
||||
### Finding Lost Commits
|
||||
|
||||
```bash
|
||||
# Find commits not in any branch
|
||||
git log --all --oneline --no-walk --decorate $(git fsck --no-reflog | grep commit | cut -d' ' -f3)
|
||||
|
||||
# Find dangling commits
|
||||
git fsck --lost-found
|
||||
|
||||
# Search commit messages
|
||||
git log --all --grep="search term"
|
||||
|
||||
# Find commits by author
|
||||
git log --author="John Doe"
|
||||
|
||||
# Find commits modifying specific code
|
||||
git log -S "function_name"
|
||||
git log -G "regex_pattern"
|
||||
```
|
||||
|
||||
### Bisect Automation
|
||||
|
||||
```bash
|
||||
# Start bisect
|
||||
git bisect start
|
||||
git bisect bad HEAD
|
||||
git bisect good abc123
|
||||
|
||||
# Automate bisect with script
|
||||
git bisect run ./test.sh
|
||||
|
||||
# test.sh example:
|
||||
#!/bin/bash
|
||||
make && make test
|
||||
exit $?
|
||||
|
||||
# Bisect will automatically find first bad commit
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Backup Before History Rewriting:** Create backup branch before complex operations
|
||||
2. **Never Rewrite Published History:** Only rewrite local commits
|
||||
3. **Communicate Rebases:** Inform team when force-pushing
|
||||
4. **Use Descriptive Commit Messages:** Even during interactive rebase
|
||||
5. **Test After Rebase:** Ensure code still works after history changes
|
||||
6. **Prefer Rebase for Local Branches:** Keep history linear
|
||||
7. **Use Merge for Shared Branches:** Preserve complete history
|
||||
8. **Sign Important Commits:** Use GPG signing for releases
|
||||
9. **Document Complex Operations:** Leave comments for future reference
|
||||
10. **Know When to Stop:** Sometimes merge commits are clearer than rebased history
|
||||
|
||||
## Resources
|
||||
|
||||
Additional guides and examples are available in the `assets/` directory:
|
||||
- `examples/` - Complex rebase and merge scenarios
|
||||
- `scripts/` - Automation scripts for common operations
|
||||
- `workflows/` - Advanced workflow patterns
|
||||
|
||||
See `references/` directory for:
|
||||
- Git internals documentation
|
||||
- Advanced rebasing strategies
|
||||
- Filter-branch alternatives
|
||||
- Conflict resolution techniques
|
||||
569
skills/git-conventions/SKILL.md
Normal file
569
skills/git-conventions/SKILL.md
Normal file
@@ -0,0 +1,569 @@
|
||||
---
|
||||
name: git-conventions
|
||||
description: Git conventions and workflow best practices including Conventional Commits, branch naming, and commit message guidelines. Use when user needs guidance on git standards, commit formats, or workflow patterns.
|
||||
---
|
||||
|
||||
# Git Conventions Skill
|
||||
|
||||
This skill provides comprehensive guidance on git conventions, workflow best practices, and standardized commit formats to maintain clean, readable repository history.
|
||||
|
||||
## When to Use
|
||||
|
||||
Activate this skill when:
|
||||
- Writing commit messages following standards
|
||||
- Establishing team git workflows
|
||||
- Setting up branch naming conventions
|
||||
- Implementing Conventional Commits
|
||||
- Creating changelog automation
|
||||
- Code review for git hygiene
|
||||
- Onboarding team members on git practices
|
||||
|
||||
## Conventional Commits
|
||||
|
||||
### Format
|
||||
|
||||
```
|
||||
<type>[optional scope]: <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer(s)]
|
||||
```
|
||||
|
||||
### Commit Types
|
||||
|
||||
**Primary Types:**
|
||||
- **feat**: New feature for the user
|
||||
- **fix**: Bug fix for the user
|
||||
- **docs**: Documentation only changes
|
||||
- **style**: Code style changes (formatting, missing semi-colons, etc)
|
||||
- **refactor**: Code change that neither fixes a bug nor adds a feature
|
||||
- **perf**: Performance improvements
|
||||
- **test**: Adding or correcting tests
|
||||
- **build**: Changes to build system or dependencies
|
||||
- **ci**: Changes to CI configuration files and scripts
|
||||
- **chore**: Other changes that don't modify src or test files
|
||||
- **revert**: Reverts a previous commit
|
||||
|
||||
### Examples
|
||||
|
||||
**Simple commit:**
|
||||
```bash
|
||||
feat: add user authentication
|
||||
|
||||
Implement JWT-based authentication system with refresh tokens.
|
||||
Includes middleware for protected routes.
|
||||
|
||||
Closes #123
|
||||
```
|
||||
|
||||
**Breaking change:**
|
||||
```bash
|
||||
feat!: redesign API response format
|
||||
|
||||
BREAKING CHANGE: API now returns data in camelCase instead of snake_case.
|
||||
Migration guide available in docs/migration-v2.md.
|
||||
|
||||
Refs: #456
|
||||
```
|
||||
|
||||
**With scope:**
|
||||
```bash
|
||||
fix(auth): resolve token expiration edge case
|
||||
|
||||
Token validation now properly handles timezone offsets.
|
||||
Adds retry logic for expired tokens within 5-minute grace period.
|
||||
```
|
||||
|
||||
**Multiple paragraphs:**
|
||||
```bash
|
||||
refactor(database): optimize query performance
|
||||
|
||||
- Add indexes on frequently queried columns
|
||||
- Implement connection pooling
|
||||
- Cache common queries with Redis
|
||||
- Reduce N+1 queries in user associations
|
||||
|
||||
Performance improved by 60% in production testing.
|
||||
|
||||
Reviewed-by: Jane Doe <jane@example.com>
|
||||
Refs: #789
|
||||
```
|
||||
|
||||
### Commit Message Rules
|
||||
|
||||
1. **Subject line:**
|
||||
- Use imperative mood ("add" not "added" or "adds")
|
||||
- No capitalization of first letter
|
||||
- No period at the end
|
||||
- Maximum 50 characters (soft limit)
|
||||
- Separate from body with blank line
|
||||
|
||||
2. **Body:**
|
||||
- Wrap at 72 characters
|
||||
- Explain what and why, not how
|
||||
- Use bullet points for multiple items
|
||||
- Reference issues and PRs
|
||||
|
||||
3. **Footer:**
|
||||
- Breaking changes start with "BREAKING CHANGE:"
|
||||
- Reference issues: "Closes #123", "Fixes #456", "Refs #789"
|
||||
- Co-authors: "Co-authored-by: Name <email>"
|
||||
|
||||
## Branch Naming Conventions
|
||||
|
||||
### Format Pattern
|
||||
|
||||
```
|
||||
<type>/<issue-number>-<short-description>
|
||||
```
|
||||
|
||||
### Branch Types
|
||||
|
||||
**Common prefixes:**
|
||||
- `feature/` or `feat/` - New features
|
||||
- `fix/` or `bugfix/` - Bug fixes
|
||||
- `hotfix/` - Urgent production fixes
|
||||
- `release/` - Release preparation
|
||||
- `docs/` - Documentation updates
|
||||
- `refactor/` - Code refactoring
|
||||
- `test/` - Test additions or fixes
|
||||
- `chore/` - Maintenance tasks
|
||||
- `experimental/` or `spike/` - Proof of concepts
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
# Feature branches
|
||||
feature/123-user-authentication
|
||||
feat/456-add-payment-gateway
|
||||
feature/oauth-integration
|
||||
|
||||
# Bug fix branches
|
||||
fix/789-resolve-memory-leak
|
||||
bugfix/login-redirect-loop
|
||||
fix/456-null-pointer-exception
|
||||
|
||||
# Hotfix branches
|
||||
hotfix/critical-security-patch
|
||||
hotfix/production-database-issue
|
||||
|
||||
# Release branches
|
||||
release/v1.2.0
|
||||
release/2024-Q1
|
||||
|
||||
# Documentation branches
|
||||
docs/api-reference-update
|
||||
docs/123-add-contributing-guide
|
||||
|
||||
# Refactor branches
|
||||
refactor/database-layer
|
||||
refactor/456-simplify-auth-flow
|
||||
|
||||
# Experimental branches
|
||||
experimental/graphql-api
|
||||
spike/performance-optimization
|
||||
```
|
||||
|
||||
### Branch Naming Rules
|
||||
|
||||
1. **Use hyphens** for word separation (not underscores)
|
||||
2. **Lowercase only** (avoid capitals)
|
||||
3. **Keep it short** but descriptive (max 50 characters)
|
||||
4. **Include issue number** when applicable
|
||||
5. **Avoid special characters** except hyphens and forward slashes
|
||||
6. **No trailing slashes**
|
||||
7. **Be consistent** within your team
|
||||
|
||||
## Protected Branch Strategy
|
||||
|
||||
### Main Branches
|
||||
|
||||
**main/master:**
|
||||
- Production-ready code
|
||||
- Always deployable
|
||||
- Protected with required reviews
|
||||
- No direct commits
|
||||
- Merge only from release or hotfix branches
|
||||
|
||||
**develop:**
|
||||
- Integration branch for features
|
||||
- Pre-production testing
|
||||
- Protected with CI checks
|
||||
- Merge target for feature branches
|
||||
|
||||
**staging:**
|
||||
- Pre-production environment
|
||||
- QA testing branch
|
||||
- Mirror of production with new features
|
||||
|
||||
### Protection Rules
|
||||
|
||||
```yaml
|
||||
# Example GitHub branch protection
|
||||
main:
|
||||
require_pull_request_reviews:
|
||||
required_approving_review_count: 2
|
||||
dismiss_stale_reviews: true
|
||||
require_code_owner_reviews: true
|
||||
|
||||
require_status_checks:
|
||||
strict: true
|
||||
contexts:
|
||||
- continuous-integration
|
||||
- code-quality
|
||||
- security-scan
|
||||
|
||||
enforce_admins: true
|
||||
require_linear_history: true
|
||||
allow_force_pushes: false
|
||||
allow_deletions: false
|
||||
```
|
||||
|
||||
## Semantic Versioning
|
||||
|
||||
### Version Format
|
||||
|
||||
```
|
||||
MAJOR.MINOR.PATCH[-prerelease][+build]
|
||||
```
|
||||
|
||||
**Examples:**
|
||||
- `1.0.0` - Initial release
|
||||
- `1.2.3` - Minor update with patches
|
||||
- `2.0.0-alpha.1` - Pre-release alpha
|
||||
- `1.5.0-rc.2+20240321` - Release candidate with build metadata
|
||||
|
||||
### Version Increment Rules
|
||||
|
||||
**MAJOR (X.0.0):**
|
||||
- Breaking changes
|
||||
- API incompatibilities
|
||||
- Major redesigns
|
||||
- Removal of deprecated features
|
||||
|
||||
**MINOR (x.Y.0):**
|
||||
- New features (backward compatible)
|
||||
- Deprecated features (still functional)
|
||||
- Substantial internal changes
|
||||
|
||||
**PATCH (x.y.Z):**
|
||||
- Bug fixes
|
||||
- Security patches
|
||||
- Performance improvements
|
||||
- Documentation updates
|
||||
|
||||
### Git Tags for Versions
|
||||
|
||||
```bash
|
||||
# Create annotated tag
|
||||
git tag -a v1.2.3 -m "Release version 1.2.3
|
||||
|
||||
- Add user authentication
|
||||
- Fix memory leak in cache
|
||||
- Improve API performance"
|
||||
|
||||
# Push tags to remote
|
||||
git push origin v1.2.3
|
||||
|
||||
# Push all tags
|
||||
git push --tags
|
||||
|
||||
# Create pre-release tag
|
||||
git tag -a v2.0.0-beta.1 -m "Beta release for v2.0.0"
|
||||
|
||||
# Delete tag
|
||||
git tag -d v1.2.3
|
||||
git push origin :refs/tags/v1.2.3
|
||||
```
|
||||
|
||||
## Workflow Patterns
|
||||
|
||||
### Git Flow
|
||||
|
||||
**Branch structure:**
|
||||
- `main` - Production releases
|
||||
- `develop` - Next release development
|
||||
- `feature/*` - New features
|
||||
- `release/*` - Release preparation
|
||||
- `hotfix/*` - Emergency fixes
|
||||
|
||||
**Feature workflow:**
|
||||
```bash
|
||||
# Start feature
|
||||
git checkout develop
|
||||
git pull origin develop
|
||||
git checkout -b feature/123-new-feature
|
||||
|
||||
# Work on feature
|
||||
git add .
|
||||
git commit -m "feat: implement user authentication"
|
||||
|
||||
# Finish feature
|
||||
git checkout develop
|
||||
git pull origin develop
|
||||
git merge --no-ff feature/123-new-feature
|
||||
git push origin develop
|
||||
git branch -d feature/123-new-feature
|
||||
```
|
||||
|
||||
**Release workflow:**
|
||||
```bash
|
||||
# Start release
|
||||
git checkout develop
|
||||
git checkout -b release/v1.2.0
|
||||
|
||||
# Prepare release (bump version, update changelog)
|
||||
git commit -m "chore: prepare release v1.2.0"
|
||||
|
||||
# Merge to main
|
||||
git checkout main
|
||||
git merge --no-ff release/v1.2.0
|
||||
git tag -a v1.2.0 -m "Release v1.2.0"
|
||||
|
||||
# Merge back to develop
|
||||
git checkout develop
|
||||
git merge --no-ff release/v1.2.0
|
||||
|
||||
# Cleanup
|
||||
git branch -d release/v1.2.0
|
||||
```
|
||||
|
||||
**Hotfix workflow:**
|
||||
```bash
|
||||
# Start hotfix from main
|
||||
git checkout main
|
||||
git checkout -b hotfix/critical-bug
|
||||
|
||||
# Fix and commit
|
||||
git commit -m "fix: resolve critical security vulnerability"
|
||||
|
||||
# Merge to main
|
||||
git checkout main
|
||||
git merge --no-ff hotfix/critical-bug
|
||||
git tag -a v1.2.1 -m "Hotfix v1.2.1"
|
||||
|
||||
# Merge to develop
|
||||
git checkout develop
|
||||
git merge --no-ff hotfix/critical-bug
|
||||
|
||||
# Cleanup
|
||||
git branch -d hotfix/critical-bug
|
||||
```
|
||||
|
||||
### GitHub Flow
|
||||
|
||||
**Simplified workflow:**
|
||||
- `main` - Always deployable
|
||||
- `feature/*` - All changes in feature branches
|
||||
|
||||
**Workflow:**
|
||||
```bash
|
||||
# Create feature branch
|
||||
git checkout -b feature/add-logging
|
||||
git push -u origin feature/add-logging
|
||||
|
||||
# Make changes and commit
|
||||
git commit -m "feat: add structured logging"
|
||||
git push origin feature/add-logging
|
||||
|
||||
# Open pull request on GitHub
|
||||
# After review and CI passes, merge to main
|
||||
# Deploy from main
|
||||
```
|
||||
|
||||
### Trunk-Based Development
|
||||
|
||||
**Single main branch:**
|
||||
- Short-lived feature branches (< 2 days)
|
||||
- Frequent integration to main
|
||||
- Feature flags for incomplete features
|
||||
- Continuous integration
|
||||
|
||||
**Workflow:**
|
||||
```bash
|
||||
# Create short-lived branch
|
||||
git checkout -b update-api-docs
|
||||
git push -u origin update-api-docs
|
||||
|
||||
# Make small, incremental changes
|
||||
git commit -m "docs: update API endpoint documentation"
|
||||
git push origin update-api-docs
|
||||
|
||||
# Immediately create PR and merge (same day)
|
||||
# Main branch always deployable with feature flags
|
||||
```
|
||||
|
||||
## Pull Request Conventions
|
||||
|
||||
### PR Title Format
|
||||
|
||||
Use Conventional Commits format:
|
||||
```
|
||||
feat(auth): add OAuth2 provider support
|
||||
fix(api): resolve rate limiting edge case
|
||||
docs: update installation guide
|
||||
```
|
||||
|
||||
### PR Description Template
|
||||
|
||||
```markdown
|
||||
## Summary
|
||||
Brief description of changes and motivation.
|
||||
|
||||
## Changes
|
||||
- Bullet list of specific changes
|
||||
- Reference architecture decisions
|
||||
- Note any breaking changes
|
||||
|
||||
## Testing
|
||||
- Unit tests added/updated
|
||||
- Integration tests passed
|
||||
- Manual testing performed
|
||||
|
||||
## Screenshots (if applicable)
|
||||
[Add screenshots for UI changes]
|
||||
|
||||
## Related Issues
|
||||
Closes #123
|
||||
Refs #456
|
||||
|
||||
## Checklist
|
||||
- [ ] Tests added/updated
|
||||
- [ ] Documentation updated
|
||||
- [ ] Changelog updated
|
||||
- [ ] Breaking changes documented
|
||||
- [ ] Code reviewed by team
|
||||
```
|
||||
|
||||
### Review Guidelines
|
||||
|
||||
**Reviewer checklist:**
|
||||
- [ ] Code follows style guide
|
||||
- [ ] Commit messages follow conventions
|
||||
- [ ] Tests are comprehensive
|
||||
- [ ] Documentation is updated
|
||||
- [ ] No security vulnerabilities
|
||||
- [ ] Performance considerations addressed
|
||||
- [ ] Breaking changes are justified
|
||||
|
||||
## Changelog Management
|
||||
|
||||
### Keep a Changelog Format
|
||||
|
||||
```markdown
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- User authentication with JWT tokens
|
||||
- API rate limiting middleware
|
||||
|
||||
### Changed
|
||||
- Updated database schema for better performance
|
||||
|
||||
### Deprecated
|
||||
- Old authentication endpoint (use /api/v2/auth instead)
|
||||
|
||||
### Removed
|
||||
- Legacy XML API support
|
||||
|
||||
### Fixed
|
||||
- Memory leak in cache implementation
|
||||
- Race condition in concurrent requests
|
||||
|
||||
### Security
|
||||
- Patch for SQL injection vulnerability
|
||||
|
||||
## [1.2.0] - 2024-03-15
|
||||
|
||||
### Added
|
||||
- Real-time notifications system
|
||||
- User profile customization
|
||||
|
||||
### Fixed
|
||||
- Login redirect loop issue
|
||||
- Session timeout handling
|
||||
|
||||
## [1.1.0] - 2024-02-01
|
||||
|
||||
### Added
|
||||
- Search functionality
|
||||
- Export to CSV feature
|
||||
|
||||
### Changed
|
||||
- Improved UI responsiveness
|
||||
```
|
||||
|
||||
### Automated Changelog
|
||||
|
||||
Use tools like:
|
||||
- `conventional-changelog` - Generate changelog from commits
|
||||
- `release-please` - Automated releases and changelog
|
||||
- `semantic-release` - Fully automated version management
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Commit Often:** Small, focused commits are easier to review and revert
|
||||
2. **Write Clear Messages:** Future you will thank present you
|
||||
3. **One Concern Per Commit:** Each commit should address one logical change
|
||||
4. **Test Before Committing:** Ensure code works before committing
|
||||
5. **Reference Issues:** Link commits to issue tracker
|
||||
6. **Review Your Own Changes:** Use `git diff --staged` before committing
|
||||
7. **Keep History Clean:** Rebase feature branches to keep linear history
|
||||
8. **Sign Your Commits:** Use GPG signing for verified commits
|
||||
9. **Use .gitignore Properly:** Never commit sensitive or generated files
|
||||
10. **Document Conventions:** Keep team conventions in repository docs
|
||||
|
||||
## Team Workflow Examples
|
||||
|
||||
### Small Team (2-5 developers)
|
||||
|
||||
```bash
|
||||
# Simplified workflow
|
||||
- Direct commits to main (with PR reviews)
|
||||
- Feature branches for major changes
|
||||
- Tags for releases
|
||||
- Linear history preferred
|
||||
```
|
||||
|
||||
### Medium Team (5-20 developers)
|
||||
|
||||
```bash
|
||||
# Git Flow variant
|
||||
- Protected main and develop branches
|
||||
- Feature branches required
|
||||
- Release branches for versions
|
||||
- Hotfix workflow for emergencies
|
||||
- Squash merge for clean history
|
||||
```
|
||||
|
||||
### Large Team (20+ developers)
|
||||
|
||||
```bash
|
||||
# Trunk-based with feature flags
|
||||
- Protected main branch
|
||||
- Very short-lived feature branches
|
||||
- Feature flags for incomplete work
|
||||
- Automated testing and deployment
|
||||
- Multiple daily integrations
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
Additional guides and templates are available in the `assets/` directory:
|
||||
- `templates/` - Commit message and PR templates
|
||||
- `examples/` - Real-world workflow examples
|
||||
- `tools/` - Git hooks and automation scripts
|
||||
|
||||
See `references/` directory for:
|
||||
- Conventional Commits specification
|
||||
- Semantic Versioning documentation
|
||||
- Git Flow and GitHub Flow guides
|
||||
- Keep a Changelog standards
|
||||
820
skills/git-repository/SKILL.md
Normal file
820
skills/git-repository/SKILL.md
Normal file
@@ -0,0 +1,820 @@
|
||||
---
|
||||
name: git-repository
|
||||
description: Repository management strategies including branch strategies (Git Flow, GitHub Flow, trunk-based), monorepo patterns, submodules, and repository organization. Use when user needs guidance on repository structure or branching strategies.
|
||||
---
|
||||
|
||||
# Git Repository Management Skill
|
||||
|
||||
This skill provides comprehensive guidance on repository management strategies, branching models, repository organization patterns, and scaling git for large teams and codebases.
|
||||
|
||||
## When to Use
|
||||
|
||||
Activate this skill when:
|
||||
- Setting up new repository structure
|
||||
- Choosing branching strategy
|
||||
- Managing monorepo vs polyrepo
|
||||
- Organizing multi-project repositories
|
||||
- Implementing submodule or subtree strategies
|
||||
- Scaling git for large teams
|
||||
- Migrating repository structures
|
||||
- Establishing team workflows
|
||||
|
||||
## Branching Strategies
|
||||
|
||||
### Git Flow
|
||||
|
||||
**Branch Structure:**
|
||||
- `main` (or `master`) - Production releases only
|
||||
- `develop` - Integration branch for next release
|
||||
- `feature/*` - Feature development branches
|
||||
- `release/*` - Release preparation branches
|
||||
- `hotfix/*` - Emergency production fixes
|
||||
|
||||
**Workflow:**
|
||||
|
||||
```bash
|
||||
# Feature Development
|
||||
git checkout develop
|
||||
git checkout -b feature/user-authentication
|
||||
# Work on feature...
|
||||
git commit -m "feat: add JWT authentication"
|
||||
git checkout develop
|
||||
git merge --no-ff feature/user-authentication
|
||||
git branch -d feature/user-authentication
|
||||
|
||||
# Release Preparation
|
||||
git checkout develop
|
||||
git checkout -b release/v1.2.0
|
||||
# Bump version, update changelog, final testing...
|
||||
git commit -m "chore: prepare release v1.2.0"
|
||||
|
||||
# Deploy Release
|
||||
git checkout main
|
||||
git merge --no-ff release/v1.2.0
|
||||
git tag -a v1.2.0 -m "Release version 1.2.0"
|
||||
git checkout develop
|
||||
git merge --no-ff release/v1.2.0
|
||||
git branch -d release/v1.2.0
|
||||
git push origin main develop --tags
|
||||
|
||||
# Hotfix
|
||||
git checkout main
|
||||
git checkout -b hotfix/security-patch
|
||||
git commit -m "fix: patch security vulnerability"
|
||||
git checkout main
|
||||
git merge --no-ff hotfix/security-patch
|
||||
git tag -a v1.2.1 -m "Hotfix v1.2.1"
|
||||
git checkout develop
|
||||
git merge --no-ff hotfix/security-patch
|
||||
git branch -d hotfix/security-patch
|
||||
git push origin main develop --tags
|
||||
```
|
||||
|
||||
**Best For:**
|
||||
- Scheduled releases
|
||||
- Multiple production versions
|
||||
- Large teams with QA process
|
||||
- Products with maintenance windows
|
||||
- Enterprise software
|
||||
|
||||
**Drawbacks:**
|
||||
- Complex workflow
|
||||
- Long-lived branches
|
||||
- Potential merge conflicts
|
||||
- Delayed integration
|
||||
|
||||
### GitHub Flow
|
||||
|
||||
**Branch Structure:**
|
||||
- `main` - Production-ready code (always deployable)
|
||||
- `feature/*` - All feature and fix branches
|
||||
|
||||
**Workflow:**
|
||||
|
||||
```bash
|
||||
# Create Feature Branch
|
||||
git checkout main
|
||||
git pull origin main
|
||||
git checkout -b feature/add-api-logging
|
||||
|
||||
# Develop Feature
|
||||
git commit -m "feat: add structured logging middleware"
|
||||
git push -u origin feature/add-api-logging
|
||||
|
||||
# Open Pull Request on GitHub
|
||||
# Review, discuss, CI passes
|
||||
|
||||
# Merge and Deploy
|
||||
# Merge PR on GitHub
|
||||
# Automatic deployment from main
|
||||
|
||||
# Cleanup
|
||||
git checkout main
|
||||
git pull origin main
|
||||
git branch -d feature/add-api-logging
|
||||
```
|
||||
|
||||
**Best For:**
|
||||
- Continuous deployment
|
||||
- Small to medium teams
|
||||
- Web applications
|
||||
- Rapid iteration
|
||||
- Cloud-native applications
|
||||
|
||||
**Drawbacks:**
|
||||
- Requires robust CI/CD
|
||||
- No release staging
|
||||
- Less structured than Git Flow
|
||||
|
||||
### Trunk-Based Development
|
||||
|
||||
**Branch Structure:**
|
||||
- `main` (or `trunk`) - Single source of truth
|
||||
- Short-lived feature branches (< 2 days, optional)
|
||||
- Feature flags for incomplete work
|
||||
|
||||
**Workflow:**
|
||||
|
||||
```bash
|
||||
# Direct Commit to Main (Small Changes)
|
||||
git checkout main
|
||||
git pull origin main
|
||||
# Make small change...
|
||||
git commit -m "fix: correct validation logic"
|
||||
git push origin main
|
||||
|
||||
# Short-Lived Branch (Larger Changes)
|
||||
git checkout -b optimize-query
|
||||
# Work for < 1 day
|
||||
git commit -m "perf: optimize database query"
|
||||
git push -u origin optimize-query
|
||||
# Immediate PR, quick review, merge same day
|
||||
|
||||
# Feature Flags for Incomplete Features
|
||||
git checkout main
|
||||
git commit -m "feat: add payment gateway (behind feature flag)"
|
||||
# Feature disabled in production until complete
|
||||
git push origin main
|
||||
```
|
||||
|
||||
**Best For:**
|
||||
- High-velocity teams
|
||||
- Continuous integration
|
||||
- Automated testing
|
||||
- Feature flag infrastructure
|
||||
- DevOps culture
|
||||
|
||||
**Drawbacks:**
|
||||
- Requires discipline
|
||||
- Needs comprehensive tests
|
||||
- Feature flag management
|
||||
- Higher deployment frequency
|
||||
|
||||
### Release Branch Strategy
|
||||
|
||||
**Branch Structure:**
|
||||
- `main` - Current development
|
||||
- `release/v*` - Long-lived release branches
|
||||
- `feature/*` - Feature branches
|
||||
|
||||
**Workflow:**
|
||||
|
||||
```bash
|
||||
# Create Release Branch
|
||||
git checkout -b release/v1.0 main
|
||||
git push -u origin release/v1.0
|
||||
|
||||
# Continue Development on Main
|
||||
git checkout main
|
||||
# Work on v2.0 features...
|
||||
|
||||
# Backport Fixes to Release
|
||||
git checkout release/v1.0
|
||||
git cherry-pick abc123 # Fix from main
|
||||
git push origin release/v1.0
|
||||
git tag -a v1.0.5 -m "Patch release v1.0.5"
|
||||
git push origin v1.0.5
|
||||
|
||||
# Multiple Release Maintenance
|
||||
git checkout release/v0.9
|
||||
git cherry-pick def456
|
||||
git tag -a v0.9.8 -m "Security patch v0.9.8"
|
||||
```
|
||||
|
||||
**Best For:**
|
||||
- Multiple product versions
|
||||
- Long-term support releases
|
||||
- Enterprise customers
|
||||
- Regulated industries
|
||||
|
||||
**Drawbacks:**
|
||||
- Maintenance overhead
|
||||
- Complex cherry-picking
|
||||
- Diverging codebases
|
||||
|
||||
### Feature Branch Workflow
|
||||
|
||||
**Branch Structure:**
|
||||
- `main` - Stable production code
|
||||
- `feature/*` - Feature branches from main
|
||||
- `bugfix/*` - Bug fix branches
|
||||
|
||||
**Workflow:**
|
||||
|
||||
```bash
|
||||
# Feature Development
|
||||
git checkout main
|
||||
git checkout -b feature/payment-integration
|
||||
|
||||
# Long-Running Feature (Sync with Main)
|
||||
git fetch origin
|
||||
git rebase origin/main
|
||||
# Or merge
|
||||
git merge origin/main
|
||||
|
||||
# Complete Feature
|
||||
git push origin feature/payment-integration
|
||||
# Create pull request
|
||||
# After review and approval, merge to main
|
||||
```
|
||||
|
||||
**Best For:**
|
||||
- Medium-sized teams
|
||||
- Code review processes
|
||||
- Parallel feature development
|
||||
- Quality gates before merge
|
||||
|
||||
## Repository Organization
|
||||
|
||||
### Monorepo
|
||||
|
||||
**Structure:**
|
||||
```
|
||||
monorepo/
|
||||
├── .git/
|
||||
├── services/
|
||||
│ ├── api/
|
||||
│ ├── web/
|
||||
│ └── worker/
|
||||
├── packages/
|
||||
│ ├── shared-utils/
|
||||
│ ├── ui-components/
|
||||
│ └── api-client/
|
||||
├── tools/
|
||||
│ ├── build-tools/
|
||||
│ └── scripts/
|
||||
└── docs/
|
||||
```
|
||||
|
||||
**Advantages:**
|
||||
- Single source of truth
|
||||
- Shared code visibility
|
||||
- Atomic cross-project changes
|
||||
- Unified versioning
|
||||
- Simplified dependency management
|
||||
- Consistent tooling
|
||||
|
||||
**Disadvantages:**
|
||||
- Large repository size
|
||||
- Slower clone/fetch
|
||||
- Complex CI/CD
|
||||
- Access control challenges
|
||||
- Tooling requirements
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```bash
|
||||
# Initialize Monorepo
|
||||
git init
|
||||
mkdir -p services/api services/web packages/shared-utils
|
||||
|
||||
# Workspace Setup (Node.js example)
|
||||
cat > package.json << EOF
|
||||
{
|
||||
"name": "monorepo",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"services/*",
|
||||
"packages/*"
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
# Sparse Checkout (Partial Clone)
|
||||
git clone --filter=blob:none --no-checkout <url>
|
||||
cd repo
|
||||
git sparse-checkout init --cone
|
||||
git sparse-checkout set services/api packages/shared-utils
|
||||
git checkout main
|
||||
|
||||
# Build Only Changed Packages
|
||||
git diff --name-only HEAD~1 | grep "^services/api" && cd services/api && npm run build
|
||||
```
|
||||
|
||||
**Tools:**
|
||||
- **Bazel** - Build system for large monorepos
|
||||
- **Nx** - Monorepo build system (Node.js)
|
||||
- **Lerna** - JavaScript monorepo management
|
||||
- **Turborepo** - High-performance build system
|
||||
- **Git-subtree** - Merge external repositories
|
||||
|
||||
### Polyrepo
|
||||
|
||||
**Structure:**
|
||||
```
|
||||
organization/
|
||||
├── api-service/ (separate repo)
|
||||
├── web-app/ (separate repo)
|
||||
├── mobile-app/ (separate repo)
|
||||
├── shared-utils/ (separate repo)
|
||||
└── documentation/ (separate repo)
|
||||
```
|
||||
|
||||
**Advantages:**
|
||||
- Clear ownership boundaries
|
||||
- Independent versioning
|
||||
- Smaller repository size
|
||||
- Granular access control
|
||||
- Flexible CI/CD
|
||||
- Team autonomy
|
||||
|
||||
**Disadvantages:**
|
||||
- Dependency version conflicts
|
||||
- Cross-repo changes are complex
|
||||
- Duplicated tooling/config
|
||||
- Harder to refactor across repos
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```bash
|
||||
# Template Repository
|
||||
git clone git@github.com:org/template-service.git new-service
|
||||
cd new-service
|
||||
rm -rf .git
|
||||
git init
|
||||
git remote add origin git@github.com:org/new-service.git
|
||||
|
||||
# Shared Configuration
|
||||
# Use git submodules or packages
|
||||
git submodule add git@github.com:org/shared-config.git config
|
||||
```
|
||||
|
||||
### Monorepo vs Polyrepo Decision Matrix
|
||||
|
||||
| Factor | Monorepo | Polyrepo |
|
||||
|--------|----------|----------|
|
||||
| Team Size | Large teams | Small, autonomous teams |
|
||||
| Code Sharing | High code reuse | Limited sharing |
|
||||
| Deployment | Coordinated releases | Independent deployments |
|
||||
| Access Control | Coarse-grained | Fine-grained |
|
||||
| Repository Size | Very large | Small to medium |
|
||||
| CI/CD Complexity | High | Low to medium |
|
||||
| Tooling Requirements | Specialized tools | Standard git tools |
|
||||
| Refactoring | Easy cross-project | Complex cross-repo |
|
||||
|
||||
## Submodule Management
|
||||
|
||||
### Basic Submodules
|
||||
|
||||
```bash
|
||||
# Add Submodule
|
||||
git submodule add https://github.com/org/shared-lib.git libs/shared
|
||||
|
||||
# Clone with Submodules
|
||||
git clone --recurse-submodules <url>
|
||||
|
||||
# Initialize After Clone
|
||||
git submodule init
|
||||
git submodule update
|
||||
|
||||
# Update Submodule
|
||||
cd libs/shared
|
||||
git pull origin main
|
||||
cd ../..
|
||||
git add libs/shared
|
||||
git commit -m "chore: update shared library"
|
||||
|
||||
# Update All Submodules
|
||||
git submodule update --remote --merge
|
||||
|
||||
# Remove Submodule
|
||||
git submodule deinit libs/shared
|
||||
git rm libs/shared
|
||||
rm -rf .git/modules/libs/shared
|
||||
```
|
||||
|
||||
### Submodule Strategies
|
||||
|
||||
**Pinned Version Strategy:**
|
||||
```bash
|
||||
# Submodule points to specific commit
|
||||
# Manual updates with testing
|
||||
git submodule update --remote libs/shared
|
||||
# Test changes...
|
||||
git add libs/shared
|
||||
git commit -m "chore: update shared-lib to v1.2.3"
|
||||
```
|
||||
|
||||
**Auto-Update Strategy:**
|
||||
```bash
|
||||
# CI automatically updates submodules
|
||||
# .github/workflows/update-submodules.yml
|
||||
name: Update Submodules
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 * * 0' # Weekly
|
||||
jobs:
|
||||
update:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: true
|
||||
- run: git submodule update --remote
|
||||
- run: git commit -am "chore: update submodules"
|
||||
- run: git push
|
||||
```
|
||||
|
||||
### Nested Submodules
|
||||
|
||||
```bash
|
||||
# Add Nested Submodule
|
||||
cd libs/framework
|
||||
git submodule add https://github.com/org/utils.git utils
|
||||
|
||||
# Update Recursively
|
||||
git submodule update --init --recursive
|
||||
|
||||
# Run Command in All Submodules
|
||||
git submodule foreach 'git checkout main'
|
||||
git submodule foreach 'git pull'
|
||||
git submodule foreach --recursive 'echo $name: $(git rev-parse HEAD)'
|
||||
```
|
||||
|
||||
## Subtree Management
|
||||
|
||||
### Git Subtree vs Submodule
|
||||
|
||||
**Subtree Advantages:**
|
||||
- Simpler for contributors
|
||||
- No separate clone steps
|
||||
- Part of main repository history
|
||||
- No broken references
|
||||
|
||||
**Subtree Disadvantages:**
|
||||
- More complex to update
|
||||
- Pollutes main history
|
||||
- Larger repository
|
||||
|
||||
### Subtree Operations
|
||||
|
||||
```bash
|
||||
# Add Subtree
|
||||
git subtree add --prefix=libs/shared https://github.com/org/shared.git main --squash
|
||||
|
||||
# Update Subtree
|
||||
git subtree pull --prefix=libs/shared https://github.com/org/shared.git main --squash
|
||||
|
||||
# Push Changes Back to Subtree
|
||||
git subtree push --prefix=libs/shared https://github.com/org/shared.git feature-branch
|
||||
|
||||
# Split Subtree (Extract to New Repo)
|
||||
git subtree split --prefix=libs/shared -b shared-lib-branch
|
||||
git push git@github.com:org/new-shared-lib.git shared-lib-branch:main
|
||||
```
|
||||
|
||||
### Subtree Workflow
|
||||
|
||||
```bash
|
||||
# Setup Remote for Easier Management
|
||||
git remote add shared-lib https://github.com/org/shared.git
|
||||
|
||||
# Add Subtree with Remote
|
||||
git subtree add --prefix=libs/shared shared-lib main --squash
|
||||
|
||||
# Pull Updates
|
||||
git fetch shared-lib
|
||||
git subtree pull --prefix=libs/shared shared-lib main --squash
|
||||
|
||||
# Contribute Back
|
||||
git subtree push --prefix=libs/shared shared-lib feature-branch
|
||||
```
|
||||
|
||||
## Repository Templates
|
||||
|
||||
### GitHub Template Repository
|
||||
|
||||
```bash
|
||||
# Create Template Structure
|
||||
mkdir -p .github/workflows
|
||||
cat > .github/workflows/ci.yml << EOF
|
||||
name: CI
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- run: make test
|
||||
EOF
|
||||
|
||||
# Template Files
|
||||
touch .gitignore README.md LICENSE CONTRIBUTING.md
|
||||
mkdir -p docs src tests
|
||||
|
||||
# Mark as Template on GitHub Settings
|
||||
# Use template to create new repositories
|
||||
```
|
||||
|
||||
### Cookiecutter Template
|
||||
|
||||
```bash
|
||||
# Install Cookiecutter
|
||||
pip install cookiecutter
|
||||
|
||||
# Create from Template
|
||||
cookiecutter https://github.com/org/project-template.git
|
||||
|
||||
# Template Structure
|
||||
project-template/
|
||||
├── cookiecutter.json
|
||||
└── {{cookiecutter.project_name}}/
|
||||
├── .git/
|
||||
├── src/
|
||||
├── tests/
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## Large Repository Management
|
||||
|
||||
### Partial Clone
|
||||
|
||||
```bash
|
||||
# Blobless Clone (No file contents initially)
|
||||
git clone --filter=blob:none <url>
|
||||
|
||||
# Treeless Clone (Even more minimal)
|
||||
git clone --filter=tree:0 <url>
|
||||
|
||||
# Shallow Clone (Limited History)
|
||||
git clone --depth 1 <url>
|
||||
|
||||
# Shallow Clone with Single Branch
|
||||
git clone --depth 1 --single-branch --branch main <url>
|
||||
```
|
||||
|
||||
### Sparse Checkout
|
||||
|
||||
```bash
|
||||
# Enable Sparse Checkout
|
||||
git sparse-checkout init --cone
|
||||
|
||||
# Specify Directories
|
||||
git sparse-checkout set src/api src/shared
|
||||
|
||||
# Add More Directories
|
||||
git sparse-checkout add docs
|
||||
|
||||
# List Current Sparse Checkout
|
||||
git sparse-checkout list
|
||||
|
||||
# Disable Sparse Checkout
|
||||
git sparse-checkout disable
|
||||
```
|
||||
|
||||
### Git LFS (Large File Storage)
|
||||
|
||||
```bash
|
||||
# Install Git LFS
|
||||
git lfs install
|
||||
|
||||
# Track Large Files
|
||||
git lfs track "*.psd"
|
||||
git lfs track "*.zip"
|
||||
git lfs track "data/**"
|
||||
|
||||
# Track Files in .gitattributes
|
||||
cat .gitattributes
|
||||
# *.psd filter=lfs diff=lfs merge=lfs -text
|
||||
|
||||
# Clone with LFS
|
||||
git clone <url>
|
||||
cd repo
|
||||
git lfs pull
|
||||
|
||||
# Migrate Existing Files to LFS
|
||||
git lfs migrate import --include="*.zip"
|
||||
```
|
||||
|
||||
## Repository Splitting
|
||||
|
||||
### Extract Subdirectory to New Repo
|
||||
|
||||
```bash
|
||||
# Using git filter-repo (recommended)
|
||||
git filter-repo --path services/api --path-rename services/api:
|
||||
|
||||
# Result: New repo with only services/api content and history
|
||||
|
||||
# Using git subtree
|
||||
git subtree split --prefix=services/api -b api-service
|
||||
mkdir ../api-service
|
||||
cd ../api-service
|
||||
git init
|
||||
git pull ../original-repo api-service
|
||||
```
|
||||
|
||||
### Merge Multiple Repos
|
||||
|
||||
```bash
|
||||
# Add Remote
|
||||
git remote add project-b ../project-b
|
||||
|
||||
# Fetch History
|
||||
git fetch project-b
|
||||
|
||||
# Merge with Unrelated Histories
|
||||
git merge --allow-unrelated-histories project-b/main
|
||||
|
||||
# Move Files to Subdirectory
|
||||
mkdir project-b
|
||||
git mv * project-b/
|
||||
git commit -m "chore: organize project-b into subdirectory"
|
||||
```
|
||||
|
||||
## Repository Maintenance
|
||||
|
||||
### Regular Maintenance Tasks
|
||||
|
||||
```bash
|
||||
# Optimize Repository
|
||||
git gc --aggressive
|
||||
|
||||
# Prune Unreachable Objects
|
||||
git prune --expire now
|
||||
|
||||
# Verify Integrity
|
||||
git fsck --full
|
||||
|
||||
# Repack Repository
|
||||
git repack -a -d --depth=250 --window=250
|
||||
|
||||
# Update Server Info (for dumb HTTP)
|
||||
git update-server-info
|
||||
```
|
||||
|
||||
### Automation Script
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# repo-maintenance.sh
|
||||
|
||||
echo "Starting repository maintenance..."
|
||||
|
||||
# Fetch all branches
|
||||
git fetch --all --prune
|
||||
|
||||
# Clean up stale branches
|
||||
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D
|
||||
|
||||
# Garbage collection
|
||||
git gc --auto
|
||||
|
||||
# Verify integrity
|
||||
git fsck --full --strict
|
||||
|
||||
echo "Maintenance complete!"
|
||||
```
|
||||
|
||||
### Scheduled Maintenance
|
||||
|
||||
```yaml
|
||||
# .github/workflows/maintenance.yml
|
||||
name: Repository Maintenance
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * 0' # Weekly at 2 AM Sunday
|
||||
jobs:
|
||||
maintain:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Run Maintenance
|
||||
run: |
|
||||
git gc --aggressive
|
||||
git prune --expire now
|
||||
git fsck --full
|
||||
```
|
||||
|
||||
## Access Control and Permissions
|
||||
|
||||
### Branch Protection Rules
|
||||
|
||||
```yaml
|
||||
# Example Configuration
|
||||
protected_branches:
|
||||
main:
|
||||
required_pull_request_reviews:
|
||||
required_approving_review_count: 2
|
||||
dismiss_stale_reviews: true
|
||||
require_code_owner_reviews: true
|
||||
required_status_checks:
|
||||
strict: true
|
||||
contexts:
|
||||
- continuous-integration
|
||||
- security-scan
|
||||
enforce_admins: true
|
||||
restrictions:
|
||||
users: []
|
||||
teams: [core-team]
|
||||
```
|
||||
|
||||
### CODEOWNERS File
|
||||
|
||||
```bash
|
||||
# .github/CODEOWNERS
|
||||
|
||||
# Global owners
|
||||
* @org/core-team
|
||||
|
||||
# Service owners
|
||||
/services/api/ @org/backend-team
|
||||
/services/web/ @org/frontend-team
|
||||
/services/mobile/ @org/mobile-team
|
||||
|
||||
# Specific files
|
||||
/docs/ @org/documentation-team
|
||||
/.github/ @org/devops-team
|
||||
/security/ @org/security-team @org/lead-architect
|
||||
|
||||
# Require multiple reviews
|
||||
/packages/shared/ @org/core-team @org/architecture-team
|
||||
```
|
||||
|
||||
## Migration Strategies
|
||||
|
||||
### SVN to Git
|
||||
|
||||
```bash
|
||||
# Create Authors File
|
||||
svn log --quiet | grep "^r" | awk '{print $3}' | sort -u > authors.txt
|
||||
|
||||
# Edit authors.txt:
|
||||
# john = John Doe <john@example.com>
|
||||
|
||||
# Convert Repository
|
||||
git svn clone <svn-url> --authors-file=authors.txt --stdlayout repo
|
||||
|
||||
# Convert Tags and Branches
|
||||
cd repo
|
||||
git for-each-ref --format="%(refname:short)" refs/remotes/tags | \
|
||||
cut -d / -f 3 | xargs -I {} git tag {} refs/remotes/tags/{}
|
||||
|
||||
# Push to Git
|
||||
git remote add origin <git-url>
|
||||
git push -u origin --all
|
||||
git push origin --tags
|
||||
```
|
||||
|
||||
### Mercurial to Git
|
||||
|
||||
```bash
|
||||
# Using hg-git
|
||||
hg bookmark -r default main
|
||||
hg push git+ssh://git@github.com/org/repo.git
|
||||
|
||||
# Using fast-export
|
||||
git clone https://github.com/frej/fast-export.git
|
||||
mkdir git-repo && cd git-repo
|
||||
git init
|
||||
../fast-export/hg-fast-export.sh -r ../hg-repo
|
||||
git checkout HEAD
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Choose Appropriate Strategy:** Match branching model to team size and deployment frequency
|
||||
2. **Document Workflows:** Keep team documentation current
|
||||
3. **Automate Maintenance:** Regular repository health checks
|
||||
4. **Use Branch Protection:** Enforce code review and CI
|
||||
5. **Clear Ownership:** Define code owners for all areas
|
||||
6. **Regular Cleanup:** Remove stale branches and merged features
|
||||
7. **Monitor Repository Size:** Use LFS for large files
|
||||
8. **Template Repositories:** Standardize new project structure
|
||||
9. **Access Control:** Implement principle of least privilege
|
||||
10. **Migration Planning:** Test migrations thoroughly before production
|
||||
|
||||
## Resources
|
||||
|
||||
Additional repository management resources are available in the `assets/` directory:
|
||||
- `templates/` - Repository structure templates
|
||||
- `scripts/` - Automation and maintenance scripts
|
||||
- `workflows/` - CI/CD workflow examples
|
||||
|
||||
See `references/` directory for:
|
||||
- Branching strategy comparison guides
|
||||
- Monorepo tool documentation
|
||||
- Enterprise git patterns
|
||||
- Repository scaling strategies
|
||||
819
skills/git-troubleshooting/SKILL.md
Normal file
819
skills/git-troubleshooting/SKILL.md
Normal file
@@ -0,0 +1,819 @@
|
||||
---
|
||||
name: git-troubleshooting
|
||||
description: Git troubleshooting techniques including recovering lost commits, fixing merge conflicts, resolving detached HEAD, and diagnosing repository issues. Use when user encounters git errors or needs to recover from mistakes.
|
||||
---
|
||||
|
||||
# Git Troubleshooting Skill
|
||||
|
||||
This skill provides comprehensive guidance on diagnosing and resolving git issues, recovering from mistakes, fixing corrupted repositories, and handling common error scenarios.
|
||||
|
||||
## When to Use
|
||||
|
||||
Activate this skill when:
|
||||
- Encountering git error messages
|
||||
- Recovering lost commits or branches
|
||||
- Fixing corrupted repositories
|
||||
- Resolving detached HEAD state
|
||||
- Handling botched merges or rebases
|
||||
- Diagnosing repository issues
|
||||
- Recovering from force push
|
||||
- Fixing authentication problems
|
||||
|
||||
## Recovering Lost Commits
|
||||
|
||||
### Using Reflog
|
||||
|
||||
```bash
|
||||
# View reflog (local history of HEAD)
|
||||
git reflog
|
||||
|
||||
# View reflog for specific branch
|
||||
git reflog show branch-name
|
||||
|
||||
# Output example:
|
||||
# abc123 HEAD@{0}: commit: feat: add authentication
|
||||
# def456 HEAD@{1}: commit: fix: resolve bug
|
||||
# ghi789 HEAD@{2}: reset: moving to HEAD~1
|
||||
|
||||
# Recover lost commit
|
||||
git cherry-pick abc123
|
||||
|
||||
# Or create branch from lost commit
|
||||
git branch recovered-branch abc123
|
||||
|
||||
# Or reset to lost commit
|
||||
git reset --hard abc123
|
||||
```
|
||||
|
||||
### Finding Dangling Commits
|
||||
|
||||
```bash
|
||||
# Find all unreachable objects
|
||||
git fsck --lost-found
|
||||
|
||||
# Output:
|
||||
# dangling commit abc123
|
||||
# dangling blob def456
|
||||
|
||||
# View dangling commit
|
||||
git show abc123
|
||||
|
||||
# Recover dangling commit
|
||||
git branch recovered abc123
|
||||
|
||||
# Or merge it
|
||||
git merge abc123
|
||||
```
|
||||
|
||||
### Recovering Deleted Branch
|
||||
|
||||
```bash
|
||||
# Find branch commit in reflog
|
||||
git reflog
|
||||
|
||||
# Look for branch deletion:
|
||||
# abc123 HEAD@{5}: checkout: moving from feature-branch to main
|
||||
|
||||
# Recreate branch
|
||||
git branch feature-branch abc123
|
||||
|
||||
# Or if branch was merged before deletion
|
||||
git log --all --oneline | grep "feature"
|
||||
git branch feature-branch def456
|
||||
```
|
||||
|
||||
### Recovering After Reset
|
||||
|
||||
```bash
|
||||
# After accidental reset --hard
|
||||
git reflog
|
||||
|
||||
# Find commit before reset:
|
||||
# abc123 HEAD@{0}: reset: moving to HEAD~5
|
||||
# def456 HEAD@{1}: commit: last good commit
|
||||
|
||||
# Restore to previous state
|
||||
git reset --hard def456
|
||||
|
||||
# Or create recovery branch
|
||||
git branch recovery def456
|
||||
```
|
||||
|
||||
## Resolving Detached HEAD
|
||||
|
||||
### Understanding Detached HEAD
|
||||
|
||||
```bash
|
||||
# Detached HEAD state occurs when:
|
||||
git checkout abc123
|
||||
git checkout v1.0.0
|
||||
git checkout origin/main
|
||||
|
||||
# HEAD is not attached to any branch
|
||||
```
|
||||
|
||||
### Recovering from Detached HEAD
|
||||
|
||||
```bash
|
||||
# Check current state
|
||||
git status
|
||||
# HEAD detached at abc123
|
||||
|
||||
# Option 1: Create new branch
|
||||
git checkout -b new-branch-name
|
||||
|
||||
# Option 2: Return to previous branch
|
||||
git checkout main
|
||||
|
||||
# Option 3: Reattach HEAD to branch
|
||||
git checkout -b temp-branch
|
||||
git checkout main
|
||||
git merge temp-branch
|
||||
|
||||
# If you made commits in detached HEAD:
|
||||
git reflog
|
||||
# Find the commits
|
||||
git branch recovery-branch abc123
|
||||
```
|
||||
|
||||
### Preventing Detached HEAD
|
||||
|
||||
```bash
|
||||
# Instead of checking out tag directly
|
||||
git checkout -b release-v1.0 v1.0.0
|
||||
|
||||
# Instead of checking out remote branch
|
||||
git checkout -b local-feature origin/feature-branch
|
||||
|
||||
# Check if HEAD is detached
|
||||
git symbolic-ref -q HEAD && echo "attached" || echo "detached"
|
||||
```
|
||||
|
||||
## Fixing Merge Conflicts
|
||||
|
||||
### Understanding Conflict Markers
|
||||
|
||||
```
|
||||
<<<<<<< HEAD (Current Change)
|
||||
int result = add(a, b);
|
||||
||||||| merged common ancestors (Base)
|
||||
int result = sum(a, b);
|
||||
=======
|
||||
int sum = calculate(a, b);
|
||||
>>>>>>> feature-branch (Incoming Change)
|
||||
```
|
||||
|
||||
### Basic Conflict Resolution
|
||||
|
||||
```bash
|
||||
# When merge conflict occurs
|
||||
git status
|
||||
# both modified: file.go
|
||||
|
||||
# View conflict
|
||||
cat file.go
|
||||
|
||||
# Option 1: Keep ours (current branch)
|
||||
git checkout --ours file.go
|
||||
git add file.go
|
||||
|
||||
# Option 2: Keep theirs (incoming branch)
|
||||
git checkout --theirs file.go
|
||||
git add file.go
|
||||
|
||||
# Option 3: Manual resolution
|
||||
# Edit file.go to resolve conflicts
|
||||
git add file.go
|
||||
|
||||
# Complete merge
|
||||
git commit
|
||||
```
|
||||
|
||||
### Aborting Operations
|
||||
|
||||
```bash
|
||||
# Abort merge
|
||||
git merge --abort
|
||||
|
||||
# Abort rebase
|
||||
git rebase --abort
|
||||
|
||||
# Abort cherry-pick
|
||||
git cherry-pick --abort
|
||||
|
||||
# Abort revert
|
||||
git revert --abort
|
||||
|
||||
# Abort am (apply mailbox)
|
||||
git am --abort
|
||||
```
|
||||
|
||||
### Complex Conflict Resolution
|
||||
|
||||
```bash
|
||||
# Use merge tool
|
||||
git mergetool
|
||||
|
||||
# View three-way diff
|
||||
git diff --ours
|
||||
git diff --theirs
|
||||
git diff --base
|
||||
|
||||
# Show conflicts with context
|
||||
git diff --check
|
||||
|
||||
# List conflicted files
|
||||
git diff --name-only --diff-filter=U
|
||||
|
||||
# After resolving all conflicts
|
||||
git add .
|
||||
git commit
|
||||
```
|
||||
|
||||
## Fixing Botched Rebase
|
||||
|
||||
### Recovering from Failed Rebase
|
||||
|
||||
```bash
|
||||
# Abort current rebase
|
||||
git rebase --abort
|
||||
|
||||
# Find state before rebase
|
||||
git reflog
|
||||
# abc123 HEAD@{1}: rebase: checkout main
|
||||
|
||||
# Return to pre-rebase state
|
||||
git reset --hard HEAD@{1}
|
||||
|
||||
# Alternative: use ORIG_HEAD
|
||||
git reset --hard ORIG_HEAD
|
||||
```
|
||||
|
||||
### Rebase Conflicts
|
||||
|
||||
```bash
|
||||
# During rebase conflict
|
||||
git status
|
||||
# both modified: file.go
|
||||
|
||||
# Resolve conflicts
|
||||
# Edit file.go
|
||||
git add file.go
|
||||
git rebase --continue
|
||||
|
||||
# Skip problematic commit
|
||||
git rebase --skip
|
||||
|
||||
# Edit commit during rebase
|
||||
git commit --amend
|
||||
git rebase --continue
|
||||
```
|
||||
|
||||
### Rebase onto Wrong Branch
|
||||
|
||||
```bash
|
||||
# Find original branch point
|
||||
git reflog
|
||||
|
||||
# Reset to before rebase
|
||||
git reset --hard HEAD@{5}
|
||||
|
||||
# Rebase onto correct branch
|
||||
git rebase correct-branch
|
||||
```
|
||||
|
||||
## Repository Corruption
|
||||
|
||||
### Detecting Corruption
|
||||
|
||||
```bash
|
||||
# Check repository integrity
|
||||
git fsck --full
|
||||
|
||||
# Check connectivity
|
||||
git fsck --connectivity-only
|
||||
|
||||
# Verify pack files
|
||||
git verify-pack -v .git/objects/pack/*.idx
|
||||
```
|
||||
|
||||
### Fixing Corrupted Objects
|
||||
|
||||
```bash
|
||||
# Remove corrupted object
|
||||
rm .git/objects/ab/cd1234...
|
||||
|
||||
# Try to recover from remote
|
||||
git fetch origin
|
||||
|
||||
# Rebuild object database
|
||||
git gc --prune=now
|
||||
|
||||
# Aggressive cleanup
|
||||
git gc --aggressive --prune=now
|
||||
```
|
||||
|
||||
### Fixing Index Corruption
|
||||
|
||||
```bash
|
||||
# Remove corrupted index
|
||||
rm .git/index
|
||||
|
||||
# Rebuild index
|
||||
git reset
|
||||
|
||||
# Or reset to HEAD
|
||||
git reset --hard HEAD
|
||||
```
|
||||
|
||||
### Recovering from Bad Pack File
|
||||
|
||||
```bash
|
||||
# Unpack corrupted pack
|
||||
git unpack-objects < .git/objects/pack/pack-*.pack
|
||||
|
||||
# Remove corrupted pack
|
||||
rm .git/objects/pack/pack-*
|
||||
|
||||
# Repack repository
|
||||
git repack -a -d
|
||||
|
||||
# Verify integrity
|
||||
git fsck --full
|
||||
```
|
||||
|
||||
## Fixing References
|
||||
|
||||
### Corrupted Branch References
|
||||
|
||||
```bash
|
||||
# View all references
|
||||
git show-ref
|
||||
|
||||
# Manual reference fix
|
||||
echo "abc123def456" > .git/refs/heads/branch-name
|
||||
|
||||
# Or use update-ref
|
||||
git update-ref refs/heads/branch-name abc123
|
||||
|
||||
# Delete corrupted reference
|
||||
git update-ref -d refs/heads/bad-branch
|
||||
```
|
||||
|
||||
### Fixing HEAD Reference
|
||||
|
||||
```bash
|
||||
# HEAD is corrupted or missing
|
||||
echo "ref: refs/heads/main" > .git/HEAD
|
||||
|
||||
# Or point to specific commit
|
||||
echo "abc123def456" > .git/HEAD
|
||||
|
||||
# Verify HEAD
|
||||
git symbolic-ref HEAD
|
||||
```
|
||||
|
||||
### Pruning Stale References
|
||||
|
||||
```bash
|
||||
# Remove stale remote references
|
||||
git remote prune origin
|
||||
|
||||
# Remove all stale references
|
||||
git fetch --prune
|
||||
|
||||
# Remove all remote branches that no longer exist
|
||||
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D
|
||||
```
|
||||
|
||||
## Undoing Changes
|
||||
|
||||
### Undo Last Commit (Keep Changes)
|
||||
|
||||
```bash
|
||||
# Soft reset (changes staged)
|
||||
git reset --soft HEAD~1
|
||||
|
||||
# Mixed reset (changes unstaged)
|
||||
git reset HEAD~1
|
||||
```
|
||||
|
||||
### Undo Last Commit (Discard Changes)
|
||||
|
||||
```bash
|
||||
# Hard reset
|
||||
git reset --hard HEAD~1
|
||||
|
||||
# Can still recover via reflog
|
||||
git reflog
|
||||
git reset --hard HEAD@{1}
|
||||
```
|
||||
|
||||
### Undo Multiple Commits
|
||||
|
||||
```bash
|
||||
# Reset to specific commit
|
||||
git reset --hard abc123
|
||||
|
||||
# Revert multiple commits (creates new commits)
|
||||
git revert HEAD~3..HEAD
|
||||
|
||||
# Interactive rebase to remove commits
|
||||
git rebase -i HEAD~5
|
||||
# Mark commits with 'drop' or delete lines
|
||||
```
|
||||
|
||||
### Undo Changes to File
|
||||
|
||||
```bash
|
||||
# Discard uncommitted changes
|
||||
git checkout -- file.go
|
||||
|
||||
# Or in Git 2.23+
|
||||
git restore file.go
|
||||
|
||||
# Discard staged changes
|
||||
git reset HEAD file.go
|
||||
git restore file.go
|
||||
|
||||
# Or in Git 2.23+
|
||||
git restore --staged file.go
|
||||
git restore file.go
|
||||
|
||||
# Restore file from specific commit
|
||||
git checkout abc123 -- file.go
|
||||
```
|
||||
|
||||
### Undo Public Commits
|
||||
|
||||
```bash
|
||||
# Never use reset on public commits
|
||||
# Use revert instead
|
||||
git revert HEAD
|
||||
git revert abc123
|
||||
git revert abc123..def456
|
||||
|
||||
# Revert merge commit
|
||||
git revert -m 1 merge-commit-hash
|
||||
```
|
||||
|
||||
## Handling Force Push Issues
|
||||
|
||||
### Recovering After Force Push
|
||||
|
||||
```bash
|
||||
# If you were force pushed over
|
||||
git reflog
|
||||
# abc123 HEAD@{1}: pull: Fast-forward
|
||||
|
||||
# Recover your commits
|
||||
git reset --hard HEAD@{1}
|
||||
|
||||
# Create backup branch
|
||||
git branch backup-branch
|
||||
|
||||
# Merge with force-pushed branch
|
||||
git pull origin main
|
||||
git merge backup-branch
|
||||
```
|
||||
|
||||
### Preventing Force Push Damage
|
||||
|
||||
```bash
|
||||
# Always fetch before force push
|
||||
git fetch origin
|
||||
|
||||
# View what would be lost
|
||||
git log origin/main..HEAD
|
||||
|
||||
# Force push with lease (safer)
|
||||
git push --force-with-lease origin main
|
||||
|
||||
# Configure push protection
|
||||
git config --global push.default simple
|
||||
```
|
||||
|
||||
## Large File Issues
|
||||
|
||||
### Finding Large Files
|
||||
|
||||
```bash
|
||||
# Find large files in history
|
||||
git rev-list --objects --all | \
|
||||
git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | \
|
||||
awk '/^blob/ {print substr($0,6)}' | \
|
||||
sort --numeric-sort --key=2 | \
|
||||
tail -10
|
||||
|
||||
# Verify current large files
|
||||
git ls-files | xargs ls -lh | sort -k 5 -h -r | head -20
|
||||
```
|
||||
|
||||
### Removing Large Files
|
||||
|
||||
```bash
|
||||
# Using git-filter-repo (recommended)
|
||||
git filter-repo --path large-file.bin --invert-paths
|
||||
|
||||
# Using BFG
|
||||
bfg --strip-blobs-bigger-than 100M
|
||||
|
||||
# After removal
|
||||
git reflog expire --expire=now --all
|
||||
git gc --prune=now --aggressive
|
||||
git push --force origin main
|
||||
```
|
||||
|
||||
### Preventing Large Files
|
||||
|
||||
```bash
|
||||
# Configure pre-commit hook
|
||||
cat > .git/hooks/pre-commit << 'EOF'
|
||||
#!/bin/bash
|
||||
if git diff --cached --name-only | xargs du -h | awk '$1 ~ /M$|G$/' | grep .; then
|
||||
echo "Error: Large file detected"
|
||||
exit 1
|
||||
fi
|
||||
EOF
|
||||
|
||||
chmod +x .git/hooks/pre-commit
|
||||
```
|
||||
|
||||
## Authentication Issues
|
||||
|
||||
### SSH Key Problems
|
||||
|
||||
```bash
|
||||
# Test SSH connection
|
||||
ssh -T git@github.com
|
||||
|
||||
# Check SSH key
|
||||
ls -la ~/.ssh
|
||||
|
||||
# Generate new SSH key
|
||||
ssh-keygen -t ed25519 -C "email@example.com"
|
||||
|
||||
# Add key to ssh-agent
|
||||
eval "$(ssh-agent -s)"
|
||||
ssh-add ~/.ssh/id_ed25519
|
||||
|
||||
# Configure SSH
|
||||
cat > ~/.ssh/config << EOF
|
||||
Host github.com
|
||||
HostName github.com
|
||||
User git
|
||||
IdentityFile ~/.ssh/id_ed25519
|
||||
EOF
|
||||
```
|
||||
|
||||
### HTTPS Authentication
|
||||
|
||||
```bash
|
||||
# Cache credentials
|
||||
git config --global credential.helper cache
|
||||
git config --global credential.helper 'cache --timeout=3600'
|
||||
|
||||
# Or use store (less secure)
|
||||
git config --global credential.helper store
|
||||
|
||||
# Update remote URL
|
||||
git remote set-url origin https://github.com/user/repo.git
|
||||
|
||||
# Use personal access token
|
||||
git clone https://TOKEN@github.com/user/repo.git
|
||||
```
|
||||
|
||||
### Permission Denied
|
||||
|
||||
```bash
|
||||
# Check remote URL
|
||||
git remote -v
|
||||
|
||||
# Change to SSH
|
||||
git remote set-url origin git@github.com:user/repo.git
|
||||
|
||||
# Change to HTTPS
|
||||
git remote set-url origin https://github.com/user/repo.git
|
||||
|
||||
# Verify permissions
|
||||
ls -la .git/
|
||||
chmod -R u+rw .git/
|
||||
```
|
||||
|
||||
## Submodule Issues
|
||||
|
||||
### Submodule Not Initialized
|
||||
|
||||
```bash
|
||||
# Initialize submodules
|
||||
git submodule init
|
||||
git submodule update
|
||||
|
||||
# Or in one command
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
### Detached HEAD in Submodule
|
||||
|
||||
```bash
|
||||
# Enter submodule
|
||||
cd submodule-dir
|
||||
|
||||
# Create branch
|
||||
git checkout -b main
|
||||
|
||||
# Or attach to existing branch
|
||||
git checkout main
|
||||
git pull origin main
|
||||
|
||||
# Update parent repo
|
||||
cd ..
|
||||
git add submodule-dir
|
||||
git commit -m "chore: update submodule"
|
||||
```
|
||||
|
||||
### Submodule Conflicts
|
||||
|
||||
```bash
|
||||
# Check submodule status
|
||||
git submodule status
|
||||
|
||||
# Reset submodule
|
||||
git submodule update --init --force
|
||||
|
||||
# Remove and re-add submodule
|
||||
git submodule deinit -f path/to/submodule
|
||||
git rm -f path/to/submodule
|
||||
git submodule add <url> path/to/submodule
|
||||
```
|
||||
|
||||
## Performance Issues
|
||||
|
||||
### Slow Operations
|
||||
|
||||
```bash
|
||||
# Optimize repository
|
||||
git gc --aggressive
|
||||
|
||||
# Repack efficiently
|
||||
git repack -a -d --depth=250 --window=250
|
||||
|
||||
# Prune old objects
|
||||
git prune --expire now
|
||||
|
||||
# Clean up unnecessary files
|
||||
git clean -fdx
|
||||
```
|
||||
|
||||
### Large Repository
|
||||
|
||||
```bash
|
||||
# Shallow clone
|
||||
git clone --depth 1 <url>
|
||||
|
||||
# Fetch only one branch
|
||||
git clone --single-branch --branch main <url>
|
||||
|
||||
# Partial clone
|
||||
git clone --filter=blob:none <url>
|
||||
|
||||
# Sparse checkout
|
||||
git sparse-checkout init --cone
|
||||
git sparse-checkout set folder1 folder2
|
||||
```
|
||||
|
||||
### Memory Issues
|
||||
|
||||
```bash
|
||||
# Increase memory limits
|
||||
git config --global pack.windowMemory "100m"
|
||||
git config --global pack.packSizeLimit "100m"
|
||||
git config --global pack.threads "1"
|
||||
|
||||
# Disable delta compression temporarily
|
||||
git config --global pack.compression 0
|
||||
```
|
||||
|
||||
## Common Error Messages
|
||||
|
||||
### "fatal: refusing to merge unrelated histories"
|
||||
|
||||
```bash
|
||||
# Allow merging unrelated histories
|
||||
git pull origin main --allow-unrelated-histories
|
||||
```
|
||||
|
||||
### "fatal: not a git repository"
|
||||
|
||||
```bash
|
||||
# Reinitialize repository
|
||||
git init
|
||||
|
||||
# Or check if .git directory exists
|
||||
ls -la .git
|
||||
|
||||
# Restore from backup if corrupted
|
||||
```
|
||||
|
||||
### "error: Your local changes would be overwritten"
|
||||
|
||||
```bash
|
||||
# Stash changes
|
||||
git stash
|
||||
git pull
|
||||
git stash pop
|
||||
|
||||
# Or discard changes
|
||||
git reset --hard HEAD
|
||||
git pull
|
||||
```
|
||||
|
||||
### "error: failed to push some refs"
|
||||
|
||||
```bash
|
||||
# Fetch and merge first
|
||||
git pull origin main
|
||||
|
||||
# Or rebase
|
||||
git pull --rebase origin main
|
||||
|
||||
# Force push (dangerous)
|
||||
git push --force origin main
|
||||
|
||||
# Safer force push
|
||||
git push --force-with-lease origin main
|
||||
```
|
||||
|
||||
### "fatal: unable to access: SSL certificate problem"
|
||||
|
||||
```bash
|
||||
# Disable SSL verification (not recommended)
|
||||
git config --global http.sslVerify false
|
||||
|
||||
# Or update SSL certificates
|
||||
git config --global http.sslCAInfo /path/to/cacert.pem
|
||||
```
|
||||
|
||||
## Diagnostic Commands
|
||||
|
||||
### Repository Health Check
|
||||
|
||||
```bash
|
||||
# Full integrity check
|
||||
git fsck --full --strict
|
||||
|
||||
# Check connectivity
|
||||
git fsck --connectivity-only
|
||||
|
||||
# Verify objects
|
||||
git verify-pack -v .git/objects/pack/*.idx
|
||||
|
||||
# Check reflog
|
||||
git reflog expire --dry-run --all
|
||||
|
||||
# Analyze repository
|
||||
git count-objects -vH
|
||||
```
|
||||
|
||||
### Debug Information
|
||||
|
||||
```bash
|
||||
# Enable verbose logging
|
||||
GIT_TRACE=1 git status
|
||||
GIT_TRACE=1 git pull
|
||||
|
||||
# Debug specific operations
|
||||
GIT_TRACE_PACKET=1 git fetch
|
||||
GIT_TRACE_PERFORMANCE=1 git diff
|
||||
GIT_CURL_VERBOSE=1 git push
|
||||
|
||||
# Configuration debugging
|
||||
git config --list --show-origin
|
||||
git config --list --show-scope
|
||||
```
|
||||
|
||||
## Prevention Strategies
|
||||
|
||||
1. **Regular Backups:** Create backup branches before risky operations
|
||||
2. **Use Reflog:** Reflog is your safety net, keep it clean
|
||||
3. **Enable Rerere:** Reuse recorded conflict resolutions
|
||||
4. **Protect Branches:** Use branch protection rules
|
||||
5. **Pre-commit Hooks:** Validate commits before they're made
|
||||
6. **Regular Maintenance:** Run `git gc` periodically
|
||||
7. **Test Before Force Push:** Always verify with `--dry-run`
|
||||
8. **Communication:** Inform team about disruptive operations
|
||||
9. **Learn Git Internals:** Understanding how git works prevents issues
|
||||
10. **Keep Git Updated:** Use latest stable version
|
||||
|
||||
## Resources
|
||||
|
||||
Additional troubleshooting guides are available in the `assets/` directory:
|
||||
- `troubleshooting/` - Step-by-step recovery procedures
|
||||
- `scripts/` - Diagnostic and recovery scripts
|
||||
- `checklists/` - Problem diagnosis workflows
|
||||
|
||||
See `references/` directory for:
|
||||
- Git error message database
|
||||
- Recovery procedure documentation
|
||||
- Git internal structure guides
|
||||
- Common pitfall documentation
|
||||
Reference in New Issue
Block a user