3 #include "parse-options.h"
6 #include "object-store.h"
7 #include "repository.h"
13 #include "ref-filter.h"
16 #include "git-compat-util.h"
19 #include "wt-status.h"
20 #include "commit-slab.h"
21 #include "commit-graph.h"
22 #include "commit-reach.h"
24 static struct ref_msg {
28 const char *ahead_behind;
30 /* Untranslated plumbing messages: */
37 void setup_ref_filter_porcelain_msg(void)
39 msgs.gone = _("gone");
40 msgs.ahead = _("ahead %d");
41 msgs.behind = _("behind %d");
42 msgs.ahead_behind = _("ahead %d, behind %d");
45 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
46 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
47 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
55 cmp_status cmp_status;
57 unsigned int then_atom_seen : 1,
59 condition_satisfied : 1;
63 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
67 static struct expand_data {
69 enum object_type type;
72 struct object_id delta_base_oid;
75 struct object_info info;
79 * An atom is a valid field atom listed below, possibly prefixed with
80 * a "*" to denote deref_tag().
82 * We parse given format string and sort specifiers, and make a list
83 * of properties that we need to extract out of objects. ref_array_item
84 * structure will hold an array of values extracted that can be
85 * indexed with the "atom number", which is an index into this
88 static struct used_atom {
93 char color[COLOR_MAXLEN];
97 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
99 struct refname_atom refname;
100 unsigned int nobracket : 1, push : 1, push_remote : 1;
103 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
104 struct process_trailer_options trailer_opts;
108 cmp_status cmp_status;
112 enum { O_FULL, O_LENGTH, O_SHORT } option;
115 struct refname_atom refname;
119 static int used_atom_cnt, need_tagged, need_symref;
122 * Expand string, append it to strbuf *sb, then return error code ret.
123 * Allow to save few lines of code.
125 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
129 strbuf_vaddf(sb, fmt, ap);
134 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
135 const char *color_value, struct strbuf *err)
138 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
139 if (color_parse(color_value, atom->u.color) < 0)
140 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
143 * We check this after we've parsed the color, which lets us complain
144 * about syntactically bogus color names even if they won't be used.
146 if (!want_color(format->use_color))
147 color_parse("", atom->u.color);
151 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
152 const char *name, struct strbuf *err)
155 atom->option = R_NORMAL;
156 else if (!strcmp(arg, "short"))
157 atom->option = R_SHORT;
158 else if (skip_prefix(arg, "lstrip=", &arg) ||
159 skip_prefix(arg, "strip=", &arg)) {
160 atom->option = R_LSTRIP;
161 if (strtol_i(arg, 10, &atom->lstrip))
162 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
163 } else if (skip_prefix(arg, "rstrip=", &arg)) {
164 atom->option = R_RSTRIP;
165 if (strtol_i(arg, 10, &atom->rstrip))
166 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
168 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
172 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
173 const char *arg, struct strbuf *err)
175 struct string_list params = STRING_LIST_INIT_DUP;
178 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
179 atom->u.remote_ref.push = 1;
182 atom->u.remote_ref.option = RR_REF;
183 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
184 arg, atom->name, err);
187 atom->u.remote_ref.nobracket = 0;
188 string_list_split(¶ms, arg, ',', -1);
190 for (i = 0; i < params.nr; i++) {
191 const char *s = params.items[i].string;
193 if (!strcmp(s, "track"))
194 atom->u.remote_ref.option = RR_TRACK;
195 else if (!strcmp(s, "trackshort"))
196 atom->u.remote_ref.option = RR_TRACKSHORT;
197 else if (!strcmp(s, "nobracket"))
198 atom->u.remote_ref.nobracket = 1;
199 else if (!strcmp(s, "remotename")) {
200 atom->u.remote_ref.option = RR_REMOTE_NAME;
201 atom->u.remote_ref.push_remote = 1;
202 } else if (!strcmp(s, "remoteref")) {
203 atom->u.remote_ref.option = RR_REMOTE_REF;
204 atom->u.remote_ref.push_remote = 1;
206 atom->u.remote_ref.option = RR_REF;
207 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
208 arg, atom->name, err)) {
209 string_list_clear(¶ms, 0);
215 string_list_clear(¶ms, 0);
219 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
220 const char *arg, struct strbuf *err)
223 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
224 if (*atom->name == '*')
225 oi_deref.info.typep = &oi_deref.type;
227 oi.info.typep = &oi.type;
231 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
232 const char *arg, struct strbuf *err)
235 return strbuf_addf_ret(err, -1, _("%%(objectsize) does not take arguments"));
236 if (*atom->name == '*')
237 oi_deref.info.sizep = &oi_deref.size;
239 oi.info.sizep = &oi.size;
243 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
244 const char *arg, struct strbuf *err)
247 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
248 atom->u.contents.option = C_BODY_DEP;
252 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
253 const char *arg, struct strbuf *err)
256 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
257 atom->u.contents.option = C_SUB;
261 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
262 const char *arg, struct strbuf *err)
264 struct string_list params = STRING_LIST_INIT_DUP;
267 atom->u.contents.trailer_opts.no_divider = 1;
270 string_list_split(¶ms, arg, ',', -1);
271 for (i = 0; i < params.nr; i++) {
272 const char *s = params.items[i].string;
273 if (!strcmp(s, "unfold"))
274 atom->u.contents.trailer_opts.unfold = 1;
275 else if (!strcmp(s, "only"))
276 atom->u.contents.trailer_opts.only_trailers = 1;
278 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
279 string_list_clear(¶ms, 0);
284 atom->u.contents.option = C_TRAILERS;
285 string_list_clear(¶ms, 0);
289 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
290 const char *arg, struct strbuf *err)
293 atom->u.contents.option = C_BARE;
294 else if (!strcmp(arg, "body"))
295 atom->u.contents.option = C_BODY;
296 else if (!strcmp(arg, "signature"))
297 atom->u.contents.option = C_SIG;
298 else if (!strcmp(arg, "subject"))
299 atom->u.contents.option = C_SUB;
300 else if (skip_prefix(arg, "trailers", &arg)) {
301 skip_prefix(arg, ":", &arg);
302 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
304 } else if (skip_prefix(arg, "lines=", &arg)) {
305 atom->u.contents.option = C_LINES;
306 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
307 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
309 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
313 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
314 const char *arg, struct strbuf *err)
317 atom->u.objectname.option = O_FULL;
318 else if (!strcmp(arg, "short"))
319 atom->u.objectname.option = O_SHORT;
320 else if (skip_prefix(arg, "short=", &arg)) {
321 atom->u.objectname.option = O_LENGTH;
322 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
323 atom->u.objectname.length == 0)
324 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
325 if (atom->u.objectname.length < MINIMUM_ABBREV)
326 atom->u.objectname.length = MINIMUM_ABBREV;
328 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
332 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
333 const char *arg, struct strbuf *err)
335 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
338 static align_type parse_align_position(const char *s)
340 if (!strcmp(s, "right"))
342 else if (!strcmp(s, "middle"))
344 else if (!strcmp(s, "left"))
349 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
350 const char *arg, struct strbuf *err)
352 struct align *align = &atom->u.align;
353 struct string_list params = STRING_LIST_INIT_DUP;
355 unsigned int width = ~0U;
358 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
360 align->position = ALIGN_LEFT;
362 string_list_split(¶ms, arg, ',', -1);
363 for (i = 0; i < params.nr; i++) {
364 const char *s = params.items[i].string;
367 if (skip_prefix(s, "position=", &s)) {
368 position = parse_align_position(s);
370 strbuf_addf(err, _("unrecognized position:%s"), s);
371 string_list_clear(¶ms, 0);
374 align->position = position;
375 } else if (skip_prefix(s, "width=", &s)) {
376 if (strtoul_ui(s, 10, &width)) {
377 strbuf_addf(err, _("unrecognized width:%s"), s);
378 string_list_clear(¶ms, 0);
381 } else if (!strtoul_ui(s, 10, &width))
383 else if ((position = parse_align_position(s)) >= 0)
384 align->position = position;
386 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
387 string_list_clear(¶ms, 0);
393 string_list_clear(¶ms, 0);
394 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
396 align->width = width;
397 string_list_clear(¶ms, 0);
401 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
402 const char *arg, struct strbuf *err)
405 atom->u.if_then_else.cmp_status = COMPARE_NONE;
407 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
408 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
409 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
410 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
412 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
416 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
417 const char *arg, struct strbuf *unused_err)
419 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
427 int (*parser)(const struct ref_format *format, struct used_atom *atom,
428 const char *arg, struct strbuf *err);
430 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
431 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
432 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
433 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
434 { "tree", SOURCE_OBJ },
435 { "parent", SOURCE_OBJ },
436 { "numparent", SOURCE_OBJ, FIELD_ULONG },
437 { "object", SOURCE_OBJ },
438 { "type", SOURCE_OBJ },
439 { "tag", SOURCE_OBJ },
440 { "author", SOURCE_OBJ },
441 { "authorname", SOURCE_OBJ },
442 { "authoremail", SOURCE_OBJ },
443 { "authordate", SOURCE_OBJ, FIELD_TIME },
444 { "committer", SOURCE_OBJ },
445 { "committername", SOURCE_OBJ },
446 { "committeremail", SOURCE_OBJ },
447 { "committerdate", SOURCE_OBJ, FIELD_TIME },
448 { "tagger", SOURCE_OBJ },
449 { "taggername", SOURCE_OBJ },
450 { "taggeremail", SOURCE_OBJ },
451 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
452 { "creator", SOURCE_OBJ },
453 { "creatordate", SOURCE_OBJ, FIELD_TIME },
454 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
455 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
456 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
457 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
458 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
459 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
460 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
461 { "flag", SOURCE_NONE },
462 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
463 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
464 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
465 { "end", SOURCE_NONE },
466 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
467 { "then", SOURCE_NONE },
468 { "else", SOURCE_NONE },
471 #define REF_FORMATTING_STATE_INIT { 0, NULL }
473 struct ref_formatting_stack {
474 struct ref_formatting_stack *prev;
475 struct strbuf output;
476 void (*at_end)(struct ref_formatting_stack **stack);
480 struct ref_formatting_state {
482 struct ref_formatting_stack *stack;
487 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
489 uintmax_t value; /* used for sorting when not FIELD_STR */
490 struct used_atom *atom;
494 * Used to parse format string and sort specifiers
496 static int parse_ref_filter_atom(const struct ref_format *format,
497 const char *atom, const char *ep,
505 if (*sp == '*' && sp < ep)
508 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
509 (int)(ep-atom), atom);
511 /* Do we have the atom already used elsewhere? */
512 for (i = 0; i < used_atom_cnt; i++) {
513 int len = strlen(used_atom[i].name);
514 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
519 * If the atom name has a colon, strip it and everything after
520 * it off - it specifies the format for this entry, and
521 * shouldn't be used for checking against the valid_atom
524 arg = memchr(sp, ':', ep - sp);
525 atom_len = (arg ? arg : ep) - sp;
527 /* Is the atom a valid one? */
528 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
529 int len = strlen(valid_atom[i].name);
530 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
534 if (ARRAY_SIZE(valid_atom) <= i)
535 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
536 (int)(ep-atom), atom);
538 /* Add it in, including the deref prefix */
541 REALLOC_ARRAY(used_atom, used_atom_cnt);
542 used_atom[at].name = xmemdupz(atom, ep - atom);
543 used_atom[at].type = valid_atom[i].cmp_type;
544 used_atom[at].source = valid_atom[i].source;
545 if (used_atom[at].source == SOURCE_OBJ) {
547 oi_deref.info.contentp = &oi_deref.content;
549 oi.info.contentp = &oi.content;
552 arg = used_atom[at].name + (arg - atom) + 1;
555 * Treat empty sub-arguments list as NULL (i.e.,
556 * "%(atom:)" is equivalent to "%(atom)").
561 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
562 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
566 if (!strcmp(valid_atom[i].name, "symref"))
571 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
573 switch (quote_style) {
575 strbuf_addstr(s, str);
578 sq_quote_buf(s, str);
581 perl_quote_buf(s, str);
584 python_quote_buf(s, str);
587 tcl_quote_buf(s, str);
592 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
593 struct strbuf *unused_err)
596 * Quote formatting is only done when the stack has a single
597 * element. Otherwise quote formatting is done on the
598 * element's entire output strbuf when the %(end) atom is
601 if (!state->stack->prev)
602 quote_formatting(&state->stack->output, v->s, state->quote_style);
604 strbuf_addstr(&state->stack->output, v->s);
608 static void push_stack_element(struct ref_formatting_stack **stack)
610 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
612 strbuf_init(&s->output, 0);
617 static void pop_stack_element(struct ref_formatting_stack **stack)
619 struct ref_formatting_stack *current = *stack;
620 struct ref_formatting_stack *prev = current->prev;
623 strbuf_addbuf(&prev->output, ¤t->output);
624 strbuf_release(¤t->output);
629 static void end_align_handler(struct ref_formatting_stack **stack)
631 struct ref_formatting_stack *cur = *stack;
632 struct align *align = (struct align *)cur->at_end_data;
633 struct strbuf s = STRBUF_INIT;
635 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
636 strbuf_swap(&cur->output, &s);
640 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
641 struct strbuf *unused_err)
643 struct ref_formatting_stack *new_stack;
645 push_stack_element(&state->stack);
646 new_stack = state->stack;
647 new_stack->at_end = end_align_handler;
648 new_stack->at_end_data = &atomv->atom->u.align;
652 static void if_then_else_handler(struct ref_formatting_stack **stack)
654 struct ref_formatting_stack *cur = *stack;
655 struct ref_formatting_stack *prev = cur->prev;
656 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
658 if (!if_then_else->then_atom_seen)
659 die(_("format: %%(if) atom used without a %%(then) atom"));
661 if (if_then_else->else_atom_seen) {
663 * There is an %(else) atom: we need to drop one state from the
664 * stack, either the %(else) branch if the condition is satisfied, or
665 * the %(then) branch if it isn't.
667 if (if_then_else->condition_satisfied) {
668 strbuf_reset(&cur->output);
669 pop_stack_element(&cur);
671 strbuf_swap(&cur->output, &prev->output);
672 strbuf_reset(&cur->output);
673 pop_stack_element(&cur);
675 } else if (!if_then_else->condition_satisfied) {
677 * No %(else) atom: just drop the %(then) branch if the
678 * condition is not satisfied.
680 strbuf_reset(&cur->output);
687 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
688 struct strbuf *unused_err)
690 struct ref_formatting_stack *new_stack;
691 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
693 if_then_else->str = atomv->atom->u.if_then_else.str;
694 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
696 push_stack_element(&state->stack);
697 new_stack = state->stack;
698 new_stack->at_end = if_then_else_handler;
699 new_stack->at_end_data = if_then_else;
703 static int is_empty(const char *s)
713 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
716 struct ref_formatting_stack *cur = state->stack;
717 struct if_then_else *if_then_else = NULL;
719 if (cur->at_end == if_then_else_handler)
720 if_then_else = (struct if_then_else *)cur->at_end_data;
722 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
723 if (if_then_else->then_atom_seen)
724 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
725 if (if_then_else->else_atom_seen)
726 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
727 if_then_else->then_atom_seen = 1;
729 * If the 'equals' or 'notequals' attribute is used then
730 * perform the required comparison. If not, only non-empty
731 * strings satisfy the 'if' condition.
733 if (if_then_else->cmp_status == COMPARE_EQUAL) {
734 if (!strcmp(if_then_else->str, cur->output.buf))
735 if_then_else->condition_satisfied = 1;
736 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
737 if (strcmp(if_then_else->str, cur->output.buf))
738 if_then_else->condition_satisfied = 1;
739 } else if (cur->output.len && !is_empty(cur->output.buf))
740 if_then_else->condition_satisfied = 1;
741 strbuf_reset(&cur->output);
745 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
748 struct ref_formatting_stack *prev = state->stack;
749 struct if_then_else *if_then_else = NULL;
751 if (prev->at_end == if_then_else_handler)
752 if_then_else = (struct if_then_else *)prev->at_end_data;
754 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
755 if (!if_then_else->then_atom_seen)
756 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
757 if (if_then_else->else_atom_seen)
758 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
759 if_then_else->else_atom_seen = 1;
760 push_stack_element(&state->stack);
761 state->stack->at_end_data = prev->at_end_data;
762 state->stack->at_end = prev->at_end;
766 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
769 struct ref_formatting_stack *current = state->stack;
770 struct strbuf s = STRBUF_INIT;
772 if (!current->at_end)
773 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
774 current->at_end(&state->stack);
776 /* Stack may have been popped within at_end(), hence reset the current pointer */
777 current = state->stack;
780 * Perform quote formatting when the stack element is that of
781 * a supporting atom. If nested then perform quote formatting
782 * only on the topmost supporting atom.
784 if (!current->prev->prev) {
785 quote_formatting(&s, current->output.buf, state->quote_style);
786 strbuf_swap(¤t->output, &s);
789 pop_stack_element(&state->stack);
794 * In a format string, find the next occurrence of %(atom).
796 static const char *find_next(const char *cp)
801 * %( is the start of an atom;
802 * %% is a quoted per-cent.
806 else if (cp[1] == '%')
807 cp++; /* skip over two % */
808 /* otherwise this is a singleton, literal % */
816 * Make sure the format string is well formed, and parse out
819 int verify_ref_format(struct ref_format *format)
823 format->need_color_reset_at_eol = 0;
824 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
825 struct strbuf err = STRBUF_INIT;
826 const char *color, *ep = strchr(sp, ')');
830 return error(_("malformed format string %s"), sp);
831 /* sp points at "%(" and ep points at the closing ")" */
832 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
837 if (skip_prefix(used_atom[at].name, "color:", &color))
838 format->need_color_reset_at_eol = !!strcmp(color, "reset");
839 strbuf_release(&err);
841 if (format->need_color_reset_at_eol && !want_color(format->use_color))
842 format->need_color_reset_at_eol = 0;
846 static int grab_objectname(const char *name, const struct object_id *oid,
847 struct atom_value *v, struct used_atom *atom)
849 if (starts_with(name, "objectname")) {
850 if (atom->u.objectname.option == O_SHORT) {
851 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
853 } else if (atom->u.objectname.option == O_FULL) {
854 v->s = xstrdup(oid_to_hex(oid));
856 } else if (atom->u.objectname.option == O_LENGTH) {
857 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
860 BUG("unknown %%(objectname) option");
865 /* See grab_values */
866 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
870 for (i = 0; i < used_atom_cnt; i++) {
871 const char *name = used_atom[i].name;
872 struct atom_value *v = &val[i];
873 if (!!deref != (*name == '*'))
877 if (!strcmp(name, "objecttype"))
878 v->s = xstrdup(type_name(oi->type));
879 else if (!strcmp(name, "objectsize")) {
881 v->s = xstrfmt("%lu", oi->size);
884 grab_objectname(name, &oi->oid, v, &used_atom[i]);
888 /* See grab_values */
889 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
892 struct tag *tag = (struct tag *) obj;
894 for (i = 0; i < used_atom_cnt; i++) {
895 const char *name = used_atom[i].name;
896 struct atom_value *v = &val[i];
897 if (!!deref != (*name == '*'))
901 if (!strcmp(name, "tag"))
902 v->s = xstrdup(tag->tag);
903 else if (!strcmp(name, "type") && tag->tagged)
904 v->s = xstrdup(type_name(tag->tagged->type));
905 else if (!strcmp(name, "object") && tag->tagged)
906 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
910 /* See grab_values */
911 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
914 struct commit *commit = (struct commit *) obj;
916 for (i = 0; i < used_atom_cnt; i++) {
917 const char *name = used_atom[i].name;
918 struct atom_value *v = &val[i];
919 if (!!deref != (*name == '*'))
923 if (!strcmp(name, "tree")) {
924 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
926 else if (!strcmp(name, "numparent")) {
927 v->value = commit_list_count(commit->parents);
928 v->s = xstrfmt("%lu", (unsigned long)v->value);
930 else if (!strcmp(name, "parent")) {
931 struct commit_list *parents;
932 struct strbuf s = STRBUF_INIT;
933 for (parents = commit->parents; parents; parents = parents->next) {
934 struct commit *parent = parents->item;
935 if (parents != commit->parents)
936 strbuf_addch(&s, ' ');
937 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
939 v->s = strbuf_detach(&s, NULL);
944 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
948 if (!strncmp(buf, who, wholen) &&
950 return buf + wholen + 1;
951 eol = strchr(buf, '\n');
956 return ""; /* end of header */
962 static const char *copy_line(const char *buf)
964 const char *eol = strchrnul(buf, '\n');
965 return xmemdupz(buf, eol - buf);
968 static const char *copy_name(const char *buf)
971 for (cp = buf; *cp && *cp != '\n'; cp++) {
972 if (!strncmp(cp, " <", 2))
973 return xmemdupz(buf, cp - buf);
978 static const char *copy_email(const char *buf)
980 const char *email = strchr(buf, '<');
984 eoemail = strchr(email, '>');
987 return xmemdupz(email, eoemail + 1 - email);
990 static char *copy_subject(const char *buf, unsigned long len)
992 char *r = xmemdupz(buf, len);
995 for (i = 0; i < len; i++)
1002 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1004 const char *eoemail = strstr(buf, "> ");
1006 timestamp_t timestamp;
1008 struct date_mode date_mode = { DATE_NORMAL };
1009 const char *formatp;
1012 * We got here because atomname ends in "date" or "date<something>";
1013 * it's not possible that <something> is not ":<format>" because
1014 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1015 * ":" means no format is specified, and use the default.
1017 formatp = strchr(atomname, ':');
1018 if (formatp != NULL) {
1020 parse_date_format(formatp, &date_mode);
1025 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1026 if (timestamp == TIME_MAX)
1028 tz = strtol(zone, NULL, 10);
1029 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1031 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1032 v->value = timestamp;
1039 /* See grab_values */
1040 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1043 int wholen = strlen(who);
1044 const char *wholine = NULL;
1046 for (i = 0; i < used_atom_cnt; i++) {
1047 const char *name = used_atom[i].name;
1048 struct atom_value *v = &val[i];
1049 if (!!deref != (*name == '*'))
1053 if (strncmp(who, name, wholen))
1055 if (name[wholen] != 0 &&
1056 strcmp(name + wholen, "name") &&
1057 strcmp(name + wholen, "email") &&
1058 !starts_with(name + wholen, "date"))
1061 wholine = find_wholine(who, wholen, buf, sz);
1063 return; /* no point looking for it */
1064 if (name[wholen] == 0)
1065 v->s = copy_line(wholine);
1066 else if (!strcmp(name + wholen, "name"))
1067 v->s = copy_name(wholine);
1068 else if (!strcmp(name + wholen, "email"))
1069 v->s = copy_email(wholine);
1070 else if (starts_with(name + wholen, "date"))
1071 grab_date(wholine, v, name);
1075 * For a tag or a commit object, if "creator" or "creatordate" is
1076 * requested, do something special.
1078 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1079 return; /* "author" for commit object is not wanted */
1081 wholine = find_wholine(who, wholen, buf, sz);
1084 for (i = 0; i < used_atom_cnt; i++) {
1085 const char *name = used_atom[i].name;
1086 struct atom_value *v = &val[i];
1087 if (!!deref != (*name == '*'))
1092 if (starts_with(name, "creatordate"))
1093 grab_date(wholine, v, name);
1094 else if (!strcmp(name, "creator"))
1095 v->s = copy_line(wholine);
1099 static void find_subpos(const char *buf, unsigned long sz,
1100 const char **sub, unsigned long *sublen,
1101 const char **body, unsigned long *bodylen,
1102 unsigned long *nonsiglen,
1103 const char **sig, unsigned long *siglen)
1106 /* skip past header until we hit empty line */
1107 while (*buf && *buf != '\n') {
1108 eol = strchrnul(buf, '\n');
1113 /* skip any empty lines */
1114 while (*buf == '\n')
1117 /* parse signature first; we might not even have a subject line */
1118 *sig = buf + parse_signature(buf, strlen(buf));
1119 *siglen = strlen(*sig);
1121 /* subject is first non-empty line */
1123 /* subject goes to first empty line */
1124 while (buf < *sig && *buf && *buf != '\n') {
1125 eol = strchrnul(buf, '\n');
1130 *sublen = buf - *sub;
1131 /* drop trailing newline, if present */
1132 if (*sublen && (*sub)[*sublen - 1] == '\n')
1135 /* skip any empty lines */
1136 while (*buf == '\n')
1139 *bodylen = strlen(buf);
1140 *nonsiglen = *sig - buf;
1144 * If 'lines' is greater than 0, append that many lines from the given
1145 * 'buf' of length 'size' to the given strbuf.
1147 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1150 const char *sp, *eol;
1155 for (i = 0; i < lines && sp < buf + size; i++) {
1157 strbuf_addstr(out, "\n ");
1158 eol = memchr(sp, '\n', size - (sp - buf));
1159 len = eol ? eol - sp : size - (sp - buf);
1160 strbuf_add(out, sp, len);
1167 /* See grab_values */
1168 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1171 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1172 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1174 for (i = 0; i < used_atom_cnt; i++) {
1175 struct used_atom *atom = &used_atom[i];
1176 const char *name = atom->name;
1177 struct atom_value *v = &val[i];
1178 if (!!deref != (*name == '*'))
1182 if (strcmp(name, "subject") &&
1183 strcmp(name, "body") &&
1184 !starts_with(name, "trailers") &&
1185 !starts_with(name, "contents"))
1188 find_subpos(buf, sz,
1190 &bodypos, &bodylen, &nonsiglen,
1193 if (atom->u.contents.option == C_SUB)
1194 v->s = copy_subject(subpos, sublen);
1195 else if (atom->u.contents.option == C_BODY_DEP)
1196 v->s = xmemdupz(bodypos, bodylen);
1197 else if (atom->u.contents.option == C_BODY)
1198 v->s = xmemdupz(bodypos, nonsiglen);
1199 else if (atom->u.contents.option == C_SIG)
1200 v->s = xmemdupz(sigpos, siglen);
1201 else if (atom->u.contents.option == C_LINES) {
1202 struct strbuf s = STRBUF_INIT;
1203 const char *contents_end = bodylen + bodypos - siglen;
1205 /* Size is the length of the message after removing the signature */
1206 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1207 v->s = strbuf_detach(&s, NULL);
1208 } else if (atom->u.contents.option == C_TRAILERS) {
1209 struct strbuf s = STRBUF_INIT;
1211 /* Format the trailer info according to the trailer_opts given */
1212 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1214 v->s = strbuf_detach(&s, NULL);
1215 } else if (atom->u.contents.option == C_BARE)
1216 v->s = xstrdup(subpos);
1221 * We want to have empty print-string for field requests
1222 * that do not apply (e.g. "authordate" for a tag object)
1224 static void fill_missing_values(struct atom_value *val)
1227 for (i = 0; i < used_atom_cnt; i++) {
1228 struct atom_value *v = &val[i];
1235 * val is a list of atom_value to hold returned values. Extract
1236 * the values for atoms in used_atom array out of (obj, buf, sz).
1237 * when deref is false, (obj, buf, sz) is the object that is
1238 * pointed at by the ref itself; otherwise it is the object the
1239 * ref (which is a tag) refers to.
1241 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1243 switch (obj->type) {
1245 grab_tag_values(val, deref, obj, buf, sz);
1246 grab_sub_body_contents(val, deref, obj, buf, sz);
1247 grab_person("tagger", val, deref, obj, buf, sz);
1250 grab_commit_values(val, deref, obj, buf, sz);
1251 grab_sub_body_contents(val, deref, obj, buf, sz);
1252 grab_person("author", val, deref, obj, buf, sz);
1253 grab_person("committer", val, deref, obj, buf, sz);
1256 /* grab_tree_values(val, deref, obj, buf, sz); */
1259 /* grab_blob_values(val, deref, obj, buf, sz); */
1262 die("Eh? Object of type %d?", obj->type);
1266 static inline char *copy_advance(char *dst, const char *src)
1273 static const char *lstrip_ref_components(const char *refname, int len)
1275 long remaining = len;
1276 const char *start = xstrdup(refname);
1277 const char *to_free = start;
1281 const char *p = refname;
1283 /* Find total no of '/' separated path-components */
1284 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1287 * The number of components we need to strip is now
1288 * the total minus the components to be left (Plus one
1289 * because we count the number of '/', but the number
1290 * of components is one more than the no of '/').
1292 remaining = i + len + 1;
1295 while (remaining > 0) {
1298 free((char *)to_free);
1306 start = xstrdup(start);
1307 free((char *)to_free);
1311 static const char *rstrip_ref_components(const char *refname, int len)
1313 long remaining = len;
1314 const char *start = xstrdup(refname);
1315 const char *to_free = start;
1319 const char *p = refname;
1321 /* Find total no of '/' separated path-components */
1322 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1325 * The number of components we need to strip is now
1326 * the total minus the components to be left (Plus one
1327 * because we count the number of '/', but the number
1328 * of components is one more than the no of '/').
1330 remaining = i + len + 1;
1333 while (remaining-- > 0) {
1334 char *p = strrchr(start, '/');
1336 free((char *)to_free);
1344 static const char *show_ref(struct refname_atom *atom, const char *refname)
1346 if (atom->option == R_SHORT)
1347 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1348 else if (atom->option == R_LSTRIP)
1349 return lstrip_ref_components(refname, atom->lstrip);
1350 else if (atom->option == R_RSTRIP)
1351 return rstrip_ref_components(refname, atom->rstrip);
1353 return xstrdup(refname);
1356 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1357 struct branch *branch, const char **s)
1359 int num_ours, num_theirs;
1360 if (atom->u.remote_ref.option == RR_REF)
1361 *s = show_ref(&atom->u.remote_ref.refname, refname);
1362 else if (atom->u.remote_ref.option == RR_TRACK) {
1363 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1364 NULL, AHEAD_BEHIND_FULL) < 0) {
1365 *s = xstrdup(msgs.gone);
1366 } else if (!num_ours && !num_theirs)
1369 *s = xstrfmt(msgs.behind, num_theirs);
1370 else if (!num_theirs)
1371 *s = xstrfmt(msgs.ahead, num_ours);
1373 *s = xstrfmt(msgs.ahead_behind,
1374 num_ours, num_theirs);
1375 if (!atom->u.remote_ref.nobracket && *s[0]) {
1376 const char *to_free = *s;
1377 *s = xstrfmt("[%s]", *s);
1378 free((void *)to_free);
1380 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1381 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1382 NULL, AHEAD_BEHIND_FULL) < 0) {
1386 if (!num_ours && !num_theirs)
1390 else if (!num_theirs)
1394 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1396 const char *remote = atom->u.remote_ref.push ?
1397 pushremote_for_branch(branch, &explicit) :
1398 remote_for_branch(branch, &explicit);
1399 *s = xstrdup(explicit ? remote : "");
1400 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1404 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1406 *s = xstrdup(explicit ? merge : "");
1408 BUG("unhandled RR_* enum");
1411 char *get_head_description(void)
1413 struct strbuf desc = STRBUF_INIT;
1414 struct wt_status_state state;
1415 memset(&state, 0, sizeof(state));
1416 wt_status_get_state(&state, 1);
1417 if (state.rebase_in_progress ||
1418 state.rebase_interactive_in_progress) {
1420 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1423 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1424 state.detached_from);
1425 } else if (state.bisect_in_progress)
1426 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1428 else if (state.detached_from) {
1429 if (state.detached_at)
1431 * TRANSLATORS: make sure this matches "HEAD
1432 * detached at " in wt-status.c
1434 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1435 state.detached_from);
1438 * TRANSLATORS: make sure this matches "HEAD
1439 * detached from " in wt-status.c
1441 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1442 state.detached_from);
1445 strbuf_addstr(&desc, _("(no branch)"));
1448 free(state.detached_from);
1449 return strbuf_detach(&desc, NULL);
1452 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1457 return show_ref(&atom->u.refname, ref->symref);
1460 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1462 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1463 return get_head_description();
1464 return show_ref(&atom->u.refname, ref->refname);
1467 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1468 struct expand_data *oi, struct strbuf *err)
1470 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1472 if (oi->info.contentp) {
1473 /* We need to know that to use parse_object_buffer properly */
1474 oi->info.sizep = &oi->size;
1475 oi->info.typep = &oi->type;
1477 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1478 OBJECT_INFO_LOOKUP_REPLACE))
1479 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1480 oid_to_hex(&oi->oid), ref->refname);
1482 if (oi->info.contentp) {
1483 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1487 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1488 oid_to_hex(&oi->oid), ref->refname);
1490 grab_values(ref->value, deref, *obj, oi->content, oi->size);
1493 grab_common_values(ref->value, deref, oi);
1500 * Parse the object referred by ref, and grab needed value.
1502 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1506 struct object_info empty = OBJECT_INFO_INIT;
1508 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1510 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1511 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1514 ref->symref = xstrdup("");
1517 /* Fill in specials first */
1518 for (i = 0; i < used_atom_cnt; i++) {
1519 struct used_atom *atom = &used_atom[i];
1520 const char *name = used_atom[i].name;
1521 struct atom_value *v = &ref->value[i];
1523 const char *refname;
1524 struct branch *branch = NULL;
1526 v->handler = append_atom;
1534 if (starts_with(name, "refname"))
1535 refname = get_refname(atom, ref);
1536 else if (starts_with(name, "symref"))
1537 refname = get_symref(atom, ref);
1538 else if (starts_with(name, "upstream")) {
1539 const char *branch_name;
1540 /* only local branches may have an upstream */
1541 if (!skip_prefix(ref->refname, "refs/heads/",
1546 branch = branch_get(branch_name);
1548 refname = branch_get_upstream(branch, NULL);
1550 fill_remote_ref_details(atom, refname, branch, &v->s);
1554 } else if (atom->u.remote_ref.push) {
1555 const char *branch_name;
1557 if (!skip_prefix(ref->refname, "refs/heads/",
1560 branch = branch_get(branch_name);
1562 if (atom->u.remote_ref.push_remote)
1565 refname = branch_get_push(branch, NULL);
1569 /* We will definitely re-init v->s on the next line. */
1571 fill_remote_ref_details(atom, refname, branch, &v->s);
1573 } else if (starts_with(name, "color:")) {
1574 v->s = xstrdup(atom->u.color);
1576 } else if (!strcmp(name, "flag")) {
1577 char buf[256], *cp = buf;
1578 if (ref->flag & REF_ISSYMREF)
1579 cp = copy_advance(cp, ",symref");
1580 if (ref->flag & REF_ISPACKED)
1581 cp = copy_advance(cp, ",packed");
1586 v->s = xstrdup(buf + 1);
1589 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1591 } else if (!strcmp(name, "HEAD")) {
1592 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1593 v->s = xstrdup("*");
1595 v->s = xstrdup(" ");
1597 } else if (starts_with(name, "align")) {
1598 v->handler = align_atom_handler;
1601 } else if (!strcmp(name, "end")) {
1602 v->handler = end_atom_handler;
1605 } else if (starts_with(name, "if")) {
1607 if (skip_prefix(name, "if:", &s))
1611 v->handler = if_atom_handler;
1613 } else if (!strcmp(name, "then")) {
1614 v->handler = then_atom_handler;
1617 } else if (!strcmp(name, "else")) {
1618 v->handler = else_atom_handler;
1625 v->s = xstrdup(refname);
1627 v->s = xstrfmt("%s^{}", refname);
1628 free((char *)refname);
1631 for (i = 0; i < used_atom_cnt; i++) {
1632 struct atom_value *v = &ref->value[i];
1633 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1634 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1635 oid_to_hex(&ref->objectname), ref->refname);
1639 oi.info.contentp = &oi.content;
1640 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1641 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1645 oi.oid = ref->objectname;
1646 if (get_object(ref, 0, &obj, &oi, err))
1650 * If there is no atom that wants to know about tagged
1651 * object, we are done.
1653 if (!need_tagged || (obj->type != OBJ_TAG))
1657 * If it is a tag object, see if we use a value that derefs
1658 * the object, and if we do grab the object it refers to.
1660 oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1663 * NEEDSWORK: This derefs tag only once, which
1664 * is good to deal with chains of trust, but
1665 * is not consistent with what deref_tag() does
1666 * which peels the onion to the core.
1668 return get_object(ref, 1, &obj, &oi_deref, err);
1672 * Given a ref, return the value for the atom. This lazily gets value
1673 * out of the object by calling populate value.
1675 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1676 struct atom_value **v, struct strbuf *err)
1679 if (populate_value(ref, err))
1681 fill_missing_values(ref->value);
1683 *v = &ref->value[atom];
1688 * Return 1 if the refname matches one of the patterns, otherwise 0.
1689 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1690 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1691 * matches "refs/heads/mas*", too).
1693 static int match_pattern(const struct ref_filter *filter, const char *refname)
1695 const char **patterns = filter->name_patterns;
1698 if (filter->ignore_case)
1699 flags |= WM_CASEFOLD;
1702 * When no '--format' option is given we need to skip the prefix
1703 * for matching refs of tags and branches.
1705 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1706 skip_prefix(refname, "refs/heads/", &refname) ||
1707 skip_prefix(refname, "refs/remotes/", &refname) ||
1708 skip_prefix(refname, "refs/", &refname));
1710 for (; *patterns; patterns++) {
1711 if (!wildmatch(*patterns, refname, flags))
1718 * Return 1 if the refname matches one of the patterns, otherwise 0.
1719 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1720 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1721 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1723 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1725 const char **pattern = filter->name_patterns;
1726 int namelen = strlen(refname);
1727 unsigned flags = WM_PATHNAME;
1729 if (filter->ignore_case)
1730 flags |= WM_CASEFOLD;
1732 for (; *pattern; pattern++) {
1733 const char *p = *pattern;
1734 int plen = strlen(p);
1736 if ((plen <= namelen) &&
1737 !strncmp(refname, p, plen) &&
1738 (refname[plen] == '\0' ||
1739 refname[plen] == '/' ||
1742 if (!wildmatch(p, refname, flags))
1748 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1749 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1751 if (!*filter->name_patterns)
1752 return 1; /* No pattern always matches */
1753 if (filter->match_as_path)
1754 return match_name_as_path(filter, refname);
1755 return match_pattern(filter, refname);
1759 * Find the longest prefix of pattern we can pass to
1760 * `for_each_fullref_in()`, namely the part of pattern preceding the
1761 * first glob character. (Note that `for_each_fullref_in()` is
1762 * perfectly happy working with a prefix that doesn't end at a
1763 * pathname component boundary.)
1765 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1769 for (p = pattern; *p && !is_glob_special(*p); p++)
1772 strbuf_add(out, pattern, p - pattern);
1776 * This is the same as for_each_fullref_in(), but it tries to iterate
1777 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1778 * pattern match, so the callback still has to match each ref individually.
1780 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1785 struct strbuf prefix = STRBUF_INIT;
1788 if (!filter->match_as_path) {
1790 * in this case, the patterns are applied after
1791 * prefixes like "refs/heads/" etc. are stripped off,
1792 * so we have to look at everything:
1794 return for_each_fullref_in("", cb, cb_data, broken);
1797 if (filter->ignore_case) {
1799 * we can't handle case-insensitive comparisons,
1800 * so just return everything and let the caller
1803 return for_each_fullref_in("", cb, cb_data, broken);
1806 if (!filter->name_patterns[0]) {
1807 /* no patterns; we have to look at everything */
1808 return for_each_fullref_in("", cb, cb_data, broken);
1811 if (filter->name_patterns[1]) {
1813 * multiple patterns; in theory this could still work as long
1814 * as the patterns are disjoint. We'd just make multiple calls
1815 * to for_each_ref(). But if they're not disjoint, we'd end up
1816 * reporting the same ref multiple times. So let's punt on that
1819 return for_each_fullref_in("", cb, cb_data, broken);
1822 find_longest_prefix(&prefix, filter->name_patterns[0]);
1824 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1825 strbuf_release(&prefix);
1830 * Given a ref (sha1, refname), check if the ref belongs to the array
1831 * of sha1s. If the given ref is a tag, check if the given tag points
1832 * at one of the sha1s in the given sha1 array.
1833 * the given sha1_array.
1835 * 1. Only a single level of inderection is obtained, we might want to
1836 * change this to account for multiple levels (e.g. annotated tags
1837 * pointing to annotated tags pointing to a commit.)
1838 * 2. As the refs are cached we might know what refname peels to without
1839 * the need to parse the object via parse_object(). peel_ref() might be a
1840 * more efficient alternative to obtain the pointee.
1842 static const struct object_id *match_points_at(struct oid_array *points_at,
1843 const struct object_id *oid,
1844 const char *refname)
1846 const struct object_id *tagged_oid = NULL;
1849 if (oid_array_lookup(points_at, oid) >= 0)
1851 obj = parse_object(the_repository, oid);
1853 die(_("malformed object at '%s'"), refname);
1854 if (obj->type == OBJ_TAG)
1855 tagged_oid = &((struct tag *)obj)->tagged->oid;
1856 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1862 * Allocate space for a new ref_array_item and copy the name and oid to it.
1864 * Callers can then fill in other struct members at their leisure.
1866 static struct ref_array_item *new_ref_array_item(const char *refname,
1867 const struct object_id *oid)
1869 struct ref_array_item *ref;
1871 FLEX_ALLOC_STR(ref, refname, refname);
1872 oidcpy(&ref->objectname, oid);
1877 struct ref_array_item *ref_array_push(struct ref_array *array,
1878 const char *refname,
1879 const struct object_id *oid)
1881 struct ref_array_item *ref = new_ref_array_item(refname, oid);
1883 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1884 array->items[array->nr++] = ref;
1889 static int ref_kind_from_refname(const char *refname)
1897 { "refs/heads/" , FILTER_REFS_BRANCHES },
1898 { "refs/remotes/" , FILTER_REFS_REMOTES },
1899 { "refs/tags/", FILTER_REFS_TAGS}
1902 if (!strcmp(refname, "HEAD"))
1903 return FILTER_REFS_DETACHED_HEAD;
1905 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1906 if (starts_with(refname, ref_kind[i].prefix))
1907 return ref_kind[i].kind;
1910 return FILTER_REFS_OTHERS;
1913 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1915 if (filter->kind == FILTER_REFS_BRANCHES ||
1916 filter->kind == FILTER_REFS_REMOTES ||
1917 filter->kind == FILTER_REFS_TAGS)
1918 return filter->kind;
1919 return ref_kind_from_refname(refname);
1922 struct ref_filter_cbdata {
1923 struct ref_array *array;
1924 struct ref_filter *filter;
1925 struct contains_cache contains_cache;
1926 struct contains_cache no_contains_cache;
1930 * A call-back given to for_each_ref(). Filter refs and keep them for
1931 * later object processing.
1933 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1935 struct ref_filter_cbdata *ref_cbdata = cb_data;
1936 struct ref_filter *filter = ref_cbdata->filter;
1937 struct ref_array_item *ref;
1938 struct commit *commit = NULL;
1941 if (flag & REF_BAD_NAME) {
1942 warning(_("ignoring ref with broken name %s"), refname);
1946 if (flag & REF_ISBROKEN) {
1947 warning(_("ignoring broken ref %s"), refname);
1951 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1952 kind = filter_ref_kind(filter, refname);
1953 if (!(kind & filter->kind))
1956 if (!filter_pattern_match(filter, refname))
1959 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1963 * A merge filter is applied on refs pointing to commits. Hence
1964 * obtain the commit using the 'oid' available and discard all
1965 * non-commits early. The actual filtering is done later.
1967 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1968 commit = lookup_commit_reference_gently(the_repository, oid,
1972 /* We perform the filtering for the '--contains' option... */
1973 if (filter->with_commit &&
1974 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1976 /* ...or for the `--no-contains' option */
1977 if (filter->no_commit &&
1978 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1983 * We do not open the object yet; sort may only need refname
1984 * to do its job and the resulting list may yet to be pruned
1985 * by maxcount logic.
1987 ref = ref_array_push(ref_cbdata->array, refname, oid);
1988 ref->commit = commit;
1995 /* Free memory allocated for a ref_array_item */
1996 static void free_array_item(struct ref_array_item *item)
1998 free((char *)item->symref);
2000 free((char *)item->value->s);
2006 /* Free all memory allocated for ref_array */
2007 void ref_array_clear(struct ref_array *array)
2011 for (i = 0; i < used_atom_cnt; i++)
2012 free((char *)used_atom[i].name);
2013 FREE_AND_NULL(used_atom);
2015 for (i = 0; i < array->nr; i++)
2016 free_array_item(array->items[i]);
2017 FREE_AND_NULL(array->items);
2018 array->nr = array->alloc = 0;
2021 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2023 struct rev_info revs;
2025 struct ref_filter *filter = ref_cbdata->filter;
2026 struct ref_array *array = ref_cbdata->array;
2027 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2029 repo_init_revisions(the_repository, &revs, NULL);
2031 for (i = 0; i < array->nr; i++) {
2032 struct ref_array_item *item = array->items[i];
2033 add_pending_object(&revs, &item->commit->object, item->refname);
2034 to_clear[i] = item->commit;
2037 filter->merge_commit->object.flags |= UNINTERESTING;
2038 add_pending_object(&revs, &filter->merge_commit->object, "");
2041 if (prepare_revision_walk(&revs))
2042 die(_("revision walk setup failed"));
2047 for (i = 0; i < old_nr; i++) {
2048 struct ref_array_item *item = array->items[i];
2049 struct commit *commit = item->commit;
2051 int is_merged = !!(commit->object.flags & UNINTERESTING);
2053 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2054 array->items[array->nr++] = array->items[i];
2056 free_array_item(item);
2059 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2060 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2065 * API for filtering a set of refs. Based on the type of refs the user
2066 * has requested, we iterate through those refs and apply filters
2067 * as per the given ref_filter structure and finally store the
2068 * filtered refs in the ref_array structure.
2070 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2072 struct ref_filter_cbdata ref_cbdata;
2074 unsigned int broken = 0;
2076 ref_cbdata.array = array;
2077 ref_cbdata.filter = filter;
2079 if (type & FILTER_REFS_INCLUDE_BROKEN)
2081 filter->kind = type & FILTER_REFS_KIND_MASK;
2083 init_contains_cache(&ref_cbdata.contains_cache);
2084 init_contains_cache(&ref_cbdata.no_contains_cache);
2086 /* Simple per-ref filtering */
2088 die("filter_refs: invalid type");
2091 * For common cases where we need only branches or remotes or tags,
2092 * we only iterate through those refs. If a mix of refs is needed,
2093 * we iterate over all refs and filter out required refs with the help
2094 * of filter_ref_kind().
2096 if (filter->kind == FILTER_REFS_BRANCHES)
2097 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2098 else if (filter->kind == FILTER_REFS_REMOTES)
2099 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2100 else if (filter->kind == FILTER_REFS_TAGS)
2101 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2102 else if (filter->kind & FILTER_REFS_ALL)
2103 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2104 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2105 head_ref(ref_filter_handler, &ref_cbdata);
2108 clear_contains_cache(&ref_cbdata.contains_cache);
2109 clear_contains_cache(&ref_cbdata.no_contains_cache);
2111 /* Filters that need revision walking */
2112 if (filter->merge_commit)
2113 do_merge_filter(&ref_cbdata);
2118 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2120 struct atom_value *va, *vb;
2122 cmp_type cmp_type = used_atom[s->atom].type;
2123 int (*cmp_fn)(const char *, const char *);
2124 struct strbuf err = STRBUF_INIT;
2126 if (get_ref_atom_value(a, s->atom, &va, &err))
2128 if (get_ref_atom_value(b, s->atom, &vb, &err))
2130 strbuf_release(&err);
2131 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2133 cmp = versioncmp(va->s, vb->s);
2134 else if (cmp_type == FIELD_STR)
2135 cmp = cmp_fn(va->s, vb->s);
2137 if (va->value < vb->value)
2139 else if (va->value == vb->value)
2140 cmp = cmp_fn(a->refname, b->refname);
2145 return (s->reverse) ? -cmp : cmp;
2148 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2150 struct ref_array_item *a = *((struct ref_array_item **)a_);
2151 struct ref_array_item *b = *((struct ref_array_item **)b_);
2152 struct ref_sorting *s;
2154 for (s = ref_sorting; s; s = s->next) {
2155 int cmp = cmp_ref_sorting(s, a, b);
2162 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2164 QSORT_S(array->items, array->nr, compare_refs, sorting);
2167 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2169 struct strbuf *s = &state->stack->output;
2171 while (*cp && (!ep || cp < ep)) {
2176 int ch = hex2chr(cp + 1);
2178 strbuf_addch(s, ch);
2184 strbuf_addch(s, *cp);
2189 int format_ref_array_item(struct ref_array_item *info,
2190 const struct ref_format *format,
2191 struct strbuf *final_buf,
2192 struct strbuf *error_buf)
2194 const char *cp, *sp, *ep;
2195 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2197 state.quote_style = format->quote_style;
2198 push_stack_element(&state.stack);
2200 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2201 struct atom_value *atomv;
2204 ep = strchr(sp, ')');
2206 append_literal(cp, sp, &state);
2207 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2208 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2209 atomv->handler(atomv, &state, error_buf)) {
2210 pop_stack_element(&state.stack);
2215 sp = cp + strlen(cp);
2216 append_literal(cp, sp, &state);
2218 if (format->need_color_reset_at_eol) {
2219 struct atom_value resetv;
2220 resetv.s = GIT_COLOR_RESET;
2221 if (append_atom(&resetv, &state, error_buf)) {
2222 pop_stack_element(&state.stack);
2226 if (state.stack->prev) {
2227 pop_stack_element(&state.stack);
2228 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2230 strbuf_addbuf(final_buf, &state.stack->output);
2231 pop_stack_element(&state.stack);
2235 void show_ref_array_item(struct ref_array_item *info,
2236 const struct ref_format *format)
2238 struct strbuf final_buf = STRBUF_INIT;
2239 struct strbuf error_buf = STRBUF_INIT;
2241 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2242 die("%s", error_buf.buf);
2243 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2244 strbuf_release(&error_buf);
2245 strbuf_release(&final_buf);
2249 void pretty_print_ref(const char *name, const struct object_id *oid,
2250 const struct ref_format *format)
2252 struct ref_array_item *ref_item;
2253 ref_item = new_ref_array_item(name, oid);
2254 ref_item->kind = ref_kind_from_refname(name);
2255 show_ref_array_item(ref_item, format);
2256 free_array_item(ref_item);
2259 static int parse_sorting_atom(const char *atom)
2262 * This parses an atom using a dummy ref_format, since we don't
2263 * actually care about the formatting details.
2265 struct ref_format dummy = REF_FORMAT_INIT;
2266 const char *end = atom + strlen(atom);
2267 struct strbuf err = STRBUF_INIT;
2268 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2271 strbuf_release(&err);
2275 /* If no sorting option is given, use refname to sort as default */
2276 struct ref_sorting *ref_default_sorting(void)
2278 static const char cstr_name[] = "refname";
2280 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2282 sorting->next = NULL;
2283 sorting->atom = parse_sorting_atom(cstr_name);
2287 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2289 struct ref_sorting *s;
2291 s = xcalloc(1, sizeof(*s));
2292 s->next = *sorting_tail;
2299 if (skip_prefix(arg, "version:", &arg) ||
2300 skip_prefix(arg, "v:", &arg))
2302 s->atom = parse_sorting_atom(arg);
2305 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2307 if (!arg) /* should --no-sort void the list ? */
2309 parse_ref_sorting(opt->value, arg);
2313 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2315 struct ref_filter *rf = opt->value;
2316 struct object_id oid;
2317 int no_merged = starts_with(opt->long_name, "no");
2321 return opterror(opt, "is incompatible with --merged", 0);
2323 return opterror(opt, "is incompatible with --no-merged", 0);
2327 rf->merge = no_merged
2328 ? REF_FILTER_MERGED_OMIT
2329 : REF_FILTER_MERGED_INCLUDE;
2331 if (get_oid(arg, &oid))
2332 die(_("malformed object name %s"), arg);
2334 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2336 if (!rf->merge_commit)
2337 return opterror(opt, "must point to a commit", 0);