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 if (*atom->name == '*')
236 oi_deref.info.sizep = &oi_deref.size;
238 oi.info.sizep = &oi.size;
239 } else if (!strcmp(arg, "disk")) {
240 if (*atom->name == '*')
241 oi_deref.info.disk_sizep = &oi_deref.disk_size;
243 oi.info.disk_sizep = &oi.disk_size;
245 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
249 static int deltabase_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, _("%%(deltabase) does not take arguments"));
254 if (*atom->name == '*')
255 oi_deref.info.delta_base_sha1 = oi_deref.delta_base_oid.hash;
257 oi.info.delta_base_sha1 = oi.delta_base_oid.hash;
261 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
262 const char *arg, struct strbuf *err)
265 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
266 atom->u.contents.option = C_BODY_DEP;
270 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
271 const char *arg, struct strbuf *err)
274 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
275 atom->u.contents.option = C_SUB;
279 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
280 const char *arg, struct strbuf *err)
282 struct string_list params = STRING_LIST_INIT_DUP;
285 atom->u.contents.trailer_opts.no_divider = 1;
288 string_list_split(¶ms, arg, ',', -1);
289 for (i = 0; i < params.nr; i++) {
290 const char *s = params.items[i].string;
291 if (!strcmp(s, "unfold"))
292 atom->u.contents.trailer_opts.unfold = 1;
293 else if (!strcmp(s, "only"))
294 atom->u.contents.trailer_opts.only_trailers = 1;
296 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
297 string_list_clear(¶ms, 0);
302 atom->u.contents.option = C_TRAILERS;
303 string_list_clear(¶ms, 0);
307 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
308 const char *arg, struct strbuf *err)
311 atom->u.contents.option = C_BARE;
312 else if (!strcmp(arg, "body"))
313 atom->u.contents.option = C_BODY;
314 else if (!strcmp(arg, "signature"))
315 atom->u.contents.option = C_SIG;
316 else if (!strcmp(arg, "subject"))
317 atom->u.contents.option = C_SUB;
318 else if (skip_prefix(arg, "trailers", &arg)) {
319 skip_prefix(arg, ":", &arg);
320 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
322 } else if (skip_prefix(arg, "lines=", &arg)) {
323 atom->u.contents.option = C_LINES;
324 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
325 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
327 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
331 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
332 const char *arg, struct strbuf *err)
335 atom->u.objectname.option = O_FULL;
336 else if (!strcmp(arg, "short"))
337 atom->u.objectname.option = O_SHORT;
338 else if (skip_prefix(arg, "short=", &arg)) {
339 atom->u.objectname.option = O_LENGTH;
340 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
341 atom->u.objectname.length == 0)
342 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
343 if (atom->u.objectname.length < MINIMUM_ABBREV)
344 atom->u.objectname.length = MINIMUM_ABBREV;
346 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
350 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
351 const char *arg, struct strbuf *err)
353 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
356 static align_type parse_align_position(const char *s)
358 if (!strcmp(s, "right"))
360 else if (!strcmp(s, "middle"))
362 else if (!strcmp(s, "left"))
367 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
368 const char *arg, struct strbuf *err)
370 struct align *align = &atom->u.align;
371 struct string_list params = STRING_LIST_INIT_DUP;
373 unsigned int width = ~0U;
376 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
378 align->position = ALIGN_LEFT;
380 string_list_split(¶ms, arg, ',', -1);
381 for (i = 0; i < params.nr; i++) {
382 const char *s = params.items[i].string;
385 if (skip_prefix(s, "position=", &s)) {
386 position = parse_align_position(s);
388 strbuf_addf(err, _("unrecognized position:%s"), s);
389 string_list_clear(¶ms, 0);
392 align->position = position;
393 } else if (skip_prefix(s, "width=", &s)) {
394 if (strtoul_ui(s, 10, &width)) {
395 strbuf_addf(err, _("unrecognized width:%s"), s);
396 string_list_clear(¶ms, 0);
399 } else if (!strtoul_ui(s, 10, &width))
401 else if ((position = parse_align_position(s)) >= 0)
402 align->position = position;
404 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
405 string_list_clear(¶ms, 0);
411 string_list_clear(¶ms, 0);
412 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
414 align->width = width;
415 string_list_clear(¶ms, 0);
419 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
420 const char *arg, struct strbuf *err)
423 atom->u.if_then_else.cmp_status = COMPARE_NONE;
425 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
426 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
427 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
428 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
430 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
434 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
435 const char *arg, struct strbuf *unused_err)
437 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
445 int (*parser)(const struct ref_format *format, struct used_atom *atom,
446 const char *arg, struct strbuf *err);
448 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
449 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
450 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
451 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
452 { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
453 { "tree", SOURCE_OBJ },
454 { "parent", SOURCE_OBJ },
455 { "numparent", SOURCE_OBJ, FIELD_ULONG },
456 { "object", SOURCE_OBJ },
457 { "type", SOURCE_OBJ },
458 { "tag", SOURCE_OBJ },
459 { "author", SOURCE_OBJ },
460 { "authorname", SOURCE_OBJ },
461 { "authoremail", SOURCE_OBJ },
462 { "authordate", SOURCE_OBJ, FIELD_TIME },
463 { "committer", SOURCE_OBJ },
464 { "committername", SOURCE_OBJ },
465 { "committeremail", SOURCE_OBJ },
466 { "committerdate", SOURCE_OBJ, FIELD_TIME },
467 { "tagger", SOURCE_OBJ },
468 { "taggername", SOURCE_OBJ },
469 { "taggeremail", SOURCE_OBJ },
470 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
471 { "creator", SOURCE_OBJ },
472 { "creatordate", SOURCE_OBJ, FIELD_TIME },
473 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
474 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
475 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
476 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
477 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
478 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
479 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
480 { "flag", SOURCE_NONE },
481 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
482 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
483 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
484 { "end", SOURCE_NONE },
485 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
486 { "then", SOURCE_NONE },
487 { "else", SOURCE_NONE },
489 * Please update $__git_ref_fieldlist in git-completion.bash
490 * when you add new atoms
494 #define REF_FORMATTING_STATE_INIT { 0, NULL }
496 struct ref_formatting_stack {
497 struct ref_formatting_stack *prev;
498 struct strbuf output;
499 void (*at_end)(struct ref_formatting_stack **stack);
503 struct ref_formatting_state {
505 struct ref_formatting_stack *stack;
510 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
512 uintmax_t value; /* used for sorting when not FIELD_STR */
513 struct used_atom *atom;
517 * Used to parse format string and sort specifiers
519 static int parse_ref_filter_atom(const struct ref_format *format,
520 const char *atom, const char *ep,
528 if (*sp == '*' && sp < ep)
531 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
532 (int)(ep-atom), atom);
534 /* Do we have the atom already used elsewhere? */
535 for (i = 0; i < used_atom_cnt; i++) {
536 int len = strlen(used_atom[i].name);
537 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
542 * If the atom name has a colon, strip it and everything after
543 * it off - it specifies the format for this entry, and
544 * shouldn't be used for checking against the valid_atom
547 arg = memchr(sp, ':', ep - sp);
548 atom_len = (arg ? arg : ep) - sp;
550 /* Is the atom a valid one? */
551 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
552 int len = strlen(valid_atom[i].name);
553 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
557 if (ARRAY_SIZE(valid_atom) <= i)
558 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
559 (int)(ep-atom), atom);
560 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
561 return strbuf_addf_ret(err, -1,
562 _("not a git repository, but the field '%.*s' requires access to object data"),
563 (int)(ep-atom), atom);
565 /* Add it in, including the deref prefix */
568 REALLOC_ARRAY(used_atom, used_atom_cnt);
569 used_atom[at].name = xmemdupz(atom, ep - atom);
570 used_atom[at].type = valid_atom[i].cmp_type;
571 used_atom[at].source = valid_atom[i].source;
572 if (used_atom[at].source == SOURCE_OBJ) {
574 oi_deref.info.contentp = &oi_deref.content;
576 oi.info.contentp = &oi.content;
579 arg = used_atom[at].name + (arg - atom) + 1;
582 * Treat empty sub-arguments list as NULL (i.e.,
583 * "%(atom:)" is equivalent to "%(atom)").
588 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
589 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
593 if (!strcmp(valid_atom[i].name, "symref"))
598 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
600 switch (quote_style) {
602 strbuf_addstr(s, str);
605 sq_quote_buf(s, str);
608 perl_quote_buf(s, str);
611 python_quote_buf(s, str);
614 tcl_quote_buf(s, str);
619 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
620 struct strbuf *unused_err)
623 * Quote formatting is only done when the stack has a single
624 * element. Otherwise quote formatting is done on the
625 * element's entire output strbuf when the %(end) atom is
628 if (!state->stack->prev)
629 quote_formatting(&state->stack->output, v->s, state->quote_style);
631 strbuf_addstr(&state->stack->output, v->s);
635 static void push_stack_element(struct ref_formatting_stack **stack)
637 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
639 strbuf_init(&s->output, 0);
644 static void pop_stack_element(struct ref_formatting_stack **stack)
646 struct ref_formatting_stack *current = *stack;
647 struct ref_formatting_stack *prev = current->prev;
650 strbuf_addbuf(&prev->output, ¤t->output);
651 strbuf_release(¤t->output);
656 static void end_align_handler(struct ref_formatting_stack **stack)
658 struct ref_formatting_stack *cur = *stack;
659 struct align *align = (struct align *)cur->at_end_data;
660 struct strbuf s = STRBUF_INIT;
662 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
663 strbuf_swap(&cur->output, &s);
667 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
668 struct strbuf *unused_err)
670 struct ref_formatting_stack *new_stack;
672 push_stack_element(&state->stack);
673 new_stack = state->stack;
674 new_stack->at_end = end_align_handler;
675 new_stack->at_end_data = &atomv->atom->u.align;
679 static void if_then_else_handler(struct ref_formatting_stack **stack)
681 struct ref_formatting_stack *cur = *stack;
682 struct ref_formatting_stack *prev = cur->prev;
683 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
685 if (!if_then_else->then_atom_seen)
686 die(_("format: %%(if) atom used without a %%(then) atom"));
688 if (if_then_else->else_atom_seen) {
690 * There is an %(else) atom: we need to drop one state from the
691 * stack, either the %(else) branch if the condition is satisfied, or
692 * the %(then) branch if it isn't.
694 if (if_then_else->condition_satisfied) {
695 strbuf_reset(&cur->output);
696 pop_stack_element(&cur);
698 strbuf_swap(&cur->output, &prev->output);
699 strbuf_reset(&cur->output);
700 pop_stack_element(&cur);
702 } else if (!if_then_else->condition_satisfied) {
704 * No %(else) atom: just drop the %(then) branch if the
705 * condition is not satisfied.
707 strbuf_reset(&cur->output);
714 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
715 struct strbuf *unused_err)
717 struct ref_formatting_stack *new_stack;
718 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
720 if_then_else->str = atomv->atom->u.if_then_else.str;
721 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
723 push_stack_element(&state->stack);
724 new_stack = state->stack;
725 new_stack->at_end = if_then_else_handler;
726 new_stack->at_end_data = if_then_else;
730 static int is_empty(const char *s)
740 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
743 struct ref_formatting_stack *cur = state->stack;
744 struct if_then_else *if_then_else = NULL;
746 if (cur->at_end == if_then_else_handler)
747 if_then_else = (struct if_then_else *)cur->at_end_data;
749 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
750 if (if_then_else->then_atom_seen)
751 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
752 if (if_then_else->else_atom_seen)
753 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
754 if_then_else->then_atom_seen = 1;
756 * If the 'equals' or 'notequals' attribute is used then
757 * perform the required comparison. If not, only non-empty
758 * strings satisfy the 'if' condition.
760 if (if_then_else->cmp_status == COMPARE_EQUAL) {
761 if (!strcmp(if_then_else->str, cur->output.buf))
762 if_then_else->condition_satisfied = 1;
763 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
764 if (strcmp(if_then_else->str, cur->output.buf))
765 if_then_else->condition_satisfied = 1;
766 } else if (cur->output.len && !is_empty(cur->output.buf))
767 if_then_else->condition_satisfied = 1;
768 strbuf_reset(&cur->output);
772 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
775 struct ref_formatting_stack *prev = state->stack;
776 struct if_then_else *if_then_else = NULL;
778 if (prev->at_end == if_then_else_handler)
779 if_then_else = (struct if_then_else *)prev->at_end_data;
781 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
782 if (!if_then_else->then_atom_seen)
783 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
784 if (if_then_else->else_atom_seen)
785 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
786 if_then_else->else_atom_seen = 1;
787 push_stack_element(&state->stack);
788 state->stack->at_end_data = prev->at_end_data;
789 state->stack->at_end = prev->at_end;
793 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
796 struct ref_formatting_stack *current = state->stack;
797 struct strbuf s = STRBUF_INIT;
799 if (!current->at_end)
800 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
801 current->at_end(&state->stack);
803 /* Stack may have been popped within at_end(), hence reset the current pointer */
804 current = state->stack;
807 * Perform quote formatting when the stack element is that of
808 * a supporting atom. If nested then perform quote formatting
809 * only on the topmost supporting atom.
811 if (!current->prev->prev) {
812 quote_formatting(&s, current->output.buf, state->quote_style);
813 strbuf_swap(¤t->output, &s);
816 pop_stack_element(&state->stack);
821 * In a format string, find the next occurrence of %(atom).
823 static const char *find_next(const char *cp)
828 * %( is the start of an atom;
829 * %% is a quoted per-cent.
833 else if (cp[1] == '%')
834 cp++; /* skip over two % */
835 /* otherwise this is a singleton, literal % */
843 * Make sure the format string is well formed, and parse out
846 int verify_ref_format(struct ref_format *format)
850 format->need_color_reset_at_eol = 0;
851 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
852 struct strbuf err = STRBUF_INIT;
853 const char *color, *ep = strchr(sp, ')');
857 return error(_("malformed format string %s"), sp);
858 /* sp points at "%(" and ep points at the closing ")" */
859 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
864 if (skip_prefix(used_atom[at].name, "color:", &color))
865 format->need_color_reset_at_eol = !!strcmp(color, "reset");
866 strbuf_release(&err);
868 if (format->need_color_reset_at_eol && !want_color(format->use_color))
869 format->need_color_reset_at_eol = 0;
873 static int grab_objectname(const char *name, const struct object_id *oid,
874 struct atom_value *v, struct used_atom *atom)
876 if (starts_with(name, "objectname")) {
877 if (atom->u.objectname.option == O_SHORT) {
878 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
880 } else if (atom->u.objectname.option == O_FULL) {
881 v->s = xstrdup(oid_to_hex(oid));
883 } else if (atom->u.objectname.option == O_LENGTH) {
884 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
887 BUG("unknown %%(objectname) option");
892 /* See grab_values */
893 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
897 for (i = 0; i < used_atom_cnt; i++) {
898 const char *name = used_atom[i].name;
899 struct atom_value *v = &val[i];
900 if (!!deref != (*name == '*'))
904 if (!strcmp(name, "objecttype"))
905 v->s = xstrdup(type_name(oi->type));
906 else if (!strcmp(name, "objectsize:disk")) {
907 v->value = oi->disk_size;
908 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
909 } else if (!strcmp(name, "objectsize")) {
911 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
912 } else if (!strcmp(name, "deltabase"))
913 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
915 grab_objectname(name, &oi->oid, v, &used_atom[i]);
919 /* See grab_values */
920 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
923 struct tag *tag = (struct tag *) obj;
925 for (i = 0; i < used_atom_cnt; i++) {
926 const char *name = used_atom[i].name;
927 struct atom_value *v = &val[i];
928 if (!!deref != (*name == '*'))
932 if (!strcmp(name, "tag"))
933 v->s = xstrdup(tag->tag);
934 else if (!strcmp(name, "type") && tag->tagged)
935 v->s = xstrdup(type_name(tag->tagged->type));
936 else if (!strcmp(name, "object") && tag->tagged)
937 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
941 /* See grab_values */
942 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
945 struct commit *commit = (struct commit *) obj;
947 for (i = 0; i < used_atom_cnt; i++) {
948 const char *name = used_atom[i].name;
949 struct atom_value *v = &val[i];
950 if (!!deref != (*name == '*'))
954 if (!strcmp(name, "tree")) {
955 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
957 else if (!strcmp(name, "numparent")) {
958 v->value = commit_list_count(commit->parents);
959 v->s = xstrfmt("%lu", (unsigned long)v->value);
961 else if (!strcmp(name, "parent")) {
962 struct commit_list *parents;
963 struct strbuf s = STRBUF_INIT;
964 for (parents = commit->parents; parents; parents = parents->next) {
965 struct commit *parent = parents->item;
966 if (parents != commit->parents)
967 strbuf_addch(&s, ' ');
968 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
970 v->s = strbuf_detach(&s, NULL);
975 static const char *find_wholine(const char *who, int wholen, const char *buf)
979 if (!strncmp(buf, who, wholen) &&
981 return buf + wholen + 1;
982 eol = strchr(buf, '\n');
987 return ""; /* end of header */
993 static const char *copy_line(const char *buf)
995 const char *eol = strchrnul(buf, '\n');
996 return xmemdupz(buf, eol - buf);
999 static const char *copy_name(const char *buf)
1002 for (cp = buf; *cp && *cp != '\n'; cp++) {
1003 if (!strncmp(cp, " <", 2))
1004 return xmemdupz(buf, cp - buf);
1009 static const char *copy_email(const char *buf)
1011 const char *email = strchr(buf, '<');
1012 const char *eoemail;
1015 eoemail = strchr(email, '>');
1018 return xmemdupz(email, eoemail + 1 - email);
1021 static char *copy_subject(const char *buf, unsigned long len)
1023 char *r = xmemdupz(buf, len);
1026 for (i = 0; i < len; i++)
1033 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1035 const char *eoemail = strstr(buf, "> ");
1037 timestamp_t timestamp;
1039 struct date_mode date_mode = { DATE_NORMAL };
1040 const char *formatp;
1043 * We got here because atomname ends in "date" or "date<something>";
1044 * it's not possible that <something> is not ":<format>" because
1045 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1046 * ":" means no format is specified, and use the default.
1048 formatp = strchr(atomname, ':');
1049 if (formatp != NULL) {
1051 parse_date_format(formatp, &date_mode);
1056 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1057 if (timestamp == TIME_MAX)
1059 tz = strtol(zone, NULL, 10);
1060 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1062 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1063 v->value = timestamp;
1070 /* See grab_values */
1071 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1074 int wholen = strlen(who);
1075 const char *wholine = NULL;
1077 for (i = 0; i < used_atom_cnt; i++) {
1078 const char *name = used_atom[i].name;
1079 struct atom_value *v = &val[i];
1080 if (!!deref != (*name == '*'))
1084 if (strncmp(who, name, wholen))
1086 if (name[wholen] != 0 &&
1087 strcmp(name + wholen, "name") &&
1088 strcmp(name + wholen, "email") &&
1089 !starts_with(name + wholen, "date"))
1092 wholine = find_wholine(who, wholen, buf);
1094 return; /* no point looking for it */
1095 if (name[wholen] == 0)
1096 v->s = copy_line(wholine);
1097 else if (!strcmp(name + wholen, "name"))
1098 v->s = copy_name(wholine);
1099 else if (!strcmp(name + wholen, "email"))
1100 v->s = copy_email(wholine);
1101 else if (starts_with(name + wholen, "date"))
1102 grab_date(wholine, v, name);
1106 * For a tag or a commit object, if "creator" or "creatordate" is
1107 * requested, do something special.
1109 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1110 return; /* "author" for commit object is not wanted */
1112 wholine = find_wholine(who, wholen, buf);
1115 for (i = 0; i < used_atom_cnt; i++) {
1116 const char *name = used_atom[i].name;
1117 struct atom_value *v = &val[i];
1118 if (!!deref != (*name == '*'))
1123 if (starts_with(name, "creatordate"))
1124 grab_date(wholine, v, name);
1125 else if (!strcmp(name, "creator"))
1126 v->s = copy_line(wholine);
1130 static void find_subpos(const char *buf,
1131 const char **sub, unsigned long *sublen,
1132 const char **body, unsigned long *bodylen,
1133 unsigned long *nonsiglen,
1134 const char **sig, unsigned long *siglen)
1137 /* skip past header until we hit empty line */
1138 while (*buf && *buf != '\n') {
1139 eol = strchrnul(buf, '\n');
1144 /* skip any empty lines */
1145 while (*buf == '\n')
1148 /* parse signature first; we might not even have a subject line */
1149 *sig = buf + parse_signature(buf, strlen(buf));
1150 *siglen = strlen(*sig);
1152 /* subject is first non-empty line */
1154 /* subject goes to first empty line */
1155 while (buf < *sig && *buf && *buf != '\n') {
1156 eol = strchrnul(buf, '\n');
1161 *sublen = buf - *sub;
1162 /* drop trailing newline, if present */
1163 if (*sublen && (*sub)[*sublen - 1] == '\n')
1166 /* skip any empty lines */
1167 while (*buf == '\n')
1170 *bodylen = strlen(buf);
1171 *nonsiglen = *sig - buf;
1175 * If 'lines' is greater than 0, append that many lines from the given
1176 * 'buf' of length 'size' to the given strbuf.
1178 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1181 const char *sp, *eol;
1186 for (i = 0; i < lines && sp < buf + size; i++) {
1188 strbuf_addstr(out, "\n ");
1189 eol = memchr(sp, '\n', size - (sp - buf));
1190 len = eol ? eol - sp : size - (sp - buf);
1191 strbuf_add(out, sp, len);
1198 /* See grab_values */
1199 static void grab_sub_body_contents(struct atom_value *val, int deref, void *buf)
1202 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1203 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1205 for (i = 0; i < used_atom_cnt; i++) {
1206 struct used_atom *atom = &used_atom[i];
1207 const char *name = atom->name;
1208 struct atom_value *v = &val[i];
1209 if (!!deref != (*name == '*'))
1213 if (strcmp(name, "subject") &&
1214 strcmp(name, "body") &&
1215 !starts_with(name, "trailers") &&
1216 !starts_with(name, "contents"))
1221 &bodypos, &bodylen, &nonsiglen,
1224 if (atom->u.contents.option == C_SUB)
1225 v->s = copy_subject(subpos, sublen);
1226 else if (atom->u.contents.option == C_BODY_DEP)
1227 v->s = xmemdupz(bodypos, bodylen);
1228 else if (atom->u.contents.option == C_BODY)
1229 v->s = xmemdupz(bodypos, nonsiglen);
1230 else if (atom->u.contents.option == C_SIG)
1231 v->s = xmemdupz(sigpos, siglen);
1232 else if (atom->u.contents.option == C_LINES) {
1233 struct strbuf s = STRBUF_INIT;
1234 const char *contents_end = bodylen + bodypos - siglen;
1236 /* Size is the length of the message after removing the signature */
1237 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1238 v->s = strbuf_detach(&s, NULL);
1239 } else if (atom->u.contents.option == C_TRAILERS) {
1240 struct strbuf s = STRBUF_INIT;
1242 /* Format the trailer info according to the trailer_opts given */
1243 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1245 v->s = strbuf_detach(&s, NULL);
1246 } else if (atom->u.contents.option == C_BARE)
1247 v->s = xstrdup(subpos);
1252 * We want to have empty print-string for field requests
1253 * that do not apply (e.g. "authordate" for a tag object)
1255 static void fill_missing_values(struct atom_value *val)
1258 for (i = 0; i < used_atom_cnt; i++) {
1259 struct atom_value *v = &val[i];
1266 * val is a list of atom_value to hold returned values. Extract
1267 * the values for atoms in used_atom array out of (obj, buf, sz).
1268 * when deref is false, (obj, buf, sz) is the object that is
1269 * pointed at by the ref itself; otherwise it is the object the
1270 * ref (which is a tag) refers to.
1272 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf)
1274 switch (obj->type) {
1276 grab_tag_values(val, deref, obj);
1277 grab_sub_body_contents(val, deref, buf);
1278 grab_person("tagger", val, deref, buf);
1281 grab_commit_values(val, deref, obj);
1282 grab_sub_body_contents(val, deref, buf);
1283 grab_person("author", val, deref, buf);
1284 grab_person("committer", val, deref, buf);
1287 /* grab_tree_values(val, deref, obj, buf, sz); */
1290 /* grab_blob_values(val, deref, obj, buf, sz); */
1293 die("Eh? Object of type %d?", obj->type);
1297 static inline char *copy_advance(char *dst, const char *src)
1304 static const char *lstrip_ref_components(const char *refname, int len)
1306 long remaining = len;
1307 const char *start = xstrdup(refname);
1308 const char *to_free = start;
1312 const char *p = refname;
1314 /* Find total no of '/' separated path-components */
1315 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1318 * The number of components we need to strip is now
1319 * the total minus the components to be left (Plus one
1320 * because we count the number of '/', but the number
1321 * of components is one more than the no of '/').
1323 remaining = i + len + 1;
1326 while (remaining > 0) {
1329 free((char *)to_free);
1337 start = xstrdup(start);
1338 free((char *)to_free);
1342 static const char *rstrip_ref_components(const char *refname, int len)
1344 long remaining = len;
1345 const char *start = xstrdup(refname);
1346 const char *to_free = start;
1350 const char *p = refname;
1352 /* Find total no of '/' separated path-components */
1353 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1356 * The number of components we need to strip is now
1357 * the total minus the components to be left (Plus one
1358 * because we count the number of '/', but the number
1359 * of components is one more than the no of '/').
1361 remaining = i + len + 1;
1364 while (remaining-- > 0) {
1365 char *p = strrchr(start, '/');
1367 free((char *)to_free);
1375 static const char *show_ref(struct refname_atom *atom, const char *refname)
1377 if (atom->option == R_SHORT)
1378 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1379 else if (atom->option == R_LSTRIP)
1380 return lstrip_ref_components(refname, atom->lstrip);
1381 else if (atom->option == R_RSTRIP)
1382 return rstrip_ref_components(refname, atom->rstrip);
1384 return xstrdup(refname);
1387 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1388 struct branch *branch, const char **s)
1390 int num_ours, num_theirs;
1391 if (atom->u.remote_ref.option == RR_REF)
1392 *s = show_ref(&atom->u.remote_ref.refname, refname);
1393 else if (atom->u.remote_ref.option == RR_TRACK) {
1394 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1395 NULL, atom->u.remote_ref.push,
1396 AHEAD_BEHIND_FULL) < 0) {
1397 *s = xstrdup(msgs.gone);
1398 } else if (!num_ours && !num_theirs)
1401 *s = xstrfmt(msgs.behind, num_theirs);
1402 else if (!num_theirs)
1403 *s = xstrfmt(msgs.ahead, num_ours);
1405 *s = xstrfmt(msgs.ahead_behind,
1406 num_ours, num_theirs);
1407 if (!atom->u.remote_ref.nobracket && *s[0]) {
1408 const char *to_free = *s;
1409 *s = xstrfmt("[%s]", *s);
1410 free((void *)to_free);
1412 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1413 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1414 NULL, atom->u.remote_ref.push,
1415 AHEAD_BEHIND_FULL) < 0) {
1419 if (!num_ours && !num_theirs)
1423 else if (!num_theirs)
1427 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1429 const char *remote = atom->u.remote_ref.push ?
1430 pushremote_for_branch(branch, &explicit) :
1431 remote_for_branch(branch, &explicit);
1432 *s = xstrdup(explicit ? remote : "");
1433 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1437 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1439 *s = xstrdup(explicit ? merge : "");
1441 BUG("unhandled RR_* enum");
1444 char *get_head_description(void)
1446 struct strbuf desc = STRBUF_INIT;
1447 struct wt_status_state state;
1448 memset(&state, 0, sizeof(state));
1449 wt_status_get_state(the_repository, &state, 1);
1450 if (state.rebase_in_progress ||
1451 state.rebase_interactive_in_progress) {
1453 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1456 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1457 state.detached_from);
1458 } else if (state.bisect_in_progress)
1459 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1461 else if (state.detached_from) {
1462 if (state.detached_at)
1464 * TRANSLATORS: make sure this matches "HEAD
1465 * detached at " in wt-status.c
1467 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1468 state.detached_from);
1471 * TRANSLATORS: make sure this matches "HEAD
1472 * detached from " in wt-status.c
1474 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1475 state.detached_from);
1478 strbuf_addstr(&desc, _("(no branch)"));
1481 free(state.detached_from);
1482 return strbuf_detach(&desc, NULL);
1485 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1490 return show_ref(&atom->u.refname, ref->symref);
1493 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1495 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1496 return get_head_description();
1497 return show_ref(&atom->u.refname, ref->refname);
1500 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1501 struct expand_data *oi, struct strbuf *err)
1503 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1505 if (oi->info.contentp) {
1506 /* We need to know that to use parse_object_buffer properly */
1507 oi->info.sizep = &oi->size;
1508 oi->info.typep = &oi->type;
1510 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1511 OBJECT_INFO_LOOKUP_REPLACE))
1512 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1513 oid_to_hex(&oi->oid), ref->refname);
1514 if (oi->info.disk_sizep && oi->disk_size < 0)
1515 BUG("Object size is less than zero.");
1517 if (oi->info.contentp) {
1518 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1522 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1523 oid_to_hex(&oi->oid), ref->refname);
1525 grab_values(ref->value, deref, *obj, oi->content);
1528 grab_common_values(ref->value, deref, oi);
1535 * Parse the object referred by ref, and grab needed value.
1537 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1541 struct object_info empty = OBJECT_INFO_INIT;
1543 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1545 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1546 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1549 ref->symref = xstrdup("");
1552 /* Fill in specials first */
1553 for (i = 0; i < used_atom_cnt; i++) {
1554 struct used_atom *atom = &used_atom[i];
1555 const char *name = used_atom[i].name;
1556 struct atom_value *v = &ref->value[i];
1558 const char *refname;
1559 struct branch *branch = NULL;
1561 v->handler = append_atom;
1569 if (starts_with(name, "refname"))
1570 refname = get_refname(atom, ref);
1571 else if (starts_with(name, "symref"))
1572 refname = get_symref(atom, ref);
1573 else if (starts_with(name, "upstream")) {
1574 const char *branch_name;
1575 /* only local branches may have an upstream */
1576 if (!skip_prefix(ref->refname, "refs/heads/",
1581 branch = branch_get(branch_name);
1583 refname = branch_get_upstream(branch, NULL);
1585 fill_remote_ref_details(atom, refname, branch, &v->s);
1589 } else if (atom->u.remote_ref.push) {
1590 const char *branch_name;
1592 if (!skip_prefix(ref->refname, "refs/heads/",
1595 branch = branch_get(branch_name);
1597 if (atom->u.remote_ref.push_remote)
1600 refname = branch_get_push(branch, NULL);
1604 /* We will definitely re-init v->s on the next line. */
1606 fill_remote_ref_details(atom, refname, branch, &v->s);
1608 } else if (starts_with(name, "color:")) {
1609 v->s = xstrdup(atom->u.color);
1611 } else if (!strcmp(name, "flag")) {
1612 char buf[256], *cp = buf;
1613 if (ref->flag & REF_ISSYMREF)
1614 cp = copy_advance(cp, ",symref");
1615 if (ref->flag & REF_ISPACKED)
1616 cp = copy_advance(cp, ",packed");
1621 v->s = xstrdup(buf + 1);
1624 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1626 } else if (!strcmp(name, "HEAD")) {
1627 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1628 v->s = xstrdup("*");
1630 v->s = xstrdup(" ");
1632 } else if (starts_with(name, "align")) {
1633 v->handler = align_atom_handler;
1636 } else if (!strcmp(name, "end")) {
1637 v->handler = end_atom_handler;
1640 } else if (starts_with(name, "if")) {
1642 if (skip_prefix(name, "if:", &s))
1646 v->handler = if_atom_handler;
1648 } else if (!strcmp(name, "then")) {
1649 v->handler = then_atom_handler;
1652 } else if (!strcmp(name, "else")) {
1653 v->handler = else_atom_handler;
1660 v->s = xstrdup(refname);
1662 v->s = xstrfmt("%s^{}", refname);
1663 free((char *)refname);
1666 for (i = 0; i < used_atom_cnt; i++) {
1667 struct atom_value *v = &ref->value[i];
1668 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1669 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1670 oid_to_hex(&ref->objectname), ref->refname);
1674 oi.info.contentp = &oi.content;
1675 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1676 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1680 oi.oid = ref->objectname;
1681 if (get_object(ref, 0, &obj, &oi, err))
1685 * If there is no atom that wants to know about tagged
1686 * object, we are done.
1688 if (!need_tagged || (obj->type != OBJ_TAG))
1692 * If it is a tag object, see if we use a value that derefs
1693 * the object, and if we do grab the object it refers to.
1695 oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1698 * NEEDSWORK: This derefs tag only once, which
1699 * is good to deal with chains of trust, but
1700 * is not consistent with what deref_tag() does
1701 * which peels the onion to the core.
1703 return get_object(ref, 1, &obj, &oi_deref, err);
1707 * Given a ref, return the value for the atom. This lazily gets value
1708 * out of the object by calling populate value.
1710 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1711 struct atom_value **v, struct strbuf *err)
1714 if (populate_value(ref, err))
1716 fill_missing_values(ref->value);
1718 *v = &ref->value[atom];
1723 * Return 1 if the refname matches one of the patterns, otherwise 0.
1724 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1725 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1726 * matches "refs/heads/mas*", too).
1728 static int match_pattern(const struct ref_filter *filter, const char *refname)
1730 const char **patterns = filter->name_patterns;
1733 if (filter->ignore_case)
1734 flags |= WM_CASEFOLD;
1737 * When no '--format' option is given we need to skip the prefix
1738 * for matching refs of tags and branches.
1740 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1741 skip_prefix(refname, "refs/heads/", &refname) ||
1742 skip_prefix(refname, "refs/remotes/", &refname) ||
1743 skip_prefix(refname, "refs/", &refname));
1745 for (; *patterns; patterns++) {
1746 if (!wildmatch(*patterns, refname, flags))
1753 * Return 1 if the refname matches one of the patterns, otherwise 0.
1754 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1755 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1756 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1758 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1760 const char **pattern = filter->name_patterns;
1761 int namelen = strlen(refname);
1762 unsigned flags = WM_PATHNAME;
1764 if (filter->ignore_case)
1765 flags |= WM_CASEFOLD;
1767 for (; *pattern; pattern++) {
1768 const char *p = *pattern;
1769 int plen = strlen(p);
1771 if ((plen <= namelen) &&
1772 !strncmp(refname, p, plen) &&
1773 (refname[plen] == '\0' ||
1774 refname[plen] == '/' ||
1777 if (!wildmatch(p, refname, flags))
1783 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1784 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1786 if (!*filter->name_patterns)
1787 return 1; /* No pattern always matches */
1788 if (filter->match_as_path)
1789 return match_name_as_path(filter, refname);
1790 return match_pattern(filter, refname);
1794 * Find the longest prefix of pattern we can pass to
1795 * `for_each_fullref_in()`, namely the part of pattern preceding the
1796 * first glob character. (Note that `for_each_fullref_in()` is
1797 * perfectly happy working with a prefix that doesn't end at a
1798 * pathname component boundary.)
1800 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1804 for (p = pattern; *p && !is_glob_special(*p); p++)
1807 strbuf_add(out, pattern, p - pattern);
1811 * This is the same as for_each_fullref_in(), but it tries to iterate
1812 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1813 * pattern match, so the callback still has to match each ref individually.
1815 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1820 struct strbuf prefix = STRBUF_INIT;
1823 if (!filter->match_as_path) {
1825 * in this case, the patterns are applied after
1826 * prefixes like "refs/heads/" etc. are stripped off,
1827 * so we have to look at everything:
1829 return for_each_fullref_in("", cb, cb_data, broken);
1832 if (filter->ignore_case) {
1834 * we can't handle case-insensitive comparisons,
1835 * so just return everything and let the caller
1838 return for_each_fullref_in("", cb, cb_data, broken);
1841 if (!filter->name_patterns[0]) {
1842 /* no patterns; we have to look at everything */
1843 return for_each_fullref_in("", cb, cb_data, broken);
1846 if (filter->name_patterns[1]) {
1848 * multiple patterns; in theory this could still work as long
1849 * as the patterns are disjoint. We'd just make multiple calls
1850 * to for_each_ref(). But if they're not disjoint, we'd end up
1851 * reporting the same ref multiple times. So let's punt on that
1854 return for_each_fullref_in("", cb, cb_data, broken);
1857 find_longest_prefix(&prefix, filter->name_patterns[0]);
1859 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1860 strbuf_release(&prefix);
1865 * Given a ref (sha1, refname), check if the ref belongs to the array
1866 * of sha1s. If the given ref is a tag, check if the given tag points
1867 * at one of the sha1s in the given sha1 array.
1868 * the given sha1_array.
1870 * 1. Only a single level of inderection is obtained, we might want to
1871 * change this to account for multiple levels (e.g. annotated tags
1872 * pointing to annotated tags pointing to a commit.)
1873 * 2. As the refs are cached we might know what refname peels to without
1874 * the need to parse the object via parse_object(). peel_ref() might be a
1875 * more efficient alternative to obtain the pointee.
1877 static const struct object_id *match_points_at(struct oid_array *points_at,
1878 const struct object_id *oid,
1879 const char *refname)
1881 const struct object_id *tagged_oid = NULL;
1884 if (oid_array_lookup(points_at, oid) >= 0)
1886 obj = parse_object(the_repository, oid);
1888 die(_("malformed object at '%s'"), refname);
1889 if (obj->type == OBJ_TAG)
1890 tagged_oid = &((struct tag *)obj)->tagged->oid;
1891 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1897 * Allocate space for a new ref_array_item and copy the name and oid to it.
1899 * Callers can then fill in other struct members at their leisure.
1901 static struct ref_array_item *new_ref_array_item(const char *refname,
1902 const struct object_id *oid)
1904 struct ref_array_item *ref;
1906 FLEX_ALLOC_STR(ref, refname, refname);
1907 oidcpy(&ref->objectname, oid);
1912 struct ref_array_item *ref_array_push(struct ref_array *array,
1913 const char *refname,
1914 const struct object_id *oid)
1916 struct ref_array_item *ref = new_ref_array_item(refname, oid);
1918 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1919 array->items[array->nr++] = ref;
1924 static int ref_kind_from_refname(const char *refname)
1932 { "refs/heads/" , FILTER_REFS_BRANCHES },
1933 { "refs/remotes/" , FILTER_REFS_REMOTES },
1934 { "refs/tags/", FILTER_REFS_TAGS}
1937 if (!strcmp(refname, "HEAD"))
1938 return FILTER_REFS_DETACHED_HEAD;
1940 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1941 if (starts_with(refname, ref_kind[i].prefix))
1942 return ref_kind[i].kind;
1945 return FILTER_REFS_OTHERS;
1948 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1950 if (filter->kind == FILTER_REFS_BRANCHES ||
1951 filter->kind == FILTER_REFS_REMOTES ||
1952 filter->kind == FILTER_REFS_TAGS)
1953 return filter->kind;
1954 return ref_kind_from_refname(refname);
1957 struct ref_filter_cbdata {
1958 struct ref_array *array;
1959 struct ref_filter *filter;
1960 struct contains_cache contains_cache;
1961 struct contains_cache no_contains_cache;
1965 * A call-back given to for_each_ref(). Filter refs and keep them for
1966 * later object processing.
1968 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1970 struct ref_filter_cbdata *ref_cbdata = cb_data;
1971 struct ref_filter *filter = ref_cbdata->filter;
1972 struct ref_array_item *ref;
1973 struct commit *commit = NULL;
1976 if (flag & REF_BAD_NAME) {
1977 warning(_("ignoring ref with broken name %s"), refname);
1981 if (flag & REF_ISBROKEN) {
1982 warning(_("ignoring broken ref %s"), refname);
1986 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1987 kind = filter_ref_kind(filter, refname);
1988 if (!(kind & filter->kind))
1991 if (!filter_pattern_match(filter, refname))
1994 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1998 * A merge filter is applied on refs pointing to commits. Hence
1999 * obtain the commit using the 'oid' available and discard all
2000 * non-commits early. The actual filtering is done later.
2002 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2003 commit = lookup_commit_reference_gently(the_repository, oid,
2007 /* We perform the filtering for the '--contains' option... */
2008 if (filter->with_commit &&
2009 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2011 /* ...or for the `--no-contains' option */
2012 if (filter->no_commit &&
2013 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2018 * We do not open the object yet; sort may only need refname
2019 * to do its job and the resulting list may yet to be pruned
2020 * by maxcount logic.
2022 ref = ref_array_push(ref_cbdata->array, refname, oid);
2023 ref->commit = commit;
2030 /* Free memory allocated for a ref_array_item */
2031 static void free_array_item(struct ref_array_item *item)
2033 free((char *)item->symref);
2035 free((char *)item->value->s);
2041 /* Free all memory allocated for ref_array */
2042 void ref_array_clear(struct ref_array *array)
2046 for (i = 0; i < used_atom_cnt; i++)
2047 free((char *)used_atom[i].name);
2048 FREE_AND_NULL(used_atom);
2050 for (i = 0; i < array->nr; i++)
2051 free_array_item(array->items[i]);
2052 FREE_AND_NULL(array->items);
2053 array->nr = array->alloc = 0;
2056 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2058 struct rev_info revs;
2060 struct ref_filter *filter = ref_cbdata->filter;
2061 struct ref_array *array = ref_cbdata->array;
2062 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2064 repo_init_revisions(the_repository, &revs, NULL);
2066 for (i = 0; i < array->nr; i++) {
2067 struct ref_array_item *item = array->items[i];
2068 add_pending_object(&revs, &item->commit->object, item->refname);
2069 to_clear[i] = item->commit;
2072 filter->merge_commit->object.flags |= UNINTERESTING;
2073 add_pending_object(&revs, &filter->merge_commit->object, "");
2076 if (prepare_revision_walk(&revs))
2077 die(_("revision walk setup failed"));
2082 for (i = 0; i < old_nr; i++) {
2083 struct ref_array_item *item = array->items[i];
2084 struct commit *commit = item->commit;
2086 int is_merged = !!(commit->object.flags & UNINTERESTING);
2088 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2089 array->items[array->nr++] = array->items[i];
2091 free_array_item(item);
2094 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2095 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2100 * API for filtering a set of refs. Based on the type of refs the user
2101 * has requested, we iterate through those refs and apply filters
2102 * as per the given ref_filter structure and finally store the
2103 * filtered refs in the ref_array structure.
2105 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2107 struct ref_filter_cbdata ref_cbdata;
2109 unsigned int broken = 0;
2111 ref_cbdata.array = array;
2112 ref_cbdata.filter = filter;
2114 if (type & FILTER_REFS_INCLUDE_BROKEN)
2116 filter->kind = type & FILTER_REFS_KIND_MASK;
2118 init_contains_cache(&ref_cbdata.contains_cache);
2119 init_contains_cache(&ref_cbdata.no_contains_cache);
2121 /* Simple per-ref filtering */
2123 die("filter_refs: invalid type");
2126 * For common cases where we need only branches or remotes or tags,
2127 * we only iterate through those refs. If a mix of refs is needed,
2128 * we iterate over all refs and filter out required refs with the help
2129 * of filter_ref_kind().
2131 if (filter->kind == FILTER_REFS_BRANCHES)
2132 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2133 else if (filter->kind == FILTER_REFS_REMOTES)
2134 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2135 else if (filter->kind == FILTER_REFS_TAGS)
2136 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2137 else if (filter->kind & FILTER_REFS_ALL)
2138 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2139 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2140 head_ref(ref_filter_handler, &ref_cbdata);
2143 clear_contains_cache(&ref_cbdata.contains_cache);
2144 clear_contains_cache(&ref_cbdata.no_contains_cache);
2146 /* Filters that need revision walking */
2147 if (filter->merge_commit)
2148 do_merge_filter(&ref_cbdata);
2153 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2155 struct atom_value *va, *vb;
2157 cmp_type cmp_type = used_atom[s->atom].type;
2158 int (*cmp_fn)(const char *, const char *);
2159 struct strbuf err = STRBUF_INIT;
2161 if (get_ref_atom_value(a, s->atom, &va, &err))
2163 if (get_ref_atom_value(b, s->atom, &vb, &err))
2165 strbuf_release(&err);
2166 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2168 cmp = versioncmp(va->s, vb->s);
2169 else if (cmp_type == FIELD_STR)
2170 cmp = cmp_fn(va->s, vb->s);
2172 if (va->value < vb->value)
2174 else if (va->value == vb->value)
2175 cmp = cmp_fn(a->refname, b->refname);
2180 return (s->reverse) ? -cmp : cmp;
2183 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2185 struct ref_array_item *a = *((struct ref_array_item **)a_);
2186 struct ref_array_item *b = *((struct ref_array_item **)b_);
2187 struct ref_sorting *s;
2189 for (s = ref_sorting; s; s = s->next) {
2190 int cmp = cmp_ref_sorting(s, a, b);
2197 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2199 QSORT_S(array->items, array->nr, compare_refs, sorting);
2202 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2204 struct strbuf *s = &state->stack->output;
2206 while (*cp && (!ep || cp < ep)) {
2211 int ch = hex2chr(cp + 1);
2213 strbuf_addch(s, ch);
2219 strbuf_addch(s, *cp);
2224 int format_ref_array_item(struct ref_array_item *info,
2225 const struct ref_format *format,
2226 struct strbuf *final_buf,
2227 struct strbuf *error_buf)
2229 const char *cp, *sp, *ep;
2230 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2232 state.quote_style = format->quote_style;
2233 push_stack_element(&state.stack);
2235 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2236 struct atom_value *atomv;
2239 ep = strchr(sp, ')');
2241 append_literal(cp, sp, &state);
2242 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2243 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2244 atomv->handler(atomv, &state, error_buf)) {
2245 pop_stack_element(&state.stack);
2250 sp = cp + strlen(cp);
2251 append_literal(cp, sp, &state);
2253 if (format->need_color_reset_at_eol) {
2254 struct atom_value resetv;
2255 resetv.s = GIT_COLOR_RESET;
2256 if (append_atom(&resetv, &state, error_buf)) {
2257 pop_stack_element(&state.stack);
2261 if (state.stack->prev) {
2262 pop_stack_element(&state.stack);
2263 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2265 strbuf_addbuf(final_buf, &state.stack->output);
2266 pop_stack_element(&state.stack);
2270 void show_ref_array_item(struct ref_array_item *info,
2271 const struct ref_format *format)
2273 struct strbuf final_buf = STRBUF_INIT;
2274 struct strbuf error_buf = STRBUF_INIT;
2276 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2277 die("%s", error_buf.buf);
2278 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2279 strbuf_release(&error_buf);
2280 strbuf_release(&final_buf);
2284 void pretty_print_ref(const char *name, const struct object_id *oid,
2285 const struct ref_format *format)
2287 struct ref_array_item *ref_item;
2288 ref_item = new_ref_array_item(name, oid);
2289 ref_item->kind = ref_kind_from_refname(name);
2290 show_ref_array_item(ref_item, format);
2291 free_array_item(ref_item);
2294 static int parse_sorting_atom(const char *atom)
2297 * This parses an atom using a dummy ref_format, since we don't
2298 * actually care about the formatting details.
2300 struct ref_format dummy = REF_FORMAT_INIT;
2301 const char *end = atom + strlen(atom);
2302 struct strbuf err = STRBUF_INIT;
2303 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2306 strbuf_release(&err);
2310 /* If no sorting option is given, use refname to sort as default */
2311 struct ref_sorting *ref_default_sorting(void)
2313 static const char cstr_name[] = "refname";
2315 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2317 sorting->next = NULL;
2318 sorting->atom = parse_sorting_atom(cstr_name);
2322 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2324 struct ref_sorting *s;
2326 s = xcalloc(1, sizeof(*s));
2327 s->next = *sorting_tail;
2334 if (skip_prefix(arg, "version:", &arg) ||
2335 skip_prefix(arg, "v:", &arg))
2337 s->atom = parse_sorting_atom(arg);
2340 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2343 * NEEDSWORK: We should probably clear the list in this case, but we've
2344 * already munged the global used_atoms list, which would need to be
2347 BUG_ON_OPT_NEG(unset);
2349 parse_ref_sorting(opt->value, arg);
2353 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2355 struct ref_filter *rf = opt->value;
2356 struct object_id oid;
2357 int no_merged = starts_with(opt->long_name, "no");
2359 BUG_ON_OPT_NEG(unset);
2363 return error(_("option `%s' is incompatible with --merged"),
2366 return error(_("option `%s' is incompatible with --no-merged"),
2371 rf->merge = no_merged
2372 ? REF_FILTER_MERGED_OMIT
2373 : REF_FILTER_MERGED_INCLUDE;
2375 if (get_oid(arg, &oid))
2376 die(_("malformed object name %s"), arg);
2378 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2380 if (!rf->merge_commit)
2381 return error(_("option `%s' must point to a commit"), opt->long_name);