Appearance
Git 最佳实践
本章总结了Git开发中的最佳实践,涵盖工作流程、提交规范、分支管理、安全实践等方面。
项目结构和初始化
仓库初始化
bash
# 1. 创建有意义的仓库名称
# - 使用小写字母和连字符
# - 遌输项目目的
# - 避免特殊字符
# 2. 初始化仓库
git init
git remote add origin https://github.com/username/project-name.git
# 3. 创建初始提交
echo "# Project Name" > README.md
echo "Project description" >> README.md
git add README.md
git commit -m "docs: initial commit with README"
git branch -M main
git push -u origin main
项目文件结构
bash
# 标准项目结构
project/
├── .git/
├── .github/ # GitHub配置
│ ├── ISSUE_TEMPLATE/
│ ├── PULL_REQUEST_TEMPLATE.md
│ └── workflows/
├── .gitignore # Git忽略文件
├── .gitattributes # Git属性配置
├── README.md # 项目说明
├── LICENSE # 许可证
├── CONTRIBUTING.md # 贡献指南
├── CODE_OF_CONDUCT.md # 行为准则
├── package.json # 项目配置
├── docs/ # 文档
├── src/ # 源代码
├── tests/ # 测试代码
├── scripts/ # 脚本文件
└── config/ # 配置文件
提交规范
约定式提交
bash
# 使用约定式提交格式
git commit -m "type(scope): description"
# 提交类型说明
# feat: 新功能
git commit -m "feat(auth): add user login functionality"
# fix: 修复bug
git commit -m "fix(api): resolve timeout in user service"
# docs: 文档更新
git commit -m "docs: update authentication API documentation"
# style: 代码格式调整
git commit -m "style: format authentication code"
# refactor: 代码重构
git commit -m "refactor: improve auth module structure"
# test: 测试相关
git commit -m "test: add authentication unit tests"
# chore: 构建工具或辅助工具变动
git commit -m "chore: update dependencies"
提交信息最佳实践
bash
# 提交信息格式
# 第一行:简短描述(50字符以内)
# 空行
# 主体:详细描述(72字符以内每行)
# 空行
# 页脚:引用信息
# 好的提交信息示例
git commit -m "feat(auth): implement secure user authentication
- Add JWT token generation and validation
- Implement password hashing with bcrypt
- Add rate limiting for login attempts
Closes #123
BREAKING CHANGE: Changes authentication flow"
# 避免的提交信息
git commit -m "fix stuff" # 太
git commit -m "changed some files" # 太
git commit -m "forgot to add this" # 太
分支管理策略
分支命名规范
bash
# 功能分支
feature/user-authentication
feature/payment-integration
feature/dashboard-redesign
# 修复分支
bugfix/login-error
bugfix/security-patch
bugfix/performance-issue
# 热修复分支
hotfix/critical-security-fix
hotfix/urgent-bug-fix
# 发布分支
release/v1.2.0
release/v2.0.0-rc1
# 实验分支
experiment/new-feature
wip/work-in-progress
分支操作最佳实践
bash
# 1. 从最新main分支创建功能分支
git checkout main
git pull origin main
git checkout -b feature/new-feature
# 2. 频繁同步main分支到功能分支
git checkout feature/new-feature
git fetch origin
git rebase origin/main
# 3. 保持功能分支更新
git checkout feature/new-feature
git pull --rebase origin main
# 4. 合并前清理提交历史
git rebase -i HEAD~n # 整理n个提交
# 5. 完成功能后清理分支
git checkout main
git pull origin main
git merge --no-ff feature/new-feature
git branch -d feature/new-feature
git push origin --delete feature/new-feature
代码审查流程
Pull Request最佳实践
bash
# PR标题规范
# feat: Add user authentication module
# fix: Resolve login timeout issue
# docs: Update API documentation
# PR描述模板
"""
## 变更内容
简要描述本次变更
## 实现细节
详细说明实现方式
## 测试验证
- [ ] 单元测试通过
- [ ] 集成测试通过
- [ ] 手动测试验证
## 相关问题
- Closes #issue-number
- Related to #issue-number
"""
代码审查清单
bash
# 代码审查检查清单
# [ ] 代码符合项目规范
# [ ] 功能按预期工作
# [ ] 测试覆盖充分
# [ ] 文档更新完整
# [ ] 没有安全问题
# [ ] 性能无负面影响
# [ ] 代码易于维护
# [ ] 遵循DRY原则
# [ ] 遵循SOLID原则
# [ ] 错误处理恰当
安全最佳实践
敏感信息保护
bash
# 1. 配置.gitignore防止敏感文件提交
cat >> .gitignore << EOF
# Environment variables
.env
.env.local
.env.*.local
# Certificates and keys
*.key
*.pem
*.crt
*.cer
config/secrets.yml
# Logs
*.log
logs/
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
EOF
# 2. 使用环境变量
# 在代码中使用环境变量而非硬编码
const apiKey = process.env.API_KEY ;
# 3. 定期轮换密钥
# 使用短期有效的密钥
# 定期更新和轮换
GPG签名验证
bash
# 1. 生成GPG密钥
gpg --full-generate-key
# 2. 配置Git使用GPG签名
git config --global user.signingkey YOUR_KEY_ID
git config --global commit.gpgsign true
# 3. 签名提交
git commit -S -m "Signed commit message"
# 4. 签名标签
git tag -s v1.0.0 -m "Signed version tag"
工作流最佳实践
Git Flow工作流
bash
# 1. 初始化Git Flow
git flow init
# 2. 开发功能
git flow feature start user-authentication
# 开发...
git flow feature finish user-authentication
# 3. 准备发布
git flow release start v1.2.0
# 测试和修复...
git flow release finish v1.2.0
# 4. 紧急修复
git flow hotfix start security-patch
# 修复...
git flow hotfix finish security-patch
GitHub Flow工作流
bash
# 1. 从main创建功能分支
git checkout main
git pull origin main
git checkout -b feature/new-feature
# 2. 开发并推送
git add .
git commit -m "feat: implement new feature"
git push -u origin feature/new-feature
# 3. 创建Pull Request
# 4. 代码审查
# 5. 合并Pull Request
# 6. 清理分支
git checkout main
git pull origin main
git branch -d feature/new-feature
性能优化
仓库性能优化
bash
# 1. 使用Git LFS处理大文件
git lfs install
git lfs track "*.psd"
git lfs track "*.zip"
git add .gitattributes
# 2. 配置性能优化
git config --global core.preloadindex true
git config --global core.fscache true
git config --global core.untrackedCache true
# 3. 定期清理仓库
git gc --aggressive --prune=now
git remote prune origin
网络优化
bash
# 1. 使用SSH而非HTTPS
git remote set-url origin git@github.com:username/repo.git
# 2. 配置网络优化
git config --global http.postBuffer 1048576000 # 1GB
git config --global fetch.parallel 4
# 3. 使用浅克隆
git clone --depth 1 https://github.com/username/repo.git
团队协作最佳实践
权限管理
bash
# 1. 设置分支保护规则
# - 需要拉取请求审查
# - 需要状态检查
# - 禁止强制推送
# - 禁止直接推送到main
# 2. 配置代码所有者
# .github/CODEOWNERS
* @maintainers
src/auth/ @auth-team
docs/ @documentation-team
沟通规范
bash
# 1. 使用标准Issue模板
# .github/ISSUE_TEMPLATE/feature_request.md
"""
---
name: 功能请求
about: 请求新功能
title: '[Feature] '
labels: 'enhancement'
assignees: ''
---
## 功能描述
## 业务价值
## 实现方案
## 优先级
"""
# 2. 配置贡献指南
# CONTRIBUTING.md
"""
# 贡献指南
## 开发环境设置
## 分支策略
## 代码规范
## 提交信息规范
"""
自动化最佳实践
Git Hooks
bash
# 使用Husky配置Git钩子
npm install --save-dev husky lint-staged
# package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["eslint --fix", "git add"]
}
}
CI/CD集成
yaml
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npm test
- run: npm run lint
- run: npm run build
监控和审计
提交审计
bash
# 1. 定期审查提交历史
git log --oneline --graph --all
# 2. 检查敏感信息
git log --all --full-history -- "*password*" "*secret*" "*token*"
# 3. 使用安全扫描工具
# GitLeaks, TruffleHog等
仓库健康检查
bash
# 1. 检查仓库完整性
git fsck
# 2. 检查仓库大小
du -sh .git
git count-objects -v
# 3. 优化仓库
git gc --aggressive
git repack -ad
故障排除最佳实践
问题诊断
bash
# 1. 使用详细日志
git config --global trace2.normalTarget /tmp/trace.log
# 2. 常用诊断命令
git status # 检查仓库状态
git log --oneline -10 # 查看最近提交
git remote -v # 查看远程仓库
git config --list # 查看配置
git fsck # 检查仓库完整性
# 3. 恢复误操作
git reflog # 查看操作历史
git reset --hard HEAD@{1} # 恢复到上一状态
文档最佳实践
项目文档
bash
# 1. 维护README.md
# - 项目简介
# - 安装说明
# - 使用示例
# - 贡献指南
# - 许可证信息
# 2. 创建CHANGELOG.md
# 记录版本变更历史
# 遵循语义化版本控制
# 3. 维护CONTRIBUTING.md
# - 开发环境设置
# - 分支策略
# - 代码规范
# - 提交规范
这些最佳实践能够帮助团队建立规范的Git工作流程,提高代码质量和协作效率。