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"
23 #include "argv-array.h"
25 static struct ref_msg {
29 const char *ahead_behind;
31 /* Untranslated plumbing messages: */
38 void setup_ref_filter_porcelain_msg(void)
40 msgs.gone = _("gone");
41 msgs.ahead = _("ahead %d");
42 msgs.behind = _("behind %d");
43 msgs.ahead_behind = _("ahead %d, behind %d");
46 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
47 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
48 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
56 cmp_status cmp_status;
58 unsigned int then_atom_seen : 1,
60 condition_satisfied : 1;
64 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
68 static struct expand_data {
70 enum object_type type;
73 struct object_id delta_base_oid;
76 struct object_info info;
80 * An atom is a valid field atom listed below, possibly prefixed with
81 * a "*" to denote deref_tag().
83 * We parse given format string and sort specifiers, and make a list
84 * of properties that we need to extract out of objects. ref_array_item
85 * structure will hold an array of values extracted that can be
86 * indexed with the "atom number", which is an index into this
89 static struct used_atom {
94 char color[COLOR_MAXLEN];
98 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
100 struct refname_atom refname;
101 unsigned int nobracket : 1, push : 1, push_remote : 1;
104 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
105 struct process_trailer_options trailer_opts;
109 cmp_status cmp_status;
113 enum { O_FULL, O_LENGTH, O_SHORT } option;
116 struct refname_atom refname;
120 static int used_atom_cnt, need_tagged, need_symref;
123 * Expand string, append it to strbuf *sb, then return error code ret.
124 * Allow to save few lines of code.
126 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
130 strbuf_vaddf(sb, fmt, ap);
135 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
136 const char *color_value, struct strbuf *err)
139 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
140 if (color_parse(color_value, atom->u.color) < 0)
141 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
144 * We check this after we've parsed the color, which lets us complain
145 * about syntactically bogus color names even if they won't be used.
147 if (!want_color(format->use_color))
148 color_parse("", atom->u.color);
152 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
153 const char *name, struct strbuf *err)
156 atom->option = R_NORMAL;
157 else if (!strcmp(arg, "short"))
158 atom->option = R_SHORT;
159 else if (skip_prefix(arg, "lstrip=", &arg) ||
160 skip_prefix(arg, "strip=", &arg)) {
161 atom->option = R_LSTRIP;
162 if (strtol_i(arg, 10, &atom->lstrip))
163 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
164 } else if (skip_prefix(arg, "rstrip=", &arg)) {
165 atom->option = R_RSTRIP;
166 if (strtol_i(arg, 10, &atom->rstrip))
167 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
169 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
173 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
174 const char *arg, struct strbuf *err)
176 struct string_list params = STRING_LIST_INIT_DUP;
179 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
180 atom->u.remote_ref.push = 1;
183 atom->u.remote_ref.option = RR_REF;
184 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
185 arg, atom->name, err);
188 atom->u.remote_ref.nobracket = 0;
189 string_list_split(¶ms, arg, ',', -1);
191 for (i = 0; i < params.nr; i++) {
192 const char *s = params.items[i].string;
194 if (!strcmp(s, "track"))
195 atom->u.remote_ref.option = RR_TRACK;
196 else if (!strcmp(s, "trackshort"))
197 atom->u.remote_ref.option = RR_TRACKSHORT;
198 else if (!strcmp(s, "nobracket"))
199 atom->u.remote_ref.nobracket = 1;
200 else if (!strcmp(s, "remotename")) {
201 atom->u.remote_ref.option = RR_REMOTE_NAME;
202 atom->u.remote_ref.push_remote = 1;
203 } else if (!strcmp(s, "remoteref")) {
204 atom->u.remote_ref.option = RR_REMOTE_REF;
205 atom->u.remote_ref.push_remote = 1;
207 atom->u.remote_ref.option = RR_REF;
208 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
209 arg, atom->name, err)) {
210 string_list_clear(¶ms, 0);
216 string_list_clear(¶ms, 0);
220 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
221 const char *arg, struct strbuf *err)
224 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
225 if (*atom->name == '*')
226 oi_deref.info.typep = &oi_deref.type;
228 oi.info.typep = &oi.type;
232 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
233 const char *arg, struct strbuf *err)
236 if (*atom->name == '*')
237 oi_deref.info.sizep = &oi_deref.size;
239 oi.info.sizep = &oi.size;
240 } else if (!strcmp(arg, "disk")) {
241 if (*atom->name == '*')
242 oi_deref.info.disk_sizep = &oi_deref.disk_size;
244 oi.info.disk_sizep = &oi.disk_size;
246 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
250 static int deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom,
251 const char *arg, struct strbuf *err)
254 return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
255 if (*atom->name == '*')
256 oi_deref.info.delta_base_sha1 = oi_deref.delta_base_oid.hash;
258 oi.info.delta_base_sha1 = oi.delta_base_oid.hash;
262 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
263 const char *arg, struct strbuf *err)
266 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
267 atom->u.contents.option = C_BODY_DEP;
271 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
272 const char *arg, struct strbuf *err)
275 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
276 atom->u.contents.option = C_SUB;
280 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
281 const char *arg, struct strbuf *err)
283 struct string_list params = STRING_LIST_INIT_DUP;
286 atom->u.contents.trailer_opts.no_divider = 1;
289 string_list_split(¶ms, arg, ',', -1);
290 for (i = 0; i < params.nr; i++) {
291 const char *s = params.items[i].string;
292 if (!strcmp(s, "unfold"))
293 atom->u.contents.trailer_opts.unfold = 1;
294 else if (!strcmp(s, "only"))
295 atom->u.contents.trailer_opts.only_trailers = 1;
297 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
298 string_list_clear(¶ms, 0);
303 atom->u.contents.option = C_TRAILERS;
304 string_list_clear(¶ms, 0);
308 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
309 const char *arg, struct strbuf *err)
312 atom->u.contents.option = C_BARE;
313 else if (!strcmp(arg, "body"))
314 atom->u.contents.option = C_BODY;
315 else if (!strcmp(arg, "signature"))
316 atom->u.contents.option = C_SIG;
317 else if (!strcmp(arg, "subject"))
318 atom->u.contents.option = C_SUB;
319 else if (skip_prefix(arg, "trailers", &arg)) {
320 skip_prefix(arg, ":", &arg);
321 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
323 } else if (skip_prefix(arg, "lines=", &arg)) {
324 atom->u.contents.option = C_LINES;
325 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
326 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
328 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
332 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
333 const char *arg, struct strbuf *err)
336 atom->u.objectname.option = O_FULL;
337 else if (!strcmp(arg, "short"))
338 atom->u.objectname.option = O_SHORT;
339 else if (skip_prefix(arg, "short=", &arg)) {
340 atom->u.objectname.option = O_LENGTH;
341 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
342 atom->u.objectname.length == 0)
343 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
344 if (atom->u.objectname.length < MINIMUM_ABBREV)
345 atom->u.objectname.length = MINIMUM_ABBREV;
347 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
351 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
352 const char *arg, struct strbuf *err)
354 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
357 static align_type parse_align_position(const char *s)
359 if (!strcmp(s, "right"))
361 else if (!strcmp(s, "middle"))
363 else if (!strcmp(s, "left"))
368 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
369 const char *arg, struct strbuf *err)
371 struct align *align = &atom->u.align;
372 struct string_list params = STRING_LIST_INIT_DUP;
374 unsigned int width = ~0U;
377 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
379 align->position = ALIGN_LEFT;
381 string_list_split(¶ms, arg, ',', -1);
382 for (i = 0; i < params.nr; i++) {
383 const char *s = params.items[i].string;
386 if (skip_prefix(s, "position=", &s)) {
387 position = parse_align_position(s);
389 strbuf_addf(err, _("unrecognized position:%s"), s);
390 string_list_clear(¶ms, 0);
393 align->position = position;
394 } else if (skip_prefix(s, "width=", &s)) {
395 if (strtoul_ui(s, 10, &width)) {
396 strbuf_addf(err, _("unrecognized width:%s"), s);
397 string_list_clear(¶ms, 0);
400 } else if (!strtoul_ui(s, 10, &width))
402 else if ((position = parse_align_position(s)) >= 0)
403 align->position = position;
405 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
406 string_list_clear(¶ms, 0);
412 string_list_clear(¶ms, 0);
413 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
415 align->width = width;
416 string_list_clear(¶ms, 0);
420 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
421 const char *arg, struct strbuf *err)
424 atom->u.if_then_else.cmp_status = COMPARE_NONE;
426 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
427 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
428 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
429 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
431 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
435 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
436 const char *arg, struct strbuf *unused_err)
438 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
446 int (*parser)(const struct ref_format *format, struct used_atom *atom,
447 const char *arg, struct strbuf *err);
449 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
450 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
451 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
452 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
453 { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
454 { "tree", SOURCE_OBJ },
455 { "parent", SOURCE_OBJ },
456 { "numparent", SOURCE_OBJ, FIELD_ULONG },
457 { "object", SOURCE_OBJ },
458 { "type", SOURCE_OBJ },
459 { "tag", SOURCE_OBJ },
460 { "author", SOURCE_OBJ },
461 { "authorname", SOURCE_OBJ },
462 { "authoremail", SOURCE_OBJ },
463 { "authordate", SOURCE_OBJ, FIELD_TIME },
464 { "committer", SOURCE_OBJ },
465 { "committername", SOURCE_OBJ },
466 { "committeremail", SOURCE_OBJ },
467 { "committerdate", SOURCE_OBJ, FIELD_TIME },
468 { "tagger", SOURCE_OBJ },
469 { "taggername", SOURCE_OBJ },
470 { "taggeremail", SOURCE_OBJ },
471 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
472 { "creator", SOURCE_OBJ },
473 { "creatordate", SOURCE_OBJ, FIELD_TIME },
474 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
475 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
476 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
477 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
478 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
479 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
480 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
481 { "flag", SOURCE_NONE },
482 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
483 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
484 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
485 { "end", SOURCE_NONE },
486 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
487 { "then", SOURCE_NONE },
488 { "else", SOURCE_NONE },
490 * Please update $__git_ref_fieldlist in git-completion.bash
491 * when you add new atoms
495 #define REF_FORMATTING_STATE_INIT { 0, NULL }
497 struct ref_formatting_stack {
498 struct ref_formatting_stack *prev;
499 struct strbuf output;
500 void (*at_end)(struct ref_formatting_stack **stack);
504 struct ref_formatting_state {
506 struct ref_formatting_stack *stack;
511 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
513 uintmax_t value; /* used for sorting when not FIELD_STR */
514 struct used_atom *atom;
518 * Used to parse format string and sort specifiers
520 static int parse_ref_filter_atom(const struct ref_format *format,
521 const char *atom, const char *ep,
529 if (*sp == '*' && sp < ep)
532 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
533 (int)(ep-atom), atom);
535 /* Do we have the atom already used elsewhere? */
536 for (i = 0; i < used_atom_cnt; i++) {
537 int len = strlen(used_atom[i].name);
538 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
543 * If the atom name has a colon, strip it and everything after
544 * it off - it specifies the format for this entry, and
545 * shouldn't be used for checking against the valid_atom
548 arg = memchr(sp, ':', ep - sp);
549 atom_len = (arg ? arg : ep) - sp;
551 /* Is the atom a valid one? */
552 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
553 int len = strlen(valid_atom[i].name);
554 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
558 if (ARRAY_SIZE(valid_atom) <= i)
559 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
560 (int)(ep-atom), atom);
561 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
562 return strbuf_addf_ret(err, -1,
563 _("not a git repository, but the field '%.*s' requires access to object data"),
564 (int)(ep-atom), atom);
566 /* Add it in, including the deref prefix */
569 REALLOC_ARRAY(used_atom, used_atom_cnt);
570 used_atom[at].name = xmemdupz(atom, ep - atom);
571 used_atom[at].type = valid_atom[i].cmp_type;
572 used_atom[at].source = valid_atom[i].source;
573 if (used_atom[at].source == SOURCE_OBJ) {
575 oi_deref.info.contentp = &oi_deref.content;
577 oi.info.contentp = &oi.content;
580 arg = used_atom[at].name + (arg - atom) + 1;
583 * Treat empty sub-arguments list as NULL (i.e.,
584 * "%(atom:)" is equivalent to "%(atom)").
589 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
590 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
594 if (!strcmp(valid_atom[i].name, "symref"))
599 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
601 switch (quote_style) {
603 strbuf_addstr(s, str);
606 sq_quote_buf(s, str);
609 perl_quote_buf(s, str);
612 python_quote_buf(s, str);
615 tcl_quote_buf(s, str);
620 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
621 struct strbuf *unused_err)
624 * Quote formatting is only done when the stack has a single
625 * element. Otherwise quote formatting is done on the
626 * element's entire output strbuf when the %(end) atom is
629 if (!state->stack->prev)
630 quote_formatting(&state->stack->output, v->s, state->quote_style);
632 strbuf_addstr(&state->stack->output, v->s);
636 static void push_stack_element(struct ref_formatting_stack **stack)
638 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
640 strbuf_init(&s->output, 0);
645 static void pop_stack_element(struct ref_formatting_stack **stack)
647 struct ref_formatting_stack *current = *stack;
648 struct ref_formatting_stack *prev = current->prev;
651 strbuf_addbuf(&prev->output, ¤t->output);
652 strbuf_release(¤t->output);
657 static void end_align_handler(struct ref_formatting_stack **stack)
659 struct ref_formatting_stack *cur = *stack;
660 struct align *align = (struct align *)cur->at_end_data;
661 struct strbuf s = STRBUF_INIT;
663 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
664 strbuf_swap(&cur->output, &s);
668 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
669 struct strbuf *unused_err)
671 struct ref_formatting_stack *new_stack;
673 push_stack_element(&state->stack);
674 new_stack = state->stack;
675 new_stack->at_end = end_align_handler;
676 new_stack->at_end_data = &atomv->atom->u.align;
680 static void if_then_else_handler(struct ref_formatting_stack **stack)
682 struct ref_formatting_stack *cur = *stack;
683 struct ref_formatting_stack *prev = cur->prev;
684 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
686 if (!if_then_else->then_atom_seen)
687 die(_("format: %%(if) atom used without a %%(then) atom"));
689 if (if_then_else->else_atom_seen) {
691 * There is an %(else) atom: we need to drop one state from the
692 * stack, either the %(else) branch if the condition is satisfied, or
693 * the %(then) branch if it isn't.
695 if (if_then_else->condition_satisfied) {
696 strbuf_reset(&cur->output);
697 pop_stack_element(&cur);
699 strbuf_swap(&cur->output, &prev->output);
700 strbuf_reset(&cur->output);
701 pop_stack_element(&cur);
703 } else if (!if_then_else->condition_satisfied) {
705 * No %(else) atom: just drop the %(then) branch if the
706 * condition is not satisfied.
708 strbuf_reset(&cur->output);
715 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
716 struct strbuf *unused_err)
718 struct ref_formatting_stack *new_stack;
719 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
721 if_then_else->str = atomv->atom->u.if_then_else.str;
722 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
724 push_stack_element(&state->stack);
725 new_stack = state->stack;
726 new_stack->at_end = if_then_else_handler;
727 new_stack->at_end_data = if_then_else;
731 static int is_empty(const char *s)
741 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
744 struct ref_formatting_stack *cur = state->stack;
745 struct if_then_else *if_then_else = NULL;
747 if (cur->at_end == if_then_else_handler)
748 if_then_else = (struct if_then_else *)cur->at_end_data;
750 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
751 if (if_then_else->then_atom_seen)
752 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
753 if (if_then_else->else_atom_seen)
754 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
755 if_then_else->then_atom_seen = 1;
757 * If the 'equals' or 'notequals' attribute is used then
758 * perform the required comparison. If not, only non-empty
759 * strings satisfy the 'if' condition.
761 if (if_then_else->cmp_status == COMPARE_EQUAL) {
762 if (!strcmp(if_then_else->str, cur->output.buf))
763 if_then_else->condition_satisfied = 1;
764 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
765 if (strcmp(if_then_else->str, cur->output.buf))
766 if_then_else->condition_satisfied = 1;
767 } else if (cur->output.len && !is_empty(cur->output.buf))
768 if_then_else->condition_satisfied = 1;
769 strbuf_reset(&cur->output);
773 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
776 struct ref_formatting_stack *prev = state->stack;
777 struct if_then_else *if_then_else = NULL;
779 if (prev->at_end == if_then_else_handler)
780 if_then_else = (struct if_then_else *)prev->at_end_data;
782 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
783 if (!if_then_else->then_atom_seen)
784 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
785 if (if_then_else->else_atom_seen)
786 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
787 if_then_else->else_atom_seen = 1;
788 push_stack_element(&state->stack);
789 state->stack->at_end_data = prev->at_end_data;
790 state->stack->at_end = prev->at_end;
794 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
797 struct ref_formatting_stack *current = state->stack;
798 struct strbuf s = STRBUF_INIT;
800 if (!current->at_end)
801 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
802 current->at_end(&state->stack);
804 /* Stack may have been popped within at_end(), hence reset the current pointer */
805 current = state->stack;
808 * Perform quote formatting when the stack element is that of
809 * a supporting atom. If nested then perform quote formatting
810 * only on the topmost supporting atom.
812 if (!current->prev->prev) {
813 quote_formatting(&s, current->output.buf, state->quote_style);
814 strbuf_swap(¤t->output, &s);
817 pop_stack_element(&state->stack);
822 * In a format string, find the next occurrence of %(atom).
824 static const char *find_next(const char *cp)
829 * %( is the start of an atom;
830 * %% is a quoted per-cent.
834 else if (cp[1] == '%')
835 cp++; /* skip over two % */
836 /* otherwise this is a singleton, literal % */
844 * Make sure the format string is well formed, and parse out
847 int verify_ref_format(struct ref_format *format)
851 format->need_color_reset_at_eol = 0;
852 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
853 struct strbuf err = STRBUF_INIT;
854 const char *color, *ep = strchr(sp, ')');
858 return error(_("malformed format string %s"), sp);
859 /* sp points at "%(" and ep points at the closing ")" */
860 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
865 if (skip_prefix(used_atom[at].name, "color:", &color))
866 format->need_color_reset_at_eol = !!strcmp(color, "reset");
867 strbuf_release(&err);
869 if (format->need_color_reset_at_eol && !want_color(format->use_color))
870 format->need_color_reset_at_eol = 0;
874 static int grab_objectname(const char *name, const struct object_id *oid,
875 struct atom_value *v, struct used_atom *atom)
877 if (starts_with(name, "objectname")) {
878 if (atom->u.objectname.option == O_SHORT) {
879 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
881 } else if (atom->u.objectname.option == O_FULL) {
882 v->s = xstrdup(oid_to_hex(oid));
884 } else if (atom->u.objectname.option == O_LENGTH) {
885 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
888 BUG("unknown %%(objectname) option");
893 /* See grab_values */
894 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
898 for (i = 0; i < used_atom_cnt; i++) {
899 const char *name = used_atom[i].name;
900 struct atom_value *v = &val[i];
901 if (!!deref != (*name == '*'))
905 if (!strcmp(name, "objecttype"))
906 v->s = xstrdup(type_name(oi->type));
907 else if (!strcmp(name, "objectsize:disk")) {
908 v->value = oi->disk_size;
909 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
910 } else if (!strcmp(name, "objectsize")) {
912 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
913 } else if (!strcmp(name, "deltabase"))
914 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
916 grab_objectname(name, &oi->oid, v, &used_atom[i]);
920 /* See grab_values */
921 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
924 struct tag *tag = (struct tag *) obj;
926 for (i = 0; i < used_atom_cnt; i++) {
927 const char *name = used_atom[i].name;
928 struct atom_value *v = &val[i];
929 if (!!deref != (*name == '*'))
933 if (!strcmp(name, "tag"))
934 v->s = xstrdup(tag->tag);
935 else if (!strcmp(name, "type") && tag->tagged)
936 v->s = xstrdup(type_name(tag->tagged->type));
937 else if (!strcmp(name, "object") && tag->tagged)
938 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
942 /* See grab_values */
943 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
946 struct commit *commit = (struct commit *) obj;
948 for (i = 0; i < used_atom_cnt; i++) {
949 const char *name = used_atom[i].name;
950 struct atom_value *v = &val[i];
951 if (!!deref != (*name == '*'))
955 if (!strcmp(name, "tree")) {
956 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
958 else if (!strcmp(name, "numparent")) {
959 v->value = commit_list_count(commit->parents);
960 v->s = xstrfmt("%lu", (unsigned long)v->value);
962 else if (!strcmp(name, "parent")) {
963 struct commit_list *parents;
964 struct strbuf s = STRBUF_INIT;
965 for (parents = commit->parents; parents; parents = parents->next) {
966 struct commit *parent = parents->item;
967 if (parents != commit->parents)
968 strbuf_addch(&s, ' ');
969 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
971 v->s = strbuf_detach(&s, NULL);
976 static const char *find_wholine(const char *who, int wholen, const char *buf)
980 if (!strncmp(buf, who, wholen) &&
982 return buf + wholen + 1;
983 eol = strchr(buf, '\n');
988 return ""; /* end of header */
994 static const char *copy_line(const char *buf)
996 const char *eol = strchrnul(buf, '\n');
997 return xmemdupz(buf, eol - buf);
1000 static const char *copy_name(const char *buf)
1003 for (cp = buf; *cp && *cp != '\n'; cp++) {
1004 if (!strncmp(cp, " <", 2))
1005 return xmemdupz(buf, cp - buf);
1010 static const char *copy_email(const char *buf)
1012 const char *email = strchr(buf, '<');
1013 const char *eoemail;
1016 eoemail = strchr(email, '>');
1019 return xmemdupz(email, eoemail + 1 - email);
1022 static char *copy_subject(const char *buf, unsigned long len)
1024 char *r = xmemdupz(buf, len);
1027 for (i = 0; i < len; i++)
1034 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1036 const char *eoemail = strstr(buf, "> ");
1038 timestamp_t timestamp;
1040 struct date_mode date_mode = { DATE_NORMAL };
1041 const char *formatp;
1044 * We got here because atomname ends in "date" or "date<something>";
1045 * it's not possible that <something> is not ":<format>" because
1046 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1047 * ":" means no format is specified, and use the default.
1049 formatp = strchr(atomname, ':');
1050 if (formatp != NULL) {
1052 parse_date_format(formatp, &date_mode);
1057 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1058 if (timestamp == TIME_MAX)
1060 tz = strtol(zone, NULL, 10);
1061 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1063 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1064 v->value = timestamp;
1071 /* See grab_values */
1072 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1075 int wholen = strlen(who);
1076 const char *wholine = NULL;
1078 for (i = 0; i < used_atom_cnt; i++) {
1079 const char *name = used_atom[i].name;
1080 struct atom_value *v = &val[i];
1081 if (!!deref != (*name == '*'))
1085 if (strncmp(who, name, wholen))
1087 if (name[wholen] != 0 &&
1088 strcmp(name + wholen, "name") &&
1089 strcmp(name + wholen, "email") &&
1090 !starts_with(name + wholen, "date"))
1093 wholine = find_wholine(who, wholen, buf);
1095 return; /* no point looking for it */
1096 if (name[wholen] == 0)
1097 v->s = copy_line(wholine);
1098 else if (!strcmp(name + wholen, "name"))
1099 v->s = copy_name(wholine);
1100 else if (!strcmp(name + wholen, "email"))
1101 v->s = copy_email(wholine);
1102 else if (starts_with(name + wholen, "date"))
1103 grab_date(wholine, v, name);
1107 * For a tag or a commit object, if "creator" or "creatordate" is
1108 * requested, do something special.
1110 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1111 return; /* "author" for commit object is not wanted */
1113 wholine = find_wholine(who, wholen, buf);
1116 for (i = 0; i < used_atom_cnt; i++) {
1117 const char *name = used_atom[i].name;
1118 struct atom_value *v = &val[i];
1119 if (!!deref != (*name == '*'))
1124 if (starts_with(name, "creatordate"))
1125 grab_date(wholine, v, name);
1126 else if (!strcmp(name, "creator"))
1127 v->s = copy_line(wholine);
1131 static void find_subpos(const char *buf,
1132 const char **sub, unsigned long *sublen,
1133 const char **body, unsigned long *bodylen,
1134 unsigned long *nonsiglen,
1135 const char **sig, unsigned long *siglen)
1138 /* skip past header until we hit empty line */
1139 while (*buf && *buf != '\n') {
1140 eol = strchrnul(buf, '\n');
1145 /* skip any empty lines */
1146 while (*buf == '\n')
1149 /* parse signature first; we might not even have a subject line */
1150 *sig = buf + parse_signature(buf, strlen(buf));
1151 *siglen = strlen(*sig);
1153 /* subject is first non-empty line */
1155 /* subject goes to first empty line */
1156 while (buf < *sig && *buf && *buf != '\n') {
1157 eol = strchrnul(buf, '\n');
1162 *sublen = buf - *sub;
1163 /* drop trailing newline, if present */
1164 if (*sublen && (*sub)[*sublen - 1] == '\n')
1167 /* skip any empty lines */
1168 while (*buf == '\n')
1171 *bodylen = strlen(buf);
1172 *nonsiglen = *sig - buf;
1176 * If 'lines' is greater than 0, append that many lines from the given
1177 * 'buf' of length 'size' to the given strbuf.
1179 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1182 const char *sp, *eol;
1187 for (i = 0; i < lines && sp < buf + size; i++) {
1189 strbuf_addstr(out, "\n ");
1190 eol = memchr(sp, '\n', size - (sp - buf));
1191 len = eol ? eol - sp : size - (sp - buf);
1192 strbuf_add(out, sp, len);
1199 /* See grab_values */
1200 static void grab_sub_body_contents(struct atom_value *val, int deref, void *buf)
1203 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1204 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1206 for (i = 0; i < used_atom_cnt; i++) {
1207 struct used_atom *atom = &used_atom[i];
1208 const char *name = atom->name;
1209 struct atom_value *v = &val[i];
1210 if (!!deref != (*name == '*'))
1214 if (strcmp(name, "subject") &&
1215 strcmp(name, "body") &&
1216 !starts_with(name, "trailers") &&
1217 !starts_with(name, "contents"))
1222 &bodypos, &bodylen, &nonsiglen,
1225 if (atom->u.contents.option == C_SUB)
1226 v->s = copy_subject(subpos, sublen);
1227 else if (atom->u.contents.option == C_BODY_DEP)
1228 v->s = xmemdupz(bodypos, bodylen);
1229 else if (atom->u.contents.option == C_BODY)
1230 v->s = xmemdupz(bodypos, nonsiglen);
1231 else if (atom->u.contents.option == C_SIG)
1232 v->s = xmemdupz(sigpos, siglen);
1233 else if (atom->u.contents.option == C_LINES) {
1234 struct strbuf s = STRBUF_INIT;
1235 const char *contents_end = bodylen + bodypos - siglen;
1237 /* Size is the length of the message after removing the signature */
1238 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1239 v->s = strbuf_detach(&s, NULL);
1240 } else if (atom->u.contents.option == C_TRAILERS) {
1241 struct strbuf s = STRBUF_INIT;
1243 /* Format the trailer info according to the trailer_opts given */
1244 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1246 v->s = strbuf_detach(&s, NULL);
1247 } else if (atom->u.contents.option == C_BARE)
1248 v->s = xstrdup(subpos);
1253 * We want to have empty print-string for field requests
1254 * that do not apply (e.g. "authordate" for a tag object)
1256 static void fill_missing_values(struct atom_value *val)
1259 for (i = 0; i < used_atom_cnt; i++) {
1260 struct atom_value *v = &val[i];
1267 * val is a list of atom_value to hold returned values. Extract
1268 * the values for atoms in used_atom array out of (obj, buf, sz).
1269 * when deref is false, (obj, buf, sz) is the object that is
1270 * pointed at by the ref itself; otherwise it is the object the
1271 * ref (which is a tag) refers to.
1273 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf)
1275 switch (obj->type) {
1277 grab_tag_values(val, deref, obj);
1278 grab_sub_body_contents(val, deref, buf);
1279 grab_person("tagger", val, deref, buf);
1282 grab_commit_values(val, deref, obj);
1283 grab_sub_body_contents(val, deref, buf);
1284 grab_person("author", val, deref, buf);
1285 grab_person("committer", val, deref, buf);
1288 /* grab_tree_values(val, deref, obj, buf, sz); */
1291 /* grab_blob_values(val, deref, obj, buf, sz); */
1294 die("Eh? Object of type %d?", obj->type);
1298 static inline char *copy_advance(char *dst, const char *src)
1305 static const char *lstrip_ref_components(const char *refname, int len)
1307 long remaining = len;
1308 const char *start = xstrdup(refname);
1309 const char *to_free = start;
1313 const char *p = refname;
1315 /* Find total no of '/' separated path-components */
1316 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1319 * The number of components we need to strip is now
1320 * the total minus the components to be left (Plus one
1321 * because we count the number of '/', but the number
1322 * of components is one more than the no of '/').
1324 remaining = i + len + 1;
1327 while (remaining > 0) {
1330 free((char *)to_free);
1338 start = xstrdup(start);
1339 free((char *)to_free);
1343 static const char *rstrip_ref_components(const char *refname, int len)
1345 long remaining = len;
1346 const char *start = xstrdup(refname);
1347 const char *to_free = start;
1351 const char *p = refname;
1353 /* Find total no of '/' separated path-components */
1354 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1357 * The number of components we need to strip is now
1358 * the total minus the components to be left (Plus one
1359 * because we count the number of '/', but the number
1360 * of components is one more than the no of '/').
1362 remaining = i + len + 1;
1365 while (remaining-- > 0) {
1366 char *p = strrchr(start, '/');
1368 free((char *)to_free);
1376 static const char *show_ref(struct refname_atom *atom, const char *refname)
1378 if (atom->option == R_SHORT)
1379 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1380 else if (atom->option == R_LSTRIP)
1381 return lstrip_ref_components(refname, atom->lstrip);
1382 else if (atom->option == R_RSTRIP)
1383 return rstrip_ref_components(refname, atom->rstrip);
1385 return xstrdup(refname);
1388 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1389 struct branch *branch, const char **s)
1391 int num_ours, num_theirs;
1392 if (atom->u.remote_ref.option == RR_REF)
1393 *s = show_ref(&atom->u.remote_ref.refname, refname);
1394 else if (atom->u.remote_ref.option == RR_TRACK) {
1395 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1396 NULL, atom->u.remote_ref.push,
1397 AHEAD_BEHIND_FULL) < 0) {
1398 *s = xstrdup(msgs.gone);
1399 } else if (!num_ours && !num_theirs)
1402 *s = xstrfmt(msgs.behind, num_theirs);
1403 else if (!num_theirs)
1404 *s = xstrfmt(msgs.ahead, num_ours);
1406 *s = xstrfmt(msgs.ahead_behind,
1407 num_ours, num_theirs);
1408 if (!atom->u.remote_ref.nobracket && *s[0]) {
1409 const char *to_free = *s;
1410 *s = xstrfmt("[%s]", *s);
1411 free((void *)to_free);
1413 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1414 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1415 NULL, atom->u.remote_ref.push,
1416 AHEAD_BEHIND_FULL) < 0) {
1420 if (!num_ours && !num_theirs)
1424 else if (!num_theirs)
1428 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1430 const char *remote = atom->u.remote_ref.push ?
1431 pushremote_for_branch(branch, &explicit) :
1432 remote_for_branch(branch, &explicit);
1433 *s = xstrdup(explicit ? remote : "");
1434 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1438 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1440 *s = xstrdup(explicit ? merge : "");
1442 BUG("unhandled RR_* enum");
1445 char *get_head_description(void)
1447 struct strbuf desc = STRBUF_INIT;
1448 struct wt_status_state state;
1449 memset(&state, 0, sizeof(state));
1450 wt_status_get_state(the_repository, &state, 1);
1451 if (state.rebase_in_progress ||
1452 state.rebase_interactive_in_progress) {
1454 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1457 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1458 state.detached_from);
1459 } else if (state.bisect_in_progress)
1460 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1462 else if (state.detached_from) {
1463 if (state.detached_at)
1465 * TRANSLATORS: make sure this matches "HEAD
1466 * detached at " in wt-status.c
1468 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1469 state.detached_from);
1472 * TRANSLATORS: make sure this matches "HEAD
1473 * detached from " in wt-status.c
1475 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1476 state.detached_from);
1479 strbuf_addstr(&desc, _("(no branch)"));
1482 free(state.detached_from);
1483 return strbuf_detach(&desc, NULL);
1486 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1491 return show_ref(&atom->u.refname, ref->symref);
1494 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1496 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1497 return get_head_description();
1498 return show_ref(&atom->u.refname, ref->refname);
1501 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1502 struct expand_data *oi, struct strbuf *err)
1504 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1506 if (oi->info.contentp) {
1507 /* We need to know that to use parse_object_buffer properly */
1508 oi->info.sizep = &oi->size;
1509 oi->info.typep = &oi->type;
1511 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1512 OBJECT_INFO_LOOKUP_REPLACE))
1513 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1514 oid_to_hex(&oi->oid), ref->refname);
1515 if (oi->info.disk_sizep && oi->disk_size < 0)
1516 BUG("Object size is less than zero.");
1518 if (oi->info.contentp) {
1519 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1523 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1524 oid_to_hex(&oi->oid), ref->refname);
1526 grab_values(ref->value, deref, *obj, oi->content);
1529 grab_common_values(ref->value, deref, oi);
1536 * Parse the object referred by ref, and grab needed value.
1538 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1542 struct object_info empty = OBJECT_INFO_INIT;
1544 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1546 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1547 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1550 ref->symref = xstrdup("");
1553 /* Fill in specials first */
1554 for (i = 0; i < used_atom_cnt; i++) {
1555 struct used_atom *atom = &used_atom[i];
1556 const char *name = used_atom[i].name;
1557 struct atom_value *v = &ref->value[i];
1559 const char *refname;
1560 struct branch *branch = NULL;
1562 v->handler = append_atom;
1570 if (starts_with(name, "refname"))
1571 refname = get_refname(atom, ref);
1572 else if (starts_with(name, "symref"))
1573 refname = get_symref(atom, ref);
1574 else if (starts_with(name, "upstream")) {
1575 const char *branch_name;
1576 /* only local branches may have an upstream */
1577 if (!skip_prefix(ref->refname, "refs/heads/",
1582 branch = branch_get(branch_name);
1584 refname = branch_get_upstream(branch, NULL);
1586 fill_remote_ref_details(atom, refname, branch, &v->s);
1590 } else if (atom->u.remote_ref.push) {
1591 const char *branch_name;
1593 if (!skip_prefix(ref->refname, "refs/heads/",
1596 branch = branch_get(branch_name);
1598 if (atom->u.remote_ref.push_remote)
1601 refname = branch_get_push(branch, NULL);
1605 /* We will definitely re-init v->s on the next line. */
1607 fill_remote_ref_details(atom, refname, branch, &v->s);
1609 } else if (starts_with(name, "color:")) {
1610 v->s = xstrdup(atom->u.color);
1612 } else if (!strcmp(name, "flag")) {
1613 char buf[256], *cp = buf;
1614 if (ref->flag & REF_ISSYMREF)
1615 cp = copy_advance(cp, ",symref");
1616 if (ref->flag & REF_ISPACKED)
1617 cp = copy_advance(cp, ",packed");
1622 v->s = xstrdup(buf + 1);
1625 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1627 } else if (!strcmp(name, "HEAD")) {
1628 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1629 v->s = xstrdup("*");
1631 v->s = xstrdup(" ");
1633 } else if (starts_with(name, "align")) {
1634 v->handler = align_atom_handler;
1637 } else if (!strcmp(name, "end")) {
1638 v->handler = end_atom_handler;
1641 } else if (starts_with(name, "if")) {
1643 if (skip_prefix(name, "if:", &s))
1647 v->handler = if_atom_handler;
1649 } else if (!strcmp(name, "then")) {
1650 v->handler = then_atom_handler;
1653 } else if (!strcmp(name, "else")) {
1654 v->handler = else_atom_handler;
1661 v->s = xstrdup(refname);
1663 v->s = xstrfmt("%s^{}", refname);
1664 free((char *)refname);
1667 for (i = 0; i < used_atom_cnt; i++) {
1668 struct atom_value *v = &ref->value[i];
1669 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1670 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1671 oid_to_hex(&ref->objectname), ref->refname);
1675 oi.info.contentp = &oi.content;
1676 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1677 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1681 oi.oid = ref->objectname;
1682 if (get_object(ref, 0, &obj, &oi, err))
1686 * If there is no atom that wants to know about tagged
1687 * object, we are done.
1689 if (!need_tagged || (obj->type != OBJ_TAG))
1693 * If it is a tag object, see if we use a value that derefs
1694 * the object, and if we do grab the object it refers to.
1696 oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1699 * NEEDSWORK: This derefs tag only once, which
1700 * is good to deal with chains of trust, but
1701 * is not consistent with what deref_tag() does
1702 * which peels the onion to the core.
1704 return get_object(ref, 1, &obj, &oi_deref, err);
1708 * Given a ref, return the value for the atom. This lazily gets value
1709 * out of the object by calling populate value.
1711 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1712 struct atom_value **v, struct strbuf *err)
1715 if (populate_value(ref, err))
1717 fill_missing_values(ref->value);
1719 *v = &ref->value[atom];
1724 * Return 1 if the refname matches one of the patterns, otherwise 0.
1725 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1726 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1727 * matches "refs/heads/mas*", too).
1729 static int match_pattern(const struct ref_filter *filter, const char *refname)
1731 const char **patterns = filter->name_patterns;
1734 if (filter->ignore_case)
1735 flags |= WM_CASEFOLD;
1738 * When no '--format' option is given we need to skip the prefix
1739 * for matching refs of tags and branches.
1741 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1742 skip_prefix(refname, "refs/heads/", &refname) ||
1743 skip_prefix(refname, "refs/remotes/", &refname) ||
1744 skip_prefix(refname, "refs/", &refname));
1746 for (; *patterns; patterns++) {
1747 if (!wildmatch(*patterns, refname, flags))
1754 * Return 1 if the refname matches one of the patterns, otherwise 0.
1755 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1756 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1757 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1759 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1761 const char **pattern = filter->name_patterns;
1762 int namelen = strlen(refname);
1763 unsigned flags = WM_PATHNAME;
1765 if (filter->ignore_case)
1766 flags |= WM_CASEFOLD;
1768 for (; *pattern; pattern++) {
1769 const char *p = *pattern;
1770 int plen = strlen(p);
1772 if ((plen <= namelen) &&
1773 !strncmp(refname, p, plen) &&
1774 (refname[plen] == '\0' ||
1775 refname[plen] == '/' ||
1778 if (!wildmatch(p, refname, flags))
1784 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1785 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1787 if (!*filter->name_patterns)
1788 return 1; /* No pattern always matches */
1789 if (filter->match_as_path)
1790 return match_name_as_path(filter, refname);
1791 return match_pattern(filter, refname);
1794 static int qsort_strcmp(const void *va, const void *vb)
1796 const char *a = *(const char **)va;
1797 const char *b = *(const char **)vb;
1799 return strcmp(a, b);
1802 static void find_longest_prefixes_1(struct string_list *out,
1803 struct strbuf *prefix,
1804 const char **patterns, size_t nr)
1808 for (i = 0; i < nr; i++) {
1809 char c = patterns[i][prefix->len];
1810 if (!c || is_glob_special(c)) {
1811 string_list_append(out, prefix->buf);
1821 * Set "end" to the index of the element _after_ the last one
1824 for (end = i + 1; end < nr; end++) {
1825 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1829 strbuf_addch(prefix, patterns[i][prefix->len]);
1830 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1831 strbuf_setlen(prefix, prefix->len - 1);
1837 static void find_longest_prefixes(struct string_list *out,
1838 const char **patterns)
1840 struct argv_array sorted = ARGV_ARRAY_INIT;
1841 struct strbuf prefix = STRBUF_INIT;
1843 argv_array_pushv(&sorted, patterns);
1844 QSORT(sorted.argv, sorted.argc, qsort_strcmp);
1846 find_longest_prefixes_1(out, &prefix, sorted.argv, sorted.argc);
1848 argv_array_clear(&sorted);
1849 strbuf_release(&prefix);
1853 * This is the same as for_each_fullref_in(), but it tries to iterate
1854 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1855 * pattern match, so the callback still has to match each ref individually.
1857 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1862 struct string_list prefixes = STRING_LIST_INIT_DUP;
1863 struct string_list_item *prefix;
1866 if (!filter->match_as_path) {
1868 * in this case, the patterns are applied after
1869 * prefixes like "refs/heads/" etc. are stripped off,
1870 * so we have to look at everything:
1872 return for_each_fullref_in("", cb, cb_data, broken);
1875 if (filter->ignore_case) {
1877 * we can't handle case-insensitive comparisons,
1878 * so just return everything and let the caller
1881 return for_each_fullref_in("", cb, cb_data, broken);
1884 if (!filter->name_patterns[0]) {
1885 /* no patterns; we have to look at everything */
1886 return for_each_fullref_in("", cb, cb_data, broken);
1889 find_longest_prefixes(&prefixes, filter->name_patterns);
1891 for_each_string_list_item(prefix, &prefixes) {
1892 ret = for_each_fullref_in(prefix->string, cb, cb_data, broken);
1897 string_list_clear(&prefixes, 0);
1902 * Given a ref (sha1, refname), check if the ref belongs to the array
1903 * of sha1s. If the given ref is a tag, check if the given tag points
1904 * at one of the sha1s in the given sha1 array.
1905 * the given sha1_array.
1907 * 1. Only a single level of inderection is obtained, we might want to
1908 * change this to account for multiple levels (e.g. annotated tags
1909 * pointing to annotated tags pointing to a commit.)
1910 * 2. As the refs are cached we might know what refname peels to without
1911 * the need to parse the object via parse_object(). peel_ref() might be a
1912 * more efficient alternative to obtain the pointee.
1914 static const struct object_id *match_points_at(struct oid_array *points_at,
1915 const struct object_id *oid,
1916 const char *refname)
1918 const struct object_id *tagged_oid = NULL;
1921 if (oid_array_lookup(points_at, oid) >= 0)
1923 obj = parse_object(the_repository, oid);
1925 die(_("malformed object at '%s'"), refname);
1926 if (obj->type == OBJ_TAG)
1927 tagged_oid = &((struct tag *)obj)->tagged->oid;
1928 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1934 * Allocate space for a new ref_array_item and copy the name and oid to it.
1936 * Callers can then fill in other struct members at their leisure.
1938 static struct ref_array_item *new_ref_array_item(const char *refname,
1939 const struct object_id *oid)
1941 struct ref_array_item *ref;
1943 FLEX_ALLOC_STR(ref, refname, refname);
1944 oidcpy(&ref->objectname, oid);
1949 struct ref_array_item *ref_array_push(struct ref_array *array,
1950 const char *refname,
1951 const struct object_id *oid)
1953 struct ref_array_item *ref = new_ref_array_item(refname, oid);
1955 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1956 array->items[array->nr++] = ref;
1961 static int ref_kind_from_refname(const char *refname)
1969 { "refs/heads/" , FILTER_REFS_BRANCHES },
1970 { "refs/remotes/" , FILTER_REFS_REMOTES },
1971 { "refs/tags/", FILTER_REFS_TAGS}
1974 if (!strcmp(refname, "HEAD"))
1975 return FILTER_REFS_DETACHED_HEAD;
1977 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1978 if (starts_with(refname, ref_kind[i].prefix))
1979 return ref_kind[i].kind;
1982 return FILTER_REFS_OTHERS;
1985 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1987 if (filter->kind == FILTER_REFS_BRANCHES ||
1988 filter->kind == FILTER_REFS_REMOTES ||
1989 filter->kind == FILTER_REFS_TAGS)
1990 return filter->kind;
1991 return ref_kind_from_refname(refname);
1994 struct ref_filter_cbdata {
1995 struct ref_array *array;
1996 struct ref_filter *filter;
1997 struct contains_cache contains_cache;
1998 struct contains_cache no_contains_cache;
2002 * A call-back given to for_each_ref(). Filter refs and keep them for
2003 * later object processing.
2005 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2007 struct ref_filter_cbdata *ref_cbdata = cb_data;
2008 struct ref_filter *filter = ref_cbdata->filter;
2009 struct ref_array_item *ref;
2010 struct commit *commit = NULL;
2013 if (flag & REF_BAD_NAME) {
2014 warning(_("ignoring ref with broken name %s"), refname);
2018 if (flag & REF_ISBROKEN) {
2019 warning(_("ignoring broken ref %s"), refname);
2023 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2024 kind = filter_ref_kind(filter, refname);
2025 if (!(kind & filter->kind))
2028 if (!filter_pattern_match(filter, refname))
2031 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2035 * A merge filter is applied on refs pointing to commits. Hence
2036 * obtain the commit using the 'oid' available and discard all
2037 * non-commits early. The actual filtering is done later.
2039 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2040 commit = lookup_commit_reference_gently(the_repository, oid,
2044 /* We perform the filtering for the '--contains' option... */
2045 if (filter->with_commit &&
2046 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2048 /* ...or for the `--no-contains' option */
2049 if (filter->no_commit &&
2050 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2055 * We do not open the object yet; sort may only need refname
2056 * to do its job and the resulting list may yet to be pruned
2057 * by maxcount logic.
2059 ref = ref_array_push(ref_cbdata->array, refname, oid);
2060 ref->commit = commit;
2067 /* Free memory allocated for a ref_array_item */
2068 static void free_array_item(struct ref_array_item *item)
2070 free((char *)item->symref);
2072 free((char *)item->value->s);
2078 /* Free all memory allocated for ref_array */
2079 void ref_array_clear(struct ref_array *array)
2083 for (i = 0; i < used_atom_cnt; i++)
2084 free((char *)used_atom[i].name);
2085 FREE_AND_NULL(used_atom);
2087 for (i = 0; i < array->nr; i++)
2088 free_array_item(array->items[i]);
2089 FREE_AND_NULL(array->items);
2090 array->nr = array->alloc = 0;
2093 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2095 struct rev_info revs;
2097 struct ref_filter *filter = ref_cbdata->filter;
2098 struct ref_array *array = ref_cbdata->array;
2099 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2101 repo_init_revisions(the_repository, &revs, NULL);
2103 for (i = 0; i < array->nr; i++) {
2104 struct ref_array_item *item = array->items[i];
2105 add_pending_object(&revs, &item->commit->object, item->refname);
2106 to_clear[i] = item->commit;
2109 filter->merge_commit->object.flags |= UNINTERESTING;
2110 add_pending_object(&revs, &filter->merge_commit->object, "");
2113 if (prepare_revision_walk(&revs))
2114 die(_("revision walk setup failed"));
2119 for (i = 0; i < old_nr; i++) {
2120 struct ref_array_item *item = array->items[i];
2121 struct commit *commit = item->commit;
2123 int is_merged = !!(commit->object.flags & UNINTERESTING);
2125 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2126 array->items[array->nr++] = array->items[i];
2128 free_array_item(item);
2131 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2132 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2137 * API for filtering a set of refs. Based on the type of refs the user
2138 * has requested, we iterate through those refs and apply filters
2139 * as per the given ref_filter structure and finally store the
2140 * filtered refs in the ref_array structure.
2142 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2144 struct ref_filter_cbdata ref_cbdata;
2146 unsigned int broken = 0;
2148 ref_cbdata.array = array;
2149 ref_cbdata.filter = filter;
2151 if (type & FILTER_REFS_INCLUDE_BROKEN)
2153 filter->kind = type & FILTER_REFS_KIND_MASK;
2155 init_contains_cache(&ref_cbdata.contains_cache);
2156 init_contains_cache(&ref_cbdata.no_contains_cache);
2158 /* Simple per-ref filtering */
2160 die("filter_refs: invalid type");
2163 * For common cases where we need only branches or remotes or tags,
2164 * we only iterate through those refs. If a mix of refs is needed,
2165 * we iterate over all refs and filter out required refs with the help
2166 * of filter_ref_kind().
2168 if (filter->kind == FILTER_REFS_BRANCHES)
2169 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2170 else if (filter->kind == FILTER_REFS_REMOTES)
2171 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2172 else if (filter->kind == FILTER_REFS_TAGS)
2173 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2174 else if (filter->kind & FILTER_REFS_ALL)
2175 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2176 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2177 head_ref(ref_filter_handler, &ref_cbdata);
2180 clear_contains_cache(&ref_cbdata.contains_cache);
2181 clear_contains_cache(&ref_cbdata.no_contains_cache);
2183 /* Filters that need revision walking */
2184 if (filter->merge_commit)
2185 do_merge_filter(&ref_cbdata);
2190 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2192 struct atom_value *va, *vb;
2194 cmp_type cmp_type = used_atom[s->atom].type;
2195 int (*cmp_fn)(const char *, const char *);
2196 struct strbuf err = STRBUF_INIT;
2198 if (get_ref_atom_value(a, s->atom, &va, &err))
2200 if (get_ref_atom_value(b, s->atom, &vb, &err))
2202 strbuf_release(&err);
2203 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2205 cmp = versioncmp(va->s, vb->s);
2206 else if (cmp_type == FIELD_STR)
2207 cmp = cmp_fn(va->s, vb->s);
2209 if (va->value < vb->value)
2211 else if (va->value == vb->value)
2212 cmp = cmp_fn(a->refname, b->refname);
2217 return (s->reverse) ? -cmp : cmp;
2220 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2222 struct ref_array_item *a = *((struct ref_array_item **)a_);
2223 struct ref_array_item *b = *((struct ref_array_item **)b_);
2224 struct ref_sorting *s;
2226 for (s = ref_sorting; s; s = s->next) {
2227 int cmp = cmp_ref_sorting(s, a, b);
2234 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2236 QSORT_S(array->items, array->nr, compare_refs, sorting);
2239 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2241 struct strbuf *s = &state->stack->output;
2243 while (*cp && (!ep || cp < ep)) {
2248 int ch = hex2chr(cp + 1);
2250 strbuf_addch(s, ch);
2256 strbuf_addch(s, *cp);
2261 int format_ref_array_item(struct ref_array_item *info,
2262 const struct ref_format *format,
2263 struct strbuf *final_buf,
2264 struct strbuf *error_buf)
2266 const char *cp, *sp, *ep;
2267 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2269 state.quote_style = format->quote_style;
2270 push_stack_element(&state.stack);
2272 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2273 struct atom_value *atomv;
2276 ep = strchr(sp, ')');
2278 append_literal(cp, sp, &state);
2279 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2280 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2281 atomv->handler(atomv, &state, error_buf)) {
2282 pop_stack_element(&state.stack);
2287 sp = cp + strlen(cp);
2288 append_literal(cp, sp, &state);
2290 if (format->need_color_reset_at_eol) {
2291 struct atom_value resetv;
2292 resetv.s = GIT_COLOR_RESET;
2293 if (append_atom(&resetv, &state, error_buf)) {
2294 pop_stack_element(&state.stack);
2298 if (state.stack->prev) {
2299 pop_stack_element(&state.stack);
2300 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2302 strbuf_addbuf(final_buf, &state.stack->output);
2303 pop_stack_element(&state.stack);
2307 void show_ref_array_item(struct ref_array_item *info,
2308 const struct ref_format *format)
2310 struct strbuf final_buf = STRBUF_INIT;
2311 struct strbuf error_buf = STRBUF_INIT;
2313 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2314 die("%s", error_buf.buf);
2315 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2316 strbuf_release(&error_buf);
2317 strbuf_release(&final_buf);
2321 void pretty_print_ref(const char *name, const struct object_id *oid,
2322 const struct ref_format *format)
2324 struct ref_array_item *ref_item;
2325 ref_item = new_ref_array_item(name, oid);
2326 ref_item->kind = ref_kind_from_refname(name);
2327 show_ref_array_item(ref_item, format);
2328 free_array_item(ref_item);
2331 static int parse_sorting_atom(const char *atom)
2334 * This parses an atom using a dummy ref_format, since we don't
2335 * actually care about the formatting details.
2337 struct ref_format dummy = REF_FORMAT_INIT;
2338 const char *end = atom + strlen(atom);
2339 struct strbuf err = STRBUF_INIT;
2340 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2343 strbuf_release(&err);
2347 /* If no sorting option is given, use refname to sort as default */
2348 struct ref_sorting *ref_default_sorting(void)
2350 static const char cstr_name[] = "refname";
2352 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2354 sorting->next = NULL;
2355 sorting->atom = parse_sorting_atom(cstr_name);
2359 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2361 struct ref_sorting *s;
2363 s = xcalloc(1, sizeof(*s));
2364 s->next = *sorting_tail;
2371 if (skip_prefix(arg, "version:", &arg) ||
2372 skip_prefix(arg, "v:", &arg))
2374 s->atom = parse_sorting_atom(arg);
2377 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2380 * NEEDSWORK: We should probably clear the list in this case, but we've
2381 * already munged the global used_atoms list, which would need to be
2384 BUG_ON_OPT_NEG(unset);
2386 parse_ref_sorting(opt->value, arg);
2390 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2392 struct ref_filter *rf = opt->value;
2393 struct object_id oid;
2394 int no_merged = starts_with(opt->long_name, "no");
2396 BUG_ON_OPT_NEG(unset);
2400 return error(_("option `%s' is incompatible with --merged"),
2403 return error(_("option `%s' is incompatible with --no-merged"),
2408 rf->merge = no_merged
2409 ? REF_FILTER_MERGED_OMIT
2410 : REF_FILTER_MERGED_INCLUDE;
2412 if (get_oid(arg, &oid))
2413 die(_("malformed object name %s"), arg);
2415 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2417 if (!rf->merge_commit)
2418 return error(_("option `%s' must point to a commit"), opt->long_name);