3 #include "parse-options.h"
11 #include "ref-filter.h"
14 #include "git-compat-util.h"
17 #include "wt-status.h"
18 #include "commit-slab.h"
20 static struct ref_msg {
24 const char *ahead_behind;
26 /* Untranslated plumbing messages: */
33 void setup_ref_filter_porcelain_msg(void)
35 msgs.gone = _("gone");
36 msgs.ahead = _("ahead %d");
37 msgs.behind = _("behind %d");
38 msgs.ahead_behind = _("ahead %d, behind %d");
41 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
42 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
50 cmp_status cmp_status;
52 unsigned int then_atom_seen : 1,
54 condition_satisfied : 1;
58 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
63 * An atom is a valid field atom listed below, possibly prefixed with
64 * a "*" to denote deref_tag().
66 * We parse given format string and sort specifiers, and make a list
67 * of properties that we need to extract out of objects. ref_array_item
68 * structure will hold an array of values extracted that can be
69 * indexed with the "atom number", which is an index into this
72 static struct used_atom {
76 char color[COLOR_MAXLEN];
80 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
82 struct refname_atom refname;
83 unsigned int nobracket : 1, push : 1, push_remote : 1;
86 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
87 struct process_trailer_options trailer_opts;
91 cmp_status cmp_status;
95 enum { O_FULL, O_LENGTH, O_SHORT } option;
98 struct refname_atom refname;
102 static int used_atom_cnt, need_tagged, need_symref;
103 struct expand_data cat_file_info;
105 static void color_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *color_value)
108 die(_("expected format: %%(color:<color>)"));
109 if (color_parse(color_value, atom->u.color) < 0)
110 die(_("unrecognized color: %%(color:%s)"), color_value);
112 * We check this after we've parsed the color, which lets us complain
113 * about syntactically bogus color names even if they won't be used.
115 if (!want_color(format->use_color))
116 color_parse("", atom->u.color);
119 static void refname_atom_parser_internal(struct refname_atom *atom,
120 const char *arg, const char *name)
123 atom->option = R_NORMAL;
124 else if (!strcmp(arg, "short"))
125 atom->option = R_SHORT;
126 else if (skip_prefix(arg, "lstrip=", &arg) ||
127 skip_prefix(arg, "strip=", &arg)) {
128 atom->option = R_LSTRIP;
129 if (strtol_i(arg, 10, &atom->lstrip))
130 die(_("Integer value expected refname:lstrip=%s"), arg);
131 } else if (skip_prefix(arg, "rstrip=", &arg)) {
132 atom->option = R_RSTRIP;
133 if (strtol_i(arg, 10, &atom->rstrip))
134 die(_("Integer value expected refname:rstrip=%s"), arg);
136 die(_("unrecognized %%(%s) argument: %s"), name, arg);
139 static void remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
141 struct string_list params = STRING_LIST_INIT_DUP;
144 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
145 atom->u.remote_ref.push = 1;
148 atom->u.remote_ref.option = RR_REF;
149 refname_atom_parser_internal(&atom->u.remote_ref.refname,
154 atom->u.remote_ref.nobracket = 0;
155 string_list_split(¶ms, arg, ',', -1);
157 for (i = 0; i < params.nr; i++) {
158 const char *s = params.items[i].string;
160 if (!strcmp(s, "track"))
161 atom->u.remote_ref.option = RR_TRACK;
162 else if (!strcmp(s, "trackshort"))
163 atom->u.remote_ref.option = RR_TRACKSHORT;
164 else if (!strcmp(s, "nobracket"))
165 atom->u.remote_ref.nobracket = 1;
166 else if (!strcmp(s, "remotename")) {
167 atom->u.remote_ref.option = RR_REMOTE_NAME;
168 atom->u.remote_ref.push_remote = 1;
169 } else if (!strcmp(s, "remoteref")) {
170 atom->u.remote_ref.option = RR_REMOTE_REF;
171 atom->u.remote_ref.push_remote = 1;
173 atom->u.remote_ref.option = RR_REF;
174 refname_atom_parser_internal(&atom->u.remote_ref.refname,
179 string_list_clear(¶ms, 0);
182 static void body_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
185 die(_("%%(body) does not take arguments"));
186 atom->u.contents.option = C_BODY_DEP;
189 static void subject_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
192 die(_("%%(subject) does not take arguments"));
193 atom->u.contents.option = C_SUB;
196 static void trailers_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
198 struct string_list params = STRING_LIST_INIT_DUP;
202 string_list_split(¶ms, arg, ',', -1);
203 for (i = 0; i < params.nr; i++) {
204 const char *s = params.items[i].string;
205 if (!strcmp(s, "unfold"))
206 atom->u.contents.trailer_opts.unfold = 1;
207 else if (!strcmp(s, "only"))
208 atom->u.contents.trailer_opts.only_trailers = 1;
210 die(_("unknown %%(trailers) argument: %s"), s);
213 atom->u.contents.option = C_TRAILERS;
214 string_list_clear(¶ms, 0);
217 static void contents_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
220 atom->u.contents.option = C_BARE;
221 else if (!strcmp(arg, "body"))
222 atom->u.contents.option = C_BODY;
223 else if (!strcmp(arg, "signature"))
224 atom->u.contents.option = C_SIG;
225 else if (!strcmp(arg, "subject"))
226 atom->u.contents.option = C_SUB;
227 else if (skip_prefix(arg, "trailers", &arg)) {
228 skip_prefix(arg, ":", &arg);
229 trailers_atom_parser(format, atom, *arg ? arg : NULL);
230 } else if (skip_prefix(arg, "lines=", &arg)) {
231 atom->u.contents.option = C_LINES;
232 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
233 die(_("positive value expected contents:lines=%s"), arg);
235 die(_("unrecognized %%(contents) argument: %s"), arg);
238 static void objectname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
241 atom->u.objectname.option = O_FULL;
242 else if (!strcmp(arg, "short"))
243 atom->u.objectname.option = O_SHORT;
244 else if (skip_prefix(arg, "short=", &arg)) {
245 atom->u.objectname.option = O_LENGTH;
246 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
247 atom->u.objectname.length == 0)
248 die(_("positive value expected objectname:short=%s"), arg);
249 if (atom->u.objectname.length < MINIMUM_ABBREV)
250 atom->u.objectname.length = MINIMUM_ABBREV;
252 die(_("unrecognized %%(objectname) argument: %s"), arg);
255 static void objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
258 cat_file_info.info.sizep = &cat_file_info.size;
259 else if (!strcmp(arg, "disk"))
260 cat_file_info.info.disk_sizep = &cat_file_info.disk_size;
262 die(_("urecognized %%(objectsize) argument: %s"), arg);
265 static void objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
268 cat_file_info.info.typep = &cat_file_info.type;
270 die(_("urecognized %%(objecttype) argument: %s"), arg);
273 static void deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
276 cat_file_info.info.delta_base_sha1 = cat_file_info.delta_base_oid.hash;
278 die(_("urecognized %%(deltabase) argument: %s"), arg);
281 static void refname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
283 refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
286 static align_type parse_align_position(const char *s)
288 if (!strcmp(s, "right"))
290 else if (!strcmp(s, "middle"))
292 else if (!strcmp(s, "left"))
297 static void align_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
299 struct align *align = &atom->u.align;
300 struct string_list params = STRING_LIST_INIT_DUP;
302 unsigned int width = ~0U;
305 die(_("expected format: %%(align:<width>,<position>)"));
307 align->position = ALIGN_LEFT;
309 string_list_split(¶ms, arg, ',', -1);
310 for (i = 0; i < params.nr; i++) {
311 const char *s = params.items[i].string;
314 if (skip_prefix(s, "position=", &s)) {
315 position = parse_align_position(s);
317 die(_("unrecognized position:%s"), s);
318 align->position = position;
319 } else if (skip_prefix(s, "width=", &s)) {
320 if (strtoul_ui(s, 10, &width))
321 die(_("unrecognized width:%s"), s);
322 } else if (!strtoul_ui(s, 10, &width))
324 else if ((position = parse_align_position(s)) >= 0)
325 align->position = position;
327 die(_("unrecognized %%(align) argument: %s"), s);
331 die(_("positive width expected with the %%(align) atom"));
332 align->width = width;
333 string_list_clear(¶ms, 0);
336 static void if_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
339 atom->u.if_then_else.cmp_status = COMPARE_NONE;
341 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
342 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
343 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
344 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
346 die(_("unrecognized %%(if) argument: %s"), arg);
350 static void head_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
352 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
355 static struct valid_atom {
358 void (*parser)(const struct ref_format *format, struct used_atom *atom, const char *arg);
360 { "refname" , FIELD_STR, refname_atom_parser },
361 { "objecttype", FIELD_STR, objecttype_atom_parser },
362 { "objectsize", FIELD_ULONG, objectsize_atom_parser },
363 { "objectname", FIELD_STR, objectname_atom_parser },
366 { "numparent", FIELD_ULONG },
373 { "authordate", FIELD_TIME },
376 { "committeremail" },
377 { "committerdate", FIELD_TIME },
381 { "taggerdate", FIELD_TIME },
383 { "creatordate", FIELD_TIME },
384 { "subject", FIELD_STR, subject_atom_parser },
385 { "body", FIELD_STR, body_atom_parser },
386 { "trailers", FIELD_STR, trailers_atom_parser },
387 { "contents", FIELD_STR, contents_atom_parser },
388 { "upstream", FIELD_STR, remote_ref_atom_parser },
389 { "push", FIELD_STR, remote_ref_atom_parser },
390 { "symref", FIELD_STR, refname_atom_parser },
392 { "HEAD", FIELD_STR, head_atom_parser },
393 { "color", FIELD_STR, color_atom_parser },
394 { "align", FIELD_STR, align_atom_parser },
396 { "if", FIELD_STR, if_atom_parser },
400 { "deltabase", FIELD_STR, deltabase_atom_parser },
403 #define REF_FORMATTING_STATE_INIT { 0, NULL }
405 struct ref_formatting_stack {
406 struct ref_formatting_stack *prev;
407 struct strbuf output;
408 void (*at_end)(struct ref_formatting_stack **stack);
412 struct ref_formatting_state {
414 struct ref_formatting_stack *stack;
419 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
420 uintmax_t value; /* used for sorting when not FIELD_STR */
421 struct used_atom *atom;
425 * Used to parse format string and sort specifiers
427 static int parse_ref_filter_atom(const struct ref_format *format,
428 const char *atom, const char *ep)
435 if (*sp == '*' && sp < ep)
438 die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
440 /* Do we have the atom already used elsewhere? */
441 for (i = 0; i < used_atom_cnt; i++) {
442 int len = strlen(used_atom[i].name);
443 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
448 * If the atom name has a colon, strip it and everything after
449 * it off - it specifies the format for this entry, and
450 * shouldn't be used for checking against the valid_atom
453 arg = memchr(sp, ':', ep - sp);
454 atom_len = (arg ? arg : ep) - sp;
456 /* Is the atom a valid one? */
457 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
458 int len = strlen(valid_atom[i].name);
459 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
463 if (ARRAY_SIZE(valid_atom) <= i)
464 die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
466 /* Add it in, including the deref prefix */
469 REALLOC_ARRAY(used_atom, used_atom_cnt);
470 used_atom[at].name = xmemdupz(atom, ep - atom);
471 used_atom[at].type = valid_atom[i].cmp_type;
473 arg = used_atom[at].name + (arg - atom) + 1;
476 * Treat empty sub-arguments list as NULL (i.e.,
477 * "%(atom:)" is equivalent to "%(atom)").
482 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
483 if (valid_atom[i].parser)
484 valid_atom[i].parser(format, &used_atom[at], arg);
487 if (!strcmp(valid_atom[i].name, "symref"))
492 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
494 switch (quote_style) {
496 strbuf_addstr(s, str);
499 sq_quote_buf(s, str);
502 perl_quote_buf(s, str);
505 python_quote_buf(s, str);
508 tcl_quote_buf(s, str);
513 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
516 * Quote formatting is only done when the stack has a single
517 * element. Otherwise quote formatting is done on the
518 * element's entire output strbuf when the %(end) atom is
521 if (!state->stack->prev)
522 quote_formatting(&state->stack->output, v->s, state->quote_style);
524 strbuf_addstr(&state->stack->output, v->s);
527 static void push_stack_element(struct ref_formatting_stack **stack)
529 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
531 strbuf_init(&s->output, 0);
536 static void pop_stack_element(struct ref_formatting_stack **stack)
538 struct ref_formatting_stack *current = *stack;
539 struct ref_formatting_stack *prev = current->prev;
542 strbuf_addbuf(&prev->output, ¤t->output);
543 strbuf_release(¤t->output);
548 static void end_align_handler(struct ref_formatting_stack **stack)
550 struct ref_formatting_stack *cur = *stack;
551 struct align *align = (struct align *)cur->at_end_data;
552 struct strbuf s = STRBUF_INIT;
554 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
555 strbuf_swap(&cur->output, &s);
559 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
561 struct ref_formatting_stack *new_stack;
563 push_stack_element(&state->stack);
564 new_stack = state->stack;
565 new_stack->at_end = end_align_handler;
566 new_stack->at_end_data = &atomv->atom->u.align;
569 static void if_then_else_handler(struct ref_formatting_stack **stack)
571 struct ref_formatting_stack *cur = *stack;
572 struct ref_formatting_stack *prev = cur->prev;
573 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
575 if (!if_then_else->then_atom_seen)
576 die(_("format: %%(if) atom used without a %%(then) atom"));
578 if (if_then_else->else_atom_seen) {
580 * There is an %(else) atom: we need to drop one state from the
581 * stack, either the %(else) branch if the condition is satisfied, or
582 * the %(then) branch if it isn't.
584 if (if_then_else->condition_satisfied) {
585 strbuf_reset(&cur->output);
586 pop_stack_element(&cur);
588 strbuf_swap(&cur->output, &prev->output);
589 strbuf_reset(&cur->output);
590 pop_stack_element(&cur);
592 } else if (!if_then_else->condition_satisfied) {
594 * No %(else) atom: just drop the %(then) branch if the
595 * condition is not satisfied.
597 strbuf_reset(&cur->output);
604 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
606 struct ref_formatting_stack *new_stack;
607 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
609 if_then_else->str = atomv->atom->u.if_then_else.str;
610 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
612 push_stack_element(&state->stack);
613 new_stack = state->stack;
614 new_stack->at_end = if_then_else_handler;
615 new_stack->at_end_data = if_then_else;
618 static int is_empty(const char *s)
628 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
630 struct ref_formatting_stack *cur = state->stack;
631 struct if_then_else *if_then_else = NULL;
633 if (cur->at_end == if_then_else_handler)
634 if_then_else = (struct if_then_else *)cur->at_end_data;
636 die(_("format: %%(then) atom used without an %%(if) atom"));
637 if (if_then_else->then_atom_seen)
638 die(_("format: %%(then) atom used more than once"));
639 if (if_then_else->else_atom_seen)
640 die(_("format: %%(then) atom used after %%(else)"));
641 if_then_else->then_atom_seen = 1;
643 * If the 'equals' or 'notequals' attribute is used then
644 * perform the required comparison. If not, only non-empty
645 * strings satisfy the 'if' condition.
647 if (if_then_else->cmp_status == COMPARE_EQUAL) {
648 if (!strcmp(if_then_else->str, cur->output.buf))
649 if_then_else->condition_satisfied = 1;
650 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
651 if (strcmp(if_then_else->str, cur->output.buf))
652 if_then_else->condition_satisfied = 1;
653 } else if (cur->output.len && !is_empty(cur->output.buf))
654 if_then_else->condition_satisfied = 1;
655 strbuf_reset(&cur->output);
658 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
660 struct ref_formatting_stack *prev = state->stack;
661 struct if_then_else *if_then_else = NULL;
663 if (prev->at_end == if_then_else_handler)
664 if_then_else = (struct if_then_else *)prev->at_end_data;
666 die(_("format: %%(else) atom used without an %%(if) atom"));
667 if (!if_then_else->then_atom_seen)
668 die(_("format: %%(else) atom used without a %%(then) atom"));
669 if (if_then_else->else_atom_seen)
670 die(_("format: %%(else) atom used more than once"));
671 if_then_else->else_atom_seen = 1;
672 push_stack_element(&state->stack);
673 state->stack->at_end_data = prev->at_end_data;
674 state->stack->at_end = prev->at_end;
677 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
679 struct ref_formatting_stack *current = state->stack;
680 struct strbuf s = STRBUF_INIT;
682 if (!current->at_end)
683 die(_("format: %%(end) atom used without corresponding atom"));
684 current->at_end(&state->stack);
686 /* Stack may have been popped within at_end(), hence reset the current pointer */
687 current = state->stack;
690 * Perform quote formatting when the stack element is that of
691 * a supporting atom. If nested then perform quote formatting
692 * only on the topmost supporting atom.
694 if (!current->prev->prev) {
695 quote_formatting(&s, current->output.buf, state->quote_style);
696 strbuf_swap(¤t->output, &s);
699 pop_stack_element(&state->stack);
703 * In a format string, find the next occurrence of %(atom).
705 static const char *find_next(const char *cp)
710 * %( is the start of an atom;
711 * %% is a quoted per-cent.
715 else if (cp[1] == '%')
716 cp++; /* skip over two % */
717 /* otherwise this is a singleton, literal % */
724 /* Search for atom in given format. */
725 int is_atom_used(const struct ref_format *format, const char *atom)
728 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
729 const char *ep = strchr(sp, ')');
730 int atom_len = ep - sp - 2;
732 if (atom_len == strlen(atom) && !memcmp(sp, atom, atom_len))
740 * Make sure the format string is well formed, and parse out
743 int verify_ref_format(struct ref_format *format)
747 cat_file_info.is_cat_file = format->is_cat_file;
748 format->need_color_reset_at_eol = 0;
749 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
750 const char *color, *ep = strchr(sp, ')');
754 return error(_("malformed format string %s"), sp);
755 /* sp points at "%(" and ep points at the closing ")" */
757 at = parse_ref_filter_atom(format, sp + 2, ep);
758 if (skip_prefix(used_atom[at].name, "color:", &color))
759 format->need_color_reset_at_eol = !!strcmp(color, "reset");
763 if (format->need_color_reset_at_eol && !want_color(format->use_color))
764 format->need_color_reset_at_eol = 0;
765 if (cat_file_info.is_cat_file && format->all_objects) {
766 struct object_info empty = OBJECT_INFO_INIT;
767 if (!memcmp(&cat_file_info.info, &empty, sizeof(empty)))
768 cat_file_info.skip_object_info = 1;
774 * Given an object name, read the object data and size, and return a
775 * "struct object". If the object data we are returning is also borrowed
776 * by the "struct object" representation, set *eaten as well---it is a
777 * signal from parse_object_buffer to us not to free the buffer.
779 static void *get_obj(const struct object_id *oid, struct object **obj, unsigned long *sz, int *eaten)
781 enum object_type type;
782 void *buf = read_sha1_file(oid->hash, &type, sz);
785 *obj = parse_object_buffer(oid, type, *sz, buf, eaten);
791 static int grab_objectname(const char *name, const unsigned char *sha1,
792 struct atom_value *v, struct used_atom *atom)
794 if (starts_with(name, "objectname")) {
795 if (atom->u.objectname.option == O_SHORT) {
796 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
798 } else if (atom->u.objectname.option == O_FULL) {
799 v->s = xstrdup(sha1_to_hex(sha1));
801 } else if (atom->u.objectname.option == O_LENGTH) {
802 v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
805 die("BUG: unknown %%(objectname) option");
810 /* See grab_values */
811 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
815 for (i = 0; i < used_atom_cnt; i++) {
816 const char *name = used_atom[i].name;
817 struct atom_value *v = &val[i];
818 if (!!deref != (*name == '*'))
822 if (!strcmp(name, "objecttype"))
823 v->s = type_name(obj->type);
824 else if (!strcmp(name, "objectsize")) {
826 v->s = xstrfmt("%lu", sz);
827 } else if (!strcmp(name, "objectsize:disk")) {
828 if (cat_file_info.is_cat_file) {
829 v->value = cat_file_info.disk_size;
830 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)v->value);
833 grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
837 /* See grab_values */
838 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
841 struct tag *tag = (struct tag *) obj;
843 for (i = 0; i < used_atom_cnt; i++) {
844 const char *name = used_atom[i].name;
845 struct atom_value *v = &val[i];
846 if (!!deref != (*name == '*'))
850 if (!strcmp(name, "tag"))
852 else if (!strcmp(name, "type") && tag->tagged)
853 v->s = type_name(tag->tagged->type);
854 else if (!strcmp(name, "object") && tag->tagged)
855 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
859 /* See grab_values */
860 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
863 struct commit *commit = (struct commit *) obj;
865 for (i = 0; i < used_atom_cnt; i++) {
866 const char *name = used_atom[i].name;
867 struct atom_value *v = &val[i];
868 if (!!deref != (*name == '*'))
872 if (!strcmp(name, "tree")) {
873 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
875 else if (!strcmp(name, "numparent")) {
876 v->value = commit_list_count(commit->parents);
877 v->s = xstrfmt("%lu", (unsigned long)v->value);
879 else if (!strcmp(name, "parent")) {
880 struct commit_list *parents;
881 struct strbuf s = STRBUF_INIT;
882 for (parents = commit->parents; parents; parents = parents->next) {
883 struct commit *parent = parents->item;
884 if (parents != commit->parents)
885 strbuf_addch(&s, ' ');
886 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
888 v->s = strbuf_detach(&s, NULL);
893 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
897 if (!strncmp(buf, who, wholen) &&
899 return buf + wholen + 1;
900 eol = strchr(buf, '\n');
905 return ""; /* end of header */
911 static const char *copy_line(const char *buf)
913 const char *eol = strchrnul(buf, '\n');
914 return xmemdupz(buf, eol - buf);
917 static const char *copy_name(const char *buf)
920 for (cp = buf; *cp && *cp != '\n'; cp++) {
921 if (!strncmp(cp, " <", 2))
922 return xmemdupz(buf, cp - buf);
927 static const char *copy_email(const char *buf)
929 const char *email = strchr(buf, '<');
933 eoemail = strchr(email, '>');
936 return xmemdupz(email, eoemail + 1 - email);
939 static char *copy_subject(const char *buf, unsigned long len)
941 char *r = xmemdupz(buf, len);
944 for (i = 0; i < len; i++)
951 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
953 const char *eoemail = strstr(buf, "> ");
955 timestamp_t timestamp;
957 struct date_mode date_mode = { DATE_NORMAL };
961 * We got here because atomname ends in "date" or "date<something>";
962 * it's not possible that <something> is not ":<format>" because
963 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
964 * ":" means no format is specified, and use the default.
966 formatp = strchr(atomname, ':');
967 if (formatp != NULL) {
969 parse_date_format(formatp, &date_mode);
974 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
975 if (timestamp == TIME_MAX)
977 tz = strtol(zone, NULL, 10);
978 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
980 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
981 v->value = timestamp;
988 /* See grab_values */
989 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
992 int wholen = strlen(who);
993 const char *wholine = NULL;
995 for (i = 0; i < used_atom_cnt; i++) {
996 const char *name = used_atom[i].name;
997 struct atom_value *v = &val[i];
998 if (!!deref != (*name == '*'))
1002 if (strncmp(who, name, wholen))
1004 if (name[wholen] != 0 &&
1005 strcmp(name + wholen, "name") &&
1006 strcmp(name + wholen, "email") &&
1007 !starts_with(name + wholen, "date"))
1010 wholine = find_wholine(who, wholen, buf, sz);
1012 return; /* no point looking for it */
1013 if (name[wholen] == 0)
1014 v->s = copy_line(wholine);
1015 else if (!strcmp(name + wholen, "name"))
1016 v->s = copy_name(wholine);
1017 else if (!strcmp(name + wholen, "email"))
1018 v->s = copy_email(wholine);
1019 else if (starts_with(name + wholen, "date"))
1020 grab_date(wholine, v, name);
1024 * For a tag or a commit object, if "creator" or "creatordate" is
1025 * requested, do something special.
1027 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1028 return; /* "author" for commit object is not wanted */
1030 wholine = find_wholine(who, wholen, buf, sz);
1033 for (i = 0; i < used_atom_cnt; i++) {
1034 const char *name = used_atom[i].name;
1035 struct atom_value *v = &val[i];
1036 if (!!deref != (*name == '*'))
1041 if (starts_with(name, "creatordate"))
1042 grab_date(wholine, v, name);
1043 else if (!strcmp(name, "creator"))
1044 v->s = copy_line(wholine);
1048 static void find_subpos(const char *buf, unsigned long sz,
1049 const char **sub, unsigned long *sublen,
1050 const char **body, unsigned long *bodylen,
1051 unsigned long *nonsiglen,
1052 const char **sig, unsigned long *siglen)
1055 /* skip past header until we hit empty line */
1056 while (*buf && *buf != '\n') {
1057 eol = strchrnul(buf, '\n');
1062 /* skip any empty lines */
1063 while (*buf == '\n')
1066 /* parse signature first; we might not even have a subject line */
1067 *sig = buf + parse_signature(buf, strlen(buf));
1068 *siglen = strlen(*sig);
1070 /* subject is first non-empty line */
1072 /* subject goes to first empty line */
1073 while (buf < *sig && *buf && *buf != '\n') {
1074 eol = strchrnul(buf, '\n');
1079 *sublen = buf - *sub;
1080 /* drop trailing newline, if present */
1081 if (*sublen && (*sub)[*sublen - 1] == '\n')
1084 /* skip any empty lines */
1085 while (*buf == '\n')
1088 *bodylen = strlen(buf);
1089 *nonsiglen = *sig - buf;
1093 * If 'lines' is greater than 0, append that many lines from the given
1094 * 'buf' of length 'size' to the given strbuf.
1096 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1099 const char *sp, *eol;
1104 for (i = 0; i < lines && sp < buf + size; i++) {
1106 strbuf_addstr(out, "\n ");
1107 eol = memchr(sp, '\n', size - (sp - buf));
1108 len = eol ? eol - sp : size - (sp - buf);
1109 strbuf_add(out, sp, len);
1116 /* See grab_values */
1117 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1120 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1121 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1123 for (i = 0; i < used_atom_cnt; i++) {
1124 struct used_atom *atom = &used_atom[i];
1125 const char *name = atom->name;
1126 struct atom_value *v = &val[i];
1127 if (!!deref != (*name == '*'))
1131 if (strcmp(name, "subject") &&
1132 strcmp(name, "body") &&
1133 !starts_with(name, "trailers") &&
1134 !starts_with(name, "contents"))
1137 find_subpos(buf, sz,
1139 &bodypos, &bodylen, &nonsiglen,
1142 if (atom->u.contents.option == C_SUB)
1143 v->s = copy_subject(subpos, sublen);
1144 else if (atom->u.contents.option == C_BODY_DEP)
1145 v->s = xmemdupz(bodypos, bodylen);
1146 else if (atom->u.contents.option == C_BODY)
1147 v->s = xmemdupz(bodypos, nonsiglen);
1148 else if (atom->u.contents.option == C_SIG)
1149 v->s = xmemdupz(sigpos, siglen);
1150 else if (atom->u.contents.option == C_LINES) {
1151 struct strbuf s = STRBUF_INIT;
1152 const char *contents_end = bodylen + bodypos - siglen;
1154 /* Size is the length of the message after removing the signature */
1155 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1156 v->s = strbuf_detach(&s, NULL);
1157 } else if (atom->u.contents.option == C_TRAILERS) {
1158 struct strbuf s = STRBUF_INIT;
1160 /* Format the trailer info according to the trailer_opts given */
1161 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1163 v->s = strbuf_detach(&s, NULL);
1164 } else if (atom->u.contents.option == C_BARE)
1165 v->s = xstrdup(subpos);
1170 * We want to have empty print-string for field requests
1171 * that do not apply (e.g. "authordate" for a tag object)
1173 static void fill_missing_values(struct atom_value *val)
1176 for (i = 0; i < used_atom_cnt; i++) {
1177 struct atom_value *v = &val[i];
1184 * val is a list of atom_value to hold returned values. Extract
1185 * the values for atoms in used_atom array out of (obj, buf, sz).
1186 * when deref is false, (obj, buf, sz) is the object that is
1187 * pointed at by the ref itself; otherwise it is the object the
1188 * ref (which is a tag) refers to.
1190 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1192 grab_common_values(val, deref, obj, buf, sz);
1193 switch (obj->type) {
1195 grab_tag_values(val, deref, obj, buf, sz);
1196 grab_sub_body_contents(val, deref, obj, buf, sz);
1197 grab_person("tagger", val, deref, obj, buf, sz);
1200 grab_commit_values(val, deref, obj, buf, sz);
1201 grab_sub_body_contents(val, deref, obj, buf, sz);
1202 grab_person("author", val, deref, obj, buf, sz);
1203 grab_person("committer", val, deref, obj, buf, sz);
1206 /* grab_tree_values(val, deref, obj, buf, sz); */
1209 /* grab_blob_values(val, deref, obj, buf, sz); */
1212 die("Eh? Object of type %d?", obj->type);
1216 static inline char *copy_advance(char *dst, const char *src)
1223 static const char *lstrip_ref_components(const char *refname, int len)
1225 long remaining = len;
1226 const char *start = refname;
1230 const char *p = refname;
1232 /* Find total no of '/' separated path-components */
1233 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1236 * The number of components we need to strip is now
1237 * the total minus the components to be left (Plus one
1238 * because we count the number of '/', but the number
1239 * of components is one more than the no of '/').
1241 remaining = i + len + 1;
1244 while (remaining > 0) {
1257 static const char *rstrip_ref_components(const char *refname, int len)
1259 long remaining = len;
1260 char *start = xstrdup(refname);
1264 const char *p = refname;
1266 /* Find total no of '/' separated path-components */
1267 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1270 * The number of components we need to strip is now
1271 * the total minus the components to be left (Plus one
1272 * because we count the number of '/', but the number
1273 * of components is one more than the no of '/').
1275 remaining = i + len + 1;
1278 while (remaining-- > 0) {
1279 char *p = strrchr(start, '/');
1288 static const char *show_ref(struct refname_atom *atom, const char *refname)
1290 if (atom->option == R_SHORT)
1291 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1292 else if (atom->option == R_LSTRIP)
1293 return lstrip_ref_components(refname, atom->lstrip);
1294 else if (atom->option == R_RSTRIP)
1295 return rstrip_ref_components(refname, atom->rstrip);
1300 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1301 struct branch *branch, const char **s)
1303 int num_ours, num_theirs;
1304 if (atom->u.remote_ref.option == RR_REF)
1305 *s = show_ref(&atom->u.remote_ref.refname, refname);
1306 else if (atom->u.remote_ref.option == RR_TRACK) {
1307 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1308 NULL, AHEAD_BEHIND_FULL) < 0) {
1309 *s = xstrdup(msgs.gone);
1310 } else if (!num_ours && !num_theirs)
1313 *s = xstrfmt(msgs.behind, num_theirs);
1314 else if (!num_theirs)
1315 *s = xstrfmt(msgs.ahead, num_ours);
1317 *s = xstrfmt(msgs.ahead_behind,
1318 num_ours, num_theirs);
1319 if (!atom->u.remote_ref.nobracket && *s[0]) {
1320 const char *to_free = *s;
1321 *s = xstrfmt("[%s]", *s);
1322 free((void *)to_free);
1324 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1325 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1326 NULL, AHEAD_BEHIND_FULL) < 0)
1329 if (!num_ours && !num_theirs)
1333 else if (!num_theirs)
1337 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1339 const char *remote = atom->u.remote_ref.push ?
1340 pushremote_for_branch(branch, &explicit) :
1341 remote_for_branch(branch, &explicit);
1343 *s = xstrdup(remote);
1346 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1350 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1353 *s = xstrdup(merge);
1357 die("BUG: unhandled RR_* enum");
1360 char *get_head_description(void)
1362 struct strbuf desc = STRBUF_INIT;
1363 struct wt_status_state state;
1364 memset(&state, 0, sizeof(state));
1365 wt_status_get_state(&state, 1);
1366 if (state.rebase_in_progress ||
1367 state.rebase_interactive_in_progress)
1368 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1370 else if (state.bisect_in_progress)
1371 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1373 else if (state.detached_from) {
1374 if (state.detached_at)
1376 * TRANSLATORS: make sure this matches "HEAD
1377 * detached at " in wt-status.c
1379 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1380 state.detached_from);
1383 * TRANSLATORS: make sure this matches "HEAD
1384 * detached from " in wt-status.c
1386 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1387 state.detached_from);
1390 strbuf_addstr(&desc, _("(no branch)"));
1393 free(state.detached_from);
1394 return strbuf_detach(&desc, NULL);
1397 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1402 return show_ref(&atom->u.refname, ref->symref);
1405 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1407 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1408 return get_head_description();
1409 return show_ref(&atom->u.refname, ref->refname);
1412 static void get_object(struct ref_array_item *ref, const struct object_id *oid,
1413 int deref, struct object **obj)
1417 void *buf = get_obj(oid, obj, &size, &eaten);
1419 die(_("missing object %s for %s"),
1420 oid_to_hex(oid), ref->refname);
1422 die(_("parse_object_buffer failed on %s for %s"),
1423 oid_to_hex(oid), ref->refname);
1425 grab_values(ref->value, deref, *obj, buf, size);
1430 static int check_and_fill_for_cat(struct ref_array_item *ref)
1432 if (!cat_file_info.info.typep)
1433 cat_file_info.info.typep = &cat_file_info.type;
1434 if (!cat_file_info.skip_object_info &&
1435 sha1_object_info_extended(ref->oid.hash, &cat_file_info.info,
1436 OBJECT_INFO_LOOKUP_REPLACE) < 0) {
1437 const char *e = ref->objectname;
1438 printf("%s missing\n", e ? e : oid_to_hex(&ref->oid));
1442 ref->type = cat_file_info.type;
1443 ref->size = cat_file_info.size;
1444 ref->disk_size = cat_file_info.disk_size;
1445 ref->delta_base_oid = &cat_file_info.delta_base_oid;
1450 * Parse the object referred by ref, and grab needed value.
1451 * Return 0 if everything was successful, -1 otherwise.
1453 static int populate_value(struct ref_array_item *ref)
1457 const struct object_id *tagged;
1459 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1461 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1462 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1468 if (cat_file_info.is_cat_file && check_and_fill_for_cat(ref))
1471 /* Fill in specials first */
1472 for (i = 0; i < used_atom_cnt; i++) {
1473 struct used_atom *atom = &used_atom[i];
1474 const char *name = used_atom[i].name;
1475 struct atom_value *v = &ref->value[i];
1477 const char *refname;
1478 struct branch *branch = NULL;
1480 v->handler = append_atom;
1488 if (starts_with(name, "refname"))
1489 refname = get_refname(atom, ref);
1490 else if (starts_with(name, "symref"))
1491 refname = get_symref(atom, ref);
1492 else if (starts_with(name, "upstream")) {
1493 const char *branch_name;
1494 /* only local branches may have an upstream */
1495 if (!skip_prefix(ref->refname, "refs/heads/",
1498 branch = branch_get(branch_name);
1500 refname = branch_get_upstream(branch, NULL);
1502 fill_remote_ref_details(atom, refname, branch, &v->s);
1504 } else if (atom->u.remote_ref.push) {
1505 const char *branch_name;
1506 if (!skip_prefix(ref->refname, "refs/heads/",
1509 branch = branch_get(branch_name);
1511 if (atom->u.remote_ref.push_remote)
1514 refname = branch_get_push(branch, NULL);
1518 fill_remote_ref_details(atom, refname, branch, &v->s);
1520 } else if (starts_with(name, "color:")) {
1521 v->s = atom->u.color;
1523 } else if (!strcmp(name, "flag")) {
1524 char buf[256], *cp = buf;
1525 if (ref->flag & REF_ISSYMREF)
1526 cp = copy_advance(cp, ",symref");
1527 if (ref->flag & REF_ISPACKED)
1528 cp = copy_advance(cp, ",packed");
1533 v->s = xstrdup(buf + 1);
1536 } else if (!deref && grab_objectname(name, ref->oid.hash, v, atom)) {
1538 } else if (!strcmp(name, "HEAD")) {
1539 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1544 } else if (starts_with(name, "rest")) {
1545 v->s = ref->rest ? ref->rest : "";
1547 } else if (starts_with(name, "deltabase")) {
1548 if (ref->delta_base_oid)
1549 v->s = xstrdup(oid_to_hex(ref->delta_base_oid));
1553 } else if (starts_with(name, "align")) {
1554 v->handler = align_atom_handler;
1556 } else if (!strcmp(name, "end")) {
1557 v->handler = end_atom_handler;
1559 } else if (starts_with(name, "if")) {
1562 if (skip_prefix(name, "if:", &s))
1564 v->handler = if_atom_handler;
1566 } else if (!strcmp(name, "then")) {
1567 v->handler = then_atom_handler;
1569 } else if (!strcmp(name, "else")) {
1570 v->handler = else_atom_handler;
1578 v->s = xstrfmt("%s^{}", refname);
1581 for (i = 0; i < used_atom_cnt; i++) {
1582 struct atom_value *v = &ref->value[i];
1587 if (used_atom_cnt <= i)
1590 get_object(ref, &ref->oid, 0, &obj);
1593 * If there is no atom that wants to know about tagged
1594 * object, we are done.
1596 if (!need_tagged || (obj->type != OBJ_TAG))
1600 * If it is a tag object, see if we use a value that derefs
1601 * the object, and if we do grab the object it refers to.
1603 tagged = &((struct tag *)obj)->tagged->oid;
1606 * NEEDSWORK: This derefs tag only once, which
1607 * is good to deal with chains of trust, but
1608 * is not consistent with what deref_tag() does
1609 * which peels the onion to the core.
1611 get_object(ref, tagged, 1, &obj);
1617 * Given a ref, return the value for the atom. This lazily gets value
1618 * out of the object by calling populate value.
1619 * Return 0 if everything was successful, -1 otherwise.
1621 static int get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1625 retval = populate_value(ref);
1626 fill_missing_values(ref->value);
1628 *v = &ref->value[atom];
1633 * Unknown has to be "0" here, because that's the default value for
1634 * contains_cache slab entries that have not yet been assigned.
1636 enum contains_result {
1637 CONTAINS_UNKNOWN = 0,
1642 define_commit_slab(contains_cache, enum contains_result);
1644 struct ref_filter_cbdata {
1645 struct ref_array *array;
1646 struct ref_filter *filter;
1647 struct contains_cache contains_cache;
1648 struct contains_cache no_contains_cache;
1652 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1655 * At each recursion step, the stack items points to the commits whose
1656 * ancestors are to be inspected.
1658 struct contains_stack {
1660 struct contains_stack_entry {
1661 struct commit *commit;
1662 struct commit_list *parents;
1666 static int in_commit_list(const struct commit_list *want, struct commit *c)
1668 for (; want; want = want->next)
1669 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1675 * Test whether the candidate or one of its parents is contained in the list.
1676 * Do not recurse to find out, though, but return -1 if inconclusive.
1678 static enum contains_result contains_test(struct commit *candidate,
1679 const struct commit_list *want,
1680 struct contains_cache *cache)
1682 enum contains_result *cached = contains_cache_at(cache, candidate);
1684 /* If we already have the answer cached, return that. */
1689 if (in_commit_list(want, candidate)) {
1690 *cached = CONTAINS_YES;
1691 return CONTAINS_YES;
1694 /* Otherwise, we don't know; prepare to recurse */
1695 parse_commit_or_die(candidate);
1696 return CONTAINS_UNKNOWN;
1699 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1701 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1702 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1703 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1706 static enum contains_result contains_tag_algo(struct commit *candidate,
1707 const struct commit_list *want,
1708 struct contains_cache *cache)
1710 struct contains_stack contains_stack = { 0, 0, NULL };
1711 enum contains_result result = contains_test(candidate, want, cache);
1713 if (result != CONTAINS_UNKNOWN)
1716 push_to_contains_stack(candidate, &contains_stack);
1717 while (contains_stack.nr) {
1718 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1719 struct commit *commit = entry->commit;
1720 struct commit_list *parents = entry->parents;
1723 *contains_cache_at(cache, commit) = CONTAINS_NO;
1724 contains_stack.nr--;
1727 * If we just popped the stack, parents->item has been marked,
1728 * therefore contains_test will return a meaningful yes/no.
1730 else switch (contains_test(parents->item, want, cache)) {
1732 *contains_cache_at(cache, commit) = CONTAINS_YES;
1733 contains_stack.nr--;
1736 entry->parents = parents->next;
1738 case CONTAINS_UNKNOWN:
1739 push_to_contains_stack(parents->item, &contains_stack);
1743 free(contains_stack.contains_stack);
1744 return contains_test(candidate, want, cache);
1747 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1748 struct commit_list *list, struct contains_cache *cache)
1750 if (filter->with_commit_tag_algo)
1751 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1752 return is_descendant_of(commit, list);
1756 * Return 1 if the refname matches one of the patterns, otherwise 0.
1757 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1758 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1759 * matches "refs/heads/mas*", too).
1761 static int match_pattern(const struct ref_filter *filter, const char *refname)
1763 const char **patterns = filter->name_patterns;
1766 if (filter->ignore_case)
1767 flags |= WM_CASEFOLD;
1770 * When no '--format' option is given we need to skip the prefix
1771 * for matching refs of tags and branches.
1773 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1774 skip_prefix(refname, "refs/heads/", &refname) ||
1775 skip_prefix(refname, "refs/remotes/", &refname) ||
1776 skip_prefix(refname, "refs/", &refname));
1778 for (; *patterns; patterns++) {
1779 if (!wildmatch(*patterns, refname, flags))
1786 * Return 1 if the refname matches one of the patterns, otherwise 0.
1787 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1788 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1789 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1791 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1793 const char **pattern = filter->name_patterns;
1794 int namelen = strlen(refname);
1795 unsigned flags = WM_PATHNAME;
1797 if (filter->ignore_case)
1798 flags |= WM_CASEFOLD;
1800 for (; *pattern; pattern++) {
1801 const char *p = *pattern;
1802 int plen = strlen(p);
1804 if ((plen <= namelen) &&
1805 !strncmp(refname, p, plen) &&
1806 (refname[plen] == '\0' ||
1807 refname[plen] == '/' ||
1810 if (!wildmatch(p, refname, WM_PATHNAME))
1816 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1817 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1819 if (!*filter->name_patterns)
1820 return 1; /* No pattern always matches */
1821 if (filter->match_as_path)
1822 return match_name_as_path(filter, refname);
1823 return match_pattern(filter, refname);
1827 * Find the longest prefix of pattern we can pass to
1828 * `for_each_fullref_in()`, namely the part of pattern preceding the
1829 * first glob character. (Note that `for_each_fullref_in()` is
1830 * perfectly happy working with a prefix that doesn't end at a
1831 * pathname component boundary.)
1833 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1837 for (p = pattern; *p && !is_glob_special(*p); p++)
1840 strbuf_add(out, pattern, p - pattern);
1844 * This is the same as for_each_fullref_in(), but it tries to iterate
1845 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1846 * pattern match, so the callback still has to match each ref individually.
1848 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1853 struct strbuf prefix = STRBUF_INIT;
1856 if (!filter->match_as_path) {
1858 * in this case, the patterns are applied after
1859 * prefixes like "refs/heads/" etc. are stripped off,
1860 * so we have to look at everything:
1862 return for_each_fullref_in("", cb, cb_data, broken);
1865 if (!filter->name_patterns[0]) {
1866 /* no patterns; we have to look at everything */
1867 return for_each_fullref_in("", cb, cb_data, broken);
1870 if (filter->name_patterns[1]) {
1872 * multiple patterns; in theory this could still work as long
1873 * as the patterns are disjoint. We'd just make multiple calls
1874 * to for_each_ref(). But if they're not disjoint, we'd end up
1875 * reporting the same ref multiple times. So let's punt on that
1878 return for_each_fullref_in("", cb, cb_data, broken);
1881 find_longest_prefix(&prefix, filter->name_patterns[0]);
1883 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1884 strbuf_release(&prefix);
1889 * Given a ref (sha1, refname), check if the ref belongs to the array
1890 * of sha1s. If the given ref is a tag, check if the given tag points
1891 * at one of the sha1s in the given sha1 array.
1892 * the given sha1_array.
1894 * 1. Only a single level of inderection is obtained, we might want to
1895 * change this to account for multiple levels (e.g. annotated tags
1896 * pointing to annotated tags pointing to a commit.)
1897 * 2. As the refs are cached we might know what refname peels to without
1898 * the need to parse the object via parse_object(). peel_ref() might be a
1899 * more efficient alternative to obtain the pointee.
1901 static const struct object_id *match_points_at(struct oid_array *points_at,
1902 const struct object_id *oid,
1903 const char *refname)
1905 const struct object_id *tagged_oid = NULL;
1908 if (oid_array_lookup(points_at, oid) >= 0)
1910 obj = parse_object(oid);
1912 die(_("malformed object at '%s'"), refname);
1913 if (obj->type == OBJ_TAG)
1914 tagged_oid = &((struct tag *)obj)->tagged->oid;
1915 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1920 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1921 static struct ref_array_item *new_ref_array_item(const char *refname,
1922 const unsigned char *objectname,
1925 struct ref_array_item *ref;
1926 FLEX_ALLOC_STR(ref, refname, refname);
1927 hashcpy(ref->oid.hash, objectname);
1933 static int ref_kind_from_refname(const char *refname)
1941 { "refs/heads/" , FILTER_REFS_BRANCHES },
1942 { "refs/remotes/" , FILTER_REFS_REMOTES },
1943 { "refs/tags/", FILTER_REFS_TAGS}
1946 if (!strcmp(refname, "HEAD"))
1947 return FILTER_REFS_DETACHED_HEAD;
1949 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1950 if (starts_with(refname, ref_kind[i].prefix))
1951 return ref_kind[i].kind;
1954 return FILTER_REFS_OTHERS;
1957 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1959 if (filter->kind == FILTER_REFS_BRANCHES ||
1960 filter->kind == FILTER_REFS_REMOTES ||
1961 filter->kind == FILTER_REFS_TAGS)
1962 return filter->kind;
1963 return ref_kind_from_refname(refname);
1967 * A call-back given to for_each_ref(). Filter refs and keep them for
1968 * later object processing.
1970 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1972 struct ref_filter_cbdata *ref_cbdata = cb_data;
1973 struct ref_filter *filter = ref_cbdata->filter;
1974 struct ref_array_item *ref;
1975 struct commit *commit = NULL;
1978 if (flag & REF_BAD_NAME) {
1979 warning(_("ignoring ref with broken name %s"), refname);
1983 if (flag & REF_ISBROKEN) {
1984 warning(_("ignoring broken ref %s"), refname);
1988 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1989 kind = filter_ref_kind(filter, refname);
1990 if (!(kind & filter->kind))
1993 if (!filter_pattern_match(filter, refname))
1996 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2000 * A merge filter is applied on refs pointing to commits. Hence
2001 * obtain the commit using the 'oid' available and discard all
2002 * non-commits early. The actual filtering is done later.
2004 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2005 commit = lookup_commit_reference_gently(oid, 1);
2008 /* We perform the filtering for the '--contains' option... */
2009 if (filter->with_commit &&
2010 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2012 /* ...or for the `--no-contains' option */
2013 if (filter->no_commit &&
2014 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2019 * We do not open the object yet; sort may only need refname
2020 * to do its job and the resulting list may yet to be pruned
2021 * by maxcount logic.
2023 ref = new_ref_array_item(refname, oid->hash, flag);
2024 ref->commit = commit;
2026 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
2027 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
2032 /* Free memory allocated for a ref_array_item */
2033 static void free_array_item(struct ref_array_item *item)
2035 free((char *)item->symref);
2039 /* Free all memory allocated for ref_array */
2040 void ref_array_clear(struct ref_array *array)
2044 for (i = 0; i < array->nr; i++)
2045 free_array_item(array->items[i]);
2046 FREE_AND_NULL(array->items);
2047 array->nr = array->alloc = 0;
2050 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2052 struct rev_info revs;
2054 struct ref_filter *filter = ref_cbdata->filter;
2055 struct ref_array *array = ref_cbdata->array;
2056 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2058 init_revisions(&revs, NULL);
2060 for (i = 0; i < array->nr; i++) {
2061 struct ref_array_item *item = array->items[i];
2062 add_pending_object(&revs, &item->commit->object, item->refname);
2063 to_clear[i] = item->commit;
2066 filter->merge_commit->object.flags |= UNINTERESTING;
2067 add_pending_object(&revs, &filter->merge_commit->object, "");
2070 if (prepare_revision_walk(&revs))
2071 die(_("revision walk setup failed"));
2076 for (i = 0; i < old_nr; i++) {
2077 struct ref_array_item *item = array->items[i];
2078 struct commit *commit = item->commit;
2080 int is_merged = !!(commit->object.flags & UNINTERESTING);
2082 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2083 array->items[array->nr++] = array->items[i];
2085 free_array_item(item);
2088 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2089 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2093 int add_str_to_commit_list(struct string_list_item *item, void *commit_list)
2095 struct object_id oid;
2096 struct commit *commit;
2098 if (get_oid(item->string, &oid)) {
2099 error(_("malformed object name %s"), item->string);
2102 commit = lookup_commit_reference(&oid);
2104 error(_("no such commit %s"), item->string);
2107 commit_list_insert(commit, commit_list);
2113 * API for filtering a set of refs. Based on the type of refs the user
2114 * has requested, we iterate through those refs and apply filters
2115 * as per the given ref_filter structure and finally store the
2116 * filtered refs in the ref_array structure.
2118 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2120 struct ref_filter_cbdata ref_cbdata;
2122 unsigned int broken = 0;
2124 /* Convert string representation and add to commit list. */
2125 for_each_string_list(&filter->with_commit_strs, add_str_to_commit_list, &filter->with_commit);
2126 for_each_string_list(&filter->no_commit_strs, add_str_to_commit_list, &filter->no_commit);
2128 ref_cbdata.array = array;
2129 ref_cbdata.filter = filter;
2131 if (type & FILTER_REFS_INCLUDE_BROKEN)
2133 filter->kind = type & FILTER_REFS_KIND_MASK;
2135 init_contains_cache(&ref_cbdata.contains_cache);
2136 init_contains_cache(&ref_cbdata.no_contains_cache);
2138 /* Simple per-ref filtering */
2140 die("filter_refs: invalid type");
2143 * For common cases where we need only branches or remotes or tags,
2144 * we only iterate through those refs. If a mix of refs is needed,
2145 * we iterate over all refs and filter out required refs with the help
2146 * of filter_ref_kind().
2148 if (filter->kind == FILTER_REFS_BRANCHES)
2149 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2150 else if (filter->kind == FILTER_REFS_REMOTES)
2151 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2152 else if (filter->kind == FILTER_REFS_TAGS)
2153 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2154 else if (filter->kind & FILTER_REFS_ALL)
2155 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2156 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2157 head_ref(ref_filter_handler, &ref_cbdata);
2160 clear_contains_cache(&ref_cbdata.contains_cache);
2161 clear_contains_cache(&ref_cbdata.no_contains_cache);
2163 /* Filters that need revision walking */
2164 if (filter->merge_commit)
2165 do_merge_filter(&ref_cbdata);
2170 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2172 struct atom_value *va, *vb;
2174 cmp_type cmp_type = used_atom[s->atom].type;
2175 int (*cmp_fn)(const char *, const char *);
2177 get_ref_atom_value(a, s->atom, &va);
2178 get_ref_atom_value(b, s->atom, &vb);
2179 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2181 cmp = versioncmp(va->s, vb->s);
2182 else if (cmp_type == FIELD_STR)
2183 cmp = cmp_fn(va->s, vb->s);
2185 if (va->value < vb->value)
2187 else if (va->value == vb->value)
2188 cmp = cmp_fn(a->refname, b->refname);
2193 return (s->reverse) ? -cmp : cmp;
2196 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2198 struct ref_array_item *a = *((struct ref_array_item **)a_);
2199 struct ref_array_item *b = *((struct ref_array_item **)b_);
2200 struct ref_sorting *s;
2202 for (s = ref_sorting; s; s = s->next) {
2203 int cmp = cmp_ref_sorting(s, a, b);
2210 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2212 QSORT_S(array->items, array->nr, compare_refs, sorting);
2215 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2217 struct strbuf *s = &state->stack->output;
2219 while (*cp && (!ep || cp < ep)) {
2224 int ch = hex2chr(cp + 1);
2226 strbuf_addch(s, ch);
2232 strbuf_addch(s, *cp);
2237 int format_ref_array_item(struct ref_array_item *info,
2238 const struct ref_format *format,
2239 struct strbuf *final_buf)
2241 const char *cp, *sp, *ep;
2242 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2245 state.quote_style = format->quote_style;
2246 push_stack_element(&state.stack);
2248 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2249 struct atom_value *atomv;
2251 ep = strchr(sp, ')');
2253 append_literal(cp, sp, &state);
2254 if (get_ref_atom_value(info,
2255 parse_ref_filter_atom(format, sp + 2, ep),
2258 atomv->handler(atomv, &state);
2260 if (cat_file_info.is_cat_file && strlen(format->format) == 0)
2261 retval = check_and_fill_for_cat(info);
2263 sp = cp + strlen(cp);
2264 append_literal(cp, sp, &state);
2266 if (format->need_color_reset_at_eol) {
2267 struct atom_value resetv;
2268 resetv.s = GIT_COLOR_RESET;
2269 append_atom(&resetv, &state);
2271 if (state.stack->prev)
2272 die(_("format: %%(end) atom missing"));
2273 strbuf_addbuf(final_buf, &state.stack->output);
2274 pop_stack_element(&state.stack);
2278 int show_ref_array_item(struct ref_array_item *info,
2279 const struct ref_format *format)
2281 struct strbuf final_buf = STRBUF_INIT;
2282 int retval = format_ref_array_item(info, format, &final_buf);
2285 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2288 strbuf_release(&final_buf);
2292 void pretty_print_ref(const char *name, const unsigned char *sha1,
2293 const struct ref_format *format)
2295 struct ref_array_item *ref_item;
2296 ref_item = new_ref_array_item(name, sha1, 0);
2297 ref_item->kind = ref_kind_from_refname(name);
2298 show_ref_array_item(ref_item, format);
2299 free_array_item(ref_item);
2302 static int parse_sorting_atom(const char *atom)
2305 * This parses an atom using a dummy ref_format, since we don't
2306 * actually care about the formatting details.
2308 struct ref_format dummy = REF_FORMAT_INIT;
2309 const char *end = atom + strlen(atom);
2310 return parse_ref_filter_atom(&dummy, atom, end);
2313 /* If no sorting option is given, use refname to sort as default */
2314 struct ref_sorting *ref_default_sorting(void)
2316 static const char cstr_name[] = "refname";
2318 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2320 sorting->next = NULL;
2321 sorting->atom = parse_sorting_atom(cstr_name);
2325 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2327 struct ref_sorting *s;
2329 s = xcalloc(1, sizeof(*s));
2330 s->next = *sorting_tail;
2337 if (skip_prefix(arg, "version:", &arg) ||
2338 skip_prefix(arg, "v:", &arg))
2340 s->atom = parse_sorting_atom(arg);
2343 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2345 if (!arg) /* should --no-sort void the list ? */
2347 parse_ref_sorting(opt->value, arg);
2351 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2353 struct ref_filter *rf = opt->value;
2354 struct object_id oid;
2355 int no_merged = starts_with(opt->long_name, "no");
2359 return opterror(opt, "is incompatible with --merged", 0);
2361 return opterror(opt, "is incompatible with --no-merged", 0);
2365 rf->merge = no_merged
2366 ? REF_FILTER_MERGED_OMIT
2367 : REF_FILTER_MERGED_INCLUDE;
2369 if (get_oid(arg, &oid))
2370 die(_("malformed object name %s"), arg);
2372 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2373 if (!rf->merge_commit)
2374 return opterror(opt, "must point to a commit", 0);