Git 最佳实践
Professional Git habits — 提交 hygiene, 分支策略, and workflows for clean history.
你将学到
- 如何 编写 meaningful 提交 and keep history clean
- 分支 naming and feature 分支 workflows
- Daily habits: 拉取, 提交, 推送 discipline
- Team 约定 for maintainable 仓库
概念讲解
Why Best Practices Matter
Git is a tool, but how you use it determines whether your project's history is a useful record or an unreadable mess. Good Git habits make it easier to:
- Understand what changed and why
- Find and revert bugs
- Onboard new team members
- Generate changelogs and release notes
- Collaborate without conflicts
Commit Best Practices
Make Atomic Commits
每个commit should represent one logical change. Do not mix a bug fix, a new feature, and a refactor in the same commit.
# Bad: three unrelated changes in one commit
git add -A
git commit -m "fix 登录, 添加搜索, refactor utils"
# Good: three separate commits
git add login.js
git commit -m "fix: handle 空用户 in 登录 redirect"
git add search.js
git commit -m "feat: 添加搜索使用 debouncing"
git add utils.js
git commit -m "refactor: extract validation 到 utils"
Write Meaningful Messages
A commit message should explain why the change was made, not just what changed (the diff shows what).
Good:
fix: handle 空 cart in checkout 总计 calculationfeat: 添加 JWT refresh 令牌 rotation for securityrefactor: extract payment validation 到 separate 模块
Bad:
fix更新wipstuff
Use Conventional Commits
Adopt the Conventional Commits format for consistency and automation:
<type>(<scope>): <description>
feat(auth): add OAuth2 login flow
fix(cart): resolve negative quantity bug
docs(api): update authentication examples
chore(deps): upgrade express to 4.18
refactor(payment): simplify refund logic
test(user): add integration tests for registration
Commit Early and Often
Make small commits as you work. You can always squash them before pushing (with interactive rebase). It is much harder to split a giant commit after the fact.
Branch Best Practices
Use Descriptive Branch Names
# Good
feature/user-authentication
bugfix/login-redirect-loop
hotfix/security-patch-cve-2024
chore/upgrade-dependencies
docs/api-reference
# Bad
my-changes
fix
branch1
test
Keep Branches Short-Lived
Feature branches should be merged within a few days, not weeks. Long-lived branches diverge from main and cause painful merges. If a feature is large, break it into smaller, mergeable pieces.
One Branch Per Feature
Do not pile multiple features onto one branch. Each feature gets its own branch, its own PR, and its own review.
Daily Workflow Habits
Pull Before You Push
git pull --rebase origin main
# resolve any conflicts
git push
Always pull before pushing to avoid rejection errors and surprise conflicts.
Commit Before You Pull
If you have local changes, commit or stash them before pulling. Uncommitted changes can conflict with the pull and leave you in a messy state.
Use .gitignore From the Start
Create your .gitignore before the first commit. It is much harder to remove tracked files from history than to never track them.
Never Commit Secrets
# .gitignore
.env
*.key
*.pem
secrets/
If you accidentally commit a secret:
- Rotate the credential immediately
- Remove it from history with
git 筛选-仓库or BFG - Add it to
.gitignore
History Hygiene
Rebase Before Merging
Keep your history linear by rebasing feature branches before merging:
git checkout feature-branch
git fetch origin
git rebase origin/main
git checkout main
git merge feature-branch # fast-forward, no merge commit
Squash WIP Commits
Use interactive rebase to squash "WIP" commits before pushing:
git rebase -i origin/main
# squash your work-in-progress commits into clean, meaningful ones
Do Not Rewrite Shared History
Never rebase or amend commits that others have pulled. Use git revert instead of git reset on shared branches.
Team Conventions
- Agree on a workflow: GitHub Flow, Git Flow, or Trunk-Based — pick one and document it
- Require PR reviews: protect
主要with branch protection rules - Use PR templates: create
.github/pull_request_template.mdfor consistent descriptions - Enforce commit conventions: use commit-msg hooks or tools like commitlint
- Automate with CI: run tests and linting on every PR
- Keep main always green: main should always be deployable
The Golden Habits
- Commit small, atomic changes with clear messages
- Pull before you push (
git 拉取 --rebase) - Use feature branches with descriptive names
- Review every PR before merging
- Never commit secrets — use .gitignore
- Never rewrite shared history — use revert, not reset
- Test before you commit — or let hooks do it for you
- Keep main deployable — always green, always tested
示例代码
# --- Atomic commits: one logical change per commit ---
git add src/auth/login.js
git commit -m "feat(auth): add JWT token generation on login"
git add src/auth/refresh.js
git commit -m "feat(auth): add refresh token rotation"
git add src/auth/middleware.js
git commit -m "refactor(auth): extract token validation into middleware"
# --- Daily workflow: pull, work, commit, push ---
git checkout main
git pull --rebase origin main
git checkout -b feature/user-settings
# ... make changes ...
git add .
git commit -m "feat(settings): add user preference management"
# Keep your branch updated with main
git fetch origin
git rebase origin/main
git push -u origin feature/user-settings
# Open a PR, get review, merge
# --- Clean up before a PR ---
git rebase -i origin/main
# squash WIP commits, reword messages, reorder
# --- Protect main: never commit directly ---
# On GitHub: Settings > Branches > Branch protection rules
# - Require pull request reviews before merging
# - Require status checks to pass before merging
# - Require branches to be up to date before merging
# --- Use a PR template ---
mkdir -p .github
cat > .github/pull_request_template.md << 'EOF'
## What
<!-- Describe what this PR does -->
## Why
<!-- Link to issue, explain the motivation -->
## Testing
- [ ] Unit tests pass
- [ ] Manual testing done
## Checklist
- [ ] No console.log left in code
- [ ] No secrets committed
EOF
# --- Never commit secrets ---
echo ".env" >> .gitignore
echo "*.key" >> .gitignore
echo "secrets/" >> .gitignore
git add .gitignore
git commit -m "chore: update gitignore for secrets"
# --- If you accidentally committed a secret ---
git rm --cached .env
git commit -m "fix: stop tracking .env file"
# Then rotate the leaked credential immediately!
# Use git filter-repo to purge from history if needed
Shows atomic 提交使用 Conventional 提交消息, daily 拉取-工作-提交-推送 workflow, keeping 分支更新使用 rebase, cleaning 上 history 之前 PR, 设置分支 protection and PR templates, and handling secrets properly. 这些 habits separate professional Git usage 从 amateur.
动手试一试
- .gitignore Generator
Generate comprehensive .gitignore 到 keep 你的仓库 clean.
- CI/CD YAML Generator
设置 CI 到 enforce 最佳实践 automatically on 每个推送.
常见错误
错误写法
Committing 大, unrelated 更改 in one giant 提交
正确做法
制作 atomic 提交 — one logical 更改每 提交. Use git 添加 <特定-files> 相反的 git 添加 . 到 stage 仅 related 更改. 如果你 有 already committed 一切 together, 你能 use interactive rebase (git rebase -i) 到拆分提交之前 pushing.
错误写法
Committing directly 到主要相反的 using feature 分支 and PRs
正确做法
从不提交 directly 到主要 on shared 项目. 创建 feature 分支, 制作你的更改, 推送, and 打开拉取请求 for review. 启用分支 protection on GitHub 到 prevent direct pushes 到主要. 这个 ensures 每个更改是 reviewed and tested 之前它 lands.
相关资源
相关代码片段
- Git Log Snippet
Inspect 你的 history 到验证最佳实践是 followed.
相关速查表
- Git Cheatsheet
最佳实践, 约定, and professional Git workflows.
练习 Git 最佳实践
6 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。