Day04_Git完全指南:从入门到精通的版本控制精通

面向前端团队的 Git 实战博客:覆盖环境准备、三区模型、基础命令、分支协作、远程仓库与工作流。理论参考 Pro GitGit 官方文档GitHub Docs

目录

  • [0. 知识脉络与名词百科](#0. 知识脉络与名词百科)
    • [0.1 本章知识图谱](#0.1 本章知识图谱)
    • [0.2 核心名词解析](#0.2 核心名词解析)
  • [1. Git概述与核心概念](#1. Git概述与核心概念)
    • [1.3 Git的文件状态](#1.3 Git的文件状态)
    • [1.4 .git 目录结构](#1.4 .git 目录结构)
    • [1.5 开发环境准备(Linux 与 Vim)](#1.5 开发环境准备(Linux 与 Vim))
    • [1.6 Git对象模型与内部原理](#1.6 Git对象模型与内部原理)
  • [2. Git安装与环境配置](#2. Git安装与环境配置)
  • [3. Git基础操作详解](#3. Git基础操作详解)
    • [3.6 版本回滚与 HEAD 指针](#3.6 版本回滚与 HEAD 指针)
    • [3.7 .gitignore 忽略规则](#3.7 .gitignore 忽略规则)
    • [3.8 基础模块归纳](#3.8 基础模块归纳)
    • [3.9 Git Stash 工作现场暂存](#3.9 Git Stash 工作现场暂存)
  • [4. Git分支管理策略](#4. Git分支管理策略)
    • [4.4 GitFlow 完整工作流](#4.4 GitFlow 完整工作流)
    • [4.5 Cherry-pick 精选提交](#4.5 Cherry-pick 精选提交)
    • [4.6 合并冲突实战解决](#4.6 合并冲突实战解决)
  • [5. Git远程协作](#5. Git远程协作)
  • [6. Git高级技巧](#6. Git高级技巧)
    • [6.5 Git 标签管理](#6.5 Git 标签管理)
    • [6.6 Git Worktree 多工作区](#6.6 Git Worktree 多工作区)
  • [7. Git工作流最佳实践](#7. Git工作流最佳实践)
  • [8. 故障排查与解决方案](#8. 故障排查与解决方案)
  • [9. 团队协作实战案例](#9. 团队协作实战案例)
  • [10. 总结与进阶学习](#10. 总结与进阶学习)
  • [附录 A:命令与场景速查](#附录 A:命令与场景速查)
  • [附录 B:官方与延伸阅读](#附录 B:官方与延伸阅读)

0. 知识脉络与名词百科

0.1 本章知识图谱

#mermaid-svg-h9SwVz8N7BGUGAfw{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-h9SwVz8N7BGUGAfw .error-icon{fill:#552222;}#mermaid-svg-h9SwVz8N7BGUGAfw .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-h9SwVz8N7BGUGAfw .marker{fill:#333333;stroke:#333333;}#mermaid-svg-h9SwVz8N7BGUGAfw .marker.cross{stroke:#333333;}#mermaid-svg-h9SwVz8N7BGUGAfw svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-h9SwVz8N7BGUGAfw p{margin:0;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge{stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .section--1 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section--1 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section--1 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section--1 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section--1 path{fill:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section--1 text{fill:#ffffff;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon--1{font-size:40px;color:#ffffff;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge--1{stroke:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth--1{stroke-width:17;}#mermaid-svg-h9SwVz8N7BGUGAfw .section--1 line{stroke:hsl(60, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-0 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-0 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-0 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-0 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-0 path{fill:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-0 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-0{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-0{stroke:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-0{stroke-width:14;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-0 line{stroke:hsl(240, 100%, 83.5294117647%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-1 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-1 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-1 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-1 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-1 path{fill:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-1 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-1{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-1{stroke:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-1{stroke-width:11;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-1 line{stroke:hsl(260, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-2 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-2 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-2 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-2 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-2 path{fill:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-2 text{fill:#ffffff;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-2{font-size:40px;color:#ffffff;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-2{stroke:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-2{stroke-width:8;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-2 line{stroke:hsl(90, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-3 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-3 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-3 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-3 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-3 path{fill:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-3 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-3{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-3{stroke:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-3{stroke-width:5;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-3 line{stroke:hsl(120, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-4 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-4 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-4 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-4 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-4 path{fill:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-4 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-4{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-4{stroke:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-4{stroke-width:2;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-4 line{stroke:hsl(150, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-5 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-5 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-5 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-5 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-5 path{fill:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-5 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-5{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-5{stroke:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-5{stroke-width:-1;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-5 line{stroke:hsl(180, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-6 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-6 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-6 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-6 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-6 path{fill:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-6 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-6{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-6{stroke:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-6{stroke-width:-4;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-6 line{stroke:hsl(210, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-7 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-7 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-7 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-7 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-7 path{fill:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-7 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-7{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-7{stroke:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-7{stroke-width:-7;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-7 line{stroke:hsl(270, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-8 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-8 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-8 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-8 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-8 path{fill:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-8 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-8{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-8{stroke:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-8{stroke-width:-10;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-8 line{stroke:hsl(330, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-9 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-9 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-9 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-9 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-9 path{fill:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-9 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-9{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-9{stroke:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-9{stroke-width:-13;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-9 line{stroke:hsl(0, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-10 rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-10 path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-10 circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-10 polygon,#mermaid-svg-h9SwVz8N7BGUGAfw .section-10 path{fill:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-10 text{fill:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .node-icon-10{font-size:40px;color:black;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-edge-10{stroke:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .edge-depth-10{stroke-width:-16;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-10 line{stroke:hsl(30, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled circle,#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:lightgray;}#mermaid-svg-h9SwVz8N7BGUGAfw .disabled text{fill:#efefef;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-root rect,#mermaid-svg-h9SwVz8N7BGUGAfw .section-root path,#mermaid-svg-h9SwVz8N7BGUGAfw .section-root circle,#mermaid-svg-h9SwVz8N7BGUGAfw .section-root polygon{fill:hsl(240, 100%, 46.2745098039%);}#mermaid-svg-h9SwVz8N7BGUGAfw .section-root text{fill:#ffffff;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-root span{color:#ffffff;}#mermaid-svg-h9SwVz8N7BGUGAfw .section-2 span{color:#ffffff;}#mermaid-svg-h9SwVz8N7BGUGAfw .icon-container{height:100%;display:flex;justify-content:center;align-items:center;}#mermaid-svg-h9SwVz8N7BGUGAfw .edge{fill:none;}#mermaid-svg-h9SwVz8N7BGUGAfw .mindmap-node-label{dy:1em;alignment-baseline:middle;text-anchor:middle;dominant-baseline:middle;text-align:center;}#mermaid-svg-h9SwVz8N7BGUGAfw :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} Git Day04
概念
分布式 VCS
工作区 暂存区 版本库
Commit Branch HEAD
基础命令
init add commit status
diff restore reset
log reflog
协作
remote push pull clone
merge rebase 冲突
工程化
gitignore 钩子
SSH 免密
GitFlow PR

【代码注释】思维导图串联「概念 → 命令 → 协作 → 工程化」四条主线,建议按此顺序在练习仓库中逐项实践。

0.2 核心名词解析

名词 英文 解析
Commit 提交 将暂存区快照写入对象库,生成唯一 SHA-1 哈希
HEAD HEAD 当前检出分支/提交的指针
Index 暂存区 git add 后的中间层,对应 .git/index
Reflog 引用日志 记录 HEAD 移动,误操作恢复的「黑匣子」
Origin 默认远程名 git clone 自动创建的远程别名
Upstream 上游分支 git push -u 建立的本地与远程跟踪关系
Fast-forward 快进合并 无分叉时目标分支直接移动到源分支顶端

业界典型落地:

  • GitHub / GitLab / Gitee:PR/MR 代码审查、CI 与分支保护
  • React / Vue 工程main + feature/* 功能分支,发布走 tag
  • Monorepo :子目录 .gitignore 与多团队协作规范

1. Git概述与核心概念

1.1 什么是Git?

Git 是目前世界上最先进的分布式版本控制系统 。它由Linux之父林纳斯·托瓦兹(Linus Torvalds)于2005年创建,最初用于管理Linux内核开发。

名词解析:

  • 版本控制系统:记录文件内容变化,方便将来查阅特定版本修订情况的系统
  • 分布式:每个开发者都拥有完整的版本库,无需依赖中央服务器
  • 仓库(Repository):存储项目文件和版本历史的地方
  • 提交(Commit):对项目状态的快照记录
  • 分支(Branch):独立的开发线,允许并行开发

Git的核心优势:
#mermaid-svg-wkeCGV8JZuB8snfF{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-wkeCGV8JZuB8snfF .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-wkeCGV8JZuB8snfF .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-wkeCGV8JZuB8snfF .error-icon{fill:#552222;}#mermaid-svg-wkeCGV8JZuB8snfF .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-wkeCGV8JZuB8snfF .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-wkeCGV8JZuB8snfF .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-wkeCGV8JZuB8snfF .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-wkeCGV8JZuB8snfF .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-wkeCGV8JZuB8snfF .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-wkeCGV8JZuB8snfF .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-wkeCGV8JZuB8snfF .marker{fill:#333333;stroke:#333333;}#mermaid-svg-wkeCGV8JZuB8snfF .marker.cross{stroke:#333333;}#mermaid-svg-wkeCGV8JZuB8snfF svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-wkeCGV8JZuB8snfF p{margin:0;}#mermaid-svg-wkeCGV8JZuB8snfF .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-wkeCGV8JZuB8snfF .cluster-label text{fill:#333;}#mermaid-svg-wkeCGV8JZuB8snfF .cluster-label span{color:#333;}#mermaid-svg-wkeCGV8JZuB8snfF .cluster-label span p{background-color:transparent;}#mermaid-svg-wkeCGV8JZuB8snfF .label text,#mermaid-svg-wkeCGV8JZuB8snfF span{fill:#333;color:#333;}#mermaid-svg-wkeCGV8JZuB8snfF .node rect,#mermaid-svg-wkeCGV8JZuB8snfF .node circle,#mermaid-svg-wkeCGV8JZuB8snfF .node ellipse,#mermaid-svg-wkeCGV8JZuB8snfF .node polygon,#mermaid-svg-wkeCGV8JZuB8snfF .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-wkeCGV8JZuB8snfF .rough-node .label text,#mermaid-svg-wkeCGV8JZuB8snfF .node .label text,#mermaid-svg-wkeCGV8JZuB8snfF .image-shape .label,#mermaid-svg-wkeCGV8JZuB8snfF .icon-shape .label{text-anchor:middle;}#mermaid-svg-wkeCGV8JZuB8snfF .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-wkeCGV8JZuB8snfF .rough-node .label,#mermaid-svg-wkeCGV8JZuB8snfF .node .label,#mermaid-svg-wkeCGV8JZuB8snfF .image-shape .label,#mermaid-svg-wkeCGV8JZuB8snfF .icon-shape .label{text-align:center;}#mermaid-svg-wkeCGV8JZuB8snfF .node.clickable{cursor:pointer;}#mermaid-svg-wkeCGV8JZuB8snfF .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-wkeCGV8JZuB8snfF .arrowheadPath{fill:#333333;}#mermaid-svg-wkeCGV8JZuB8snfF .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-wkeCGV8JZuB8snfF .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-wkeCGV8JZuB8snfF .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-wkeCGV8JZuB8snfF .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-wkeCGV8JZuB8snfF .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-wkeCGV8JZuB8snfF .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-wkeCGV8JZuB8snfF .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-wkeCGV8JZuB8snfF .cluster text{fill:#333;}#mermaid-svg-wkeCGV8JZuB8snfF .cluster span{color:#333;}#mermaid-svg-wkeCGV8JZuB8snfF div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-wkeCGV8JZuB8snfF .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-wkeCGV8JZuB8snfF rect.text{fill:none;stroke-width:0;}#mermaid-svg-wkeCGV8JZuB8snfF .icon-shape,#mermaid-svg-wkeCGV8JZuB8snfF .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-wkeCGV8JZuB8snfF .icon-shape p,#mermaid-svg-wkeCGV8JZuB8snfF .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-wkeCGV8JZuB8snfF .icon-shape .label rect,#mermaid-svg-wkeCGV8JZuB8snfF .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-wkeCGV8JZuB8snfF .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-wkeCGV8JZuB8snfF .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-wkeCGV8JZuB8snfF :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} Git优势
分布式架构
强大的分支管理
快速性能
数据完整性保证
离线工作
无单点故障
并行开发
功能隔离
本地操作快速
高效存储
SHA-1校验
防止数据损坏

【代码注释】关系图展示概念对比、流程或决策路径。

1.2 Git的三大区域

理解Git工作区域的核心概念:
#mermaid-svg-TJ81ObNRhgQFYnrU{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-TJ81ObNRhgQFYnrU .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-TJ81ObNRhgQFYnrU .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-TJ81ObNRhgQFYnrU .error-icon{fill:#552222;}#mermaid-svg-TJ81ObNRhgQFYnrU .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-TJ81ObNRhgQFYnrU .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-TJ81ObNRhgQFYnrU .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-TJ81ObNRhgQFYnrU .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-TJ81ObNRhgQFYnrU .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-TJ81ObNRhgQFYnrU .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-TJ81ObNRhgQFYnrU .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-TJ81ObNRhgQFYnrU .marker{fill:#333333;stroke:#333333;}#mermaid-svg-TJ81ObNRhgQFYnrU .marker.cross{stroke:#333333;}#mermaid-svg-TJ81ObNRhgQFYnrU svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-TJ81ObNRhgQFYnrU p{margin:0;}#mermaid-svg-TJ81ObNRhgQFYnrU .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-TJ81ObNRhgQFYnrU .cluster-label text{fill:#333;}#mermaid-svg-TJ81ObNRhgQFYnrU .cluster-label span{color:#333;}#mermaid-svg-TJ81ObNRhgQFYnrU .cluster-label span p{background-color:transparent;}#mermaid-svg-TJ81ObNRhgQFYnrU .label text,#mermaid-svg-TJ81ObNRhgQFYnrU span{fill:#333;color:#333;}#mermaid-svg-TJ81ObNRhgQFYnrU .node rect,#mermaid-svg-TJ81ObNRhgQFYnrU .node circle,#mermaid-svg-TJ81ObNRhgQFYnrU .node ellipse,#mermaid-svg-TJ81ObNRhgQFYnrU .node polygon,#mermaid-svg-TJ81ObNRhgQFYnrU .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-TJ81ObNRhgQFYnrU .rough-node .label text,#mermaid-svg-TJ81ObNRhgQFYnrU .node .label text,#mermaid-svg-TJ81ObNRhgQFYnrU .image-shape .label,#mermaid-svg-TJ81ObNRhgQFYnrU .icon-shape .label{text-anchor:middle;}#mermaid-svg-TJ81ObNRhgQFYnrU .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-TJ81ObNRhgQFYnrU .rough-node .label,#mermaid-svg-TJ81ObNRhgQFYnrU .node .label,#mermaid-svg-TJ81ObNRhgQFYnrU .image-shape .label,#mermaid-svg-TJ81ObNRhgQFYnrU .icon-shape .label{text-align:center;}#mermaid-svg-TJ81ObNRhgQFYnrU .node.clickable{cursor:pointer;}#mermaid-svg-TJ81ObNRhgQFYnrU .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-TJ81ObNRhgQFYnrU .arrowheadPath{fill:#333333;}#mermaid-svg-TJ81ObNRhgQFYnrU .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-TJ81ObNRhgQFYnrU .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-TJ81ObNRhgQFYnrU .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-TJ81ObNRhgQFYnrU .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-TJ81ObNRhgQFYnrU .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-TJ81ObNRhgQFYnrU .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-TJ81ObNRhgQFYnrU .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-TJ81ObNRhgQFYnrU .cluster text{fill:#333;}#mermaid-svg-TJ81ObNRhgQFYnrU .cluster span{color:#333;}#mermaid-svg-TJ81ObNRhgQFYnrU div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-TJ81ObNRhgQFYnrU .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-TJ81ObNRhgQFYnrU rect.text{fill:none;stroke-width:0;}#mermaid-svg-TJ81ObNRhgQFYnrU .icon-shape,#mermaid-svg-TJ81ObNRhgQFYnrU .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-TJ81ObNRhgQFYnrU .icon-shape p,#mermaid-svg-TJ81ObNRhgQFYnrU .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-TJ81ObNRhgQFYnrU .icon-shape .label rect,#mermaid-svg-TJ81ObNRhgQFYnrU .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-TJ81ObNRhgQFYnrU .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-TJ81ObNRhgQFYnrU .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-TJ81ObNRhgQFYnrU :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 工作区 Workspace
暂存区 Staging Area
版本库 Repository
编辑文件

git add
准备提交

git commit
保存历史

git push
git checkout

恢复文件
git reset

取消暂存
git revert

撤销提交

【代码注释】关系图展示概念对比、流程或决策路径。

三个区域的详细说明:

区域 说明 对应命令 数据状态
工作区 代码编辑的实际目录 git checkout 文件可能被修改
暂存区 准备提交的文件集合 git add 等待提交的变更
版本库 Git存储历史记录的地方 git commit 已保存的快照

名词解析 · 三区模型 :工作区是磁盘上可见的项目目录;暂存区(Index)是下次提交的「购物车」;版本库(.git/objects)保存所有历史快照。git add 只影响暂存区,git commit 才写入版本库。

实际应用示例:

bash 复制代码
# 【代码注释】创建测试项目
mkdir my-git-project
cd my-git-project
git init

# 【代码注释】工作区操作
echo "# 我的项目" > README.md
# 此时文件在工作区,Git还未跟踪

# 【代码注释】暂存区操作
git add README.md
# 文件已添加到暂存区,等待提交

# 【代码注释】版本库操作
git commit -m "初始提交:添加README文件"
# 文件已提交到版本库,成为历史记录

【代码注释】创建测试项目;工作区操作;暂存区操作;版本库操作

1.3 Git的文件状态

文件在Git中的四种状态:
#mermaid-svg-fB1Zntlj4CxrE3Tr{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-fB1Zntlj4CxrE3Tr .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-fB1Zntlj4CxrE3Tr .error-icon{fill:#552222;}#mermaid-svg-fB1Zntlj4CxrE3Tr .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-fB1Zntlj4CxrE3Tr .marker{fill:#333333;stroke:#333333;}#mermaid-svg-fB1Zntlj4CxrE3Tr .marker.cross{stroke:#333333;}#mermaid-svg-fB1Zntlj4CxrE3Tr svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-fB1Zntlj4CxrE3Tr p{margin:0;}#mermaid-svg-fB1Zntlj4CxrE3Tr defs #statediagram-barbEnd{fill:#333333;stroke:#333333;}#mermaid-svg-fB1Zntlj4CxrE3Tr g.stateGroup text{fill:#9370DB;stroke:none;font-size:10px;}#mermaid-svg-fB1Zntlj4CxrE3Tr g.stateGroup text{fill:#333;stroke:none;font-size:10px;}#mermaid-svg-fB1Zntlj4CxrE3Tr g.stateGroup .state-title{font-weight:bolder;fill:#131300;}#mermaid-svg-fB1Zntlj4CxrE3Tr g.stateGroup rect{fill:#ECECFF;stroke:#9370DB;}#mermaid-svg-fB1Zntlj4CxrE3Tr g.stateGroup line{stroke:#333333;stroke-width:1;}#mermaid-svg-fB1Zntlj4CxrE3Tr .transition{stroke:#333333;stroke-width:1;fill:none;}#mermaid-svg-fB1Zntlj4CxrE3Tr .stateGroup .composit{fill:white;border-bottom:1px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .state-note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-fB1Zntlj4CxrE3Tr .state-note text{fill:black;stroke:none;font-size:10px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edgeLabel .label rect{fill:#ECECFF;opacity:0.5;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-fB1Zntlj4CxrE3Tr .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-fB1Zntlj4CxrE3Tr .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-fB1Zntlj4CxrE3Tr .edgeLabel .label text{fill:#333;}#mermaid-svg-fB1Zntlj4CxrE3Tr .label div .edgeLabel{color:#333;}#mermaid-svg-fB1Zntlj4CxrE3Tr .stateLabel text{fill:#131300;font-size:10px;font-weight:bold;}#mermaid-svg-fB1Zntlj4CxrE3Tr .node circle.state-start{fill:#333333;stroke:#333333;}#mermaid-svg-fB1Zntlj4CxrE3Tr .node .fork-join{fill:#333333;stroke:#333333;}#mermaid-svg-fB1Zntlj4CxrE3Tr .node circle.state-end{fill:#9370DB;stroke:white;stroke-width:1.5;}#mermaid-svg-fB1Zntlj4CxrE3Tr .end-state-inner{fill:white;stroke-width:1.5;}#mermaid-svg-fB1Zntlj4CxrE3Tr .node rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .node polygon{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-fB1Zntlj4CxrE3Tr #statediagram-barbEnd{fill:#333333;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-cluster rect{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .cluster-label,#mermaid-svg-fB1Zntlj4CxrE3Tr .nodeLabel{color:#131300;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-cluster rect.outer{rx:5px;ry:5px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-state .divider{stroke:#9370DB;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-state .title-state{rx:5px;ry:5px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-cluster.statediagram-cluster .inner{fill:white;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-cluster.statediagram-cluster-alt .inner{fill:#f0f0f0;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-cluster .inner{rx:0;ry:0;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-state rect.basic{rx:5px;ry:5px;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#f0f0f0;}#mermaid-svg-fB1Zntlj4CxrE3Tr .note-edge{stroke-dasharray:5;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-note rect{fill:#fff5ad;stroke:#aaaa33;stroke-width:1px;rx:0;ry:0;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-note text{fill:black;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram-note .nodeLabel{color:black;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagram .edgeLabel{color:red;}#mermaid-svg-fB1Zntlj4CxrE3Tr #dependencyStart,#mermaid-svg-fB1Zntlj4CxrE3Tr #dependencyEnd{fill:#333333;stroke:#333333;stroke-width:1;}#mermaid-svg-fB1Zntlj4CxrE3Tr .statediagramTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-fB1Zntlj4CxrE3Tr :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 新文件
git add
再次修改
git add
git commit
修改文件
修改已跟踪文件
未跟踪
已暂存
已修改
已提交

【代码注释】状态图描述对象/文件在不同阶段之间的转换。

状态转换详解:

javascript 复制代码
// 【代码注释】Git文件状态模拟
class GitFileStatus {
    constructor(filename) {
        this.filename = filename;
        this.status = 'untracked'; // 初始状态
        this.changes = [];
    }
    
    // 【代码注释】模拟git add命令
    stage() {
        if (this.status === 'untracked' || this.status === 'modified') {
            this.status = 'staged';
            console.log(`${this.filename} 已添加到暂存区`);
        }
    }
    
    // 【代码注释】模拟git commit命令
    commit() {
        if (this.status === 'staged') {
            this.status = 'committed';
            console.log(`${this.filename} 已提交到版本库`);
        }
    }
    
    // 【代码注释】模拟文件修改
    modify() {
        if (this.status === 'unmodified' || this.status === 'committed') {
            this.status = 'modified';
            console.log(`${this.filename} 已被修改`);
        }
    }
    
    // 【代码注释】获取当前状态
    getStatus() {
        const statusMap = {
            'untracked': '未跟踪',
            'staged': '已暂存',
            'modified': '已修改',
            'committed': '已提交'
        };
        return statusMap[this.status] || this.status;
    }
}

// 【代码注释】使用示例
const readmeFile = new GitFileStatus('README.md');
console.log(`初始状态: ${readmeFile.getStatus()}`);

readmeFile.stage();
console.log(`执行git add后: ${readmeFile.getStatus()}`);

readmeFile.commit();
console.log(`执行git commit后: ${readmeFile.getStatus()}`);

readmeFile.modify();
console.log(`修改文件后: ${readmeFile.getStatus()}`);

【代码注释】Git文件状态模拟;模拟git add命令;模拟git commit命令;模拟文件修改;获取当前状态;使用示例

1.4 .git 目录结构

执行 git init 后,项目根目录会出现 .git 隐藏文件夹,切勿手动修改其中内容

路径 作用
hooks/ 客户端/服务端钩子脚本(pre-commit、commit-msg 等)
info/ 全局排除规则等
logs/ 引用变更日志
objects/ 所有对象数据(blob/tree/commit)的存储位置
refs/ 分支、标签等指针
config 本仓库配置
HEAD 当前检出的分支引用
index 暂存区二进制索引

经典应用场景 :排查「提交后文件仍显示修改」时,检查 core.fileModecore.autocrlfconfig 项。

1.5 开发环境准备(Linux 与 Vim)

终端是 Git 的主要操作界面,掌握基础 Shell 与 Vim 可显著提升效率。

常用 Linux 命令:

bash 复制代码
ls          # 列举文件;-a 含隐藏,-l 详细信息
ls -al
cd 目录路径   # 进入目录;cd .. 返回上级
rm -rf 目录名 # 递归删除(谨慎使用)
clear       # 清屏

【代码注释】tab 可自动补全路径;Ctrl+C 终止当前命令;上下方向键调取历史命令。

Vim 三种模式:

bash 复制代码
vim 文件名    # 打开或创建文件

【代码注释】命令模式下按 i 进入输入模式;输入模式下 Esc 回到命令模式;命令模式下 : 进入底线命令。

模式 说明 常用命令
命令模式 打开文件后的默认模式 i 进入输入模式
输入模式 编辑文本 Esc 返回命令模式
底线命令模式 保存、退出 :w 保存,:q 退出,:wq 保存并退出

1.6 Git对象模型与内部原理

深入理解 Git 的底层模型,能让你在遇到疑难问题时胸有成竹,而不只是背命令。

四种对象类型:

对象类型 存储内容 类比
blob 文件的二进制内容快照 档案馆里的一份文件原件
tree 目录快照(指向 blob/tree) 档案馆的目录索引页
commit 指向 tree + 父 commit + 元信息 一次存档操作的完整记录
tag 带注释的命名指针 档案馆的版本封面标签

对象之间的关系(DAG 有向无环图):
#mermaid-svg-ZTn8HjcwtZwQawzr{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-ZTn8HjcwtZwQawzr .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-ZTn8HjcwtZwQawzr .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-ZTn8HjcwtZwQawzr .error-icon{fill:#552222;}#mermaid-svg-ZTn8HjcwtZwQawzr .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-ZTn8HjcwtZwQawzr .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-ZTn8HjcwtZwQawzr .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-ZTn8HjcwtZwQawzr .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-ZTn8HjcwtZwQawzr .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-ZTn8HjcwtZwQawzr .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-ZTn8HjcwtZwQawzr .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-ZTn8HjcwtZwQawzr .marker{fill:#333333;stroke:#333333;}#mermaid-svg-ZTn8HjcwtZwQawzr .marker.cross{stroke:#333333;}#mermaid-svg-ZTn8HjcwtZwQawzr svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-ZTn8HjcwtZwQawzr p{margin:0;}#mermaid-svg-ZTn8HjcwtZwQawzr .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-ZTn8HjcwtZwQawzr .cluster-label text{fill:#333;}#mermaid-svg-ZTn8HjcwtZwQawzr .cluster-label span{color:#333;}#mermaid-svg-ZTn8HjcwtZwQawzr .cluster-label span p{background-color:transparent;}#mermaid-svg-ZTn8HjcwtZwQawzr .label text,#mermaid-svg-ZTn8HjcwtZwQawzr span{fill:#333;color:#333;}#mermaid-svg-ZTn8HjcwtZwQawzr .node rect,#mermaid-svg-ZTn8HjcwtZwQawzr .node circle,#mermaid-svg-ZTn8HjcwtZwQawzr .node ellipse,#mermaid-svg-ZTn8HjcwtZwQawzr .node polygon,#mermaid-svg-ZTn8HjcwtZwQawzr .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-ZTn8HjcwtZwQawzr .rough-node .label text,#mermaid-svg-ZTn8HjcwtZwQawzr .node .label text,#mermaid-svg-ZTn8HjcwtZwQawzr .image-shape .label,#mermaid-svg-ZTn8HjcwtZwQawzr .icon-shape .label{text-anchor:middle;}#mermaid-svg-ZTn8HjcwtZwQawzr .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-ZTn8HjcwtZwQawzr .rough-node .label,#mermaid-svg-ZTn8HjcwtZwQawzr .node .label,#mermaid-svg-ZTn8HjcwtZwQawzr .image-shape .label,#mermaid-svg-ZTn8HjcwtZwQawzr .icon-shape .label{text-align:center;}#mermaid-svg-ZTn8HjcwtZwQawzr .node.clickable{cursor:pointer;}#mermaid-svg-ZTn8HjcwtZwQawzr .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-ZTn8HjcwtZwQawzr .arrowheadPath{fill:#333333;}#mermaid-svg-ZTn8HjcwtZwQawzr .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-ZTn8HjcwtZwQawzr .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-ZTn8HjcwtZwQawzr .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-ZTn8HjcwtZwQawzr .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-ZTn8HjcwtZwQawzr .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-ZTn8HjcwtZwQawzr .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-ZTn8HjcwtZwQawzr .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-ZTn8HjcwtZwQawzr .cluster text{fill:#333;}#mermaid-svg-ZTn8HjcwtZwQawzr .cluster span{color:#333;}#mermaid-svg-ZTn8HjcwtZwQawzr div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-ZTn8HjcwtZwQawzr .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-ZTn8HjcwtZwQawzr rect.text{fill:none;stroke-width:0;}#mermaid-svg-ZTn8HjcwtZwQawzr .icon-shape,#mermaid-svg-ZTn8HjcwtZwQawzr .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-ZTn8HjcwtZwQawzr .icon-shape p,#mermaid-svg-ZTn8HjcwtZwQawzr .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-ZTn8HjcwtZwQawzr .icon-shape .label rect,#mermaid-svg-ZTn8HjcwtZwQawzr .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-ZTn8HjcwtZwQawzr .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-ZTn8HjcwtZwQawzr .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-ZTn8HjcwtZwQawzr :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} commit B

tree:t2 parent:A
commit A

tree:t1 parent:-
tree t2
tree t1
blob: README v1
blob: app.js v1
blob: app.js v2 ← 只有这个 blob 是新建的
blob: index.html

【代码注释】Git 的存储极为高效:两次提交之间,只有真正变化的文件会生成新 blob,未改动的文件直接复用旧 blob,这也是 Git 比其他 VCS 更节省磁盘的原因。

用命令亲眼看对象:

bash 复制代码
# 查看 HEAD 指向的 commit 对象内容
git cat-file -t HEAD          # 输出: commit(显示对象类型)
git cat-file -p HEAD          # 输出: tree sha、parent sha、author、message

# 查看当前目录的 tree 快照
git cat-file -p HEAD^{tree}   # 列出目录下所有 blob/子 tree 及其哈希

# 查看某个文件的原始内容(blob)
git ls-tree HEAD              # 列出 HEAD 下所有对象哈希
git cat-file -p <blob-sha>    # 输出该文件的原始文本内容

# 统计仓库对象数量与磁盘占用
git count-objects -vH

SHA-1 哈希的安全意义:

每个对象的 SHA-1 由内容计算得来。如果有人篡改了历史提交中哪怕一个字节,该 commit 的哈希就会改变,其后所有 commit 的哈希也会连锁变化------这从数学上保证了 Git 历史的不可篡改性

bash 复制代码
# 演示:观察一次提交的哈希构成
echo "hello git" | git hash-object --stdin   # 计算任意内容的 SHA-1
# 输出: 8d0e41234f24b6da002d962a26c2495ea16a425f(示例哈希)

为什么 Git 的本地操作如此快速?

  • 所有历史数据都在 .git/objects/ 本地磁盘中,无需网络请求
  • git loggit diffgit blame 全部本地完成,响应毫秒级
  • 哈希索引使任意对象的查找接近 O(1)

2. Git安装与环境配置

2.1 Git安装指南

不同操作系统安装Git:

bash 复制代码
# 【代码注释】Windows系统安装
# 1. 访问Git官网下载安装程序
# https://git-scm.com/download/win
# 2. 运行安装程序,使用默认设置即可
# 3. 验证安装
git --version

# 【代码注释】macOS系统安装
# 使用Homebrew安装(推荐)
brew install git

# 或从官方安装包安装
# https://git-scm.com/download/mac

# 【代码注释】Linux系统安装
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install git

# CentOS/RHEL
sudo yum install git

# Fedora
sudo dnf install git

【代码注释】Windows系统安装;macOS系统安装;Linux系统安装

2.2 初始配置设置

Git配置的三个级别:

bash 复制代码
# 【代码注释】系统级配置(所有用户)
git config --system user.name "Your Name"
git config --system user.email "email@example.com"

# 【代码注释】全局配置(当前用户所有仓库)
git config --global user.name "Your Name"
git config --global user.email "email@example.com"

# 【代码注释】仓库级配置(仅当前仓库)
git config --local user.name "Repository Specific Name"
git config --local user.email "repository@example.com"

# 【代码注释】查看配置
git config --list              # 查看所有配置
git config user.name           # 查看特定配置
git config --global --list     # 查看全局配置

【代码注释】系统级配置(所有用户);全局配置(当前用户所有仓库);仓库级配置(仅当前仓库);查看配置

推荐的最佳配置:

bash 复制代码
# 【代码注释】基础身份信息
git config --global user.name "张三"
git config --global user.email "zhangsan@example.com"

# 【代码注释】设置默认分支名(Git 2.28+)
git config --global init.defaultBranch main

# 【代码注释】配置默认编辑器
git config --global core.editor "code --wait"  # VS Code
git config --global core.editor "vim"           # Vim

# 【代码注释】配置差异比较工具
git config --global diff.tool "vscode"
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"

# 【代码注释】配置别名(提高效率)
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.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual 'log --graph --oneline --all'

# 【代码注释】配置HTTPS缓存(避免频繁输入密码)
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'  # 缓存1小时

# 【代码注释】配置换行符处理
git config --global core.autocrlf input    # macOS/Linux
git config --global core.autocrlf true     # Windows

# 【代码注释】配置文件权限
git config --global core.fileMode false    # 忽略文件权限变化

【代码注释】基础身份信息;设置默认分支名(Git 2.28+);配置默认编辑器;配置差异比较工具;配置别名(提高效率);配置HTTPS缓存(避免频繁输入密码);配置换行符处理;配置文件权限

2.3 SSH密钥配置

生成SSH密钥用于GitHub/GitLab认证:

bash 复制代码
# 【代码注释】生成SSH密钥对
ssh-keygen -t ed25519 -C "your_email@example.com"

# 【代码注释】或使用RSA算法(兼容性更好)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# 【代码注释】启动SSH代理并添加密钥
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

# 【代码注释】复制公钥到剪贴板(macOS)
pbcopy < ~/.ssh/id_ed25519.pub

# 【代码注释】复制公钥到剪贴板(Linux)
cat ~/.ssh/id_ed25519.pub | clip

# 【代码注释】复制公钥(Windows PowerShell)
type $env:USERPROFILE\.ssh\id_ed25519.pub | clip

# 【代码注释】测试SSH连接
ssh -T git@github.com
ssh -T git@gitlab.com

【代码注释】生成SSH密钥对;或使用RSA算法(兼容性更好);启动SSH代理并添加密钥;复制公钥到剪贴板(macOS);复制公钥到剪贴板(Linux);复制公钥(Windows PowerShell);测试SSH连接

配置SSH配置文件:

bash 复制代码
# 【代码注释】编辑SSH配置文件
cat > ~/.ssh/config << EOF
# GitHub配置
Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519
    
# GitLab配置
Host gitlab.com
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/id_ed25519
    
# 自定义Git服务器
Host company-git
    HostName git.company.com
    User git
    IdentityFile ~/.ssh/company_key
    Port 2222
EOF

【代码注释】编辑SSH配置文件


3. Git基础操作详解

3.1 仓库初始化与克隆

创建新仓库的不同方式:

bash 复制代码
# 【代码注释】方法一:初始化本地仓库
mkdir new-project
cd new-project
git init
# 当前目录会创建.git子目录,包含Git的所有数据

# 【代码注释】方法二:克隆远程仓库
git clone https://github.com/username/repo.git
git clone git@github.com:username/repo.git
git clone -b develop https://github.com/username/repo.git  # 克隆特定分支

# 【代码注释】方法三:初始化并设置远程仓库
git init
git remote add origin https://github.com/username/repo.git
git remote -v  # 查看远程仓库配置

【代码注释】方法一:初始化本地仓库;方法二:克隆远程仓库;方法三:初始化并设置远程仓库

3.2 文件操作核心命令

文件添加与提交:

bash 复制代码
# 【代码注释】添加文件到暂存区
git add filename                    # 添加指定文件
git add .                           # 添加当前目录所有修改
git add -A                          # 添加所有变化(包括删除)
git add -u                          # 添加所有修改和删除(不包括新文件)
git add *.txt                       # 添加所有txt文件
git add docs/                       # 添加docs目录
git add docs/*.md                   # 添加docs目录下所有md文件

# 【代码注释】提交更改
git commit -m "提交信息"
git commit -am "提交信息"           # 添加并提交(已跟踪文件)
git commit --amend                 # 修改最后一次提交
git commit --amend -m "新的提交信息"  # 修改提交信息
git commit --allow-empty           # 创建空提交

# 【代码注释】查看状态
git status                         # 简要状态
git status -s                      # 短格式状态
git status --ignored               # 包含被忽略的文件

【代码注释】添加文件到暂存区;提交更改;查看状态

实际工作流程示例:

bash 复制代码
# 【代码注释】完整的开发工作流
# 1. 创建项目文件
echo "# 我的Git项目" > README.md
echo "console.log('Hello, Git!');" > app.js

# 2. 查看工作区状态
git status
# 输出: Untracked files: README.md, app.js

# 3. 添加文件到暂存区
git add README.md
git status
# 输出: Changes to be committed: README.md

# 4. 继续编辑其他文件
echo "const port = 3000;" >> app.js
git status
# 输出: README.md已暂存, app.js未跟踪

# 5. 一次性添加所有文件
git add .
git commit -m "初始提交:添加项目基础文件"

【代码注释】完整的开发工作流

3.3 查看历史与差异

提交历史查看:

bash 复制代码
# 【代码注释】基本历史查看
git log                            # 详细历史
git log --oneline                  # 简洁历史
git log --graph                    # 图形化历史
git log --all                      # 所有分支历史
git log --stat                     # 显示文件统计
git log --patch                    # 显示具体修改内容

# 【代码注释】过滤历史记录
git log -n 5                       # 最近5次提交
git log --since="2 weeks ago"      # 最近两周
git log --until="2024-01-01"       # 某日期之前
git log --author="张三"             # 特定作者
git log --grep="修复"              # 搜索提交信息
git log -- filename                # 特定文件的历史

# 【代码注释】格式化输出
git log --pretty=format:"%h - %an, %ar : %s"
# h: 简短哈希, an: 作者名, ar: 相对时间, s: 提交信息

# 【代码注释】图形化分支历史
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit

【代码注释】基本历史查看;过滤历史记录;格式化输出;图形化分支历史

文件差异比较:

bash 复制代码
# 【代码注释】工作区与暂存区比较
git diff                          # 所有文件的差异
git diff filename                 # 特定文件的差异
git diff --stat                   # 仅显示统计信息

# 【代码注释】暂存区与版本库比较
git diff --staged                 # 已暂存的变更
git diff --cached                 # 同上(别名)

# 【代码注释】工作区与版本库比较
git diff HEAD                     # 与最新提交比较
git diff HEAD~1                   # 与上一次提交比较

# 【代码注释】不同提交之间比较
git diff commit1 commit2          # 两次提交之间的差异
git diff main feature             # 两个分支之间的差异

# 【代码注释】比较特定文件
git diff branch1 branch2 -- filename

# 【代码注释】使用图形化工具
gitk                              # Git图形化历史查看器
git difftool                      # 使用配置的差异工具

【代码注释】工作区与暂存区比较;暂存区与版本库比较;工作区与版本库比较;不同提交之间比较;比较特定文件;使用图形化工具

3.4 撤销与恢复操作

撤销操作的完整指南:

bash 复制代码
# 【代码注释】工作区撤销(恢复文件)
git restore filename              # 恢复特定文件
git restore .                     # 恢复所有文件
git restore --source=HEAD~1 filename  # 从特定提交恢复

# 【代码注释】暂存区撤销(取消暂存)
git restore --staged filename     # 取消特定文件的暂存
git restore --staged .            # 取消所有文件的暂存
git reset HEAD filename           # 传统方法(同上)

# 【代码注释】版本库撤销(撤销提交)
git revert HEAD                   # 创建新提交撤销上一次提交
git revert HEAD~2                 # 撤销指定的提交

# 【代码注释】重置到历史版本(谨慎使用)
git reset --soft HEAD~1           # 保留工作区和暂存区
git reset --mixed HEAD~1          # 保留工作区,清空暂存区(默认)
git reset --hard HEAD~1           # 清空工作区和暂存区(危险)

# 【代码注释】删除未跟踪的文件
git clean -f                      # 删除未跟踪的文件
git clean -fd                     # 删除未跟踪的文件和目录
git clean -n                      # 预览将要删除的文件

【代码注释】工作区撤销(恢复文件);暂存区撤销(取消暂存);版本库撤销(撤销提交);重置到历史版本(谨慎使用);删除未跟踪的文件

实际撤销场景示例:

javascript 复制代码
// 【代码注释】Git撤销操作模拟器
class GitOperationSimulator {
    constructor() {
        this.workspace = {};
        this.staging = {};
        this.repository = [];
        this.head = null;
    }
    
    // 【代码注释】模拟文件修改
    modifyFile(filename, content) {
        this.workspace[filename] = content;
        console.log(`修改文件: ${filename}`);
    }
    
    // 【代码注释】模拟git add
    stageFile(filename) {
        if (this.workspace[filename]) {
            this.staging[filename] = this.workspace[filename];
            console.log(`暂存文件: ${filename}`);
        }
    }
    
    // 【代码注释】模拟git commit
    commit(message) {
        if (Object.keys(this.staging).length > 0) {
            const commit = {
                id: 'commit_' + Date.now(),
                message: message,
                files: {...this.staging},
                timestamp: new Date().toISOString()
            };
            this.repository.push(commit);
            this.head = commit.id;
            this.staging = {};
            console.log(`提交: ${message} (${commit.id})`);
        }
    }
    
    // 【代码注释】模拟git restore
    restoreFile(filename) {
        if (this.head) {
            const lastCommit = this.repository.find(c => c.id === this.head);
            if (lastCommit && lastCommit.files[filename]) {
                this.workspace[filename] = lastCommit.files[filename];
                console.log(`恢复文件: ${filename} 到上次提交状态`);
            }
        }
    }
    
    // 【代码注释】模拟git reset --soft
    resetSoft() {
        if (this.repository.length > 0) {
            const lastCommit = this.repository.pop();
            this.staging = {...lastCommit.files};
            this.head = this.repository.length > 0 ? 
                this.repository[this.repository.length - 1].id : null;
            console.log(`软重置: ${lastCommit.id} 已移到暂存区`);
        }
    }
    
    // 【代码注释】查看当前状态
    status() {
        return {
            workspace: Object.keys(this.workspace),
            staging: Object.keys(this.staging),
            repository: this.repository.map(c => c.id),
            head: this.head
        };
    }
}

// 【代码注释】使用示例
const gitSim = new GitOperationSimulator();

// 模拟工作流程
gitSim.modifyFile('app.js', 'console.log("v1");');
gitSim.stageFile('app.js');
gitSim.commit('初始版本');

gitSim.modifyFile('app.js', 'console.log("v2");');
gitSim.modifyFile('readme.md', '# 我的项目');
console.log('当前状态:', gitSim.status());

// 撤销工作区修改
gitSim.restoreFile('app.js');

【代码注释】Git撤销操作模拟器;模拟文件修改;模拟git add;模拟git commit;模拟git restore;模拟git reset --soft;查看当前状态;使用示例

3.5 文件删除与移动

Git中文件操作的最佳实践:

bash 复制代码
# 【代码注释】推荐使用git命令操作文件
git rm filename                    # 删除文件(暂存删除)
git rm -r directory                # 删除目录
git rm --cached filename           # 从版本库删除,但保留本地文件

# 【代码注释】移动/重命名文件
git mv old_filename new_filename   # 重命名文件
git mv file1.txt dir/              # 移动文件到目录

# 【代码注释】恢复被删除的文件
git restore filename               # 从暂存区恢复
git restore --source=HEAD~1 filename  # 从历史提交恢复

【代码注释】推荐使用git命令操作文件;移动/重命名文件;恢复被删除的文件

3.6 版本回滚与 HEAD 指针

名词解析:

  • HEAD:当前分支最新提交的指针
  • HEAD^ / HEAD~1 :上一个提交;HEAD~5 表示前 5 个提交
  • reflog:记录 HEAD 移动历史,误删分支/提交的恢复入口
bash 复制代码
git log --oneline              # 查看简洁历史
git log -3                     # 最近 3 次提交
git reflog                     # 查看所有 HEAD 移动(含被 reset 的提交)

git reset --hard a1b2c3d       # 按完整或前 7 位哈希回滚
git reset --hard HEAD^         # 回滚到上一版本
git reset --hard HEAD~5       # 回滚到前 5 个版本

git reset --soft HEAD~1       # 仅撤销提交,保留暂存区与工作区(改 commit message)
git reset --mixed HEAD~1      # 撤销提交并清空暂存区(默认)

【代码注释】--hard 会丢失未提交改动;找回「丢失」提交:git reflog 查哈希后 git reset --hard <hash>
#mermaid-svg-ztudIJPpZT8t4wDY{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-ztudIJPpZT8t4wDY .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-ztudIJPpZT8t4wDY .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-ztudIJPpZT8t4wDY .error-icon{fill:#552222;}#mermaid-svg-ztudIJPpZT8t4wDY .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-ztudIJPpZT8t4wDY .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-ztudIJPpZT8t4wDY .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-ztudIJPpZT8t4wDY .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-ztudIJPpZT8t4wDY .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-ztudIJPpZT8t4wDY .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-ztudIJPpZT8t4wDY .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-ztudIJPpZT8t4wDY .marker{fill:#333333;stroke:#333333;}#mermaid-svg-ztudIJPpZT8t4wDY .marker.cross{stroke:#333333;}#mermaid-svg-ztudIJPpZT8t4wDY svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-ztudIJPpZT8t4wDY p{margin:0;}#mermaid-svg-ztudIJPpZT8t4wDY .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-ztudIJPpZT8t4wDY .cluster-label text{fill:#333;}#mermaid-svg-ztudIJPpZT8t4wDY .cluster-label span{color:#333;}#mermaid-svg-ztudIJPpZT8t4wDY .cluster-label span p{background-color:transparent;}#mermaid-svg-ztudIJPpZT8t4wDY .label text,#mermaid-svg-ztudIJPpZT8t4wDY span{fill:#333;color:#333;}#mermaid-svg-ztudIJPpZT8t4wDY .node rect,#mermaid-svg-ztudIJPpZT8t4wDY .node circle,#mermaid-svg-ztudIJPpZT8t4wDY .node ellipse,#mermaid-svg-ztudIJPpZT8t4wDY .node polygon,#mermaid-svg-ztudIJPpZT8t4wDY .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-ztudIJPpZT8t4wDY .rough-node .label text,#mermaid-svg-ztudIJPpZT8t4wDY .node .label text,#mermaid-svg-ztudIJPpZT8t4wDY .image-shape .label,#mermaid-svg-ztudIJPpZT8t4wDY .icon-shape .label{text-anchor:middle;}#mermaid-svg-ztudIJPpZT8t4wDY .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-ztudIJPpZT8t4wDY .rough-node .label,#mermaid-svg-ztudIJPpZT8t4wDY .node .label,#mermaid-svg-ztudIJPpZT8t4wDY .image-shape .label,#mermaid-svg-ztudIJPpZT8t4wDY .icon-shape .label{text-align:center;}#mermaid-svg-ztudIJPpZT8t4wDY .node.clickable{cursor:pointer;}#mermaid-svg-ztudIJPpZT8t4wDY .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-ztudIJPpZT8t4wDY .arrowheadPath{fill:#333333;}#mermaid-svg-ztudIJPpZT8t4wDY .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-ztudIJPpZT8t4wDY .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-ztudIJPpZT8t4wDY .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-ztudIJPpZT8t4wDY .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-ztudIJPpZT8t4wDY .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-ztudIJPpZT8t4wDY .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-ztudIJPpZT8t4wDY .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-ztudIJPpZT8t4wDY .cluster text{fill:#333;}#mermaid-svg-ztudIJPpZT8t4wDY .cluster span{color:#333;}#mermaid-svg-ztudIJPpZT8t4wDY div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-ztudIJPpZT8t4wDY .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-ztudIJPpZT8t4wDY rect.text{fill:none;stroke-width:0;}#mermaid-svg-ztudIJPpZT8t4wDY .icon-shape,#mermaid-svg-ztudIJPpZT8t4wDY .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-ztudIJPpZT8t4wDY .icon-shape p,#mermaid-svg-ztudIJPpZT8t4wDY .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-ztudIJPpZT8t4wDY .icon-shape .label rect,#mermaid-svg-ztudIJPpZT8t4wDY .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-ztudIJPpZT8t4wDY .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-ztudIJPpZT8t4wDY .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-ztudIJPpZT8t4wDY :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 是

需要回滚?
保留工作区修改?
--soft 或 --mixed
--hard
改 message / 重新 add
彻底回到某版本
reflog 可恢复误操作

【代码注释】流程图帮助在 soft/mixed/hard 之间做选型;生产环境慎用 --hard

可运行示例 · log 与 reset 练习:

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>Git log 与 reset 练习</title>
  <style>
    body { font-family: ui-monospace, monospace; max-width: 720px; margin: 2rem auto; line-height: 1.6; }
    pre { background: #0f172a; color: #e2e8f0; padding: 1rem; border-radius: 8px; }
    .tip { background: #fef3c7; padding: 0.75rem; border-radius: 6px; margin: 1rem 0; }
  </style>
</head>
<body>
  <h1>log / reflog / reset 三步练</h1>
  <div class="tip">在练习仓库中连续提交 3 次后,按下列命令观察 HEAD 变化。</div>
  <pre>git log --oneline
git reset --hard HEAD^
git reflog
git reset --hard &lt;reflog 中的旧哈希&gt;</pre>
  <p>前 7 位 Commit ID 即可定位版本,无需完整 40 位 SHA。</p>
</body>
</html>

【代码注释】HTML 页仅作命令清单展示;实际练习需在终端进入已 git init 的目录执行。

兼容写法(旧版 Git):

bash 复制代码
git checkout -- 文件名      # 同 git restore 文件名
git checkout -- .          # 同 git restore .

【代码注释】Git 2.23+ 推荐 git restore / git restore --staged;旧项目文档可能仍写 checkout --

3.7 .gitignore 忽略规则

名词解析 · gitignore :根目录或子目录下的忽略清单,未跟踪文件匹配规则后不会被 git add

bash 复制代码
# 注释行
*.log
node_modules/
dist/
.env
!.env.example          # 否定:重新包含
/build/                # 仅根目录 build
doc/**/*.pdf

【代码注释】前端工程常见忽略:node_modules/dist/.env、IDE 目录(.vscode/.idea/)。

已从版本库跟踪的文件需先取消跟踪:

bash 复制代码
git rm --cached 文件名
git rm -r --cached 目录名

【代码注释】rm --cached 只从索引移除,本地文件保留;配合 .gitignore 后不再被提交。

经典应用场景:

  • React/Vue :忽略 node_modulesdist.next
  • 密钥安全 :忽略 .env,仅提交 .env.example 模板

3.8 基础模块归纳

操作 工作区 暂存区 版本库 常用命令
查看状态 git status
暂存 修改 → 暂存 git add / git add -A
提交 暂存 → 版本库 git commit
撤销工作区 恢复 git restore .
取消暂存 清空项 git restore --staged
回滚提交 视模式 视模式 移动 HEAD reset / revert

3.9 Git Stash 工作现场暂存

核心概念stash 把工作区 + 暂存区的变更打包存入一个「栈」,随时可弹出恢复,让你在不提交半成品的情况下安全切换分支。

基础命令:

bash 复制代码
# 暂存当前工作现场
git stash                          # 暂存(已跟踪文件的所有修改)
git stash push -m "登录页面开发中"  # 带描述的暂存(强烈推荐)
git stash -u                       # 同时暂存未跟踪的新文件(-u = --include-untracked)
git stash -a                       # 包含 .gitignore 忽略的文件(-a = --all)

# 查看暂存列表
git stash list
# 输出示例:
# stash@{0}: On feature/login: 登录页面开发中
# stash@{1}: WIP on main: fix header style

# 恢复工作现场
git stash pop                      # 弹出最近一次暂存(恢复后自动删除)
git stash apply stash@{1}          # 应用指定暂存但不从栈中删除
git stash drop stash@{0}           # 手动删除指定暂存
git stash clear                    # 清空所有暂存(不可恢复,谨慎使用)

# 查看暂存内容
git stash show stash@{0}           # 简要统计(改了哪些文件)
git stash show -p stash@{0}        # 详细差异(显示具体代码变更)

经典使用场景:

bash 复制代码
# =====================================================
# 场景一:开发到一半,突然接到紧急 Bug
# =====================================================

# 当前在 feature/login 分支,表单逻辑写到一半,无法直接提交
git stash push -m "登录表单---验证逻辑未完成"

# 切换到 main 分支处理紧急 Bug
git switch main
git switch -c hotfix/nav-crash
# ... 修复 Bug,提交 ...
git commit -m "fix: 修复导航栏点击崩溃问题"
git switch main
git merge --no-ff hotfix/nav-crash
git branch -d hotfix/nav-crash

# 回到功能分支,一键恢复之前的工作现场
git switch feature/login
git stash pop
# 代码回到中断时的精确状态,继续开发

# =====================================================
# 场景二:误在主分支上改代码,应该在新分支上改
# =====================================================

git stash                          # 先把修改暂存起来
git switch -c feature/new-feature  # 创建正确的功能分支
git stash pop                      # 代码完美移入新分支,继续开发

# =====================================================
# 场景三:对比两次暂存的差异
# =====================================================

git stash list
git diff stash@{0} stash@{1}       # 对比两次暂存之间的代码差异

# =====================================================
# 场景四:将暂存内容应用到其他分支(不切换,直接用 apply)
# =====================================================

git switch release/v1.2
git stash apply stash@{0}          # 把之前的修复应用到发布分支
# 注意:apply 不删除暂存,可以多次应用到不同分支

4. Git分支管理策略

4.1 分支的基本操作

分支管理核心命令:

bash 复制代码
# 【代码注释】分支创建与切换
git branch feature-login           # 创建分支
git checkout -b feature-login      # 创建并切换到新分支
git switch feature-login           # 切换到已有分支(Git 2.23+)
git checkout feature-login         # 传统切换分支方法

# 【代码注释】分支查看
git branch                         # 查看本地分支
git branch -r                      # 查看远程分支
git branch -a                      # 查看所有分支
git branch -v                      # 查看分支和最新提交
git branch --merged                # 查看已合并的分支
git branch --no-merged             # 查看未合并的分支

# 【代码注释】分支删除
git branch -d feature-login        # 删除已合并的分支
git branch -D feature-login        # 强制删除分支
git push origin --delete feature-login  # 删除远程分支

# 【代码注释】分支重命名
git branch -m old-name new-name    # 重命名当前分支
git branch -m feature-login feature-auth  # 重命名指定分支

【代码注释】分支创建与切换;分支查看;分支删除;分支重命名

4.2 分支合并策略

三种合并方式对比:
#mermaid-svg-AswNna9er56aCpSm{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-AswNna9er56aCpSm .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-AswNna9er56aCpSm .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-AswNna9er56aCpSm .error-icon{fill:#552222;}#mermaid-svg-AswNna9er56aCpSm .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-AswNna9er56aCpSm .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-AswNna9er56aCpSm .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-AswNna9er56aCpSm .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-AswNna9er56aCpSm .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-AswNna9er56aCpSm .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-AswNna9er56aCpSm .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-AswNna9er56aCpSm .marker{fill:#333333;stroke:#333333;}#mermaid-svg-AswNna9er56aCpSm .marker.cross{stroke:#333333;}#mermaid-svg-AswNna9er56aCpSm svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-AswNna9er56aCpSm p{margin:0;}#mermaid-svg-AswNna9er56aCpSm .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-AswNna9er56aCpSm .cluster-label text{fill:#333;}#mermaid-svg-AswNna9er56aCpSm .cluster-label span{color:#333;}#mermaid-svg-AswNna9er56aCpSm .cluster-label span p{background-color:transparent;}#mermaid-svg-AswNna9er56aCpSm .label text,#mermaid-svg-AswNna9er56aCpSm span{fill:#333;color:#333;}#mermaid-svg-AswNna9er56aCpSm .node rect,#mermaid-svg-AswNna9er56aCpSm .node circle,#mermaid-svg-AswNna9er56aCpSm .node ellipse,#mermaid-svg-AswNna9er56aCpSm .node polygon,#mermaid-svg-AswNna9er56aCpSm .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-AswNna9er56aCpSm .rough-node .label text,#mermaid-svg-AswNna9er56aCpSm .node .label text,#mermaid-svg-AswNna9er56aCpSm .image-shape .label,#mermaid-svg-AswNna9er56aCpSm .icon-shape .label{text-anchor:middle;}#mermaid-svg-AswNna9er56aCpSm .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-AswNna9er56aCpSm .rough-node .label,#mermaid-svg-AswNna9er56aCpSm .node .label,#mermaid-svg-AswNna9er56aCpSm .image-shape .label,#mermaid-svg-AswNna9er56aCpSm .icon-shape .label{text-align:center;}#mermaid-svg-AswNna9er56aCpSm .node.clickable{cursor:pointer;}#mermaid-svg-AswNna9er56aCpSm .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-AswNna9er56aCpSm .arrowheadPath{fill:#333333;}#mermaid-svg-AswNna9er56aCpSm .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-AswNna9er56aCpSm .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-AswNna9er56aCpSm .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-AswNna9er56aCpSm .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-AswNna9er56aCpSm .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-AswNna9er56aCpSm .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-AswNna9er56aCpSm .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-AswNna9er56aCpSm .cluster text{fill:#333;}#mermaid-svg-AswNna9er56aCpSm .cluster span{color:#333;}#mermaid-svg-AswNna9er56aCpSm div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-AswNna9er56aCpSm .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-AswNna9er56aCpSm rect.text{fill:none;stroke-width:0;}#mermaid-svg-AswNna9er56aCpSm .icon-shape,#mermaid-svg-AswNna9er56aCpSm .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-AswNna9er56aCpSm .icon-shape p,#mermaid-svg-AswNna9er56aCpSm .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-AswNna9er56aCpSm .icon-shape .label rect,#mermaid-svg-AswNna9er56aCpSm .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-AswNna9er56aCpSm .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-AswNna9er56aCpSm .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-AswNna9er56aCpSm :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 合并策略
Fast-forward

快进合并
Three-way Merge

三方合并
Rebase

变基
适用:线性历史

直接移动指针
适用:分叉历史

创建合并提交
适用:清理历史

重写提交

【代码注释】关系图展示概念对比、流程或决策路径。

实际合并操作:

bash 复制代码
# 【代码注释】快进合并(Fast-forward)
git checkout main
git merge feature-login
# 当feature-login是main的直接后代时,快进合并

# 【代码注释】三方合并(Three-way merge)
git checkout main
git merge feature-login
# 当分支分叉时,Git创建合并提交

# 【代码注释】解决合并冲突
git merge feature-login
# 当遇到冲突时,Git会标记冲突文件

# 【代码注释】手动解决冲突后
git add conflicted-file
git commit  # 完成合并

# 【代码注释】中止合并
git merge --abort                 # 取消合并,恢复到合并前状态

# 【代码注释】变基(Rebase)
git checkout feature-login
git rebase main                   # 将feature-login的提交变基到main
# 变基会创建线性的提交历史

# 【代码注释】交互式变基(编辑历史)
git rebase -i HEAD~3              # 编辑最近3次提交
# 在编辑器中可以:
# pick:保留该提交
# reword:修改提交信息
# edit:修改提交内容
# squash:合并到前一个提交
# drop:删除该提交

【代码注释】快进合并(Fast-forward);三方合并(Three-way merge);解决合并冲突;手动解决冲突后;中止合并;变基(Rebase);交互式变基(编辑历史)

4.3 现代分支策略

2024年推荐的分支策略:
#mermaid-svg-oVORSrdUwhsKSNUu{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-oVORSrdUwhsKSNUu .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-oVORSrdUwhsKSNUu .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-oVORSrdUwhsKSNUu .error-icon{fill:#552222;}#mermaid-svg-oVORSrdUwhsKSNUu .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-oVORSrdUwhsKSNUu .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-oVORSrdUwhsKSNUu .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-oVORSrdUwhsKSNUu .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-oVORSrdUwhsKSNUu .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-oVORSrdUwhsKSNUu .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-oVORSrdUwhsKSNUu .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-oVORSrdUwhsKSNUu .marker{fill:#333333;stroke:#333333;}#mermaid-svg-oVORSrdUwhsKSNUu .marker.cross{stroke:#333333;}#mermaid-svg-oVORSrdUwhsKSNUu svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-oVORSrdUwhsKSNUu p{margin:0;}#mermaid-svg-oVORSrdUwhsKSNUu .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-oVORSrdUwhsKSNUu .cluster-label text{fill:#333;}#mermaid-svg-oVORSrdUwhsKSNUu .cluster-label span{color:#333;}#mermaid-svg-oVORSrdUwhsKSNUu .cluster-label span p{background-color:transparent;}#mermaid-svg-oVORSrdUwhsKSNUu .label text,#mermaid-svg-oVORSrdUwhsKSNUu span{fill:#333;color:#333;}#mermaid-svg-oVORSrdUwhsKSNUu .node rect,#mermaid-svg-oVORSrdUwhsKSNUu .node circle,#mermaid-svg-oVORSrdUwhsKSNUu .node ellipse,#mermaid-svg-oVORSrdUwhsKSNUu .node polygon,#mermaid-svg-oVORSrdUwhsKSNUu .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-oVORSrdUwhsKSNUu .rough-node .label text,#mermaid-svg-oVORSrdUwhsKSNUu .node .label text,#mermaid-svg-oVORSrdUwhsKSNUu .image-shape .label,#mermaid-svg-oVORSrdUwhsKSNUu .icon-shape .label{text-anchor:middle;}#mermaid-svg-oVORSrdUwhsKSNUu .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-oVORSrdUwhsKSNUu .rough-node .label,#mermaid-svg-oVORSrdUwhsKSNUu .node .label,#mermaid-svg-oVORSrdUwhsKSNUu .image-shape .label,#mermaid-svg-oVORSrdUwhsKSNUu .icon-shape .label{text-align:center;}#mermaid-svg-oVORSrdUwhsKSNUu .node.clickable{cursor:pointer;}#mermaid-svg-oVORSrdUwhsKSNUu .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-oVORSrdUwhsKSNUu .arrowheadPath{fill:#333333;}#mermaid-svg-oVORSrdUwhsKSNUu .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-oVORSrdUwhsKSNUu .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-oVORSrdUwhsKSNUu .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-oVORSrdUwhsKSNUu .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-oVORSrdUwhsKSNUu .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-oVORSrdUwhsKSNUu .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-oVORSrdUwhsKSNUu .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-oVORSrdUwhsKSNUu .cluster text{fill:#333;}#mermaid-svg-oVORSrdUwhsKSNUu .cluster span{color:#333;}#mermaid-svg-oVORSrdUwhsKSNUu div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-oVORSrdUwhsKSNUu .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-oVORSrdUwhsKSNUu rect.text{fill:none;stroke-width:0;}#mermaid-svg-oVORSrdUwhsKSNUu .icon-shape,#mermaid-svg-oVORSrdUwhsKSNUu .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-oVORSrdUwhsKSNUu .icon-shape p,#mermaid-svg-oVORSrdUwhsKSNUu .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-oVORSrdUwhsKSNUu .icon-shape .label rect,#mermaid-svg-oVORSrdUwhsKSNUu .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-oVORSrdUwhsKSNUu .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-oVORSrdUwhsKSNUu .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-oVORSrdUwhsKSNUu :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} Trunk-Based Development

主干开发
主干分支

main
短期功能分支

feature/*
修复分支

fix/*
发布分支

release/*
Feature Branch Workflow

功能分支工作流
长期运行的主分支

main/develop
功能分支

feature/*
GitLab Flow

GitLab工作流
主分支

main
环境分支

staging/production

【代码注释】关系图展示概念对比、流程或决策路径。

Trunk-Based Development实现:

bash 复制代码
# 【代码注释】创建短期功能分支
git checkout -b feature/user-authentication

# 【代码注释】开发功能并频繁提交
git add .
git commit -m "feat: 添加用户登录页面"

# 【代码注释】定期同步主分支变更
git fetch origin
git rebase origin/main

# 【代码注释】功能完成后合并回主分支
git checkout main
git merge --no-ff feature/user-authentication
git push origin main

# 【代码注释】删除功能分支
git branch -d feature/user-authentication

【代码注释】创建短期功能分支;开发功能并频繁提交;定期同步主分支变更;功能完成后合并回主分支;删除功能分支

4.4 GitFlow 完整工作流

GitFlow 由 Vincent Driessen 于 2010 年提出,是最广泛采用的 Git 分支策略之一,特别适合有明确版本发布周期的项目(如 App、SDK、SaaS 定期发版)。

五种分支的职责:

分支 命名规范 作用 生命周期
main main 生产环境代码,每次合并自动打 tag 永久
develop develop 下次发布的集成基线 永久
feature feature/* 新功能开发,基于 develop 短期(完成即删)
release release/* 发布准备(仅改版本号、CHANGELOG) 短期
hotfix hotfix/* 生产紧急修复,基于 main 短期

#mermaid-svg-56Kds9N5OWnZg9Tr{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-56Kds9N5OWnZg9Tr .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-56Kds9N5OWnZg9Tr .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-56Kds9N5OWnZg9Tr .error-icon{fill:#552222;}#mermaid-svg-56Kds9N5OWnZg9Tr .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-56Kds9N5OWnZg9Tr .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-56Kds9N5OWnZg9Tr .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-56Kds9N5OWnZg9Tr .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-56Kds9N5OWnZg9Tr .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-56Kds9N5OWnZg9Tr .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-56Kds9N5OWnZg9Tr .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-56Kds9N5OWnZg9Tr .marker{fill:#333333;stroke:#333333;}#mermaid-svg-56Kds9N5OWnZg9Tr .marker.cross{stroke:#333333;}#mermaid-svg-56Kds9N5OWnZg9Tr svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-56Kds9N5OWnZg9Tr p{margin:0;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-id,#mermaid-svg-56Kds9N5OWnZg9Tr .commit-msg,#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms',verdana,arial,sans-serif;font-family:var(--mermaid-font-family);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label0{fill:#ffffff;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit0{stroke:hsl(240, 100%, 46.2745098039%);fill:hsl(240, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight0{stroke:hsl(60, 100%, 3.7254901961%);fill:hsl(60, 100%, 3.7254901961%);}#mermaid-svg-56Kds9N5OWnZg9Tr .label0{fill:hsl(240, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow0{stroke:hsl(240, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label1{fill:black;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit1{stroke:hsl(60, 100%, 43.5294117647%);fill:hsl(60, 100%, 43.5294117647%);}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight1{stroke:rgb(0, 0, 160.5);fill:rgb(0, 0, 160.5);}#mermaid-svg-56Kds9N5OWnZg9Tr .label1{fill:hsl(60, 100%, 43.5294117647%);}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow1{stroke:hsl(60, 100%, 43.5294117647%);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label2{fill:black;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit2{stroke:hsl(80, 100%, 46.2745098039%);fill:hsl(80, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight2{stroke:rgb(48.8333333334, 0, 146.5000000001);fill:rgb(48.8333333334, 0, 146.5000000001);}#mermaid-svg-56Kds9N5OWnZg9Tr .label2{fill:hsl(80, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow2{stroke:hsl(80, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label3{fill:#ffffff;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit3{stroke:hsl(210, 100%, 46.2745098039%);fill:hsl(210, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight3{stroke:rgb(146.5000000001, 73.2500000001, 0);fill:rgb(146.5000000001, 73.2500000001, 0);}#mermaid-svg-56Kds9N5OWnZg9Tr .label3{fill:hsl(210, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow3{stroke:hsl(210, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label4{fill:black;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit4{stroke:hsl(180, 100%, 46.2745098039%);fill:hsl(180, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight4{stroke:rgb(146.5000000001, 0, 0);fill:rgb(146.5000000001, 0, 0);}#mermaid-svg-56Kds9N5OWnZg9Tr .label4{fill:hsl(180, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow4{stroke:hsl(180, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label5{fill:black;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit5{stroke:hsl(150, 100%, 46.2745098039%);fill:hsl(150, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight5{stroke:rgb(146.5000000001, 0, 73.2500000001);fill:rgb(146.5000000001, 0, 73.2500000001);}#mermaid-svg-56Kds9N5OWnZg9Tr .label5{fill:hsl(150, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow5{stroke:hsl(150, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label6{fill:black;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit6{stroke:hsl(300, 100%, 46.2745098039%);fill:hsl(300, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight6{stroke:rgb(0, 146.5000000001, 0);fill:rgb(0, 146.5000000001, 0);}#mermaid-svg-56Kds9N5OWnZg9Tr .label6{fill:hsl(300, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow6{stroke:hsl(300, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch-label7{fill:black;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit7{stroke:hsl(0, 100%, 46.2745098039%);fill:hsl(0, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight7{stroke:rgb(0, 146.5000000001, 146.5000000001);fill:rgb(0, 146.5000000001, 146.5000000001);}#mermaid-svg-56Kds9N5OWnZg9Tr .label7{fill:hsl(0, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow7{stroke:hsl(0, 100%, 46.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .branch{stroke-width:1;stroke:#333333;stroke-dasharray:2;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-label{font-size:10px;fill:#000021;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-label-bkg{font-size:10px;fill:#ffffde;opacity:0.5;}#mermaid-svg-56Kds9N5OWnZg9Tr .tag-label{font-size:10px;fill:#131300;}#mermaid-svg-56Kds9N5OWnZg9Tr .tag-label-bkg{fill:#ECECFF;stroke:hsl(240, 60%, 86.2745098039%);}#mermaid-svg-56Kds9N5OWnZg9Tr .tag-hole{fill:#333;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-merge{stroke:#ECECFF;fill:#ECECFF;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-reverse{stroke:#ECECFF;fill:#ECECFF;stroke-width:3;}#mermaid-svg-56Kds9N5OWnZg9Tr .commit-highlight-inner{stroke:#ECECFF;fill:#ECECFF;}#mermaid-svg-56Kds9N5OWnZg9Tr .arrow{stroke-width:8;stroke-linecap:round;fill:none;}#mermaid-svg-56Kds9N5OWnZg9Tr .gitTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-56Kds9N5OWnZg9Tr :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} main develop feature/login release/v1.0 hotfix/v1.0.1 init 项目初始化 登录 UI 登录 API 合并登录功能 更新版本号 v1.0.0 修复崩溃 Bug v1.0.1

【代码注释】gitGraph 直观展示各分支的时序关系,注意 hotfix 同时合并到 main 和 develop,保证两个长期分支都包含该修复。

实战命令(纯 Git,无需额外工具):

bash 复制代码
# ===== 项目初始化 =====
git init
git commit --allow-empty -m "chore: 项目初始化"
git switch -c develop            # 从 main 创建 develop 分支

# ===== 功能开发 =====
git switch develop
git switch -c feature/user-auth  # 从 develop 切出功能分支
# ... 开发功能 ...
git commit -m "feat(auth): 实现 JWT 登录认证"
git switch develop
git merge --no-ff feature/user-auth -m "merge: 合并用户认证功能"
git branch -d feature/user-auth  # 功能分支完成后删除

# ===== 发布准备 =====
git switch develop
git switch -c release/v1.0.0     # 从 develop 切出发布分支
# 只允许修改版本号、文档,不开发新功能
git commit -m "chore: 版本号升至 v1.0.0"
git switch main
git merge --no-ff release/v1.0.0
git tag -a v1.0.0 -m "Release v1.0.0"
git switch develop
git merge --no-ff release/v1.0.0  # 发布分支也需同步回 develop
git branch -d release/v1.0.0

# ===== 紧急热修复 =====
git switch main                  # 从 main 切出,而非 develop
git switch -c hotfix/login-crash
git commit -m "fix: 修复 iOS 下登录白屏"
git switch main
git merge --no-ff hotfix/login-crash
git tag -a v1.0.1 -m "Hotfix v1.0.1"
git switch develop
git merge --no-ff hotfix/login-crash  # 同样需要同步回 develop
git branch -d hotfix/login-crash

GitFlow 适用与不适用场景对比:

适合 GitFlow 不适合 GitFlow
定期版本发布(APP、SDK) 持续部署(每天多次上线)
多版本并行维护 小型团队 / 独立开发者
严格 QA 测试周期的项目 Monorepo 微服务架构

4.5 Cherry-pick 精选提交

git cherry-pick 允许从任意分支「摘取」一个或多个提交,应用到当前分支,无需合并整个分支

核心使用场景:

  • develop 上某个 Bug Fix 单独移植到已发布的 release 分支
  • 从废弃分支中救回有价值的提交
  • 在多个维护版本之间同步相同的修复

基础命令:

bash 复制代码
# 应用单个提交(最常用)
git cherry-pick <commit-hash>

# 应用多个不连续的提交
git cherry-pick abc123 def456 ghi789

# 应用连续区间(含 end,不含 start)
git cherry-pick start..end
# 或(含两端)
git cherry-pick start^..end

# 仅应用变更到工作区,不自动提交(方便手动调整后再提交)
git cherry-pick -n <commit-hash>

# 遇到冲突时的处理流程
git cherry-pick --continue    # 解决冲突后继续
git cherry-pick --abort       # 放弃整个 cherry-pick,恢复原状
git cherry-pick --skip        # 跳过当前有冲突的提交

经典场景:将 develop 上的修复移植到已发布版本

bash 复制代码
# Step 1: 在 develop 上查看提交历史,找到目标修复
git log develop --oneline
# abc1234 fix(auth): 修复 token 过期未自动刷新
# def5678 feat: 添加深色模式(不需要,不移植)

# Step 2: 切换到需要修复的维护分支
git switch release/v1.2

# Step 3: 精准移植目标提交
git cherry-pick abc1234
# 成功后:会生成一个新哈希的提交,内容与 abc1234 相同

# Step 4: 更新补丁版本号并打标签
git tag -a v1.2.1 -m "fix: 移植 token 自动刷新修复"
git push origin release/v1.2 --follow-tags

注意cherry-pick 会重写 SHA-1,新提交的内容相同但哈希不同。避免在多人共用的公共分支上对已有提交反复使用,会造成混乱的历史。


4.6 合并冲突实战解决

冲突(Conflict)是团队协作中的常态,而非异常。理解冲突标记并从容处理,是高级开发者的必备技能。

冲突标记解读:

复制代码
<<<<<<< HEAD                   ← 当前分支(你的代码,在 === 上方)
const API_URL = 'http://localhost:8080';
=======                        ← 分隔线
const API_URL = 'https://api.example.com';
>>>>>>> feature/config         ← 被合并进来的分支(在 === 下方)

完整冲突解决五步法:

bash 复制代码
# Step 1: 触发合并,Git 自动报告冲突
git switch main
git merge feature/config
# Auto-merging config.js
# CONFLICT (content): Merge conflict in config.js
# Automatic merge failed; fix conflicts and then commit the result.

# Step 2: 确认哪些文件有冲突
git status
# both modified: config.js   ← 需要手动解决的文件

# Step 3: 打开冲突文件,手动选择保留的代码
# 方式 A:直接编辑文件,删除 <<<, ===, >>> 标记,保留正确内容
# 方式 B(推荐):用图形工具可视化解决
git mergetool                     # 调用已配置的 mergetool(如 VS Code)

# Step 4: 标记冲突已解决,加入暂存区
git add config.js

# Step 5: 完成合并提交
git commit
# Git 自动填写合并提交信息,也可以手动修改

# 验证结果
git log --graph --oneline -5

配置 VS Code 为可视化合并工具:

bash 复制代码
# 全局配置
git config --global merge.tool vscode
git config --global mergetool.vscode.cmd 'code --wait $MERGED'
git config --global mergetool.keepBackup false  # 合并后不保留 .orig 备份文件

# 合并时一键启动 VS Code 三窗格界面
git mergetool

预防冲突的最佳实践:

bash 复制代码
# 1. 开发期间频繁同步主分支(减少冲突积累,越早合并冲突越少)
git fetch origin
git rebase origin/main           # 变基比 merge 更保持线性历史

# 2. 推送前先拉取,确保本地与远程同步
git pull --rebase origin main
git push origin feature/my-feature

# 3. 合并前先预览冲突(演习)
git merge --no-commit --no-ff feature/x   # 合并但不提交
git diff --staged                          # 查看合并结果
git merge --abort                          # 不满意就一键放弃

# 4. 模块化拆分文件,减少多人改同一文件的概率
# 例如:把 config.js 拆为 config.dev.js / config.prod.js

5. Git远程协作

5.1 远程仓库管理

远程仓库基础操作:

bash 复制代码
# 【代码注释】查看远程仓库
git remote                        # 显示远程仓库名称
git remote -v                     # 显示详细信息
git remote show origin           # 显示远程仓库详情

# 【代码注释】添加远程仓库
git remote add origin https://github.com/username/repo.git
git remote add upstream https://github.com/original/repo.git

# 【代码注释】删除远程仓库
git remote remove origin

# 【代码注释】重命名远程仓库
git remote rename origin upstream

# 【代码注释】修改远程仓库URL
git remote set-url origin https://github.com/username/new-repo.git

【代码注释】查看远程仓库;添加远程仓库;删除远程仓库;重命名远程仓库;修改远程仓库URL

5.2 推送与拉取

与远程仓库同步:

bash 复制代码
# 【代码注释】推送到远程仓库
git push origin main              # 推送main分支
git push -u origin feature-branch # 推送并设置上游分支
git push --all origin             # 推送所有分支
git push --tags                   # 推送所有标签
git push --force                  # 强制推送(谨慎使用)

# 【代码注释】从远程仓库获取更新
git fetch origin                  # 获取所有分支更新
git fetch origin main             # 获取特定分支更新
git pull origin main              # 拉取并合并到当前分支
git pull --rebase origin main     # 拉取并变基

# 【代码注释】拉取与变基的最佳实践
git pull --rebase --autostash     # 自动暂存本地修改

【代码注释】推送到远程仓库;从远程仓库获取更新;拉取与变基的最佳实践

5.3 协作工作流

团队协作常用模式:

bash 复制代码
# 【代码注释】Fork & Pull Request工作流
# 1. Fork原始仓库到个人账号
# 2. 克隆个人仓库
git clone https://github.com/your-username/forked-repo.git

# 3. 添加上游仓库
git remote add upstream https://github.com/original/repo.git

# 4. 创建功能分支
git checkout -b feature-new-functionality

# 5. 开发并提交
git add .
git commit -m "feat: 添加新功能"

# 6. 推送到个人仓库
git push origin feature-new-functionality

# 7. 同步上游更新
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

# 【代码注释】Shared Repository工作流
# 1. 克隆共享仓库
git clone https://github.com/company/shared-repo.git

# 2. 为每个任务创建分支
git checkout -b feature/task-123

# 3. 推送到远程
git push -u origin feature/task-123

# 4. 创建Pull Request进行代码审查
# 5. 审查通过后合并到主分支
# 6. 删除功能分支
git branch -d feature/task-123
git push origin --delete feature/task-123

【代码注释】Fork & Pull Request工作流;Shared Repository工作流


6. Git高级技巧

6.1 Git钩子(Hooks)

自动化工作流的钩子脚本:

bash 复制代码
# 【代码注释】Git钩子位置
.git/hooks/
├── pre-commit       # 提交前执行
├── prepare-commit-msg # 准备提交信息时执行
├── commit-msg       # 提交信息验证
├── post-commit      # 提交后执行
├── pre-push         # 推送前执行
└── post-merge       # 合并后执行

# 【代码注释】示例:代码检查钩子
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
# 代码检查钩子
echo "运行代码检查..."

# 运行ESLint
npm run lint
if [ $? -ne 0 ]; then
    echo "代码检查失败,提交中止"
    exit 1
fi

# 检查文件大小
for file in $(git diff --cached --name-only); do
    size=$(stat -c%s "$file")
    if [ $size -gt 1048576 ]; then
        echo "错误:文件 $file 大小超过1MB"
        exit 1
    fi
done

echo "代码检查通过"
EOF

chmod +x .git/hooks/pre-commit

# 【代码注释】示例:提交信息规范钩子
cat > .git/hooks/commit-msg << 'EOF'
#!/bin/bash
# 提交信息规范检查
commit_msg=$(cat $1)
pattern="^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}"

if ! [[ $commit_msg =~ $pattern ]]; then
    echo "错误:提交信息不符合规范"
    echo "格式:类型(范围): 简短描述"
    echo "类型:feat, fix, docs, style, refactor, test, chore"
    exit 1
fi
EOF

chmod +x .git/hooks/commit-msg

【代码注释】Git钩子位置;示例:代码检查钩子;示例:提交信息规范钩子

6.2 Git别名配置

提高效率的别名设置:

bash 复制代码
# 【代码注释】实用的Git别名配置
git config --global alias.co checkout
git config --global alias.br 'branch -av'
git config --global alias.ci 'commit -v'
git config --global alias.st 'status -sb'
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

# 【代码注释】高级别名示例
git config --global alias.amend 'commit --amend --no-edit'
git config --global alias.aliases 'config --get-regexp alias'
git config --global alias.cleanup "!git branch --merged | grep -v \"\\*\" | xargs -n 1 git branch -d"
git config --global alias.unpushed "log @{u}.."
git config --global alias.pullff "pull --ff-only"

# 【代码注释】使用示例
git co main                        # 等同于 git checkout main
git br                             # 等同于 git branch -av
git lg                             # 图形化日志
git cleanup                        # 清理已合并的分支

【代码注释】实用的Git别名配置;高级别名示例;使用示例

6.3 高级搜索与过滤

在代码历史中高效搜索:

bash 复制代码
# 【代码注释】搜索提交历史
git log --all --grep="搜索关键词"   # 按提交信息搜索
git log --all --author="张三"       # 按作者搜索
git log --all --since="2024-01-01"  # 按时间搜索

# 【代码注释】搜索代码内容
git grep "function_name"           # 在当前代码中搜索
git grep "function_name" $(git rev-list --all)  # 在所有版本中搜索

# 【代码注释】查找引入bug的提交
git bisect start                   # 开始二分查找
git bisect bad                      # 标记当前提交为坏
git bisect good HEAD~10             # 标记已知好的提交
# Git会自动切换到中间提交供测试
git bisect good/bad                # 继续标记,直到找到问题提交
git bisect reset                    # 结束查找

# 【代码注释】查找文件历史
git log --follow -- filename       # 查看文件完整历史(包括重命名)
git whatchanged filename            # 显示文件变更历史

【代码注释】搜索提交历史;搜索代码内容;查找引入bug的提交;查找文件历史

6.4 子模块管理

管理项目依赖:

bash 复制代码
# 【代码注释】添加子模块
git submodule add https://github.com/user/repo.git path/to/submodule

# 【代码注释】初始化和更新子模块
git submodule init                  # 初始化子模块配置
git submodule update               # 更新子模块
git submodule update --init --recursive  # 初始化并更新所有子模块

# 【代码注释】克隆包含子模块的项目
git clone --recursive https://github.com/user/project.git

# 【代码注释】子模块工作流程
cd path/to/submodule
git pull origin main               # 更新子模块
cd ../..
git add path/to/submodule
git commit -m "更新子模块版本"

【代码注释】添加子模块;初始化和更新子模块;克隆包含子模块的项目;子模块工作流程

6.5 Git 标签管理

标签(tag)是对某个 commit 的命名快照,常用于标记正式发布版本,配合 SemVer 规范使用。

两种标签类型对比:

类型 创建命令 特点 适用场景
轻量标签 git tag v1.0 只是 commit 的别名指针 临时标记、本地调试
附注标签 git tag -a v1.0 -m "说明" 独立对象,含作者/日期/签名 正式版本发布(推荐)

标签管理命令:

bash 复制代码
# ===== 创建标签 =====
git tag v1.0.0                                     # 轻量标签(不推荐用于发版)
git tag -a v1.0.0 -m "正式发布 v1.0.0"             # 附注标签(推荐)
git tag -a v0.9.0 abc1234 -m "为历史提交补打标签"   # 给历史提交打标签

# ===== 查看标签 =====
git tag                                            # 列出所有标签
git tag -l "v1.*"                                  # 按 glob 模式过滤
git show v1.0.0                                    # 查看标签详情(含提交信息)

# ===== 推送标签到远程 =====
git push origin v1.0.0                             # 推送单个标签
git push origin --tags                             # 推送所有本地标签
git push --follow-tags                             # 推送提交时自动同步附注标签

# ===== 删除标签 =====
git tag -d v1.0.0-beta                             # 删除本地标签
git push origin --delete v1.0.0-beta               # 删除远程标签

# ===== 基于标签操作 =====
git checkout v1.0.0                                # 检出标签(进入 detached HEAD)
git checkout -b fix/v1.0 v1.0.0                    # 基于标签创建修复分支(推荐)

SemVer 语义化版本规范:

复制代码
v主版本号.次版本号.修订号[-预发布标识]

v1.0.0        → 正式发布
v1.1.0        → 新增向后兼容的功能(次版本号+1)
v1.1.1        → Bug 修复(修订号+1)
v2.0.0        → 有破坏性变更(主版本号+1)
v2.0.0-alpha  → 预览版(不保证稳定)
v2.0.0-beta.1 → 公测版第一轮
v2.0.0-rc.1   → 发布候选版

自动化发布脚本(release.sh):

bash 复制代码
#!/bin/bash
# 用法: ./release.sh v1.2.0

VERSION=$1

if [ -z "$VERSION" ]; then
  echo "用法: ./release.sh <版本号,如 v1.2.0>"
  exit 1
fi

# 检查是否在 main 分支
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ]; then
  echo "错误:请在 main 分支执行发布"
  exit 1
fi

# 确保工作区干净
if [ -n "$(git status --porcelain)" ]; then
  echo "错误:工作区有未提交的修改,请先提交"
  exit 1
fi

git tag -a "$VERSION" -m "Release $VERSION"
git push origin "$VERSION"
echo "已成功发布 $VERSION"

6.6 Git Worktree 多工作区

痛点 :需要同时在 main 上排查线上问题、在 feature/login 上继续开发,来回 stash + checkout 极为繁琐。

Worktree 解决方案 :同一仓库在多个目录 同时检出不同分支,共享同一个 .git 数据库,互不干扰。

bash 复制代码
# 添加新工作区(在 ../project-hotfix 目录检出 hotfix/crash 分支)
git worktree add ../project-hotfix hotfix/crash

# 创建新分支并检出到指定目录
git worktree add -b experiment/perf-test ../project-perf HEAD

# 查看当前所有工作区
git worktree list
# 输出示例:
# /Users/dev/my-project       abc1234 [main]
# /Users/dev/project-hotfix   def5678 [hotfix/crash]

# 在新工作区独立操作(另开一个终端窗口)
cd ../project-hotfix
git status        # 完全独立的工作区,与主目录互不影响
# ... 修复代码,提交 ...
git commit -m "fix: 修复支付崩溃"

# 工作完成后移除辅助工作区
cd ../my-project
git worktree remove ../project-hotfix

适用场景:

场景 说明
紧急 Bug 修复 主目录继续开发,新工作区专门 hotfix
A/B 性能测试 两个目录各跑一个分支,直接对比结果
Code Review 把 PR 分支检出到独立目录,不影响当前工作
同时查看两版本文档 老版本和新版本文档并排对比

提示:同一分支不能被两个工作区同时检出,Git 会报错提示。


7. Git工作流最佳实践

7.1 提交信息规范

遵循Conventional Commits规范:

bash 复制代码
# 【代码注释】提交信息格式
<type>(<scope>): <subject>

<body>

<footer>

# 【代码注释】类型(type)
feat:     新功能
fix:      修复bug
docs:     文档变更
style:    代码格式调整(不影响功能)
refactor: 重构(不是新功能也不是修复)
test:     添加测试
chore:    构建过程或辅助工具的变动

# 【代码注释】实际示例
git commit -m "feat(auth): 添加用户登录功能"
git commit -m "fix(api): 修复用户数据获取bug"
git commit -m "docs(readme): 更新安装说明"
git commit -m "refactor(user): 重构用户模块代码结构"

# 【代码注释】详细的多行提交
git commit -m "feat(dashboard): 添加数据可视化功能

- 实现图表展示组件
- 添加数据导出功能
- 支持多种图表类型

Closes #123"

【代码注释】提交信息格式;类型(type);实际示例;详细的多行提交

7.2 分支命名约定

团队统一的分支命名规范:

bash 复制代码
# 【代码注释】功能分支
feature/user-authentication
feature/payment-gateway
feature/admin-panel

# 【代码注释】修复分支
fix/login-bug
fix/payment-error
fix/navigation-issue

# 【代码注释】发布分支
release/v1.0.0
release/v2.1.3

# 【代码注释】热修复分支
hotfix/critical-security-fix
hotfix/emergency-patch

# 【代码注释】实验性分支
experiment/new-ui-design
experiment/performance-test

# 【代码注释】版本标签
v1.0.0
v2.1.3

【代码注释】功能分支;修复分支;发布分支;热修复分支;实验性分支;版本标签

7.3 代码审查流程

Pull Request最佳实践:

javascript 复制代码
// 【代码注释】Pull Request模板
const pullRequestTemplate = `
## 描述
简要描述此PR的目的和实现的功能。

## 变更类型
- [ ] 新功能
- [ ] Bug修复
- [ ] 重构
- [ ] 文档更新
- [ ] 性能优化

## 测试
- [ ] 添加了单元测试
- [ ] 手动测试通过
- [ ] 更新了相关文档

## 检查清单
- [ ] 代码符合团队规范
- [ ] 提交信息清晰明确
- [ ] 无console.log或调试代码
- [ ] 更新了相关文档

## 相关Issue
Closes #[issue_number]
`;

// 【代码注释】PR审查检查项
const reviewChecklist = {
    codeQuality: [
        "代码逻辑清晰易懂",
        "变量和函数命名规范",
        "适当的错误处理",
        "代码注释充分且准确"
    ],
    functionality: [
        "功能实现符合需求",
        "边界情况处理正确",
        "用户体验良好",
        "性能表现可接受"
    ],
    testing: [
        "单元测试覆盖率充足",
        "集成测试通过",
        "手动测试验证",
        "回归测试无副作用"
    ],
    documentation: [
        "README文件更新",
        "API文档完整",
        "变更日志更新",
        "注释清晰准确"
    ]
};

【代码注释】Pull Request模板;PR审查检查项


8. 故障排查与解决方案

8.1 常见问题解决

日常开发中的常见问题:

bash 复制代码
# 【代码注释】问题1:合并冲突
# 症状:Git无法自动合并文件
# 解决方案:
git status                           # 查看冲突文件
git diff                             # 查看具体冲突
# 手动编辑冲突文件,解决冲突标记
git add conflicted-file              # 标记为已解决
git commit                           # 完成合并

# 【代码注释】问题2:误删分支
# 症状:删除了错误的分支
# 解决方案:
git reflog                           # 查找分支哈希
git checkout -b branch-name <hash>   # 恢复分支

# 【代码注释】问题3:错误的提交
# 症状:提交了错误的内容或信息
# 解决方案:
git reset --soft HEAD~1             # 撤销最后一次提交
git reset --hard HEAD~1             # 完全删除最后一次提交
git revert HEAD                      # 创建新提交撤销旧提交

# 【代码注释】问题4:意外的文件删除
# 症状:误删了重要文件
# 解决方案:
git restore filename                # 从暂存区恢复
git restore --source=HEAD~1 filename  # 从历史提交恢复
git checkout HEAD~1 -- filename      # 从特定版本恢复

# 【代码注释】问题5:推送被拒绝
# 症状:远程仓库有本地没有的更新
# 解决方案:
git pull --rebase                   # 拉取并变基
git pull                            # 拉取并合并
git push                            # 重新推送

【代码注释】问题1:合并冲突;问题2:误删分支;问题3:错误的提交;问题4:意外的文件删除;问题5:推送被拒绝

8.2 数据恢复技巧

Git数据恢复的完整指南:

bash 复制代码
# 【代码注释】恢复删除的提交
git reflog                           # 查看所有操作记录
git show <commit-hash>               # 查看特定提交
git checkout -b recovery-branch <commit-hash>  # 恢复到分支

# 【代码注释】恢复丢失的文件
git fsck --full                      # 检查仓库完整性
git show <blob-hash> > recovered-file.txt  # 恢复文件内容

# 【代码注释】从垃圾回收中恢复
git stash list                       # 查看暂存列表
git stash pop                        # 恢复暂存内容
git stash apply                      # 应用暂存但不删除

# 【代码注释】恢复删除的远程分支
git reflog show origin/feature-branch  # 查看远程分支历史
git checkout -b feature-branch origin/feature-branch  # 重建分支

【代码注释】恢复删除的提交;恢复丢失的文件;从垃圾回收中恢复;恢复删除的远程分支


9. 团队协作实战案例

9.1 多人协作场景

实际团队协作工作流:

bash 复制代码
# 【代码注释】场景:团队开发新功能
# 开发者A: 初始化项目
mkdir team-project
cd team-project
git init
echo "# 团队项目" > README.md
git add .
git commit -m "feat: 初始化项目"
git remote add origin https://github.com/team/project.git
git push -u origin main

# 【代码注释】开发者B: 加入项目
git clone https://github.com/team/project.git
cd project
git checkout -b feature-user-auth
# 开发认证功能...

# 【代码注释】开发者C: 同时开发其他功能
git clone https://github.com/team/project.git
cd project
git checkout -b feature-admin-panel
# 开发管理面板...

# 【代码注释】同步开发
# 开发者B完成功能
git add .
git commit -m "feat(auth): 添加用户认证"
git push -u origin feature-user-auth
# 创建Pull Request

# 开发者C同步最新代码
git fetch origin
git rebase origin/main
git push -u origin feature-admin-panel

# 【代码注释】代码审查与合并
# 团队成员审查PR,提出修改意见
# 开发者根据反馈修改代码
# 维护者合并PR到主分支
# 删除已合并的功能分支

【代码注释】场景:团队开发新功能;开发者B: 加入项目;开发者C: 同时开发其他功能;同步开发;代码审查与合并

9.2 发布管理流程

版本发布的标准流程:

bash 复制代码
# 【代码注释】准备发布
git checkout -b release/v1.0.0
# 更新版本号、修改日志等
git commit -m "chore: 准备v1.0.0发布"

# 【代码注释】创建发布标签
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin release/v1.0.0
git push origin v1.0.0

# 【代码注释】合并到主分支
git checkout main
git merge release/v1.0.0
git push origin main

# 【代码注释】发现问题时的热修复
git checkout -b hotfix/critical-bug
# 修复bug...
git commit -m "fix: 修复关键安全bug"

# 【代码注释】热修复发布
git checkout main
git merge hotfix/critical-bug
git tag -a v1.0.1 -m "Hotfix release 1.0.1"
git push origin main --tags

【代码注释】准备发布;创建发布标签;合并到主分支;发现问题时的热修复;热修复发布


10. 总结与进阶学习

10.1 Git技能发展路径

#mermaid-svg-RODffqBSMJ27G0io{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-RODffqBSMJ27G0io .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-RODffqBSMJ27G0io .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-RODffqBSMJ27G0io .error-icon{fill:#552222;}#mermaid-svg-RODffqBSMJ27G0io .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-RODffqBSMJ27G0io .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-RODffqBSMJ27G0io .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-RODffqBSMJ27G0io .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-RODffqBSMJ27G0io .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-RODffqBSMJ27G0io .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-RODffqBSMJ27G0io .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-RODffqBSMJ27G0io .marker{fill:#333333;stroke:#333333;}#mermaid-svg-RODffqBSMJ27G0io .marker.cross{stroke:#333333;}#mermaid-svg-RODffqBSMJ27G0io svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-RODffqBSMJ27G0io p{margin:0;}#mermaid-svg-RODffqBSMJ27G0io .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-RODffqBSMJ27G0io .cluster-label text{fill:#333;}#mermaid-svg-RODffqBSMJ27G0io .cluster-label span{color:#333;}#mermaid-svg-RODffqBSMJ27G0io .cluster-label span p{background-color:transparent;}#mermaid-svg-RODffqBSMJ27G0io .label text,#mermaid-svg-RODffqBSMJ27G0io span{fill:#333;color:#333;}#mermaid-svg-RODffqBSMJ27G0io .node rect,#mermaid-svg-RODffqBSMJ27G0io .node circle,#mermaid-svg-RODffqBSMJ27G0io .node ellipse,#mermaid-svg-RODffqBSMJ27G0io .node polygon,#mermaid-svg-RODffqBSMJ27G0io .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-RODffqBSMJ27G0io .rough-node .label text,#mermaid-svg-RODffqBSMJ27G0io .node .label text,#mermaid-svg-RODffqBSMJ27G0io .image-shape .label,#mermaid-svg-RODffqBSMJ27G0io .icon-shape .label{text-anchor:middle;}#mermaid-svg-RODffqBSMJ27G0io .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-RODffqBSMJ27G0io .rough-node .label,#mermaid-svg-RODffqBSMJ27G0io .node .label,#mermaid-svg-RODffqBSMJ27G0io .image-shape .label,#mermaid-svg-RODffqBSMJ27G0io .icon-shape .label{text-align:center;}#mermaid-svg-RODffqBSMJ27G0io .node.clickable{cursor:pointer;}#mermaid-svg-RODffqBSMJ27G0io .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-RODffqBSMJ27G0io .arrowheadPath{fill:#333333;}#mermaid-svg-RODffqBSMJ27G0io .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-RODffqBSMJ27G0io .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-RODffqBSMJ27G0io .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-RODffqBSMJ27G0io .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-RODffqBSMJ27G0io .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-RODffqBSMJ27G0io .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-RODffqBSMJ27G0io .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-RODffqBSMJ27G0io .cluster text{fill:#333;}#mermaid-svg-RODffqBSMJ27G0io .cluster span{color:#333;}#mermaid-svg-RODffqBSMJ27G0io div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-RODffqBSMJ27G0io .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-RODffqBSMJ27G0io rect.text{fill:none;stroke-width:0;}#mermaid-svg-RODffqBSMJ27G0io .icon-shape,#mermaid-svg-RODffqBSMJ27G0io .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-RODffqBSMJ27G0io .icon-shape p,#mermaid-svg-RODffqBSMJ27G0io .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-RODffqBSMJ27G0io .icon-shape .label rect,#mermaid-svg-RODffqBSMJ27G0io .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-RODffqBSMJ27G0io .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-RODffqBSMJ27G0io .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-RODffqBSMJ27G0io :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 初级水平

基础命令
中级水平

分支管理
高级水平

工作流优化
专家水平

工具定制与团队指导
git add/commit/pull/push
merge/rebase/cherry-pick
钩子脚本/别名配置
Git架构设计/性能优化

【代码注释】关系图展示概念对比、流程或决策路径。

10.2 Day04 知识点速查

模块 核心要点
三区模型 工作区 → git add → 暂存区 → git commit → 版本库
对象模型 blob/tree/commit/tag 四种对象;SHA-1 保证历史不可篡改
撤销 restore 工作区;restore --staged 暂存区;reset/revert 历史
回滚 HEAD~nreflog 找回;--soft/--mixed/--hard 选型
Stash 切换分支前 stash push -m;恢复用 pop;不提交半成品
分支 branch/switch/merge;冲突五步法;cherry-pick 精选移植
GitFlow main + develop + feature + release + hotfix 五分支模型
远程 clone/push/pull-u 设上游;Fork + PR 协作
标签 tag -a v1.0 -m;SemVer 规范;push --follow-tags
Worktree 多目录同时检出不同分支,共享 .git,代替频繁 stash

10.3 持续学习资源

官方资源:

实践项目建议:

  1. 个人项目:使用Git管理个人代码库
  2. 开源贡献:参与GitHub开源项目
  3. 团队协作:在工作中推行Git最佳实践
  4. 工具定制:编写个性化的Git脚本和别名

参考资料:

掌握Git是一个持续的过程,从基础命令到高级特性,再到团队协作和工作流优化,每个阶段都需要大量的实践和经验积累。建议在日常开发中不断尝试新技巧,逐步建立适合自己的Git工作流程。


附录 A:命令与场景速查

场景 推荐命令
首次配置 git config --global user.name / user.email
新建仓库 git initgit add -Agit commit
克隆项目 git clone <url>
查看改动 git status / git diff / git diff --staged
撤销误改 git restore . / git restore --staged
回滚版本 git refloggit reset --hard <hash>
同步远程 git pull --rebasegit push
功能开发 git switch -c feature/x → 开发 → PR
紧急切换 git stash push -m "描述" → 切分支 → git stash pop
精选移植 git cherry-pick <hash> 把某提交移植到当前分支
版本发布 git tag -a v1.0.0 -m "说明"git push --follow-tags
多分支并行 git worktree add ../dir branch-name 多目录并行工作
解决冲突 编辑冲突文件 → git addgit commit
查看对象 git cat-file -p HEAD / git ls-tree HEAD 观察内部结构

附录 B:官方与延伸阅读

资源 链接 说明
Pro Git 中文版 https://git-scm.com/book/zh/v2 权威免费电子书
Git 参考手册 https://git-scm.com/docs 命令参数详解
GitHub Docs https://docs.github.com/zh PR、Actions、分支保护
Gitee 帮助 https://gitee.com/help 国内托管平台文档
Git 速查表 https://git-scm.com/cheat-sheet 命令一页汇总

文中 HTML 示例可直接保存后在浏览器打开;Git 命令请在终端进入练习目录执行。

相关推荐
码出财富3 小时前
InsForge 后端分支管理实战指南
git
2601_961194024 小时前
2026六级词汇PDF下载|大学英语六级单词表+音频PDF
windows·git·eclipse·pdf·github
幽冥三王爷6 小时前
Git 操作常见问题与处理办法
git
独挽离人7 小时前
git标准推送流程
git
无人生还别怕8 小时前
搭建gitlab服务并接入openldap认证
git·gitlab·github·openldap·ldap·统一认证
努力努力再努力wz9 小时前
【Qt入门系列】一文掌握 Qt 常用显示类控件:QLCDNumber、QProgressBar 与 QCalendarWidget
c语言·开发语言·数据结构·数据库·c++·git·qt
查拉图斯特拉面条9 小时前
Git操作指南:克隆、提交、推送与避坑大全
大数据·git·elasticsearch
恋喵大鲤鱼12 小时前
git status
git·git status
恋喵大鲤鱼12 小时前
git rm
git·git rm