ls-tree: major rewrite to do pathspec
[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
14static int ls_options = 0;
aa1c48df 15
3c5e8468
LT
16static const char ls_tree_usage[] =
17 "git-ls-tree [-d] [-r] [-z] <tree-ish> [path...]";
aa1c48df 18
3c5e8468 19static int show_tree(unsigned char *sha1, const char *base, int baselen, const char *pathname, unsigned mode, int stage)
6af1f019 20{
3c5e8468
LT
21 const char *type = "blob";
22 int retval = 0;
ab1630a3 23
3c5e8468
LT
24 if (S_ISDIR(mode)) {
25 type = "tree";
26 if (ls_options & LS_RECURSIVE)
27 retval = READ_TREE_RECURSIVE;
6af1f019 28 }
ab1630a3 29
3c5e8468
LT
30 printf("%06o %s %s\t%.*s%s%c", mode, type, sha1_to_hex(sha1), baselen, base, pathname, line_termination);
31 return retval;
6af1f019 32}
0f2303f7 33
3c5e8468 34int main(int argc, const char **argv)
6af1f019 35{
3c5e8468 36 const char **path, *prefix;
7912c070 37 unsigned char sha1[20];
3c5e8468
LT
38 char *buf;
39 unsigned long size;
7912c070 40
3c5e8468 41 prefix = setup_git_directory();
aa1c48df
JH
42 while (1 < argc && argv[1][0] == '-') {
43 switch (argv[1][1]) {
44 case 'z':
45 line_termination = 0;
46 break;
47 case 'r':
6af1f019
JH
48 ls_options |= LS_RECURSIVE;
49 break;
50 case 'd':
51 ls_options |= LS_TREE_ONLY;
aa1c48df
JH
52 break;
53 default:
0f2303f7 54 usage(ls_tree_usage);
aa1c48df
JH
55 }
56 argc--; argv++;
57 }
58
6d3a5077 59 if (argc < 2)
0f2303f7 60 usage(ls_tree_usage);
3c249c95 61 if (get_sha1(argv[1], sha1) < 0)
0f2303f7 62 usage(ls_tree_usage);
6af1f019 63
3c5e8468
LT
64 path = get_pathspec(prefix, argv + 2);
65 buf = read_object_with_reference(sha1, "tree", &size, NULL);
66 if (!buf)
67 die("not a tree object");
68 read_tree_recursive(buf, size, "", 0, 0, path, show_tree);
69
7912c070
PB
70 return 0;
71}