GIT 源码阅读之 init-db

来源:互联网 发布:淘宝上共享账号下软件 编辑:程序博客网 时间:2024/06/05 20:21

说明

本文所有代码基于 GIT COMMIT e83c5163316f89bfbde7d9ab23ca2e25604af290 版本的源码,在 Ubuntu 16.04 上编译运行,部分代码有所改动。

init-db

init-db 是 GIT 最初版本中用于初始化缓存目录的命令,部分源码如下所示(有所修改)。

int main(int argc, char **argv){        char *sha1_dir = getenv(DB_ENVIRONMENT), *path;        int len, i, fd;        if (mkdir(".dircache", 0700) < 0) {                perror("unable to create .dircache");                exit(1);        }        /*         * If you want to, you can share the DB area with any number of branches.         * That has advantages: you can save space by sharing all the SHA1 objects.         * On the other hand, it might just make lookup slower and messier. You         * be the judge.         */        sha1_dir = getenv(DB_ENVIRONMENT);        if (sha1_dir) {                struct stat st;                if (!stat(sha1_dir, &st) < 0 && S_ISDIR(st.st_mode))                        return 0; /* 增加返回值 */                fprintf(stderr, "DB_ENVIRONMENT set to bad directory %s: ", sha1_dir);        }        /*         * The default case is to have a DB per managed directory.         */        sha1_dir = DEFAULT_DB_ENVIRONMENT;        fprintf(stderr, "defaulting to private storage area\n");        len = strlen(sha1_dir);        if (mkdir(sha1_dir, 0700) < 0) {                if (errno != EEXIST) {                        perror(sha1_dir);                        exit(1);                }        }        path = malloc(len + 40);        memcpy(path, sha1_dir, len);        for (i = 0; i < 256; i++) {                sprintf(path+len, "/%02x", i);                if (mkdir(path, 0700) < 0) {                        if (errno != EEXIST) {                                perror(path);                                exit(1);                        }                }        }        return 0;}

从源码可以看出, init-db 首先在当前路径创建 .dircache 目录。接着通过环境变量 DB_ENVIRONMENT 来判断用户是采用私有存储空间还是公有存储空间,两者的区别在于 SHA1 对象是否共享,公有存储可以共享相同的 SHA1 对象,但是它将导致查询速度变慢。当采用私有存储空间时, init-db 将在 .dircache 目录下创建 objects 目录用于存放 SHA1 对象。最后, init-db 将在 .dircache/objects 目录创建 256 个目录用于分类存放 SHA1 对象。

原创粉丝点击