git-master

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Mastery - Complete Git Expertise

Git精通 - 完整Git专业指南

🚨 CRITICAL GUIDELINES

🚨 关键指南

Windows File Path Requirements

Windows文件路径要求

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
强制要求:Windows系统中文件路径必须使用反斜杠
在Windows系统中使用编辑或写入工具时,文件路径必须使用反斜杠(
\
),而非正斜杠(
/
)。
示例:
  • ❌ 错误:
    D:/repos/project/file.tsx
  • ✅ 正确:
    D:\repos\project\file.tsx
此要求适用于:
  • 编辑工具的file_path参数
  • 写入工具的file_path参数
  • Windows系统上的所有文件操作

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.

除非用户明确要求,否则绝不创建新的文档文件。
  • 优先级:优先更新现有README.md文件,而非创建新文档
  • 仓库整洁性:保持仓库根目录整洁 - 除非用户要求,否则仅保留README.md
  • 风格:文档应简洁、直接、专业 - 避免AI生成的生硬语气
  • 用户偏好:仅当用户明确要求文档时,才创建额外的.md文件

涵盖从基础到高级的所有Git操作的综合指南,包括带有安全防护机制的高风险操作。

TL;DR QUICK REFERENCE

快速参考(TL;DR)

Safety First - Before ANY Destructive Operation:
bash
undefined
安全第一 - 执行任何破坏性操作前:
bash
undefined

ALWAYS check status first

始终先检查状态

git status git log --oneline -10
git status git log --oneline -10

For risky operations, create a safety branch

对于高风险操作,创建安全分支

git branch backup-$(date +%Y%m%d-%H%M%S)
git branch backup-$(date +%Y%m%d-%H%M%S)

Remember: git reflog is your safety net (90 days default)

记住:git reflog是你的安全网(默认保留90天)

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

---
git reflog

**用户偏好确认:**
- **必须询问:** "你希望我自动创建提交,还是你手动控制提交?"
- 在整个会话过程中尊重用户的选择

---

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)

本技能为任何Git操作提供完整的专业知识支持,无论操作是基础、小众还是高风险。涵盖内容包括:
必须使用本技能的场景:
  • ✅ 任何Git命令或操作
  • ✅ 仓库初始化、克隆、配置
  • ✅ 分支管理与策略
  • ✅ 提交工作流与最佳实践
  • ✅ 合并策略与冲突解决
  • ✅ Rebase操作(交互式与非交互式)
  • ✅ 历史重写(filter-repo、reset、revert)
  • ✅ 恢复操作(reflog、fsck)
  • ✅ 高风险操作(强制推送、硬重置)
  • ✅ 平台专属工作流(GitHub、Azure DevOps、Bitbucket)
  • ✅ 高级功能(子模块、工作树、钩子)
  • ✅ 性能优化
  • ✅ 跨平台兼容性(Windows/Linux/macOS)

Core Principles

核心原则

1. Safety Guardrails for Destructive Operations

1. 破坏性操作的安全防护机制

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
undefined
关键:执行任何破坏性操作(reset --hard、强制推送、filter-repo等)前:
  1. 必须明确警告用户
  2. 清晰解释风险
  3. 请求确认
  4. 建议先创建备份分支
  5. 提供恢复说明
bash
undefined

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
undefined
echo "⚠️ 警告:此操作具有破坏性,将:" echo " - 永久删除未提交的更改" echo " - 重写Git历史" echo " - [该操作的特定风险]" echo "" echo "安全建议:先创建备份分支..." git branch backup-before-reset-$(date +%Y%m%d-%H%M%S) echo "" echo "如需恢复:git reset --hard backup-before-reset-XXXXXXXX" echo "" read -p "你确定要继续吗?(yes/NO): " confirm if [[ "$confirm" != "yes" ]]; then echo "操作已取消。" exit 1 fi
undefined

2. Commit Creation Policy

2. 提交创建规则

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.
在任何Git任务开始时必须询问: "你希望我:
  1. 使用合适的消息自动创建提交
  2. 仅暂存更改(你手动处理提交)
  3. 仅提供指导(不执行自动操作)"
在整个会话过程中尊重用户的选择。

3. Platform Awareness

3. 平台适配性

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

Git的行为和工作流因平台和托管服务商而异:
Windows(Git Bash/PowerShell):
  • 行尾处理(core.autocrlf)
  • 路径分隔符与大小写敏感性
  • 凭据管理(Windows凭据管理器)
Linux/macOS:
  • 大小写敏感的文件系统
  • SSH密钥管理
  • 权限处理
托管平台:
  • GitHub:拉取请求、GitHub Actions、GitHub CLI
  • Azure DevOps:拉取请求、Azure Pipelines、策略
  • Bitbucket:拉取请求、Bitbucket Pipelines、Jira集成
  • GitLab:合并请求、GitLab CI/CD

Basic Git Operations

基础Git操作

Repository Initialization and Cloning

仓库初始化与克隆

bash
undefined
bash
undefined

Initialize new repository

初始化新仓库

git init git init --initial-branch=main # Specify default branch name
git init git init --initial-branch=main # 指定默认分支名称

Clone repository

克隆仓库

git clone <url> git clone <url> <directory> git clone --depth 1 <url> # Shallow clone (faster, less history) git clone --branch <branch> <url> # Clone specific branch git clone --recurse-submodules <url> # Include submodules
undefined
git clone <url> git clone <url> <directory> git clone --depth 1 <url> # 浅克隆(更快,历史记录更少) git clone --branch <branch> <url> # 克隆指定分支 git clone --recurse-submodules <url> # 包含子模块
undefined

Configuration

配置

bash
undefined
bash
undefined

User identity (required for commits)

用户身份(提交必需)

git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
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
git config --global init.defaultBranch main

Line ending handling (Windows)

行尾处理(Windows)

git config --global core.autocrlf true # Windows git config --global core.autocrlf input # macOS/Linux
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"
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'
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'
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'
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
undefined
git config --list git config --global --list git config --local --list git config user.name # 获取特定值
undefined

Basic Workflow

基础工作流

bash
undefined
bash
undefined

Check status

检查状态

git status git status -s # Short format git status -sb # Short with branch info
git status git status -s # 简洁格式 git status -sb # 带分支信息的简洁格式

Add files

添加文件

git add <file> git add . # Add all changes in current directory git add -A # Add all changes in repository git add -p # Interactive staging (patch mode)
git add <file> git add . # 添加当前目录下的所有更改 git add -A # 添加仓库中的所有更改 git add -p # 交互式暂存(补丁模式)

Remove files

删除文件

git rm <file> git rm --cached <file> # Remove from index, keep in working directory git rm -r <directory>
git rm <file> git rm --cached <file> # 从索引中移除,保留工作目录中的文件 git rm -r <directory>

Move/rename files

移动/重命名文件

git mv <old> <new>
git mv <old> <new>

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)
git commit -m "message" git commit -am "message" # 添加并提交已跟踪的文件 git commit --amend # 修改最后一次提交 git commit --amend --no-edit # 修改提交但不更改消息 git commit --allow-empty -m "message" # 空提交(适用于触发操作)

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 -- <file> # History of specific file git log --follow <file> # Follow renames
git log git log --oneline git log --graph --oneline --all --decorate git log --stat # 显示文件统计信息 git log --patch # 显示差异 git log -p -2 # 显示最后2次提交及差异 git log --since="2 weeks ago" git log --until="2025-01-01" git log --author="Name" git log --grep="pattern" git log -- <file> # 特定文件的历史 git log --follow <file> # 跟踪文件重命名

Show changes

显示更改

git diff # Unstaged changes git diff --staged # Staged changes git diff HEAD # All changes since last commit git diff <branch> # Compare with another branch git diff <commit1> <commit2> git diff <commit> # Changes since specific commit git diff <branch1>...<branch2> # Changes between branches
git diff # 未暂存的更改 git diff --staged # 已暂存的更改 git diff HEAD # 自上次提交以来的所有更改 git diff <branch> # 与其他分支对比 git diff <commit1> <commit2> git diff <commit> # 自特定提交以来的更改 git diff <branch1>...<branch2> # 分支间的更改

Show commit details

显示提交详情

git show <commit> git show <commit>:<file> # Show file at specific commit

---
git show <commit> git show <commit>:<file> # 显示特定提交时的文件内容

---

Branch Management

分支管理

Creating and Switching Branches

分支创建与切换

bash
undefined
bash
undefined

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
git branch # 本地分支 git branch -r # 远程分支 git branch -a # 所有分支 git branch -v # 包含最后一次提交信息 git branch -vv # 包含跟踪信息

Create branch

创建分支

git branch <branch-name> git branch <branch-name> <start-point> # From specific commit/tag
git branch <branch-name> git branch <branch-name> <start-point> # 从特定提交/标签创建

Switch branch

切换分支

git switch <branch-name> git checkout <branch-name> # Old syntax, still works
git switch <branch-name> git checkout <branch-name> # 旧语法,仍可使用

Create and switch

创建并切换分支

git switch -c <branch-name> git checkout -b <branch-name> git switch -c <branch-name> <start-point>
git switch -c <branch-name> git checkout -b <branch-name> git switch -c <branch-name> <start-point>

Delete branch

删除分支

git branch -d <branch-name> # Safe delete (only if merged) git branch -D <branch-name> # Force delete (even if not merged)
git branch -d <branch-name> # 安全删除(仅当分支已合并时) git branch -D <branch-name> # 强制删除(即使未合并)

Rename branch

重命名分支

git branch -m <old-name> <new-name> git branch -m <new-name> # Rename current branch
git branch -m <old-name> <new-name> git branch -m <new-name> # 重命名当前分支

Set upstream tracking

设置上游跟踪

git branch --set-upstream-to=origin/<branch> git branch -u origin/<branch>
undefined
git branch --set-upstream-to=origin/<branch> git branch -u origin/<branch>
undefined

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

Git Flow:
  • main/master
    :生产就绪代码
  • develop
    :功能集成分支
  • feature/*
    :新功能
  • release/*
    :发布准备
  • hotfix/*
    :生产环境修复
GitHub Flow:
  • main
    :始终可部署
  • feature/*
    :短期功能分支
  • 创建PR、审核、合并
主干开发(Trunk-Based Development):
  • main
    :单一主干分支
  • 短期功能分支(<1天)
  • 使用功能标记管理未完成功能
GitLab Flow:
  • 环境分支:
    production
    staging
    main
  • 功能分支合并到
    main
  • 从环境分支部署

Merging and Rebasing

合并与Rebase

Merge Strategies

合并策略

bash
undefined
bash
undefined

Fast-forward merge (default if possible)

快进合并(默认,如果可能)

git merge <branch>
git merge <branch>

Force merge commit (even if fast-forward possible)

强制创建合并提交(即使可以快进)

git merge --no-ff <branch>
git merge --no-ff <branch>

Squash merge (combine all commits into one)

压缩合并(将所有提交合并为一个)

git merge --squash <branch>
git merge --squash <branch>

Then commit manually: git commit -m "Merged feature X"

然后手动提交:git commit -m "合并功能X"

Merge with specific strategy

使用特定策略合并

git merge -s recursive <branch> # Default strategy git merge -s ours <branch> # Always use "our" version git merge -s theirs <branch> # Always use "their" version (requires merge-theirs) git merge -s octopus <branch1> <branch2> <branch3> # Merge multiple branches
git merge -s recursive <branch> # 默认策略 git merge -s ours <branch> # 始终使用“我们的”版本 git merge -s theirs <branch> # 始终使用“他们的”版本(需要merge-theirs) git merge -s octopus <branch1> <branch2> <branch3> # 合并多个分支

Merge with strategy options

带策略选项的合并

git merge -X ours <branch> # Prefer "our" changes in conflicts git merge -X theirs <branch> # Prefer "their" changes in conflicts git merge -X ignore-all-space <branch> git merge -X ignore-space-change <branch>
git merge -X ours <branch> # 冲突时优先“我们的”更改 git merge -X theirs <branch> # 冲突时优先“他们的”更改 git merge -X ignore-all-space <branch> git merge -X ignore-space-change <branch>

Abort merge

中止合并

git merge --abort
git merge --abort

Continue after resolving conflicts

解决冲突后继续合并

git merge --continue
undefined
git merge --continue
undefined

Conflict Resolution

冲突解决

bash
undefined
bash
undefined

When merge conflicts occur

发生合并冲突时

git status # See conflicted files
git status # 查看冲突文件

Conflict markers in files:

文件中的冲突标记:

<<<<<<< HEAD

<<<<<<< HEAD

Your changes

你的更改

=======

=======

Their changes

他们的更改

>>>>>>> branch-name

>>>>>>> branch-name

Resolve conflicts manually, then:

手动解决冲突后:

git add <resolved-file> git commit # Complete the merge
git add <resolved-file> git commit # 完成合并

Use mergetool

使用合并工具

git mergetool
git mergetool

Accept one side completely

完全接受某一方的更改

git checkout --ours <file> # Keep our version git checkout --theirs <file> # Keep their version git add <file>
git checkout --ours <file> # 保留我们的版本 git checkout --theirs <file> # 保留他们的版本 git add <file>

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
git diff # 显示冲突 git diff --ours # 与我们的版本对比 git diff --theirs # 与他们的版本对比 git diff --base # 与基础版本对比

List conflicts

列出冲突文件

git diff --name-only --diff-filter=U
undefined
git diff --name-only --diff-filter=U
undefined

Rebase Operations

Rebase操作

⚠️ WARNING: Rebase rewrites history. Never rebase commits that have been pushed to shared branches!
bash
undefined
⚠️ 警告:Rebase会重写历史记录。绝不要对已推送到共享分支的提交执行Rebase!
bash
undefined

Basic rebase

基础Rebase

git rebase <base-branch> git rebase origin/main
git rebase <base-branch> git rebase origin/main

Interactive rebase (POWERFUL)

交互式Rebase(功能强大)

git rebase -i <base-commit> git rebase -i HEAD~5 # Last 5 commits
git rebase -i <base-commit> git rebase -i HEAD~5 # 最后5次提交

Interactive rebase commands:

交互式Rebase命令:

p, pick = use commit

p, pick = 使用该提交

r, reword = use commit, but edit message

r, reword = 使用该提交,但编辑消息

e, edit = use commit, but stop for amending

e, edit = 使用该提交,但暂停以进行修改

s, squash = use commit, but meld into previous commit

s, squash = 使用该提交,但合并到前一个提交

f, fixup = like squash, but discard commit message

f, fixup = 类似squash,但丢弃提交消息

x, exec = run command (rest of line) using shell

x, exec = 使用shell运行命令(行的剩余部分)

b, break = stop here (continue rebase later with 'git rebase --continue')

b, break = 在此处停止(稍后使用'git rebase --continue'继续)

d, drop = remove commit

d, drop = 删除提交

l, label = label current HEAD with a name

l, label = 为当前HEAD添加标签

t, reset = reset HEAD to a label

t, reset = 将HEAD重置为标签

Rebase onto different base

重新基于不同的基准

git rebase --onto <new-base> <old-base> <branch>
git rebase --onto <new-base> <old-base> <branch>

Continue after resolving conflicts

解决冲突后继续Rebase

git rebase --continue
git rebase --continue

Skip current commit

跳过当前提交

git rebase --skip
git rebase --skip

Abort rebase

中止Rebase

git rebase --abort
git rebase --abort

Preserve merge commits

保留合并提交

git rebase --preserve-merges <base> # Deprecated git rebase --rebase-merges <base> # Modern approach
git rebase --preserve-merges <base> # 已弃用 git rebase --rebase-merges <base> # 现代方法

Autosquash (with fixup commits)

自动压缩(配合fixup提交)

git commit --fixup <commit> git rebase -i --autosquash <base>
undefined
git commit --fixup <commit> git rebase -i --autosquash <base>
undefined

Cherry-Pick

Cherry-Pick

bash
undefined
bash
undefined

Apply specific commit to current branch

将特定提交应用到当前分支

git cherry-pick <commit>
git cherry-pick <commit>

Cherry-pick multiple commits

Cherry-Pick多个提交

git cherry-pick <commit1> <commit2> git cherry-pick <commit1>..<commit5>
git cherry-pick <commit1> <commit2> git cherry-pick <commit1>..<commit5>

Cherry-pick without committing

Cherry-Pick但不提交

git cherry-pick -n <commit> git cherry-pick --no-commit <commit>
git cherry-pick -n <commit> git cherry-pick --no-commit <commit>

Continue after resolving conflicts

解决冲突后继续Cherry-Pick

git cherry-pick --continue
git cherry-pick --continue

Abort cherry-pick

中止Cherry-Pick

git cherry-pick --abort

---
git cherry-pick --abort

---

Remote Operations

远程操作

Remote Management

远程仓库管理

bash
undefined
bash
undefined

List remotes

列出远程仓库

git remote git remote -v # With URLs
git remote git remote -v # 包含URL

Add remote

添加远程仓库

git remote add <name> <url> git remote add origin https://github.com/user/repo.git
git remote add <name> <url> git remote add origin https://github.com/user/repo.git

Change remote URL

修改远程仓库URL

git remote set-url <name> <new-url>
git remote set-url <name> <new-url>

Remove remote

删除远程仓库

git remote remove <name> git remote rm <name>
git remote remove <name> git remote rm <name>

Rename remote

重命名远程仓库

git remote rename <old> <new>
git remote rename <old> <new>

Show remote info

显示远程仓库信息

git remote show <name> git remote show origin
git remote show <name> git remote show origin

Prune stale remote branches

清理过时的远程分支

git remote prune origin git fetch --prune
undefined
git remote prune origin git fetch --prune
undefined

Fetch and Pull

Fetch与Pull

bash
undefined
bash
undefined

Fetch from remote (doesn't merge)

从远程仓库获取(不合并)

git fetch git fetch origin git fetch --all # All remotes git fetch --prune # Remove stale remote-tracking branches
git fetch git fetch origin git fetch --all # 所有远程仓库 git fetch --prune # 删除过时的远程跟踪分支

Pull (fetch + merge)

Pull(fetch + 合并)

git pull git pull origin <branch> 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
git pull git pull origin <branch> git pull --rebase # fetch + rebase而非合并 git pull --no-ff # 始终创建合并提交 git pull --ff-only # 仅当可以快进时

Set default pull behavior

设置默认Pull行为

git config --global pull.rebase true # Always rebase git config --global pull.ff only # Only fast-forward
undefined
git config --global pull.rebase true # 始终使用rebase git config --global pull.ff only # 仅快进
undefined

Push

Push

bash
undefined
bash
undefined

Push to remote

推送到远程仓库

git push git push origin <branch> git push origin <local-branch>:<remote-branch>
git push git push origin <branch> git push origin <local-branch>:<remote-branch>

Push new branch and set upstream

推送新分支并设置上游

git push -u origin <branch> git push --set-upstream origin <branch>
git push -u origin <branch> git push --set-upstream origin <branch>

Push all branches

推送所有分支

git push --all
git push --all

Push tags

推送标签

git push --tags git push origin <tag-name>
git push --tags git push origin <tag-name>

Delete remote branch

删除远程分支

git push origin --delete <branch> git push origin :<branch> # Old syntax
git push origin --delete <branch> git push origin :<branch> # 旧语法

Delete remote tag

删除远程标签

git push origin --delete <tag> git push origin :refs/tags/<tag>
git push origin --delete <tag> git push origin :refs/tags/<tag>

⚠️ DANGEROUS: Force push (overwrites remote history)

⚠️ 危险:强制推送(覆盖远程历史)

ALWAYS ASK USER FOR CONFIRMATION FIRST

必须先获得用户确认

git push --force git push -f
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=<ref>:<expected-value>

**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/<branch> ^<branch> --decorate

if [ -z "$(git log --oneline origin/<branch> ^<branch>)" ]; 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/<branch> ^<branch>
    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

git push --force-with-lease git push --force-with-lease=<ref>:<expected-value>

**强制推送安全流程:**

在执行任何强制推送前,运行以下安全检查:

```bash
echo "⚠️  危险:强制推送将覆盖远程历史!"
echo ""
echo "远程分支状态:"
git fetch origin
git log --oneline origin/<branch> ^<branch> --decorate

if [ -z "$(git log --oneline origin/<branch> ^<branch>)" ]; then
    echo "✓ 不会丢失任何提交(远程落后于本地)"
else
    echo "❌ 警告:远程有提交将丢失:"
    git log --oneline --decorate origin/<branch> ^<branch>
    echo ""
    echo "其他开发者的这些提交将被销毁!"
fi

echo ""
echo "考虑使用--force-with-lease替代--force"
echo ""
read -p "输入'force push'以确认:" confirm
if [[ "$confirm" != "force push" ]]; then
    echo "已取消。"
    exit 1
fi

Advanced Commands

高级命令

Stash

Stash

bash
undefined
bash
undefined

Stash changes

暂存更改

git stash git stash save "message" git stash push -m "message"
git stash git stash save "message" git stash push -m "message"

Stash including untracked files

暂存包含未跟踪文件

git stash -u git stash --include-untracked
git stash -u git stash --include-untracked

Stash including ignored files

暂存包含忽略文件

git stash -a git stash --all
git stash -a git stash --all

List stashes

列出暂存

git stash list
git stash list

Show stash contents

显示暂存内容

git stash show git stash show -p # With diff git stash show stash@{2}
git stash show git stash show -p # 带差异 git stash show stash@{2}

Apply stash (keep in stash list)

应用暂存(保留在暂存列表中)

git stash apply git stash apply stash@{2}
git stash apply git stash apply stash@{2}

Pop stash (apply and remove)

弹出暂存(应用并移除)

git stash pop git stash pop stash@{2}
git stash pop git stash pop stash@{2}

Drop stash

删除暂存

git stash drop git stash drop stash@{2}
git stash drop git stash drop stash@{2}

Clear all stashes

清空所有暂存

git stash clear
git stash clear

Create branch from stash

从暂存创建分支

git stash branch <branch-name> git stash branch <branch-name> stash@{1}
git stash branch <branch-name> git stash branch <branch-name> stash@{1}

Git 2.51+ : Import/Export stashes (share stashes between machines)

Git 2.51+ : 导入/导出暂存(在机器间共享暂存)

Export stash to a file

将暂存导出到文件

git stash store --file=stash.patch stash@{0}
git stash store --file=stash.patch stash@{0}

Import stash from a file

从文件导入暂存

git stash import --file=stash.patch
git stash import --file=stash.patch

Share stashes like branches/tags

像分支/标签一样共享暂存

git stash export > my-stash.patch git stash import < my-stash.patch
undefined
git stash export > my-stash.patch git stash import < my-stash.patch
undefined

Reset

Reset

⚠️ WARNING: reset can permanently delete changes!
bash
undefined
⚠️ 警告:reset会永久删除更改!
bash
undefined

Soft reset (keep changes staged)

软重置(保留更改在暂存区)

git reset --soft <commit> git reset --soft HEAD~1 # Undo last commit, keep changes staged
git reset --soft <commit> git reset --soft HEAD~1 # 撤销最后一次提交,保留更改在暂存区

Mixed reset (default - keep changes unstaged)

混合重置(默认 - 保留更改在工作区)

git reset <commit> git reset HEAD~1 # Undo last commit, keep changes unstaged
git reset <commit> git reset HEAD~1 # 撤销最后一次提交,保留更改在工作区

⚠️ HARD reset (DELETE all changes - DANGEROUS!)

⚠️ 硬重置(删除所有更改 - 危险!)

ALWAYS create backup branch first!

必须先创建备份分支!

git branch backup-$(date +%Y%m%d-%H%M%S) git reset --hard <commit> git reset --hard HEAD~1 # Undo last commit and DELETE all changes git reset --hard origin/<branch> # Reset to remote state
git branch backup-$(date +%Y%m%d-%H%M%S) git reset --hard <commit> git reset --hard HEAD~1 # 撤销最后一次提交并删除所有更改 git reset --hard origin/<branch> # 重置为远程状态

Unstage files

取消暂存文件

git reset HEAD <file> git reset -- <file>
git reset HEAD <file> git reset -- <file>

Reset specific file to commit

将特定文件重置为提交时的状态

git checkout <commit> -- <file>
undefined
git checkout <commit> -- <file>
undefined

Revert

Revert

bash
undefined
bash
undefined

Revert commit (creates new commit that undoes changes)

撤销提交(创建新提交以撤销更改)

Safer than reset for shared branches

对于共享分支,比reset更安全

git revert <commit>
git revert <commit>

Revert without creating commit

撤销但不创建提交

git revert -n <commit> git revert --no-commit <commit>
git revert -n <commit> git revert --no-commit <commit>

Revert merge commit

撤销合并提交

git revert -m 1 <merge-commit> # Keep first parent git revert -m 2 <merge-commit> # Keep second parent
git revert -m 1 <merge-commit> # 保留第一个父分支 git revert -m 2 <merge-commit> # 保留第二个父分支

Revert multiple commits

撤销多个提交

git revert <commit1> <commit2> git revert <commit1>..<commit5>
git revert <commit1> <commit2> git revert <commit1>..<commit5>

Continue after resolving conflicts

解决冲突后继续撤销

git revert --continue
git revert --continue

Abort revert

中止撤销

git revert --abort
undefined
git revert --abort
undefined

Reflog (Recovery)

Reflog(恢复)

reflog is your safety net - it tracks all HEAD movements for 90 days (default)
bash
undefined
reflog是你的安全网 - 它会跟踪所有HEAD移动,默认保留90天
bash
undefined

View reflog

查看reflog

git reflog git reflog show git reflog show <branch>
git reflog git reflog show git reflog show <branch>

More detailed reflog

更详细的reflog

git log -g # Reflog as log git log -g --all
git log -g # 以日志形式显示reflog git log -g --all

Find lost commits

查找丢失的提交

git reflog --all git fsck --lost-found
git reflog --all git fsck --lost-found

Recover deleted branch

恢复已删除的分支

git reflog # Find commit where branch existed git branch <branch-name> <commit-hash>
git reflog # 查找分支存在时的提交 git branch <branch-name> <commit-hash>

Recover from hard reset

从硬重置中恢复

git reflog # Find commit before reset git reset --hard <commit-hash>
git reflog # 查找重置前的提交 git reset --hard <commit-hash>

Recover deleted commits

恢复已删除的提交

git cherry-pick <commit-hash>
git cherry-pick <commit-hash>

Reflog expiration (change retention)

Reflog过期时间(修改保留时长)

git config gc.reflogExpire "90 days" git config gc.reflogExpireUnreachable "30 days"
undefined
git config gc.reflogExpire "90 days" git config gc.reflogExpireUnreachable "30 days"
undefined

Bisect (Find Bad Commits)

Bisect(查找错误提交)

bash
undefined
bash
undefined

Start bisect

开始Bisect

git bisect start
git bisect start

Mark current commit as bad

将当前标记为错误提交

git bisect bad
git bisect bad

Mark known good commit

标记已知的正确提交

git bisect good <commit>
git bisect good <commit>

Test each commit, then mark as good or bad

测试每个提交,然后标记为正确或错误

git bisect good # Current commit is good git bisect bad # Current commit is bad
git bisect good # 当前提交正确 git bisect bad # 当前提交错误

Automate with test script

使用测试脚本自动化

git bisect run <test-script>
git bisect run <test-script>

Bisect shows the first bad commit

Bisect会显示第一个错误提交

Finish bisect

结束Bisect

git bisect reset
git bisect reset

Skip commit if unable to test

如果无法测试,跳过提交

git bisect skip
undefined
git bisect skip
undefined

Clean

Clean

⚠️ WARNING: clean permanently deletes untracked files!
bash
undefined
⚠️ 警告:clean会永久删除未跟踪文件!
bash
undefined

Show what would be deleted (dry run - ALWAYS do this first!)

显示将被删除的内容(试运行 - 必须先执行此操作!)

git clean -n git clean --dry-run
git clean -n git clean --dry-run

Delete untracked files

删除未跟踪文件

git clean -f
git clean -f

Delete untracked files and directories

删除未跟踪文件和目录

git clean -fd
git clean -fd

Delete untracked and ignored files

删除未跟踪和忽略的文件

git clean -fdx
git clean -fdx

Interactive clean

交互式清理

git clean -i
undefined
git clean -i
undefined

Worktrees

工作树(Worktrees)

bash
undefined
bash
undefined

List worktrees

列出工作树

git worktree list
git worktree list

Add new worktree

添加新工作树

git worktree add <path> <branch> git worktree add ../project-feature feature-branch
git worktree add <path> <branch> git worktree add ../project-feature feature-branch

Add worktree for new branch

为新分支添加工作树

git worktree add -b <new-branch> <path>
git worktree add -b <new-branch> <path>

Remove worktree

移除工作树

git worktree remove <path>
git worktree remove <path>

Prune stale worktrees

清理过时的工作树

git worktree prune
undefined
git worktree prune
undefined

Submodules

子模块(Submodules)

bash
undefined
bash
undefined

Add submodule

添加子模块

git submodule add <url> <path>
git submodule add <url> <path>

Initialize submodules (after clone)

初始化子模块(克隆后)

git submodule init git submodule update
git submodule init git submodule update

Clone with submodules

克隆包含子模块的仓库

git clone --recurse-submodules <url>
git clone --recurse-submodules <url>

Update submodules

更新子模块

git submodule update --remote git submodule update --init --recursive
git submodule update --remote git submodule update --init --recursive

Execute command in all submodules

在所有子模块中执行命令

git submodule foreach <command> git submodule foreach git pull origin main
git submodule foreach <command> git submodule foreach git pull origin main

Remove submodule

移除子模块

git submodule deinit <path> git rm <path> rm -rf .git/modules/<path>

---
git submodule deinit <path> git rm <path> rm -rf .git/modules/<path>

---

Dangerous Operations (High Risk)

高风险操作

Filter-Repo (History Rewriting)

Filter-Repo(历史重写)

⚠️ EXTREMELY DANGEROUS: Rewrites entire repository history!
bash
undefined
⚠️ 极度危险:重写整个仓库历史!
bash
undefined

Install git-filter-repo (not built-in)

安装git-filter-repo(非内置)

pip install git-filter-repo

pip install git-filter-repo

Remove file from all history

从所有历史中移除文件

git filter-repo --path <file> --invert-paths
git filter-repo --path <file> --invert-paths

Remove directory from all history

从所有历史中移除目录

git filter-repo --path <directory> --invert-paths
git filter-repo --path <directory> --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")'
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
git filter-repo --strip-blobs-bigger-than 10M

⚠️ After filter-repo, force push required

⚠️ 执行filter-repo后,需要强制推送

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 <repo-url> 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
git push --force --all git push --force --tags

**Filter-Repo安全流程:**

```bash
echo "⚠️⚠️⚠️  极度危险  ⚠️⚠️⚠️"
echo "此操作将:"
echo "  - 重写整个仓库历史"
echo "  - 修改所有提交哈希"
echo "  - 破坏所有现有克隆"
echo "  - 要求所有团队成员重新克隆"
echo "  - 强制推送后无法撤销"
echo ""
echo "必须:创建完整备份:"
git clone --mirror <repo-url> backup-$(date +%Y%m%d-%H%M%S)
echo ""
echo "在继续前通知所有团队成员!"
echo ""
read -p "输入'I UNDERSTAND THE RISKS'以继续:" confirm
if [[ "$confirm" != "I UNDERSTAND THE RISKS" ]]; then
    echo "已取消。"
    exit 1
fi

Amend Pushed Commits

修改已推送的提交

⚠️ DANGER: Changing pushed commits requires force push!
bash
undefined
⚠️ 危险:修改已推送的提交需要强制推送!
bash
undefined

Amend last commit

修改最后一次提交

git commit --amend
git commit --amend

Amend without changing message

修改提交但不更改消息

git commit --amend --no-edit
git commit --amend --no-edit

Change author of last commit

修改最后一次提交的作者

git commit --amend --author="Name <email>"
git commit --amend --author="Name <email>"

⚠️ Force push required if already pushed

⚠️ 如果已推送,需要强制推送

git push --force-with-lease
undefined
git push --force-with-lease
undefined

Rewrite Multiple Commits

重写多个提交

⚠️ DANGER: Interactive rebase on pushed commits!
bash
undefined
⚠️ 危险:对已推送的提交执行交互式Rebase!
bash
undefined

Interactive rebase

交互式Rebase

git rebase -i HEAD~5
git rebase -i HEAD~5

Change author of older commits

修改旧提交的作者

git rebase -i <commit>^
git rebase -i <commit>^

Mark commit as "edit"

将提交标记为"edit"

When stopped:

当停止时:

git commit --amend --author="Name <email>" --no-edit git rebase --continue
git commit --amend --author="Name <email>" --no-edit git rebase --continue

⚠️ Force push required

⚠️ 需要强制推送

git push --force-with-lease

---
git push --force-with-lease

---

Platform-Specific Workflows

平台专属工作流

GitHub

GitHub

Pull Requests:
bash
undefined
拉取请求:
bash
undefined

Install GitHub CLI

安装GitHub CLI

Create PR

创建PR

gh pr create gh pr create --title "Title" --body "Description" gh pr create --base main --head feature-branch
gh pr create gh pr create --title "Title" --body "Description" gh pr create --base main --head feature-branch

List PRs

列出PR

gh pr list
gh pr list

View PR

查看PR

gh pr view gh pr view <number>
gh pr view gh pr view <number>

Check out PR locally

在本地检出PR

gh pr checkout <number>
gh pr checkout <number>

Review PR

审核PR

gh pr review gh pr review --approve gh pr review --request-changes gh pr review --comment
gh pr review gh pr review --approve gh pr review --request-changes gh pr review --comment

Merge PR

合并PR

gh pr merge gh pr merge --squash gh pr merge --rebase gh pr merge --merge
gh pr merge gh pr merge --squash gh pr merge --rebase gh pr merge --merge

Close PR

关闭PR

gh pr close <number>

**GitHub Actions:**
```yaml
gh pr close <number>

**GitHub Actions:**
```yaml

.github/workflows/ci.yml

.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
undefined
name: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Run tests run: npm test
undefined

Azure DevOps

Azure DevOps

Pull Requests:
bash
undefined
拉取请求:
bash
undefined

Install Azure DevOps CLI

安装Azure DevOps CLI

Create PR

创建PR

az repos pr create --title "Title" --description "Description" az repos pr create --source-branch feature --target-branch main
az repos pr create --title "Title" --description "Description" az repos pr create --source-branch feature --target-branch main

List PRs

列出PR

az repos pr list
az repos pr list

View PR

查看PR

az repos pr show --id <id>
az repos pr show --id <id>

Complete PR

完成PR

az repos pr update --id <id> --status completed
az repos pr update --id <id> --status completed

Branch policies

分支策略

az repos policy list az repos policy create --config policy.json

**Azure Pipelines:**
```yaml
az repos policy list az repos policy create --config policy.json

**Azure Pipelines:**
```yaml

azure-pipelines.yml

azure-pipelines.yml

trigger:
  • main pool: vmImage: 'ubuntu-latest' steps:
  • script: npm test displayName: 'Run tests'
undefined
trigger:
  • main pool: vmImage: 'ubuntu-latest' steps:
  • script: npm test displayName: 'Run tests'
undefined

Bitbucket

Bitbucket

Pull Requests:
bash
undefined
拉取请求:
bash
undefined

Create PR (via web or Bitbucket CLI)

创建PR(通过网页或Bitbucket CLI)

bb pr create
bb pr create

Review PR

审核PR

bb pr list bb pr view <id>
bb pr list bb pr view <id>

Merge PR

合并PR

bb pr merge <id>

**Bitbucket Pipelines:**
```yaml
bb pr merge <id>

**Bitbucket Pipelines:**
```yaml

bitbucket-pipelines.yml

bitbucket-pipelines.yml

pipelines: default: - step: script: - npm test
undefined
pipelines: default: - step: script: - npm test
undefined

GitLab

GitLab

Merge Requests:
bash
undefined
合并请求:
bash
undefined

Install GitLab CLI (glab)

安装GitLab CLI(glab)

Create MR

创建MR

glab mr create glab mr create --title "Title" --description "Description"
glab mr create glab mr create --title "Title" --description "Description"

List MRs

列出MR

glab mr list
glab mr list

View MR

查看MR

glab mr view <id>
glab mr view <id>

Merge MR

合并MR

glab mr merge <id>
glab mr merge <id>

Close MR

关闭MR

glab mr close <id>

**GitLab CI:**
```yaml
glab mr close <id>

**GitLab CI:**
```yaml

.gitlab-ci.yml

.gitlab-ci.yml

stages:
  • test test: stage: test script:
    • npm test

---
stages:
  • test test: stage: test script:
    • npm test

---

Performance Optimization

性能优化

Repository Maintenance

仓库维护

bash
undefined
bash
undefined

Garbage collection

垃圾回收

git gc git gc --aggressive # More thorough, slower
git gc git gc --aggressive # 更彻底,但速度更慢

Prune unreachable objects

清理不可达对象

git prune
git prune

Verify repository

验证仓库

git fsck git fsck --full
git fsck git fsck --full

Optimize repository

优化仓库

git repack -a -d --depth=250 --window=250
git repack -a -d --depth=250 --window=250

Git 2.51+: Path-walk repacking (generates smaller packs)

Git 2.51+:路径遍历打包(生成更小的包)

More efficient delta compression by walking paths

通过遍历路径实现更高效的增量压缩

git repack --path-walk -a -d
git repack --path-walk -a -d

Count objects

统计对象数量

git count-objects -v
git count-objects -v

Repository size

仓库大小

du -sh .git
undefined
du -sh .git
undefined

Large Files

大文件

bash
undefined
bash
undefined

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 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(大文件存储)

git lfs install git lfs track ".psd" git lfs track ".zip" git add .gitattributes git add file.psd git commit -m "Add large file"
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

列出LFS文件

git lfs ls-files
git lfs ls-files

Fetch LFS files

获取LFS文件

git lfs fetch git lfs pull
undefined
git lfs fetch git lfs pull
undefined

Shallow Clones

浅克隆

bash
undefined
bash
undefined

Shallow clone (faster, less disk space)

浅克隆(更快,占用更少磁盘空间)

git clone --depth 1 <url>
git clone --depth 1 <url>

Unshallow (convert to full clone)

转换为完整克隆

git fetch --unshallow
git fetch --unshallow

Fetch more history

获取更多历史

git fetch --depth=100

---
git fetch --depth=100

---

Tags and Releases

标签与发布

Creating Tags

创建标签

bash
undefined
bash
undefined

Lightweight tag

轻量标签

git tag <tag-name> git tag v1.0.0
git tag <tag-name> git tag v1.0.0

Annotated tag (recommended - includes metadata)

附注标签(推荐 - 包含元数据)

git tag -a <tag-name> -m "message" git tag -a v1.0.0 -m "Release version 1.0.0"
git tag -a <tag-name> -m "message" git tag -a v1.0.0 -m "发布版本1.0.0"

Tag specific commit

为特定提交创建标签

git tag -a <tag-name> <commit>
git tag -a <tag-name> <commit>

Signed tag (GPG signature)

签名标签(GPG签名)

git tag -s <tag-name> -m "message"
undefined
git tag -s <tag-name> -m "message"
undefined

Managing Tags

管理标签

bash
undefined
bash
undefined

List tags

列出标签

git tag git tag -l "v1.*" # Pattern matching
git tag git tag -l "v1.*" # 模式匹配

Show tag info

显示标签信息

git show <tag-name>
git show <tag-name>

Delete local tag

删除本地标签

git tag -d <tag-name>
git tag -d <tag-name>

Delete remote tag

删除远程标签

git push origin --delete <tag-name> git push origin :refs/tags/<tag-name>
git push origin --delete <tag-name> git push origin :refs/tags/<tag-name>

Push tags

推送标签

git push origin <tag-name> git push --tags # All tags git push --follow-tags # Only annotated tags

---
git push origin <tag-name> git push --tags # 所有标签 git push --follow-tags # 仅附注标签

---

Git Hooks

Git钩子

Client-Side Hooks

客户端钩子

bash
undefined
bash
undefined

Hooks location: .git/hooks/

钩子位置:.git/hooks/

pre-commit: Run before commit

pre-commit:提交前运行

Example: .git/hooks/pre-commit

示例:.git/hooks/pre-commit

#!/bin/bash npm run lint || exit 1
#!/bin/bash npm run lint || exit 1

prepare-commit-msg: Edit commit message before editor opens

prepare-commit-msg:编辑器打开前编辑提交消息

commit-msg: Validate commit message

commit-msg:验证提交消息

#!/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
#!/bin/bash msg=$(cat "$1") if ! echo "$msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore):"; then echo "错误:提交消息必须以类型开头(feat|fix|docs|...):" exit 1 fi

post-commit: Run after commit

post-commit:提交后运行

pre-push: Run before push

pre-push:推送前运行

post-checkout: Run after checkout

post-checkout:检出后运行

post-merge: Run after merge

post-merge:合并后运行

Make hook executable

使钩子可执行

chmod +x .git/hooks/pre-commit
undefined
chmod +x .git/hooks/pre-commit
undefined

Server-Side Hooks

服务端钩子

bash
undefined
bash
undefined

pre-receive: Run before refs are updated

pre-receive:更新引用前运行

update: Run for each branch being updated

update:为每个正在更新的分支运行

post-receive: Run after refs are updated

post-receive:更新引用后运行

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

---
#!/bin/bash while read oldrev newrev refname; do if [ "$oldrev" != "0000000000000000000000000000000000000000" ]; then if ! git merge-base --is-ancestor "$oldrev" "$newrev"; then echo "错误:拒绝强制推送" exit 1 fi fi done

---

Troubleshooting and Recovery

故障排除与恢复

Common Problems

常见问题

Detached HEAD:
bash
undefined
分离HEAD状态:
bash
undefined

You're in detached HEAD state

处于分离HEAD状态

git branch temp # Create branch at current commit git switch main git merge temp git branch -d temp

**Merge conflicts:**
```bash
git branch temp # 在当前提交创建分支 git switch main git merge temp git branch -d temp

**合并冲突:**
```bash

During merge/rebase

合并/Rebase期间

git status # See conflicted files
git status # 查看冲突文件

Edit files to resolve conflicts

编辑文件解决冲突

git add <resolved-files> git merge --continue # or git rebase --continue
git add <resolved-files> git merge --continue # 或 git rebase --continue

Abort and start over

中止并重新开始

git merge --abort git rebase --abort

**Accidentally deleted branch:**
```bash
git merge --abort git rebase --abort

**意外删除分支:**
```bash

Find branch in reflog

在reflog中查找分支

git reflog
git reflog

Create branch at commit

在提交处创建分支

git branch <branch-name> <commit-hash>

**Committed to wrong branch:**
```bash
git branch <branch-name> <commit-hash>

**提交到错误分支:**
```bash

Move commit to correct branch

将提交移动到正确分支

git switch correct-branch git cherry-pick <commit> git switch wrong-branch git reset --hard HEAD~1 # Remove from wrong branch

**Pushed sensitive data:**
```bash
git switch correct-branch git cherry-pick <commit> git switch wrong-branch git reset --hard HEAD~1 # 从错误分支移除提交

**推送了敏感数据:**
```bash

⚠️ URGENT: Remove from history immediately

⚠️ 紧急:立即从历史中移除

git filter-repo --path <sensitive-file> --invert-paths git push --force --all
git filter-repo --path <sensitive-file> --invert-paths git push --force --all

Then: Rotate compromised credentials immediately!

然后:立即轮换泄露的凭据!


**Large commit by mistake:**
```bash

**意外提交大文件:**
```bash

Before pushing

推送前

git reset --soft HEAD~1 git reset HEAD <large-file> git commit -m "message"
git reset --soft HEAD~1 git reset HEAD <large-file> git commit -m "message"

After pushing - use filter-repo or BFG

推送后 - 使用filter-repo或BFG

undefined
undefined

Recovery Scenarios

恢复场景

Recover after hard reset:
bash
git reflog
git reset --hard <commit-before-reset>
Recover deleted file:
bash
git log --all --full-history -- <file>
git checkout <commit>^ -- <file>
Recover deleted commits:
bash
git reflog  # Find commit hash
git cherry-pick <commit>
从硬重置恢复:
bash
git reflog
git reset --hard <commit-before-reset>
恢复已删除的文件:
bash
git log --all --full-history -- <file>
git checkout <commit>^ -- <file>
恢复已删除的提交:
bash
git reflog  # 查找提交哈希
git cherry-pick <commit>

or

git merge <commit>
git merge <commit>

or

git reset --hard <commit>

**Recover from corrupted repository:**
```bash
git reset --hard <commit>

**从损坏的仓库恢复:**
```bash

Verify corruption

验证损坏情况

git fsck --full
git fsck --full

Attempt repair

尝试修复

git gc --aggressive
git gc --aggressive

Last resort: clone from remote

最后手段:从远程克隆


---

---

Best Practices

最佳实践

Commit Messages

提交消息

Conventional Commits format:
<type>(<scope>): <subject>

<body>

<footer>
Types:
  • feat
    : New feature
  • fix
    : Bug fix
  • docs
    : Documentation
  • style
    : Formatting (no code change)
  • refactor
    : Code restructuring
  • test
    : Adding tests
  • chore
    : Maintenance
Example:
feat(auth): add OAuth2 authentication

Implement OAuth2 flow for Google and GitHub providers.
Includes token refresh and revocation.

Closes #123
约定式提交格式:
<type>(<scope>): <subject>

<body>

<footer>
类型:
  • feat
    : 新功能
  • fix
    : 错误修复
  • docs
    : 文档
  • style
    : 格式调整(无代码更改)
  • refactor
    : 代码重构
  • test
    : 添加测试
  • chore
    : 维护工作
示例:
feat(auth): 添加OAuth2认证

实现Google和GitHub提供商的OAuth2流程。
包含令牌刷新和吊销功能。

关闭#123

Branching Best Practices

分支最佳实践

  1. Keep branches short-lived (< 2 days ideal)
  2. Use descriptive names:
    feature/user-auth
    ,
    fix/header-crash
  3. One purpose per branch
  4. Rebase before merge to keep history clean
  5. Delete merged branches
  1. 保持分支短期存在(理想情况下<2天)
  2. 使用描述性名称
    feature/user-auth
    fix/header-crash
  3. 每个分支单一用途
  4. 合并前Rebase以保持历史整洁
  5. 删除已合并的分支

Workflow Best Practices

工作流最佳实践

  1. Commit often (small, logical chunks)
  2. Pull before push (stay up to date)
  3. Review before commit (
    git diff --staged
    )
  4. Write meaningful messages
  5. Test before commit
  6. Never commit secrets (use
    .gitignore
    , environment variables)
  1. 经常提交(小而逻辑完整的块)
  2. 推送前Pull(保持本地更新)
  3. 提交前审核
    git diff --staged
  4. 编写有意义的消息
  5. 提交前测试代码
  6. 绝不提交机密信息(使用
    .gitignore
    、环境变量)

.gitignore Best Practices

.gitignore最佳实践

gitignore
undefined
gitignore
undefined

Environment files

环境文件

.env .env.local *.env
.env .env.local *.env

Dependencies

依赖

node_modules/ vendor/ venv/
node_modules/ vendor/ venv/

Build outputs

构建输出

dist/ build/ *.exe *.dll *.so
dist/ build/ *.exe *.dll *.so

IDE

IDE

.vscode/ .idea/ *.swp *.swo
.vscode/ .idea/ *.swp *.swo

OS files

系统文件

.DS_Store Thumbs.db
.DS_Store Thumbs.db

Logs

日志

*.log logs/
*.log logs/

Temporary files

临时文件

tmp/ temp/ *.tmp

---
tmp/ temp/ *.tmp

---

Security Best Practices

安全最佳实践

Credential Management

凭据管理

bash
undefined
bash
undefined

Store credentials (cache for 1 hour)

存储凭据(缓存1小时)

git config --global credential.helper cache git config --global credential.helper 'cache --timeout=3600'
git config --global credential.helper cache git config --global credential.helper 'cache --timeout=3600'

Store credentials (permanent - use with caution)

永久存储凭据(谨慎使用)

git config --global credential.helper store
git config --global credential.helper store

Windows: Use Credential Manager

Windows:使用凭据管理器

git config --global credential.helper wincred
git config --global credential.helper wincred

macOS: Use Keychain

macOS:使用钥匙串

git config --global credential.helper osxkeychain
git config --global credential.helper osxkeychain

Linux: Use libsecret

Linux:使用libsecret

git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
undefined
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
undefined

SSH Keys

SSH密钥

bash
undefined
bash
undefined

Generate SSH key

生成SSH密钥

ssh-keygen -t ed25519 -C "your_email@example.com" ssh-keygen -t rsa -b 4096 -C "your_email@example.com" # If ed25519 not supported
ssh-keygen -t ed25519 -C "your_email@example.com" ssh-keygen -t rsa -b 4096 -C "your_email@example.com" # 如果不支持ed25519

Start ssh-agent

启动ssh-agent

eval "$(ssh-agent -s)"
eval "$(ssh-agent -s)"

Add key to ssh-agent

将密钥添加到ssh-agent

ssh-add ~/.ssh/id_ed25519
ssh-add ~/.ssh/id_ed25519

Test connection

测试连接

ssh -T git@github.com ssh -T git@ssh.dev.azure.com
undefined
ssh -T git@github.com ssh -T git@ssh.dev.azure.com
undefined

GPG Signing

GPG签名

bash
undefined
bash
undefined

Generate GPG key

生成GPG密钥

gpg --full-generate-key
gpg --full-generate-key

List keys

列出密钥

gpg --list-secret-keys --keyid-format LONG
gpg --list-secret-keys --keyid-format LONG

Configure Git to sign commits

配置Git签名提交

git config --global user.signingkey <key-id> git config --global commit.gpgsign true
git config --global user.signingkey <key-id> git config --global commit.gpgsign true

Sign commits

签名提交

git commit -S -m "message"
git commit -S -m "message"

Verify signatures

验证签名

git log --show-signature
undefined
git log --show-signature
undefined

Preventing Secrets

防止提交机密信息

bash
undefined
bash
undefined

Git-secrets (AWS tool)

Git-secrets(AWS工具)

git secrets --install git secrets --register-aws
git secrets --install git secrets --register-aws

Gitleaks

Gitleaks

gitleaks detect
gitleaks detect

Pre-commit hook

提交前钩子

#!/bin/bash if git diff --cached | grep -E "(password|secret|api_key)" ; then echo "Potential secret detected!" exit 1 fi

---
#!/bin/bash if git diff --cached | grep -E "(password|secret|api_key)" ; then echo "检测到潜在机密信息!" exit 1 fi

---

Cross-Platform Considerations

跨平台注意事项

Line Endings

行尾

bash
undefined
bash
undefined

Windows (CRLF in working directory, LF in repository)

Windows(工作目录中使用CRLF,仓库中使用LF)

git config --global core.autocrlf true
git config --global core.autocrlf true

macOS/Linux (LF everywhere)

macOS/Linux(所有地方使用LF)

git config --global core.autocrlf input
git config --global core.autocrlf input

No conversion (not recommended)

不转换(不推荐)

git config --global core.autocrlf false
git config --global core.autocrlf false

Use .gitattributes for consistency

使用.gitattributes保持一致性

.gitattributes:

.gitattributes:

  • text=auto *.sh text eol=lf *.bat text eol=crlf
undefined
  • text=auto *.sh text eol=lf *.bat text eol=crlf
undefined

Case Sensitivity

大小写敏感性

bash
undefined
bash
undefined

macOS/Windows: Case-insensitive filesystems

macOS/Windows:大小写不敏感的文件系统

Linux: Case-sensitive filesystem

Linux:大小写敏感的文件系统

Enable case sensitivity in Git

在Git中启用大小写敏感性

git config --global core.ignorecase false
git config --global core.ignorecase false

Rename file (case-only change)

重命名文件(仅更改大小写)

git mv --force myfile.txt MyFile.txt
undefined
git mv --force myfile.txt MyFile.txt
undefined

Path Handling

路径处理

bash
undefined
bash
undefined

Git always uses forward slashes internally

Git内部始终使用正斜杠

Works on all platforms:

在所有平台上都有效:

git add src/components/Header.jsx
git add src/components/Header.jsx

Windows-specific tools may need backslashes in some contexts

Windows特定工具在某些情况下可能需要反斜杠

undefined
undefined

Git Bash / MINGW Path Conversion (Windows)

Git Bash / MINGW路径转换(Windows)

CRITICAL: Git Bash is the primary Git environment on Windows!
Git Bash (MINGW/MSYS2) automatically converts Unix-style paths to Windows paths for native executables, which can cause issues with Git operations.
Path Conversion Behavior:
bash
undefined
关键:Git Bash是Windows上的主要Git环境!
Git Bash(MINGW/MSYS2)会自动将Unix风格的路径转换为Windows路径,这可能导致Git操作出现问题。
路径转换行为:
bash
undefined

Automatic conversions that occur:

发生的自动转换:

/foo → C:/Program Files/Git/usr/foo /foo:/bar → C:\msys64\foo;C:\msys64\bar --dir=/foo → --dir=C:/msys64/foo
/foo → C:/Program Files/Git/usr/foo /foo:/bar → C:\msys64\foo;C:\msys64\bar --dir=/foo → --dir=C:/msys64/foo

What triggers conversion:

触发转换的情况:

✓ Leading forward slash (/) in arguments

✓ 参数以正斜杠(/)开头

✓ Colon-separated path lists

✓ 冒号分隔的路径列表

✓ Arguments after - or , with path components

✓ -或,后的包含路径组件的参数

What's exempt from conversion:

豁免转换的情况:

✓ Arguments containing = (variable assignments)

✓ 包含=的参数(变量赋值)

✓ Drive specifiers (C:)

✓ 驱动器标识符(C:)

✓ Arguments with ; (already Windows format)

✓ 包含;的参数(已为Windows格式)

✓ Arguments starting with // (Windows switches)

✓ 以//开头的参数(Windows开关)


**Controlling Path Conversion:**

```bash

**控制路径转换:**

```bash

Method 1: MSYS_NO_PATHCONV (Git for Windows only)

方法1:MSYS_NO_PATHCONV(仅适用于Git for Windows)

Disable ALL path conversion for a command

禁用命令的所有路径转换

MSYS_NO_PATHCONV=1 git command --option=/path
MSYS_NO_PATHCONV=1 git command --option=/path

Permanently disable (use with caution - can break scripts)

永久禁用(谨慎使用 - 可能破坏脚本)

export MSYS_NO_PATHCONV=1
export MSYS_NO_PATHCONV=1

Method 2: MSYS2_ARG_CONV_EXCL (MSYS2)

方法2:MSYS2_ARG_CONV_EXCL(MSYS2)

Exclude specific argument patterns

排除特定参数模式

export MSYS2_ARG_CONV_EXCL="*" # Exclude everything export MSYS2_ARG_CONV_EXCL="--dir=;/test" # Specific prefixes
export MSYS2_ARG_CONV_EXCL="*" # 排除所有 export MSYS2_ARG_CONV_EXCL="--dir=;/test" # 特定前缀

Method 3: Manual conversion with cygpath

方法3:使用cygpath手动转换

cygpath -u "C:\path" # → Unix format: /c/path cygpath -w "/c/path" # → Windows format: C:\path cygpath -m "/c/path" # → Mixed format: C:/path
cygpath -u "C:\path" # → Unix格式: /c/path cygpath -w "/c/path" # → Windows格式: C:\path cygpath -m "/c/path" # → 混合格式: C:/path

Method 4: Workarounds

方法4:解决方法

Use double slashes: //e //s instead of /e /s

使用双斜杠: //e //s 替代 /e /s

Use dash notation: -e -s instead of /e /s

使用短横线表示: -e -s 替代 /e /s

Quote paths with spaces: "/c/Program Files/file.txt"

为包含空格的路径添加引号: "/c/Program Files/file.txt"


**Shell Detection in Git Workflows:**

```bash

**Git工作流中的Shell检测:**

```bash

Method 1: $MSYSTEM (Most Reliable for Git Bash)

方法1:$MSYSTEM(最可靠的Git Bash检测方式)

case "$MSYSTEM" in MINGW64) echo "Git Bash 64-bit" ;; MINGW32) echo "Git Bash 32-bit" ;; MSYS) echo "MSYS environment" ;; esac
case "$MSYSTEM" in MINGW64) echo "Git Bash 64位" ;; MINGW32) echo "Git Bash 32位" ;; MSYS) echo "MSYS环境" ;; esac

Method 2: uname -s (Portable)

方法2:uname -s(可移植)

case "$(uname -s)" in MINGW64_NT*) echo "Git Bash 64-bit" ;; MINGW32_NT*) echo "Git Bash 32-bit" ;; MSYS_NT*) echo "MSYS" ;; CYGWIN*) echo "Cygwin" ;; Darwin*) echo "macOS" ;; Linux*) echo "Linux" ;; esac
case "$(uname -s)" in MINGW64_NT*) echo "Git Bash 64位" ;; MINGW32_NT*) echo "Git Bash 32位" ;; MSYS_NT*) echo "MSYS" ;; CYGWIN*) echo "Cygwin" ;; Darwin*) echo "macOS" ;; Linux*) echo "Linux" ;; esac

Method 3: $OSTYPE (Bash-only, fast)

方法3:$OSTYPE(仅Bash,快速)

case "$OSTYPE" in msys*) echo "Git Bash/MSYS" ;; cygwin*) echo "Cygwin" ;; darwin*) echo "macOS" ;; linux-gnu*) echo "Linux" ;; esac

**Git Bash Path Issues & Solutions:**

```bash
case "$OSTYPE" in msys*) echo "Git Bash/MSYS" ;; cygwin*) echo "Cygwin" ;; darwin*) echo "macOS" ;; linux-gnu*) echo "Linux" ;; esac

**Git Bash路径问题与解决方案:**

```bash

Issue: Git commands with paths fail in Git Bash

问题:Git Bash中带路径的Git命令失败

Example: git log --follow /path/to/file fails

示例:git log --follow /path/to/file 失败

Solution 1: Use relative paths

解决方案1:使用相对路径

git log --follow ./path/to/file
git log --follow ./path/to/file

Solution 2: Disable path conversion

解决方案2:禁用路径转换

MSYS_NO_PATHCONV=1 git log --follow /path/to/file
MSYS_NO_PATHCONV=1 git log --follow /path/to/file

Solution 3: Use Windows-style paths

解决方案3:使用Windows风格路径

git log --follow C:/path/to/file
git log --follow C:/path/to/file

Issue: Spaces in paths (Program Files)

问题:路径中包含空格(Program Files)

Solution: Always quote paths

解决方案:始终为包含空格的路径添加引号

git add "/c/Program Files/project/file.txt"
git add "/c/Program Files/project/file.txt"

Issue: Drive letter duplication (D:\dev → D:\d\dev)

问题:驱动器字母重复(D:\dev → D:\d\dev)

Solution: Use cygpath for conversion

解决方案:使用cygpath转换

file=$(cygpath -u "D:\dev\file.txt") git add "$file"

**Git Bash Best Practices:**

1. **Always use forward slashes in Git commands** - Git handles them on all platforms
2. **Quote paths with spaces** - Essential in Git Bash
3. **Use relative paths when possible** - Avoids conversion issues
4. **Detect shell environment** - Use $MSYSTEM for Git Bash detection
5. **Test scripts on Git Bash** - Primary Windows Git environment
6. **Use MSYS_NO_PATHCONV selectively** - Only when needed, not globally

---
file=$(cygpath -u "D:\dev\file.txt") git add "$file"

**Git Bash最佳实践:**

1. **在Git命令中始终使用正斜杠** - Git会在所有平台上处理它们
2. **为包含空格的路径添加引号** - 在Git Bash中必不可少
3. **尽可能使用相对路径** - 避免转换问题
4. **检测Shell环境** - 使用$MSYSTEM检测Git Bash
5. **在Git Bash上测试脚本** - Windows的主要Git环境
6. **有选择地使用MSYS_NO_PATHCONV** - 仅在需要时使用,不全局启用

---

Success Criteria

成功标准

A Git workflow using this skill should:
  1. ✓ ALWAYS ask user preference for automatic commits vs manual
  2. ✓ ALWAYS warn before destructive operations
  3. ✓ ALWAYS create backup branches before risky operations
  4. ✓ ALWAYS explain recovery procedures
  5. ✓ Use appropriate branch strategy for the project
  6. ✓ Write meaningful commit messages
  7. ✓ Keep commit history clean and linear
  8. ✓ Never commit secrets or large binary files
  9. ✓ Test code before committing
  10. ✓ Know how to recover from any mistake

使用本技能的Git工作流应满足:
  1. ✓ 必须询问用户偏好自动提交还是手动控制
  2. ✓ 执行破坏性操作前必须警告
  3. ✓ 执行高风险操作前必须创建备份分支
  4. ✓ 必须提供恢复步骤说明
  5. ✓ 为项目使用合适的分支策略
  6. ✓ 编写有意义的提交消息
  7. ✓ 保持提交历史整洁、线性
  8. ✓ 绝不提交机密信息或大二进制文件
  9. ✓ 提交前测试代码
  10. ✓ 知道如何从任何错误中恢复

Emergency Recovery Reference

紧急恢复参考

Quick recovery commands:
bash
undefined
快速恢复命令:
bash
undefined

Undo last commit (keep changes)

撤销最后一次提交(保留更改)

git reset --soft HEAD~1
git reset --soft HEAD~1

Undo changes to file

撤销文件的更改

git checkout -- <file>
git checkout -- <file>

Recover deleted branch

恢复已删除的分支

git reflog git branch <name> <commit>
git reflog git branch <name> <commit>

Undo force push (if recent)

撤销强制推送(如果是最近操作)

git reflog git reset --hard <commit-before-push> git push --force-with-lease
git reflog git reset --hard <commit-before-push> git push --force-with-lease

Recover from hard reset

从硬重置恢复

git reflog git reset --hard <commit-before-reset>
git reflog git reset --hard <commit-before-reset>

Find lost commits

查找丢失的提交

git fsck --lost-found git reflog --all
git fsck --lost-found git reflog --all

Recover deleted file

恢复已删除的文件

git log --all --full-history -- <file> git checkout <commit>^ -- <file>

---
git log --all --full-history -- <file> git checkout <commit>^ -- <file>

---

When to Use This Skill

何时使用本技能

Always activate for:
  • Any Git command or operation
  • Repository management questions
  • Branch strategy decisions
  • Merge conflict resolution
  • History rewriting needs
  • Recovery from Git mistakes
  • Platform-specific Git questions
  • Dangerous operations (with appropriate warnings)
Key indicators:
  • User mentions Git, GitHub, GitLab, Bitbucket, Azure DevOps
  • Version control questions
  • Commit, push, pull, merge, rebase operations
  • Branch management
  • History modification
  • Recovery scenarios

This skill provides COMPLETE Git expertise. Combined with the reference files and safety guardrails, you have the knowledge to handle ANY Git operation safely and effectively.
在以下场景启用:
  • 任何Git命令或操作
  • 仓库管理问题
  • 分支策略决策
  • 合并冲突解决
  • 历史重写需求
  • Git错误恢复
  • 平台专属Git问题
  • 高风险操作(配合适当的警告)
关键指标:
  • 用户提到Git、GitHub、GitLab、Bitbucket、Azure DevOps
  • 版本控制问题
  • 提交、推送、拉取、合并、Rebase操作
  • 分支管理
  • 历史修改
  • 恢复场景

本技能提供完整的Git专业知识。结合参考文件和安全防护机制,你可以安全、有效地处理任何Git操作。