git-workflow

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Workflow Patterns

Git工作流模式

Best practices for Git version control, branching strategies, and collaborative development.
Git版本控制、分支策略与协作开发的最佳实践。

When to Activate

适用场景

  • Setting up Git workflow for a new project
  • Deciding on branching strategy (GitFlow, trunk-based, GitHub flow)
  • Writing commit messages and PR descriptions
  • Resolving merge conflicts
  • Managing releases and version tags
  • Onboarding new team members to Git practices
  • 为新项目配置Git工作流
  • 确定分支策略(GitFlow、基于主干开发、GitHub flow)
  • 编写提交信息与PR描述
  • 解决合并冲突
  • 管理版本发布与版本标签
  • 向新团队成员培训Git规范

Branching Strategies

分支策略

GitHub Flow (Simple, Recommended for Most)

GitHub Flow(简单模式,推荐大多数场景使用)

Best for continuous deployment and small-to-medium teams.
main (protected, always deployable)
  ├── feature/user-auth      → PR → merge to main
  ├── feature/payment-flow   → PR → merge to main
  └── fix/login-bug          → PR → merge to main
Rules:
  • main
    is always deployable
  • Create feature branches from
    main
  • Open Pull Request when ready for review
  • After approval and CI passes, merge to
    main
  • Deploy immediately after merge
最适合持续部署场景与中小规模团队。
main (受保护,始终可部署)
  ├── feature/user-auth      → PR → 合并到main
  ├── feature/payment-flow   → PR → 合并到main
  └── fix/login-bug          → PR → 合并到main
规则:
  • main
    分支代码始终可部署
  • main
    分支创建功能分支
  • 开发完成可评审时提交Pull Request
  • 审批通过且CI流程通过后,合并到
    main
    分支
  • 合并后立即部署

Trunk-Based Development (High-Velocity Teams)

基于主干开发(高交付速度团队适用)

Best for teams with strong CI/CD and feature flags.
main (trunk)
  ├── short-lived feature (1-2 days max)
  ├── short-lived feature
  └── short-lived feature
Rules:
  • Everyone commits to
    main
    or very short-lived branches
  • Feature flags hide incomplete work
  • CI must pass before merge
  • Deploy multiple times per day
最适合拥有完善CI/CD与功能开关的团队。
main (主干)
  ├── 短生命周期功能分支(最多1-2天)
  ├── 短生命周期功能分支
  └── 短生命周期功能分支
规则:
  • 所有人直接提交到
    main
    或生命周期极短的分支
  • 未完成功能通过功能开关隐藏
  • 合并前CI流程必须全部通过
  • 每日部署多次

GitFlow (Complex, Release-Cycle Driven)

GitFlow(复杂模式,按发布周期驱动)

Best for scheduled releases and enterprise projects.
main (production releases)
  └── develop (integration branch)
        ├── feature/user-auth
        ├── feature/payment
        ├── release/1.0.0    → merge to main and develop
        └── hotfix/critical  → merge to main and develop
Rules:
  • main
    contains production-ready code only
  • develop
    is the integration branch
  • Feature branches from
    develop
    , merge back to
    develop
  • Release branches from
    develop
    , merge to
    main
    and
    develop
  • Hotfix branches from
    main
    , merge to both
    main
    and
    develop
最适合 scheduled 发布与企业级项目。
main (生产发布分支)
  └── develop (集成分支)
        ├── feature/user-auth
        ├── feature/payment
        ├── release/1.0.0    → 合并到main与develop
        └── hotfix/critical  → 合并到main与develop
规则:
  • main
    分支仅包含可上线的生产级代码
  • develop
    为集成分支
  • 功能分支从
    develop
    创建,开发完成合并回
    develop
  • 发布分支从
    develop
    创建,完成后合并到
    main
    develop
  • 热修复分支从
    main
    创建,完成后合并到
    main
    develop

When to Use Which

分支策略选型指南

StrategyTeam SizeRelease CadenceBest For
GitHub FlowAnyContinuousSaaS, web apps, startups
Trunk-Based5+ experiencedMultiple/dayHigh-velocity teams, feature flags
GitFlow10+ScheduledEnterprise, regulated industries
策略团队规模发布频率适用场景
GitHub Flow任意持续发布SaaS产品、Web应用、创业公司
基于主干开发5人以上经验丰富团队每日多次高交付速度团队、使用功能开关
GitFlow10人以上按计划发布企业级项目、受监管行业

Commit Messages

提交信息规范

Conventional Commits Format

约定式提交格式

<type>(<scope>): <subject>

[optional body]

[optional footer(s)]
<type>(<scope>): <subject>

[可选正文]

[可选页脚]

Types

提交类型

TypeUse ForExample
feat
New feature
feat(auth): add OAuth2 login
fix
Bug fix
fix(api): handle null response in user endpoint
docs
Documentation
docs(readme): update installation instructions
style
Formatting, no code change
style: fix indentation in login component
refactor
Code refactoring
refactor(db): extract connection pool to module
test
Adding/updating tests
test(auth): add unit tests for token validation
chore
Maintenance tasks
chore(deps): update dependencies
perf
Performance improvement
perf(query): add index to users table
ci
CI/CD changes
ci: add PostgreSQL service to test workflow
revert
Revert previous commit
revert: revert "feat(auth): add OAuth2 login"
类型用途示例
feat
新增功能
feat(auth): add OAuth2 login
fix
修复Bug
fix(api): handle null response in user endpoint
docs
文档更新
docs(readme): update installation instructions
style
代码格式调整,无逻辑变更
style: fix indentation in login component
refactor
代码重构
refactor(db): extract connection pool to module
test
新增/更新测试
test(auth): add unit tests for token validation
chore
维护类任务
chore(deps): update dependencies
perf
性能优化
perf(query): add index to users table
ci
CI/CD相关变更
ci: add PostgreSQL service to test workflow
revert
回滚之前的提交
revert: revert "feat(auth): add OAuth2 login"

Good vs Bad Examples

正反示例对比

undefined
undefined

BAD: Vague, no context

反面示例:模糊无上下文

git commit -m "fixed stuff" git commit -m "updates" git commit -m "WIP"
git commit -m "fixed stuff" git commit -m "updates" git commit -m "WIP"

GOOD: Clear, specific, explains why

正面示例:清晰具体,说明变更原因

git commit -m "fix(api): retry requests on 503 Service Unavailable
The external API occasionally returns 503 errors during peak hours. Added exponential backoff retry logic with max 3 attempts.
Closes #123"
undefined
git commit -m "fix(api): retry requests on 503 Service Unavailable
The external API occasionally returns 503 errors during peak hours. Added exponential backoff retry logic with max 3 attempts.
Closes #123"
undefined

Commit Message Template

提交信息模板

Create
.gitmessage
in repo root:
undefined
在仓库根目录创建
.gitmessage
文件:
undefined

<type>(<scope>): <subject>

<type>(<scope>): <subject>

Types: feat, fix, docs, style, refactor, test, chore, perf, ci, revert

类型可选: feat, fix, docs, style, refactor, test, chore, perf, ci, revert

Scope: api, ui, db, auth, etc.

范围可选: api, ui, db, auth 等

Subject: imperative mood, no period, max 50 chars

主题: 使用祈使语气,不加句号,最长50字符

[optional body] - explain why, not what

[可选正文] - 说明变更原因,而非变更内容

[optional footer] - Breaking changes, closes #issue

[可选页脚] - 说明破坏性变更、关联关闭的issue


Enable with: `git config commit.template .gitmessage`

启用命令:`git config commit.template .gitmessage`

Merge vs Rebase

合并 vs 变基

Merge (Preserves History)

合并(保留历史)

bash
undefined
bash
undefined

Creates a merge commit

创建一个合并提交

git checkout main git merge feature/user-auth
git checkout main git merge feature/user-auth

Result:

结果:

* merge commit

* merge commit

|\

|\

| * feature commits

| * feature commits

|/

|/

* main commits

* main commits


**Use when:**
- Merging feature branches into `main`
- You want to preserve exact history
- Multiple people worked on the branch
- The branch has been pushed and others may have based work on it

**适用场景:**
- 将功能分支合并到`main`时
- 需要保留完整的历史记录时
- 多人共同开发该分支时
- 分支已推送到远程,其他人可能基于该分支开发时

Rebase (Linear History)

变基(线性历史)

bash
undefined
bash
undefined

Rewrites feature commits onto target branch

将功能分支的提交重放到目标分支上

git checkout feature/user-auth git rebase main
git checkout feature/user-auth git rebase main

Result:

结果:

* feature commits (rewritten)

* feature commits (rewritten)

* main commits

* main commits


**Use when:**
- Updating your local feature branch with latest `main`
- You want a linear, clean history
- The branch is local-only (not pushed)
- You're the only one working on the branch

**适用场景:**
- 用最新的`main`分支代码更新本地功能分支时
- 需要整洁的线性提交历史时
- 分支仅在本地存在(未推送到远程)时
- 你是该分支的唯一开发者时

Rebase Workflow

变基工作流

bash
undefined
bash
undefined

Update feature branch with latest main (before PR)

PR提交前,用最新的main分支代码更新功能分支

git checkout feature/user-auth git fetch origin git rebase origin/main
git checkout feature/user-auth git fetch origin git rebase origin/main

Fix any conflicts

修复所有冲突

Tests should still pass

确认测试仍可通过

Force push (only if you're the only contributor)

强制推送(仅当你是该分支唯一贡献者时使用)

git push --force-with-lease origin feature/user-auth
undefined
git push --force-with-lease origin feature/user-auth
undefined

When NOT to Rebase

禁止变基的场景

undefined
undefined

NEVER rebase branches that:

绝对不要对以下分支执行变基:

  • Have been pushed to a shared repository
  • Other people have based work on
  • Are protected branches (main, develop)
  • Are already merged
  • 已推送到共享仓库的分支
  • 其他人已基于该分支开展开发的分支
  • 受保护分支(main、develop)
  • 已完成合并的分支

Why: Rebase rewrites history, breaking others' work

原因: 变基会重写历史,破坏其他人的本地开发环境

undefined
undefined

Pull Request Workflow

Pull Request工作流

PR Title Format

PR标题格式

<type>(<scope>): <description>

Examples:
feat(auth): add SSO support for enterprise users
fix(api): resolve race condition in order processing
docs(api): add OpenAPI specification for v2 endpoints
<type>(<scope>): <description>

示例:
feat(auth): add SSO support for enterprise users
fix(api): resolve race condition in order processing
docs(api): add OpenAPI specification for v2 endpoints

PR Description Template

PR描述模板

markdown
undefined
markdown
undefined

What

变更内容

Brief description of what this PR does.
简述本PR实现的功能。

Why

变更背景

Explain the motivation and context.
说明开发的动机与上下文。

How

实现方案

Key implementation details worth highlighting.
值得关注的核心实现细节。

Testing

测试情况

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed
  • 新增/更新了单元测试
  • 新增/更新了集成测试
  • 完成了手动测试

Screenshots (if applicable)

截图(如适用)

Before/after screenshots for UI changes.
UI变更的前后对比截图。

Checklist

Checklist

  • Code follows project style guidelines
  • Self-review completed
  • Comments added for complex logic
  • Documentation updated
  • No new warnings introduced
  • Tests pass locally
  • Related issues linked
Closes #123
undefined
  • 代码符合项目风格规范
  • 完成了代码自评
  • 复杂逻辑添加了注释说明
  • 更新了相关文档
  • 未引入新的警告
  • 本地测试全部通过
  • 关联了相关issue
Closes #123
undefined

Code Review Checklist

代码评审清单

For Reviewers:
  • Does the code solve the stated problem?
  • Are there any edge cases not handled?
  • Is the code readable and maintainable?
  • Are there sufficient tests?
  • Are there security concerns?
  • Is the commit history clean (squashed if needed)?
For Authors:
  • Self-review completed before requesting review
  • CI passes (tests, lint, typecheck)
  • PR size is reasonable (<500 lines ideal)
  • Related to a single feature/fix
  • Description clearly explains the change
评审人:
  • 代码是否解决了预期的问题?
  • 是否存在未处理的边缘场景?
  • 代码是否可读、可维护?
  • 是否有足够的测试覆盖?
  • 是否存在安全隐患?
  • 提交历史是否整洁(必要时是否已压缩提交)?
提交人:
  • 申请评审前已完成代码自评
  • CI流程全部通过(测试、lint、类型检查)
  • PR规模合理(理想情况低于500行)
  • 仅关联单个功能/修复
  • 描述清晰说明了变更内容

Conflict Resolution

冲突解决

Identify Conflicts

识别冲突

bash
undefined
bash
undefined

Check for conflicts before merge

合并前检查是否存在冲突

git checkout main git merge feature/user-auth --no-commit --no-ff
git checkout main git merge feature/user-auth --no-commit --no-ff

If conflicts, Git will show:

若存在冲突,Git会提示:

CONFLICT (content): Merge conflict in src/auth/login.ts

CONFLICT (content): Merge conflict in src/auth/login.ts

Automatic merge failed; fix conflicts and then commit the result.

Automatic merge failed; fix conflicts and then commit the result.

undefined
undefined

Resolve Conflicts

解决冲突

bash
undefined
bash
undefined

See conflicted files

查看冲突文件

git status
git status

View conflict markers in file

查看文件中的冲突标记

<<<<<<< HEAD

<<<<<<< HEAD

content from main

main分支的内容

=======

=======

content from feature branch

功能分支的内容

>>>>>>> feature/user-auth

>>>>>>> feature/user-auth

Option 1: Manual resolution

方案1:手动解决

Edit file, remove markers, keep correct content

编辑文件,删除冲突标记,保留正确的内容

Option 2: Use merge tool

方案2:使用合并工具

git mergetool
git mergetool

Option 3: Accept one side

方案3:直接接受某一侧的版本

git checkout --ours src/auth/login.ts # Keep main version git checkout --theirs src/auth/login.ts # Keep feature version
git checkout --ours src/auth/login.ts # 保留main分支版本 git checkout --theirs src/auth/login.ts # 保留功能分支版本

After resolving, stage and commit

解决完成后,暂存并提交

git add src/auth/login.ts git commit
undefined
git add src/auth/login.ts git commit
undefined

Conflict Prevention Strategies

冲突预防策略

bash
undefined
bash
undefined

1. Keep feature branches small and short-lived

1. 保持功能分支规模小、生命周期短

2. Rebase frequently onto main

2. 频繁基于main分支变基更新

git checkout feature/user-auth git fetch origin git rebase origin/main
git checkout feature/user-auth git fetch origin git rebase origin/main

3. Communicate with team about touching shared files

3. 团队内沟通共享文件的修改计划

4. Use feature flags instead of long-lived branches

4. 使用功能开关而非长生命周期分支

5. Review and merge PRs promptly

5. 及时评审、合并PR

undefined
undefined

Branch Management

分支管理

Naming Conventions

命名规范

undefined
undefined

Feature branches

功能分支

feature/user-authentication feature/JIRA-123-payment-integration
feature/user-authentication feature/JIRA-123-payment-integration

Bug fixes

Bug修复分支

fix/login-redirect-loop fix/456-null-pointer-exception
fix/login-redirect-loop fix/456-null-pointer-exception

Hotfixes (production issues)

热修复分支(生产问题)

hotfix/critical-security-patch hotfix/database-connection-leak
hotfix/critical-security-patch hotfix/database-connection-leak

Releases

发布分支

release/1.2.0 release/2024-01-hotfix
release/1.2.0 release/2024-01-hotfix

Experiments/POCs

实验/POC分支

experiment/new-caching-strategy poc/graphql-migration
undefined
experiment/new-caching-strategy poc/graphql-migration
undefined

Branch Cleanup

分支清理

bash
undefined
bash
undefined

Delete local branches that are merged

删除本地已合并的分支

git branch --merged main | grep -v "^*|main" | xargs -n 1 git branch -d
git branch --merged main | grep -v "^*|main" | xargs -n 1 git branch -d

Delete remote-tracking references for deleted remote branches

删除远程已删除分支对应的本地远程跟踪引用

git fetch -p
git fetch -p

Delete local branch

删除本地分支

git branch -d feature/user-auth # Safe delete (only if merged) git branch -D feature/user-auth # Force delete
git branch -d feature/user-auth # 安全删除(仅已合并的分支) git branch -D feature/user-auth # 强制删除

Delete remote branch

删除远程分支

git push origin --delete feature/user-auth
undefined
git push origin --delete feature/user-auth
undefined

Stash Workflow

暂存工作流

bash
undefined
bash
undefined

Save work in progress

保存进行中的工作

git stash push -m "WIP: user authentication"
git stash push -m "WIP: user authentication"

List stashes

查看暂存列表

git stash list
git stash list

Apply most recent stash

应用最近一次暂存并删除暂存记录

git stash pop
git stash pop

Apply specific stash

应用指定暂存,保留暂存记录

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

Drop stash

删除指定暂存

git stash drop stash@{0}
undefined
git stash drop stash@{0}
undefined

Release Management

版本发布管理

Semantic Versioning

语义化版本规范

MAJOR.MINOR.PATCH

MAJOR: Breaking changes
MINOR: New features, backward compatible
PATCH: Bug fixes, backward compatible

Examples:
1.0.0 → 1.0.1 (patch: bug fix)
1.0.1 → 1.1.0 (minor: new feature)
1.1.0 → 2.0.0 (major: breaking change)
MAJOR.MINOR.PATCH

MAJOR: 包含破坏性变更
MINOR: 新增功能,向后兼容
PATCH: Bug修复,向后兼容

示例:
1.0.0 → 1.0.1 (PATCH: Bug修复)
1.0.1 → 1.1.0 (MINOR: 新增功能)
1.1.0 → 2.0.0 (MAJOR: 破坏性变更)

Creating Releases

创建版本发布

bash
undefined
bash
undefined

Create annotated tag

创建带注解的标签

git tag -a v1.2.0 -m "Release v1.2.0
Features:
  • Add user authentication
  • Implement password reset
Fixes:
  • Resolve login redirect issue
Breaking Changes:
  • None"
git tag -a v1.2.0 -m "Release v1.2.0
Features:
  • Add user authentication
  • Implement password reset
Fixes:
  • Resolve login redirect issue
Breaking Changes:
  • None"

Push tag to remote

推送标签到远程

git push origin v1.2.0
git push origin v1.2.0

List tags

查看标签列表

git tag -l
git tag -l

Delete tag

删除标签

git tag -d v1.2.0 git push origin --delete v1.2.0
undefined
git tag -d v1.2.0 git push origin --delete v1.2.0
undefined

Changelog Generation

生成更新日志

bash
undefined
bash
undefined

Generate changelog from commits

从提交记录生成更新日志

git log v1.1.0..v1.2.0 --oneline --no-merges
git log v1.1.0..v1.2.0 --oneline --no-merges

Or use conventional-changelog

或使用conventional-changelog工具

npx conventional-changelog -i CHANGELOG.md -s
undefined
npx conventional-changelog -i CHANGELOG.md -s
undefined

Git Configuration

Git配置

Essential Configs

基础配置

bash
undefined
bash
undefined

User identity

用户身份

git config --global user.name "Your Name" git config --global user.email "your@email.com"
git config --global user.name "Your Name" git config --global user.email "your@email.com"

Default branch name

默认分支名称

git config --global init.defaultBranch main
git config --global init.defaultBranch main

Pull behavior (rebase instead of merge)

Pull行为(默认变基而非合并)

git config --global pull.rebase true
git config --global pull.rebase true

Push behavior (push current branch only)

Push行为(仅推送当前分支)

git config --global push.default current
git config --global push.default current

Auto-correct typos

自动修正拼写错误

git config --global help.autocorrect 1
git config --global help.autocorrect 1

Better diff algorithm

更优的diff算法

git config --global diff.algorithm histogram
git config --global diff.algorithm histogram

Color output

彩色输出

git config --global color.ui auto
undefined
git config --global color.ui auto
undefined

Useful Aliases

常用别名

bash
undefined
bash
undefined

Add to ~/.gitconfig

添加到~/.gitconfig文件

[alias] co = checkout br = branch ci = commit st = status unstage = reset HEAD -- last = log -1 HEAD visual = log --oneline --graph --all amend = commit --amend --no-edit wip = commit -m "WIP" undo = reset --soft HEAD~1 contributors = shortlog -sn
undefined
[alias] co = checkout br = branch ci = commit st = status unstage = reset HEAD -- last = log -1 HEAD visual = log --oneline --graph --all amend = commit --amend --no-edit wip = commit -m "WIP" undo = reset --soft HEAD~1 contributors = shortlog -sn
undefined

Gitignore Patterns

Gitignore配置模板

gitignore
undefined
gitignore
undefined

Dependencies

依赖

node_modules/ vendor/
node_modules/ vendor/

Build outputs

构建产物

dist/ build/ *.o *.exe
dist/ build/ *.o *.exe

Environment files

环境变量文件

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

IDE

IDE配置

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

OS files

OS文件

.DS_Store Thumbs.db
.DS_Store Thumbs.db

Logs

日志

*.log logs/
*.log logs/

Test coverage

测试覆盖率

coverage/
coverage/

Cache

缓存

.cache/ *.tsbuildinfo
undefined
.cache/ *.tsbuildinfo
undefined

Common Workflows

常用工作流

Starting a New Feature

新建功能

bash
undefined
bash
undefined

1. Update main branch

1. 更新main分支

git checkout main git pull origin main
git checkout main git pull origin main

2. Create feature branch

2. 创建功能分支

git checkout -b feature/user-auth
git checkout -b feature/user-auth

3. Make changes and commit

3. 开发变更并提交

git add . git commit -m "feat(auth): implement OAuth2 login"
git add . git commit -m "feat(auth): implement OAuth2 login"

4. Push to remote

4. 推送到远程

git push -u origin feature/user-auth
git push -u origin feature/user-auth

5. Create Pull Request on GitHub/GitLab

5. 在GitHub/GitLab上创建Pull Request

undefined
undefined

Updating a PR with New Changes

更新PR内容

bash
undefined
bash
undefined

1. Make additional changes

1. 新增变更

git add . git commit -m "feat(auth): add error handling"
git add . git commit -m "feat(auth): add error handling"

2. Push updates

2. 推送更新

git push origin feature/user-auth
undefined
git push origin feature/user-auth
undefined

Syncing Fork with Upstream

同步Fork仓库与上游仓库

bash
undefined
bash
undefined

1. Add upstream remote (once)

1. 添加上游远程仓库(仅需执行一次)

git remote add upstream https://github.com/original/repo.git
git remote add upstream https://github.com/original/repo.git

2. Fetch upstream

2. 拉取上游仓库内容

git fetch upstream
git fetch upstream

3. Merge upstream/main into your main

3. 将上游main分支合并到你的main分支

git checkout main git merge upstream/main
git checkout main git merge upstream/main

4. Push to your fork

4. 推送到你的Fork仓库

git push origin main
undefined
git push origin main
undefined

Undoing Mistakes

撤销错误操作

bash
undefined
bash
undefined

Undo last commit (keep changes)

撤销最后一次提交(保留变更内容)

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

Undo last commit (discard changes)

撤销最后一次提交(丢弃变更内容)

git reset --hard HEAD~1
git reset --hard HEAD~1

Undo last commit pushed to remote

撤销已推送到远程的最后一次提交

git revert HEAD git push origin main
git revert HEAD git push origin main

Undo specific file changes

撤销指定文件的修改

git checkout HEAD -- path/to/file
git checkout HEAD -- path/to/file

Fix last commit message

修改最后一次提交的信息

git commit --amend -m "New message"
git commit --amend -m "New message"

Add forgotten file to last commit

将遗漏的文件添加到最后一次提交

git add forgotten-file git commit --amend --no-edit
undefined
git add forgotten-file git commit --amend --no-edit
undefined

Git Hooks

Git钩子

Pre-Commit Hook

提交前钩子

bash
#!/bin/bash
bash
#!/bin/bash

.git/hooks/pre-commit

.git/hooks/pre-commit

Run linting

执行代码检查

npm run lint || exit 1
npm run lint || exit 1

Run tests

执行测试

npm test || exit 1
npm test || exit 1

Check for secrets

检查是否提交了敏感信息

if git diff --cached | grep -E '(password|api_key|secret)'; then echo "Possible secret detected. Commit aborted." exit 1 fi
undefined
if git diff --cached | grep -E '(password|api_key|secret)'; then echo "检测到可能的敏感信息,提交已终止。" exit 1 fi
undefined

Pre-Push Hook

推送前钩子

bash
#!/bin/bash
bash
#!/bin/bash

.git/hooks/pre-push

.git/hooks/pre-push

Run full test suite

执行全量测试

npm run test:all || exit 1
npm run test:all || exit 1

Check for console.log statements

检查是否存在console.log语句

if git diff origin/main | grep -E 'console.log'; then echo "Remove console.log statements before pushing." exit 1 fi
undefined
if git diff origin/main | grep -E 'console.log'; then echo "推送前请删除console.log语句。" exit 1 fi
undefined

Anti-Patterns

反模式

undefined
undefined

BAD: Committing directly to main

错误:直接提交到main分支

git checkout main git commit -m "fix bug"
git checkout main git commit -m "fix bug"

GOOD: Use feature branches and PRs

正确:使用功能分支+PR流程

BAD: Committing secrets

错误:提交敏感信息

git add .env # Contains API keys
git add .env # 包含API密钥

GOOD: Add to .gitignore, use environment variables

正确:将敏感文件添加到.gitignore,使用环境变量管理

BAD: Giant PRs (1000+ lines)

错误:超大PR(1000行以上)

GOOD: Break into smaller, focused PRs

正确:拆分为多个小的、聚焦的PR

BAD: "Update" commit messages

错误:模糊的提交信息

git commit -m "update" git commit -m "fix"
git commit -m "update" git commit -m "fix"

GOOD: Descriptive messages

正确:描述清晰的提交信息

git commit -m "fix(auth): resolve redirect loop after login"
git commit -m "fix(auth): resolve redirect loop after login"

BAD: Rewriting public history

错误:重写公共分支的历史

git push --force origin main
git push --force origin main

GOOD: Use revert for public branches

正确:公共分支使用revert回滚

git revert HEAD
git revert HEAD

BAD: Long-lived feature branches (weeks/months)

错误:长生命周期功能分支(数周/数月)

GOOD: Keep branches short (days), rebase frequently

正确:保持分支生命周期短(数天),频繁变基更新

BAD: Committing generated files

错误:提交生成的文件

git add dist/ git add node_modules/
git add dist/ git add node_modules/

GOOD: Add to .gitignore

正确:将生成文件添加到.gitignore

undefined
undefined

Quick Reference

快速参考

TaskCommand
Create branch
git checkout -b feature/name
Switch branch
git checkout branch-name
Delete branch
git branch -d branch-name
Merge branch
git merge branch-name
Rebase branch
git rebase main
View history
git log --oneline --graph
View changes
git diff
Stage changes
git add .
or
git add -p
Commit
git commit -m "message"
Push
git push origin branch-name
Pull
git pull origin branch-name
Stash
git stash push -m "message"
Undo last commit
git reset --soft HEAD~1
Revert commit
git revert HEAD
任务命令
创建分支
git checkout -b feature/name
切换分支
git checkout branch-name
删除分支
git branch -d branch-name
合并分支
git merge branch-name
变基分支
git rebase main
查看历史
git log --oneline --graph
查看变更
git diff
暂存变更
git add .
git add -p
提交变更
git commit -m "message"
推送
git push origin branch-name
拉取
git pull origin branch-name
暂存工作
git stash push -m "message"
撤销最后一次提交
git reset --soft HEAD~1
回滚提交
git revert HEAD