1.10. 添加文件到索引
我们接下来看一下如何将文件添加到索引。到目前为止,我们一直在讨论 git 对已提交镜像的 low level 的表达方式。接下来我们要来手动准备和提交一个新的快照。这将让我们了解 git 是如何管理工作目录和暂存区的。
添加文件到索引
创建一个新的文件,名为 news-4.html
vi news-4.html
将下面的内容加进去:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Indigo Invasion</title>
<link rel="stylesheet" href="style.css" />
<meta charset="utf-8" />
</head>
<body>
<h1 style="color: #A0C">Indigo Invasion</h1>
<p>Last week, a coalition of Asian designers, artists,
and advertisers announced the official color of Asia:
<span style="color: #A0C">Indigo</span>.</p>
<p><a href="index.html">Return to home page</a></p>
</body>
</html>
接下来我们更新一下 index.html,在 news 区块加入一行:
<h2 style="color: #C00">News</h2>
<ul>
<li><a href="news-1.html">Blue Is The New Hue</a></li>
<li><a href="rainbow.html">Our New Rainbow</a></li>
<li><a href="news-2.html">A Red Rebellion</a></li>
<li><a href="news-3.html">Middle East's Silent Beast</a></li>
+ <li><a href="news-4.html">Indigo Invasion</a></li>
</ul>
我们看一下现在的状态。
➜ plumbing-demo git:(main) ✗ git status
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: index.html
Untracked files:
(use "git add <file>..." to include in what will be committed)
news-4.html
通常情况下,如果要将这两个文件加入暂存区,我们需要使用 git add 命令。但是现在我们要用 low level 的方式来操作。我们使用 git update-index 这个命令来添加文件到暂存区。
索引是 git 对暂存镜像的专业术语。我们使用 git update-index 这个命令来将它们添加到暂存区。
➜ plumbing-demo git:(main) ✗ git update-index index.html
➜ plumbing-demo git:(main) ✗ git status
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: index.html
Untracked files:
(use "git add <file>..." to include in what will be committed)
news-4.html
我们就可以看到我们的 index.html
已经添加到了暂停区。接下来我们要对新创建的这个文件进行操作。
➜ plumbing-demo git:(main) ✗ git update-index news-4.html
error: news-4.html: cannot add to the index - missing --add option?
fatal: Unable to process path news-4.html
这里我们就看到了,出现了错误,它提示不能够将这个文件添加到索引,并问是不是少了 --add 这个选项。因为对于 git update-index
命令,假如你没有明确地指出这是一个新文件,git 是不会将其添加到暂存区的(update index 从字面上来说就是更新索引,你都还没有被添加进去,谈何 update?),所以说我们应该加上 add 这个选项。然后我们现在运行一下 git status 看一下:
➜ plumbing-demo git:(main) ✗ git update-index --add news-4.html
➜ plumbing-demo git:(main) ✗ git status
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: index.html
new file: news-4.html
这个时候就可以了。现在两个文件都已经被我们加入暂存区了,这就是说我们接下来就可以准备提交镜像了。然而(提交镜像)这个过程并不像我们之前使用 git commit 那么简单。