2 minute read     Posted on:     Updated on:

Recall the Basics

1.3 Getting Started - What is Git?

眾所周知,Git 會將檔案分成以下幾種狀態

  • untracked :arrow_right: 新檔案
  • modified :arrow_right: 檔案已被更改,尚未被 git 追蹤最新更改紀錄
  • staged :arrow_right: 檔案最新狀態已被更新至 staging area 了,等待 commit 進 local database
  • committed :arrow_right: 檔案狀態已經被寫入 local database

透過 $ git add 你可以將 modified 或 untracked 的檔案推入 staged 的狀態

modified untracked

檔案狀態

Introduction to Git Add

git add 的操作簡單,卻也有不同的玩法

我最近遇到了一個狀況,是這樣子的
開發一個新 feature 的時候,想當然的會有許多的修改,動輒十幾個檔案的異動
我自己的習慣會是偏向一次寫完一個段落在 commit
但是在上版控的時候就是一個災難了

如先前所提到的,十幾個檔案 changes 必須合理的分配在不同的 commit 裡面
比方說

* Add router endpoint
* Add user database implementation
* Add user service layer implementation

而實作中可能會在同一個檔案裡面,參雜到不同 commit 的 changes

這時候 git add 如果能夠分不同部份 個別 commit
那麼對於整體 git history 就會更有善了

Git Add - Partial Add

要進行 partial add 只需要加一個參數 -p 在 git add 後面即可

$ git add -p 2022-09-24-git-add.md

git add -pgit add --interactive 的 patch mode

接下來它會提示你接下來的操作

Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?

hunk 表示一個區塊,上方顯示的所有修改都屬於同一個 hunk
所以你操作的單位都是以 hunk 為主

目前我比較常用的操作是

operation description
y stage 目前的 hunk
n 不要 stage 目前的 hunk
q 離開並且不 stage 任何東西
s 將目前的 hunk 切成更小部份
e 手動分割 hunk

你也可以輸入 ? 取得所有操作的手冊(它會顯示在 hunk 上方,所以要往上拉才看得到)

當你完成所有的 hunk 操作之後,你就完成 partial add 了
接下來的操作你就很熟悉了, commit 然後 push 到 remote

Hunk Slice

前面提到,你可以將一個 hunk 切成更小的部份
s 是自動切成更小的 hunk
有時候你會遇到他的 prompt 沒有 s 的情況

(1/1) Stage addition [y,n,q,a,d,e,?]?

這時候你就必須手動切 hunk 了(e)


輸入之後它會帶你到文字編輯器,長的像下面這個樣子

# Manual hunk edit mode -- see bottom for a quick guide

+ ...
+ ...
- ...

# ---
# To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.
# If it doesn't apply cleanly, you will be given an opportunity to
# edit again. If all lines of the hunk are removed, then the edit is
# aborted and the hunk is left unchanged.

中間顯示的部份是你這次新增的 changes, 預設都是會被加到 staging area
如果你 不希望把某一行加到這次的 commit,

  • 對於 + 開頭的 :arrow_right: 就把它刪掉(這裡的刪掉不會刪掉你的 changes, 它只是標記說這行不要加進 staging area)
  • 對於 - 開頭的 :arrow_right:
    • 把開頭的 - 號 替換成 {empty space} (空白 space)
      -this is the deleted line
    

    變成

       this is the deleted line
    
    • 這樣被刪除的 changes 就不會被加到 staging area 了

如果你改錯了 它會顯示

Your edited hunk does not apply. Edit again (saying "no" discards!) [y/n]?

How to do Partial Add for Untracked File

對於新的檔案,你可能會遇到

$ git add -p new_file
No changes.

這是因為 git 並不認得新的檔案,它屬於 untracked file
只要將它加進去版控裡面就可以了

$ git add -N new_file
$ git add -p new_file
...
Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?

References

Leave a comment