Git version control patterns, branching strategies, and team collaboration best practices.
Git版本控制模式、分支策略以及团队协作最佳实践。
main ─────●────────────●─────────────●───────────
\ / \
\ release/1.0 release/1.1
\ / \ /
develop ──────●───●──────●────●──────●────────────
\ / \ /
feature/ feature/ feature/
login payment search
main ─────●────────────●─────────────●───────────
\ / \
\ release/1.0 release/1.1
\ / \ /
develop ──────●───●──────●────●──────●────────────
\ / \ /
feature/ feature/ feature/
login payment search
Initialize git flow
Initialize git flow
Start a new feature
Start a new feature
git flow feature start user-authentication
git flow feature start user-authentication
Work on feature...
Work on feature...
git flow feature finish user-authentication
git flow feature finish user-authentication
Start a release
Start a release
git flow release start 1.0.0
git flow release start 1.0.0
Bug fixes only...
Bug fixes only...
git flow release finish 1.0.0
git flow release finish 1.0.0
Hotfix for production
Hotfix for production
git flow hotfix start critical-bug
git flow hotfix finish critical-bug
git flow hotfix start critical-bug
git flow hotfix finish critical-bug
GitHub Flow (Simplified)
GitHub Flow(简化版)
main ─────●──────●──────●──────●──────●───────
\ / \ / \
feature/ feature/ feature/
add-auth fix-bug new-ui
main ─────●──────●──────●──────●──────●───────
\ / \ / \
feature/ feature/ feature/
add-auth fix-bug new-ui
1. Create branch from main
1. Create branch from main
git checkout main
git pull origin main
git checkout -b feature/add-authentication
git checkout main
git pull origin main
git checkout -b feature/add-authentication
2. Make changes and commit
2. Make changes and commit
git add .
git commit -m "feat: add user authentication"
git add .
git commit -m "feat: add user authentication"
3. Push and create PR
3. Push and create PR
git push -u origin feature/add-authentication
gh pr create --title "Add user authentication" --body "..."
git push -u origin feature/add-authentication
gh pr create --title "Add user authentication" --body "..."
4. After review, merge via GitHub
4. After review, merge via GitHub
5. Delete branch
5. Delete branch
git checkout main
git pull origin main
git branch -d feature/add-authentication
git checkout main
git pull origin main
git branch -d feature/add-authentication
Trunk-Based Development
基于主干的开发
main ────●──●──●──●──●──●──●──●──●────
│ │ │
└─────┴────────┴─── short-lived branches (< 1 day)
main ────●──●──●──●──●──●──●──●──●────
│ │ │
└─────┴────────┴─── 短期分支(<1天)
Small, frequent commits directly to main or via short-lived branches
小型、频繁的提交,直接提交到主干或通过短期分支
git checkout main
git pull
git checkout -b fix/typo-in-readme
git checkout main
git pull
git checkout -b fix/typo-in-readme
Make small change...
进行小修改...
git commit -m "fix: typo in README"
git push -u origin fix/typo-in-readme
git commit -m "fix: typo in README"
git push -u origin fix/typo-in-readme
PR, review, merge same day
当日完成PR、评审与合并
Stage specific changes
暂存特定更改
git add -p # Interactive staging
Commit with message
附带信息提交
git commit -m "feat(auth): add JWT token validation"
git commit -m "feat(auth): add JWT token validation"
Amend last commit (not pushed)
修改最后一次提交(未推送)
git commit --amend -m "feat(auth): add JWT token validation and refresh"
git commit --amend -m "feat(auth): add JWT token validation and refresh"
Commit with co-author
联合作者提交
git commit -m "feat: implement feature
Co-authored-by: Name email@example.com"
git commit -m "feat: implement feature
Co-authored-by: Name email@example.com"
Empty commit (trigger CI)
空提交(触发CI)
git commit --allow-empty -m "chore: trigger CI build"
git commit --allow-empty -m "chore: trigger CI build"
Conventional Commits
规范化提交格式
<type>(<scope>): <description>
[optional body]
[optional footer(s)]
| Type | Description |
|---|
| feat | New feature |
| fix | Bug fix |
| docs | Documentation only |
| style | Formatting, no code change |
| refactor | Code change, no new feature or fix |
| perf | Performance improvement |
| test | Adding tests |
| chore | Build, CI, tooling |
<type>(<scope>): <description>
[可选正文]
[可选页脚]
| 类型 | 说明 |
|---|
| feat | 新功能 |
| fix | Bug修复 |
| docs | 仅文档更新 |
| style | 格式调整,无代码逻辑变更 |
| refactor | 代码重构,无新功能或Bug修复 |
| perf | 性能优化 |
| test | 添加测试 |
| chore | 构建、CI、工具链相关 |
git commit -m "feat(api): add user registration endpoint"
git commit -m "fix(auth): handle expired token refresh"
git commit -m "docs: update API documentation"
git commit -m "refactor(db): extract connection pool logic"
git commit -m "test(user): add unit tests for validation"
git commit -m "feat(api): add user registration endpoint"
git commit -m "fix(auth): handle expired token refresh"
git commit -m "docs: update API documentation"
git commit -m "refactor(db): extract connection pool logic"
git commit -m "test(user): add unit tests for validation"
Create and switch to branch
创建并切换到分支
git checkout -b feature/new-feature
git checkout -b feature/new-feature
git switch -c feature/new-feature
git switch -c feature/new-feature
git branch -a # All branches
git branch -vv # With tracking info
git branch -a # 所有分支
git branch -vv # 包含跟踪信息
git branch -d feature/merged-branch # Safe delete
git branch -D feature/unmerged-branch # Force delete
git branch -d feature/merged-branch # 安全删除
git branch -D feature/unmerged-branch # 强制删除
git branch -m old-name new-name
git branch -m old-name new-name
git branch --set-upstream-to=origin/main main
git branch --set-upstream-to=origin/main main
Merge branch into current
将分支合并到当前分支
Merge with no fast-forward (always create merge commit)
禁用快进合并(始终创建合并提交)
git merge --no-ff feature/branch
git merge --no-ff feature/branch
Squash merge (combine all commits)
squash合并(合并所有提交)
git merge --squash feature/branch
git commit -m "feat: add feature (squashed)"
git merge --squash feature/branch
git commit -m "feat: add feature (squashed)"
Rebase current branch onto main
将当前分支变基到主干
git fetch origin
git rebase origin/main
git fetch origin
git rebase origin/main
Interactive rebase (last 3 commits)
交互式变基(最近3次提交)
In editor, change 'pick' to:
在编辑器中,将'pick'改为:
- squash (s): combine with previous
- squash (s): 与前一次提交合并
- fixup (f): combine, discard message
- fixup (f): 合并并丢弃提交信息
- reword (r): change commit message
- reword (r): 修改提交信息
- edit (e): stop for amending
- edit (e): 暂停以修改提交
- drop (d): remove commit
- drop (d): 删除提交
Continue rebase after resolving conflicts
解决冲突后继续变基
git add .
git rebase --continue
git add .
git rebase --continue
git stash
git stash push -m "work in progress"
git stash
git stash push -m "work in progress"
Stash including untracked files
暂存包含未跟踪文件
git stash pop # Apply and remove
git stash apply # Apply and keep
git stash apply stash@{2} # Apply specific
git stash pop # 应用并删除暂存
git stash apply # 应用并保留暂存
git stash apply stash@{2} # 应用指定暂存
Show stash contents
查看暂存内容
git stash show -p stash@{0}
git stash show -p stash@{0}
git stash drop stash@{0}
git stash clear # Drop all
git stash drop stash@{0}
git stash clear # 删除所有暂存
Discard changes in working directory
丢弃工作区的更改
git checkout -- file.txt
git restore file.txt # Git 2.23+
git checkout -- file.txt
git restore file.txt # Git 2.23+
git reset HEAD file.txt
git restore --staged file.txt # Git 2.23+
git reset HEAD file.txt
git restore --staged file.txt # Git 2.23+
Reset to previous commit (keep changes staged)
重置到上一次提交(保留更改在暂存区)
Reset to previous commit (keep changes unstaged)
重置到上一次提交(保留更改在工作区)
git reset HEAD1
git reset --mixed HEAD1
git reset HEAD1
git reset --mixed HEAD1
Reset to previous commit (discard changes)
重置到上一次提交(丢弃所有更改)
Revert a commit (create new commit that undoes)
撤销提交(创建新提交来抵消原提交)
Revert merge commit
撤销合并提交
git revert -m 1 <merge-commit-hash>
git revert -m 1 <merge-commit-hash>
.git/hooks/pre-commit
.git/hooks/pre-commit
npm run lint
if [ $? -ne 0 ]; then
echo "Linting failed. Please fix errors before committing."
exit 1
fi
npm run lint
if [ $? -ne 0 ]; then
echo "代码检查失败,请修复错误后再提交。"
exit 1
fi
npm run type-check
if [ $? -ne 0 ]; then
echo "Type checking failed. Please fix errors before committing."
exit 1
fi
npm run type-check
if [ $? -ne 0 ]; then
echo "类型检查失败,请修复错误后再提交。"
exit 1
fi
Check for console.log
检查是否存在console.log
if git diff --cached | grep -E '^+.*console.(log|debug|info)' > /dev/null; then
echo "Warning: Found console.log statements. Remove before committing."
exit 1
fi
if git diff --cached | grep -E '^+.*console.(log|debug|info)' > /dev/null; then
echo "警告:发现console.log语句,请在提交前移除。"
exit 1
fi
Husky + lint-staged
Husky + lint-staged
json
// package.json
{
"scripts": {
"prepare": "husky install"
},
"lint-staged": {
"*.{js,ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md,yml}": [
"prettier --write"
]
}
}
json
// package.json
{
"scripts": {
"prepare": "husky install"
},
"lint-staged": {
"*.{js,ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md,yml}": [
"prettier --write"
]
}
}
.husky/pre-commit
.husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
.husky/commit-msg
.husky/commit-msg
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no -- commitlint --edit "$1"
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no -- commitlint --edit "$1"
Apply specific commit to current branch
将指定提交应用到当前分支
git cherry-pick <commit-hash>
git cherry-pick <commit-hash>
Cherry-pick multiple commits
拣选多个提交
git cherry-pick <commit1> <commit2> <commit3>
git cherry-pick <commit1> <commit2> <commit3>
Cherry-pick without committing
拣选提交但不自动提交
git cherry-pick -n <commit-hash>
git cherry-pick -n <commit-hash>
Cherry-pick merge commit
拣选合并提交
git cherry-pick -m 1 <merge-commit-hash>
git cherry-pick -m 1 <merge-commit-hash>
Bisect (Find Bug Introduction)
二分查找(定位Bug引入点)
Mark current as bad
标记当前提交为有问题
Mark known good commit
标记已知正常的提交
Git checks out middle commit, test and mark
Git会检出中间提交,测试后标记
git bisect good # or
git bisect bad
git bisect good # 或
git bisect bad
Repeat until found
重复直到找到问题提交
Git reports the first bad commit
Git会报告第一个有问题的提交
git bisect start HEAD v1.0.0
git bisect run npm test
git bisect start HEAD v1.0.0
git bisect run npm test
Create worktree for parallel work
创建工作树以并行开发
git worktree add ../project-hotfix hotfix/urgent-fix
git worktree add ../project-feature feature/new-feature
git worktree add ../project-hotfix hotfix/urgent-fix
git worktree add ../project-feature feature/new-feature
git worktree remove ../project-hotfix
git worktree remove ../project-hotfix
Clone with submodules
克隆包含子模块的项目
git submodule update --init --recursive
git submodule update --init --recursive
Pull submodule updates
拉取子模块更新
git submodule update --remote
git submodule update --remote
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global init.defaultBranch main
git config --global core.editor "code --wait"
git config --global core.editor "code --wait"
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.lg "log --oneline --graph --all"
git config --global alias.unstage "reset HEAD --"
git config --global alias.last "log -1 HEAD"
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.lg "log --oneline --graph --all"
git config --global alias.unstage "reset HEAD --"
git config --global alias.last "log -1 HEAD"
git config --global pull.rebase true
git config --global pull.rebase true
Auto-setup remote tracking
自动设置远程跟踪
git config --global push.autoSetupRemote true
git config --global push.autoSetupRemote true
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'
- [[devops-cicd]] - CI/CD with Git
- [[code-quality]] - Code review practices
- [[project-management]] - Agile workflows
- [[devops-cicd]] - 基于Git的CI/CD
- [[code-quality]] - 代码评审实践
- [[project-management]] - 敏捷工作流