ENGINEERING WORKFLOW · 62
Git Foundation:Working Tree、Staging Area、Commit 不是同一件事
Git 最容易學錯的方法,就是把它背成 add → commit → push 三行指令。真正要理解的是:Git 同時追蹤 working tree、staging area、commit history;每個 command 都是在這些 state 之間移動資料。
Learning outcomes
- 能區分 working tree、index/staging area、HEAD commit。
- 能解釋 status/diff/add/commit/log 各觀察哪個 state。
- 能判斷「檔案有改但 commit 沒包含」的原因。
- 能安全檢查變更再建立 commit。
1. 三個核心狀態
Working tree
│ git add
▼
Staging area / index
│ git commit
▼
Repository history
│
▼
HEAD → latest commit你在 editor 存檔,只改 working tree。git add 把某個版本放進 staging area;git commit 再把 staged snapshot 寫入 history。
2. status 是第一個 evidence
git status
git diff
git diff --staged
git log --oneline -5git diff 常看 working tree 相對 staging 的差異;git diff --staged 看下一個 commit 準備包含什麼。不要只看到「modified」就直接 commit。
3. Commit 是 snapshot + history node
git add lessons/62-git-command-foundations.html
git commit -m "Deepen Git state model"Commit message 應描述一個 coherent change。把「修 CSS、改 API、刪資料、重寫課程」全部塞進同一 commit,會讓 review、rollback、bisect 都更困難。
4. push 不是 commit
git push origin mainPush 把本機已存在的 commits 傳到 remote。若 working tree 還有未 commit 修改,push 不會自動把它們一起上傳。
5. Project checkpoint:Course Workspace v1
建立一個小型 course workspace,修改 README 與一個 HTML lesson。先故意只 stage README,再觀察 status/diff,確認下一個 commit 不會意外包含 lesson。
git status
git add README.md
git diff --staged
git commit -m "Document course workspace"Debug evidence:為什麼 GitHub 沒看到我剛改的檔?
- Working tree 有沒有修改?
- 修改有沒有 staged?
- 有沒有真的產生新 commit?
- 目前 branch 是哪一條?
- 新 commit 有沒有 push 到正確 remote?
Knowledge check
- 存檔後、git add 前,變更在哪一層?
git diff --staged解答什麼問題?- push 為什麼不會上傳未 commit 的 working-tree change?
- 做一次「只 stage 一半檔案」的實驗並預測 commit 內容。