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;
83 struct worktree *wt; /* key is wt->head_ref */
86 static int ref_to_worktree_map_cmpfnc(const void *unused_lookupdata,
87 const struct hashmap_entry *eptr,
88 const struct hashmap_entry *kptr,
89 const void *keydata_aka_refname)
91 const struct ref_to_worktree_entry *e, *k;
93 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
94 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
96 return strcmp(e->wt->head_ref,
97 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
100 static struct ref_to_worktree_map {
102 struct worktree **worktrees;
103 } ref_to_worktree_map;
106 * An atom is a valid field atom listed below, possibly prefixed with
107 * a "*" to denote deref_tag().
109 * We parse given format string and sort specifiers, and make a list
110 * of properties that we need to extract out of objects. ref_array_item
111 * structure will hold an array of values extracted that can be
112 * indexed with the "atom number", which is an index into this
115 static struct used_atom {
120 char color[COLOR_MAXLEN];
124 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
126 struct refname_atom refname;
127 unsigned int nobracket : 1, push : 1, push_remote : 1;
130 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
131 struct process_trailer_options trailer_opts;
135 cmp_status cmp_status;
139 enum { O_FULL, O_LENGTH, O_SHORT } option;
142 struct refname_atom refname;
146 static int used_atom_cnt, need_tagged, need_symref;
149 * Expand string, append it to strbuf *sb, then return error code ret.
150 * Allow to save few lines of code.
152 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
156 strbuf_vaddf(sb, fmt, ap);
161 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
162 const char *color_value, struct strbuf *err)
165 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
166 if (color_parse(color_value, atom->u.color) < 0)
167 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
170 * We check this after we've parsed the color, which lets us complain
171 * about syntactically bogus color names even if they won't be used.
173 if (!want_color(format->use_color))
174 color_parse("", atom->u.color);
178 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
179 const char *name, struct strbuf *err)
182 atom->option = R_NORMAL;
183 else if (!strcmp(arg, "short"))
184 atom->option = R_SHORT;
185 else if (skip_prefix(arg, "lstrip=", &arg) ||
186 skip_prefix(arg, "strip=", &arg)) {
187 atom->option = R_LSTRIP;
188 if (strtol_i(arg, 10, &atom->lstrip))
189 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
190 } else if (skip_prefix(arg, "rstrip=", &arg)) {
191 atom->option = R_RSTRIP;
192 if (strtol_i(arg, 10, &atom->rstrip))
193 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
195 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
199 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
200 const char *arg, struct strbuf *err)
202 struct string_list params = STRING_LIST_INIT_DUP;
205 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
206 atom->u.remote_ref.push = 1;
209 atom->u.remote_ref.option = RR_REF;
210 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
211 arg, atom->name, err);
214 atom->u.remote_ref.nobracket = 0;
215 string_list_split(¶ms, arg, ',', -1);
217 for (i = 0; i < params.nr; i++) {
218 const char *s = params.items[i].string;
220 if (!strcmp(s, "track"))
221 atom->u.remote_ref.option = RR_TRACK;
222 else if (!strcmp(s, "trackshort"))
223 atom->u.remote_ref.option = RR_TRACKSHORT;
224 else if (!strcmp(s, "nobracket"))
225 atom->u.remote_ref.nobracket = 1;
226 else if (!strcmp(s, "remotename")) {
227 atom->u.remote_ref.option = RR_REMOTE_NAME;
228 atom->u.remote_ref.push_remote = 1;
229 } else if (!strcmp(s, "remoteref")) {
230 atom->u.remote_ref.option = RR_REMOTE_REF;
231 atom->u.remote_ref.push_remote = 1;
233 atom->u.remote_ref.option = RR_REF;
234 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
235 arg, atom->name, err)) {
236 string_list_clear(¶ms, 0);
242 string_list_clear(¶ms, 0);
246 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
247 const char *arg, struct strbuf *err)
250 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
251 if (*atom->name == '*')
252 oi_deref.info.typep = &oi_deref.type;
254 oi.info.typep = &oi.type;
258 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
259 const char *arg, struct strbuf *err)
262 if (*atom->name == '*')
263 oi_deref.info.sizep = &oi_deref.size;
265 oi.info.sizep = &oi.size;
266 } else if (!strcmp(arg, "disk")) {
267 if (*atom->name == '*')
268 oi_deref.info.disk_sizep = &oi_deref.disk_size;
270 oi.info.disk_sizep = &oi.disk_size;
272 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
276 static int deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom,
277 const char *arg, struct strbuf *err)
280 return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
281 if (*atom->name == '*')
282 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
284 oi.info.delta_base_oid = &oi.delta_base_oid;
288 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
289 const char *arg, struct strbuf *err)
292 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
293 atom->u.contents.option = C_BODY_DEP;
297 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
298 const char *arg, struct strbuf *err)
301 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
302 atom->u.contents.option = C_SUB;
306 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
307 const char *arg, struct strbuf *err)
309 struct string_list params = STRING_LIST_INIT_DUP;
312 atom->u.contents.trailer_opts.no_divider = 1;
315 string_list_split(¶ms, arg, ',', -1);
316 for (i = 0; i < params.nr; i++) {
317 const char *s = params.items[i].string;
318 if (!strcmp(s, "unfold"))
319 atom->u.contents.trailer_opts.unfold = 1;
320 else if (!strcmp(s, "only"))
321 atom->u.contents.trailer_opts.only_trailers = 1;
323 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
324 string_list_clear(¶ms, 0);
329 atom->u.contents.option = C_TRAILERS;
330 string_list_clear(¶ms, 0);
334 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
335 const char *arg, struct strbuf *err)
338 atom->u.contents.option = C_BARE;
339 else if (!strcmp(arg, "body"))
340 atom->u.contents.option = C_BODY;
341 else if (!strcmp(arg, "signature"))
342 atom->u.contents.option = C_SIG;
343 else if (!strcmp(arg, "subject"))
344 atom->u.contents.option = C_SUB;
345 else if (!strcmp(arg, "trailers")) {
346 if (trailers_atom_parser(format, atom, NULL, err))
348 } else if (skip_prefix(arg, "trailers:", &arg)) {
349 if (trailers_atom_parser(format, atom, arg, err))
351 } else if (skip_prefix(arg, "lines=", &arg)) {
352 atom->u.contents.option = C_LINES;
353 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
354 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
356 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
360 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
361 const char *arg, struct strbuf *err)
364 atom->u.objectname.option = O_FULL;
365 else if (!strcmp(arg, "short"))
366 atom->u.objectname.option = O_SHORT;
367 else if (skip_prefix(arg, "short=", &arg)) {
368 atom->u.objectname.option = O_LENGTH;
369 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
370 atom->u.objectname.length == 0)
371 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
372 if (atom->u.objectname.length < MINIMUM_ABBREV)
373 atom->u.objectname.length = MINIMUM_ABBREV;
375 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
379 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
380 const char *arg, struct strbuf *err)
382 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
385 static align_type parse_align_position(const char *s)
387 if (!strcmp(s, "right"))
389 else if (!strcmp(s, "middle"))
391 else if (!strcmp(s, "left"))
396 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
397 const char *arg, struct strbuf *err)
399 struct align *align = &atom->u.align;
400 struct string_list params = STRING_LIST_INIT_DUP;
402 unsigned int width = ~0U;
405 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
407 align->position = ALIGN_LEFT;
409 string_list_split(¶ms, arg, ',', -1);
410 for (i = 0; i < params.nr; i++) {
411 const char *s = params.items[i].string;
414 if (skip_prefix(s, "position=", &s)) {
415 position = parse_align_position(s);
417 strbuf_addf(err, _("unrecognized position:%s"), s);
418 string_list_clear(¶ms, 0);
421 align->position = position;
422 } else if (skip_prefix(s, "width=", &s)) {
423 if (strtoul_ui(s, 10, &width)) {
424 strbuf_addf(err, _("unrecognized width:%s"), s);
425 string_list_clear(¶ms, 0);
428 } else if (!strtoul_ui(s, 10, &width))
430 else if ((position = parse_align_position(s)) >= 0)
431 align->position = position;
433 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
434 string_list_clear(¶ms, 0);
440 string_list_clear(¶ms, 0);
441 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
443 align->width = width;
444 string_list_clear(¶ms, 0);
448 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
449 const char *arg, struct strbuf *err)
452 atom->u.if_then_else.cmp_status = COMPARE_NONE;
454 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
455 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
456 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
457 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
459 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
463 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
464 const char *arg, struct strbuf *unused_err)
466 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
474 int (*parser)(const struct ref_format *format, struct used_atom *atom,
475 const char *arg, struct strbuf *err);
477 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
478 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
479 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
480 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
481 { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
482 { "tree", SOURCE_OBJ },
483 { "parent", SOURCE_OBJ },
484 { "numparent", SOURCE_OBJ, FIELD_ULONG },
485 { "object", SOURCE_OBJ },
486 { "type", SOURCE_OBJ },
487 { "tag", SOURCE_OBJ },
488 { "author", SOURCE_OBJ },
489 { "authorname", SOURCE_OBJ },
490 { "authoremail", SOURCE_OBJ },
491 { "authordate", SOURCE_OBJ, FIELD_TIME },
492 { "committer", SOURCE_OBJ },
493 { "committername", SOURCE_OBJ },
494 { "committeremail", SOURCE_OBJ },
495 { "committerdate", SOURCE_OBJ, FIELD_TIME },
496 { "tagger", SOURCE_OBJ },
497 { "taggername", SOURCE_OBJ },
498 { "taggeremail", SOURCE_OBJ },
499 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
500 { "creator", SOURCE_OBJ },
501 { "creatordate", SOURCE_OBJ, FIELD_TIME },
502 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
503 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
504 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
505 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
506 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
507 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
508 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
509 { "flag", SOURCE_NONE },
510 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
511 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
512 { "worktreepath", SOURCE_NONE },
513 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
514 { "end", SOURCE_NONE },
515 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
516 { "then", SOURCE_NONE },
517 { "else", SOURCE_NONE },
519 * Please update $__git_ref_fieldlist in git-completion.bash
520 * when you add new atoms
524 #define REF_FORMATTING_STATE_INIT { 0, NULL }
526 struct ref_formatting_stack {
527 struct ref_formatting_stack *prev;
528 struct strbuf output;
529 void (*at_end)(struct ref_formatting_stack **stack);
533 struct ref_formatting_state {
535 struct ref_formatting_stack *stack;
540 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
542 uintmax_t value; /* used for sorting when not FIELD_STR */
543 struct used_atom *atom;
547 * Used to parse format string and sort specifiers
549 static int parse_ref_filter_atom(const struct ref_format *format,
550 const char *atom, const char *ep,
558 if (*sp == '*' && sp < ep)
561 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
562 (int)(ep-atom), atom);
564 /* Do we have the atom already used elsewhere? */
565 for (i = 0; i < used_atom_cnt; i++) {
566 int len = strlen(used_atom[i].name);
567 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
572 * If the atom name has a colon, strip it and everything after
573 * it off - it specifies the format for this entry, and
574 * shouldn't be used for checking against the valid_atom
577 arg = memchr(sp, ':', ep - sp);
578 atom_len = (arg ? arg : ep) - sp;
580 /* Is the atom a valid one? */
581 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
582 int len = strlen(valid_atom[i].name);
583 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
587 if (ARRAY_SIZE(valid_atom) <= i)
588 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
589 (int)(ep-atom), atom);
590 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
591 return strbuf_addf_ret(err, -1,
592 _("not a git repository, but the field '%.*s' requires access to object data"),
593 (int)(ep-atom), atom);
595 /* Add it in, including the deref prefix */
598 REALLOC_ARRAY(used_atom, used_atom_cnt);
599 used_atom[at].name = xmemdupz(atom, ep - atom);
600 used_atom[at].type = valid_atom[i].cmp_type;
601 used_atom[at].source = valid_atom[i].source;
602 if (used_atom[at].source == SOURCE_OBJ) {
604 oi_deref.info.contentp = &oi_deref.content;
606 oi.info.contentp = &oi.content;
609 arg = used_atom[at].name + (arg - atom) + 1;
612 * Treat empty sub-arguments list as NULL (i.e.,
613 * "%(atom:)" is equivalent to "%(atom)").
618 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
619 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
623 if (!strcmp(valid_atom[i].name, "symref"))
628 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
630 switch (quote_style) {
632 strbuf_addstr(s, str);
635 sq_quote_buf(s, str);
638 perl_quote_buf(s, str);
641 python_quote_buf(s, str);
644 tcl_quote_buf(s, str);
649 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
650 struct strbuf *unused_err)
653 * Quote formatting is only done when the stack has a single
654 * element. Otherwise quote formatting is done on the
655 * element's entire output strbuf when the %(end) atom is
658 if (!state->stack->prev)
659 quote_formatting(&state->stack->output, v->s, state->quote_style);
661 strbuf_addstr(&state->stack->output, v->s);
665 static void push_stack_element(struct ref_formatting_stack **stack)
667 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
669 strbuf_init(&s->output, 0);
674 static void pop_stack_element(struct ref_formatting_stack **stack)
676 struct ref_formatting_stack *current = *stack;
677 struct ref_formatting_stack *prev = current->prev;
680 strbuf_addbuf(&prev->output, ¤t->output);
681 strbuf_release(¤t->output);
686 static void end_align_handler(struct ref_formatting_stack **stack)
688 struct ref_formatting_stack *cur = *stack;
689 struct align *align = (struct align *)cur->at_end_data;
690 struct strbuf s = STRBUF_INIT;
692 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
693 strbuf_swap(&cur->output, &s);
697 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
698 struct strbuf *unused_err)
700 struct ref_formatting_stack *new_stack;
702 push_stack_element(&state->stack);
703 new_stack = state->stack;
704 new_stack->at_end = end_align_handler;
705 new_stack->at_end_data = &atomv->atom->u.align;
709 static void if_then_else_handler(struct ref_formatting_stack **stack)
711 struct ref_formatting_stack *cur = *stack;
712 struct ref_formatting_stack *prev = cur->prev;
713 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
715 if (!if_then_else->then_atom_seen)
716 die(_("format: %%(if) atom used without a %%(then) atom"));
718 if (if_then_else->else_atom_seen) {
720 * There is an %(else) atom: we need to drop one state from the
721 * stack, either the %(else) branch if the condition is satisfied, or
722 * the %(then) branch if it isn't.
724 if (if_then_else->condition_satisfied) {
725 strbuf_reset(&cur->output);
726 pop_stack_element(&cur);
728 strbuf_swap(&cur->output, &prev->output);
729 strbuf_reset(&cur->output);
730 pop_stack_element(&cur);
732 } else if (!if_then_else->condition_satisfied) {
734 * No %(else) atom: just drop the %(then) branch if the
735 * condition is not satisfied.
737 strbuf_reset(&cur->output);
744 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
745 struct strbuf *unused_err)
747 struct ref_formatting_stack *new_stack;
748 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
750 if_then_else->str = atomv->atom->u.if_then_else.str;
751 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
753 push_stack_element(&state->stack);
754 new_stack = state->stack;
755 new_stack->at_end = if_then_else_handler;
756 new_stack->at_end_data = if_then_else;
760 static int is_empty(const char *s)
770 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
773 struct ref_formatting_stack *cur = state->stack;
774 struct if_then_else *if_then_else = NULL;
776 if (cur->at_end == if_then_else_handler)
777 if_then_else = (struct if_then_else *)cur->at_end_data;
779 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
780 if (if_then_else->then_atom_seen)
781 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
782 if (if_then_else->else_atom_seen)
783 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
784 if_then_else->then_atom_seen = 1;
786 * If the 'equals' or 'notequals' attribute is used then
787 * perform the required comparison. If not, only non-empty
788 * strings satisfy the 'if' condition.
790 if (if_then_else->cmp_status == COMPARE_EQUAL) {
791 if (!strcmp(if_then_else->str, cur->output.buf))
792 if_then_else->condition_satisfied = 1;
793 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
794 if (strcmp(if_then_else->str, cur->output.buf))
795 if_then_else->condition_satisfied = 1;
796 } else if (cur->output.len && !is_empty(cur->output.buf))
797 if_then_else->condition_satisfied = 1;
798 strbuf_reset(&cur->output);
802 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
805 struct ref_formatting_stack *prev = state->stack;
806 struct if_then_else *if_then_else = NULL;
808 if (prev->at_end == if_then_else_handler)
809 if_then_else = (struct if_then_else *)prev->at_end_data;
811 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
812 if (!if_then_else->then_atom_seen)
813 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
814 if (if_then_else->else_atom_seen)
815 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
816 if_then_else->else_atom_seen = 1;
817 push_stack_element(&state->stack);
818 state->stack->at_end_data = prev->at_end_data;
819 state->stack->at_end = prev->at_end;
823 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
826 struct ref_formatting_stack *current = state->stack;
827 struct strbuf s = STRBUF_INIT;
829 if (!current->at_end)
830 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
831 current->at_end(&state->stack);
833 /* Stack may have been popped within at_end(), hence reset the current pointer */
834 current = state->stack;
837 * Perform quote formatting when the stack element is that of
838 * a supporting atom. If nested then perform quote formatting
839 * only on the topmost supporting atom.
841 if (!current->prev->prev) {
842 quote_formatting(&s, current->output.buf, state->quote_style);
843 strbuf_swap(¤t->output, &s);
846 pop_stack_element(&state->stack);
851 * In a format string, find the next occurrence of %(atom).
853 static const char *find_next(const char *cp)
858 * %( is the start of an atom;
859 * %% is a quoted per-cent.
863 else if (cp[1] == '%')
864 cp++; /* skip over two % */
865 /* otherwise this is a singleton, literal % */
873 * Make sure the format string is well formed, and parse out
876 int verify_ref_format(struct ref_format *format)
880 format->need_color_reset_at_eol = 0;
881 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
882 struct strbuf err = STRBUF_INIT;
883 const char *color, *ep = strchr(sp, ')');
887 return error(_("malformed format string %s"), sp);
888 /* sp points at "%(" and ep points at the closing ")" */
889 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
894 if (skip_prefix(used_atom[at].name, "color:", &color))
895 format->need_color_reset_at_eol = !!strcmp(color, "reset");
896 strbuf_release(&err);
898 if (format->need_color_reset_at_eol && !want_color(format->use_color))
899 format->need_color_reset_at_eol = 0;
903 static int grab_objectname(const char *name, const struct object_id *oid,
904 struct atom_value *v, struct used_atom *atom)
906 if (starts_with(name, "objectname")) {
907 if (atom->u.objectname.option == O_SHORT) {
908 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
910 } else if (atom->u.objectname.option == O_FULL) {
911 v->s = xstrdup(oid_to_hex(oid));
913 } else if (atom->u.objectname.option == O_LENGTH) {
914 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
917 BUG("unknown %%(objectname) option");
922 /* See grab_values */
923 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
927 for (i = 0; i < used_atom_cnt; i++) {
928 const char *name = used_atom[i].name;
929 struct atom_value *v = &val[i];
930 if (!!deref != (*name == '*'))
934 if (!strcmp(name, "objecttype"))
935 v->s = xstrdup(type_name(oi->type));
936 else if (!strcmp(name, "objectsize:disk")) {
937 v->value = oi->disk_size;
938 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
939 } else if (!strcmp(name, "objectsize")) {
941 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
942 } else if (!strcmp(name, "deltabase"))
943 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
945 grab_objectname(name, &oi->oid, v, &used_atom[i]);
949 /* See grab_values */
950 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
953 struct tag *tag = (struct tag *) obj;
955 for (i = 0; i < used_atom_cnt; i++) {
956 const char *name = used_atom[i].name;
957 struct atom_value *v = &val[i];
958 if (!!deref != (*name == '*'))
962 if (!strcmp(name, "tag"))
963 v->s = xstrdup(tag->tag);
964 else if (!strcmp(name, "type") && tag->tagged)
965 v->s = xstrdup(type_name(tag->tagged->type));
966 else if (!strcmp(name, "object") && tag->tagged)
967 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
971 /* See grab_values */
972 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
975 struct commit *commit = (struct commit *) obj;
977 for (i = 0; i < used_atom_cnt; i++) {
978 const char *name = used_atom[i].name;
979 struct atom_value *v = &val[i];
980 if (!!deref != (*name == '*'))
984 if (!strcmp(name, "tree")) {
985 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
987 else if (!strcmp(name, "numparent")) {
988 v->value = commit_list_count(commit->parents);
989 v->s = xstrfmt("%lu", (unsigned long)v->value);
991 else if (!strcmp(name, "parent")) {
992 struct commit_list *parents;
993 struct strbuf s = STRBUF_INIT;
994 for (parents = commit->parents; parents; parents = parents->next) {
995 struct commit *parent = parents->item;
996 if (parents != commit->parents)
997 strbuf_addch(&s, ' ');
998 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
1000 v->s = strbuf_detach(&s, NULL);
1005 static const char *find_wholine(const char *who, int wholen, const char *buf)
1009 if (!strncmp(buf, who, wholen) &&
1011 return buf + wholen + 1;
1012 eol = strchr(buf, '\n');
1017 return ""; /* end of header */
1023 static const char *copy_line(const char *buf)
1025 const char *eol = strchrnul(buf, '\n');
1026 return xmemdupz(buf, eol - buf);
1029 static const char *copy_name(const char *buf)
1032 for (cp = buf; *cp && *cp != '\n'; cp++) {
1033 if (!strncmp(cp, " <", 2))
1034 return xmemdupz(buf, cp - buf);
1039 static const char *copy_email(const char *buf)
1041 const char *email = strchr(buf, '<');
1042 const char *eoemail;
1045 eoemail = strchr(email, '>');
1048 return xmemdupz(email, eoemail + 1 - email);
1051 static char *copy_subject(const char *buf, unsigned long len)
1053 char *r = xmemdupz(buf, len);
1056 for (i = 0; i < len; i++)
1063 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1065 const char *eoemail = strstr(buf, "> ");
1067 timestamp_t timestamp;
1069 struct date_mode date_mode = { DATE_NORMAL };
1070 const char *formatp;
1073 * We got here because atomname ends in "date" or "date<something>";
1074 * it's not possible that <something> is not ":<format>" because
1075 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1076 * ":" means no format is specified, and use the default.
1078 formatp = strchr(atomname, ':');
1079 if (formatp != NULL) {
1081 parse_date_format(formatp, &date_mode);
1086 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1087 if (timestamp == TIME_MAX)
1089 tz = strtol(zone, NULL, 10);
1090 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1092 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1093 v->value = timestamp;
1100 /* See grab_values */
1101 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1104 int wholen = strlen(who);
1105 const char *wholine = NULL;
1107 for (i = 0; i < used_atom_cnt; i++) {
1108 const char *name = used_atom[i].name;
1109 struct atom_value *v = &val[i];
1110 if (!!deref != (*name == '*'))
1114 if (strncmp(who, name, wholen))
1116 if (name[wholen] != 0 &&
1117 strcmp(name + wholen, "name") &&
1118 strcmp(name + wholen, "email") &&
1119 !starts_with(name + wholen, "date"))
1122 wholine = find_wholine(who, wholen, buf);
1124 return; /* no point looking for it */
1125 if (name[wholen] == 0)
1126 v->s = copy_line(wholine);
1127 else if (!strcmp(name + wholen, "name"))
1128 v->s = copy_name(wholine);
1129 else if (!strcmp(name + wholen, "email"))
1130 v->s = copy_email(wholine);
1131 else if (starts_with(name + wholen, "date"))
1132 grab_date(wholine, v, name);
1136 * For a tag or a commit object, if "creator" or "creatordate" is
1137 * requested, do something special.
1139 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1140 return; /* "author" for commit object is not wanted */
1142 wholine = find_wholine(who, wholen, buf);
1145 for (i = 0; i < used_atom_cnt; i++) {
1146 const char *name = used_atom[i].name;
1147 struct atom_value *v = &val[i];
1148 if (!!deref != (*name == '*'))
1153 if (starts_with(name, "creatordate"))
1154 grab_date(wholine, v, name);
1155 else if (!strcmp(name, "creator"))
1156 v->s = copy_line(wholine);
1160 static void find_subpos(const char *buf,
1161 const char **sub, unsigned long *sublen,
1162 const char **body, unsigned long *bodylen,
1163 unsigned long *nonsiglen,
1164 const char **sig, unsigned long *siglen)
1167 /* skip past header until we hit empty line */
1168 while (*buf && *buf != '\n') {
1169 eol = strchrnul(buf, '\n');
1174 /* skip any empty lines */
1175 while (*buf == '\n')
1178 /* parse signature first; we might not even have a subject line */
1179 *sig = buf + parse_signature(buf, strlen(buf));
1180 *siglen = strlen(*sig);
1182 /* subject is first non-empty line */
1184 /* subject goes to first empty line */
1185 while (buf < *sig && *buf && *buf != '\n') {
1186 eol = strchrnul(buf, '\n');
1191 *sublen = buf - *sub;
1192 /* drop trailing newline, if present */
1193 if (*sublen && (*sub)[*sublen - 1] == '\n')
1196 /* skip any empty lines */
1197 while (*buf == '\n')
1200 *bodylen = strlen(buf);
1201 *nonsiglen = *sig - buf;
1205 * If 'lines' is greater than 0, append that many lines from the given
1206 * 'buf' of length 'size' to the given strbuf.
1208 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1211 const char *sp, *eol;
1216 for (i = 0; i < lines && sp < buf + size; i++) {
1218 strbuf_addstr(out, "\n ");
1219 eol = memchr(sp, '\n', size - (sp - buf));
1220 len = eol ? eol - sp : size - (sp - buf);
1221 strbuf_add(out, sp, len);
1228 /* See grab_values */
1229 static void grab_sub_body_contents(struct atom_value *val, int deref, void *buf)
1232 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1233 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1235 for (i = 0; i < used_atom_cnt; i++) {
1236 struct used_atom *atom = &used_atom[i];
1237 const char *name = atom->name;
1238 struct atom_value *v = &val[i];
1239 if (!!deref != (*name == '*'))
1243 if (strcmp(name, "subject") &&
1244 strcmp(name, "body") &&
1245 !starts_with(name, "trailers") &&
1246 !starts_with(name, "contents"))
1251 &bodypos, &bodylen, &nonsiglen,
1254 if (atom->u.contents.option == C_SUB)
1255 v->s = copy_subject(subpos, sublen);
1256 else if (atom->u.contents.option == C_BODY_DEP)
1257 v->s = xmemdupz(bodypos, bodylen);
1258 else if (atom->u.contents.option == C_BODY)
1259 v->s = xmemdupz(bodypos, nonsiglen);
1260 else if (atom->u.contents.option == C_SIG)
1261 v->s = xmemdupz(sigpos, siglen);
1262 else if (atom->u.contents.option == C_LINES) {
1263 struct strbuf s = STRBUF_INIT;
1264 const char *contents_end = bodylen + bodypos - siglen;
1266 /* Size is the length of the message after removing the signature */
1267 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1268 v->s = strbuf_detach(&s, NULL);
1269 } else if (atom->u.contents.option == C_TRAILERS) {
1270 struct strbuf s = STRBUF_INIT;
1272 /* Format the trailer info according to the trailer_opts given */
1273 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1275 v->s = strbuf_detach(&s, NULL);
1276 } else if (atom->u.contents.option == C_BARE)
1277 v->s = xstrdup(subpos);
1282 * We want to have empty print-string for field requests
1283 * that do not apply (e.g. "authordate" for a tag object)
1285 static void fill_missing_values(struct atom_value *val)
1288 for (i = 0; i < used_atom_cnt; i++) {
1289 struct atom_value *v = &val[i];
1296 * val is a list of atom_value to hold returned values. Extract
1297 * the values for atoms in used_atom array out of (obj, buf, sz).
1298 * when deref is false, (obj, buf, sz) is the object that is
1299 * pointed at by the ref itself; otherwise it is the object the
1300 * ref (which is a tag) refers to.
1302 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf)
1304 switch (obj->type) {
1306 grab_tag_values(val, deref, obj);
1307 grab_sub_body_contents(val, deref, buf);
1308 grab_person("tagger", val, deref, buf);
1311 grab_commit_values(val, deref, obj);
1312 grab_sub_body_contents(val, deref, buf);
1313 grab_person("author", val, deref, buf);
1314 grab_person("committer", val, deref, buf);
1317 /* grab_tree_values(val, deref, obj, buf, sz); */
1320 /* grab_blob_values(val, deref, obj, buf, sz); */
1323 die("Eh? Object of type %d?", obj->type);
1327 static inline char *copy_advance(char *dst, const char *src)
1334 static const char *lstrip_ref_components(const char *refname, int len)
1336 long remaining = len;
1337 const char *start = xstrdup(refname);
1338 const char *to_free = start;
1342 const char *p = refname;
1344 /* Find total no of '/' separated path-components */
1345 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1348 * The number of components we need to strip is now
1349 * the total minus the components to be left (Plus one
1350 * because we count the number of '/', but the number
1351 * of components is one more than the no of '/').
1353 remaining = i + len + 1;
1356 while (remaining > 0) {
1359 free((char *)to_free);
1367 start = xstrdup(start);
1368 free((char *)to_free);
1372 static const char *rstrip_ref_components(const char *refname, int len)
1374 long remaining = len;
1375 const char *start = xstrdup(refname);
1376 const char *to_free = start;
1380 const char *p = refname;
1382 /* Find total no of '/' separated path-components */
1383 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1386 * The number of components we need to strip is now
1387 * the total minus the components to be left (Plus one
1388 * because we count the number of '/', but the number
1389 * of components is one more than the no of '/').
1391 remaining = i + len + 1;
1394 while (remaining-- > 0) {
1395 char *p = strrchr(start, '/');
1397 free((char *)to_free);
1405 static const char *show_ref(struct refname_atom *atom, const char *refname)
1407 if (atom->option == R_SHORT)
1408 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1409 else if (atom->option == R_LSTRIP)
1410 return lstrip_ref_components(refname, atom->lstrip);
1411 else if (atom->option == R_RSTRIP)
1412 return rstrip_ref_components(refname, atom->rstrip);
1414 return xstrdup(refname);
1417 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1418 struct branch *branch, const char **s)
1420 int num_ours, num_theirs;
1421 if (atom->u.remote_ref.option == RR_REF)
1422 *s = show_ref(&atom->u.remote_ref.refname, refname);
1423 else if (atom->u.remote_ref.option == RR_TRACK) {
1424 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1425 NULL, atom->u.remote_ref.push,
1426 AHEAD_BEHIND_FULL) < 0) {
1427 *s = xstrdup(msgs.gone);
1428 } else if (!num_ours && !num_theirs)
1431 *s = xstrfmt(msgs.behind, num_theirs);
1432 else if (!num_theirs)
1433 *s = xstrfmt(msgs.ahead, num_ours);
1435 *s = xstrfmt(msgs.ahead_behind,
1436 num_ours, num_theirs);
1437 if (!atom->u.remote_ref.nobracket && *s[0]) {
1438 const char *to_free = *s;
1439 *s = xstrfmt("[%s]", *s);
1440 free((void *)to_free);
1442 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1443 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1444 NULL, atom->u.remote_ref.push,
1445 AHEAD_BEHIND_FULL) < 0) {
1449 if (!num_ours && !num_theirs)
1453 else if (!num_theirs)
1457 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1459 const char *remote = atom->u.remote_ref.push ?
1460 pushremote_for_branch(branch, &explicit) :
1461 remote_for_branch(branch, &explicit);
1462 *s = xstrdup(explicit ? remote : "");
1463 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1466 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1467 *s = xstrdup(merge ? merge : "");
1469 BUG("unhandled RR_* enum");
1472 char *get_head_description(void)
1474 struct strbuf desc = STRBUF_INIT;
1475 struct wt_status_state state;
1476 memset(&state, 0, sizeof(state));
1477 wt_status_get_state(the_repository, &state, 1);
1480 * The ( character must be hard-coded and not part of a localizable
1481 * string, since the description is used as a sort key and compared
1484 strbuf_addch(&desc, '(');
1485 if (state.rebase_in_progress ||
1486 state.rebase_interactive_in_progress) {
1488 strbuf_addf(&desc, _("no branch, rebasing %s"),
1491 strbuf_addf(&desc, _("no branch, rebasing detached HEAD %s"),
1492 state.detached_from);
1493 } else if (state.bisect_in_progress)
1494 strbuf_addf(&desc, _("no branch, bisect started on %s"),
1496 else if (state.detached_from) {
1497 if (state.detached_at)
1498 strbuf_addstr(&desc, HEAD_DETACHED_AT);
1500 strbuf_addstr(&desc, HEAD_DETACHED_FROM);
1501 strbuf_addstr(&desc, state.detached_from);
1504 strbuf_addstr(&desc, _("no branch"));
1505 strbuf_addch(&desc, ')');
1509 free(state.detached_from);
1510 return strbuf_detach(&desc, NULL);
1513 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1518 return show_ref(&atom->u.refname, ref->symref);
1521 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1523 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1524 return get_head_description();
1525 return show_ref(&atom->u.refname, ref->refname);
1528 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1529 struct expand_data *oi, struct strbuf *err)
1531 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1533 if (oi->info.contentp) {
1534 /* We need to know that to use parse_object_buffer properly */
1535 oi->info.sizep = &oi->size;
1536 oi->info.typep = &oi->type;
1538 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1539 OBJECT_INFO_LOOKUP_REPLACE))
1540 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1541 oid_to_hex(&oi->oid), ref->refname);
1542 if (oi->info.disk_sizep && oi->disk_size < 0)
1543 BUG("Object size is less than zero.");
1545 if (oi->info.contentp) {
1546 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1550 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1551 oid_to_hex(&oi->oid), ref->refname);
1553 grab_values(ref->value, deref, *obj, oi->content);
1556 grab_common_values(ref->value, deref, oi);
1562 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1566 for (i = 0; worktrees[i]; i++) {
1567 if (worktrees[i]->head_ref) {
1568 struct ref_to_worktree_entry *entry;
1569 entry = xmalloc(sizeof(*entry));
1570 entry->wt = worktrees[i];
1571 hashmap_entry_init(&entry->ent,
1572 strhash(worktrees[i]->head_ref));
1574 hashmap_add(map, &entry->ent);
1579 static void lazy_init_worktree_map(void)
1581 if (ref_to_worktree_map.worktrees)
1584 ref_to_worktree_map.worktrees = get_worktrees();
1585 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1586 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1589 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1591 struct hashmap_entry entry, *e;
1592 struct ref_to_worktree_entry *lookup_result;
1594 lazy_init_worktree_map();
1596 hashmap_entry_init(&entry, strhash(ref->refname));
1597 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1602 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1604 return xstrdup(lookup_result->wt->path);
1608 * Parse the object referred by ref, and grab needed value.
1610 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1614 struct object_info empty = OBJECT_INFO_INIT;
1616 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1618 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1619 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1622 ref->symref = xstrdup("");
1625 /* Fill in specials first */
1626 for (i = 0; i < used_atom_cnt; i++) {
1627 struct used_atom *atom = &used_atom[i];
1628 const char *name = used_atom[i].name;
1629 struct atom_value *v = &ref->value[i];
1631 const char *refname;
1632 struct branch *branch = NULL;
1634 v->handler = append_atom;
1642 if (starts_with(name, "refname"))
1643 refname = get_refname(atom, ref);
1644 else if (!strcmp(name, "worktreepath")) {
1645 if (ref->kind == FILTER_REFS_BRANCHES)
1646 v->s = get_worktree_path(atom, ref);
1651 else if (starts_with(name, "symref"))
1652 refname = get_symref(atom, ref);
1653 else if (starts_with(name, "upstream")) {
1654 const char *branch_name;
1655 /* only local branches may have an upstream */
1656 if (!skip_prefix(ref->refname, "refs/heads/",
1661 branch = branch_get(branch_name);
1663 refname = branch_get_upstream(branch, NULL);
1665 fill_remote_ref_details(atom, refname, branch, &v->s);
1669 } else if (atom->u.remote_ref.push) {
1670 const char *branch_name;
1672 if (!skip_prefix(ref->refname, "refs/heads/",
1675 branch = branch_get(branch_name);
1677 if (atom->u.remote_ref.push_remote)
1680 refname = branch_get_push(branch, NULL);
1684 /* We will definitely re-init v->s on the next line. */
1686 fill_remote_ref_details(atom, refname, branch, &v->s);
1688 } else if (starts_with(name, "color:")) {
1689 v->s = xstrdup(atom->u.color);
1691 } else if (!strcmp(name, "flag")) {
1692 char buf[256], *cp = buf;
1693 if (ref->flag & REF_ISSYMREF)
1694 cp = copy_advance(cp, ",symref");
1695 if (ref->flag & REF_ISPACKED)
1696 cp = copy_advance(cp, ",packed");
1701 v->s = xstrdup(buf + 1);
1704 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1706 } else if (!strcmp(name, "HEAD")) {
1707 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1708 v->s = xstrdup("*");
1710 v->s = xstrdup(" ");
1712 } else if (starts_with(name, "align")) {
1713 v->handler = align_atom_handler;
1716 } else if (!strcmp(name, "end")) {
1717 v->handler = end_atom_handler;
1720 } else if (starts_with(name, "if")) {
1722 if (skip_prefix(name, "if:", &s))
1726 v->handler = if_atom_handler;
1728 } else if (!strcmp(name, "then")) {
1729 v->handler = then_atom_handler;
1732 } else if (!strcmp(name, "else")) {
1733 v->handler = else_atom_handler;
1740 v->s = xstrdup(refname);
1742 v->s = xstrfmt("%s^{}", refname);
1743 free((char *)refname);
1746 for (i = 0; i < used_atom_cnt; i++) {
1747 struct atom_value *v = &ref->value[i];
1748 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1749 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1750 oid_to_hex(&ref->objectname), ref->refname);
1754 oi.info.contentp = &oi.content;
1755 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1756 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1760 oi.oid = ref->objectname;
1761 if (get_object(ref, 0, &obj, &oi, err))
1765 * If there is no atom that wants to know about tagged
1766 * object, we are done.
1768 if (!need_tagged || (obj->type != OBJ_TAG))
1772 * If it is a tag object, see if we use a value that derefs
1773 * the object, and if we do grab the object it refers to.
1775 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
1778 * NEEDSWORK: This derefs tag only once, which
1779 * is good to deal with chains of trust, but
1780 * is not consistent with what deref_tag() does
1781 * which peels the onion to the core.
1783 return get_object(ref, 1, &obj, &oi_deref, err);
1787 * Given a ref, return the value for the atom. This lazily gets value
1788 * out of the object by calling populate value.
1790 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1791 struct atom_value **v, struct strbuf *err)
1794 if (populate_value(ref, err))
1796 fill_missing_values(ref->value);
1798 *v = &ref->value[atom];
1803 * Return 1 if the refname matches one of the patterns, otherwise 0.
1804 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1805 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1806 * matches "refs/heads/mas*", too).
1808 static int match_pattern(const struct ref_filter *filter, const char *refname)
1810 const char **patterns = filter->name_patterns;
1813 if (filter->ignore_case)
1814 flags |= WM_CASEFOLD;
1817 * When no '--format' option is given we need to skip the prefix
1818 * for matching refs of tags and branches.
1820 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1821 skip_prefix(refname, "refs/heads/", &refname) ||
1822 skip_prefix(refname, "refs/remotes/", &refname) ||
1823 skip_prefix(refname, "refs/", &refname));
1825 for (; *patterns; patterns++) {
1826 if (!wildmatch(*patterns, refname, flags))
1833 * Return 1 if the refname matches one of the patterns, otherwise 0.
1834 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1835 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1836 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1838 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1840 const char **pattern = filter->name_patterns;
1841 int namelen = strlen(refname);
1842 unsigned flags = WM_PATHNAME;
1844 if (filter->ignore_case)
1845 flags |= WM_CASEFOLD;
1847 for (; *pattern; pattern++) {
1848 const char *p = *pattern;
1849 int plen = strlen(p);
1851 if ((plen <= namelen) &&
1852 !strncmp(refname, p, plen) &&
1853 (refname[plen] == '\0' ||
1854 refname[plen] == '/' ||
1857 if (!wildmatch(p, refname, flags))
1863 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1864 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1866 if (!*filter->name_patterns)
1867 return 1; /* No pattern always matches */
1868 if (filter->match_as_path)
1869 return match_name_as_path(filter, refname);
1870 return match_pattern(filter, refname);
1873 static int qsort_strcmp(const void *va, const void *vb)
1875 const char *a = *(const char **)va;
1876 const char *b = *(const char **)vb;
1878 return strcmp(a, b);
1881 static void find_longest_prefixes_1(struct string_list *out,
1882 struct strbuf *prefix,
1883 const char **patterns, size_t nr)
1887 for (i = 0; i < nr; i++) {
1888 char c = patterns[i][prefix->len];
1889 if (!c || is_glob_special(c)) {
1890 string_list_append(out, prefix->buf);
1900 * Set "end" to the index of the element _after_ the last one
1903 for (end = i + 1; end < nr; end++) {
1904 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1908 strbuf_addch(prefix, patterns[i][prefix->len]);
1909 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1910 strbuf_setlen(prefix, prefix->len - 1);
1916 static void find_longest_prefixes(struct string_list *out,
1917 const char **patterns)
1919 struct argv_array sorted = ARGV_ARRAY_INIT;
1920 struct strbuf prefix = STRBUF_INIT;
1922 argv_array_pushv(&sorted, patterns);
1923 QSORT(sorted.argv, sorted.argc, qsort_strcmp);
1925 find_longest_prefixes_1(out, &prefix, sorted.argv, sorted.argc);
1927 argv_array_clear(&sorted);
1928 strbuf_release(&prefix);
1932 * This is the same as for_each_fullref_in(), but it tries to iterate
1933 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1934 * pattern match, so the callback still has to match each ref individually.
1936 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1941 struct string_list prefixes = STRING_LIST_INIT_DUP;
1942 struct string_list_item *prefix;
1945 if (!filter->match_as_path) {
1947 * in this case, the patterns are applied after
1948 * prefixes like "refs/heads/" etc. are stripped off,
1949 * so we have to look at everything:
1951 return for_each_fullref_in("", cb, cb_data, broken);
1954 if (filter->ignore_case) {
1956 * we can't handle case-insensitive comparisons,
1957 * so just return everything and let the caller
1960 return for_each_fullref_in("", cb, cb_data, broken);
1963 if (!filter->name_patterns[0]) {
1964 /* no patterns; we have to look at everything */
1965 return for_each_fullref_in("", cb, cb_data, broken);
1968 find_longest_prefixes(&prefixes, filter->name_patterns);
1970 for_each_string_list_item(prefix, &prefixes) {
1971 ret = for_each_fullref_in(prefix->string, cb, cb_data, broken);
1976 string_list_clear(&prefixes, 0);
1981 * Given a ref (oid, refname), check if the ref belongs to the array
1982 * of oids. If the given ref is a tag, check if the given tag points
1983 * at one of the oids in the given oid array.
1985 * 1. Only a single level of inderection is obtained, we might want to
1986 * change this to account for multiple levels (e.g. annotated tags
1987 * pointing to annotated tags pointing to a commit.)
1988 * 2. As the refs are cached we might know what refname peels to without
1989 * the need to parse the object via parse_object(). peel_ref() might be a
1990 * more efficient alternative to obtain the pointee.
1992 static const struct object_id *match_points_at(struct oid_array *points_at,
1993 const struct object_id *oid,
1994 const char *refname)
1996 const struct object_id *tagged_oid = NULL;
1999 if (oid_array_lookup(points_at, oid) >= 0)
2001 obj = parse_object(the_repository, oid);
2003 die(_("malformed object at '%s'"), refname);
2004 if (obj->type == OBJ_TAG)
2005 tagged_oid = get_tagged_oid((struct tag *)obj);
2006 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2012 * Allocate space for a new ref_array_item and copy the name and oid to it.
2014 * Callers can then fill in other struct members at their leisure.
2016 static struct ref_array_item *new_ref_array_item(const char *refname,
2017 const struct object_id *oid)
2019 struct ref_array_item *ref;
2021 FLEX_ALLOC_STR(ref, refname, refname);
2022 oidcpy(&ref->objectname, oid);
2027 struct ref_array_item *ref_array_push(struct ref_array *array,
2028 const char *refname,
2029 const struct object_id *oid)
2031 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2033 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2034 array->items[array->nr++] = ref;
2039 static int ref_kind_from_refname(const char *refname)
2047 { "refs/heads/" , FILTER_REFS_BRANCHES },
2048 { "refs/remotes/" , FILTER_REFS_REMOTES },
2049 { "refs/tags/", FILTER_REFS_TAGS}
2052 if (!strcmp(refname, "HEAD"))
2053 return FILTER_REFS_DETACHED_HEAD;
2055 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2056 if (starts_with(refname, ref_kind[i].prefix))
2057 return ref_kind[i].kind;
2060 return FILTER_REFS_OTHERS;
2063 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2065 if (filter->kind == FILTER_REFS_BRANCHES ||
2066 filter->kind == FILTER_REFS_REMOTES ||
2067 filter->kind == FILTER_REFS_TAGS)
2068 return filter->kind;
2069 return ref_kind_from_refname(refname);
2072 struct ref_filter_cbdata {
2073 struct ref_array *array;
2074 struct ref_filter *filter;
2075 struct contains_cache contains_cache;
2076 struct contains_cache no_contains_cache;
2080 * A call-back given to for_each_ref(). Filter refs and keep them for
2081 * later object processing.
2083 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2085 struct ref_filter_cbdata *ref_cbdata = cb_data;
2086 struct ref_filter *filter = ref_cbdata->filter;
2087 struct ref_array_item *ref;
2088 struct commit *commit = NULL;
2091 if (flag & REF_BAD_NAME) {
2092 warning(_("ignoring ref with broken name %s"), refname);
2096 if (flag & REF_ISBROKEN) {
2097 warning(_("ignoring broken ref %s"), refname);
2101 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2102 kind = filter_ref_kind(filter, refname);
2103 if (!(kind & filter->kind))
2106 if (!filter_pattern_match(filter, refname))
2109 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2113 * A merge filter is applied on refs pointing to commits. Hence
2114 * obtain the commit using the 'oid' available and discard all
2115 * non-commits early. The actual filtering is done later.
2117 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2118 commit = lookup_commit_reference_gently(the_repository, oid,
2122 /* We perform the filtering for the '--contains' option... */
2123 if (filter->with_commit &&
2124 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2126 /* ...or for the `--no-contains' option */
2127 if (filter->no_commit &&
2128 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2133 * We do not open the object yet; sort may only need refname
2134 * to do its job and the resulting list may yet to be pruned
2135 * by maxcount logic.
2137 ref = ref_array_push(ref_cbdata->array, refname, oid);
2138 ref->commit = commit;
2145 /* Free memory allocated for a ref_array_item */
2146 static void free_array_item(struct ref_array_item *item)
2148 free((char *)item->symref);
2151 for (i = 0; i < used_atom_cnt; i++)
2152 free((char *)item->value[i].s);
2158 /* Free all memory allocated for ref_array */
2159 void ref_array_clear(struct ref_array *array)
2163 for (i = 0; i < array->nr; i++)
2164 free_array_item(array->items[i]);
2165 FREE_AND_NULL(array->items);
2166 array->nr = array->alloc = 0;
2168 for (i = 0; i < used_atom_cnt; i++)
2169 free((char *)used_atom[i].name);
2170 FREE_AND_NULL(used_atom);
2173 if (ref_to_worktree_map.worktrees) {
2174 hashmap_free_entries(&(ref_to_worktree_map.map),
2175 struct ref_to_worktree_entry, ent);
2176 free_worktrees(ref_to_worktree_map.worktrees);
2177 ref_to_worktree_map.worktrees = NULL;
2181 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2183 struct rev_info revs;
2185 struct ref_filter *filter = ref_cbdata->filter;
2186 struct ref_array *array = ref_cbdata->array;
2187 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2189 repo_init_revisions(the_repository, &revs, NULL);
2191 for (i = 0; i < array->nr; i++) {
2192 struct ref_array_item *item = array->items[i];
2193 add_pending_object(&revs, &item->commit->object, item->refname);
2194 to_clear[i] = item->commit;
2197 filter->merge_commit->object.flags |= UNINTERESTING;
2198 add_pending_object(&revs, &filter->merge_commit->object, "");
2201 if (prepare_revision_walk(&revs))
2202 die(_("revision walk setup failed"));
2207 for (i = 0; i < old_nr; i++) {
2208 struct ref_array_item *item = array->items[i];
2209 struct commit *commit = item->commit;
2211 int is_merged = !!(commit->object.flags & UNINTERESTING);
2213 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2214 array->items[array->nr++] = array->items[i];
2216 free_array_item(item);
2219 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2220 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2225 * API for filtering a set of refs. Based on the type of refs the user
2226 * has requested, we iterate through those refs and apply filters
2227 * as per the given ref_filter structure and finally store the
2228 * filtered refs in the ref_array structure.
2230 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2232 struct ref_filter_cbdata ref_cbdata;
2234 unsigned int broken = 0;
2236 ref_cbdata.array = array;
2237 ref_cbdata.filter = filter;
2239 if (type & FILTER_REFS_INCLUDE_BROKEN)
2241 filter->kind = type & FILTER_REFS_KIND_MASK;
2243 init_contains_cache(&ref_cbdata.contains_cache);
2244 init_contains_cache(&ref_cbdata.no_contains_cache);
2246 /* Simple per-ref filtering */
2248 die("filter_refs: invalid type");
2251 * For common cases where we need only branches or remotes or tags,
2252 * we only iterate through those refs. If a mix of refs is needed,
2253 * we iterate over all refs and filter out required refs with the help
2254 * of filter_ref_kind().
2256 if (filter->kind == FILTER_REFS_BRANCHES)
2257 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2258 else if (filter->kind == FILTER_REFS_REMOTES)
2259 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2260 else if (filter->kind == FILTER_REFS_TAGS)
2261 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2262 else if (filter->kind & FILTER_REFS_ALL)
2263 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2264 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2265 head_ref(ref_filter_handler, &ref_cbdata);
2268 clear_contains_cache(&ref_cbdata.contains_cache);
2269 clear_contains_cache(&ref_cbdata.no_contains_cache);
2271 /* Filters that need revision walking */
2272 if (filter->merge_commit)
2273 do_merge_filter(&ref_cbdata);
2278 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2280 struct atom_value *va, *vb;
2282 cmp_type cmp_type = used_atom[s->atom].type;
2283 int (*cmp_fn)(const char *, const char *);
2284 struct strbuf err = STRBUF_INIT;
2286 if (get_ref_atom_value(a, s->atom, &va, &err))
2288 if (get_ref_atom_value(b, s->atom, &vb, &err))
2290 strbuf_release(&err);
2291 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2293 cmp = versioncmp(va->s, vb->s);
2294 else if (cmp_type == FIELD_STR)
2295 cmp = cmp_fn(va->s, vb->s);
2297 if (va->value < vb->value)
2299 else if (va->value == vb->value)
2305 return (s->reverse) ? -cmp : cmp;
2308 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2310 struct ref_array_item *a = *((struct ref_array_item **)a_);
2311 struct ref_array_item *b = *((struct ref_array_item **)b_);
2312 struct ref_sorting *s;
2314 for (s = ref_sorting; s; s = s->next) {
2315 int cmp = cmp_ref_sorting(s, a, b);
2320 return s && s->ignore_case ?
2321 strcasecmp(a->refname, b->refname) :
2322 strcmp(a->refname, b->refname);
2325 void ref_sorting_icase_all(struct ref_sorting *sorting, int flag)
2327 for (; sorting; sorting = sorting->next)
2328 sorting->ignore_case = !!flag;
2331 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2333 QSORT_S(array->items, array->nr, compare_refs, sorting);
2336 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2338 struct strbuf *s = &state->stack->output;
2340 while (*cp && (!ep || cp < ep)) {
2345 int ch = hex2chr(cp + 1);
2347 strbuf_addch(s, ch);
2353 strbuf_addch(s, *cp);
2358 int format_ref_array_item(struct ref_array_item *info,
2359 const struct ref_format *format,
2360 struct strbuf *final_buf,
2361 struct strbuf *error_buf)
2363 const char *cp, *sp, *ep;
2364 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2366 state.quote_style = format->quote_style;
2367 push_stack_element(&state.stack);
2369 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2370 struct atom_value *atomv;
2373 ep = strchr(sp, ')');
2375 append_literal(cp, sp, &state);
2376 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2377 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2378 atomv->handler(atomv, &state, error_buf)) {
2379 pop_stack_element(&state.stack);
2384 sp = cp + strlen(cp);
2385 append_literal(cp, sp, &state);
2387 if (format->need_color_reset_at_eol) {
2388 struct atom_value resetv;
2389 resetv.s = GIT_COLOR_RESET;
2390 if (append_atom(&resetv, &state, error_buf)) {
2391 pop_stack_element(&state.stack);
2395 if (state.stack->prev) {
2396 pop_stack_element(&state.stack);
2397 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2399 strbuf_addbuf(final_buf, &state.stack->output);
2400 pop_stack_element(&state.stack);
2404 void show_ref_array_item(struct ref_array_item *info,
2405 const struct ref_format *format)
2407 struct strbuf final_buf = STRBUF_INIT;
2408 struct strbuf error_buf = STRBUF_INIT;
2410 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2411 die("%s", error_buf.buf);
2412 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2413 strbuf_release(&error_buf);
2414 strbuf_release(&final_buf);
2418 void pretty_print_ref(const char *name, const struct object_id *oid,
2419 const struct ref_format *format)
2421 struct ref_array_item *ref_item;
2422 ref_item = new_ref_array_item(name, oid);
2423 ref_item->kind = ref_kind_from_refname(name);
2424 show_ref_array_item(ref_item, format);
2425 free_array_item(ref_item);
2428 static int parse_sorting_atom(const char *atom)
2431 * This parses an atom using a dummy ref_format, since we don't
2432 * actually care about the formatting details.
2434 struct ref_format dummy = REF_FORMAT_INIT;
2435 const char *end = atom + strlen(atom);
2436 struct strbuf err = STRBUF_INIT;
2437 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2440 strbuf_release(&err);
2444 /* If no sorting option is given, use refname to sort as default */
2445 struct ref_sorting *ref_default_sorting(void)
2447 static const char cstr_name[] = "refname";
2449 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2451 sorting->next = NULL;
2452 sorting->atom = parse_sorting_atom(cstr_name);
2456 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2458 struct ref_sorting *s;
2460 s = xcalloc(1, sizeof(*s));
2461 s->next = *sorting_tail;
2468 if (skip_prefix(arg, "version:", &arg) ||
2469 skip_prefix(arg, "v:", &arg))
2471 s->atom = parse_sorting_atom(arg);
2474 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2477 * NEEDSWORK: We should probably clear the list in this case, but we've
2478 * already munged the global used_atoms list, which would need to be
2481 BUG_ON_OPT_NEG(unset);
2483 parse_ref_sorting(opt->value, arg);
2487 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2489 struct ref_filter *rf = opt->value;
2490 struct object_id oid;
2491 int no_merged = starts_with(opt->long_name, "no");
2493 BUG_ON_OPT_NEG(unset);
2497 return error(_("option `%s' is incompatible with --merged"),
2500 return error(_("option `%s' is incompatible with --no-merged"),
2505 rf->merge = no_merged
2506 ? REF_FILTER_MERGED_OMIT
2507 : REF_FILTER_MERGED_INCLUDE;
2509 if (get_oid(arg, &oid))
2510 die(_("malformed object name %s"), arg);
2512 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2514 if (!rf->merge_commit)
2515 return error(_("option `%s' must point to a commit"), opt->long_name);