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