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:
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
**用户偏好确认:**
- **必须询问:** "你希望我自动创建提交,还是你手动控制提交?"
- 在整个会话过程中尊重用户的选择
---
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)
1. Safety Guardrails for Destructive Operations
1. 破坏性操作的安全防护机制
CRITICAL: Before ANY destructive operation (reset --hard, force push, filter-repo, etc.):
- Always warn the user explicitly
- Explain the risks clearly
- Ask for confirmation
- Suggest creating a backup branch first
- Provide recovery instructions
关键:执行任何破坏性操作(reset --hard、强制推送、filter-repo等)前:
- 必须明确警告用户
- 清晰解释风险
- 请求确认
- 建议先创建备份分支
- 提供恢复说明
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
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
2. Commit Creation Policy
2. 提交创建规则
ALWAYS ASK at the start of ANY Git task:
"Would you like me to:
- Create commits automatically with appropriate messages
- Stage changes only (you handle commits manually)
- Just provide guidance (no automatic operations)"
Respect this choice throughout the session.
在任何Git任务开始时必须询问:
"你希望我:
- 使用合适的消息自动创建提交
- 仅暂存更改(你手动处理提交)
- 仅提供指导(不执行自动操作)"
在整个会话过程中尊重用户的选择。
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:
托管平台:
- 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
仓库初始化与克隆
Initialize new repository
初始化新仓库
git init
git init --initial-branch=main # Specify default branch name
git init
git init --initial-branch=main # 指定默认分支名称
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
git clone <url>
git clone <url> <directory>
git clone --depth 1 <url> # 浅克隆(更快,历史记录更少)
git clone --branch <branch> <url> # 克隆指定分支
git clone --recurse-submodules <url> # 包含子模块
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
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"
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'
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'
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'
git config --list
git config --global --list
git config --local --list
git config user.name # Get specific value
git config --list
git config --global --list
git config --local --list
git config user.name # 获取特定值
git status
git status -s # Short format
git status -sb # Short with branch info
git status
git status -s # 简洁格式
git status -sb # 带分支信息的简洁格式
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 # 交互式暂存(补丁模式)
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 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" # 空提交(适用于触发操作)
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> # 跟踪文件重命名
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> # 显示特定提交时的文件内容
Creating and Switching 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 # 包含跟踪信息
git branch <branch-name>
git branch <branch-name> <start-point> # From specific commit/tag
git branch <branch-name>
git branch <branch-name> <start-point> # 从特定提交/标签创建
git switch <branch-name>
git checkout <branch-name> # Old syntax, still works
git switch <branch-name>
git checkout <branch-name> # 旧语法,仍可使用
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>
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> # 强制删除(即使未合并)
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>
git branch --set-upstream-to=origin/<branch>
git branch -u origin/<branch>
Git Flow:
- : Production-ready code
- : Integration branch for features
- : New features
- : Release preparation
- : Production fixes
GitHub Flow:
- : Always deployable
- : Short-lived feature branches
- Create PR, review, merge
Trunk-Based Development:
- : Single branch
- Short-lived feature branches (< 1 day)
- Feature flags for incomplete features
GitLab Flow:
- Environment branches: , ,
- Feature branches merge to
- Deploy from environment branches
Git Flow:
- :生产就绪代码
- :功能集成分支
- :新功能
- :发布准备
- :生产环境修复
GitHub Flow:
- :始终可部署
- :短期功能分支
- 创建PR、审核、合并
主干开发(Trunk-Based Development):
- :单一主干分支
- 短期功能分支(<1天)
- 使用功能标记管理未完成功能
GitLab Flow:
Merging and Rebasing
合并与Rebase
Fast-forward merge (default if possible)
快进合并(默认,如果可能)
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>
Continue after resolving conflicts
解决冲突后继续合并
When merge conflicts occur
发生合并冲突时
git status # See conflicted files
Conflict markers in files:
文件中的冲突标记:
>>>>>>> branch-name
>>>>>>> branch-name
Resolve conflicts manually, then:
手动解决冲突后:
git add <resolved-file>
git commit # Complete the merge
git add <resolved-file>
git commit # 完成合并
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>
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 # 与基础版本对比
git diff --name-only --diff-filter=U
git diff --name-only --diff-filter=U
Rebase Operations
Rebase操作
⚠️ WARNING: Rebase rewrites history. Never rebase commits that have been pushed to shared branches!
⚠️ 警告: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
Skip current commit
跳过当前提交
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>
git commit --fixup <commit>
git rebase -i --autosquash <base>
Apply specific commit to current branch
将特定提交应用到当前分支
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 remote
git remote -v # With URLs
git remote
git remote -v # 包含URL
Change remote URL
修改远程仓库URL
git remote set-url <name> <new-url>
git remote set-url <name> <new-url>
git remote remove <name>
git remote rm <name>
git remote remove <name>
git remote rm <name>
git remote rename <old> <new>
git remote rename <old> <new>
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
git remote prune origin
git fetch --prune
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
git config --global pull.rebase true # 始终使用rebase
git config --global pull.ff only # 仅快进
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>
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> # 旧语法
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
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
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}
git stash drop
git stash drop stash@{2}
git stash drop
git stash drop stash@{2}
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
git stash export > my-stash.patch
git stash import < my-stash.patch
⚠️ WARNING: reset can permanently delete changes!
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> # 重置为远程状态
git reset HEAD <file>
git reset -- <file>
git reset HEAD <file>
git reset -- <file>
Reset specific file to commit
将特定文件重置为提交时的状态
git checkout <commit> -- <file>
git checkout <commit> -- <file>
Revert commit (creates new commit that undoes changes)
撤销提交(创建新提交以撤销更改)
Safer than reset for shared branches
对于共享分支,比reset更安全
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
解决冲突后继续撤销
Reflog (Recovery)
Reflog(恢复)
reflog is your safety net - it tracks all HEAD movements for 90 days (default)
reflog是你的安全网 - 它会跟踪所有HEAD移动,默认保留90天
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
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"
git config gc.reflogExpire "90 days"
git config gc.reflogExpireUnreachable "30 days"
Bisect (Find Bad Commits)
Bisect(查找错误提交)
Mark current commit as bad
将当前标记为错误提交
Mark known 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会显示第一个错误提交
Skip commit if unable to test
如果无法测试,跳过提交
⚠️ WARNING: clean permanently deletes untracked files!
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
删除未跟踪文件
Delete untracked files and directories
删除未跟踪文件和目录
Delete untracked and ignored files
删除未跟踪和忽略的文件
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>
git worktree remove <path>
git worktree remove <path>
Prune stale worktrees
清理过时的工作树
Submodules
子模块(Submodules)
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>
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
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!
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
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")'
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!
Amend last commit
修改最后一次提交
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
git push --force-with-lease
Rewrite Multiple Commits
重写多个提交
⚠️ DANGER: Interactive rebase on pushed commits!
⚠️ 危险:对已推送的提交执行交互式Rebase!
Interactive rebase
交互式Rebase
Change author of older commits
修改旧提交的作者
Mark commit as "edit"
将提交标记为"edit"
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
平台专属工作流
Install GitHub CLI
安装GitHub CLI
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
gh pr view
gh pr view <number>
gh pr view
gh pr view <number>
Check out PR locally
在本地检出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
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
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
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
run: npm test
Install Azure DevOps CLI
安装Azure DevOps CLI
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
az repos pr show --id <id>
az repos pr show --id <id>
az repos pr update --id <id> --status completed
az repos pr update --id <id> --status completed
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'
trigger:
- main
pool:
vmImage: 'ubuntu-latest'
steps:
- script: npm test
displayName: 'Run tests'
Create PR (via web or Bitbucket CLI)
创建PR(通过网页或Bitbucket CLI)
bb pr list
bb pr view <id>
bb pr list
bb pr view <id>
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
pipelines:
default:
- step:
script:
- npm test
Install GitLab CLI (glab)
安装GitLab CLI(glab)
glab mr create
glab mr create --title "Title" --description "Description"
glab mr create
glab mr create --title "Title" --description "Description"
.gitlab-ci.yml
.gitlab-ci.yml
stages:
- test
test:
stage: test
script:
stages:
- test
test:
stage: test
script:
Performance Optimization
性能优化
Repository Maintenance
仓库维护
git gc
git gc --aggressive # More thorough, slower
git gc
git gc --aggressive # 更彻底,但速度更慢
Prune unreachable objects
清理不可达对象
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
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"
git lfs fetch
git lfs pull
git lfs fetch
git lfs pull
Shallow clone (faster, less disk space)
浅克隆(更快,占用更少磁盘空间)
git clone --depth 1 <url>
git clone --depth 1 <url>
Unshallow (convert to full clone)
转换为完整克隆
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"
git tag -s <tag-name> -m "message"
git tag
git tag -l "v1.*" # Pattern matching
git tag
git tag -l "v1.*" # 模式匹配
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>
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 # 仅附注标签
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
chmod +x .git/hooks/pre-commit
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
故障排除与恢复
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
During merge/rebase
合并/Rebase期间
git status # See conflicted files
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
Find branch in reflog
在reflog中查找分支
Create branch at commit
在提交处创建分支
git branch <branch-name> <commit-hash>
**Committed to wrong branch:**
```bash
git branch <branch-name> <commit-hash>
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 # 从错误分支移除提交
⚠️ 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
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
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>
git reset --hard <commit>
**Recover from corrupted repository:**
```bash
git reset --hard <commit>
Last resort: clone from remote
最后手段:从远程克隆
Conventional Commits format:
<type>(<scope>): <subject>
<body>
<footer>
Types:
- : New feature
- : Bug fix
- : Documentation
- : Formatting (no code change)
- : Code restructuring
- : Adding tests
- : 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(auth): 添加OAuth2认证
实现Google和GitHub提供商的OAuth2流程。
包含令牌刷新和吊销功能。
关闭#123
Branching Best Practices
分支最佳实践
- Keep branches short-lived (< 2 days ideal)
- Use descriptive names: ,
- One purpose per branch
- Rebase before merge to keep history clean
- Delete merged branches
- 保持分支短期存在(理想情况下<2天)
- 使用描述性名称:、
- 每个分支单一用途
- 合并前Rebase以保持历史整洁
- 删除已合并的分支
Workflow Best Practices
工作流最佳实践
- Commit often (small, logical chunks)
- Pull before push (stay up to date)
- Review before commit ()
- Write meaningful messages
- Test before commit
- Never commit secrets (use , environment variables)
- 经常提交(小而逻辑完整的块)
- 推送前Pull(保持本地更新)
- 提交前审核()
- 编写有意义的消息
- 提交前测试代码
- 绝不提交机密信息(使用、环境变量)
.gitignore Best Practices
.gitignore最佳实践
node_modules/
vendor/
venv/
node_modules/
vendor/
venv/
dist/
build/
*.exe
*.dll
*.so
dist/
build/
*.exe
*.dll
*.so
.vscode/
.idea/
*.swp
*.swo
.vscode/
.idea/
*.swp
*.swo
Security Best Practices
安全最佳实践
Credential Management
凭据管理
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
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret
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
Add key to ssh-agent
将密钥添加到ssh-agent
ssh-add ~/.ssh/id_ed25519
ssh-add ~/.ssh/id_ed25519
ssh -T git@github.com
ssh -T git@ssh.dev.azure.com
ssh -T git@github.com
ssh -T git@ssh.dev.azure.com
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
git commit -S -m "message"
git commit -S -m "message"
Preventing Secrets
防止提交机密信息
Git-secrets (AWS tool)
Git-secrets(AWS工具)
git secrets --install
git secrets --register-aws
git secrets --install
git secrets --register-aws
#!/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
跨平台注意事项
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
- text=auto
*.sh text eol=lf
*.bat text eol=crlf
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
git mv --force myfile.txt MyFile.txt
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特定工具在某些情况下可能需要反斜杠
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:
关键:Git Bash是Windows上的主要Git环境!
Git Bash(MINGW/MSYS2)会自动将Unix风格的路径转换为Windows路径,这可能导致Git操作出现问题。
路径转换行为:
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
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** - 仅在需要时使用,不全局启用
---
A Git workflow using this skill should:
- ✓ ALWAYS ask user preference for automatic commits vs manual
- ✓ ALWAYS warn before destructive operations
- ✓ ALWAYS create backup branches before risky operations
- ✓ ALWAYS explain recovery procedures
- ✓ Use appropriate branch strategy for the project
- ✓ Write meaningful commit messages
- ✓ Keep commit history clean and linear
- ✓ Never commit secrets or large binary files
- ✓ Test code before committing
- ✓ Know how to recover from any mistake
使用本技能的Git工作流应满足:
- ✓ 必须询问用户偏好自动提交还是手动控制
- ✓ 执行破坏性操作前必须警告
- ✓ 执行高风险操作前必须创建备份分支
- ✓ 必须提供恢复步骤说明
- ✓ 为项目使用合适的分支策略
- ✓ 编写有意义的提交消息
- ✓ 保持提交历史整洁、线性
- ✓ 绝不提交机密信息或大二进制文件
- ✓ 提交前测试代码
- ✓ 知道如何从任何错误中恢复
Emergency Recovery Reference
紧急恢复参考
Undo last commit (keep changes)
撤销最后一次提交(保留更改)
Undo changes to 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>
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操作。