git 的init-db命令执行逻辑

在创建和管理git目录仓库的过程中,git的init-db命令是第一个执行的命令,为git仓库创建进行必要的准备,具体来说就是创建一些目录结构,用来管理对象数据库和cache信息.

该命令的执行入口函数为(init-db.c):

 8 int main(int argc, char **argv)
 9 {
10         char *sha1_dir = getenv(DB_ENVIRONMENT), *path;
11         int len, i, fd;
12 
13         if (mkdir(".dircache", 0700) < 0) {
14                 perror("unable to create .dircache");
15                 exit(1);
16         }
17 
18         /*
19          * If you want to, you can share the DB area with any number of branches.
20          * That has advantages: you can save space by sharing all the SHA1 objects.
21          * On the other hand, it might just make lookup slower and messier. You
22          * be the judge.
23          */
24         sha1_dir = getenv(DB_ENVIRONMENT);
25         if (sha1_dir) {
26                 struct stat st;
27                 if (!stat(sha1_dir, &st) < 0 && S_ISDIR(st.st_mode))
28                         return;
29                 fprintf(stderr, "DB_ENVIRONMENT set to bad directory %s: ", sha1_dir);
30         }
31 
32         /*
33          * The default case is to have a DB per managed directory.
34          */
35         sha1_dir = DEFAULT_DB_ENVIRONMENT;
36         fprintf(stderr, "defaulting to private storage area\n");
37         len = strlen(sha1_dir);
38         if (mkdir(sha1_dir, 0700) < 0) {
39                 if (errno != EEXIST) {
40                         perror(sha1_dir);
41                         exit(1);
42                 }
43         }
44         path = malloc(len + 40);
45         memcpy(path, sha1_dir, len);
46         for (i = 0; i < 256; i++) {
47                 sprintf(path+len, "/%02x", i);
48                 if (mkdir(path, 0700) < 0) {
49                         if (errno != EEXIST) {
50                                 perror(path);
51                                 exit(1);
52                         }
53                 }
54         }
55         return 0;
56 }

Line13:16在当前目录下创建名为.dircache的目录,这个目录用来管理cache信息,也可以用来管理对象数据库.Line18:30如果存在环境变量DB_ENVIRONMENT配置,那么所有的对象将被统一管理,统一管理对象数据库,可能在存储效率上省一些空间,但是对于对象的查找可能要慢一些.Line32:43创建目录DEFAULT_DB_ENVIRONMENT(.dircache/objects),对象数据库将在该目录下进行管理.Line44:54的含义是在目录DEFAULT_DB_ENVIRONMENT下面创建256个子目录,这些子目录的名字是0~255的整数,并且是16进制格式,2个字符对齐.这个逻辑的涉及思想可以通过和其他命令结合来理解,因为对象文件存储时,(对象文件名是个SHA1字符串,20个字符),会被存储到特定的目录下,这个规则就是其SHA1名字的前两个字符的目录名,所以相当于把对象文件进行了一个均匀的映射,使其查找效率更高效,而且这里必须创建256个子目录.

猜你喜欢

转载自blog.csdn.net/azurelaker/article/details/81670178