Git源码解析-环境搭建

Why? How?

Why?

做这件事的起因是在和导师做的一篇论文想去argue一个场景,场景下涉及到去了解git的delta compression机制,所以这个系列的文章核心是弄清楚git的压缩相关机制,当然如果工作流有涉及那么也会一起研究下。

How?

在本地环境从源码编译git的源代码。

1. 获取源代码

1
2
git clone https://github.com/git/git.git
cd git

2. 配置编译选项

在编译之前,可以配置安装路径和其他选项。为了不覆盖系统自带的Git,建议将编译后的Git安装到 /usr/local 或者其他自定义目录。

1
2
make configure
./configure --prefix=/home/Helix/repos/myGit/

–prefix=/usr/local 指定安装路径为 /usr/local,这样不会覆盖系统自带的Git(通常安装在 /usr/bin/git)。

3. 编译和安装Git

1
2
3
4
5
6
7
make all

# 可选:运行测试确保一切正常
make test

# 安装到指定目录
sudo make install

4. 创建别名

创建一个自定义别名即可。

1
2
3
# 添加到zshrc文件中
alias mygit='/home/Helix/repos/myGit/bin/git'
source ~/.zshrc

之后使用mygit就可以执行编译后的版本,方便调试。

5. 编写脚本方便后续编译

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/bin/bash

# 定义安装前缀
PREFIX=/home/junwu202322080121/Helix/repos/myGit

# 导航到 Git 源代码目录
cd /home/junwu202322080121/Helix/repos/git || exit

# 拉取最新更改(如果需要)
# git pull origin master

# 配置编译选项(如果尚未配置)
if [ ! -f Makefile ]; then
make configure
./configure --prefix=${PREFIX}
fi

# 编译
make -j$(nproc)

# # 运行测试(可选)
# make test

# 安装
sudo make install

# 打印版本以验证
${PREFIX}/bin/git --versioncd

6. 修改代码验证

这里我们在 git.c中的 cmd_main函数中加一句输出(git的程序入口)

1
2
3
4
5
6
int cmd_main(int argc, const char **argv)
{
// ...
printf("This is mygit building.\n");
// ...
}

编译并在任意空目录使用mygit创建一个new repo

证明环境搭建成功。


Git源码解析-环境搭建
https://arcanus.red/2024/11/03/git源码解析-环境搭建/
作者
Helix
发布于
2024年11月3日
许可协议