for-each-ref.c 2.4 KB
Newer Older
1
#include "builtin.h"
2 3 4
#include "cache.h"
#include "refs.h"
#include "object.h"
5
#include "parse-options.h"
K
Karthik Nayak 已提交
6
#include "ref-filter.h"
7

8
static 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 12 13 14
	NULL
};

int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
15
{
16
	int i;
17
	const char *format = "%(objectname) %(objecttype)\t%(refname)";
18
	struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
19
	int maxcount = 0, quote_style = 0;
20 21
	struct ref_array array;
	struct ref_filter filter;
22

23
	struct option opts[] = {
24
		OPT_BIT('s', "shell", &quote_style,
25
			N_("quote placeholders suitably for shells"), QUOTE_SHELL),
26
		OPT_BIT('p', "perl",  &quote_style,
27
			N_("quote placeholders suitably for perl"), QUOTE_PERL),
28
		OPT_BIT(0 , "python", &quote_style,
29
			N_("quote placeholders suitably for python"), QUOTE_PYTHON),
30
		OPT_BIT(0 , "tcl",  &quote_style,
31
			N_("quote placeholders suitably for Tcl"), QUOTE_TCL),
32 33

		OPT_GROUP(""),
34 35
		OPT_INTEGER( 0 , "count", &maxcount, N_("show only <n> matched refs")),
		OPT_STRING(  0 , "format", &format, N_("format"), N_("format to use for the output")),
36
		OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"),
37
			    N_("field name to sort on"), &parse_opt_ref_sorting),
38 39 40
		OPT_CALLBACK(0, "points-at", &filter.points_at,
			     N_("object"), N_("print only refs which points at the given object"),
			     parse_opt_object_name),
41 42 43
		OPT_END(),
	};

44 45 46
	memset(&array, 0, sizeof(array));
	memset(&filter, 0, sizeof(filter));

47
	parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
48 49 50
	if (maxcount < 0) {
		error("invalid --count argument: `%d'", maxcount);
		usage_with_options(for_each_ref_usage, opts);
51
	}
52
	if (HAS_MULTI_BITS(quote_style)) {
53
		error("more than one quoting style?");
54 55
		usage_with_options(for_each_ref_usage, opts);
	}
56
	if (verify_ref_format(format))
57
		usage_with_options(for_each_ref_usage, opts);
58

59 60
	if (!sorting)
		sorting = ref_default_sorting();
61

62 63 64
	/* for warn_ambiguous_refs */
	git_config(git_default_config, NULL);

65 66 67
	filter.name_patterns = argv;
	filter_refs(&array, &filter, FILTER_REFS_ALL | FILTER_REFS_INCLUDE_BROKEN);
	ref_array_sort(sorting, &array);
68

69 70
	if (!maxcount || array.nr < maxcount)
		maxcount = array.nr;
71
	for (i = 0; i < maxcount; i++)
72 73
		show_ref_array_item(array.items[i], format, quote_style);
	ref_array_clear(&array);
74 75
	return 0;
}