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
8static char const * const for_each_ref_usage[] = {
9 N_("git for-each-ref [<options>] [<pattern>]"),
10 N_("git for-each-ref [--points-at <object>]"),
11 N_("git for-each-ref [(--merged | --no-merged) [<object>]]"),
12 NULL
13};
14
15int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
16{
17 int i;
18 const char *format = "%(objectname) %(objecttype)\t%(refname)";
19 struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
20 int maxcount = 0, quote_style = 0;
21 struct ref_array array;
22 struct ref_filter filter;
23
24 struct option opts[] = {
25 OPT_BIT('s', "shell", "e_style,
26 N_("quote placeholders suitably for shells"), QUOTE_SHELL),
27 OPT_BIT('p', "perl", "e_style,
28 N_("quote placeholders suitably for perl"), QUOTE_PERL),
29 OPT_BIT(0 , "python", "e_style,
30 N_("quote placeholders suitably for python"), QUOTE_PYTHON),
31 OPT_BIT(0 , "tcl", "e_style,
32 N_("quote placeholders suitably for Tcl"), QUOTE_TCL),
33
34 OPT_GROUP(""),
35 OPT_INTEGER( 0 , "count", &maxcount, N_("show only <n> matched refs")),
36 OPT_STRING( 0 , "format", &format, N_("format"), N_("format to use for the output")),
37 OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"),
38 N_("field name to sort on"), &parse_opt_ref_sorting),
39 OPT_CALLBACK(0, "points-at", &filter.points_at,
40 N_("object"), N_("print only refs which points at the given object"),
41 parse_opt_object_name),
42 OPT_MERGED(&filter, N_("print only refs that are merged")),
43 OPT_NO_MERGED(&filter, N_("print only refs that are not merged")),
44 OPT_END(),
45 };
46
47 memset(&array, 0, sizeof(array));
48 memset(&filter, 0, sizeof(filter));
49
50 parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
51 if (maxcount < 0) {
52 error("invalid --count argument: `%d'", maxcount);
53 usage_with_options(for_each_ref_usage, opts);
54 }
55 if (HAS_MULTI_BITS(quote_style)) {
56 error("more than one quoting style?");
57 usage_with_options(for_each_ref_usage, opts);
58 }
59 if (verify_ref_format(format))
60 usage_with_options(for_each_ref_usage, opts);
61
62 if (!sorting)
63 sorting = ref_default_sorting();
64
65 /* for warn_ambiguous_refs */
66 git_config(git_default_config, NULL);
67
68 filter.name_patterns = argv;
69 filter_refs(&array, &filter, FILTER_REFS_ALL | FILTER_REFS_INCLUDE_BROKEN);
70 ref_array_sort(sorting, &array);
71
72 if (!maxcount || array.nr < maxcount)
73 maxcount = array.nr;
74 for (i = 0; i < maxcount; i++)
75 show_ref_array_item(array.items[i], format, quote_style);
76 ref_array_clear(&array);
77 return 0;
78}