ls-tree: further tweaks of the rewrite
[git/git.git] / ls-tree.c
CommitLineData
7912c070
PB
1/*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 */
6#include "cache.h"
6af1f019
JH
7#include "blob.h"
8#include "tree.h"
22ddf719 9#include "quote.h"
7912c070 10
e99d59ff 11static int line_termination = '\n';
6af1f019
JH
12#define LS_RECURSIVE 1
13#define LS_TREE_ONLY 2
e2466376
LT
14static int ls_options = 0;
15const char **pathspec;
aa1c48df 16
3c5e8468
LT
17static const char ls_tree_usage[] =
18 "git-ls-tree [-d] [-r] [-z] <tree-ish> [path...]";
aa1c48df 19
3c5e8468 20static int show_tree(unsigned char *sha1, const char *base, int baselen, const char *pathname, unsigned mode, int stage)
6af1f019 21{
3c5e8468 22 const char *type = "blob";
ab1630a3 23
3c5e8468 24 if (S_ISDIR(mode)) {
e2466376 25 const char **s;
3c5e8468 26 if (ls_options & LS_RECURSIVE)
b45c569b 27 return READ_TREE_RECURSIVE;
e2466376
LT
28 s = pathspec;
29 if (s) {
30 for (;;) {
31 const char *spec = *s++;
32 int len, speclen;
33
34 if (!spec)
35 break;
36 if (strncmp(base, spec, baselen))
37 continue;
38 len = strlen(pathname);
39 spec += baselen;
40 speclen = strlen(spec);
41 if (speclen <= len)
42 continue;
43 if (memcmp(pathname, spec, len))
44 continue;
45 return READ_TREE_RECURSIVE;
46 }
47 }
b45c569b 48 type = "tree";
6af1f019 49 }
ab1630a3 50
3c5e8468 51 printf("%06o %s %s\t%.*s%s%c", mode, type, sha1_to_hex(sha1), baselen, base, pathname, line_termination);
b45c569b 52 return 0;
6af1f019 53}
0f2303f7 54
3c5e8468 55int main(int argc, const char **argv)
6af1f019 56{
e2466376 57 const char *prefix;
7912c070 58 unsigned char sha1[20];
3c5e8468
LT
59 char *buf;
60 unsigned long size;
7912c070 61
3c5e8468 62 prefix = setup_git_directory();
aa1c48df
JH
63 while (1 < argc && argv[1][0] == '-') {
64 switch (argv[1][1]) {
65 case 'z':
66 line_termination = 0;
67 break;
68 case 'r':
6af1f019
JH
69 ls_options |= LS_RECURSIVE;
70 break;
71 case 'd':
72 ls_options |= LS_TREE_ONLY;
aa1c48df
JH
73 break;
74 default:
0f2303f7 75 usage(ls_tree_usage);
aa1c48df
JH
76 }
77 argc--; argv++;
78 }
79
6d3a5077 80 if (argc < 2)
0f2303f7 81 usage(ls_tree_usage);
3c249c95 82 if (get_sha1(argv[1], sha1) < 0)
0f2303f7 83 usage(ls_tree_usage);
6af1f019 84
e2466376 85 pathspec = get_pathspec(prefix, argv + 2);
3c5e8468
LT
86 buf = read_object_with_reference(sha1, "tree", &size, NULL);
87 if (!buf)
88 die("not a tree object");
e2466376 89 read_tree_recursive(buf, size, "", 0, 0, pathspec, show_tree);
3c5e8468 90
7912c070
PB
91 return 0;
92}