2 * GIT - the stupid content tracker
4 * Copyright (c) Junio C Hamano, 2006
11 static struct treeent
{
13 unsigned char sha1
[20];
15 char name
[FLEX_ARRAY
];
17 static int alloc
, used
;
19 static void append_to_tree(unsigned mode
, unsigned char *sha1
, char *path
)
22 int len
= strlen(path
);
23 if (strchr(path
, '/'))
24 die("path %s contains slash", path
);
27 alloc
= alloc_nr(used
);
28 entries
= xrealloc(entries
, sizeof(*entries
) * alloc
);
30 ent
= entries
[used
++] = xmalloc(sizeof(**entries
) + len
+ 1);
33 hashcpy(ent
->sha1
, sha1
);
34 memcpy(ent
->name
, path
, len
+1);
37 static int ent_compare(const void *a_
, const void *b_
)
39 struct treeent
*a
= *(struct treeent
**)a_
;
40 struct treeent
*b
= *(struct treeent
**)b_
;
41 return base_name_compare(a
->name
, a
->len
, a
->mode
,
42 b
->name
, b
->len
, b
->mode
);
45 static void write_tree(unsigned char *sha1
)
51 qsort(entries
, used
, sizeof(*entries
), ent_compare
);
52 for (size
= i
= 0; i
< used
; i
++)
53 size
+= 32 + entries
[i
]->len
;
55 strbuf_grow(&buf
, size
);
57 for (i
= 0; i
< used
; i
++) {
58 struct treeent
*ent
= entries
[i
];
59 strbuf_addf(&buf
, "%o %s%c", ent
->mode
, ent
->name
, '\0');
60 strbuf_add(&buf
, ent
->sha1
, 20);
63 write_sha1_file(buf
.buf
, buf
.len
, tree_type
, sha1
);
66 static const char mktree_usage
[] = "git-mktree [-z]";
68 int main(int ac
, char **av
)
71 unsigned char sha1
[20];
72 int line_termination
= '\n';
74 setup_git_directory();
76 while ((1 < ac
) && av
[1][0] == '-') {
78 if (!strcmp("-z", arg
))
90 enum object_type type
;
93 read_line(&sb
, stdin
, line_termination
);
97 /* Input is non-recursive ls-tree output format
98 * mode SP type SP sha1 TAB name
100 mode
= strtoul(ptr
, &ntr
, 8);
101 if (ptr
== ntr
|| !ntr
|| *ntr
!= ' ')
102 die("input format error: %s", sb
.buf
);
103 ptr
= ntr
+ 1; /* type */
104 ntr
= strchr(ptr
, ' ');
105 if (!ntr
|| sb
.buf
+ sb
.len
<= ntr
+ 40 ||
107 get_sha1_hex(ntr
+ 1, sha1
))
108 die("input format error: %s", sb
.buf
);
109 type
= sha1_object_info(sha1
, NULL
);
111 die("object %s unavailable", sha1_to_hex(sha1
));
112 *ntr
++ = 0; /* now at the beginning of SHA1 */
113 if (type
!= type_from_string(ptr
))
114 die("object type %s mismatch (%s)", ptr
, typename(type
));
115 ntr
+= 41; /* at the beginning of name */
116 if (line_termination
&& ntr
[0] == '"')
117 path
= unquote_c_style(ntr
, NULL
);
121 append_to_tree(mode
, sha1
, path
);
127 puts(sha1_to_hex(sha1
));