git 源码解析(六)read-tree

本文介绍了一个用于解析SHA1标识的文件内容的C程序。该程序能够处理不同类型的文件(如blob、tree或commit),并从中提取文件类型、大小及内容等关键信息。此外,对于tree类型的文件,程序还能够递归地解析其所引用的所有子文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

int main(int argc, char **argv)
{
    unsigned char sha1[20];
    if (argc != 2)
        usage("read-tree <key>");
    if (get_sha1_hex(argv[1], sha1) < 0)
        usage("read-tree <key>");
    unpack(sha1);
        // get file type(blob/tree/commit), content size and content
        buffer = read_sha1_file(sha1, type, &size); 
            map = map_sha1_file(sha1, &mapsize);
	            char *filename = sha1_file_name(sha1);
                int fd = open(filename, O_RDONLY);
                fstat(fd, &st);
                map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
                *mapsize = st.st_size;
                return map;
            buf = unpack_sha1_file(map, mapsize, type, size);
                char buffer[8192];
                stream.next_in = map;
                stream.avail_in = mapsize;
                stream.next_out = buffer;
                stream.avail_out = sizeof(buffer);
                inflate(&stream, 0); 
                // buffer: "blob %lu\0xxx"
                // buffer: "tree %lu\0%o %s\0sha1%o %s\0sha1...%o %s\0sha1"
                // buffer: "commit %lu\0tree %s\nparent %s\n..parent %s\nauthor %s <%s> %s\ncommitter %s <%s> %s\n\n%s"
                sscanf(buffer, "%10s %lu", type, size);
                bytes = strlen(buffer) + 1;
                buf = malloc(*size);
                memcpy(buf, buffer + bytes, stream.total_out - bytes);
                // buf: "xxx" 
                // buf: "%o %s\0sha1%o %s\0sha1...%o %s\0sha1" 
                // buf: "tree %s\nparent %s\n..parent %s\nauthor %s <%s> %s\ncommitter %s <%s> %s\n\n%s" 
                return buf; 
        if (strcmp(type, "tree"))
            usage("expected a 'tree' node");
        while (size) 
            int len = strlen(buffer)+1; // buffer: "%o %s\0sha1%o %s\0sha1...%o %s\0sha1"
            unsigned char *sha1 = buffer + len;
            char *path = strchr(buffer, ' ')+1;
            sscanf(buffer, "%o", &mode);
            buffer = sha1 + 20;
            size -= len + 20;
            // get file type(blob), content size and content
            data = read_sha1_file(sha1, type, &filesize); 
            if (!data || strcmp(type, "blob"))
                usage("tree file refers to bad file data");
            fd = create_file(path); // save blob content to file
            write(fd, data, filesize);
            fchmod(fd, mode);
            close(fd);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值