git-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Expert Skill

Git 专家技能

Installation

安装

The skill invokes the
git
CLI. Install Git if not present:
  • Windows: Download from git-scm.com or
    winget install --id Git.Git -e --source winget
  • macOS:
    brew install git
    or Xcode CLI tools:
    xcode-select --install
  • Linux:
    apt-get install git
    (Debian/Ubuntu),
    dnf install git
    (Fedora),
    pacman -S git
    (Arch)
Verify:
git --version
该技能会调用
git
CLI。如果未安装Git,请按以下方式安装:
  • Windows:从git-scm.com下载,或执行
    winget install --id Git.Git -e --source winget
  • macOS:执行
    brew install git
    ,或安装Xcode CLI工具:
    xcode-select --install
  • Linux
    apt-get install git
    (Debian/Ubuntu),
    dnf install git
    (Fedora),
    pacman -S git
    (Arch)
验证安装:
git --version

Cheat Sheet & Best Practices

速查表与最佳实践

Essential commands (token-efficient):
  • git status -s
    — short status;
    git add -p
    — stage hunks;
    git diff --cached
    — review staged
  • git switch -c <branch>
    or
    git checkout -b <branch>
    — new branch;
    git branch
    — list
  • git log --oneline -5
    — compact history;
    git log --follow <file>
    — track renames
  • git restore <file>
    — discard unstaged;
    git reset --soft HEAD~1
    — undo last commit (keep changes)
  • git fetch
    then
    git merge
    or
    git pull
    — prefer fetch+merge over blind pull
Hacks: Set
git config --global color.ui auto
and
user.name
/
user.email
. Use
.gitignore
aggressively. Prefer
git merge --squash
for clean history on feature merge. Use
git cherry-pick <commit>
to bring single commits. Never rebase pushed commits without team agreement.
高效令牌的核心命令:
  • 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
    git pull
    — 优先使用fetch+merge而非直接pull
技巧: 设置
git config --global color.ui auto
以及
user.name
/
user.email
。灵活使用
.gitignore
。合并功能分支时优先使用
git merge --squash
以保持历史整洁。使用
git cherry-pick <commit>
迁移单个提交。未经团队同意,绝不要对已推送的提交执行rebase操作。

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
commit-validator
(conventional commits). Pre-push: run tests (reference
tdd
/
verification-before-completion
). Post-merge: optional memory/learnings update.
Workflows: 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
.claude/workflows
for feature-development and code-review workflows that use git-expert.
推荐钩子: 提交前:运行
commit-validator
(符合约定式提交规范)。推送前:运行测试(参考
tdd
/
verification-before-completion
)。合并后:可选的记忆/学习记录更新。
工作流: 主要与开发人员配合,也适用于DevOps。流程:分支→编辑→暂存→验证提交信息→提交→推送;使用github-opsgithub-mcp创建PR。查看
.claude/workflows
了解使用git-expert的功能开发与代码评审工作流。

⚡ Token-Efficient Workflow

⚡ 高效令牌工作流

Do not use
git status
repeatedly. Use this workflow:
  1. Check State:
    git status -s
    (Short format saves tokens)
  2. Diff:
    git diff --cached
    (Only check what you are about to commit)
  3. Log:
    git log --oneline -5
    (Context without the noise)
不要重复使用
git status
。请遵循以下工作流:
  1. 检查状态
    git status -s
    (简洁格式节省令牌)
  2. 对比差异
    git diff --cached
    (仅查看即将提交的内容)
  3. 查看日志
    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~1
bash
git reset --soft HEAD~1

Fix Merge Conflict

修复合并冲突

  1. git status
    to see conflict files.
  2. Edit file to resolve markers (
    <<<<
    ,
    ====
    ,
    >>>>
    ).
  3. git add <file>
  4. git commit --no-edit
  1. git status
    查看冲突文件。
  2. 编辑文件解决冲突标记(
    <<<<
    ,
    ====
    ,
    >>>>
    )。
  3. git add <file>
  4. git commit --no-edit

Iron Laws

铁律

  1. NEVER use
    git push --force
    on shared branches — force-pushing rewrites history for all collaborators, causes lost commits, and breaks in-progress rebases silently; use
    --force-with-lease
    when truly necessary.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  1. 绝对不要在共享分支上使用
    git push --force
    —— 强制推送会重写所有协作者的历史记录,导致提交丢失,且会静默破坏正在进行的rebase分支;确实需要时请使用
    --force-with-lease
  2. 绝对不要提交密钥、凭证或令牌到仓库 —— 一旦推送,即使从HEAD中删除,这些信息也会永久保留在所有分支和克隆的历史记录中。
  3. 必须在推送到共享分支前运行测试套件并确保通过 —— 共享分支中的损坏代码会阻塞所有人,并触发紧急回滚。
  4. 必须在合并前将功能分支rebase到基准分支上 —— 基于陈旧基准合并会产生可避免的冲突,并在共享历史中留下杂乱的合并提交。
  5. 绝对不要对已推送到共享远程仓库的提交执行rebase或重写历史 —— 队友的本地分支会出现分歧,下次拉取时会产生重复提交。

Anti-Patterns

反模式

Anti-PatternWhy It FailsCorrect Approach
git push --force
on shared branches
Overwrites teammates' commits; destroys in-progress rebase branchesUse
--force-with-lease
for personal branches only; never on main/develop
Committing
.env
or credentials
Permanently visible in history even after deletion; requires key rotationAdd sensitive files to
.gitignore
; use pre-commit secret-scanning hooks
Long-lived feature branches (>5 days)Massive merge conflicts; integration bugs discovered too lateUse short-lived branches with daily rebases onto main (trunk-based dev)
git commit -m "fix"
or
wip
messages
Makes
git log
useless for bisect and changelog generation
Use conventional commits:
fix: resolve null pointer in user auth
Merging without pulling latest baseStale merge base; CI catches conflicts only after the merge lands
git fetch && git rebase origin/main
before any merge or PR
反模式失败原因正确做法
在共享分支上使用
git push --force
覆盖队友的提交;破坏正在进行的rebase分支仅在个人分支使用
--force-with-lease
;绝对不要在main/develop分支使用
提交
.env
或凭证文件
即使删除后也会永久保留在历史中;需要轮换密钥将敏感文件添加到
.gitignore
;使用提交前的密钥扫描钩子
长期存在的功能分支(超过5天)大量合并冲突;集成问题发现过晚使用短期分支,每天rebase到main分支(基于主干的开发)
使用
git commit -m "fix"
wip
作为提交信息
使
git log
在二分查找和生成变更日志时毫无用处
使用约定式提交:
fix: resolve null pointer in user auth
未拉取最新基准就合并合并基准陈旧;CI仅在合并后才发现冲突任何合并或PR前执行
git fetch && git rebase origin/main

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
files
reference format with a binary format that is faster, atomic, and storage-efficient:
Benefits:
  • 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-repo
Check current backend:
bash
git rev-parse --show-ref-format
Reftable后端完全取代了传统的
files
引用格式,采用二进制格式,速度更快、支持原子操作且存储效率更高:
优势:
  • 原子化多引用更新(要么全部成功要么全部失败)
  • 更快的单引用查找和引用范围遍历
  • 一致性读取 —— 永远不会读取到部分更新的状态
  • 更高效的reflog存储
为新仓库启用:
bash
git init --ref-format=reftable my-repo
检查当前后端:
bash
git rev-parse --show-ref-format

outputs: 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
undefined

Generate 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
undefined

Clone 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/payments
Cone mode vs. non-cone mode:
ModePattern MatchingPerformance
Cone (recommended)Directory prefix onlyFast (O(log n) path matching)
Non-coneFull gitignore-style patternsSlow 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
undefined
Scalar是Git自带的仓库管理工具(从Git 2.38开始),可自动配置和维护所有推荐的性能设置:
bash
undefined

Clone a large repo with all performance features enabled

克隆大型仓库并启用所有性能特性

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 index
scalar 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
undefined
SSH密钥签名比GPG更简单,可使用你已用于认证的密钥:
bash
undefined

Configure 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:**

```bash
git 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-signature
GitHub verification: Add your SSH signing key to GitHub under
Settings > SSH and GPG keys > New SSH key > Signing Key
. Commits signed with that key will show "Verified" on GitHub.
FIDO2 / hardware security key signing:
bash
undefined
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-signature
GitHub验证: 在GitHub的
Settings > SSH and GPG keys > New SSH key > Signing Key
中添加你的SSH签名密钥。使用该密钥签名的提交会在GitHub上显示“已验证”。
FIDO2 / 硬件安全密钥签名:
bash
undefined

Generate 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
undefined
ssh-keygen -t ed25519-sk -O resident -f ~/.ssh/id_ed25519_sk_fido2 git config --global user.signingKey ~/.ssh/id_ed25519_sk_fido2.pub
undefined

Improved Merge Strategies (Git 2.38+
ort
)

改进的合并策略(Git 2.38+
ort

The
ort
merge strategy has been the default since Git 2.34. It is significantly faster than
recursive
for large trees and more deterministic:
bash
undefined
ort
合并策略从Git 2.34开始成为默认策略。对于大型树结构,它比
recursive
快得多且更具确定性:
bash
undefined

ort 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
undefined
git config --global merge.conflictStyle zdiff3
undefined

Performance Commands for Large Repos

大型仓库的性能命令

bash
undefined
bash
undefined

Enable 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
undefined
GIT_TRACE_PERFORMANCE=1 git status
undefined

Related Skills

相关技能

  • gitflow
    - Branch workflow patterns (feature, release, hotfix branches)
  • gitflow
    - 分支工作流模式(功能、发布、热修复分支)

Memory Protocol (MANDATORY)

记忆协议(强制要求)

Before starting: Read
.claude/context/memory/learnings.md
After 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
假设会被中断:如果未记录在记忆中,就视为未发生。