16/19 本篇章節
第五篇 · 19 章
開始使用 Git
- 01 新增、初始 Repository
- 02 把檔案交給 Git 控管
- 03 工作區、暫存區與儲存庫
- 04 檢視紀錄
- 05 【狀況題】如何在 Git 裡刪除檔案或變更檔名?
- 06 【狀況題】修改 Commit 紀錄
- 07 【狀況題】追加檔案到最近一次的 Commit
- 08 【狀況題】新增目錄?
- 09 【狀況題】有些檔案我不想放在 Git 裡面...
- 10 【狀況題】檢視特定檔案的 Commit 紀錄
- 11 【狀況題】等等,這行程式誰寫的?
- 12 【狀況題】啊!不小心把檔案或目錄刪掉了…
- 13 【狀況題】剛才的 Commit 後悔了,想要拆掉重做…
- 14 【狀況題】不小心使用 hard 模式 Reset 了某個 Commit,救得回來嗎?
- 15 【冷知識】HEAD 是什麼東西?
- 16 【狀況題】可以只 Commit 一個檔案的部份的內容嗎?
- 17 【冷知識】那個長得很像亂碼 SHA-1 是怎麼算出來的?
- 18 【超冷知識】在 .git 目錄裡有什麼東西?Part 1 僅收錄於電子書
- 19 【超冷知識】在 .git 目錄裡有什麼東西?Part 2 僅收錄於電子書
第五篇 · 開始使用 Git
【狀況題】可以只 Commit 一個檔案的部份的內容嗎?
舉個例子來說,假設我的網站的首頁 index.html 的內容是這樣:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>首頁</title>
</head>
<body>
<div class="container">
<h1 id="heading">頭版消息</h1>
<div>
內文
內文
內文
內文
</div>
<div id="footer">
版權沒有,歡迎取用
</div>
</div>
</body>
</html>
如果我因為某些龜毛的原因,footer 那個區塊還不想 Commit,在 Git 也可以先 Commit 其它的部份。
$ git add -p index.html
diff --git a/index.html b/index.html
index e90bdb3..2cac685 100644
--- a/index.html
+++ b/index.html
@@ -6,6 +6,16 @@
</head>
<body>
<div class="container">
+ <h1 id="heading">頭版消息</h1>
+ <div>
+ 內文
+ 內文
+ 內文
+ 內文
+ </div>
+ <div id="footer">
+ 版權沒有,歡迎取用
+ </div>
</div>
</body>
</html>
Stage this hunk [y,n,q,a,d,/,e,?]?
當使用 git add 的時候加上 -p 參數後,Git 會問說是不是要把這個區塊(hunk)加到暫存區,如果選 y 就是整個檔案加進去。但因為我只想送出部份內容,所以選擇了 e 選項,接著就會出現編輯器顯示以下內容:
# Manual hunk edit mode -- see bottom for a quick guide.
@@ -6,6 +6,16 @@
</head>
<body>
<div class="container">
+ <h1 id="heading">頭版消息</h1>
+ <div>
+ 內文
+ 內文
+ 內文
+ 內文
+ </div>
+ <div id="footer">
+ 版權沒有,歡迎取用
+ </div>
</div>
</body>
</html>
# ---
# To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.
#
# If the patch applies cleanly, the edited hunk will immediately be
# marked for staging.
# If it does not 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.
在這邊就可以編輯想要加到暫存區的區塊,因為 footer 的那個區塊我還不想加進去,所以我就把那三行刪掉,存檔並離開便可「把部份內容加到暫存區」。看一下目前的狀態:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: index.html
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: index.html
index.html 這個檔案就有部份在暫存區,同時也有一份有包括那三行的版本放在工作目錄。這樣一來就可以只先 Commit 部份的內容了。
在 SourceTree 做這件事相對的比較簡單一些,用滑鼠選取想要加入的內容,按滑鼠右鍵選擇「Stage Selected Lines」,然後就搞定了。
