From 139e230a67ea6c28d2073c3733c70b43fb9b0550 Mon Sep 17 00:00:00 2001 From: Zhongwei Li Date: Sun, 30 Nov 2025 08:29:08 +0800 Subject: [PATCH] Initial commit --- .claude-plugin/plugin.json | 15 + README.md | 3 + commands/git-safe-rebase.md | 96 ++ plugin.lock.json | 69 ++ skills/git-2-49-features.md | 330 ++++++ skills/git-2025-features.md | 459 ++++++++ skills/git-master/SKILL.md | 1746 +++++++++++++++++++++++++++++ skills/git-security-2025.md | 697 ++++++++++++ skills/github-actions-2025.md | 487 ++++++++ skills/github-ai-features-2025.md | 382 +++++++ 10 files changed, 4284 insertions(+) create mode 100644 .claude-plugin/plugin.json create mode 100644 README.md create mode 100644 commands/git-safe-rebase.md create mode 100644 plugin.lock.json create mode 100644 skills/git-2-49-features.md create mode 100644 skills/git-2025-features.md create mode 100644 skills/git-master/SKILL.md create mode 100644 skills/git-security-2025.md create mode 100644 skills/github-actions-2025.md create mode 100644 skills/github-ai-features-2025.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..2e4a30b --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "git-master", + "description": "Complete Git expertise for ALL operations with 2025 features. PROACTIVELY activate for: (1) ANY Git task (basic/advanced/dangerous), (2) Git 2.51+ features (stash import/export, path-walk repacking, git-backfill for partial clones, reftables 50-80% faster, sparse-checkout, worktrees), (3) Windows/Git Bash compatibility (MINGW/MSYS2 path conversion, MSYS_NO_PATHCONV, cygpath utilities, shell detection with $MSYSTEM), (4) Security (signed commits GPG/SSH, zero-trust workflows, GitHub secret scanning with AI, CodeQL, Gitleaks), (5) Trunk-Based Development with < 1 day branches (Google/Microsoft scale), (6) GitHub CLI 2.x (Copilot CLI integration, model evaluations, triangular workflows, OAuth clipboard), (7) GitHub Actions 2025 (1 vCPU runners, immutable releases, Node24), (8) Repository management and optimization, (9) Modern workflows (monorepo, parallel development), (10) Branch strategies (Gitflow, Feature Branch, TBD), (11) Conflict resolution, (12) History rewriting/recovery with safety guardrails, (13) Platform operations (GitHub/GitLab/Azure DevOps/Bitbucket). Provides: Git 2.51 stash import/export for sharing stashes between machines, path-walk repacking for smaller pack files, Git Bash/MINGW path conversion handling (MSYS_NO_PATHCONV, MSYS2_ARG_CONV_EXCL, cygpath), shell detection ($MSYSTEM, uname -s, $OSTYPE), Git 2.49 git-backfill for efficient partial clone downloads, reftables migration, sparse-checkout for monorepos (90% space reduction), worktrees for parallel development with path handling guidance, GitHub Copilot CLI (replacing gh-copilot extension), gh models eval for prompt evaluations, zero-trust security patterns with continuous monitoring, signed commits (GPG and SSH), GitHub Actions 2025 features (1 vCPU runners, immutable releases), CodeQL with Copilot Autofix, complete command reference, automatic backups before destructive operations, safety guardrails, reflog recovery, emergency procedures, cross-platform path compatibility. Ensures modern, secure, efficient Git workflows following 2025 industry standards with comprehensive Windows/Git Bash support.", + "version": "1.5.0", + "author": { + "name": "Josiah Siegel", + "email": "JosiahSiegel@users.noreply.github.com" + }, + "skills": [ + "./skills" + ], + "commands": [ + "./commands" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..f2627a0 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# git-master + +Complete Git expertise for ALL operations with 2025 features. PROACTIVELY activate for: (1) ANY Git task (basic/advanced/dangerous), (2) Git 2.51+ features (stash import/export, path-walk repacking, git-backfill for partial clones, reftables 50-80% faster, sparse-checkout, worktrees), (3) Windows/Git Bash compatibility (MINGW/MSYS2 path conversion, MSYS_NO_PATHCONV, cygpath utilities, shell detection with $MSYSTEM), (4) Security (signed commits GPG/SSH, zero-trust workflows, GitHub secret scanning with AI, CodeQL, Gitleaks), (5) Trunk-Based Development with < 1 day branches (Google/Microsoft scale), (6) GitHub CLI 2.x (Copilot CLI integration, model evaluations, triangular workflows, OAuth clipboard), (7) GitHub Actions 2025 (1 vCPU runners, immutable releases, Node24), (8) Repository management and optimization, (9) Modern workflows (monorepo, parallel development), (10) Branch strategies (Gitflow, Feature Branch, TBD), (11) Conflict resolution, (12) History rewriting/recovery with safety guardrails, (13) Platform operations (GitHub/GitLab/Azure DevOps/Bitbucket). Provides: Git 2.51 stash import/export for sharing stashes between machines, path-walk repacking for smaller pack files, Git Bash/MINGW path conversion handling (MSYS_NO_PATHCONV, MSYS2_ARG_CONV_EXCL, cygpath), shell detection ($MSYSTEM, uname -s, $OSTYPE), Git 2.49 git-backfill for efficient partial clone downloads, reftables migration, sparse-checkout for monorepos (90% space reduction), worktrees for parallel development with path handling guidance, GitHub Copilot CLI (replacing gh-copilot extension), gh models eval for prompt evaluations, zero-trust security patterns with continuous monitoring, signed commits (GPG and SSH), GitHub Actions 2025 features (1 vCPU runners, immutable releases), CodeQL with Copilot Autofix, complete command reference, automatic backups before destructive operations, safety guardrails, reflog recovery, emergency procedures, cross-platform path compatibility. Ensures modern, secure, efficient Git workflows following 2025 industry standards with comprehensive Windows/Git Bash support. diff --git a/commands/git-safe-rebase.md b/commands/git-safe-rebase.md new file mode 100644 index 0000000..c55928c --- /dev/null +++ b/commands/git-safe-rebase.md @@ -0,0 +1,96 @@ +--- +description: Perform interactive rebase with safety guardrails +--- + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- ✅ CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + +--- + +You are an expert Git operator helping the user safely perform an interactive rebase. + +# Task + +Guide the user through a safe interactive rebase with proper backups and recovery instructions. + +# Safety Protocol + +1. **Create backup branch**: + ```bash + git branch backup-before-rebase-$(date +%Y%m%d-%H%M%S) + ``` + +2. **Show what will be rebased**: + ```bash + git log --oneline --graph .. + ``` + +3. **Warn about risks**: + - "⚠️ Interactive rebase will rewrite commit history" + - "⚠️ If this branch has been pushed and others are working on it, DO NOT proceed" + - "⚠️ All commits will get new hashes" + +4. **Ask for confirmation**: + - "Has this branch been pushed to a shared remote? (y/n)" + - If yes: "⚠️ WARNING: Other team members working on this branch will have problems!" + - "Do you want to proceed? (yes/NO)" + +5. **Perform rebase**: + ```bash + git rebase -i + ``` + +6. **Provide recovery instructions**: + ``` + If something goes wrong: + - Abort: git rebase --abort + - Recover: git reset --hard backup-before-rebase-XXXXXXXX + ``` + +7. **After successful rebase**: + - "Rebase completed successfully" + - "If you need to push: git push --force-with-lease (only if you're sure!)" + - "To delete backup: git branch -d backup-before-rebase-XXXXXXXX" + +# Rebase Commands Reference + +Interactive rebase commands you can use: +- `p, pick` = use commit +- `r, reword` = use commit, but edit message +- `e, edit` = use commit, but stop for amending +- `s, squash` = combine with previous commit +- `f, fixup` = like squash, but discard message +- `d, drop` = remove commit + +# Safety Rules + +- ALWAYS create backup branch first +- ALWAYS warn if branch has been pushed +- ALWAYS ask for explicit confirmation +- ALWAYS provide recovery instructions +- NEVER rebase shared/public branches without team coordination diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..06d70dd --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,69 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:JosiahSiegel/claude-code-marketplace:plugins/git-master", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "b822af22980444ef65584915dfbe115a77b9dbcf", + "treeHash": "4b48fafd3df65628699d880d3875960bbd7f927a93b3992cd77387c1d75be29e", + "generatedAt": "2025-11-28T10:11:49.687061Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "git-master", + "description": "Complete Git expertise for ALL operations with 2025 features. PROACTIVELY activate for: (1) ANY Git task (basic/advanced/dangerous), (2) Git 2.51+ features (stash import/export, path-walk repacking, git-backfill for partial clones, reftables 50-80% faster, sparse-checkout, worktrees), (3) Windows/Git Bash compatibility (MINGW/MSYS2 path conversion, MSYS_NO_PATHCONV, cygpath utilities, shell detection with $MSYSTEM), (4) Security (signed commits GPG/SSH, zero-trust workflows, GitHub secret scanning with AI, CodeQL, Gitleaks), (5) Trunk-Based Development with < 1 day branches (Google/Microsoft scale), (6) GitHub CLI 2.x (Copilot CLI integration, model evaluations, triangular workflows, OAuth clipboard), (7) GitHub Actions 2025 (1 vCPU runners, immutable releases, Node24), (8) Repository management and optimization, (9) Modern workflows (monorepo, parallel development), (10) Branch strategies (Gitflow, Feature Branch, TBD), (11) Conflict resolution, (12) History rewriting/recovery with safety guardrails, (13) Platform operations (GitHub/GitLab/Azure DevOps/Bitbucket). Provides: Git 2.51 stash import/export for sharing stashes between machines, path-walk repacking for smaller pack files, Git Bash/MINGW path conversion handling (MSYS_NO_PATHCONV, MSYS2_ARG_CONV_EXCL, cygpath), shell detection ($MSYSTEM, uname -s, $OSTYPE), Git 2.49 git-backfill for efficient partial clone downloads, reftables migration, sparse-checkout for monorepos (90% space reduction), worktrees for parallel development with path handling guidance, GitHub Copilot CLI (replacing gh-copilot extension), gh models eval for prompt evaluations, zero-trust security patterns with continuous monitoring, signed commits (GPG and SSH), GitHub Actions 2025 features (1 vCPU runners, immutable releases), CodeQL with Copilot Autofix, complete command reference, automatic backups before destructive operations, safety guardrails, reflog recovery, emergency procedures, cross-platform path compatibility. Ensures modern, secure, efficient Git workflows following 2025 industry standards with comprehensive Windows/Git Bash support.", + "version": "1.5.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "f1b8d4f894b54a52d085a0250e07ad8d4122ee80db3a37769cb916a9c1b2fe4d" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "0cd829bb407ea1f66ebb6a382198dd4237aeb1c48eeb8a998154f8f94ae8cab1" + }, + { + "path": "commands/git-safe-rebase.md", + "sha256": "82678a557e27c77eb7f635d280b995a20652d8882ff4b25fd2b6665f830609f2" + }, + { + "path": "skills/github-actions-2025.md", + "sha256": "7f2ffa820dc507462620827b00ead9fb8b79e603494b7105ba9a75192baa9f56" + }, + { + "path": "skills/git-security-2025.md", + "sha256": "61a5f6c9eacbd9ab83802f0fbc30f561b31d79d39a4ce443bcdee37758dc95f6" + }, + { + "path": "skills/git-2-49-features.md", + "sha256": "acdc33be56eef1eb539a304a1bcbc15e583123e24ceb881f13e5fae88b9465f7" + }, + { + "path": "skills/github-ai-features-2025.md", + "sha256": "5b92bce8c57e2b7516a21277190720010bf04c8b41a348b8a406d1ac112d7070" + }, + { + "path": "skills/git-2025-features.md", + "sha256": "c6a914560cd25e718b11251a0c66b9511d56dc0693cadcac2a4f1a26abdd574e" + }, + { + "path": "skills/git-master/SKILL.md", + "sha256": "0582b0a42b23d8b1df4e6367fe1f9745a5d246d0e59b177d12bedf07852574fc" + } + ], + "dirSha256": "4b48fafd3df65628699d880d3875960bbd7f927a93b3992cd77387c1d75be29e" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/git-2-49-features.md b/skills/git-2-49-features.md new file mode 100644 index 0000000..af96215 --- /dev/null +++ b/skills/git-2-49-features.md @@ -0,0 +1,330 @@ +--- +name: git-2-49-features +description: Git 2.49+ features including git-backfill, path-walk API, and performance improvements +--- + +# Git 2.49+ Features (2025) + +## git-backfill Command (New in 2.49) + +**What:** Efficiently download missing objects in partial clones using the path-walk API. + +**Why:** Dramatically improves delta compression when fetching objects from partial clones, resulting in smaller downloads and better performance. + +### Basic Usage + +```bash +# Check if you have a partial clone +git config extensions.partialClone + +# Download missing objects in background +git backfill + +# Download with custom batch size +git backfill --batch-size=1000 + +# Respect sparse-checkout patterns (only fetch needed files) +git backfill --sparse + +# Check progress +git backfill --verbose +``` + +### When to Use + +**Scenario 1: After cloning with --filter=blob:none** +```bash +# Clone without blobs +git clone --filter=blob:none https://github.com/large/repo.git +cd repo + +# Later, prefetch all missing objects efficiently +git backfill +``` + +**Scenario 2: Sparse-checkout + Partial clone** +```bash +# Clone with both optimizations +git clone --filter=blob:none --sparse https://github.com/monorepo.git +cd monorepo +git sparse-checkout set src/api + +# Fetch only needed objects +git backfill --sparse +``` + +**Scenario 3: CI/CD Optimization** +```bash +# In CI pipeline - fetch only what's needed +git clone --filter=blob:none --depth=1 repo +git backfill --sparse +# Much faster than full clone +``` + +### Performance Comparison + +**Traditional partial clone fetch:** +```bash +git fetch --unshallow +# Downloads 500MB in random order +# Poor delta compression +``` + +**With git-backfill:** +```bash +git backfill +# Downloads 150MB with optimized delta compression (70% reduction) +# Groups objects by path for better compression +``` + +## Path-Walk API (New in 2.49) + +**What:** Internal API that groups together objects appearing at the same path, enabling much better delta compression. + +**How it works:** Instead of processing objects in commit order, path-walk processes them by filesystem path, allowing Git to find better delta bases. + +**Benefits:** +- 50-70% better compression in partial clone scenarios +- Faster object transfers +- Reduced network usage +- Optimized packfile generation + +**You benefit automatically when using:** +- `git backfill` +- `git repack` (improved in 2.49) +- Server-side object transfers + +### Enable Path-Walk Optimizations + +```bash +# For repack operations +git config pack.useBitmaps true +git config pack.writeBitmaps true + +# Repack with path-walk optimizations +git repack -a -d -f + +# Check improvement +git count-objects -v +``` + +## Performance Improvements with zlib-ng + +**What:** Git 2.49 includes improved performance through zlib-ng integration for compression/decompression. + +**Benefits:** +- 20-30% faster compression +- 10-15% faster decompression +- Lower CPU usage during pack operations +- Transparent - no configuration needed + +**Automatically improves:** +- `git clone` +- `git fetch` +- `git push` +- `git gc` +- `git repack` + +## New Name-Hashing Algorithm + +**What:** Improved algorithm for selecting object pairs during delta compression. + +**Results:** +- More efficient packfiles +- Better compression ratios (5-10% improvement) +- Faster repack operations + +**Automatic - no action needed.** + +## Rust Bindings for libgit + +**What:** Git 2.49 added Rust bindings (libgit-sys and libgit-rs) for Git's internal libraries. + +**Relevance:** Future Git tooling and performance improvements will leverage Rust for memory safety and performance. + +**For developers:** You can now build Git tools in Rust using official bindings. + +## Promisor Remote Enhancements + +**What:** Servers can now advertise promisor remote information to clients. + +**Benefits:** +- Better handling of large files in partial clones +- Improved lazy fetching +- More efficient missing object retrieval + +**Configuration:** +```bash +# View promisor remote info +git config remote.origin.promisor +git config extensions.partialClone + +# Verify promisor packfiles +ls -lah .git/objects/pack/*.promisor +``` + +## Git 2.49 Workflow Examples + +### Example 1: Ultra-Efficient Monorepo Clone + +```bash +# Clone large monorepo with maximum efficiency +git clone --filter=blob:none --sparse https://github.com/company/monorepo.git +cd monorepo + +# Only checkout your team's service +git sparse-checkout set --cone services/api + +# Fetch needed objects with path-walk optimization +git backfill --sparse + +# Result: 95% smaller than full clone, 70% faster download +``` + +### Example 2: CI/CD Pipeline Optimization + +```yaml +# .github/workflows/ci.yml +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Checkout with optimizations + run: | + git clone --filter=blob:none --depth=1 --sparse ${{ github.repositoryUrl }} + cd repo + git sparse-checkout set src tests + git backfill --sparse + + - name: Run tests + run: npm test +# 80% faster than full clone in CI +``` + +### Example 3: Working with Huge History + +```bash +# Clone repository with massive history +git clone --filter=blob:none https://github.com/project/with-long-history.git +cd with-long-history + +# Work on recent code only (objects fetched on demand) +git checkout -b feature/new-feature + +# When you need full history +git backfill + +# Repack for optimal storage +git repack -a -d -f # Uses path-walk API +``` + +## Deprecated Features (Removal in Git 3.0) + +**⚠️ Now Officially Deprecated:** +- `.git/branches/` directory (use remotes instead) +- `.git/remotes/` directory (use git remote commands) + +**Migration:** +```bash +# If you have old-style remotes, convert them +# Check for deprecated directories +ls -la .git/branches .git/remotes 2>/dev/null + +# Use modern remote configuration +git remote add origin https://github.com/user/repo.git +git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*' +``` + +## Meson Build System + +**What:** Continued development on Meson as alternative build system for Git. + +**Why:** Faster builds, better cross-platform support. + +**Status:** Experimental - use `make` for production. + +## netrc Support Re-enabled + +**What:** HTTP transport now supports .netrc for authentication. + +**Usage:** +```bash +# ~/.netrc +machine github.com + login your-username + password your-token + +# Git will now use these credentials automatically +git clone https://github.com/private/repo.git +``` + +## Best Practices with Git 2.49 + +1. **Use git-backfill for partial clones:** + ```bash + git backfill --sparse # Better than git fetch --unshallow + ``` + +2. **Combine optimizations:** + ```bash + git clone --filter=blob:none --sparse + git sparse-checkout set --cone + git backfill --sparse + ``` + +3. **Regular maintenance:** + ```bash + git backfill # Fill in missing objects + git repack -a -d -f # Optimize with path-walk + git prune # Clean up + ``` + +4. **Monitor partial clone status:** + ```bash + # Check promisor remotes + git config extensions.partialClone + + # List missing objects + git rev-list --objects --all --missing=print | grep "^?" + ``` + +5. **Migrate deprecated features:** + ```bash + # Move away from .git/branches and .git/remotes + # Use git remote commands instead + ``` + +## Troubleshooting + +**git-backfill not found:** +```bash +# Verify Git version +git --version # Must be 2.49+ + +# Update Git +brew upgrade git # macOS +apt update && apt install git # Ubuntu +``` + +**Promisor remote issues:** +```bash +# Reset promisor configuration +git config --unset extensions.partialClone +git config --unset remote.origin.promisor + +# Re-enable +git config extensions.partialClone origin +git config remote.origin.promisor true +``` + +**Poor delta compression:** +```bash +# Force repack with path-walk optimization +git repack -a -d -f --depth=250 --window=250 +``` + +## Resources + +- [Git 2.49 Release Notes](https://github.blog/open-source/git/highlights-from-git-2-49/) +- [Path-Walk API Documentation](https://git-scm.com/docs/api-path-walk) +- [Partial Clone Documentation](https://git-scm.com/docs/partial-clone) diff --git a/skills/git-2025-features.md b/skills/git-2025-features.md new file mode 100644 index 0000000..ddc4121 --- /dev/null +++ b/skills/git-2025-features.md @@ -0,0 +1,459 @@ +--- +name: git-2025-features +description: Git 2.49+ features including reftables, sparse-checkout, partial clone, git-backfill, and worktrees +--- + +**📌 NOTE:** For detailed Git 2.49+ features (git-backfill, path-walk API, zlib-ng), see git-2-49-features.md skill. + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- ✅ CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + +--- + +# Git 2025 Features - Advanced Capabilities + +## Git 2.49 (March 2025) - Latest + +**Major additions:** git-backfill, path-walk API, zlib-ng performance, improved delta compression. + +**See git-2-49-features.md for complete coverage.** + +## Git 2.48-2.49 Features + +### Reftables Migration (Completed in 2.48) + +**What:** New reference storage format replacing loose ref files and packed-refs. + +**Benefits:** +- Faster ref operations (50-80% improvement) +- Atomic ref updates +- Better scalability for repositories with many refs +- Reflogs fully migratable (completed in 2.48) + +**Migration:** + +```bash +# Check current ref storage format +git config core.refStorage + +# Migrate to reftables +git refs migrate --ref-storage=reftables + +# Verify migration +git fsck --full +git log --oneline -5 + +# Roll back if needed (before critical operations) +git refs migrate --ref-storage=files +``` + +**When to use:** +- Repositories with 10,000+ refs +- High-frequency branch operations +- CI/CD systems creating many temporary refs +- Monorepos with extensive branching + +### Performance Milestones (2.48-2.49) + +**Git 2.48:** +- Memory leak free status achieved +- Stable memory usage in long-running operations + +**Git 2.49:** +- zlib-ng integration: 20-30% faster compression +- Path-walk API: 50-70% better delta compression +- New name-hashing algorithm for optimal packfiles + +Benefits automatically in: +- Large repository clones +- Extended rebase sessions +- Bulk operations (filter-repo, GC, repack) + +## Sparse-Checkout (Enhanced in 2.48) + +**What:** Check out only a subset of files from repository. + +**Use cases:** +- Monorepos (work on one service) +- Large repositories (reduce disk usage) +- Build systems (fetch only needed files) + +**Cone Mode (Default - Recommended):** + +```bash +# Clone with sparse-checkout +git clone --filter=blob:none --sparse +cd + +# Initialize sparse-checkout in cone mode +git sparse-checkout init --cone + +# Add directories to checkout +git sparse-checkout set src/api src/shared docs + +# Add more directories +git sparse-checkout add tests/integration + +# View current patterns +git sparse-checkout list + +# Check what would be matched +git sparse-checkout check-rules src/api/users.ts + +# Disable sparse-checkout +git sparse-checkout disable +``` + +**Advanced Patterns (Non-Cone Mode):** + +```bash +# Enable pattern mode +git sparse-checkout init --no-cone + +# Add patterns (one per line) +git sparse-checkout set \ + "*.md" \ + "src/api/*" \ + "!src/api/legacy/*" + +# Read patterns from file +git sparse-checkout set --stdin < patterns.txt +``` + +**Reapply Rules:** + +```bash +# After merge/rebase that materialized unwanted files +git sparse-checkout reapply +``` + +## Partial Clone + +**What:** Clone repository without downloading all objects initially. + +**Filters:** + +1. **blob:none** - Defer all blobs (fastest, smallest) +2. **tree:0** - Defer all trees and blobs +3. **blob:limit=1m** - Defer blobs larger than 1MB + +**Usage:** + +```bash +# Clone without blobs (fetch on demand) +git clone --filter=blob:none + +# Clone without large files +git clone --filter=blob:limit=10m + +# Combine with sparse-checkout +git clone --filter=blob:none --sparse +cd +git sparse-checkout set src/api + +# Convert existing repository to partial clone +git config extensions.partialClone origin +git config remote.origin.promisor true +git fetch --filter=blob:none + +# Prefetch all missing objects +git fetch --unshallow +``` + +**Combine Partial Clone + Sparse-Checkout:** + +```bash +# Ultimate efficiency: Only objects for specific directories +git clone --filter=blob:none --sparse +cd +git sparse-checkout set --cone src/api +git checkout main + +# Result: Only have objects for src/api +``` + +**Check promisor objects:** + +```bash +# Verify partial clone status +git config extensions.partialClone + +# See promisor packfiles +ls -lah .git/objects/pack/*.promisor + +# Force fetch specific object +git rev-list --objects --missing=print HEAD | grep "^?" +``` + +## Git Worktrees + +**What:** Multiple working directories from one repository. + +**Benefits:** +- Work on multiple branches simultaneously +- No need to stash/commit before switching +- Parallel work (review PR while coding) +- Shared .git (one fetch updates all) + +**Basic Operations:** + +```bash +# List worktrees +git worktree list + +# Create worktree for existing branch +git worktree add ../project-feature feature-branch + +# Create worktree with new branch +git worktree add -b new-feature ../project-new-feature + +# Create worktree from remote branch +git worktree add ../project-fix origin/fix-bug + +# Remove worktree +git worktree remove ../project-feature + +# Clean up stale worktree references +git worktree prune +``` + +**Advanced Patterns:** + +```bash +# Worktree for PR review while coding +git worktree add ../myproject-pr-123 origin/pull/123/head +cd ../myproject-pr-123 +# Review PR in separate directory +cd - +# Continue coding in main worktree + +# Worktree for hotfix +git worktree add --detach ../myproject-hotfix v1.2.3 +cd ../myproject-hotfix +# Make hotfix +git switch -c hotfix/security-patch +git commit -am "fix: patch vulnerability" +git push -u origin hotfix/security-patch + +# Worktree organization +mkdir -p ~/worktrees/myproject +git worktree add ~/worktrees/myproject/feature-a -b feature-a +git worktree add ~/worktrees/myproject/feature-b -b feature-b +git worktree add ~/worktrees/myproject/pr-review origin/pull/42/head +``` + +**Best Practices:** + +1. **Organize directory structure:** +```bash +~/projects/ + myproject/ # Main worktree + myproject-feature/ # Feature worktree + myproject-review/ # Review worktree +``` + +2. **Clean up regularly:** +```bash +# Remove merged worktrees +git worktree list | grep feature | while read wt branch commit; do + if git branch --merged | grep -q "$branch"; then + git worktree remove "$wt" + fi +done +``` + +3. **Shared configuration:** +- .git/config applies to all worktrees +- .git/info/exclude applies to all worktrees +- Each worktree has own index and HEAD + +## Scalar (Large Repository Tool) + +**What:** Tool for optimizing very large repositories (Microsoft-developed). + +```bash +# Install scalar (comes with Git 2.47+) +scalar register + +# Clone with scalar optimizations +scalar clone --branch main + +# Enables automatically: +# - Sparse-checkout (cone mode) +# - Partial clone (blob:none) +# - Multi-pack-index +# - Commit-graph +# - Background maintenance + +# Unregister +scalar unregister + +# Delete repository +scalar delete +``` + +## Git Backfill (Experimental) + +**What:** Background process to fetch missing objects in partial clone. + +```bash +# Fetch missing blobs in background +git backfill + +# Configure batch size +git backfill --min-batch-size=1000 + +# Respect sparse-checkout patterns +git backfill --sparse +``` + +## Performance Comparison + +**Traditional Clone:** +```bash +git clone large-repo +# Size: 5GB, Time: 10 minutes +``` + +**Sparse-Checkout:** +```bash +git clone --sparse large-repo +git sparse-checkout set src/api +# Size: 500MB, Time: 3 minutes +``` + +**Partial Clone:** +```bash +git clone --filter=blob:none large-repo +# Size: 100MB, Time: 1 minute +``` + +**Partial Clone + Sparse-Checkout:** +```bash +git clone --filter=blob:none --sparse large-repo +git sparse-checkout set src/api +# Size: 50MB, Time: 30 seconds +``` + +## When to Use Each Feature + +**Sparse-Checkout:** +- ✓ Monorepos +- ✓ Working on specific services/modules +- ✓ Limited disk space +- ✗ Need entire codebase often + +**Partial Clone:** +- ✓ CI/CD pipelines +- ✓ Large repositories +- ✓ Good network connectivity +- ✗ Offline work frequently + +**Worktrees:** +- ✓ Parallel development +- ✓ PR reviews during work +- ✓ Multiple branch testing +- ✗ Low disk space + +**Combine All:** +- ✓ Massive monorepos (Google scale) +- ✓ Multiple simultaneous tasks +- ✓ Minimal local storage +- ✓ Fast network connection + +## Troubleshooting + +**Sparse-checkout not working:** +```bash +# Verify configuration +git config core.sparseCheckout +git config core.sparseCheckoutCone + +# Re-apply patterns +git sparse-checkout reapply + +# Check patterns +git sparse-checkout list +``` + +**Missing objects in partial clone:** +```bash +# Fetch specific object +git fetch origin + +# Fetch all missing +git fetch --unshallow + +# Verify promisor config +git config extensions.partialClone +``` + +**Worktree issues:** +```bash +# Locked worktree +git worktree unlock + +# Corrupted worktree +git worktree remove --force +git worktree prune + +# Branch already checked out +git checkout --ignore-other-worktrees +``` + +## Migration Guide + +**From traditional to optimized workflow:** + +```bash +# 1. Current large clone +cd large-project +du -sh .git # 5GB + +# 2. Create optimized new clone +cd .. +git clone --filter=blob:none --sparse large-project-new +cd large-project-new +git sparse-checkout set src/api src/shared + +# 3. Verify size +du -sh .git # 50MB + +# 4. Switch workflow +cd ../large-project-new + +# 5. Delete old clone when comfortable +rm -rf ../large-project +``` + +## Resources + +- [Git Partial Clone Documentation](https://git-scm.com/docs/partial-clone) +- [Git Sparse-Checkout Guide](https://github.blog/open-source/git/bring-your-monorepo-down-to-size-with-sparse-checkout/) +- [Git Worktree Best Practices](https://git-scm.com/docs/git-worktree) +- [Scalar Documentation](https://github.com/microsoft/scalar) diff --git a/skills/git-master/SKILL.md b/skills/git-master/SKILL.md new file mode 100644 index 0000000..f24910c --- /dev/null +++ b/skills/git-master/SKILL.md @@ -0,0 +1,1746 @@ +--- +name: git-master +description: "Complete Git expertise system for ALL git operations. PROACTIVELY activate for: (1) ANY Git task (basic/advanced/dangerous), (2) Repository management, (3) Branch strategies and workflows, (4) Conflict resolution, (5) History rewriting/recovery, (6) Platform-specific operations (GitHub/Azure DevOps/Bitbucket), (7) Advanced commands (rebase/cherry-pick/filter-repo). Provides: complete Git command reference, safety guardrails for destructive operations, platform best practices, workflow strategies, reflog recovery techniques, and expert guidance for even the most risky operations. Always asks user preference for automatic commits vs manual control." +--- + +# Git Mastery - Complete Git Expertise + +## 🚨 CRITICAL GUIDELINES + +### Windows File Path Requirements + +**MANDATORY: Always Use Backslashes on Windows for File Paths** + +When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`). + +**Examples:** +- ❌ WRONG: `D:/repos/project/file.tsx` +- ✅ CORRECT: `D:\repos\project\file.tsx` + +This applies to: +- Edit tool file_path parameter +- Write tool file_path parameter +- All file operations on Windows systems + +### Documentation Guidelines + +**NEVER create new documentation files unless explicitly requested by the user.** + +- **Priority**: Update existing README.md files rather than creating new documentation +- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise +- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone +- **User preference**: Only create additional .md files when user specifically asks for documentation + + + +--- + +Comprehensive guide for ALL Git operations from basic to advanced, including dangerous operations with safety guardrails. + +--- + +## TL;DR QUICK REFERENCE + +**Safety First - Before ANY Destructive Operation:** +```bash +# ALWAYS check status first +git status +git log --oneline -10 + +# For risky operations, create a safety branch +git branch backup-$(date +%Y%m%d-%H%M%S) + +# Remember: git reflog is your safety net (90 days default) +git reflog +``` + +**User Preference Check:** +- **ALWAYS ASK:** "Would you like me to create commits automatically, or would you prefer to handle commits manually?" +- Respect user's choice throughout the session + +--- + +## Overview + +This skill provides COMPLETE Git expertise for ANY Git operation, no matter how advanced, niche, or risky. It covers: + +**MUST use this skill for:** +- ✅ ANY Git command or operation +- ✅ Repository initialization, cloning, configuration +- ✅ Branch management and strategies +- ✅ Commit workflows and best practices +- ✅ Merge strategies and conflict resolution +- ✅ Rebase operations (interactive and non-interactive) +- ✅ History rewriting (filter-repo, reset, revert) +- ✅ Recovery operations (reflog, fsck) +- ✅ Dangerous operations (force push, hard reset) +- ✅ Platform-specific workflows (GitHub, Azure DevOps, Bitbucket) +- ✅ Advanced features (submodules, worktrees, hooks) +- ✅ Performance optimization +- ✅ Cross-platform compatibility (Windows/Linux/macOS) + +--- + +## Core Principles + +### 1. Safety Guardrails for Destructive Operations + +**CRITICAL: Before ANY destructive operation (reset --hard, force push, filter-repo, etc.):** + +1. **Always warn the user explicitly** +2. **Explain the risks clearly** +3. **Ask for confirmation** +4. **Suggest creating a backup branch first** +5. **Provide recovery instructions** + +```bash +# Example safety pattern for dangerous operations +echo "⚠️ WARNING: This operation is DESTRUCTIVE and will:" +echo " - Permanently delete uncommitted changes" +echo " - Rewrite Git history" +echo " - [specific risks for the operation]" +echo "" +echo "Safety recommendation: Creating backup branch first..." +git branch backup-before-reset-$(date +%Y%m%d-%H%M%S) +echo "" +echo "To recover if needed: git reset --hard backup-before-reset-XXXXXXXX" +echo "" +read -p "Are you SURE you want to proceed? (yes/NO): " confirm +if [[ "$confirm" != "yes" ]]; then + echo "Operation cancelled." + exit 1 +fi +``` + +### 2. Commit Creation Policy + +**ALWAYS ASK at the start of ANY Git task:** +"Would you like me to: +1. Create commits automatically with appropriate messages +2. Stage changes only (you handle commits manually) +3. Just provide guidance (no automatic operations)" + +Respect this choice throughout the session. + +### 3. Platform Awareness + +Git behavior and workflows differ across platforms and hosting providers: + +**Windows (Git Bash/PowerShell):** +- Line ending handling (core.autocrlf) +- Path separators and case sensitivity +- Credential management (Windows Credential Manager) + +**Linux/macOS:** +- Case-sensitive filesystems +- SSH key management +- Permission handling + +**Hosting Platforms:** +- GitHub: Pull requests, GitHub Actions, GitHub CLI +- Azure DevOps: Pull requests, Azure Pipelines, policies +- Bitbucket: Pull requests, Bitbucket Pipelines, Jira integration +- GitLab: Merge requests, GitLab CI/CD + +--- + +## Basic Git Operations + +### Repository Initialization and Cloning + +```bash +# Initialize new repository +git init +git init --initial-branch=main # Specify default branch name + +# Clone repository +git clone +git clone +git clone --depth 1 # Shallow clone (faster, less history) +git clone --branch # Clone specific branch +git clone --recurse-submodules # Include submodules +``` + +### Configuration + +```bash +# User identity (required for commits) +git config --global user.name "Your Name" +git config --global user.email "your.email@example.com" + +# Default branch name +git config --global init.defaultBranch main + +# Line ending handling (Windows) +git config --global core.autocrlf true # Windows +git config --global core.autocrlf input # macOS/Linux + +# Editor +git config --global core.editor "code --wait" # VS Code +git config --global core.editor "vim" + +# Diff tool +git config --global diff.tool vscode +git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE' + +# Merge tool +git config --global merge.tool vscode +git config --global mergetool.vscode.cmd 'code --wait $MERGED' + +# Aliases +git config --global alias.st status +git config --global alias.co checkout +git config --global alias.br branch +git config --global alias.ci commit +git config --global alias.unstage 'reset HEAD --' +git config --global alias.last 'log -1 HEAD' +git config --global alias.visual '!gitk' + +# View configuration +git config --list +git config --global --list +git config --local --list +git config user.name # Get specific value +``` + +### Basic Workflow + +```bash +# Check status +git status +git status -s # Short format +git status -sb # Short with branch info + +# Add files +git add +git add . # Add all changes in current directory +git add -A # Add all changes in repository +git add -p # Interactive staging (patch mode) + +# Remove files +git rm +git rm --cached # Remove from index, keep in working directory +git rm -r + +# Move/rename files +git mv + +# Commit +git commit -m "message" +git commit -am "message" # Add and commit tracked files +git commit --amend # Amend last commit +git commit --amend --no-edit # Amend without changing message +git commit --allow-empty -m "message" # Empty commit (useful for triggers) + +# View history +git log +git log --oneline +git log --graph --oneline --all --decorate +git log --stat # Show file statistics +git log --patch # Show diffs +git log -p -2 # Show last 2 commits with diffs +git log --since="2 weeks ago" +git log --until="2025-01-01" +git log --author="Name" +git log --grep="pattern" +git log -- # History of specific file +git log --follow # Follow renames + +# Show changes +git diff # Unstaged changes +git diff --staged # Staged changes +git diff HEAD # All changes since last commit +git diff # Compare with another branch +git diff +git diff # Changes since specific commit +git diff ... # Changes between branches + +# Show commit details +git show +git show : # Show file at specific commit +``` + +--- + +## Branch Management + +### Creating and Switching Branches + +```bash +# List branches +git branch # Local branches +git branch -r # Remote branches +git branch -a # All branches +git branch -v # With last commit info +git branch -vv # With tracking info + +# Create branch +git branch +git branch # From specific commit/tag + +# Switch branch +git switch +git checkout # Old syntax, still works + +# Create and switch +git switch -c +git checkout -b +git switch -c + +# Delete branch +git branch -d # Safe delete (only if merged) +git branch -D # Force delete (even if not merged) + +# Rename branch +git branch -m +git branch -m # Rename current branch + +# Set upstream tracking +git branch --set-upstream-to=origin/ +git branch -u origin/ +``` + +### Branch Strategies + +**Git Flow:** +- `main/master`: Production-ready code +- `develop`: Integration branch for features +- `feature/*`: New features +- `release/*`: Release preparation +- `hotfix/*`: Production fixes + +**GitHub Flow:** +- `main`: Always deployable +- `feature/*`: Short-lived feature branches +- Create PR, review, merge + +**Trunk-Based Development:** +- `main`: Single branch +- Short-lived feature branches (< 1 day) +- Feature flags for incomplete features + +**GitLab Flow:** +- Environment branches: `production`, `staging`, `main` +- Feature branches merge to `main` +- Deploy from environment branches + +--- + +## Merging and Rebasing + +### Merge Strategies + +```bash +# Fast-forward merge (default if possible) +git merge + +# Force merge commit (even if fast-forward possible) +git merge --no-ff + +# Squash merge (combine all commits into one) +git merge --squash +# Then commit manually: git commit -m "Merged feature X" + +# Merge with specific strategy +git merge -s recursive # Default strategy +git merge -s ours # Always use "our" version +git merge -s theirs # Always use "their" version (requires merge-theirs) +git merge -s octopus # Merge multiple branches + +# Merge with strategy options +git merge -X ours # Prefer "our" changes in conflicts +git merge -X theirs # Prefer "their" changes in conflicts +git merge -X ignore-all-space +git merge -X ignore-space-change + +# Abort merge +git merge --abort + +# Continue after resolving conflicts +git merge --continue +``` + +### Conflict Resolution + +```bash +# When merge conflicts occur +git status # See conflicted files + +# Conflict markers in files: +# <<<<<<< HEAD +# Your changes +# ======= +# Their changes +# >>>>>>> branch-name + +# Resolve conflicts manually, then: +git add +git commit # Complete the merge + +# Use mergetool +git mergetool + +# Accept one side completely +git checkout --ours # Keep our version +git checkout --theirs # Keep their version +git add + +# View conflict diff +git diff # Show conflicts +git diff --ours # Compare with our version +git diff --theirs # Compare with their version +git diff --base # Compare with base version + +# List conflicts +git diff --name-only --diff-filter=U +``` + +### Rebase Operations + +**⚠️ WARNING: Rebase rewrites history. Never rebase commits that have been pushed to shared branches!** + +```bash +# Basic rebase +git rebase +git rebase origin/main + +# Interactive rebase (POWERFUL) +git rebase -i +git rebase -i HEAD~5 # Last 5 commits + +# Interactive rebase commands: +# p, pick = use commit +# r, reword = use commit, but edit 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 (rest of line) using shell +# b, break = stop here (continue rebase later with 'git rebase --continue') +# d, drop = remove commit +# l, label = label current HEAD with a name +# t, reset = reset HEAD to a label + +# Rebase onto different base +git rebase --onto + +# Continue after resolving conflicts +git rebase --continue + +# Skip current commit +git rebase --skip + +# Abort rebase +git rebase --abort + +# Preserve merge commits +git rebase --preserve-merges # Deprecated +git rebase --rebase-merges # Modern approach + +# Autosquash (with fixup commits) +git commit --fixup +git rebase -i --autosquash +``` + +### Cherry-Pick + +```bash +# Apply specific commit to current branch +git cherry-pick + +# Cherry-pick multiple commits +git cherry-pick +git cherry-pick .. + +# Cherry-pick without committing +git cherry-pick -n +git cherry-pick --no-commit + +# Continue after resolving conflicts +git cherry-pick --continue + +# Abort cherry-pick +git cherry-pick --abort +``` + +--- + +## Remote Operations + +### Remote Management + +```bash +# List remotes +git remote +git remote -v # With URLs + +# Add remote +git remote add +git remote add origin https://github.com/user/repo.git + +# Change remote URL +git remote set-url + +# Remove remote +git remote remove +git remote rm + +# Rename remote +git remote rename + +# Show remote info +git remote show +git remote show origin + +# Prune stale remote branches +git remote prune origin +git fetch --prune +``` + +### Fetch and Pull + +```bash +# Fetch from remote (doesn't merge) +git fetch +git fetch origin +git fetch --all # All remotes +git fetch --prune # Remove stale remote-tracking branches + +# Pull (fetch + merge) +git pull +git pull origin +git pull --rebase # Fetch + rebase instead of merge +git pull --no-ff # Always create merge commit +git pull --ff-only # Only if fast-forward possible + +# Set default pull behavior +git config --global pull.rebase true # Always rebase +git config --global pull.ff only # Only fast-forward +``` + +### Push + +```bash +# Push to remote +git push +git push origin +git push origin : + +# Push new branch and set upstream +git push -u origin +git push --set-upstream origin + +# Push all branches +git push --all + +# Push tags +git push --tags +git push origin + +# Delete remote branch +git push origin --delete +git push origin : # Old syntax + +# Delete remote tag +git push origin --delete +git push origin :refs/tags/ + +# ⚠️ DANGEROUS: Force push (overwrites remote history) +# ALWAYS ASK USER FOR CONFIRMATION FIRST +git push --force +git push -f + +# ⚠️ SAFER: Force push with lease (fails if remote updated) +git push --force-with-lease +git push --force-with-lease=: +``` + +**Force Push Safety Protocol:** + +Before ANY force push, execute this safety check: + +```bash +echo "⚠️ DANGER: Force push will overwrite remote history!" +echo "" +echo "Remote branch status:" +git fetch origin +git log --oneline origin/ ^ --decorate + +if [ -z "$(git log --oneline origin/ ^)" ]; then + echo "✓ No commits will be lost (remote is behind local)" +else + echo "❌ WARNING: Remote has commits that will be LOST:" + git log --oneline --decorate origin/ ^ + echo "" + echo "These commits from other developers will be destroyed!" +fi + +echo "" +echo "Consider using --force-with-lease instead of --force" +echo "" +read -p "Type 'force push' to confirm: " confirm +if [[ "$confirm" != "force push" ]]; then + echo "Cancelled." + exit 1 +fi +``` + +--- + +## Advanced Commands + +### Stash + +```bash +# Stash changes +git stash +git stash save "message" +git stash push -m "message" + +# Stash including untracked files +git stash -u +git stash --include-untracked + +# Stash including ignored files +git stash -a +git stash --all + +# List stashes +git stash list + +# Show stash contents +git stash show +git stash show -p # With diff +git stash show stash@{2} + +# Apply stash (keep in stash list) +git stash apply +git stash apply stash@{2} + +# Pop stash (apply and remove) +git stash pop +git stash pop stash@{2} + +# Drop stash +git stash drop +git stash drop stash@{2} + +# Clear all stashes +git stash clear + +# Create branch from stash +git stash branch +git stash branch stash@{1} + +# Git 2.51+ : Import/Export stashes (share stashes between machines) +# Export stash to a file +git stash store --file=stash.patch stash@{0} + +# Import stash from a file +git stash import --file=stash.patch + +# Share stashes like branches/tags +git stash export > my-stash.patch +git stash import < my-stash.patch +``` + +### Reset + +**⚠️ WARNING: reset can permanently delete changes!** + +```bash +# Soft reset (keep changes staged) +git reset --soft +git reset --soft HEAD~1 # Undo last commit, keep changes staged + +# Mixed reset (default - keep changes unstaged) +git reset +git reset HEAD~1 # Undo last commit, keep changes unstaged + +# ⚠️ HARD reset (DELETE all changes - DANGEROUS!) +# ALWAYS create backup branch first! +git branch backup-$(date +%Y%m%d-%H%M%S) +git reset --hard +git reset --hard HEAD~1 # Undo last commit and DELETE all changes +git reset --hard origin/ # Reset to remote state + +# Unstage files +git reset HEAD +git reset -- + +# Reset specific file to commit +git checkout -- +``` + +### Revert + +```bash +# Revert commit (creates new commit that undoes changes) +# Safer than reset for shared branches +git revert + +# Revert without creating commit +git revert -n +git revert --no-commit + +# Revert merge commit +git revert -m 1 # Keep first parent +git revert -m 2 # Keep second parent + +# Revert multiple commits +git revert +git revert .. + +# Continue after resolving conflicts +git revert --continue + +# Abort revert +git revert --abort +``` + +### Reflog (Recovery) + +**reflog is your safety net - it tracks all HEAD movements for 90 days (default)** + +```bash +# View reflog +git reflog +git reflog show +git reflog show + +# More detailed reflog +git log -g # Reflog as log +git log -g --all + +# Find lost commits +git reflog --all +git fsck --lost-found + +# Recover deleted branch +git reflog # Find commit where branch existed +git branch + +# Recover from hard reset +git reflog # Find commit before reset +git reset --hard + +# Recover deleted commits +git cherry-pick + +# Reflog expiration (change retention) +git config gc.reflogExpire "90 days" +git config gc.reflogExpireUnreachable "30 days" +``` + +### Bisect (Find Bad Commits) + +```bash +# Start bisect +git bisect start + +# Mark current commit as bad +git bisect bad + +# Mark known good commit +git bisect good + +# Test each commit, then mark as good or bad +git bisect good # Current commit is good +git bisect bad # Current commit is bad + +# Automate with test script +git bisect run + +# Bisect shows the first bad commit + +# Finish bisect +git bisect reset + +# Skip commit if unable to test +git bisect skip +``` + +### Clean + +**⚠️ WARNING: clean permanently deletes untracked files!** + +```bash +# Show what would be deleted (dry run - ALWAYS do this first!) +git clean -n +git clean --dry-run + +# Delete untracked files +git clean -f + +# Delete untracked files and directories +git clean -fd + +# Delete untracked and ignored files +git clean -fdx + +# Interactive clean +git clean -i +``` + +### Worktrees + +```bash +# List worktrees +git worktree list + +# Add new worktree +git worktree add +git worktree add ../project-feature feature-branch + +# Add worktree for new branch +git worktree add -b + +# Remove worktree +git worktree remove + +# Prune stale worktrees +git worktree prune +``` + +### Submodules + +```bash +# Add submodule +git submodule add + +# Initialize submodules (after clone) +git submodule init +git submodule update + +# Clone with submodules +git clone --recurse-submodules + +# Update submodules +git submodule update --remote +git submodule update --init --recursive + +# Execute command in all submodules +git submodule foreach +git submodule foreach git pull origin main + +# Remove submodule +git submodule deinit +git rm +rm -rf .git/modules/ +``` + +--- + +## Dangerous Operations (High Risk) + +### Filter-Repo (History Rewriting) + +**⚠️ EXTREMELY DANGEROUS: Rewrites entire repository history!** + +```bash +# Install git-filter-repo (not built-in) +# pip install git-filter-repo + +# Remove file from all history +git filter-repo --path --invert-paths + +# Remove directory from all history +git filter-repo --path --invert-paths + +# Change author info +git filter-repo --name-callback 'return name.replace(b"Old Name", b"New Name")' +git filter-repo --email-callback 'return email.replace(b"old@email.com", b"new@email.com")' + +# Remove large files +git filter-repo --strip-blobs-bigger-than 10M + +# ⚠️ After filter-repo, force push required +git push --force --all +git push --force --tags +``` + +**Safety protocol for filter-repo:** + +```bash +echo "⚠️⚠️⚠️ EXTREME DANGER ⚠️⚠️⚠️" +echo "This operation will:" +echo " - Rewrite ENTIRE repository history" +echo " - Change ALL commit hashes" +echo " - Break all existing clones" +echo " - Require all team members to re-clone" +echo " - Cannot be undone after force push" +echo "" +echo "MANDATORY: Create full backup:" +git clone --mirror backup-$(date +%Y%m%d-%H%M%S) +echo "" +echo "Notify ALL team members before proceeding!" +echo "" +read -p "Type 'I UNDERSTAND THE RISKS' to continue: " confirm +if [[ "$confirm" != "I UNDERSTAND THE RISKS" ]]; then + echo "Cancelled." + exit 1 +fi +``` + +### Amend Pushed Commits + +**⚠️ DANGER: Changing pushed commits requires force push!** + +```bash +# Amend last commit +git commit --amend + +# Amend without changing message +git commit --amend --no-edit + +# Change author of last commit +git commit --amend --author="Name " + +# ⚠️ Force push required if already pushed +git push --force-with-lease +``` + +### Rewrite Multiple Commits + +**⚠️ DANGER: Interactive rebase on pushed commits!** + +```bash +# Interactive rebase +git rebase -i HEAD~5 + +# Change author of older commits +git rebase -i ^ +# Mark commit as "edit" +# When stopped: +git commit --amend --author="Name " --no-edit +git rebase --continue + +# ⚠️ Force push required +git push --force-with-lease +``` + +--- + +## Platform-Specific Workflows + +### GitHub + +**Pull Requests:** +```bash +# Install GitHub CLI +# https://cli.github.com/ + +# Create PR +gh pr create +gh pr create --title "Title" --body "Description" +gh pr create --base main --head feature-branch + +# List PRs +gh pr list + +# View PR +gh pr view +gh pr view + +# Check out PR locally +gh pr checkout + +# Review PR +gh pr review +gh pr review --approve +gh pr review --request-changes +gh pr review --comment + +# Merge PR +gh pr merge +gh pr merge --squash +gh pr merge --rebase +gh pr merge --merge + +# Close PR +gh pr close +``` + +**GitHub Actions:** +```yaml +# .github/workflows/ci.yml +name: CI +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Run tests + run: npm test +``` + +### Azure DevOps + +**Pull Requests:** +```bash +# Install Azure DevOps CLI +# https://docs.microsoft.com/en-us/cli/azure/install-azure-cli + +# Create PR +az repos pr create --title "Title" --description "Description" +az repos pr create --source-branch feature --target-branch main + +# List PRs +az repos pr list + +# View PR +az repos pr show --id + +# Complete PR +az repos pr update --id --status completed + +# Branch policies +az repos policy list +az repos policy create --config policy.json +``` + +**Azure Pipelines:** +```yaml +# azure-pipelines.yml +trigger: + - main +pool: + vmImage: 'ubuntu-latest' +steps: + - script: npm test + displayName: 'Run tests' +``` + +### Bitbucket + +**Pull Requests:** +```bash +# Create PR (via web or Bitbucket CLI) +bb pr create + +# Review PR +bb pr list +bb pr view + +# Merge PR +bb pr merge +``` + +**Bitbucket Pipelines:** +```yaml +# bitbucket-pipelines.yml +pipelines: + default: + - step: + script: + - npm test +``` + +### GitLab + +**Merge Requests:** +```bash +# Install GitLab CLI (glab) +# https://gitlab.com/gitlab-org/cli + +# Create MR +glab mr create +glab mr create --title "Title" --description "Description" + +# List MRs +glab mr list + +# View MR +glab mr view + +# Merge MR +glab mr merge + +# Close MR +glab mr close +``` + +**GitLab CI:** +```yaml +# .gitlab-ci.yml +stages: + - test +test: + stage: test + script: + - npm test +``` + +--- + +## Performance Optimization + +### Repository Maintenance + +```bash +# Garbage collection +git gc +git gc --aggressive # More thorough, slower + +# Prune unreachable objects +git prune + +# Verify repository +git fsck +git fsck --full + +# Optimize repository +git repack -a -d --depth=250 --window=250 + +# Git 2.51+: Path-walk repacking (generates smaller packs) +# More efficient delta compression by walking paths +git repack --path-walk -a -d + +# Count objects +git count-objects -v + +# Repository size +du -sh .git +``` + +### Large Files + +```bash +# Find large files in history +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 10 + +# Git LFS (Large File Storage) +git lfs install +git lfs track "*.psd" +git lfs track "*.zip" +git add .gitattributes +git add file.psd +git commit -m "Add large file" + +# List LFS files +git lfs ls-files + +# Fetch LFS files +git lfs fetch +git lfs pull +``` + +### Shallow Clones + +```bash +# Shallow clone (faster, less disk space) +git clone --depth 1 + +# Unshallow (convert to full clone) +git fetch --unshallow + +# Fetch more history +git fetch --depth=100 +``` + +--- + +## Tags and Releases + +### Creating Tags + +```bash +# Lightweight tag +git tag +git tag v1.0.0 + +# Annotated tag (recommended - includes metadata) +git tag -a -m "message" +git tag -a v1.0.0 -m "Release version 1.0.0" + +# Tag specific commit +git tag -a + +# Signed tag (GPG signature) +git tag -s -m "message" +``` + +### Managing Tags + +```bash +# List tags +git tag +git tag -l "v1.*" # Pattern matching + +# Show tag info +git show + +# Delete local tag +git tag -d + +# Delete remote tag +git push origin --delete +git push origin :refs/tags/ + +# Push tags +git push origin +git push --tags # All tags +git push --follow-tags # Only annotated tags +``` + +--- + +## Git Hooks + +### Client-Side Hooks + +```bash +# Hooks location: .git/hooks/ + +# pre-commit: Run before commit +# Example: .git/hooks/pre-commit +#!/bin/bash +npm run lint || exit 1 + +# prepare-commit-msg: Edit commit message before editor opens +# commit-msg: Validate commit message +#!/bin/bash +msg=$(cat "$1") +if ! echo "$msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore):"; then + echo "Error: Commit message must start with type (feat|fix|docs|...):" + exit 1 +fi + +# post-commit: Run after commit +# pre-push: Run before push +# post-checkout: Run after checkout +# post-merge: Run after merge + +# Make hook executable +chmod +x .git/hooks/pre-commit +``` + +### Server-Side Hooks + +```bash +# pre-receive: Run before refs are updated +# update: Run for each branch being updated +# post-receive: Run after refs are updated + +# Example: Reject force pushes +#!/bin/bash +while read oldrev newrev refname; do + if [ "$oldrev" != "0000000000000000000000000000000000000000" ]; then + if ! git merge-base --is-ancestor "$oldrev" "$newrev"; then + echo "Error: Force push rejected" + exit 1 + fi + fi +done +``` + +--- + +## Troubleshooting and Recovery + +### Common Problems + +**Detached HEAD:** +```bash +# You're in detached HEAD state +git branch temp # Create branch at current commit +git switch main +git merge temp +git branch -d temp +``` + +**Merge conflicts:** +```bash +# During merge/rebase +git status # See conflicted files +# Edit files to resolve conflicts +git add +git merge --continue # or git rebase --continue + +# Abort and start over +git merge --abort +git rebase --abort +``` + +**Accidentally deleted branch:** +```bash +# Find branch in reflog +git reflog +# Create branch at commit +git branch +``` + +**Committed to wrong branch:** +```bash +# Move commit to correct branch +git switch correct-branch +git cherry-pick +git switch wrong-branch +git reset --hard HEAD~1 # Remove from wrong branch +``` + +**Pushed sensitive data:** +```bash +# ⚠️ URGENT: Remove from history immediately +git filter-repo --path --invert-paths +git push --force --all +# Then: Rotate compromised credentials immediately! +``` + +**Large commit by mistake:** +```bash +# Before pushing +git reset --soft HEAD~1 +git reset HEAD +git commit -m "message" + +# After pushing - use filter-repo or BFG +``` + +### Recovery Scenarios + +**Recover after hard reset:** +```bash +git reflog +git reset --hard +``` + +**Recover deleted file:** +```bash +git log --all --full-history -- +git checkout ^ -- +``` + +**Recover deleted commits:** +```bash +git reflog # Find commit hash +git cherry-pick +# or +git merge +# or +git reset --hard +``` + +**Recover from corrupted repository:** +```bash +# Verify corruption +git fsck --full + +# Attempt repair +git gc --aggressive + +# Last resort: clone from remote +``` + +--- + +## Best Practices + +### Commit Messages + +**Conventional Commits format:** +``` +(): + + + +