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"
19 #include "commit-graph.h"
21 static struct ref_msg {
25 const char *ahead_behind;
27 /* Untranslated plumbing messages: */
34 void setup_ref_filter_porcelain_msg(void)
36 msgs.gone = _("gone");
37 msgs.ahead = _("ahead %d");
38 msgs.behind = _("behind %d");
39 msgs.ahead_behind = _("ahead %d, behind %d");
42 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
43 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
44 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
52 cmp_status cmp_status;
54 unsigned int then_atom_seen : 1,
56 condition_satisfied : 1;
60 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
64 static struct expand_data {
66 enum object_type type;
69 struct object_id delta_base_oid;
72 struct object_info info;
76 * An atom is a valid field atom listed below, possibly prefixed with
77 * a "*" to denote deref_tag().
79 * We parse given format string and sort specifiers, and make a list
80 * of properties that we need to extract out of objects. ref_array_item
81 * structure will hold an array of values extracted that can be
82 * indexed with the "atom number", which is an index into this
85 static struct used_atom {
90 char color[COLOR_MAXLEN];
94 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
96 struct refname_atom refname;
97 unsigned int nobracket : 1, push : 1, push_remote : 1;
100 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
101 struct process_trailer_options trailer_opts;
105 cmp_status cmp_status;
109 enum { O_FULL, O_LENGTH, O_SHORT } option;
112 struct refname_atom refname;
116 static int used_atom_cnt, need_tagged, need_symref;
119 * Expand string, append it to strbuf *sb, then return error code ret.
120 * Allow to save few lines of code.
122 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
126 strbuf_vaddf(sb, fmt, ap);
131 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
132 const char *color_value, struct strbuf *err)
135 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
136 if (color_parse(color_value, atom->u.color) < 0)
137 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
140 * We check this after we've parsed the color, which lets us complain
141 * about syntactically bogus color names even if they won't be used.
143 if (!want_color(format->use_color))
144 color_parse("", atom->u.color);
148 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
149 const char *name, struct strbuf *err)
152 atom->option = R_NORMAL;
153 else if (!strcmp(arg, "short"))
154 atom->option = R_SHORT;
155 else if (skip_prefix(arg, "lstrip=", &arg) ||
156 skip_prefix(arg, "strip=", &arg)) {
157 atom->option = R_LSTRIP;
158 if (strtol_i(arg, 10, &atom->lstrip))
159 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
160 } else if (skip_prefix(arg, "rstrip=", &arg)) {
161 atom->option = R_RSTRIP;
162 if (strtol_i(arg, 10, &atom->rstrip))
163 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
165 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
169 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
170 const char *arg, struct strbuf *err)
172 struct string_list params = STRING_LIST_INIT_DUP;
175 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
176 atom->u.remote_ref.push = 1;
179 atom->u.remote_ref.option = RR_REF;
180 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
181 arg, atom->name, err);
184 atom->u.remote_ref.nobracket = 0;
185 string_list_split(¶ms, arg, ',', -1);
187 for (i = 0; i < params.nr; i++) {
188 const char *s = params.items[i].string;
190 if (!strcmp(s, "track"))
191 atom->u.remote_ref.option = RR_TRACK;
192 else if (!strcmp(s, "trackshort"))
193 atom->u.remote_ref.option = RR_TRACKSHORT;
194 else if (!strcmp(s, "nobracket"))
195 atom->u.remote_ref.nobracket = 1;
196 else if (!strcmp(s, "remotename")) {
197 atom->u.remote_ref.option = RR_REMOTE_NAME;
198 atom->u.remote_ref.push_remote = 1;
199 } else if (!strcmp(s, "remoteref")) {
200 atom->u.remote_ref.option = RR_REMOTE_REF;
201 atom->u.remote_ref.push_remote = 1;
203 atom->u.remote_ref.option = RR_REF;
204 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
205 arg, atom->name, err)) {
206 string_list_clear(¶ms, 0);
212 string_list_clear(¶ms, 0);
216 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
217 const char *arg, struct strbuf *err)
220 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
221 if (*atom->name == '*')
222 oi_deref.info.typep = &oi_deref.type;
224 oi.info.typep = &oi.type;
228 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
229 const char *arg, struct strbuf *err)
232 return strbuf_addf_ret(err, -1, _("%%(objectsize) does not take arguments"));
233 if (*atom->name == '*')
234 oi_deref.info.sizep = &oi_deref.size;
236 oi.info.sizep = &oi.size;
240 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
241 const char *arg, struct strbuf *err)
244 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
245 atom->u.contents.option = C_BODY_DEP;
249 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
250 const char *arg, struct strbuf *err)
253 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
254 atom->u.contents.option = C_SUB;
258 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
259 const char *arg, struct strbuf *err)
261 struct string_list params = STRING_LIST_INIT_DUP;
265 string_list_split(¶ms, arg, ',', -1);
266 for (i = 0; i < params.nr; i++) {
267 const char *s = params.items[i].string;
268 if (!strcmp(s, "unfold"))
269 atom->u.contents.trailer_opts.unfold = 1;
270 else if (!strcmp(s, "only"))
271 atom->u.contents.trailer_opts.only_trailers = 1;
273 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
274 string_list_clear(¶ms, 0);
279 atom->u.contents.option = C_TRAILERS;
280 string_list_clear(¶ms, 0);
284 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
285 const char *arg, struct strbuf *err)
288 atom->u.contents.option = C_BARE;
289 else if (!strcmp(arg, "body"))
290 atom->u.contents.option = C_BODY;
291 else if (!strcmp(arg, "signature"))
292 atom->u.contents.option = C_SIG;
293 else if (!strcmp(arg, "subject"))
294 atom->u.contents.option = C_SUB;
295 else if (skip_prefix(arg, "trailers", &arg)) {
296 skip_prefix(arg, ":", &arg);
297 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
299 } else if (skip_prefix(arg, "lines=", &arg)) {
300 atom->u.contents.option = C_LINES;
301 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
302 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
304 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
308 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
309 const char *arg, struct strbuf *err)
312 atom->u.objectname.option = O_FULL;
313 else if (!strcmp(arg, "short"))
314 atom->u.objectname.option = O_SHORT;
315 else if (skip_prefix(arg, "short=", &arg)) {
316 atom->u.objectname.option = O_LENGTH;
317 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
318 atom->u.objectname.length == 0)
319 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
320 if (atom->u.objectname.length < MINIMUM_ABBREV)
321 atom->u.objectname.length = MINIMUM_ABBREV;
323 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
327 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
328 const char *arg, struct strbuf *err)
330 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
333 static align_type parse_align_position(const char *s)
335 if (!strcmp(s, "right"))
337 else if (!strcmp(s, "middle"))
339 else if (!strcmp(s, "left"))
344 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
345 const char *arg, struct strbuf *err)
347 struct align *align = &atom->u.align;
348 struct string_list params = STRING_LIST_INIT_DUP;
350 unsigned int width = ~0U;
353 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
355 align->position = ALIGN_LEFT;
357 string_list_split(¶ms, arg, ',', -1);
358 for (i = 0; i < params.nr; i++) {
359 const char *s = params.items[i].string;
362 if (skip_prefix(s, "position=", &s)) {
363 position = parse_align_position(s);
365 strbuf_addf(err, _("unrecognized position:%s"), s);
366 string_list_clear(¶ms, 0);
369 align->position = position;
370 } else if (skip_prefix(s, "width=", &s)) {
371 if (strtoul_ui(s, 10, &width)) {
372 strbuf_addf(err, _("unrecognized width:%s"), s);
373 string_list_clear(¶ms, 0);
376 } else if (!strtoul_ui(s, 10, &width))
378 else if ((position = parse_align_position(s)) >= 0)
379 align->position = position;
381 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
382 string_list_clear(¶ms, 0);
388 string_list_clear(¶ms, 0);
389 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
391 align->width = width;
392 string_list_clear(¶ms, 0);
396 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
397 const char *arg, struct strbuf *err)
400 atom->u.if_then_else.cmp_status = COMPARE_NONE;
402 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
403 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
404 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
405 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
407 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
411 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
412 const char *arg, struct strbuf *unused_err)
414 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
422 int (*parser)(const struct ref_format *format, struct used_atom *atom,
423 const char *arg, struct strbuf *err);
425 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
426 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
427 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
428 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
429 { "tree", SOURCE_OBJ },
430 { "parent", SOURCE_OBJ },
431 { "numparent", SOURCE_OBJ, FIELD_ULONG },
432 { "object", SOURCE_OBJ },
433 { "type", SOURCE_OBJ },
434 { "tag", SOURCE_OBJ },
435 { "author", SOURCE_OBJ },
436 { "authorname", SOURCE_OBJ },
437 { "authoremail", SOURCE_OBJ },
438 { "authordate", SOURCE_OBJ, FIELD_TIME },
439 { "committer", SOURCE_OBJ },
440 { "committername", SOURCE_OBJ },
441 { "committeremail", SOURCE_OBJ },
442 { "committerdate", SOURCE_OBJ, FIELD_TIME },
443 { "tagger", SOURCE_OBJ },
444 { "taggername", SOURCE_OBJ },
445 { "taggeremail", SOURCE_OBJ },
446 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
447 { "creator", SOURCE_OBJ },
448 { "creatordate", SOURCE_OBJ, FIELD_TIME },
449 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
450 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
451 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
452 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
453 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
454 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
455 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
456 { "flag", SOURCE_NONE },
457 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
458 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
459 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
460 { "end", SOURCE_NONE },
461 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
462 { "then", SOURCE_NONE },
463 { "else", SOURCE_NONE },
466 #define REF_FORMATTING_STATE_INIT { 0, NULL }
468 struct ref_formatting_stack {
469 struct ref_formatting_stack *prev;
470 struct strbuf output;
471 void (*at_end)(struct ref_formatting_stack **stack);
475 struct ref_formatting_state {
477 struct ref_formatting_stack *stack;
482 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
484 uintmax_t value; /* used for sorting when not FIELD_STR */
485 struct used_atom *atom;
489 * Used to parse format string and sort specifiers
491 static int parse_ref_filter_atom(const struct ref_format *format,
492 const char *atom, const char *ep,
500 if (*sp == '*' && sp < ep)
503 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
504 (int)(ep-atom), atom);
506 /* Do we have the atom already used elsewhere? */
507 for (i = 0; i < used_atom_cnt; i++) {
508 int len = strlen(used_atom[i].name);
509 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
514 * If the atom name has a colon, strip it and everything after
515 * it off - it specifies the format for this entry, and
516 * shouldn't be used for checking against the valid_atom
519 arg = memchr(sp, ':', ep - sp);
520 atom_len = (arg ? arg : ep) - sp;
522 /* Is the atom a valid one? */
523 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
524 int len = strlen(valid_atom[i].name);
525 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
529 if (ARRAY_SIZE(valid_atom) <= i)
530 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
531 (int)(ep-atom), atom);
533 /* Add it in, including the deref prefix */
536 REALLOC_ARRAY(used_atom, used_atom_cnt);
537 used_atom[at].name = xmemdupz(atom, ep - atom);
538 used_atom[at].type = valid_atom[i].cmp_type;
539 used_atom[at].source = valid_atom[i].source;
540 if (used_atom[at].source == SOURCE_OBJ) {
542 oi_deref.info.contentp = &oi_deref.content;
544 oi.info.contentp = &oi.content;
547 arg = used_atom[at].name + (arg - atom) + 1;
550 * Treat empty sub-arguments list as NULL (i.e.,
551 * "%(atom:)" is equivalent to "%(atom)").
556 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
557 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
561 if (!strcmp(valid_atom[i].name, "symref"))
566 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
568 switch (quote_style) {
570 strbuf_addstr(s, str);
573 sq_quote_buf(s, str);
576 perl_quote_buf(s, str);
579 python_quote_buf(s, str);
582 tcl_quote_buf(s, str);
587 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
588 struct strbuf *unused_err)
591 * Quote formatting is only done when the stack has a single
592 * element. Otherwise quote formatting is done on the
593 * element's entire output strbuf when the %(end) atom is
596 if (!state->stack->prev)
597 quote_formatting(&state->stack->output, v->s, state->quote_style);
599 strbuf_addstr(&state->stack->output, v->s);
603 static void push_stack_element(struct ref_formatting_stack **stack)
605 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
607 strbuf_init(&s->output, 0);
612 static void pop_stack_element(struct ref_formatting_stack **stack)
614 struct ref_formatting_stack *current = *stack;
615 struct ref_formatting_stack *prev = current->prev;
618 strbuf_addbuf(&prev->output, ¤t->output);
619 strbuf_release(¤t->output);
624 static void end_align_handler(struct ref_formatting_stack **stack)
626 struct ref_formatting_stack *cur = *stack;
627 struct align *align = (struct align *)cur->at_end_data;
628 struct strbuf s = STRBUF_INIT;
630 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
631 strbuf_swap(&cur->output, &s);
635 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
636 struct strbuf *unused_err)
638 struct ref_formatting_stack *new_stack;
640 push_stack_element(&state->stack);
641 new_stack = state->stack;
642 new_stack->at_end = end_align_handler;
643 new_stack->at_end_data = &atomv->atom->u.align;
647 static void if_then_else_handler(struct ref_formatting_stack **stack)
649 struct ref_formatting_stack *cur = *stack;
650 struct ref_formatting_stack *prev = cur->prev;
651 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
653 if (!if_then_else->then_atom_seen)
654 die(_("format: %%(if) atom used without a %%(then) atom"));
656 if (if_then_else->else_atom_seen) {
658 * There is an %(else) atom: we need to drop one state from the
659 * stack, either the %(else) branch if the condition is satisfied, or
660 * the %(then) branch if it isn't.
662 if (if_then_else->condition_satisfied) {
663 strbuf_reset(&cur->output);
664 pop_stack_element(&cur);
666 strbuf_swap(&cur->output, &prev->output);
667 strbuf_reset(&cur->output);
668 pop_stack_element(&cur);
670 } else if (!if_then_else->condition_satisfied) {
672 * No %(else) atom: just drop the %(then) branch if the
673 * condition is not satisfied.
675 strbuf_reset(&cur->output);
682 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
683 struct strbuf *unused_err)
685 struct ref_formatting_stack *new_stack;
686 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
688 if_then_else->str = atomv->atom->u.if_then_else.str;
689 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
691 push_stack_element(&state->stack);
692 new_stack = state->stack;
693 new_stack->at_end = if_then_else_handler;
694 new_stack->at_end_data = if_then_else;
698 static int is_empty(const char *s)
708 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
711 struct ref_formatting_stack *cur = state->stack;
712 struct if_then_else *if_then_else = NULL;
714 if (cur->at_end == if_then_else_handler)
715 if_then_else = (struct if_then_else *)cur->at_end_data;
717 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
718 if (if_then_else->then_atom_seen)
719 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
720 if (if_then_else->else_atom_seen)
721 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
722 if_then_else->then_atom_seen = 1;
724 * If the 'equals' or 'notequals' attribute is used then
725 * perform the required comparison. If not, only non-empty
726 * strings satisfy the 'if' condition.
728 if (if_then_else->cmp_status == COMPARE_EQUAL) {
729 if (!strcmp(if_then_else->str, cur->output.buf))
730 if_then_else->condition_satisfied = 1;
731 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
732 if (strcmp(if_then_else->str, cur->output.buf))
733 if_then_else->condition_satisfied = 1;
734 } else if (cur->output.len && !is_empty(cur->output.buf))
735 if_then_else->condition_satisfied = 1;
736 strbuf_reset(&cur->output);
740 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
743 struct ref_formatting_stack *prev = state->stack;
744 struct if_then_else *if_then_else = NULL;
746 if (prev->at_end == if_then_else_handler)
747 if_then_else = (struct if_then_else *)prev->at_end_data;
749 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
750 if (!if_then_else->then_atom_seen)
751 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
752 if (if_then_else->else_atom_seen)
753 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
754 if_then_else->else_atom_seen = 1;
755 push_stack_element(&state->stack);
756 state->stack->at_end_data = prev->at_end_data;
757 state->stack->at_end = prev->at_end;
761 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
764 struct ref_formatting_stack *current = state->stack;
765 struct strbuf s = STRBUF_INIT;
767 if (!current->at_end)
768 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
769 current->at_end(&state->stack);
771 /* Stack may have been popped within at_end(), hence reset the current pointer */
772 current = state->stack;
775 * Perform quote formatting when the stack element is that of
776 * a supporting atom. If nested then perform quote formatting
777 * only on the topmost supporting atom.
779 if (!current->prev->prev) {
780 quote_formatting(&s, current->output.buf, state->quote_style);
781 strbuf_swap(¤t->output, &s);
784 pop_stack_element(&state->stack);
789 * In a format string, find the next occurrence of %(atom).
791 static const char *find_next(const char *cp)
796 * %( is the start of an atom;
797 * %% is a quoted per-cent.
801 else if (cp[1] == '%')
802 cp++; /* skip over two % */
803 /* otherwise this is a singleton, literal % */
811 * Make sure the format string is well formed, and parse out
814 int verify_ref_format(struct ref_format *format)
818 format->need_color_reset_at_eol = 0;
819 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
820 struct strbuf err = STRBUF_INIT;
821 const char *color, *ep = strchr(sp, ')');
825 return error(_("malformed format string %s"), sp);
826 /* sp points at "%(" and ep points at the closing ")" */
827 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
832 if (skip_prefix(used_atom[at].name, "color:", &color))
833 format->need_color_reset_at_eol = !!strcmp(color, "reset");
834 strbuf_release(&err);
836 if (format->need_color_reset_at_eol && !want_color(format->use_color))
837 format->need_color_reset_at_eol = 0;
841 static int grab_objectname(const char *name, const struct object_id *oid,
842 struct atom_value *v, struct used_atom *atom)
844 if (starts_with(name, "objectname")) {
845 if (atom->u.objectname.option == O_SHORT) {
846 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
848 } else if (atom->u.objectname.option == O_FULL) {
849 v->s = xstrdup(oid_to_hex(oid));
851 } else if (atom->u.objectname.option == O_LENGTH) {
852 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
855 BUG("unknown %%(objectname) option");
860 /* See grab_values */
861 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
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, "objecttype"))
873 v->s = type_name(oi->type);
874 else if (!strcmp(name, "objectsize")) {
876 v->s = xstrfmt("%lu", oi->size);
879 grab_objectname(name, &oi->oid, v, &used_atom[i]);
883 /* See grab_values */
884 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
887 struct tag *tag = (struct tag *) obj;
889 for (i = 0; i < used_atom_cnt; i++) {
890 const char *name = used_atom[i].name;
891 struct atom_value *v = &val[i];
892 if (!!deref != (*name == '*'))
896 if (!strcmp(name, "tag"))
898 else if (!strcmp(name, "type") && tag->tagged)
899 v->s = type_name(tag->tagged->type);
900 else if (!strcmp(name, "object") && tag->tagged)
901 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
905 /* See grab_values */
906 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
909 struct commit *commit = (struct commit *) obj;
911 for (i = 0; i < used_atom_cnt; i++) {
912 const char *name = used_atom[i].name;
913 struct atom_value *v = &val[i];
914 if (!!deref != (*name == '*'))
918 if (!strcmp(name, "tree")) {
919 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
921 else if (!strcmp(name, "numparent")) {
922 v->value = commit_list_count(commit->parents);
923 v->s = xstrfmt("%lu", (unsigned long)v->value);
925 else if (!strcmp(name, "parent")) {
926 struct commit_list *parents;
927 struct strbuf s = STRBUF_INIT;
928 for (parents = commit->parents; parents; parents = parents->next) {
929 struct commit *parent = parents->item;
930 if (parents != commit->parents)
931 strbuf_addch(&s, ' ');
932 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
934 v->s = strbuf_detach(&s, NULL);
939 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
943 if (!strncmp(buf, who, wholen) &&
945 return buf + wholen + 1;
946 eol = strchr(buf, '\n');
951 return ""; /* end of header */
957 static const char *copy_line(const char *buf)
959 const char *eol = strchrnul(buf, '\n');
960 return xmemdupz(buf, eol - buf);
963 static const char *copy_name(const char *buf)
966 for (cp = buf; *cp && *cp != '\n'; cp++) {
967 if (!strncmp(cp, " <", 2))
968 return xmemdupz(buf, cp - buf);
973 static const char *copy_email(const char *buf)
975 const char *email = strchr(buf, '<');
979 eoemail = strchr(email, '>');
982 return xmemdupz(email, eoemail + 1 - email);
985 static char *copy_subject(const char *buf, unsigned long len)
987 char *r = xmemdupz(buf, len);
990 for (i = 0; i < len; i++)
997 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
999 const char *eoemail = strstr(buf, "> ");
1001 timestamp_t timestamp;
1003 struct date_mode date_mode = { DATE_NORMAL };
1004 const char *formatp;
1007 * We got here because atomname ends in "date" or "date<something>";
1008 * it's not possible that <something> is not ":<format>" because
1009 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1010 * ":" means no format is specified, and use the default.
1012 formatp = strchr(atomname, ':');
1013 if (formatp != NULL) {
1015 parse_date_format(formatp, &date_mode);
1020 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1021 if (timestamp == TIME_MAX)
1023 tz = strtol(zone, NULL, 10);
1024 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1026 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1027 v->value = timestamp;
1034 /* See grab_values */
1035 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1038 int wholen = strlen(who);
1039 const char *wholine = NULL;
1041 for (i = 0; i < used_atom_cnt; i++) {
1042 const char *name = used_atom[i].name;
1043 struct atom_value *v = &val[i];
1044 if (!!deref != (*name == '*'))
1048 if (strncmp(who, name, wholen))
1050 if (name[wholen] != 0 &&
1051 strcmp(name + wholen, "name") &&
1052 strcmp(name + wholen, "email") &&
1053 !starts_with(name + wholen, "date"))
1056 wholine = find_wholine(who, wholen, buf, sz);
1058 return; /* no point looking for it */
1059 if (name[wholen] == 0)
1060 v->s = copy_line(wholine);
1061 else if (!strcmp(name + wholen, "name"))
1062 v->s = copy_name(wholine);
1063 else if (!strcmp(name + wholen, "email"))
1064 v->s = copy_email(wholine);
1065 else if (starts_with(name + wholen, "date"))
1066 grab_date(wholine, v, name);
1070 * For a tag or a commit object, if "creator" or "creatordate" is
1071 * requested, do something special.
1073 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1074 return; /* "author" for commit object is not wanted */
1076 wholine = find_wholine(who, wholen, buf, sz);
1079 for (i = 0; i < used_atom_cnt; i++) {
1080 const char *name = used_atom[i].name;
1081 struct atom_value *v = &val[i];
1082 if (!!deref != (*name == '*'))
1087 if (starts_with(name, "creatordate"))
1088 grab_date(wholine, v, name);
1089 else if (!strcmp(name, "creator"))
1090 v->s = copy_line(wholine);
1094 static void find_subpos(const char *buf, unsigned long sz,
1095 const char **sub, unsigned long *sublen,
1096 const char **body, unsigned long *bodylen,
1097 unsigned long *nonsiglen,
1098 const char **sig, unsigned long *siglen)
1101 /* skip past header until we hit empty line */
1102 while (*buf && *buf != '\n') {
1103 eol = strchrnul(buf, '\n');
1108 /* skip any empty lines */
1109 while (*buf == '\n')
1112 /* parse signature first; we might not even have a subject line */
1113 *sig = buf + parse_signature(buf, strlen(buf));
1114 *siglen = strlen(*sig);
1116 /* subject is first non-empty line */
1118 /* subject goes to first empty line */
1119 while (buf < *sig && *buf && *buf != '\n') {
1120 eol = strchrnul(buf, '\n');
1125 *sublen = buf - *sub;
1126 /* drop trailing newline, if present */
1127 if (*sublen && (*sub)[*sublen - 1] == '\n')
1130 /* skip any empty lines */
1131 while (*buf == '\n')
1134 *bodylen = strlen(buf);
1135 *nonsiglen = *sig - buf;
1139 * If 'lines' is greater than 0, append that many lines from the given
1140 * 'buf' of length 'size' to the given strbuf.
1142 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1145 const char *sp, *eol;
1150 for (i = 0; i < lines && sp < buf + size; i++) {
1152 strbuf_addstr(out, "\n ");
1153 eol = memchr(sp, '\n', size - (sp - buf));
1154 len = eol ? eol - sp : size - (sp - buf);
1155 strbuf_add(out, sp, len);
1162 /* See grab_values */
1163 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1166 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1167 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1169 for (i = 0; i < used_atom_cnt; i++) {
1170 struct used_atom *atom = &used_atom[i];
1171 const char *name = atom->name;
1172 struct atom_value *v = &val[i];
1173 if (!!deref != (*name == '*'))
1177 if (strcmp(name, "subject") &&
1178 strcmp(name, "body") &&
1179 !starts_with(name, "trailers") &&
1180 !starts_with(name, "contents"))
1183 find_subpos(buf, sz,
1185 &bodypos, &bodylen, &nonsiglen,
1188 if (atom->u.contents.option == C_SUB)
1189 v->s = copy_subject(subpos, sublen);
1190 else if (atom->u.contents.option == C_BODY_DEP)
1191 v->s = xmemdupz(bodypos, bodylen);
1192 else if (atom->u.contents.option == C_BODY)
1193 v->s = xmemdupz(bodypos, nonsiglen);
1194 else if (atom->u.contents.option == C_SIG)
1195 v->s = xmemdupz(sigpos, siglen);
1196 else if (atom->u.contents.option == C_LINES) {
1197 struct strbuf s = STRBUF_INIT;
1198 const char *contents_end = bodylen + bodypos - siglen;
1200 /* Size is the length of the message after removing the signature */
1201 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1202 v->s = strbuf_detach(&s, NULL);
1203 } else if (atom->u.contents.option == C_TRAILERS) {
1204 struct strbuf s = STRBUF_INIT;
1206 /* Format the trailer info according to the trailer_opts given */
1207 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1209 v->s = strbuf_detach(&s, NULL);
1210 } else if (atom->u.contents.option == C_BARE)
1211 v->s = xstrdup(subpos);
1216 * We want to have empty print-string for field requests
1217 * that do not apply (e.g. "authordate" for a tag object)
1219 static void fill_missing_values(struct atom_value *val)
1222 for (i = 0; i < used_atom_cnt; i++) {
1223 struct atom_value *v = &val[i];
1230 * val is a list of atom_value to hold returned values. Extract
1231 * the values for atoms in used_atom array out of (obj, buf, sz).
1232 * when deref is false, (obj, buf, sz) is the object that is
1233 * pointed at by the ref itself; otherwise it is the object the
1234 * ref (which is a tag) refers to.
1236 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1238 switch (obj->type) {
1240 grab_tag_values(val, deref, obj, buf, sz);
1241 grab_sub_body_contents(val, deref, obj, buf, sz);
1242 grab_person("tagger", val, deref, obj, buf, sz);
1245 grab_commit_values(val, deref, obj, buf, sz);
1246 grab_sub_body_contents(val, deref, obj, buf, sz);
1247 grab_person("author", val, deref, obj, buf, sz);
1248 grab_person("committer", val, deref, obj, buf, sz);
1251 /* grab_tree_values(val, deref, obj, buf, sz); */
1254 /* grab_blob_values(val, deref, obj, buf, sz); */
1257 die("Eh? Object of type %d?", obj->type);
1261 static inline char *copy_advance(char *dst, const char *src)
1268 static const char *lstrip_ref_components(const char *refname, int len)
1270 long remaining = len;
1271 const char *start = refname;
1275 const char *p = refname;
1277 /* Find total no of '/' separated path-components */
1278 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1281 * The number of components we need to strip is now
1282 * the total minus the components to be left (Plus one
1283 * because we count the number of '/', but the number
1284 * of components is one more than the no of '/').
1286 remaining = i + len + 1;
1289 while (remaining > 0) {
1302 static const char *rstrip_ref_components(const char *refname, int len)
1304 long remaining = len;
1305 char *start = xstrdup(refname);
1309 const char *p = refname;
1311 /* Find total no of '/' separated path-components */
1312 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1315 * The number of components we need to strip is now
1316 * the total minus the components to be left (Plus one
1317 * because we count the number of '/', but the number
1318 * of components is one more than the no of '/').
1320 remaining = i + len + 1;
1323 while (remaining-- > 0) {
1324 char *p = strrchr(start, '/');
1333 static const char *show_ref(struct refname_atom *atom, const char *refname)
1335 if (atom->option == R_SHORT)
1336 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1337 else if (atom->option == R_LSTRIP)
1338 return lstrip_ref_components(refname, atom->lstrip);
1339 else if (atom->option == R_RSTRIP)
1340 return rstrip_ref_components(refname, atom->rstrip);
1345 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1346 struct branch *branch, const char **s)
1348 int num_ours, num_theirs;
1349 if (atom->u.remote_ref.option == RR_REF)
1350 *s = show_ref(&atom->u.remote_ref.refname, refname);
1351 else if (atom->u.remote_ref.option == RR_TRACK) {
1352 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1353 NULL, AHEAD_BEHIND_FULL) < 0) {
1354 *s = xstrdup(msgs.gone);
1355 } else if (!num_ours && !num_theirs)
1358 *s = xstrfmt(msgs.behind, num_theirs);
1359 else if (!num_theirs)
1360 *s = xstrfmt(msgs.ahead, num_ours);
1362 *s = xstrfmt(msgs.ahead_behind,
1363 num_ours, num_theirs);
1364 if (!atom->u.remote_ref.nobracket && *s[0]) {
1365 const char *to_free = *s;
1366 *s = xstrfmt("[%s]", *s);
1367 free((void *)to_free);
1369 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1370 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1371 NULL, AHEAD_BEHIND_FULL) < 0)
1374 if (!num_ours && !num_theirs)
1378 else if (!num_theirs)
1382 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1384 const char *remote = atom->u.remote_ref.push ?
1385 pushremote_for_branch(branch, &explicit) :
1386 remote_for_branch(branch, &explicit);
1388 *s = xstrdup(remote);
1391 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1395 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1398 *s = xstrdup(merge);
1402 BUG("unhandled RR_* enum");
1405 char *get_head_description(void)
1407 struct strbuf desc = STRBUF_INIT;
1408 struct wt_status_state state;
1409 memset(&state, 0, sizeof(state));
1410 wt_status_get_state(&state, 1);
1411 if (state.rebase_in_progress ||
1412 state.rebase_interactive_in_progress) {
1414 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1417 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1418 state.detached_from);
1419 } else if (state.bisect_in_progress)
1420 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1422 else if (state.detached_from) {
1423 if (state.detached_at)
1425 * TRANSLATORS: make sure this matches "HEAD
1426 * detached at " in wt-status.c
1428 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1429 state.detached_from);
1432 * TRANSLATORS: make sure this matches "HEAD
1433 * detached from " in wt-status.c
1435 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1436 state.detached_from);
1439 strbuf_addstr(&desc, _("(no branch)"));
1442 free(state.detached_from);
1443 return strbuf_detach(&desc, NULL);
1446 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1451 return show_ref(&atom->u.refname, ref->symref);
1454 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1456 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1457 return get_head_description();
1458 return show_ref(&atom->u.refname, ref->refname);
1461 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1462 struct expand_data *oi, struct strbuf *err)
1464 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1466 if (oi->info.contentp) {
1467 /* We need to know that to use parse_object_buffer properly */
1468 oi->info.sizep = &oi->size;
1469 oi->info.typep = &oi->type;
1471 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1472 OBJECT_INFO_LOOKUP_REPLACE))
1473 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1474 oid_to_hex(&oi->oid), ref->refname);
1476 if (oi->info.contentp) {
1477 *obj = parse_object_buffer(&oi->oid, oi->type, oi->size, oi->content, &eaten);
1481 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1482 oid_to_hex(&oi->oid), ref->refname);
1484 grab_values(ref->value, deref, *obj, oi->content, oi->size);
1487 grab_common_values(ref->value, deref, oi);
1494 * Parse the object referred by ref, and grab needed value.
1496 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1500 struct object_info empty = OBJECT_INFO_INIT;
1502 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1504 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1505 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1511 /* Fill in specials first */
1512 for (i = 0; i < used_atom_cnt; i++) {
1513 struct used_atom *atom = &used_atom[i];
1514 const char *name = used_atom[i].name;
1515 struct atom_value *v = &ref->value[i];
1517 const char *refname;
1518 struct branch *branch = NULL;
1520 v->handler = append_atom;
1528 if (starts_with(name, "refname"))
1529 refname = get_refname(atom, ref);
1530 else if (starts_with(name, "symref"))
1531 refname = get_symref(atom, ref);
1532 else if (starts_with(name, "upstream")) {
1533 const char *branch_name;
1535 /* only local branches may have an upstream */
1536 if (!skip_prefix(ref->refname, "refs/heads/",
1539 branch = branch_get(branch_name);
1541 refname = branch_get_upstream(branch, NULL);
1543 fill_remote_ref_details(atom, refname, branch, &v->s);
1545 } else if (atom->u.remote_ref.push) {
1546 const char *branch_name;
1548 if (!skip_prefix(ref->refname, "refs/heads/",
1551 branch = branch_get(branch_name);
1553 if (atom->u.remote_ref.push_remote)
1556 refname = branch_get_push(branch, NULL);
1560 fill_remote_ref_details(atom, refname, branch, &v->s);
1562 } else if (starts_with(name, "color:")) {
1563 v->s = atom->u.color;
1565 } else if (!strcmp(name, "flag")) {
1566 char buf[256], *cp = buf;
1567 if (ref->flag & REF_ISSYMREF)
1568 cp = copy_advance(cp, ",symref");
1569 if (ref->flag & REF_ISPACKED)
1570 cp = copy_advance(cp, ",packed");
1575 v->s = xstrdup(buf + 1);
1578 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1580 } else if (!strcmp(name, "HEAD")) {
1581 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1586 } else if (starts_with(name, "align")) {
1587 v->handler = align_atom_handler;
1590 } else if (!strcmp(name, "end")) {
1591 v->handler = end_atom_handler;
1594 } else if (starts_with(name, "if")) {
1597 if (skip_prefix(name, "if:", &s))
1599 v->handler = if_atom_handler;
1601 } else if (!strcmp(name, "then")) {
1602 v->handler = then_atom_handler;
1605 } else if (!strcmp(name, "else")) {
1606 v->handler = else_atom_handler;
1615 v->s = xstrfmt("%s^{}", refname);
1618 for (i = 0; i < used_atom_cnt; i++) {
1619 struct atom_value *v = &ref->value[i];
1620 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1621 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1622 oid_to_hex(&ref->objectname), ref->refname);
1626 oi.info.contentp = &oi.content;
1627 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1628 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1632 oi.oid = ref->objectname;
1633 if (get_object(ref, 0, &obj, &oi, err))
1637 * If there is no atom that wants to know about tagged
1638 * object, we are done.
1640 if (!need_tagged || (obj->type != OBJ_TAG))
1644 * If it is a tag object, see if we use a value that derefs
1645 * the object, and if we do grab the object it refers to.
1647 oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1650 * NEEDSWORK: This derefs tag only once, which
1651 * is good to deal with chains of trust, but
1652 * is not consistent with what deref_tag() does
1653 * which peels the onion to the core.
1655 return get_object(ref, 1, &obj, &oi_deref, err);
1659 * Given a ref, return the value for the atom. This lazily gets value
1660 * out of the object by calling populate value.
1662 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1663 struct atom_value **v, struct strbuf *err)
1666 if (populate_value(ref, err))
1668 fill_missing_values(ref->value);
1670 *v = &ref->value[atom];
1675 * Unknown has to be "0" here, because that's the default value for
1676 * contains_cache slab entries that have not yet been assigned.
1678 enum contains_result {
1679 CONTAINS_UNKNOWN = 0,
1684 define_commit_slab(contains_cache, enum contains_result);
1686 struct ref_filter_cbdata {
1687 struct ref_array *array;
1688 struct ref_filter *filter;
1689 struct contains_cache contains_cache;
1690 struct contains_cache no_contains_cache;
1694 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1697 * At each recursion step, the stack items points to the commits whose
1698 * ancestors are to be inspected.
1700 struct contains_stack {
1702 struct contains_stack_entry {
1703 struct commit *commit;
1704 struct commit_list *parents;
1708 static int in_commit_list(const struct commit_list *want, struct commit *c)
1710 for (; want; want = want->next)
1711 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1717 * Test whether the candidate is contained in the list.
1718 * Do not recurse to find out, though, but return -1 if inconclusive.
1720 static enum contains_result contains_test(struct commit *candidate,
1721 const struct commit_list *want,
1722 struct contains_cache *cache,
1725 enum contains_result *cached = contains_cache_at(cache, candidate);
1727 /* If we already have the answer cached, return that. */
1732 if (in_commit_list(want, candidate)) {
1733 *cached = CONTAINS_YES;
1734 return CONTAINS_YES;
1737 /* Otherwise, we don't know; prepare to recurse */
1738 parse_commit_or_die(candidate);
1740 if (candidate->generation < cutoff)
1743 return CONTAINS_UNKNOWN;
1746 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1748 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1749 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1750 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1753 static enum contains_result contains_tag_algo(struct commit *candidate,
1754 const struct commit_list *want,
1755 struct contains_cache *cache)
1757 struct contains_stack contains_stack = { 0, 0, NULL };
1758 enum contains_result result;
1759 uint32_t cutoff = GENERATION_NUMBER_INFINITY;
1760 const struct commit_list *p;
1762 for (p = want; p; p = p->next) {
1763 struct commit *c = p->item;
1764 load_commit_graph_info(c);
1765 if (c->generation < cutoff)
1766 cutoff = c->generation;
1769 result = contains_test(candidate, want, cache, cutoff);
1770 if (result != CONTAINS_UNKNOWN)
1773 push_to_contains_stack(candidate, &contains_stack);
1774 while (contains_stack.nr) {
1775 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1776 struct commit *commit = entry->commit;
1777 struct commit_list *parents = entry->parents;
1780 *contains_cache_at(cache, commit) = CONTAINS_NO;
1781 contains_stack.nr--;
1784 * If we just popped the stack, parents->item has been marked,
1785 * therefore contains_test will return a meaningful yes/no.
1787 else switch (contains_test(parents->item, want, cache, cutoff)) {
1789 *contains_cache_at(cache, commit) = CONTAINS_YES;
1790 contains_stack.nr--;
1793 entry->parents = parents->next;
1795 case CONTAINS_UNKNOWN:
1796 push_to_contains_stack(parents->item, &contains_stack);
1800 free(contains_stack.contains_stack);
1801 return contains_test(candidate, want, cache, cutoff);
1804 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1805 struct commit_list *list, struct contains_cache *cache)
1807 if (filter->with_commit_tag_algo)
1808 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1809 return is_descendant_of(commit, list);
1813 * Return 1 if the refname matches one of the patterns, otherwise 0.
1814 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1815 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1816 * matches "refs/heads/mas*", too).
1818 static int match_pattern(const struct ref_filter *filter, const char *refname)
1820 const char **patterns = filter->name_patterns;
1823 if (filter->ignore_case)
1824 flags |= WM_CASEFOLD;
1827 * When no '--format' option is given we need to skip the prefix
1828 * for matching refs of tags and branches.
1830 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1831 skip_prefix(refname, "refs/heads/", &refname) ||
1832 skip_prefix(refname, "refs/remotes/", &refname) ||
1833 skip_prefix(refname, "refs/", &refname));
1835 for (; *patterns; patterns++) {
1836 if (!wildmatch(*patterns, refname, flags))
1843 * Return 1 if the refname matches one of the patterns, otherwise 0.
1844 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1845 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1846 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1848 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1850 const char **pattern = filter->name_patterns;
1851 int namelen = strlen(refname);
1852 unsigned flags = WM_PATHNAME;
1854 if (filter->ignore_case)
1855 flags |= WM_CASEFOLD;
1857 for (; *pattern; pattern++) {
1858 const char *p = *pattern;
1859 int plen = strlen(p);
1861 if ((plen <= namelen) &&
1862 !strncmp(refname, p, plen) &&
1863 (refname[plen] == '\0' ||
1864 refname[plen] == '/' ||
1867 if (!wildmatch(p, refname, WM_PATHNAME))
1873 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1874 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1876 if (!*filter->name_patterns)
1877 return 1; /* No pattern always matches */
1878 if (filter->match_as_path)
1879 return match_name_as_path(filter, refname);
1880 return match_pattern(filter, refname);
1884 * Find the longest prefix of pattern we can pass to
1885 * `for_each_fullref_in()`, namely the part of pattern preceding the
1886 * first glob character. (Note that `for_each_fullref_in()` is
1887 * perfectly happy working with a prefix that doesn't end at a
1888 * pathname component boundary.)
1890 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1894 for (p = pattern; *p && !is_glob_special(*p); p++)
1897 strbuf_add(out, pattern, p - pattern);
1901 * This is the same as for_each_fullref_in(), but it tries to iterate
1902 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1903 * pattern match, so the callback still has to match each ref individually.
1905 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1910 struct strbuf prefix = STRBUF_INIT;
1913 if (!filter->match_as_path) {
1915 * in this case, the patterns are applied after
1916 * prefixes like "refs/heads/" etc. are stripped off,
1917 * so we have to look at everything:
1919 return for_each_fullref_in("", cb, cb_data, broken);
1922 if (!filter->name_patterns[0]) {
1923 /* no patterns; we have to look at everything */
1924 return for_each_fullref_in("", cb, cb_data, broken);
1927 if (filter->name_patterns[1]) {
1929 * multiple patterns; in theory this could still work as long
1930 * as the patterns are disjoint. We'd just make multiple calls
1931 * to for_each_ref(). But if they're not disjoint, we'd end up
1932 * reporting the same ref multiple times. So let's punt on that
1935 return for_each_fullref_in("", cb, cb_data, broken);
1938 find_longest_prefix(&prefix, filter->name_patterns[0]);
1940 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1941 strbuf_release(&prefix);
1946 * Given a ref (sha1, refname), check if the ref belongs to the array
1947 * of sha1s. If the given ref is a tag, check if the given tag points
1948 * at one of the sha1s in the given sha1 array.
1949 * the given sha1_array.
1951 * 1. Only a single level of inderection is obtained, we might want to
1952 * change this to account for multiple levels (e.g. annotated tags
1953 * pointing to annotated tags pointing to a commit.)
1954 * 2. As the refs are cached we might know what refname peels to without
1955 * the need to parse the object via parse_object(). peel_ref() might be a
1956 * more efficient alternative to obtain the pointee.
1958 static const struct object_id *match_points_at(struct oid_array *points_at,
1959 const struct object_id *oid,
1960 const char *refname)
1962 const struct object_id *tagged_oid = NULL;
1965 if (oid_array_lookup(points_at, oid) >= 0)
1967 obj = parse_object(oid);
1969 die(_("malformed object at '%s'"), refname);
1970 if (obj->type == OBJ_TAG)
1971 tagged_oid = &((struct tag *)obj)->tagged->oid;
1972 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1978 * Allocate space for a new ref_array_item and copy the name and oid to it.
1980 * Callers can then fill in other struct members at their leisure.
1982 static struct ref_array_item *new_ref_array_item(const char *refname,
1983 const struct object_id *oid)
1985 struct ref_array_item *ref;
1987 FLEX_ALLOC_STR(ref, refname, refname);
1988 oidcpy(&ref->objectname, oid);
1993 struct ref_array_item *ref_array_push(struct ref_array *array,
1994 const char *refname,
1995 const struct object_id *oid)
1997 struct ref_array_item *ref = new_ref_array_item(refname, oid);
1999 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2000 array->items[array->nr++] = ref;
2005 static int ref_kind_from_refname(const char *refname)
2013 { "refs/heads/" , FILTER_REFS_BRANCHES },
2014 { "refs/remotes/" , FILTER_REFS_REMOTES },
2015 { "refs/tags/", FILTER_REFS_TAGS}
2018 if (!strcmp(refname, "HEAD"))
2019 return FILTER_REFS_DETACHED_HEAD;
2021 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2022 if (starts_with(refname, ref_kind[i].prefix))
2023 return ref_kind[i].kind;
2026 return FILTER_REFS_OTHERS;
2029 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2031 if (filter->kind == FILTER_REFS_BRANCHES ||
2032 filter->kind == FILTER_REFS_REMOTES ||
2033 filter->kind == FILTER_REFS_TAGS)
2034 return filter->kind;
2035 return ref_kind_from_refname(refname);
2039 * A call-back given to for_each_ref(). Filter refs and keep them for
2040 * later object processing.
2042 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2044 struct ref_filter_cbdata *ref_cbdata = cb_data;
2045 struct ref_filter *filter = ref_cbdata->filter;
2046 struct ref_array_item *ref;
2047 struct commit *commit = NULL;
2050 if (flag & REF_BAD_NAME) {
2051 warning(_("ignoring ref with broken name %s"), refname);
2055 if (flag & REF_ISBROKEN) {
2056 warning(_("ignoring broken ref %s"), refname);
2060 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2061 kind = filter_ref_kind(filter, refname);
2062 if (!(kind & filter->kind))
2065 if (!filter_pattern_match(filter, refname))
2068 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2072 * A merge filter is applied on refs pointing to commits. Hence
2073 * obtain the commit using the 'oid' available and discard all
2074 * non-commits early. The actual filtering is done later.
2076 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2077 commit = lookup_commit_reference_gently(oid, 1);
2080 /* We perform the filtering for the '--contains' option... */
2081 if (filter->with_commit &&
2082 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2084 /* ...or for the `--no-contains' option */
2085 if (filter->no_commit &&
2086 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2091 * We do not open the object yet; sort may only need refname
2092 * to do its job and the resulting list may yet to be pruned
2093 * by maxcount logic.
2095 ref = ref_array_push(ref_cbdata->array, refname, oid);
2096 ref->commit = commit;
2103 /* Free memory allocated for a ref_array_item */
2104 static void free_array_item(struct ref_array_item *item)
2106 free((char *)item->symref);
2110 /* Free all memory allocated for ref_array */
2111 void ref_array_clear(struct ref_array *array)
2115 for (i = 0; i < array->nr; i++)
2116 free_array_item(array->items[i]);
2117 FREE_AND_NULL(array->items);
2118 array->nr = array->alloc = 0;
2121 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2123 struct rev_info revs;
2125 struct ref_filter *filter = ref_cbdata->filter;
2126 struct ref_array *array = ref_cbdata->array;
2127 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2129 init_revisions(&revs, NULL);
2131 for (i = 0; i < array->nr; i++) {
2132 struct ref_array_item *item = array->items[i];
2133 add_pending_object(&revs, &item->commit->object, item->refname);
2134 to_clear[i] = item->commit;
2137 filter->merge_commit->object.flags |= UNINTERESTING;
2138 add_pending_object(&revs, &filter->merge_commit->object, "");
2141 if (prepare_revision_walk(&revs))
2142 die(_("revision walk setup failed"));
2147 for (i = 0; i < old_nr; i++) {
2148 struct ref_array_item *item = array->items[i];
2149 struct commit *commit = item->commit;
2151 int is_merged = !!(commit->object.flags & UNINTERESTING);
2153 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2154 array->items[array->nr++] = array->items[i];
2156 free_array_item(item);
2159 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2160 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2165 * API for filtering a set of refs. Based on the type of refs the user
2166 * has requested, we iterate through those refs and apply filters
2167 * as per the given ref_filter structure and finally store the
2168 * filtered refs in the ref_array structure.
2170 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2172 struct ref_filter_cbdata ref_cbdata;
2174 unsigned int broken = 0;
2176 ref_cbdata.array = array;
2177 ref_cbdata.filter = filter;
2179 if (type & FILTER_REFS_INCLUDE_BROKEN)
2181 filter->kind = type & FILTER_REFS_KIND_MASK;
2183 init_contains_cache(&ref_cbdata.contains_cache);
2184 init_contains_cache(&ref_cbdata.no_contains_cache);
2186 /* Simple per-ref filtering */
2188 die("filter_refs: invalid type");
2191 * For common cases where we need only branches or remotes or tags,
2192 * we only iterate through those refs. If a mix of refs is needed,
2193 * we iterate over all refs and filter out required refs with the help
2194 * of filter_ref_kind().
2196 if (filter->kind == FILTER_REFS_BRANCHES)
2197 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2198 else if (filter->kind == FILTER_REFS_REMOTES)
2199 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2200 else if (filter->kind == FILTER_REFS_TAGS)
2201 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2202 else if (filter->kind & FILTER_REFS_ALL)
2203 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2204 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2205 head_ref(ref_filter_handler, &ref_cbdata);
2208 clear_contains_cache(&ref_cbdata.contains_cache);
2209 clear_contains_cache(&ref_cbdata.no_contains_cache);
2211 /* Filters that need revision walking */
2212 if (filter->merge_commit)
2213 do_merge_filter(&ref_cbdata);
2218 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2220 struct atom_value *va, *vb;
2222 cmp_type cmp_type = used_atom[s->atom].type;
2223 int (*cmp_fn)(const char *, const char *);
2224 struct strbuf err = STRBUF_INIT;
2226 if (get_ref_atom_value(a, s->atom, &va, &err))
2228 if (get_ref_atom_value(b, s->atom, &vb, &err))
2230 strbuf_release(&err);
2231 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2233 cmp = versioncmp(va->s, vb->s);
2234 else if (cmp_type == FIELD_STR)
2235 cmp = cmp_fn(va->s, vb->s);
2237 if (va->value < vb->value)
2239 else if (va->value == vb->value)
2240 cmp = cmp_fn(a->refname, b->refname);
2245 return (s->reverse) ? -cmp : cmp;
2248 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2250 struct ref_array_item *a = *((struct ref_array_item **)a_);
2251 struct ref_array_item *b = *((struct ref_array_item **)b_);
2252 struct ref_sorting *s;
2254 for (s = ref_sorting; s; s = s->next) {
2255 int cmp = cmp_ref_sorting(s, a, b);
2262 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2264 QSORT_S(array->items, array->nr, compare_refs, sorting);
2267 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2269 struct strbuf *s = &state->stack->output;
2271 while (*cp && (!ep || cp < ep)) {
2276 int ch = hex2chr(cp + 1);
2278 strbuf_addch(s, ch);
2284 strbuf_addch(s, *cp);
2289 int format_ref_array_item(struct ref_array_item *info,
2290 const struct ref_format *format,
2291 struct strbuf *final_buf,
2292 struct strbuf *error_buf)
2294 const char *cp, *sp, *ep;
2295 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2297 state.quote_style = format->quote_style;
2298 push_stack_element(&state.stack);
2300 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2301 struct atom_value *atomv;
2304 ep = strchr(sp, ')');
2306 append_literal(cp, sp, &state);
2307 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2308 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2309 atomv->handler(atomv, &state, error_buf)) {
2310 pop_stack_element(&state.stack);
2315 sp = cp + strlen(cp);
2316 append_literal(cp, sp, &state);
2318 if (format->need_color_reset_at_eol) {
2319 struct atom_value resetv;
2320 resetv.s = GIT_COLOR_RESET;
2321 if (append_atom(&resetv, &state, error_buf)) {
2322 pop_stack_element(&state.stack);
2326 if (state.stack->prev) {
2327 pop_stack_element(&state.stack);
2328 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2330 strbuf_addbuf(final_buf, &state.stack->output);
2331 pop_stack_element(&state.stack);
2335 void show_ref_array_item(struct ref_array_item *info,
2336 const struct ref_format *format)
2338 struct strbuf final_buf = STRBUF_INIT;
2339 struct strbuf error_buf = STRBUF_INIT;
2341 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2342 die("%s", error_buf.buf);
2343 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2344 strbuf_release(&error_buf);
2345 strbuf_release(&final_buf);
2349 void pretty_print_ref(const char *name, const struct object_id *oid,
2350 const struct ref_format *format)
2352 struct ref_array_item *ref_item;
2353 ref_item = new_ref_array_item(name, oid);
2354 ref_item->kind = ref_kind_from_refname(name);
2355 show_ref_array_item(ref_item, format);
2356 free_array_item(ref_item);
2359 static int parse_sorting_atom(const char *atom)
2362 * This parses an atom using a dummy ref_format, since we don't
2363 * actually care about the formatting details.
2365 struct ref_format dummy = REF_FORMAT_INIT;
2366 const char *end = atom + strlen(atom);
2367 struct strbuf err = STRBUF_INIT;
2368 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2371 strbuf_release(&err);
2375 /* If no sorting option is given, use refname to sort as default */
2376 struct ref_sorting *ref_default_sorting(void)
2378 static const char cstr_name[] = "refname";
2380 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2382 sorting->next = NULL;
2383 sorting->atom = parse_sorting_atom(cstr_name);
2387 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2389 struct ref_sorting *s;
2391 s = xcalloc(1, sizeof(*s));
2392 s->next = *sorting_tail;
2399 if (skip_prefix(arg, "version:", &arg) ||
2400 skip_prefix(arg, "v:", &arg))
2402 s->atom = parse_sorting_atom(arg);
2405 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2407 if (!arg) /* should --no-sort void the list ? */
2409 parse_ref_sorting(opt->value, arg);
2413 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2415 struct ref_filter *rf = opt->value;
2416 struct object_id oid;
2417 int no_merged = starts_with(opt->long_name, "no");
2421 return opterror(opt, "is incompatible with --merged", 0);
2423 return opterror(opt, "is incompatible with --no-merged", 0);
2427 rf->merge = no_merged
2428 ? REF_FILTER_MERGED_OMIT
2429 : REF_FILTER_MERGED_INCLUDE;
2431 if (get_oid(arg, &oid))
2432 die(_("malformed object name %s"), arg);
2434 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2435 if (!rf->merge_commit)
2436 return opterror(opt, "must point to a commit", 0);