git commit - 提交變更

git commit 把暫存區的變更存到 repository,建立一個新的 commit。每個 commit 就像一個存檔點,記錄了專案在某個時間點的狀態。

基本用法

提交並輸入訊息

git commit -m "你的 commit 訊息"

例如:

git commit -m "Add login feature"

開啟編輯器輸入訊息

git commit

這會開啟預設編輯器(通常是 Vim),讓你輸入較長的 commit message。

一次加入並提交

git commit -am "Your message"

-a 會自動把所有已追蹤檔案的修改加入暫存區,然後 commit。

注意:-a 不會加入新的未追蹤檔案,只會處理已追蹤檔案的修改和刪除。

Commit Message 撰寫規範

好的 commit message 對於專案維護非常重要。

基本格式

<type>: <subject>

<body>

<footer>

常見的 Type

  • feat: 新功能
  • fix: 修復 bug
  • docs: 文件更新
  • style: 程式碼格式調整(不影響功能)
  • refactor: 重構
  • test: 測試相關
  • chore: 雜項(建置工具、依賴更新等)

範例

簡短訊息:

git commit -m "feat: add user registration"
git commit -m "fix: resolve login timeout issue"
git commit -m "docs: update README"

詳細訊息:

feat: add user registration

- Add registration form component
- Implement email validation
- Connect to authentication API

Closes #123

好的 Commit Message 特點

  1. 簡潔明瞭:第一行不超過 50 字元
  2. 使用祈使句:用 "Add feature" 而不是 "Added feature"
  3. 說明 What 和 Why:說明做了什麼以及為什麼

不好的範例:

git commit -m "update"
git commit -m "fix bug"
git commit -m "asdfasdf"

好的範例:

git commit -m "Fix user avatar not displaying on profile page"
git commit -m "Add pagination to product listing"

修改 Commit

修改最後一次 Commit

如果你剛 commit 完就發現訊息打錯了,或忘記加入某個檔案:

# 修改 commit message
git commit --amend -m "新的訊息"

# 加入遺漏的檔案(不改訊息)
git add forgotten-file.txt
git commit --amend --no-edit

--amend 會用新的 commit 取代最後一個 commit。

如果 commit 已經推送到遠端,修改後需要強制推送 git push --force。在團隊協作時要非常小心,可能會造成其他人的困擾。

開啟編輯器修改訊息

git commit --amend

空 Commit

有時候你需要建立一個沒有任何檔案變更的 commit(例如觸發 CI/CD):

git commit --allow-empty -m "Trigger CI build"

查看 Commit 前的變更

在 commit 之前,確認一下要提交的內容:

# 查看暫存區的變更
git diff --staged

# 查看狀態
git status

實際工作流程

小步 Commit

好的習慣是經常 commit,每完成一個小功能就 commit 一次:

# 完成登入表單
git add src/components/LoginForm.js
git commit -m "feat: add login form component"

# 完成驗證邏輯
git add src/utils/validation.js
git commit -m "feat: add form validation utils"

# 完成 API 整合
git add src/api/auth.js
git commit -m "feat: integrate login API"

使用 Patch 模式

如果一個檔案有多處不相關的修改,可以分開 commit:

git add -p index.js
# 選擇要加入的部分
git commit -m "fix: resolve null pointer error"

git add -p index.js
# 選擇其他部分
git commit -m "feat: add error logging"

其他選項

指定作者

git commit --author="Name <email@example.com>" -m "Message"

指定日期

git commit --date="2024-01-01 12:00:00" -m "Message"

跳過 Hooks

git commit --no-verify -m "Message"

如果專案有設定 pre-commit hook(例如跑 lint),用 --no-verify 可以跳過。

常見問題

Nothing to commit

nothing to commit, working tree clean

這表示暫存區是空的。你需要先用 git add 加入檔案。

不小心 commit 了不該 commit 的檔案

如果還沒 push,可以:

# 回到上一個 commit,但保留變更
git reset --soft HEAD~1

# 然後重新 add 和 commit
git add correct-files.txt
git commit -m "Message"