1/*
2* GIT - The information manager from hell
3*
4* Copyright (C) Linus Torvalds, 2005
5*/
6#include "cache.h"
78
int line_termination = '\n';
9int recursive = 0;
1011
struct path_prefix {
12struct path_prefix *prev;
13const char *name;
14};
1516
static void print_path_prefix(struct path_prefix *prefix)
17{
18if (prefix) {
19if (prefix->prev)
20print_path_prefix(prefix->prev);
21fputs(prefix->name, stdout);
22putchar('/');
23}
24}
2526
static void list_recursive(void *buffer,
27unsigned char *type,
28unsigned long size,
29struct path_prefix *prefix)
30{
31struct path_prefix this_prefix;
32this_prefix.prev = prefix;
3334
if (strcmp(type, "tree"))
35die("expected a 'tree' node");
3637
while (size) {
38int namelen = strlen(buffer)+1;
39void *eltbuf;
40char elttype[20];
41unsigned long eltsize;
42unsigned char *sha1 = buffer + namelen;
43char *path = strchr(buffer, ' ') + 1;
44unsigned int mode;
4546
if (size < namelen + 20 || sscanf(buffer, "%o", &mode) != 1)
47die("corrupt 'tree' file");
48buffer = sha1 + 20;
49size -= namelen + 20;
5051
/* XXX: We do some ugly mode heuristics here.
52* It seems not worth it to read each file just to get this
53* and the file size. -- pasky@ucw.cz
54* ... that is, when we are not recursive -- junkio@cox.net
55*/
56eltbuf = (recursive ? read_sha1_file(sha1, elttype, &eltsize) :
57NULL);
58if (! eltbuf) {
59if (recursive)
60error("cannot read %s", sha1_to_hex(sha1));
61type = S_ISDIR(mode) ? "tree" : "blob";
62}
63else
64type = elttype;
6566
printf("%03o\t%s\t%s\t", mode, type, sha1_to_hex(sha1));
67print_path_prefix(prefix);
68fputs(path, stdout);
69putchar(line_termination);
7071
if (eltbuf && !strcmp(type, "tree")) {
72this_prefix.name = path;
73list_recursive(eltbuf, elttype, eltsize, &this_prefix);
74}
75free(eltbuf);
76}
77}
7879
static int list(unsigned char *sha1)
80{
81void *buffer;
82unsigned long size;
83char type[20];
8485
buffer = read_sha1_file(sha1, type, &size);
86if (!buffer)
87die("unable to read sha1 file");
88list_recursive(buffer, type, size, NULL);
89return 0;
90}
9192
static void _usage(void)
93{
94usage("ls-tree [-r] [-z] <key>");
95}
9697
int main(int argc, char **argv)
98{
99unsigned char sha1[20];
100101
while (1 < argc && argv[1][0] == '-') {
102switch (argv[1][1]) {
103case 'z':
104line_termination = 0;
105break;
106case 'r':
107recursive = 1;
108break;
109default:
110_usage();
111}
112argc--; argv++;
113}
114115
if (argc != 2)
116_usage();
117if (get_sha1_hex(argv[1], sha1) < 0)
118_usage();
119sha1_file_directory = getenv(DB_ENVIRONMENT);
120if (!sha1_file_directory)
121sha1_file_directory = DEFAULT_DB_ENVIRONMENT;
122if (list(sha1) < 0)
123die("list failed");
124return 0;
125}