git-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGit Expert Skill
Git 专家技能
Installation
安装
The skill invokes the CLI. Install Git if not present:
git- Windows: Download from git-scm.com or
winget install --id Git.Git -e --source winget - macOS: or Xcode CLI tools:
brew install gitxcode-select --install - Linux: (Debian/Ubuntu),
apt-get install git(Fedora),dnf install git(Arch)pacman -S git
Verify:
git --version该技能会调用 CLI。如果未安装Git,请按以下方式安装:
git- Windows:从git-scm.com下载,或执行
winget install --id Git.Git -e --source winget - macOS:执行,或安装Xcode CLI工具:
brew install gitxcode-select --install - Linux:(Debian/Ubuntu),
apt-get install git(Fedora),dnf install git(Arch)pacman -S git
验证安装:
git --versionCheat Sheet & Best Practices
速查表与最佳实践
Essential commands (token-efficient):
- — short status;
git status -s— stage hunks;git add -p— review stagedgit diff --cached - or
git switch -c <branch>— new branch;git checkout -b <branch>— listgit branch - — compact history;
git log --oneline -5— track renamesgit log --follow <file> - — discard unstaged;
git restore <file>— undo last commit (keep changes)git reset --soft HEAD~1 - then
git fetchorgit merge— prefer fetch+merge over blind pullgit pull
Hacks: Set and /. Use aggressively. Prefer for clean history on feature merge. Use to bring single commits. Never rebase pushed commits without team agreement.
git config --global color.ui autouser.nameuser.email.gitignoregit merge --squashgit cherry-pick <commit>高效令牌的核心命令:
- — 简洁状态展示;
git status -s— 分块暂存;git add -p— 查看已暂存内容git diff --cached - 或
git switch -c <branch>— 创建新分支;git checkout -b <branch>— 列出分支git branch - — 紧凑提交历史;
git log --oneline -5— 追踪文件重命名git log --follow <file> - — 丢弃未暂存修改;
git restore <file>— 撤销最后一次提交(保留修改)git reset --soft HEAD~1 - 后执行
git fetch或git merge— 优先使用fetch+merge而非直接pullgit pull
技巧: 设置以及/。灵活使用。合并功能分支时优先使用以保持历史整洁。使用迁移单个提交。未经团队同意,绝不要对已推送的提交执行rebase操作。
git config --global color.ui autouser.nameuser.email.gitignoregit merge --squashgit cherry-pick <commit>Certifications & Training
认证与培训
Free / official: Atlassian Git Tutorials (beginner–advanced). Microsoft Learn – GitHub Training (GitHub Foundations path). GitHub Learn (Git + GitHub). No single “Git cert”; GitHub Foundations aligns with fundamentals.
Skill data: Focus on branching, undo (reset/restore/revert), merge vs rebase, remote workflow, and safety (no force-push, no secrets).
免费/官方资源: Atlassian Git教程(从入门到进阶)。Microsoft Learn – GitHub 培训(GitHub基础路径)。GitHub Learn(Git + GitHub)。目前没有统一的“Git认证”;GitHub基础认证与核心知识对齐。
技能重点: 分支管理、撤销操作(reset/restore/revert)、merge与rebase对比、远程工作流、安全规范(禁止强制推送、禁止提交密钥)。
Hooks & Workflows
钩子与工作流
Suggested hooks: Pre-commit: run (conventional commits). Pre-push: run tests (reference / ). Post-merge: optional memory/learnings update.
commit-validatortddverification-before-completionWorkflows: Use with developer (primary), devops (always). Flow: branch → edit → add → validate commit message → commit → push; use github-ops or github-mcp for PR/create. See for feature-development and code-review workflows that use git-expert.
.claude/workflows推荐钩子: 提交前:运行(符合约定式提交规范)。推送前:运行测试(参考 / )。合并后:可选的记忆/学习记录更新。
commit-validatortddverification-before-completion工作流: 主要与开发人员配合,也适用于DevOps。流程:分支→编辑→暂存→验证提交信息→提交→推送;使用github-ops或github-mcp创建PR。查看了解使用git-expert的功能开发与代码评审工作流。
.claude/workflows⚡ Token-Efficient Workflow
⚡ 高效令牌工作流
Do not use repeatedly. Use this workflow:
git status- Check State: (Short format saves tokens)
git status -s - Diff: (Only check what you are about to commit)
git diff --cached - Log: (Context without the noise)
git log --oneline -5
不要重复使用。请遵循以下工作流:
git status- 检查状态:(简洁格式节省令牌)
git status -s - 对比差异:(仅查看即将提交的内容)
git diff --cached - 查看日志:(获取上下文且无冗余信息)
git log --oneline -5
🔄 Common Patterns
🔄 常见模式
Safe Commit
安全提交
bash
git add <file>
git diff --cached # REVIEW THIS!
git commit -m "feat: description"bash
git add <file>
git diff --cached # 务必检查!
git commit -m "feat: description"Undo Last Commit (Soft)
软撤销最后一次提交
bash
git reset --soft HEAD~1bash
git reset --soft HEAD~1Fix Merge Conflict
修复合并冲突
- to see conflict files.
git status - Edit file to resolve markers (,
<<<<,====).>>>> git add <file>git commit --no-edit
- 查看冲突文件。
git status - 编辑文件解决冲突标记(,
<<<<,====)。>>>> git add <file>git commit --no-edit
Iron Laws
铁律
- NEVER use on shared branches — force-pushing rewrites history for all collaborators, causes lost commits, and breaks in-progress rebases silently; use
git push --forcewhen truly necessary.--force-with-lease - NEVER commit secrets, credentials, or tokens to the repository — once pushed, secrets are visible in all forks and clones forever even after deletion from HEAD.
- ALWAYS run the test suite and verify it passes before pushing to shared branches — broken code in shared branches blocks everyone and triggers emergency rollbacks.
- ALWAYS rebase feature branches onto the base branch before merging — merging with a stale base creates avoidable conflicts and produces noisy merge commits in shared history.
- NEVER rebase or rewrite history on commits that have already been pushed to a shared remote — teammates' local branches will diverge and produce duplicate commits on next pull.
- 绝对不要在共享分支上使用—— 强制推送会重写所有协作者的历史记录,导致提交丢失,且会静默破坏正在进行的rebase分支;确实需要时请使用
git push --force。--force-with-lease - 绝对不要提交密钥、凭证或令牌到仓库 —— 一旦推送,即使从HEAD中删除,这些信息也会永久保留在所有分支和克隆的历史记录中。
- 必须在推送到共享分支前运行测试套件并确保通过 —— 共享分支中的损坏代码会阻塞所有人,并触发紧急回滚。
- 必须在合并前将功能分支rebase到基准分支上 —— 基于陈旧基准合并会产生可避免的冲突,并在共享历史中留下杂乱的合并提交。
- 绝对不要对已推送到共享远程仓库的提交执行rebase或重写历史 —— 队友的本地分支会出现分歧,下次拉取时会产生重复提交。
Anti-Patterns
反模式
| Anti-Pattern | Why It Fails | Correct Approach |
|---|---|---|
| Overwrites teammates' commits; destroys in-progress rebase branches | Use |
Committing | Permanently visible in history even after deletion; requires key rotation | Add sensitive files to |
| Long-lived feature branches (>5 days) | Massive merge conflicts; integration bugs discovered too late | Use short-lived branches with daily rebases onto main (trunk-based dev) |
| Makes | Use conventional commits: |
| Merging without pulling latest base | Stale merge base; CI catches conflicts only after the merge lands | |
| 反模式 | 失败原因 | 正确做法 |
|---|---|---|
在共享分支上使用 | 覆盖队友的提交;破坏正在进行的rebase分支 | 仅在个人分支使用 |
提交 | 即使删除后也会永久保留在历史中;需要轮换密钥 | 将敏感文件添加到 |
| 长期存在的功能分支(超过5天) | 大量合并冲突;集成问题发现过晚 | 使用短期分支,每天rebase到main分支(基于主干的开发) |
使用 | 使 | 使用约定式提交: |
| 未拉取最新基准就合并 | 合并基准陈旧;CI仅在合并后才发现冲突 | 任何合并或PR前执行 |
Git 2.45–2.50 Features (2024–2025)
Git 2.45–2.50 新特性(2024–2025)
Reftable Backend (Git 2.45+)
Reftable 后端(Git 2.45+)
The reftable backend completely replaces the legacy reference format with a binary format that is faster, atomic, and storage-efficient:
filesBenefits:
- Atomic multi-ref updates (all-or-nothing transactions)
- Faster single-ref lookup and iteration over ref ranges
- Consistent reads — never reads a partial update state
- More efficient reflog storage
Enable for a new repository:
bash
git init --ref-format=reftable my-repoCheck current backend:
bash
git rev-parse --show-ref-formatReftable后端完全取代了传统的引用格式,采用二进制格式,速度更快、支持原子操作且存储效率更高:
files优势:
- 原子化多引用更新(要么全部成功要么全部失败)
- 更快的单引用查找和引用范围遍历
- 一致性读取 —— 永远不会读取到部分更新的状态
- 更高效的reflog存储
为新仓库启用:
bash
git init --ref-format=reftable my-repo检查当前后端:
bash
git rev-parse --show-ref-formatoutputs: files OR reftable
输出:files 或 reftable
**Migration note:** Converting an existing repo from `files` to `reftable` requires re-cloning or using `git clone --ref-format=reftable`. Clients using `files` repos are unaffected — the backend is server/local only.
**迁移说明:** 将现有仓库从`files`转换为`reftable`需要重新克隆,或使用`git clone --ref-format=reftable`。使用`files`格式的客户端不受影响 —— 后端仅作用于服务器/本地仓库。Incremental Multi-Pack Indexes (Git 2.47+)
增量多包索引(Git 2.47+)
Multi-pack indexes (MIDXs) allow Git to maintain a single index across multiple packfiles without repacking. Git 2.47 adds incremental MIDX updates — only newly added packs are indexed rather than rebuilding the full MIDX:
bash
undefined多包索引(MIDX)允许Git在多个包文件上维护单个索引而无需重新打包。Git 2.47新增了增量MIDX更新 —— 仅索引新添加的包,而非重建完整的MIDX:
bash
undefinedGenerate or update multi-pack index
生成或更新多包索引
git multi-pack-index write --stdin-packs
git multi-pack-index write --stdin-packs
Verify the MIDX
验证MIDX
git multi-pack-index verify
git multi-pack-index verify
Enable via maintenance
通过维护任务启用
git maintenance start
**Multi-pack reachability bitmaps** extend MIDX with precomputed reachability data, dramatically speeding up `git clone`, `git fetch`, and garbage collection on large repositories.git maintenance start
**多包可达性位图**扩展了MIDX,预计算了可达性数据,大幅加快了大型仓库的`git clone`、`git fetch`和垃圾回收速度。Sparse Checkout for Monorepos (Git 2.25+ cone mode)
单体仓库的稀疏检出(Git 2.25+ 锥形模式)
Sparse checkout lets you check out only the directories you need from a large monorepo:
bash
undefined稀疏检出允许你仅从大型单体仓库中检出所需的目录:
bash
undefinedClone without checking out any files
克隆时不检出任何文件
git clone --no-checkout --filter=blob:none https://github.com/org/monorepo.git
cd monorepo
git clone --no-checkout --filter=blob:none https://github.com/org/monorepo.git
cd monorepo
Initialize in cone mode (recommended — uses fast prefix matching)
以锥形模式初始化(推荐 —— 使用快速前缀匹配)
git sparse-checkout init --cone
git sparse-checkout init --cone
Check out only specific directories
仅检出特定目录
git sparse-checkout set frontend docs shared/utils
git sparse-checkout set frontend docs shared/utils
See what is currently checked out
查看当前已检出的内容
git sparse-checkout list
git sparse-checkout list
Add more directories without losing current ones
添加更多目录而不丢失现有内容
git sparse-checkout add backend/api
git sparse-checkout add backend/api
Disable sparse checkout (restore full working tree)
禁用稀疏检出(恢复完整工作区)
git sparse-checkout disable
**One-command clone (Git 2.25+):**
```bash
git clone --filter=blob:none --sparse https://github.com/org/monorepo.git
cd monorepo
git sparse-checkout set services/paymentsCone mode vs. non-cone mode:
| Mode | Pattern Matching | Performance |
|---|---|---|
| Cone (recommended) | Directory prefix only | Fast (O(log n) path matching) |
| Non-cone | Full gitignore-style patterns | Slow on large trees |
git sparse-checkout disable
**一键克隆(Git 2.25+):**
```bash
git clone --filter=blob:none --sparse https://github.com/org/monorepo.git
cd monorepo
git sparse-checkout set services/payments锥形模式 vs 非锥形模式:
| 模式 | 匹配规则 | 性能 |
|---|---|---|
| 锥形(推荐) | 仅目录前缀 | 快速(O(log n)路径匹配) |
| 非锥形 | 完整gitignore风格匹配 | 大型树结构下速度较慢 |
Git Scalar — Large Repository Optimization
Git Scalar —— 大型仓库优化
Scalar is a repository management tool bundled with Git (since Git 2.38) that configures and maintains all recommended performance settings automatically:
bash
undefinedScalar是Git自带的仓库管理工具(从Git 2.38开始),可自动配置和维护所有推荐的性能设置:
bash
undefinedClone a large repo with all performance features enabled
克隆大型仓库并启用所有性能特性
scalar clone https://github.com/org/large-monorepo.git
scalar clone https://github.com/org/large-monorepo.git
Register an existing repo with Scalar
将现有仓库注册到Scalar
scalar register
scalar register
Run all maintenance tasks manually
手动运行所有维护任务
scalar run all
scalar run all
View configured enlistments
查看已配置的仓库
scalar list
**What Scalar configures automatically:**
- Partial clone (`--filter=blob:none`)
- Sparse checkout (cone mode)
- File system monitor (`core.fsmonitor`)
- Commit graph generation
- Background maintenance (hourly fetch, daily gc)
- Multi-pack indexscalar list
**Scalar自动配置的内容:**
- 部分克隆(`--filter=blob:none`)
- 稀疏检出(锥形模式)
- 文件系统监视器(`core.fsmonitor`)
- 提交图生成
- 后台维护(每小时拉取,每日垃圾回收)
- 多包索引Sign Commits with SSH Keys (Git 2.34+)
使用SSH密钥签名提交(Git 2.34+)
SSH key signing is simpler than GPG and works with keys you already use for authentication:
bash
undefinedSSH密钥签名比GPG更简单,可使用你已用于认证的密钥:
bash
undefinedConfigure SSH signing globally
全局配置SSH签名
git config --global gpg.format ssh
git config --global user.signingKey ~/.ssh/id_ed25519.pub
git config --global gpg.format ssh
git config --global user.signingKey ~/.ssh/id_ed25519.pub
Sign all commits automatically
自动签名所有提交
git config --global commit.gpgSign true
git config --global commit.gpgSign true
Or sign a single commit manually
或手动签名单个提交
git commit -S -m "feat: add payment service"
git commit -S -m "feat: add payment service"
Verify a commit
验证提交
git verify-commit HEAD
**Set up an allowed-signers file for team verification:**
```bashgit verify-commit HEAD
**为团队验证设置允许签名者文件:**
```bash~/.config/git/allowed_signers
~/.config/git/allowed_signers
alice@example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA...
bob@example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA...
```bash
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
git log --show-signatureGitHub verification: Add your SSH signing key to GitHub under . Commits signed with that key will show "Verified" on GitHub.
Settings > SSH and GPG keys > New SSH key > Signing KeyFIDO2 / hardware security key signing:
bash
undefinedalice@example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA...
bob@example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA...
```bash
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
git log --show-signatureGitHub验证: 在GitHub的中添加你的SSH签名密钥。使用该密钥签名的提交会在GitHub上显示“已验证”。
Settings > SSH and GPG keys > New SSH key > Signing KeyFIDO2 / 硬件安全密钥签名:
bash
undefinedGenerate a resident key on a FIDO2 security key (e.g., YubiKey)
在FIDO2安全密钥(如YubiKey)上生成驻留密钥
ssh-keygen -t ed25519-sk -O resident -f ~/.ssh/id_ed25519_sk_fido2
git config --global user.signingKey ~/.ssh/id_ed25519_sk_fido2.pub
undefinedssh-keygen -t ed25519-sk -O resident -f ~/.ssh/id_ed25519_sk_fido2
git config --global user.signingKey ~/.ssh/id_ed25519_sk_fido2.pub
undefinedImproved Merge Strategies (Git 2.38+ ort
)
ort改进的合并策略(Git 2.38+ ort
)
ortThe merge strategy has been the default since Git 2.34. It is significantly faster than for large trees and more deterministic:
ortrecursivebash
undefinedortrecursivebash
undefinedort is the default; explicitly select if needed
ort是默认策略;如需可显式指定
git merge -s ort feature/my-feature
git merge -s ort feature/my-feature
Rename detection threshold (default 50%)
重命名检测阈值(默认50%)
git merge -X rename-threshold=80 feature/rename-heavy-branch
git merge -X rename-threshold=80 feature/rename-heavy-branch
Conflict style: diff3 (shows common ancestor) — strongly recommended
冲突样式:diff3(显示公共祖先)—— 强烈推荐
git config --global merge.conflictStyle diff3
git config --global merge.conflictStyle diff3
Or zdiff3 (even cleaner context in conflicts, Git 2.35+)
或zdiff3(冲突上下文更清晰,Git 2.35+)
git config --global merge.conflictStyle zdiff3
undefinedgit config --global merge.conflictStyle zdiff3
undefinedPerformance Commands for Large Repos
大型仓库的性能命令
bash
undefinedbash
undefinedEnable file system monitor (avoids scanning entire tree for status)
启用文件系统监视器(避免扫描整个树结构获取状态)
git config core.fsmonitor true
git config core.untrackedCache true
git config core.fsmonitor true
git config core.untrackedCache true
Precompute commit graph for faster log/blame
预计算提交图以加快log/blame速度
git commit-graph write --reachable --changed-paths
git config fetch.writeCommitGraph true
git commit-graph write --reachable --changed-paths
git config fetch.writeCommitGraph true
Partial clone — skip large blobs on clone, fetch on demand
部分克隆 —— 克隆时跳过大型blob,按需获取
git clone --filter=blob:none <url>
git clone --filter=blob:none <url>
Shallow clone (CI use case — last N commits only)
浅克隆(CI场景 —— 仅最后N次提交)
git clone --depth=1 <url>
git clone --depth=1 <url>
Check repository health and performance
检查仓库健康状况与性能
GIT_TRACE_PERFORMANCE=1 git status
undefinedGIT_TRACE_PERFORMANCE=1 git status
undefinedRelated Skills
相关技能
- - Branch workflow patterns (feature, release, hotfix branches)
gitflow
- - 分支工作流模式(功能、发布、热修复分支)
gitflow
Memory Protocol (MANDATORY)
记忆协议(强制要求)
Before starting:
Read
.claude/context/memory/learnings.mdAfter completing:
- New pattern ->
.claude/context/memory/learnings.md - Issue found ->
.claude/context/memory/issues.md - Decision made ->
.claude/context/memory/decisions.md
ASSUME INTERRUPTION: If it's not in memory, it didn't happen.
开始前:
阅读
.claude/context/memory/learnings.md完成后:
- 新模式 ->
.claude/context/memory/learnings.md - 发现问题 ->
.claude/context/memory/issues.md - 决策记录 ->
.claude/context/memory/decisions.md
假设会被中断:如果未记录在记忆中,就视为未发生。