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"
25 #include "argv-array.h"
27 static struct ref_msg {
31 const char *ahead_behind;
33 /* Untranslated plumbing messages: */
40 void setup_ref_filter_porcelain_msg(void)
42 msgs.gone = _("gone");
43 msgs.ahead = _("ahead %d");
44 msgs.behind = _("behind %d");
45 msgs.ahead_behind = _("ahead %d, behind %d");
48 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
49 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
50 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
58 cmp_status cmp_status;
60 unsigned int then_atom_seen : 1,
62 condition_satisfied : 1;
66 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
70 static struct expand_data {
72 enum object_type type;
75 struct object_id delta_base_oid;
78 struct object_info info;
81 struct ref_to_worktree_entry {
82 struct hashmap_entry ent; /* must be the first member! */
83 struct worktree *wt; /* key is wt->head_ref */
86 static int ref_to_worktree_map_cmpfnc(const void *unused_lookupdata,
87 const void *existing_hashmap_entry_to_test,
89 const void *keydata_aka_refname)
91 const struct ref_to_worktree_entry *e = existing_hashmap_entry_to_test;
92 const struct ref_to_worktree_entry *k = key;
93 return strcmp(e->wt->head_ref,
94 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
97 static struct ref_to_worktree_map {
99 struct worktree **worktrees;
100 } ref_to_worktree_map;
103 * An atom is a valid field atom listed below, possibly prefixed with
104 * a "*" to denote deref_tag().
106 * We parse given format string and sort specifiers, and make a list
107 * of properties that we need to extract out of objects. ref_array_item
108 * structure will hold an array of values extracted that can be
109 * indexed with the "atom number", which is an index into this
112 static struct used_atom {
117 char color[COLOR_MAXLEN];
121 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
123 struct refname_atom refname;
124 unsigned int nobracket : 1, push : 1, push_remote : 1;
127 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
128 struct process_trailer_options trailer_opts;
132 cmp_status cmp_status;
136 enum { O_FULL, O_LENGTH, O_SHORT } option;
139 struct refname_atom refname;
143 static int used_atom_cnt, need_tagged, need_symref;
146 * Expand string, append it to strbuf *sb, then return error code ret.
147 * Allow to save few lines of code.
149 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
153 strbuf_vaddf(sb, fmt, ap);
158 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
159 const char *color_value, struct strbuf *err)
162 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
163 if (color_parse(color_value, atom->u.color) < 0)
164 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
167 * We check this after we've parsed the color, which lets us complain
168 * about syntactically bogus color names even if they won't be used.
170 if (!want_color(format->use_color))
171 color_parse("", atom->u.color);
175 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
176 const char *name, struct strbuf *err)
179 atom->option = R_NORMAL;
180 else if (!strcmp(arg, "short"))
181 atom->option = R_SHORT;
182 else if (skip_prefix(arg, "lstrip=", &arg) ||
183 skip_prefix(arg, "strip=", &arg)) {
184 atom->option = R_LSTRIP;
185 if (strtol_i(arg, 10, &atom->lstrip))
186 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
187 } else if (skip_prefix(arg, "rstrip=", &arg)) {
188 atom->option = R_RSTRIP;
189 if (strtol_i(arg, 10, &atom->rstrip))
190 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
192 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
196 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
197 const char *arg, struct strbuf *err)
199 struct string_list params = STRING_LIST_INIT_DUP;
202 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
203 atom->u.remote_ref.push = 1;
206 atom->u.remote_ref.option = RR_REF;
207 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
208 arg, atom->name, err);
211 atom->u.remote_ref.nobracket = 0;
212 string_list_split(¶ms, arg, ',', -1);
214 for (i = 0; i < params.nr; i++) {
215 const char *s = params.items[i].string;
217 if (!strcmp(s, "track"))
218 atom->u.remote_ref.option = RR_TRACK;
219 else if (!strcmp(s, "trackshort"))
220 atom->u.remote_ref.option = RR_TRACKSHORT;
221 else if (!strcmp(s, "nobracket"))
222 atom->u.remote_ref.nobracket = 1;
223 else if (!strcmp(s, "remotename")) {
224 atom->u.remote_ref.option = RR_REMOTE_NAME;
225 atom->u.remote_ref.push_remote = 1;
226 } else if (!strcmp(s, "remoteref")) {
227 atom->u.remote_ref.option = RR_REMOTE_REF;
228 atom->u.remote_ref.push_remote = 1;
230 atom->u.remote_ref.option = RR_REF;
231 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
232 arg, atom->name, err)) {
233 string_list_clear(¶ms, 0);
239 string_list_clear(¶ms, 0);
243 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
244 const char *arg, struct strbuf *err)
247 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
248 if (*atom->name == '*')
249 oi_deref.info.typep = &oi_deref.type;
251 oi.info.typep = &oi.type;
255 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
256 const char *arg, struct strbuf *err)
259 if (*atom->name == '*')
260 oi_deref.info.sizep = &oi_deref.size;
262 oi.info.sizep = &oi.size;
263 } else if (!strcmp(arg, "disk")) {
264 if (*atom->name == '*')
265 oi_deref.info.disk_sizep = &oi_deref.disk_size;
267 oi.info.disk_sizep = &oi.disk_size;
269 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
273 static int deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom,
274 const char *arg, struct strbuf *err)
277 return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
278 if (*atom->name == '*')
279 oi_deref.info.delta_base_sha1 = oi_deref.delta_base_oid.hash;
281 oi.info.delta_base_sha1 = oi.delta_base_oid.hash;
285 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
286 const char *arg, struct strbuf *err)
289 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
290 atom->u.contents.option = C_BODY_DEP;
294 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
295 const char *arg, struct strbuf *err)
298 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
299 atom->u.contents.option = C_SUB;
303 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
304 const char *arg, struct strbuf *err)
306 struct string_list params = STRING_LIST_INIT_DUP;
309 atom->u.contents.trailer_opts.no_divider = 1;
312 string_list_split(¶ms, arg, ',', -1);
313 for (i = 0; i < params.nr; i++) {
314 const char *s = params.items[i].string;
315 if (!strcmp(s, "unfold"))
316 atom->u.contents.trailer_opts.unfold = 1;
317 else if (!strcmp(s, "only"))
318 atom->u.contents.trailer_opts.only_trailers = 1;
320 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
321 string_list_clear(¶ms, 0);
326 atom->u.contents.option = C_TRAILERS;
327 string_list_clear(¶ms, 0);
331 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
332 const char *arg, struct strbuf *err)
335 atom->u.contents.option = C_BARE;
336 else if (!strcmp(arg, "body"))
337 atom->u.contents.option = C_BODY;
338 else if (!strcmp(arg, "signature"))
339 atom->u.contents.option = C_SIG;
340 else if (!strcmp(arg, "subject"))
341 atom->u.contents.option = C_SUB;
342 else if (skip_prefix(arg, "trailers", &arg)) {
343 skip_prefix(arg, ":", &arg);
344 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
346 } else if (skip_prefix(arg, "lines=", &arg)) {
347 atom->u.contents.option = C_LINES;
348 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
349 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
351 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
355 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
356 const char *arg, struct strbuf *err)
359 atom->u.objectname.option = O_FULL;
360 else if (!strcmp(arg, "short"))
361 atom->u.objectname.option = O_SHORT;
362 else if (skip_prefix(arg, "short=", &arg)) {
363 atom->u.objectname.option = O_LENGTH;
364 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
365 atom->u.objectname.length == 0)
366 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
367 if (atom->u.objectname.length < MINIMUM_ABBREV)
368 atom->u.objectname.length = MINIMUM_ABBREV;
370 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
374 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
375 const char *arg, struct strbuf *err)
377 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
380 static align_type parse_align_position(const char *s)
382 if (!strcmp(s, "right"))
384 else if (!strcmp(s, "middle"))
386 else if (!strcmp(s, "left"))
391 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
392 const char *arg, struct strbuf *err)
394 struct align *align = &atom->u.align;
395 struct string_list params = STRING_LIST_INIT_DUP;
397 unsigned int width = ~0U;
400 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
402 align->position = ALIGN_LEFT;
404 string_list_split(¶ms, arg, ',', -1);
405 for (i = 0; i < params.nr; i++) {
406 const char *s = params.items[i].string;
409 if (skip_prefix(s, "position=", &s)) {
410 position = parse_align_position(s);
412 strbuf_addf(err, _("unrecognized position:%s"), s);
413 string_list_clear(¶ms, 0);
416 align->position = position;
417 } else if (skip_prefix(s, "width=", &s)) {
418 if (strtoul_ui(s, 10, &width)) {
419 strbuf_addf(err, _("unrecognized width:%s"), s);
420 string_list_clear(¶ms, 0);
423 } else if (!strtoul_ui(s, 10, &width))
425 else if ((position = parse_align_position(s)) >= 0)
426 align->position = position;
428 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
429 string_list_clear(¶ms, 0);
435 string_list_clear(¶ms, 0);
436 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
438 align->width = width;
439 string_list_clear(¶ms, 0);
443 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
444 const char *arg, struct strbuf *err)
447 atom->u.if_then_else.cmp_status = COMPARE_NONE;
449 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
450 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
451 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
452 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
454 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
458 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
459 const char *arg, struct strbuf *unused_err)
461 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
469 int (*parser)(const struct ref_format *format, struct used_atom *atom,
470 const char *arg, struct strbuf *err);
472 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
473 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
474 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
475 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
476 { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
477 { "tree", SOURCE_OBJ },
478 { "parent", SOURCE_OBJ },
479 { "numparent", SOURCE_OBJ, FIELD_ULONG },
480 { "object", SOURCE_OBJ },
481 { "type", SOURCE_OBJ },
482 { "tag", SOURCE_OBJ },
483 { "author", SOURCE_OBJ },
484 { "authorname", SOURCE_OBJ },
485 { "authoremail", SOURCE_OBJ },
486 { "authordate", SOURCE_OBJ, FIELD_TIME },
487 { "committer", SOURCE_OBJ },
488 { "committername", SOURCE_OBJ },
489 { "committeremail", SOURCE_OBJ },
490 { "committerdate", SOURCE_OBJ, FIELD_TIME },
491 { "tagger", SOURCE_OBJ },
492 { "taggername", SOURCE_OBJ },
493 { "taggeremail", SOURCE_OBJ },
494 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
495 { "creator", SOURCE_OBJ },
496 { "creatordate", SOURCE_OBJ, FIELD_TIME },
497 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
498 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
499 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
500 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
501 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
502 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
503 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
504 { "flag", SOURCE_NONE },
505 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
506 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
507 { "worktreepath", SOURCE_NONE },
508 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
509 { "end", SOURCE_NONE },
510 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
511 { "then", SOURCE_NONE },
512 { "else", SOURCE_NONE },
514 * Please update $__git_ref_fieldlist in git-completion.bash
515 * when you add new atoms
519 #define REF_FORMATTING_STATE_INIT { 0, NULL }
521 struct ref_formatting_stack {
522 struct ref_formatting_stack *prev;
523 struct strbuf output;
524 void (*at_end)(struct ref_formatting_stack **stack);
528 struct ref_formatting_state {
530 struct ref_formatting_stack *stack;
535 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
537 uintmax_t value; /* used for sorting when not FIELD_STR */
538 struct used_atom *atom;
542 * Used to parse format string and sort specifiers
544 static int parse_ref_filter_atom(const struct ref_format *format,
545 const char *atom, const char *ep,
553 if (*sp == '*' && sp < ep)
556 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
557 (int)(ep-atom), atom);
559 /* Do we have the atom already used elsewhere? */
560 for (i = 0; i < used_atom_cnt; i++) {
561 int len = strlen(used_atom[i].name);
562 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
567 * If the atom name has a colon, strip it and everything after
568 * it off - it specifies the format for this entry, and
569 * shouldn't be used for checking against the valid_atom
572 arg = memchr(sp, ':', ep - sp);
573 atom_len = (arg ? arg : ep) - sp;
575 /* Is the atom a valid one? */
576 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
577 int len = strlen(valid_atom[i].name);
578 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
582 if (ARRAY_SIZE(valid_atom) <= i)
583 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
584 (int)(ep-atom), atom);
585 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
586 return strbuf_addf_ret(err, -1,
587 _("not a git repository, but the field '%.*s' requires access to object data"),
588 (int)(ep-atom), atom);
590 /* Add it in, including the deref prefix */
593 REALLOC_ARRAY(used_atom, used_atom_cnt);
594 used_atom[at].name = xmemdupz(atom, ep - atom);
595 used_atom[at].type = valid_atom[i].cmp_type;
596 used_atom[at].source = valid_atom[i].source;
597 if (used_atom[at].source == SOURCE_OBJ) {
599 oi_deref.info.contentp = &oi_deref.content;
601 oi.info.contentp = &oi.content;
604 arg = used_atom[at].name + (arg - atom) + 1;
607 * Treat empty sub-arguments list as NULL (i.e.,
608 * "%(atom:)" is equivalent to "%(atom)").
613 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
614 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
618 if (!strcmp(valid_atom[i].name, "symref"))
623 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
625 switch (quote_style) {
627 strbuf_addstr(s, str);
630 sq_quote_buf(s, str);
633 perl_quote_buf(s, str);
636 python_quote_buf(s, str);
639 tcl_quote_buf(s, str);
644 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
645 struct strbuf *unused_err)
648 * Quote formatting is only done when the stack has a single
649 * element. Otherwise quote formatting is done on the
650 * element's entire output strbuf when the %(end) atom is
653 if (!state->stack->prev)
654 quote_formatting(&state->stack->output, v->s, state->quote_style);
656 strbuf_addstr(&state->stack->output, v->s);
660 static void push_stack_element(struct ref_formatting_stack **stack)
662 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
664 strbuf_init(&s->output, 0);
669 static void pop_stack_element(struct ref_formatting_stack **stack)
671 struct ref_formatting_stack *current = *stack;
672 struct ref_formatting_stack *prev = current->prev;
675 strbuf_addbuf(&prev->output, ¤t->output);
676 strbuf_release(¤t->output);
681 static void end_align_handler(struct ref_formatting_stack **stack)
683 struct ref_formatting_stack *cur = *stack;
684 struct align *align = (struct align *)cur->at_end_data;
685 struct strbuf s = STRBUF_INIT;
687 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
688 strbuf_swap(&cur->output, &s);
692 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
693 struct strbuf *unused_err)
695 struct ref_formatting_stack *new_stack;
697 push_stack_element(&state->stack);
698 new_stack = state->stack;
699 new_stack->at_end = end_align_handler;
700 new_stack->at_end_data = &atomv->atom->u.align;
704 static void if_then_else_handler(struct ref_formatting_stack **stack)
706 struct ref_formatting_stack *cur = *stack;
707 struct ref_formatting_stack *prev = cur->prev;
708 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
710 if (!if_then_else->then_atom_seen)
711 die(_("format: %%(if) atom used without a %%(then) atom"));
713 if (if_then_else->else_atom_seen) {
715 * There is an %(else) atom: we need to drop one state from the
716 * stack, either the %(else) branch if the condition is satisfied, or
717 * the %(then) branch if it isn't.
719 if (if_then_else->condition_satisfied) {
720 strbuf_reset(&cur->output);
721 pop_stack_element(&cur);
723 strbuf_swap(&cur->output, &prev->output);
724 strbuf_reset(&cur->output);
725 pop_stack_element(&cur);
727 } else if (!if_then_else->condition_satisfied) {
729 * No %(else) atom: just drop the %(then) branch if the
730 * condition is not satisfied.
732 strbuf_reset(&cur->output);
739 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
740 struct strbuf *unused_err)
742 struct ref_formatting_stack *new_stack;
743 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
745 if_then_else->str = atomv->atom->u.if_then_else.str;
746 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
748 push_stack_element(&state->stack);
749 new_stack = state->stack;
750 new_stack->at_end = if_then_else_handler;
751 new_stack->at_end_data = if_then_else;
755 static int is_empty(const char *s)
765 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
768 struct ref_formatting_stack *cur = state->stack;
769 struct if_then_else *if_then_else = NULL;
771 if (cur->at_end == if_then_else_handler)
772 if_then_else = (struct if_then_else *)cur->at_end_data;
774 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
775 if (if_then_else->then_atom_seen)
776 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
777 if (if_then_else->else_atom_seen)
778 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
779 if_then_else->then_atom_seen = 1;
781 * If the 'equals' or 'notequals' attribute is used then
782 * perform the required comparison. If not, only non-empty
783 * strings satisfy the 'if' condition.
785 if (if_then_else->cmp_status == COMPARE_EQUAL) {
786 if (!strcmp(if_then_else->str, cur->output.buf))
787 if_then_else->condition_satisfied = 1;
788 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
789 if (strcmp(if_then_else->str, cur->output.buf))
790 if_then_else->condition_satisfied = 1;
791 } else if (cur->output.len && !is_empty(cur->output.buf))
792 if_then_else->condition_satisfied = 1;
793 strbuf_reset(&cur->output);
797 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
800 struct ref_formatting_stack *prev = state->stack;
801 struct if_then_else *if_then_else = NULL;
803 if (prev->at_end == if_then_else_handler)
804 if_then_else = (struct if_then_else *)prev->at_end_data;
806 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
807 if (!if_then_else->then_atom_seen)
808 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
809 if (if_then_else->else_atom_seen)
810 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
811 if_then_else->else_atom_seen = 1;
812 push_stack_element(&state->stack);
813 state->stack->at_end_data = prev->at_end_data;
814 state->stack->at_end = prev->at_end;
818 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
821 struct ref_formatting_stack *current = state->stack;
822 struct strbuf s = STRBUF_INIT;
824 if (!current->at_end)
825 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
826 current->at_end(&state->stack);
828 /* Stack may have been popped within at_end(), hence reset the current pointer */
829 current = state->stack;
832 * Perform quote formatting when the stack element is that of
833 * a supporting atom. If nested then perform quote formatting
834 * only on the topmost supporting atom.
836 if (!current->prev->prev) {
837 quote_formatting(&s, current->output.buf, state->quote_style);
838 strbuf_swap(¤t->output, &s);
841 pop_stack_element(&state->stack);
846 * In a format string, find the next occurrence of %(atom).
848 static const char *find_next(const char *cp)
853 * %( is the start of an atom;
854 * %% is a quoted per-cent.
858 else if (cp[1] == '%')
859 cp++; /* skip over two % */
860 /* otherwise this is a singleton, literal % */
868 * Make sure the format string is well formed, and parse out
871 int verify_ref_format(struct ref_format *format)
875 format->need_color_reset_at_eol = 0;
876 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
877 struct strbuf err = STRBUF_INIT;
878 const char *color, *ep = strchr(sp, ')');
882 return error(_("malformed format string %s"), sp);
883 /* sp points at "%(" and ep points at the closing ")" */
884 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
889 if (skip_prefix(used_atom[at].name, "color:", &color))
890 format->need_color_reset_at_eol = !!strcmp(color, "reset");
891 strbuf_release(&err);
893 if (format->need_color_reset_at_eol && !want_color(format->use_color))
894 format->need_color_reset_at_eol = 0;
898 static int grab_objectname(const char *name, const struct object_id *oid,
899 struct atom_value *v, struct used_atom *atom)
901 if (starts_with(name, "objectname")) {
902 if (atom->u.objectname.option == O_SHORT) {
903 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
905 } else if (atom->u.objectname.option == O_FULL) {
906 v->s = xstrdup(oid_to_hex(oid));
908 } else if (atom->u.objectname.option == O_LENGTH) {
909 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
912 BUG("unknown %%(objectname) option");
917 /* See grab_values */
918 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
922 for (i = 0; i < used_atom_cnt; i++) {
923 const char *name = used_atom[i].name;
924 struct atom_value *v = &val[i];
925 if (!!deref != (*name == '*'))
929 if (!strcmp(name, "objecttype"))
930 v->s = xstrdup(type_name(oi->type));
931 else if (!strcmp(name, "objectsize:disk")) {
932 v->value = oi->disk_size;
933 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
934 } else if (!strcmp(name, "objectsize")) {
936 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
937 } else if (!strcmp(name, "deltabase"))
938 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
940 grab_objectname(name, &oi->oid, v, &used_atom[i]);
944 /* See grab_values */
945 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
948 struct tag *tag = (struct tag *) obj;
950 for (i = 0; i < used_atom_cnt; i++) {
951 const char *name = used_atom[i].name;
952 struct atom_value *v = &val[i];
953 if (!!deref != (*name == '*'))
957 if (!strcmp(name, "tag"))
958 v->s = xstrdup(tag->tag);
959 else if (!strcmp(name, "type") && tag->tagged)
960 v->s = xstrdup(type_name(tag->tagged->type));
961 else if (!strcmp(name, "object") && tag->tagged)
962 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
966 /* See grab_values */
967 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
970 struct commit *commit = (struct commit *) obj;
972 for (i = 0; i < used_atom_cnt; i++) {
973 const char *name = used_atom[i].name;
974 struct atom_value *v = &val[i];
975 if (!!deref != (*name == '*'))
979 if (!strcmp(name, "tree")) {
980 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
982 else if (!strcmp(name, "numparent")) {
983 v->value = commit_list_count(commit->parents);
984 v->s = xstrfmt("%lu", (unsigned long)v->value);
986 else if (!strcmp(name, "parent")) {
987 struct commit_list *parents;
988 struct strbuf s = STRBUF_INIT;
989 for (parents = commit->parents; parents; parents = parents->next) {
990 struct commit *parent = parents->item;
991 if (parents != commit->parents)
992 strbuf_addch(&s, ' ');
993 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
995 v->s = strbuf_detach(&s, NULL);
1000 static const char *find_wholine(const char *who, int wholen, const char *buf)
1004 if (!strncmp(buf, who, wholen) &&
1006 return buf + wholen + 1;
1007 eol = strchr(buf, '\n');
1012 return ""; /* end of header */
1018 static const char *copy_line(const char *buf)
1020 const char *eol = strchrnul(buf, '\n');
1021 return xmemdupz(buf, eol - buf);
1024 static const char *copy_name(const char *buf)
1027 for (cp = buf; *cp && *cp != '\n'; cp++) {
1028 if (!strncmp(cp, " <", 2))
1029 return xmemdupz(buf, cp - buf);
1034 static const char *copy_email(const char *buf)
1036 const char *email = strchr(buf, '<');
1037 const char *eoemail;
1040 eoemail = strchr(email, '>');
1043 return xmemdupz(email, eoemail + 1 - email);
1046 static char *copy_subject(const char *buf, unsigned long len)
1048 char *r = xmemdupz(buf, len);
1051 for (i = 0; i < len; i++)
1058 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1060 const char *eoemail = strstr(buf, "> ");
1062 timestamp_t timestamp;
1064 struct date_mode date_mode = { DATE_NORMAL };
1065 const char *formatp;
1068 * We got here because atomname ends in "date" or "date<something>";
1069 * it's not possible that <something> is not ":<format>" because
1070 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1071 * ":" means no format is specified, and use the default.
1073 formatp = strchr(atomname, ':');
1074 if (formatp != NULL) {
1076 parse_date_format(formatp, &date_mode);
1081 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1082 if (timestamp == TIME_MAX)
1084 tz = strtol(zone, NULL, 10);
1085 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1087 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1088 v->value = timestamp;
1095 /* See grab_values */
1096 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1099 int wholen = strlen(who);
1100 const char *wholine = NULL;
1102 for (i = 0; i < used_atom_cnt; i++) {
1103 const char *name = used_atom[i].name;
1104 struct atom_value *v = &val[i];
1105 if (!!deref != (*name == '*'))
1109 if (strncmp(who, name, wholen))
1111 if (name[wholen] != 0 &&
1112 strcmp(name + wholen, "name") &&
1113 strcmp(name + wholen, "email") &&
1114 !starts_with(name + wholen, "date"))
1117 wholine = find_wholine(who, wholen, buf);
1119 return; /* no point looking for it */
1120 if (name[wholen] == 0)
1121 v->s = copy_line(wholine);
1122 else if (!strcmp(name + wholen, "name"))
1123 v->s = copy_name(wholine);
1124 else if (!strcmp(name + wholen, "email"))
1125 v->s = copy_email(wholine);
1126 else if (starts_with(name + wholen, "date"))
1127 grab_date(wholine, v, name);
1131 * For a tag or a commit object, if "creator" or "creatordate" is
1132 * requested, do something special.
1134 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1135 return; /* "author" for commit object is not wanted */
1137 wholine = find_wholine(who, wholen, buf);
1140 for (i = 0; i < used_atom_cnt; i++) {
1141 const char *name = used_atom[i].name;
1142 struct atom_value *v = &val[i];
1143 if (!!deref != (*name == '*'))
1148 if (starts_with(name, "creatordate"))
1149 grab_date(wholine, v, name);
1150 else if (!strcmp(name, "creator"))
1151 v->s = copy_line(wholine);
1155 static void find_subpos(const char *buf,
1156 const char **sub, unsigned long *sublen,
1157 const char **body, unsigned long *bodylen,
1158 unsigned long *nonsiglen,
1159 const char **sig, unsigned long *siglen)
1162 /* skip past header until we hit empty line */
1163 while (*buf && *buf != '\n') {
1164 eol = strchrnul(buf, '\n');
1169 /* skip any empty lines */
1170 while (*buf == '\n')
1173 /* parse signature first; we might not even have a subject line */
1174 *sig = buf + parse_signature(buf, strlen(buf));
1175 *siglen = strlen(*sig);
1177 /* subject is first non-empty line */
1179 /* subject goes to first empty line */
1180 while (buf < *sig && *buf && *buf != '\n') {
1181 eol = strchrnul(buf, '\n');
1186 *sublen = buf - *sub;
1187 /* drop trailing newline, if present */
1188 if (*sublen && (*sub)[*sublen - 1] == '\n')
1191 /* skip any empty lines */
1192 while (*buf == '\n')
1195 *bodylen = strlen(buf);
1196 *nonsiglen = *sig - buf;
1200 * If 'lines' is greater than 0, append that many lines from the given
1201 * 'buf' of length 'size' to the given strbuf.
1203 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1206 const char *sp, *eol;
1211 for (i = 0; i < lines && sp < buf + size; i++) {
1213 strbuf_addstr(out, "\n ");
1214 eol = memchr(sp, '\n', size - (sp - buf));
1215 len = eol ? eol - sp : size - (sp - buf);
1216 strbuf_add(out, sp, len);
1223 /* See grab_values */
1224 static void grab_sub_body_contents(struct atom_value *val, int deref, void *buf)
1227 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1228 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1230 for (i = 0; i < used_atom_cnt; i++) {
1231 struct used_atom *atom = &used_atom[i];
1232 const char *name = atom->name;
1233 struct atom_value *v = &val[i];
1234 if (!!deref != (*name == '*'))
1238 if (strcmp(name, "subject") &&
1239 strcmp(name, "body") &&
1240 !starts_with(name, "trailers") &&
1241 !starts_with(name, "contents"))
1246 &bodypos, &bodylen, &nonsiglen,
1249 if (atom->u.contents.option == C_SUB)
1250 v->s = copy_subject(subpos, sublen);
1251 else if (atom->u.contents.option == C_BODY_DEP)
1252 v->s = xmemdupz(bodypos, bodylen);
1253 else if (atom->u.contents.option == C_BODY)
1254 v->s = xmemdupz(bodypos, nonsiglen);
1255 else if (atom->u.contents.option == C_SIG)
1256 v->s = xmemdupz(sigpos, siglen);
1257 else if (atom->u.contents.option == C_LINES) {
1258 struct strbuf s = STRBUF_INIT;
1259 const char *contents_end = bodylen + bodypos - siglen;
1261 /* Size is the length of the message after removing the signature */
1262 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1263 v->s = strbuf_detach(&s, NULL);
1264 } else if (atom->u.contents.option == C_TRAILERS) {
1265 struct strbuf s = STRBUF_INIT;
1267 /* Format the trailer info according to the trailer_opts given */
1268 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1270 v->s = strbuf_detach(&s, NULL);
1271 } else if (atom->u.contents.option == C_BARE)
1272 v->s = xstrdup(subpos);
1277 * We want to have empty print-string for field requests
1278 * that do not apply (e.g. "authordate" for a tag object)
1280 static void fill_missing_values(struct atom_value *val)
1283 for (i = 0; i < used_atom_cnt; i++) {
1284 struct atom_value *v = &val[i];
1291 * val is a list of atom_value to hold returned values. Extract
1292 * the values for atoms in used_atom array out of (obj, buf, sz).
1293 * when deref is false, (obj, buf, sz) is the object that is
1294 * pointed at by the ref itself; otherwise it is the object the
1295 * ref (which is a tag) refers to.
1297 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf)
1299 switch (obj->type) {
1301 grab_tag_values(val, deref, obj);
1302 grab_sub_body_contents(val, deref, buf);
1303 grab_person("tagger", val, deref, buf);
1306 grab_commit_values(val, deref, obj);
1307 grab_sub_body_contents(val, deref, buf);
1308 grab_person("author", val, deref, buf);
1309 grab_person("committer", val, deref, buf);
1312 /* grab_tree_values(val, deref, obj, buf, sz); */
1315 /* grab_blob_values(val, deref, obj, buf, sz); */
1318 die("Eh? Object of type %d?", obj->type);
1322 static inline char *copy_advance(char *dst, const char *src)
1329 static const char *lstrip_ref_components(const char *refname, int len)
1331 long remaining = len;
1332 const char *start = xstrdup(refname);
1333 const char *to_free = start;
1337 const char *p = refname;
1339 /* Find total no of '/' separated path-components */
1340 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1343 * The number of components we need to strip is now
1344 * the total minus the components to be left (Plus one
1345 * because we count the number of '/', but the number
1346 * of components is one more than the no of '/').
1348 remaining = i + len + 1;
1351 while (remaining > 0) {
1354 free((char *)to_free);
1362 start = xstrdup(start);
1363 free((char *)to_free);
1367 static const char *rstrip_ref_components(const char *refname, int len)
1369 long remaining = len;
1370 const char *start = xstrdup(refname);
1371 const char *to_free = start;
1375 const char *p = refname;
1377 /* Find total no of '/' separated path-components */
1378 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1381 * The number of components we need to strip is now
1382 * the total minus the components to be left (Plus one
1383 * because we count the number of '/', but the number
1384 * of components is one more than the no of '/').
1386 remaining = i + len + 1;
1389 while (remaining-- > 0) {
1390 char *p = strrchr(start, '/');
1392 free((char *)to_free);
1400 static const char *show_ref(struct refname_atom *atom, const char *refname)
1402 if (atom->option == R_SHORT)
1403 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1404 else if (atom->option == R_LSTRIP)
1405 return lstrip_ref_components(refname, atom->lstrip);
1406 else if (atom->option == R_RSTRIP)
1407 return rstrip_ref_components(refname, atom->rstrip);
1409 return xstrdup(refname);
1412 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1413 struct branch *branch, const char **s)
1415 int num_ours, num_theirs;
1416 if (atom->u.remote_ref.option == RR_REF)
1417 *s = show_ref(&atom->u.remote_ref.refname, refname);
1418 else if (atom->u.remote_ref.option == RR_TRACK) {
1419 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1420 NULL, atom->u.remote_ref.push,
1421 AHEAD_BEHIND_FULL) < 0) {
1422 *s = xstrdup(msgs.gone);
1423 } else if (!num_ours && !num_theirs)
1426 *s = xstrfmt(msgs.behind, num_theirs);
1427 else if (!num_theirs)
1428 *s = xstrfmt(msgs.ahead, num_ours);
1430 *s = xstrfmt(msgs.ahead_behind,
1431 num_ours, num_theirs);
1432 if (!atom->u.remote_ref.nobracket && *s[0]) {
1433 const char *to_free = *s;
1434 *s = xstrfmt("[%s]", *s);
1435 free((void *)to_free);
1437 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1438 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1439 NULL, atom->u.remote_ref.push,
1440 AHEAD_BEHIND_FULL) < 0) {
1444 if (!num_ours && !num_theirs)
1448 else if (!num_theirs)
1452 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1454 const char *remote = atom->u.remote_ref.push ?
1455 pushremote_for_branch(branch, &explicit) :
1456 remote_for_branch(branch, &explicit);
1457 *s = xstrdup(explicit ? remote : "");
1458 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1462 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1464 *s = xstrdup(explicit ? merge : "");
1466 BUG("unhandled RR_* enum");
1469 char *get_head_description(void)
1471 struct strbuf desc = STRBUF_INIT;
1472 struct wt_status_state state;
1473 memset(&state, 0, sizeof(state));
1474 wt_status_get_state(the_repository, &state, 1);
1477 * The ( character must be hard-coded and not part of a localizable
1478 * string, since the description is used as a sort key and compared
1481 strbuf_addch(&desc, '(');
1482 if (state.rebase_in_progress ||
1483 state.rebase_interactive_in_progress) {
1485 strbuf_addf(&desc, _("no branch, rebasing %s"),
1488 strbuf_addf(&desc, _("no branch, rebasing detached HEAD %s"),
1489 state.detached_from);
1490 } else if (state.bisect_in_progress)
1491 strbuf_addf(&desc, _("no branch, bisect started on %s"),
1493 else if (state.detached_from) {
1494 if (state.detached_at)
1495 strbuf_addstr(&desc, HEAD_DETACHED_AT);
1497 strbuf_addstr(&desc, HEAD_DETACHED_FROM);
1498 strbuf_addstr(&desc, state.detached_from);
1501 strbuf_addstr(&desc, _("no branch"));
1502 strbuf_addch(&desc, ')');
1506 free(state.detached_from);
1507 return strbuf_detach(&desc, NULL);
1510 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1515 return show_ref(&atom->u.refname, ref->symref);
1518 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1520 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1521 return get_head_description();
1522 return show_ref(&atom->u.refname, ref->refname);
1525 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1526 struct expand_data *oi, struct strbuf *err)
1528 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1530 if (oi->info.contentp) {
1531 /* We need to know that to use parse_object_buffer properly */
1532 oi->info.sizep = &oi->size;
1533 oi->info.typep = &oi->type;
1535 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1536 OBJECT_INFO_LOOKUP_REPLACE))
1537 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1538 oid_to_hex(&oi->oid), ref->refname);
1539 if (oi->info.disk_sizep && oi->disk_size < 0)
1540 BUG("Object size is less than zero.");
1542 if (oi->info.contentp) {
1543 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1547 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1548 oid_to_hex(&oi->oid), ref->refname);
1550 grab_values(ref->value, deref, *obj, oi->content);
1553 grab_common_values(ref->value, deref, oi);
1559 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1563 for (i = 0; worktrees[i]; i++) {
1564 if (worktrees[i]->head_ref) {
1565 struct ref_to_worktree_entry *entry;
1566 entry = xmalloc(sizeof(*entry));
1567 entry->wt = worktrees[i];
1568 hashmap_entry_init(entry, strhash(worktrees[i]->head_ref));
1570 hashmap_add(map, entry);
1575 static void lazy_init_worktree_map(void)
1577 if (ref_to_worktree_map.worktrees)
1580 ref_to_worktree_map.worktrees = get_worktrees(0);
1581 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1582 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1585 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1587 struct hashmap_entry entry;
1588 struct ref_to_worktree_entry *lookup_result;
1590 lazy_init_worktree_map();
1592 hashmap_entry_init(&entry, strhash(ref->refname));
1593 lookup_result = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1596 return xstrdup(lookup_result->wt->path);
1602 * Parse the object referred by ref, and grab needed value.
1604 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1608 struct object_info empty = OBJECT_INFO_INIT;
1610 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1612 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1613 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1616 ref->symref = xstrdup("");
1619 /* Fill in specials first */
1620 for (i = 0; i < used_atom_cnt; i++) {
1621 struct used_atom *atom = &used_atom[i];
1622 const char *name = used_atom[i].name;
1623 struct atom_value *v = &ref->value[i];
1625 const char *refname;
1626 struct branch *branch = NULL;
1628 v->handler = append_atom;
1636 if (starts_with(name, "refname"))
1637 refname = get_refname(atom, ref);
1638 else if (!strcmp(name, "worktreepath")) {
1639 if (ref->kind == FILTER_REFS_BRANCHES)
1640 v->s = get_worktree_path(atom, ref);
1645 else if (starts_with(name, "symref"))
1646 refname = get_symref(atom, ref);
1647 else if (starts_with(name, "upstream")) {
1648 const char *branch_name;
1649 /* only local branches may have an upstream */
1650 if (!skip_prefix(ref->refname, "refs/heads/",
1655 branch = branch_get(branch_name);
1657 refname = branch_get_upstream(branch, NULL);
1659 fill_remote_ref_details(atom, refname, branch, &v->s);
1663 } else if (atom->u.remote_ref.push) {
1664 const char *branch_name;
1666 if (!skip_prefix(ref->refname, "refs/heads/",
1669 branch = branch_get(branch_name);
1671 if (atom->u.remote_ref.push_remote)
1674 refname = branch_get_push(branch, NULL);
1678 /* We will definitely re-init v->s on the next line. */
1680 fill_remote_ref_details(atom, refname, branch, &v->s);
1682 } else if (starts_with(name, "color:")) {
1683 v->s = xstrdup(atom->u.color);
1685 } else if (!strcmp(name, "flag")) {
1686 char buf[256], *cp = buf;
1687 if (ref->flag & REF_ISSYMREF)
1688 cp = copy_advance(cp, ",symref");
1689 if (ref->flag & REF_ISPACKED)
1690 cp = copy_advance(cp, ",packed");
1695 v->s = xstrdup(buf + 1);
1698 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1700 } else if (!strcmp(name, "HEAD")) {
1701 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1702 v->s = xstrdup("*");
1704 v->s = xstrdup(" ");
1706 } else if (starts_with(name, "align")) {
1707 v->handler = align_atom_handler;
1710 } else if (!strcmp(name, "end")) {
1711 v->handler = end_atom_handler;
1714 } else if (starts_with(name, "if")) {
1716 if (skip_prefix(name, "if:", &s))
1720 v->handler = if_atom_handler;
1722 } else if (!strcmp(name, "then")) {
1723 v->handler = then_atom_handler;
1726 } else if (!strcmp(name, "else")) {
1727 v->handler = else_atom_handler;
1734 v->s = xstrdup(refname);
1736 v->s = xstrfmt("%s^{}", refname);
1737 free((char *)refname);
1740 for (i = 0; i < used_atom_cnt; i++) {
1741 struct atom_value *v = &ref->value[i];
1742 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1743 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1744 oid_to_hex(&ref->objectname), ref->refname);
1748 oi.info.contentp = &oi.content;
1749 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1750 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1754 oi.oid = ref->objectname;
1755 if (get_object(ref, 0, &obj, &oi, err))
1759 * If there is no atom that wants to know about tagged
1760 * object, we are done.
1762 if (!need_tagged || (obj->type != OBJ_TAG))
1766 * If it is a tag object, see if we use a value that derefs
1767 * the object, and if we do grab the object it refers to.
1769 oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1772 * NEEDSWORK: This derefs tag only once, which
1773 * is good to deal with chains of trust, but
1774 * is not consistent with what deref_tag() does
1775 * which peels the onion to the core.
1777 return get_object(ref, 1, &obj, &oi_deref, err);
1781 * Given a ref, return the value for the atom. This lazily gets value
1782 * out of the object by calling populate value.
1784 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1785 struct atom_value **v, struct strbuf *err)
1788 if (populate_value(ref, err))
1790 fill_missing_values(ref->value);
1792 *v = &ref->value[atom];
1797 * Return 1 if the refname matches one of the patterns, otherwise 0.
1798 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1799 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1800 * matches "refs/heads/mas*", too).
1802 static int match_pattern(const struct ref_filter *filter, const char *refname)
1804 const char **patterns = filter->name_patterns;
1807 if (filter->ignore_case)
1808 flags |= WM_CASEFOLD;
1811 * When no '--format' option is given we need to skip the prefix
1812 * for matching refs of tags and branches.
1814 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1815 skip_prefix(refname, "refs/heads/", &refname) ||
1816 skip_prefix(refname, "refs/remotes/", &refname) ||
1817 skip_prefix(refname, "refs/", &refname));
1819 for (; *patterns; patterns++) {
1820 if (!wildmatch(*patterns, refname, flags))
1827 * Return 1 if the refname matches one of the patterns, otherwise 0.
1828 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1829 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1830 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1832 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1834 const char **pattern = filter->name_patterns;
1835 int namelen = strlen(refname);
1836 unsigned flags = WM_PATHNAME;
1838 if (filter->ignore_case)
1839 flags |= WM_CASEFOLD;
1841 for (; *pattern; pattern++) {
1842 const char *p = *pattern;
1843 int plen = strlen(p);
1845 if ((plen <= namelen) &&
1846 !strncmp(refname, p, plen) &&
1847 (refname[plen] == '\0' ||
1848 refname[plen] == '/' ||
1851 if (!wildmatch(p, refname, flags))
1857 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1858 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1860 if (!*filter->name_patterns)
1861 return 1; /* No pattern always matches */
1862 if (filter->match_as_path)
1863 return match_name_as_path(filter, refname);
1864 return match_pattern(filter, refname);
1867 static int qsort_strcmp(const void *va, const void *vb)
1869 const char *a = *(const char **)va;
1870 const char *b = *(const char **)vb;
1872 return strcmp(a, b);
1875 static void find_longest_prefixes_1(struct string_list *out,
1876 struct strbuf *prefix,
1877 const char **patterns, size_t nr)
1881 for (i = 0; i < nr; i++) {
1882 char c = patterns[i][prefix->len];
1883 if (!c || is_glob_special(c)) {
1884 string_list_append(out, prefix->buf);
1894 * Set "end" to the index of the element _after_ the last one
1897 for (end = i + 1; end < nr; end++) {
1898 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1902 strbuf_addch(prefix, patterns[i][prefix->len]);
1903 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1904 strbuf_setlen(prefix, prefix->len - 1);
1910 static void find_longest_prefixes(struct string_list *out,
1911 const char **patterns)
1913 struct argv_array sorted = ARGV_ARRAY_INIT;
1914 struct strbuf prefix = STRBUF_INIT;
1916 argv_array_pushv(&sorted, patterns);
1917 QSORT(sorted.argv, sorted.argc, qsort_strcmp);
1919 find_longest_prefixes_1(out, &prefix, sorted.argv, sorted.argc);
1921 argv_array_clear(&sorted);
1922 strbuf_release(&prefix);
1926 * This is the same as for_each_fullref_in(), but it tries to iterate
1927 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1928 * pattern match, so the callback still has to match each ref individually.
1930 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1935 struct string_list prefixes = STRING_LIST_INIT_DUP;
1936 struct string_list_item *prefix;
1939 if (!filter->match_as_path) {
1941 * in this case, the patterns are applied after
1942 * prefixes like "refs/heads/" etc. are stripped off,
1943 * so we have to look at everything:
1945 return for_each_fullref_in("", cb, cb_data, broken);
1948 if (filter->ignore_case) {
1950 * we can't handle case-insensitive comparisons,
1951 * so just return everything and let the caller
1954 return for_each_fullref_in("", cb, cb_data, broken);
1957 if (!filter->name_patterns[0]) {
1958 /* no patterns; we have to look at everything */
1959 return for_each_fullref_in("", cb, cb_data, broken);
1962 find_longest_prefixes(&prefixes, filter->name_patterns);
1964 for_each_string_list_item(prefix, &prefixes) {
1965 ret = for_each_fullref_in(prefix->string, cb, cb_data, broken);
1970 string_list_clear(&prefixes, 0);
1975 * Given a ref (sha1, refname), check if the ref belongs to the array
1976 * of sha1s. If the given ref is a tag, check if the given tag points
1977 * at one of the sha1s in the given sha1 array.
1978 * the given sha1_array.
1980 * 1. Only a single level of inderection is obtained, we might want to
1981 * change this to account for multiple levels (e.g. annotated tags
1982 * pointing to annotated tags pointing to a commit.)
1983 * 2. As the refs are cached we might know what refname peels to without
1984 * the need to parse the object via parse_object(). peel_ref() might be a
1985 * more efficient alternative to obtain the pointee.
1987 static const struct object_id *match_points_at(struct oid_array *points_at,
1988 const struct object_id *oid,
1989 const char *refname)
1991 const struct object_id *tagged_oid = NULL;
1994 if (oid_array_lookup(points_at, oid) >= 0)
1996 obj = parse_object(the_repository, oid);
1998 die(_("malformed object at '%s'"), refname);
1999 if (obj->type == OBJ_TAG)
2000 tagged_oid = &((struct tag *)obj)->tagged->oid;
2001 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2007 * Allocate space for a new ref_array_item and copy the name and oid to it.
2009 * Callers can then fill in other struct members at their leisure.
2011 static struct ref_array_item *new_ref_array_item(const char *refname,
2012 const struct object_id *oid)
2014 struct ref_array_item *ref;
2016 FLEX_ALLOC_STR(ref, refname, refname);
2017 oidcpy(&ref->objectname, oid);
2022 struct ref_array_item *ref_array_push(struct ref_array *array,
2023 const char *refname,
2024 const struct object_id *oid)
2026 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2028 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2029 array->items[array->nr++] = ref;
2034 static int ref_kind_from_refname(const char *refname)
2042 { "refs/heads/" , FILTER_REFS_BRANCHES },
2043 { "refs/remotes/" , FILTER_REFS_REMOTES },
2044 { "refs/tags/", FILTER_REFS_TAGS}
2047 if (!strcmp(refname, "HEAD"))
2048 return FILTER_REFS_DETACHED_HEAD;
2050 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2051 if (starts_with(refname, ref_kind[i].prefix))
2052 return ref_kind[i].kind;
2055 return FILTER_REFS_OTHERS;
2058 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2060 if (filter->kind == FILTER_REFS_BRANCHES ||
2061 filter->kind == FILTER_REFS_REMOTES ||
2062 filter->kind == FILTER_REFS_TAGS)
2063 return filter->kind;
2064 return ref_kind_from_refname(refname);
2067 struct ref_filter_cbdata {
2068 struct ref_array *array;
2069 struct ref_filter *filter;
2070 struct contains_cache contains_cache;
2071 struct contains_cache no_contains_cache;
2075 * A call-back given to for_each_ref(). Filter refs and keep them for
2076 * later object processing.
2078 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2080 struct ref_filter_cbdata *ref_cbdata = cb_data;
2081 struct ref_filter *filter = ref_cbdata->filter;
2082 struct ref_array_item *ref;
2083 struct commit *commit = NULL;
2086 if (flag & REF_BAD_NAME) {
2087 warning(_("ignoring ref with broken name %s"), refname);
2091 if (flag & REF_ISBROKEN) {
2092 warning(_("ignoring broken ref %s"), refname);
2096 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2097 kind = filter_ref_kind(filter, refname);
2098 if (!(kind & filter->kind))
2101 if (!filter_pattern_match(filter, refname))
2104 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2108 * A merge filter is applied on refs pointing to commits. Hence
2109 * obtain the commit using the 'oid' available and discard all
2110 * non-commits early. The actual filtering is done later.
2112 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2113 commit = lookup_commit_reference_gently(the_repository, oid,
2117 /* We perform the filtering for the '--contains' option... */
2118 if (filter->with_commit &&
2119 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2121 /* ...or for the `--no-contains' option */
2122 if (filter->no_commit &&
2123 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2128 * We do not open the object yet; sort may only need refname
2129 * to do its job and the resulting list may yet to be pruned
2130 * by maxcount logic.
2132 ref = ref_array_push(ref_cbdata->array, refname, oid);
2133 ref->commit = commit;
2140 /* Free memory allocated for a ref_array_item */
2141 static void free_array_item(struct ref_array_item *item)
2143 free((char *)item->symref);
2146 for (i = 0; i < used_atom_cnt; i++)
2147 free((char *)item->value[i].s);
2153 /* Free all memory allocated for ref_array */
2154 void ref_array_clear(struct ref_array *array)
2158 for (i = 0; i < array->nr; i++)
2159 free_array_item(array->items[i]);
2160 FREE_AND_NULL(array->items);
2161 array->nr = array->alloc = 0;
2163 for (i = 0; i < used_atom_cnt; i++)
2164 free((char *)used_atom[i].name);
2165 FREE_AND_NULL(used_atom);
2168 if (ref_to_worktree_map.worktrees) {
2169 hashmap_free(&(ref_to_worktree_map.map), 1);
2170 free_worktrees(ref_to_worktree_map.worktrees);
2171 ref_to_worktree_map.worktrees = NULL;
2175 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2177 struct rev_info revs;
2179 struct ref_filter *filter = ref_cbdata->filter;
2180 struct ref_array *array = ref_cbdata->array;
2181 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2183 repo_init_revisions(the_repository, &revs, NULL);
2185 for (i = 0; i < array->nr; i++) {
2186 struct ref_array_item *item = array->items[i];
2187 add_pending_object(&revs, &item->commit->object, item->refname);
2188 to_clear[i] = item->commit;
2191 filter->merge_commit->object.flags |= UNINTERESTING;
2192 add_pending_object(&revs, &filter->merge_commit->object, "");
2195 if (prepare_revision_walk(&revs))
2196 die(_("revision walk setup failed"));
2201 for (i = 0; i < old_nr; i++) {
2202 struct ref_array_item *item = array->items[i];
2203 struct commit *commit = item->commit;
2205 int is_merged = !!(commit->object.flags & UNINTERESTING);
2207 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2208 array->items[array->nr++] = array->items[i];
2210 free_array_item(item);
2213 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2214 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2219 * API for filtering a set of refs. Based on the type of refs the user
2220 * has requested, we iterate through those refs and apply filters
2221 * as per the given ref_filter structure and finally store the
2222 * filtered refs in the ref_array structure.
2224 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2226 struct ref_filter_cbdata ref_cbdata;
2228 unsigned int broken = 0;
2230 ref_cbdata.array = array;
2231 ref_cbdata.filter = filter;
2233 if (type & FILTER_REFS_INCLUDE_BROKEN)
2235 filter->kind = type & FILTER_REFS_KIND_MASK;
2237 init_contains_cache(&ref_cbdata.contains_cache);
2238 init_contains_cache(&ref_cbdata.no_contains_cache);
2240 /* Simple per-ref filtering */
2242 die("filter_refs: invalid type");
2245 * For common cases where we need only branches or remotes or tags,
2246 * we only iterate through those refs. If a mix of refs is needed,
2247 * we iterate over all refs and filter out required refs with the help
2248 * of filter_ref_kind().
2250 if (filter->kind == FILTER_REFS_BRANCHES)
2251 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2252 else if (filter->kind == FILTER_REFS_REMOTES)
2253 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2254 else if (filter->kind == FILTER_REFS_TAGS)
2255 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2256 else if (filter->kind & FILTER_REFS_ALL)
2257 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2258 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2259 head_ref(ref_filter_handler, &ref_cbdata);
2262 clear_contains_cache(&ref_cbdata.contains_cache);
2263 clear_contains_cache(&ref_cbdata.no_contains_cache);
2265 /* Filters that need revision walking */
2266 if (filter->merge_commit)
2267 do_merge_filter(&ref_cbdata);
2272 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2274 struct atom_value *va, *vb;
2276 cmp_type cmp_type = used_atom[s->atom].type;
2277 int (*cmp_fn)(const char *, const char *);
2278 struct strbuf err = STRBUF_INIT;
2280 if (get_ref_atom_value(a, s->atom, &va, &err))
2282 if (get_ref_atom_value(b, s->atom, &vb, &err))
2284 strbuf_release(&err);
2285 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2287 cmp = versioncmp(va->s, vb->s);
2288 else if (cmp_type == FIELD_STR)
2289 cmp = cmp_fn(va->s, vb->s);
2291 if (va->value < vb->value)
2293 else if (va->value == vb->value)
2294 cmp = cmp_fn(a->refname, b->refname);
2299 return (s->reverse) ? -cmp : cmp;
2302 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2304 struct ref_array_item *a = *((struct ref_array_item **)a_);
2305 struct ref_array_item *b = *((struct ref_array_item **)b_);
2306 struct ref_sorting *s;
2308 for (s = ref_sorting; s; s = s->next) {
2309 int cmp = cmp_ref_sorting(s, a, b);
2316 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2318 QSORT_S(array->items, array->nr, compare_refs, sorting);
2321 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2323 struct strbuf *s = &state->stack->output;
2325 while (*cp && (!ep || cp < ep)) {
2330 int ch = hex2chr(cp + 1);
2332 strbuf_addch(s, ch);
2338 strbuf_addch(s, *cp);
2343 int format_ref_array_item(struct ref_array_item *info,
2344 const struct ref_format *format,
2345 struct strbuf *final_buf,
2346 struct strbuf *error_buf)
2348 const char *cp, *sp, *ep;
2349 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2351 state.quote_style = format->quote_style;
2352 push_stack_element(&state.stack);
2354 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2355 struct atom_value *atomv;
2358 ep = strchr(sp, ')');
2360 append_literal(cp, sp, &state);
2361 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2362 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2363 atomv->handler(atomv, &state, error_buf)) {
2364 pop_stack_element(&state.stack);
2369 sp = cp + strlen(cp);
2370 append_literal(cp, sp, &state);
2372 if (format->need_color_reset_at_eol) {
2373 struct atom_value resetv;
2374 resetv.s = GIT_COLOR_RESET;
2375 if (append_atom(&resetv, &state, error_buf)) {
2376 pop_stack_element(&state.stack);
2380 if (state.stack->prev) {
2381 pop_stack_element(&state.stack);
2382 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2384 strbuf_addbuf(final_buf, &state.stack->output);
2385 pop_stack_element(&state.stack);
2389 void show_ref_array_item(struct ref_array_item *info,
2390 const struct ref_format *format)
2392 struct strbuf final_buf = STRBUF_INIT;
2393 struct strbuf error_buf = STRBUF_INIT;
2395 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2396 die("%s", error_buf.buf);
2397 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2398 strbuf_release(&error_buf);
2399 strbuf_release(&final_buf);
2403 void pretty_print_ref(const char *name, const struct object_id *oid,
2404 const struct ref_format *format)
2406 struct ref_array_item *ref_item;
2407 ref_item = new_ref_array_item(name, oid);
2408 ref_item->kind = ref_kind_from_refname(name);
2409 show_ref_array_item(ref_item, format);
2410 free_array_item(ref_item);
2413 static int parse_sorting_atom(const char *atom)
2416 * This parses an atom using a dummy ref_format, since we don't
2417 * actually care about the formatting details.
2419 struct ref_format dummy = REF_FORMAT_INIT;
2420 const char *end = atom + strlen(atom);
2421 struct strbuf err = STRBUF_INIT;
2422 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2425 strbuf_release(&err);
2429 /* If no sorting option is given, use refname to sort as default */
2430 struct ref_sorting *ref_default_sorting(void)
2432 static const char cstr_name[] = "refname";
2434 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2436 sorting->next = NULL;
2437 sorting->atom = parse_sorting_atom(cstr_name);
2441 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2443 struct ref_sorting *s;
2445 s = xcalloc(1, sizeof(*s));
2446 s->next = *sorting_tail;
2453 if (skip_prefix(arg, "version:", &arg) ||
2454 skip_prefix(arg, "v:", &arg))
2456 s->atom = parse_sorting_atom(arg);
2459 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2462 * NEEDSWORK: We should probably clear the list in this case, but we've
2463 * already munged the global used_atoms list, which would need to be
2466 BUG_ON_OPT_NEG(unset);
2468 parse_ref_sorting(opt->value, arg);
2472 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2474 struct ref_filter *rf = opt->value;
2475 struct object_id oid;
2476 int no_merged = starts_with(opt->long_name, "no");
2478 BUG_ON_OPT_NEG(unset);
2482 return error(_("option `%s' is incompatible with --merged"),
2485 return error(_("option `%s' is incompatible with --no-merged"),
2490 rf->merge = no_merged
2491 ? REF_FILTER_MERGED_OMIT
2492 : REF_FILTER_MERGED_INCLUDE;
2494 if (get_oid(arg, &oid))
2495 die(_("malformed object name %s"), arg);
2497 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2499 if (!rf->merge_commit)
2500 return error(_("option `%s' must point to a commit"), opt->long_name);