第三章:Git 版本控制基础
最后更新: 2024-01-01
作者: DevOps Team
页面目录
第三章:Git 版本控制基础
Git 是现代软件开发中不可或缺的版本控制系统。本章将深入讲解 Git 的核心概念、常用命令以及团队协作的最佳实践。
3.1 Git 核心概念
3.1.1 Git 工作区域
┌─────────────────────────────────────────────────────────────┐
│ 工作目录 │
│ (Working Directory) │
└─────────────────────────────────────────────────────────────┘
↓ git add
↓
┌─────────────────────────────────────────────────────────────┐
│ 暂存区 │
│ (Staging Area) │
│ Index / Cache │
└─────────────────────────────────────────────────────────────┘
↓ git commit
↓
┌─────────────────────────────────────────────────────────────┐
│ 本地仓库 │
│ (Local Repository) │
│ .git directory │
└─────────────────────────────────────────────────────────────┘
↓ git push
↓
┌─────────────────────────────────────────────────────────────┐
│ 远程仓库 │
│ (Remote Repository) │
│ GitHub/GitLab/Gitea │
└─────────────────────────────────────────────────────────────┘
3.1.2 三种状态
| 状态 | 说明 | Git 命令 |
|---|---|---|
| Modified | 文件已修改但未暂存 | - |
| Staged | 文件已修改并已添加到暂存区 | git add |
| Committed | 文件已提交到本地仓库 | git commit |
3.2 基础命令
3.2.1 仓库初始化与克隆
# 在当前目录初始化新仓库
git init
# 克隆远程仓库
git clone https://github.com/user/repo.git
git clone https://github.com/user/repo.git my-folder
# 克隆特定分支
git clone -b develop https://github.com/user/repo.git
# 浅克隆 (加快下载速度)
git clone --depth 1 https://github.com/user/repo.git
3.2.2 基本操作
# 查看工作目录状态
git status
# 查看详细状态
git status -s
# 输出格式: [状态][状态] [文件路径]
# M = Modified
# A = Added
# D = Deleted
# R = Renamed
# ?? = Untracked
# 暂存文件
git add filename.txt # 暂存单个文件
git add file1.txt file2.txt # 暂存多个文件
git add *.txt # 使用通配符
git add . # 暂存所有变化
git add -A # 暂存所有变化 (包括删除)
git add -p # 交互式暂存 (选择性地暂存部分修改)
# 提交更改
git commit -m "提交信息"
git commit -m "feat: 添加新功能" # 格式: type: description
git commit -m "fix: 修复登录bug" # fix: 修复bug
git commit -m "docs: 更新文档" # docs: 文档更新
git commit -m "style: 代码格式调整" # style: 格式
git commit -m "refactor: 重构代码" # refactor: 重构
git commit -m "test: 添加测试" # test: 测试
git commit -m "chore: 构建/工具变更" # chore: 维护
# 追加修改到上一个提交
git add .
git commit --amend --no-edit
# 修改提交信息
git commit --amend -m "新的提交信息"
3.2.3 查看历史
# 查看提交历史
git log
git log --oneline # 简洁模式
git log --oneline --graph # 图形化显示
git log --oneline -n 10 # 最近10条
git log --author="author name" # 按作者筛选
git log --since="2024-01-01" # 按时间筛选
git log --grep="keyword" # 按关键词搜索
git log -p filename # 查看文件的变更历史
# 查看差异
git diff # 工作区 vs 暂存区
git diff --staged # 暂存区 vs 上次提交
git diff HEAD # 工作区 vs HEAD
git diff commit1 commit2 # 两个提交之间的差异
git diff --name-only # 只显示文件名
git diff branch1 branch2 # 分支间的差异
3.3 分支管理
3.3.1 分支基础操作
# 查看分支
git branch # 本地分支
git branch -a # 所有分支 (本地+远程)
git branch -r # 远程分支
# 创建分支
git branch feature/new-feature # 创建但不切换
git checkout -b feature/new-feature # 创建并切换
git switch -c feature/new-feature # 同上 (新语法)
# 切换分支
git checkout main
git switch main
git switch - # 切换到上一个分支
# 删除分支
git branch -d feature/old-feature # 安全删除 (未合并会警告)
git branch -D feature/old-feature # 强制删除
# 重命名分支
git branch -m old-name new-name
3.3.2 合并分支
# 合并分支
git checkout main
git merge feature/new-feature
# 解决合并冲突
# 1. 打开冲突文件
# 2. 手动编辑解决冲突
# 3. 暂存解决后的文件
git add conflicted-file.txt
git commit -m "resolve merge conflict"
# 取消合并
git merge --abort
3.3.3 Rebase 操作
# 变基操作 - 将当前分支的修改应用到目标分支之上
git checkout feature/new-feature
git rebase main
# 交互式变基 - 修改提交历史
git rebase -i HEAD~3 # 修改最近3个提交
# 变基选项:
# pick - 保留该提交
# squash - 将提交合并到上一个
# reword - 修改提交信息
# edit - 暂停以修改提交
# drop - 删除提交
# 危险操作:同步远程分支
git rebase origin/main
3.4 远程仓库操作
3.4.1 远程仓库管理
# 查看远程仓库
git remote -v
# 添加远程仓库
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git
# 重命名远程仓库
git remote rename origin upstream
# 删除远程仓库
git remote remove origin
# 修改远程仓库 URL
git remote set-url origin https://github.com/user/new-repo.git
3.4.2 推送和拉取
# 推送到远程仓库
git push # 推送到默认分支
git push origin main # 推送到指定分支
git push -u origin feature/branch # 设置上游分支
git push --force # 强制推送 (谨慎使用!)
git push --force-with-lease # 安全强制推送
# 从远程拉取
git pull # 拉取并合并
git pull origin main # 拉取指定分支
git pull --rebase # 使用 rebase 方式拉取
# 获取远程更新 (不合并)
git fetch origin
git fetch --all # 获取所有远程
# 拉取远程分支
git checkout -b feature/branch origin/feature/branch
git checkout --track origin/feature/branch
3.5 Git 工作流
3.5.1 Git Flow 工作流
develop
↑
┌──────┴──────┐
↓ ↓
feature/* release/*
↓ ↓
└──────┬──────┘
↓
main
↓
hotfix/*
# Git Flow 命令示例
# 开始新功能
git checkout develop
git checkout -b feature/new-feature
# ... 开发完成后 ...
git checkout develop
git merge --no-ff feature/new-feature
git branch -d feature/new-feature
# 创建发布分支
git checkout -b release/1.0.0 develop
# ... 完成发布 ...
git checkout main
git merge release/1.0.0 --no-ff
git tag -a v1.0.0 -m "Release version 1.0.0"
git checkout develop
git merge release/1.0.0 --no-ff
git branch -d release/1.0.0
# 紧急修复
git checkout -b hotfix/bugfix main
# ... 修复完成后 ...
git checkout main
git merge hotfix/bugfix --no-ff
git tag -a v1.0.1 -m "Hotfix version 1.0.1"
git checkout develop
git merge hotfix/bugfix --no-ff
git branch -d hotfix/bugfix
3.5.2 GitHub Flow
适用于持续部署的团队:
# 1. 从 main 创建功能分支
git checkout -b feature/new-feature
# 2. 在分支上开发并提交
git add .
git commit -m "feat: implement new feature"
# 3. 推送分支到远程
git push -u origin feature/new-feature
# 4. 创建 Pull Request
# 在 GitHub/GitLab 上操作
# 5. 代码审查后合并到 main
# 在 GitHub/GitLab 上操作
# 6. 删除分支
git branch -d feature/new-feature
git push origin --delete feature/new-feature
3.5.3 trunk-based Development
# 所有开发者从 main/trunk 创建短期分支
git checkout -b feature/tiny-fix main
git checkout -b feature/another-fix main
# 频繁集成到 main
git checkout main
git merge feature/tiny-fix --no-ff
git push origin main
3.6 团队协作规范
3.6.1 Git 提交信息规范
推荐使用 Conventional Commits 规范:
<type>(<scope>): <subject>
<body>
<footer>
Type 类型:
| Type | Description |
|---|---|
| feat | 新功能 |
| fix | Bug 修复 |
| docs | 文档变更 |
| style | 代码格式 (不影响代码运行) |
| refactor | 重构 (非功能变更) |
| perf | 性能优化 |
| test | 测试相关 |
| build | 构建系统或依赖变更 |
| ci | CI 配置变更 |
| chore | 其他杂项 |
示例:
feat(auth): 添加 OAuth2 登录支持
实现了 Google 和 GitHub 的 OAuth2 登录功能
- 添加 OAuth2 回调处理
- 集成社交登录按钮
- 添加登录状态管理
Closes #123
3.6.2 .gitignore 配置
# .gitignore 示例
# 操作系统
.DS_Store
Thumbs.db
# IDE
.idea/
.vscode/
*.swp
*.swo
# 依赖
node_modules/
vendor/
bower_components/
# 构建产物
dist/
build/
target/
*.class
*.jar
*.war
# 日志
*.log
logs/
# 环境配置
.env
.env.local
*.local
# 测试覆盖率
coverage/
.nyc_output/
# Docker
.dockerignore
# Terraform
*.tfstate
*.tfstate.*
.terraform/
3.6.3 Git Hooks
# 创建 pre-commit hook
mkdir -p .git/hooks
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
# 禁止直接提交到 main
branch=$(git symbolic-ref --short HEAD)
if [ "$branch" = "main" ]; then
echo "Error: Direct commit to main is not allowed!"
exit 1
fi
# 运行测试
npm test
# 代码格式检查
npm run lint
EOF
chmod +x .git/hooks/pre-commit
3.7 高级技巧
3.7.1 贮藏 (Stash)
# 贮藏当前修改
git stash
git stash save "工作进度备注"
# 查看贮藏列表
git stash list
# 输出: stash@{0}: WIP on main: abc123 feat: add feature
# 应用最新贮藏
git stash pop
# 应用指定贮藏
git stash apply stash@{1}
# 删除贮藏
git stash drop stash@{0}
git stash clear # 清空所有
3.7.2 标签 (Tag)
# 创建标签
git tag v1.0.0 # 轻量标签
git tag -a v1.0.0 -m "Version 1.0.0" # 注解标签
# 列出标签
git tag
git tag -l "v1.*"
# 查看标签详情
git show v1.0.0
# 推送标签
git push origin v1.0.0 # 推送单个
git push origin --tags # 推送所有
# 删除标签
git tag -d v1.0.0 # 删除本地
git push origin --delete v1.0.0 # 删除远程
3.7.3 Bisect 二分查找
# 开始二分查找
git bisect start
# 指定已知有问题的版本
git bisect bad
# 指定已知正常的版本
git bisect good v1.0.0
# Git 会自动检出中间的版本
# 测试后标记
git bisect good # 或 git bisect bad
# Git 会继续检出下一个版本
# ...
# 找到问题后重置
git bisect reset
3.8 Git 配置最佳实践
3.8.1 全局配置
# 用户信息
git config --global user.name "Your Name"
git config --global user.email "your.email@company.com"
# 默认分支
git config --global init.defaultBranch main
# 颜色输出
git config --global color.ui auto
# 拉取策略
git config --global pull.rebase false # merge (默认)
git config --global pull.rebase true # rebase
git config --global pull.ff only # fast-forward only
# 推送策略
git config --global push.default current
# 记住所拉取的分支
git config --global push.followTags true
# 别名
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.df diff
git config --global alias.lg "log --oneline --graph --all"
3.8.2 仓库级别配置
# 针对单个仓库的配置
git config user.name "Project Name"
git config user.email "project@company.com"
# 查看配置
git config --list --local
git config --list --global
git config --list --system
3.9 本章小结
| 分类 | 关键命令 |
|---|---|
| 基础操作 | git init, git clone, git add, git commit |
| 查看历史 | git log, git diff, git status |
| 分支管理 | git branch, git checkout, git merge, git rebase |
| 远程操作 | git push, git pull, git fetch |
| 协作工具 | git stash, git tag, git bisect |
📌 下一章预告
下一章我们将学习 持续集成与持续部署 (CI/CD),包括:
- CI/CD 核心概念
- Jenkins 流水线配置
- GitLab CI/GitHub Actions 使用
- ArgoCD 部署策略
💡 提示:建议团队制定统一的 Git 工作流和提交规范,并在项目初期通过 Git Hooks 强制执行这些规范。