637fc4ad9fe407eaea244ae94b9a5489235f0952
[git/git.git] / builtin / for-each-ref.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "refs.h"
4 #include "object.h"
5 #include "parse-options.h"
6 #include "ref-filter.h"
7
8 static char const * const for_each_ref_usage[] = {
9 N_("git for-each-ref [<options>] [<pattern>]"),
10 NULL
11 };
12
13 int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
14 {
15 int i;
16 const char *format = "%(objectname) %(objecttype)\t%(refname)";
17 struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
18 int maxcount = 0, quote_style = 0;
19 struct ref_filter_cbdata ref_cbdata;
20
21 struct option opts[] = {
22 OPT_BIT('s', "shell", &quote_style,
23 N_("quote placeholders suitably for shells"), QUOTE_SHELL),
24 OPT_BIT('p', "perl", &quote_style,
25 N_("quote placeholders suitably for perl"), QUOTE_PERL),
26 OPT_BIT(0 , "python", &quote_style,
27 N_("quote placeholders suitably for python"), QUOTE_PYTHON),
28 OPT_BIT(0 , "tcl", &quote_style,
29 N_("quote placeholders suitably for Tcl"), QUOTE_TCL),
30
31 OPT_GROUP(""),
32 OPT_INTEGER( 0 , "count", &maxcount, N_("show only <n> matched refs")),
33 OPT_STRING( 0 , "format", &format, N_("format"), N_("format to use for the output")),
34 OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"),
35 N_("field name to sort on"), &parse_opt_ref_sorting),
36 OPT_END(),
37 };
38
39 parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
40 if (maxcount < 0) {
41 error("invalid --count argument: `%d'", maxcount);
42 usage_with_options(for_each_ref_usage, opts);
43 }
44 if (HAS_MULTI_BITS(quote_style)) {
45 error("more than one quoting style?");
46 usage_with_options(for_each_ref_usage, opts);
47 }
48 if (verify_ref_format(format))
49 usage_with_options(for_each_ref_usage, opts);
50
51 if (!sorting)
52 sorting = ref_default_sorting();
53
54 /* for warn_ambiguous_refs */
55 git_config(git_default_config, NULL);
56
57 memset(&ref_cbdata, 0, sizeof(ref_cbdata));
58 ref_cbdata.filter.name_patterns = argv;
59 for_each_rawref(ref_filter_handler, &ref_cbdata);
60
61 ref_array_sort(sorting, &ref_cbdata.array);
62
63 if (!maxcount || ref_cbdata.array.nr < maxcount)
64 maxcount = ref_cbdata.array.nr;
65 for (i = 0; i < maxcount; i++)
66 show_ref_array_item(ref_cbdata.array.items[i], format, quote_style);
67 ref_array_clear(&ref_cbdata.array);
68 return 0;
69 }