Skip to content

Git - 执行修改

Jerry 克隆了 仓库(repository),并决定实现基本的字符串操作。于是他创建了一个 string_utils.c 文件。添加内容后,string_utils.c 将如下所示:

#include <stdio.h>
#include <string.h> // For strcmp, strcpy if used later
// A custom function to calculate string length
size_t my_strlen(const char *s)
{
const char *p = s;
while (*p) {
++p;
}
return (p - s);
}
int main(void)
{
int i;
char *s[] =
{
"Git tutorials",
"Tutorials Point"
};
printf("Demonstrating my_strlen:\n");
for (i = 0; i < 2; ++i) {
printf("Length of \"%s\" = %zu\n", s[i], my_strlen(s[i]));
}
return 0;
}

他编译并测试了他的代码(例如,gcc string_utils.c -o string_app),一切按预期工作。编译生成的输出文件 string_app 通常不进行 版本控制(version-controlled),在实际项目中会被添加到 .gitignore 文件中。现在,他可以安全地将源代码变更添加到 仓库 中了。

git add 命令将文件内容添加到 暂存区(staging area),也称为 索引(index)。

[jerry@devbox project]$ git status -s
?? string_utils.c
[jerry@devbox project]$ git add string_utils.c

最初,git status -s 在 string_utils.c 前显示 ??,表示这是一个 未跟踪文件(untracked file)。在执行 git add string_utils.c 后,Git 开始跟踪此文件,其当前内容已 暂存(staged)以待下次 提交(commit)。

Jerry 已将文件添加到 暂存区。git status 命令现在将显示该文件已 暂存。

[jerry@devbox project]$ git status -s
A string_utils.c

要 提交 暂存的变更,他使用带 -m 选项的 git commit 命令来添加 提交信息(commit message)。如果省略 -m 选项,Git 将打开一个文本编辑器来编写更详细的 提交信息。最佳实践是编写清晰简洁的 提交信息,解释变更的原因。

[jerry@devbox project]$ git commit -m "Implement my_strlen function and main demo"

上述命令将产生类似于以下的输出:

[main abc1234] Implement my_strlen function and main demo
1 file changed, 25 insertions(+)
create mode 100644 string_utils.c

提交 后,他运行 git log 命令来查看 提交历史。它显示所有 提交 的信息,包括它们的 提交 ID(SHA-1 hash)、 作者(author)、 日期(date) 和 提交信息。

[jerry@devbox project]$ git log

上述命令将产生类似于以下的输出(最新 提交 在最前面):

commit abc1234b140dad24b2c35b15cc7e26a6f02d2277 (HEAD -> main)
Author: Jerry Mouse <jerry@example.com>
Date: Mon Jan 15 10:00:00 2024 +0000
Implement my_strlen function and main demo
commit 19ae20683fc460db7d127cf201a1429523b0e319
Author: Tom Cat <tom@example.com>
Date: Sun Jan 14 09:30:00 2024 +0000
Initial commit