1/*2* GIT - the stupid content tracker3*4* Copyright (c) Junio C Hamano, 20065*/6#include "cache.h"7#include "strbuf.h"8#include "quote.h"9#include "tree.h"1011static struct treeent {12unsigned mode;13unsigned char sha1[20];14int len;15char name[FLEX_ARRAY];16} **entries;17static int alloc, used;1819static void append_to_tree(unsigned mode, unsigned char *sha1, char *path)20{21struct treeent *ent;22int len = strlen(path);23if (strchr(path, '/'))24die("path %s contains slash", path);2526if (alloc <= used) {27alloc = alloc_nr(used);28entries = xrealloc(entries, sizeof(*entries) * alloc);29}30ent = entries[used++] = xmalloc(sizeof(**entries) + len + 1);31ent->mode = mode;32ent->len = len;33hashcpy(ent->sha1, sha1);34memcpy(ent->name, path, len+1);35}3637static int ent_compare(const void *a_, const void *b_)38{39struct treeent *a = *(struct treeent **)a_;40struct treeent *b = *(struct treeent **)b_;41return base_name_compare(a->name, a->len, a->mode,42b->name, b->len, b->mode);43}4445static void write_tree(unsigned char *sha1)46{47struct strbuf buf;48size_t size;49int i;5051qsort(entries, used, sizeof(*entries), ent_compare);52for (size = i = 0; i < used; i++)53size += 32 + entries[i]->len;54strbuf_init(&buf);55strbuf_grow(&buf, size);5657for (i = 0; i < used; i++) {58struct treeent *ent = entries[i];59strbuf_addf(&buf, "%o %s%c", ent->mode, ent->name, '\0');60strbuf_add(&buf, ent->sha1, 20);61}6263write_sha1_file(buf.buf, buf.len, tree_type, sha1);64}6566static const char mktree_usage[] = "git-mktree [-z]";6768int main(int ac, char **av)69{70struct strbuf sb;71unsigned char sha1[20];72int line_termination = '\n';7374setup_git_directory();7576while ((1 < ac) && av[1][0] == '-') {77char *arg = av[1];78if (!strcmp("-z", arg))79line_termination = 0;80else81usage(mktree_usage);82ac--;83av++;84}8586strbuf_init(&sb);87while (1) {88char *ptr, *ntr;89unsigned mode;90enum object_type type;91char *path;9293read_line(&sb, stdin, line_termination);94if (sb.eof)95break;96ptr = sb.buf;97/* Input is non-recursive ls-tree output format98* mode SP type SP sha1 TAB name99*/100mode = strtoul(ptr, &ntr, 8);101if (ptr == ntr || !ntr || *ntr != ' ')102die("input format error: %s", sb.buf);103ptr = ntr + 1; /* type */104ntr = strchr(ptr, ' ');105if (!ntr || sb.buf + sb.len <= ntr + 40 ||106ntr[41] != '\t' ||107get_sha1_hex(ntr + 1, sha1))108die("input format error: %s", sb.buf);109type = sha1_object_info(sha1, NULL);110if (type < 0)111die("object %s unavailable", sha1_to_hex(sha1));112*ntr++ = 0; /* now at the beginning of SHA1 */113if (type != type_from_string(ptr))114die("object type %s mismatch (%s)", ptr, typename(type));115ntr += 41; /* at the beginning of name */116if (line_termination && ntr[0] == '"')117path = unquote_c_style(ntr, NULL);118else119path = ntr;120121append_to_tree(mode, sha1, path);122123if (path != ntr)124free(path);125}126write_tree(sha1);127puts(sha1_to_hex(sha1));128exit(0);129}