Skip to content

L04. Git 版本控制 (上):时光机的使用说明

Vibe Coding 宣言:代码是可以重来的,人生不行。但 Git 可以让你在代码世界里拥有“读档重来”的超能力。

0. 为什么这一课至关重要? (Why It Matters)

  • 后悔药:改崩了?一键回滚。
  • 协作基石:没有 Git,你只能靠发压缩包 final_v2_真的最后版.zip 给队友。太 low 了。
  • 必须掌握:这是程序员的入场券。

1. 目标 (Goal)

学会建立仓库 (Repo),存档代码 (Commit),查看历史 (Log),并学会忽略不该传的文件 (.gitignore)。

2. 核心概念/装备/指令 (The Core)

2.1 三个区域 (The Areas)

别被复杂的图绕晕了。你只需要知道:

  • 工作区 (Workspace):你正在写代码的地方。
  • 暂存区 (Stage):你觉得写得差不多了,准备存一下的地方。(git add)
  • 仓库 (Repository):永久存档的地方。(git commit)

2.2 核心指令 (The Big 4)

  • git init:把这个文件夹变成 Git 仓库。
  • git add .:把所有修改放入暂存区。(别一个个加了,全加进去!)
  • git commit -m "msg":正式存档。
  • git status:现在是什么情况?

2.3 忽略文件 (.gitignore)

有些东西不能传:密码、依赖包 (node_modules)、临时文件。创建一个 .gitignore 文件,把它们的名字写进去。

3. 实战演练 (Action)

Step 1: 初始化 (Start)

进入你的项目目录,把 Git 叫醒。

bash
cd my-vibe-project
git init
# 输出:Initialized empty Git repository in ...

Step 2: 设置身份 (Identity)

告诉 Git 你是谁(只需要做一次)。

bash
git config --global user.name "Your Name"
git config --global user.email "your@email.com"

Step 3: 忽略垃圾 (.gitignore)

创建 .gitignore 文件,写入不想管的东西。

bash
touch .gitignore
echo "node_modules/" >> .gitignore
echo ".env" >> .gitignore  # 重要!保护你的 Key
echo "__pycache__/" >> .gitignore

Step 4: 第一次存档 (Save Point)

查看状态:

bash
git status
# 会看到一堆红色的文件(Untracked)

全部加入暂存区:

bash
git add .
git status
# 变绿了(Changes to be committed)

提交存档:

bash
git commit -m "feat: init project"
# 存档成功!

Step 5: 查看历史 (Time Travel)

看看你刚才干了啥。

bash
git log
# 或者用简洁模式
git log --oneline
# 输出:a1b2c3d feat: init project

4. 常见问题 (FAQ - Vibe Style)

Q: git add 后悔了怎么办? A: git reset。如果不带参数,就是把暂存区的东西撤回来。

Q: 提交信息 (Commit Message) 怎么写? A: 遵循 type: description 格式。

  • feat: 新功能
  • fix: 修 Bug
  • docs: 改文档
  • chore: 杂活
  • Vibe Tip: 如果不知道怎么写,直接把 git diff 甩给 Claude,让它帮你生成 Commit Message。

Q: 为什么要有暂存区?直接提交不行吗? A: 可以,用 git commit -am "msg" (前提是文件已经被追踪过)。但暂存区能让你分批提交,更有条理。新手直接 git add . 就行。

5. 验收标准 (Definition of Done)

  1. 在项目里运行 git status,显示 "nothing to commit, working tree clean"。
  2. 运行 git log,能看到至少一条提交记录。
  3. 确保 .env 文件存在,但在 git status 里看不到它(被忽略了)。

Next Mission: L05. Git 版本控制 (下):多人运动指南

基于 Claude Code 构建