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 (skip_prefix(arg, "trailers", &arg)) {
346 skip_prefix(arg, ":", &arg);
347 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
349 } else if (skip_prefix(arg, "lines=", &arg)) {
350 atom->u.contents.option = C_LINES;
351 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
352 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
354 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
358 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
359 const char *arg, struct strbuf *err)
362 atom->u.objectname.option = O_FULL;
363 else if (!strcmp(arg, "short"))
364 atom->u.objectname.option = O_SHORT;
365 else if (skip_prefix(arg, "short=", &arg)) {
366 atom->u.objectname.option = O_LENGTH;
367 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
368 atom->u.objectname.length == 0)
369 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
370 if (atom->u.objectname.length < MINIMUM_ABBREV)
371 atom->u.objectname.length = MINIMUM_ABBREV;
373 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
377 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
378 const char *arg, struct strbuf *err)
380 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
383 static align_type parse_align_position(const char *s)
385 if (!strcmp(s, "right"))
387 else if (!strcmp(s, "middle"))
389 else if (!strcmp(s, "left"))
394 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
395 const char *arg, struct strbuf *err)
397 struct align *align = &atom->u.align;
398 struct string_list params = STRING_LIST_INIT_DUP;
400 unsigned int width = ~0U;
403 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
405 align->position = ALIGN_LEFT;
407 string_list_split(¶ms, arg, ',', -1);
408 for (i = 0; i < params.nr; i++) {
409 const char *s = params.items[i].string;
412 if (skip_prefix(s, "position=", &s)) {
413 position = parse_align_position(s);
415 strbuf_addf(err, _("unrecognized position:%s"), s);
416 string_list_clear(¶ms, 0);
419 align->position = position;
420 } else if (skip_prefix(s, "width=", &s)) {
421 if (strtoul_ui(s, 10, &width)) {
422 strbuf_addf(err, _("unrecognized width:%s"), s);
423 string_list_clear(¶ms, 0);
426 } else if (!strtoul_ui(s, 10, &width))
428 else if ((position = parse_align_position(s)) >= 0)
429 align->position = position;
431 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
432 string_list_clear(¶ms, 0);
438 string_list_clear(¶ms, 0);
439 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
441 align->width = width;
442 string_list_clear(¶ms, 0);
446 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
447 const char *arg, struct strbuf *err)
450 atom->u.if_then_else.cmp_status = COMPARE_NONE;
452 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
453 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
454 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
455 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
457 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
461 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
462 const char *arg, struct strbuf *unused_err)
464 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
472 int (*parser)(const struct ref_format *format, struct used_atom *atom,
473 const char *arg, struct strbuf *err);
475 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
476 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
477 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
478 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
479 { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
480 { "tree", SOURCE_OBJ },
481 { "parent", SOURCE_OBJ },
482 { "numparent", SOURCE_OBJ, FIELD_ULONG },
483 { "object", SOURCE_OBJ },
484 { "type", SOURCE_OBJ },
485 { "tag", SOURCE_OBJ },
486 { "author", SOURCE_OBJ },
487 { "authorname", SOURCE_OBJ },
488 { "authoremail", SOURCE_OBJ },
489 { "authordate", SOURCE_OBJ, FIELD_TIME },
490 { "committer", SOURCE_OBJ },
491 { "committername", SOURCE_OBJ },
492 { "committeremail", SOURCE_OBJ },
493 { "committerdate", SOURCE_OBJ, FIELD_TIME },
494 { "tagger", SOURCE_OBJ },
495 { "taggername", SOURCE_OBJ },
496 { "taggeremail", SOURCE_OBJ },
497 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
498 { "creator", SOURCE_OBJ },
499 { "creatordate", SOURCE_OBJ, FIELD_TIME },
500 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
501 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
502 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
503 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
504 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
505 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
506 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
507 { "flag", SOURCE_NONE },
508 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
509 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
510 { "worktreepath", SOURCE_NONE },
511 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
512 { "end", SOURCE_NONE },
513 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
514 { "then", SOURCE_NONE },
515 { "else", SOURCE_NONE },
517 * Please update $__git_ref_fieldlist in git-completion.bash
518 * when you add new atoms
522 #define REF_FORMATTING_STATE_INIT { 0, NULL }
524 struct ref_formatting_stack {
525 struct ref_formatting_stack *prev;
526 struct strbuf output;
527 void (*at_end)(struct ref_formatting_stack **stack);
531 struct ref_formatting_state {
533 struct ref_formatting_stack *stack;
538 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
540 uintmax_t value; /* used for sorting when not FIELD_STR */
541 struct used_atom *atom;
545 * Used to parse format string and sort specifiers
547 static int parse_ref_filter_atom(const struct ref_format *format,
548 const char *atom, const char *ep,
556 if (*sp == '*' && sp < ep)
559 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
560 (int)(ep-atom), atom);
562 /* Do we have the atom already used elsewhere? */
563 for (i = 0; i < used_atom_cnt; i++) {
564 int len = strlen(used_atom[i].name);
565 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
570 * If the atom name has a colon, strip it and everything after
571 * it off - it specifies the format for this entry, and
572 * shouldn't be used for checking against the valid_atom
575 arg = memchr(sp, ':', ep - sp);
576 atom_len = (arg ? arg : ep) - sp;
578 /* Is the atom a valid one? */
579 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
580 int len = strlen(valid_atom[i].name);
581 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
585 if (ARRAY_SIZE(valid_atom) <= i)
586 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
587 (int)(ep-atom), atom);
588 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
589 return strbuf_addf_ret(err, -1,
590 _("not a git repository, but the field '%.*s' requires access to object data"),
591 (int)(ep-atom), atom);
593 /* Add it in, including the deref prefix */
596 REALLOC_ARRAY(used_atom, used_atom_cnt);
597 used_atom[at].name = xmemdupz(atom, ep - atom);
598 used_atom[at].type = valid_atom[i].cmp_type;
599 used_atom[at].source = valid_atom[i].source;
600 if (used_atom[at].source == SOURCE_OBJ) {
602 oi_deref.info.contentp = &oi_deref.content;
604 oi.info.contentp = &oi.content;
607 arg = used_atom[at].name + (arg - atom) + 1;
610 * Treat empty sub-arguments list as NULL (i.e.,
611 * "%(atom:)" is equivalent to "%(atom)").
616 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
617 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
621 if (!strcmp(valid_atom[i].name, "symref"))
626 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
628 switch (quote_style) {
630 strbuf_addstr(s, str);
633 sq_quote_buf(s, str);
636 perl_quote_buf(s, str);
639 python_quote_buf(s, str);
642 tcl_quote_buf(s, str);
647 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
648 struct strbuf *unused_err)
651 * Quote formatting is only done when the stack has a single
652 * element. Otherwise quote formatting is done on the
653 * element's entire output strbuf when the %(end) atom is
656 if (!state->stack->prev)
657 quote_formatting(&state->stack->output, v->s, state->quote_style);
659 strbuf_addstr(&state->stack->output, v->s);
663 static void push_stack_element(struct ref_formatting_stack **stack)
665 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
667 strbuf_init(&s->output, 0);
672 static void pop_stack_element(struct ref_formatting_stack **stack)
674 struct ref_formatting_stack *current = *stack;
675 struct ref_formatting_stack *prev = current->prev;
678 strbuf_addbuf(&prev->output, ¤t->output);
679 strbuf_release(¤t->output);
684 static void end_align_handler(struct ref_formatting_stack **stack)
686 struct ref_formatting_stack *cur = *stack;
687 struct align *align = (struct align *)cur->at_end_data;
688 struct strbuf s = STRBUF_INIT;
690 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
691 strbuf_swap(&cur->output, &s);
695 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
696 struct strbuf *unused_err)
698 struct ref_formatting_stack *new_stack;
700 push_stack_element(&state->stack);
701 new_stack = state->stack;
702 new_stack->at_end = end_align_handler;
703 new_stack->at_end_data = &atomv->atom->u.align;
707 static void if_then_else_handler(struct ref_formatting_stack **stack)
709 struct ref_formatting_stack *cur = *stack;
710 struct ref_formatting_stack *prev = cur->prev;
711 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
713 if (!if_then_else->then_atom_seen)
714 die(_("format: %%(if) atom used without a %%(then) atom"));
716 if (if_then_else->else_atom_seen) {
718 * There is an %(else) atom: we need to drop one state from the
719 * stack, either the %(else) branch if the condition is satisfied, or
720 * the %(then) branch if it isn't.
722 if (if_then_else->condition_satisfied) {
723 strbuf_reset(&cur->output);
724 pop_stack_element(&cur);
726 strbuf_swap(&cur->output, &prev->output);
727 strbuf_reset(&cur->output);
728 pop_stack_element(&cur);
730 } else if (!if_then_else->condition_satisfied) {
732 * No %(else) atom: just drop the %(then) branch if the
733 * condition is not satisfied.
735 strbuf_reset(&cur->output);
742 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
743 struct strbuf *unused_err)
745 struct ref_formatting_stack *new_stack;
746 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
748 if_then_else->str = atomv->atom->u.if_then_else.str;
749 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
751 push_stack_element(&state->stack);
752 new_stack = state->stack;
753 new_stack->at_end = if_then_else_handler;
754 new_stack->at_end_data = if_then_else;
758 static int is_empty(const char *s)
768 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
771 struct ref_formatting_stack *cur = state->stack;
772 struct if_then_else *if_then_else = NULL;
774 if (cur->at_end == if_then_else_handler)
775 if_then_else = (struct if_then_else *)cur->at_end_data;
777 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
778 if (if_then_else->then_atom_seen)
779 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
780 if (if_then_else->else_atom_seen)
781 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
782 if_then_else->then_atom_seen = 1;
784 * If the 'equals' or 'notequals' attribute is used then
785 * perform the required comparison. If not, only non-empty
786 * strings satisfy the 'if' condition.
788 if (if_then_else->cmp_status == COMPARE_EQUAL) {
789 if (!strcmp(if_then_else->str, cur->output.buf))
790 if_then_else->condition_satisfied = 1;
791 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
792 if (strcmp(if_then_else->str, cur->output.buf))
793 if_then_else->condition_satisfied = 1;
794 } else if (cur->output.len && !is_empty(cur->output.buf))
795 if_then_else->condition_satisfied = 1;
796 strbuf_reset(&cur->output);
800 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
803 struct ref_formatting_stack *prev = state->stack;
804 struct if_then_else *if_then_else = NULL;
806 if (prev->at_end == if_then_else_handler)
807 if_then_else = (struct if_then_else *)prev->at_end_data;
809 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
810 if (!if_then_else->then_atom_seen)
811 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
812 if (if_then_else->else_atom_seen)
813 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
814 if_then_else->else_atom_seen = 1;
815 push_stack_element(&state->stack);
816 state->stack->at_end_data = prev->at_end_data;
817 state->stack->at_end = prev->at_end;
821 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
824 struct ref_formatting_stack *current = state->stack;
825 struct strbuf s = STRBUF_INIT;
827 if (!current->at_end)
828 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
829 current->at_end(&state->stack);
831 /* Stack may have been popped within at_end(), hence reset the current pointer */
832 current = state->stack;
835 * Perform quote formatting when the stack element is that of
836 * a supporting atom. If nested then perform quote formatting
837 * only on the topmost supporting atom.
839 if (!current->prev->prev) {
840 quote_formatting(&s, current->output.buf, state->quote_style);
841 strbuf_swap(¤t->output, &s);
844 pop_stack_element(&state->stack);
849 * In a format string, find the next occurrence of %(atom).
851 static const char *find_next(const char *cp)
856 * %( is the start of an atom;
857 * %% is a quoted per-cent.
861 else if (cp[1] == '%')
862 cp++; /* skip over two % */
863 /* otherwise this is a singleton, literal % */
871 * Make sure the format string is well formed, and parse out
874 int verify_ref_format(struct ref_format *format)
878 format->need_color_reset_at_eol = 0;
879 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
880 struct strbuf err = STRBUF_INIT;
881 const char *color, *ep = strchr(sp, ')');
885 return error(_("malformed format string %s"), sp);
886 /* sp points at "%(" and ep points at the closing ")" */
887 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
892 if (skip_prefix(used_atom[at].name, "color:", &color))
893 format->need_color_reset_at_eol = !!strcmp(color, "reset");
894 strbuf_release(&err);
896 if (format->need_color_reset_at_eol && !want_color(format->use_color))
897 format->need_color_reset_at_eol = 0;
901 static int grab_objectname(const char *name, const struct object_id *oid,
902 struct atom_value *v, struct used_atom *atom)
904 if (starts_with(name, "objectname")) {
905 if (atom->u.objectname.option == O_SHORT) {
906 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
908 } else if (atom->u.objectname.option == O_FULL) {
909 v->s = xstrdup(oid_to_hex(oid));
911 } else if (atom->u.objectname.option == O_LENGTH) {
912 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
915 BUG("unknown %%(objectname) option");
920 /* See grab_values */
921 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
925 for (i = 0; i < used_atom_cnt; i++) {
926 const char *name = used_atom[i].name;
927 struct atom_value *v = &val[i];
928 if (!!deref != (*name == '*'))
932 if (!strcmp(name, "objecttype"))
933 v->s = xstrdup(type_name(oi->type));
934 else if (!strcmp(name, "objectsize:disk")) {
935 v->value = oi->disk_size;
936 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
937 } else if (!strcmp(name, "objectsize")) {
939 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
940 } else if (!strcmp(name, "deltabase"))
941 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
943 grab_objectname(name, &oi->oid, v, &used_atom[i]);
947 /* See grab_values */
948 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
951 struct tag *tag = (struct tag *) obj;
953 for (i = 0; i < used_atom_cnt; i++) {
954 const char *name = used_atom[i].name;
955 struct atom_value *v = &val[i];
956 if (!!deref != (*name == '*'))
960 if (!strcmp(name, "tag"))
961 v->s = xstrdup(tag->tag);
962 else if (!strcmp(name, "type") && tag->tagged)
963 v->s = xstrdup(type_name(tag->tagged->type));
964 else if (!strcmp(name, "object") && tag->tagged)
965 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
969 /* See grab_values */
970 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
973 struct commit *commit = (struct commit *) obj;
975 for (i = 0; i < used_atom_cnt; i++) {
976 const char *name = used_atom[i].name;
977 struct atom_value *v = &val[i];
978 if (!!deref != (*name == '*'))
982 if (!strcmp(name, "tree")) {
983 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
985 else if (!strcmp(name, "numparent")) {
986 v->value = commit_list_count(commit->parents);
987 v->s = xstrfmt("%lu", (unsigned long)v->value);
989 else if (!strcmp(name, "parent")) {
990 struct commit_list *parents;
991 struct strbuf s = STRBUF_INIT;
992 for (parents = commit->parents; parents; parents = parents->next) {
993 struct commit *parent = parents->item;
994 if (parents != commit->parents)
995 strbuf_addch(&s, ' ');
996 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
998 v->s = strbuf_detach(&s, NULL);
1003 static const char *find_wholine(const char *who, int wholen, const char *buf)
1007 if (!strncmp(buf, who, wholen) &&
1009 return buf + wholen + 1;
1010 eol = strchr(buf, '\n');
1015 return ""; /* end of header */
1021 static const char *copy_line(const char *buf)
1023 const char *eol = strchrnul(buf, '\n');
1024 return xmemdupz(buf, eol - buf);
1027 static const char *copy_name(const char *buf)
1030 for (cp = buf; *cp && *cp != '\n'; cp++) {
1031 if (!strncmp(cp, " <", 2))
1032 return xmemdupz(buf, cp - buf);
1037 static const char *copy_email(const char *buf)
1039 const char *email = strchr(buf, '<');
1040 const char *eoemail;
1043 eoemail = strchr(email, '>');
1046 return xmemdupz(email, eoemail + 1 - email);
1049 static char *copy_subject(const char *buf, unsigned long len)
1051 char *r = xmemdupz(buf, len);
1054 for (i = 0; i < len; i++)
1061 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1063 const char *eoemail = strstr(buf, "> ");
1065 timestamp_t timestamp;
1067 struct date_mode date_mode = { DATE_NORMAL };
1068 const char *formatp;
1071 * We got here because atomname ends in "date" or "date<something>";
1072 * it's not possible that <something> is not ":<format>" because
1073 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1074 * ":" means no format is specified, and use the default.
1076 formatp = strchr(atomname, ':');
1077 if (formatp != NULL) {
1079 parse_date_format(formatp, &date_mode);
1084 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1085 if (timestamp == TIME_MAX)
1087 tz = strtol(zone, NULL, 10);
1088 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1090 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1091 v->value = timestamp;
1098 /* See grab_values */
1099 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1102 int wholen = strlen(who);
1103 const char *wholine = NULL;
1105 for (i = 0; i < used_atom_cnt; i++) {
1106 const char *name = used_atom[i].name;
1107 struct atom_value *v = &val[i];
1108 if (!!deref != (*name == '*'))
1112 if (strncmp(who, name, wholen))
1114 if (name[wholen] != 0 &&
1115 strcmp(name + wholen, "name") &&
1116 strcmp(name + wholen, "email") &&
1117 !starts_with(name + wholen, "date"))
1120 wholine = find_wholine(who, wholen, buf);
1122 return; /* no point looking for it */
1123 if (name[wholen] == 0)
1124 v->s = copy_line(wholine);
1125 else if (!strcmp(name + wholen, "name"))
1126 v->s = copy_name(wholine);
1127 else if (!strcmp(name + wholen, "email"))
1128 v->s = copy_email(wholine);
1129 else if (starts_with(name + wholen, "date"))
1130 grab_date(wholine, v, name);
1134 * For a tag or a commit object, if "creator" or "creatordate" is
1135 * requested, do something special.
1137 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1138 return; /* "author" for commit object is not wanted */
1140 wholine = find_wholine(who, wholen, buf);
1143 for (i = 0; i < used_atom_cnt; i++) {
1144 const char *name = used_atom[i].name;
1145 struct atom_value *v = &val[i];
1146 if (!!deref != (*name == '*'))
1151 if (starts_with(name, "creatordate"))
1152 grab_date(wholine, v, name);
1153 else if (!strcmp(name, "creator"))
1154 v->s = copy_line(wholine);
1158 static void find_subpos(const char *buf,
1159 const char **sub, unsigned long *sublen,
1160 const char **body, unsigned long *bodylen,
1161 unsigned long *nonsiglen,
1162 const char **sig, unsigned long *siglen)
1165 /* skip past header until we hit empty line */
1166 while (*buf && *buf != '\n') {
1167 eol = strchrnul(buf, '\n');
1172 /* skip any empty lines */
1173 while (*buf == '\n')
1176 /* parse signature first; we might not even have a subject line */
1177 *sig = buf + parse_signature(buf, strlen(buf));
1178 *siglen = strlen(*sig);
1180 /* subject is first non-empty line */
1182 /* subject goes to first empty line */
1183 while (buf < *sig && *buf && *buf != '\n') {
1184 eol = strchrnul(buf, '\n');
1189 *sublen = buf - *sub;
1190 /* drop trailing newline, if present */
1191 if (*sublen && (*sub)[*sublen - 1] == '\n')
1194 /* skip any empty lines */
1195 while (*buf == '\n')
1198 *bodylen = strlen(buf);
1199 *nonsiglen = *sig - buf;
1203 * If 'lines' is greater than 0, append that many lines from the given
1204 * 'buf' of length 'size' to the given strbuf.
1206 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1209 const char *sp, *eol;
1214 for (i = 0; i < lines && sp < buf + size; i++) {
1216 strbuf_addstr(out, "\n ");
1217 eol = memchr(sp, '\n', size - (sp - buf));
1218 len = eol ? eol - sp : size - (sp - buf);
1219 strbuf_add(out, sp, len);
1226 /* See grab_values */
1227 static void grab_sub_body_contents(struct atom_value *val, int deref, void *buf)
1230 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1231 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1233 for (i = 0; i < used_atom_cnt; i++) {
1234 struct used_atom *atom = &used_atom[i];
1235 const char *name = atom->name;
1236 struct atom_value *v = &val[i];
1237 if (!!deref != (*name == '*'))
1241 if (strcmp(name, "subject") &&
1242 strcmp(name, "body") &&
1243 !starts_with(name, "trailers") &&
1244 !starts_with(name, "contents"))
1249 &bodypos, &bodylen, &nonsiglen,
1252 if (atom->u.contents.option == C_SUB)
1253 v->s = copy_subject(subpos, sublen);
1254 else if (atom->u.contents.option == C_BODY_DEP)
1255 v->s = xmemdupz(bodypos, bodylen);
1256 else if (atom->u.contents.option == C_BODY)
1257 v->s = xmemdupz(bodypos, nonsiglen);
1258 else if (atom->u.contents.option == C_SIG)
1259 v->s = xmemdupz(sigpos, siglen);
1260 else if (atom->u.contents.option == C_LINES) {
1261 struct strbuf s = STRBUF_INIT;
1262 const char *contents_end = bodylen + bodypos - siglen;
1264 /* Size is the length of the message after removing the signature */
1265 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1266 v->s = strbuf_detach(&s, NULL);
1267 } else if (atom->u.contents.option == C_TRAILERS) {
1268 struct strbuf s = STRBUF_INIT;
1270 /* Format the trailer info according to the trailer_opts given */
1271 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1273 v->s = strbuf_detach(&s, NULL);
1274 } else if (atom->u.contents.option == C_BARE)
1275 v->s = xstrdup(subpos);
1280 * We want to have empty print-string for field requests
1281 * that do not apply (e.g. "authordate" for a tag object)
1283 static void fill_missing_values(struct atom_value *val)
1286 for (i = 0; i < used_atom_cnt; i++) {
1287 struct atom_value *v = &val[i];
1294 * val is a list of atom_value to hold returned values. Extract
1295 * the values for atoms in used_atom array out of (obj, buf, sz).
1296 * when deref is false, (obj, buf, sz) is the object that is
1297 * pointed at by the ref itself; otherwise it is the object the
1298 * ref (which is a tag) refers to.
1300 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf)
1302 switch (obj->type) {
1304 grab_tag_values(val, deref, obj);
1305 grab_sub_body_contents(val, deref, buf);
1306 grab_person("tagger", val, deref, buf);
1309 grab_commit_values(val, deref, obj);
1310 grab_sub_body_contents(val, deref, buf);
1311 grab_person("author", val, deref, buf);
1312 grab_person("committer", val, deref, buf);
1315 /* grab_tree_values(val, deref, obj, buf, sz); */
1318 /* grab_blob_values(val, deref, obj, buf, sz); */
1321 die("Eh? Object of type %d?", obj->type);
1325 static inline char *copy_advance(char *dst, const char *src)
1332 static const char *lstrip_ref_components(const char *refname, int len)
1334 long remaining = len;
1335 const char *start = xstrdup(refname);
1336 const char *to_free = start;
1340 const char *p = refname;
1342 /* Find total no of '/' separated path-components */
1343 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1346 * The number of components we need to strip is now
1347 * the total minus the components to be left (Plus one
1348 * because we count the number of '/', but the number
1349 * of components is one more than the no of '/').
1351 remaining = i + len + 1;
1354 while (remaining > 0) {
1357 free((char *)to_free);
1365 start = xstrdup(start);
1366 free((char *)to_free);
1370 static const char *rstrip_ref_components(const char *refname, int len)
1372 long remaining = len;
1373 const char *start = xstrdup(refname);
1374 const char *to_free = start;
1378 const char *p = refname;
1380 /* Find total no of '/' separated path-components */
1381 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1384 * The number of components we need to strip is now
1385 * the total minus the components to be left (Plus one
1386 * because we count the number of '/', but the number
1387 * of components is one more than the no of '/').
1389 remaining = i + len + 1;
1392 while (remaining-- > 0) {
1393 char *p = strrchr(start, '/');
1395 free((char *)to_free);
1403 static const char *show_ref(struct refname_atom *atom, const char *refname)
1405 if (atom->option == R_SHORT)
1406 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1407 else if (atom->option == R_LSTRIP)
1408 return lstrip_ref_components(refname, atom->lstrip);
1409 else if (atom->option == R_RSTRIP)
1410 return rstrip_ref_components(refname, atom->rstrip);
1412 return xstrdup(refname);
1415 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1416 struct branch *branch, const char **s)
1418 int num_ours, num_theirs;
1419 if (atom->u.remote_ref.option == RR_REF)
1420 *s = show_ref(&atom->u.remote_ref.refname, refname);
1421 else if (atom->u.remote_ref.option == RR_TRACK) {
1422 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1423 NULL, atom->u.remote_ref.push,
1424 AHEAD_BEHIND_FULL) < 0) {
1425 *s = xstrdup(msgs.gone);
1426 } else if (!num_ours && !num_theirs)
1429 *s = xstrfmt(msgs.behind, num_theirs);
1430 else if (!num_theirs)
1431 *s = xstrfmt(msgs.ahead, num_ours);
1433 *s = xstrfmt(msgs.ahead_behind,
1434 num_ours, num_theirs);
1435 if (!atom->u.remote_ref.nobracket && *s[0]) {
1436 const char *to_free = *s;
1437 *s = xstrfmt("[%s]", *s);
1438 free((void *)to_free);
1440 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1441 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1442 NULL, atom->u.remote_ref.push,
1443 AHEAD_BEHIND_FULL) < 0) {
1447 if (!num_ours && !num_theirs)
1451 else if (!num_theirs)
1455 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1457 const char *remote = atom->u.remote_ref.push ?
1458 pushremote_for_branch(branch, &explicit) :
1459 remote_for_branch(branch, &explicit);
1460 *s = xstrdup(explicit ? remote : "");
1461 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1464 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1465 *s = xstrdup(merge ? merge : "");
1467 BUG("unhandled RR_* enum");
1470 char *get_head_description(void)
1472 struct strbuf desc = STRBUF_INIT;
1473 struct wt_status_state state;
1474 memset(&state, 0, sizeof(state));
1475 wt_status_get_state(the_repository, &state, 1);
1478 * The ( character must be hard-coded and not part of a localizable
1479 * string, since the description is used as a sort key and compared
1482 strbuf_addch(&desc, '(');
1483 if (state.rebase_in_progress ||
1484 state.rebase_interactive_in_progress) {
1486 strbuf_addf(&desc, _("no branch, rebasing %s"),
1489 strbuf_addf(&desc, _("no branch, rebasing detached HEAD %s"),
1490 state.detached_from);
1491 } else if (state.bisect_in_progress)
1492 strbuf_addf(&desc, _("no branch, bisect started on %s"),
1494 else if (state.detached_from) {
1495 if (state.detached_at)
1496 strbuf_addstr(&desc, HEAD_DETACHED_AT);
1498 strbuf_addstr(&desc, HEAD_DETACHED_FROM);
1499 strbuf_addstr(&desc, state.detached_from);
1502 strbuf_addstr(&desc, _("no branch"));
1503 strbuf_addch(&desc, ')');
1507 free(state.detached_from);
1508 return strbuf_detach(&desc, NULL);
1511 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1516 return show_ref(&atom->u.refname, ref->symref);
1519 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1521 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1522 return get_head_description();
1523 return show_ref(&atom->u.refname, ref->refname);
1526 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1527 struct expand_data *oi, struct strbuf *err)
1529 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1531 if (oi->info.contentp) {
1532 /* We need to know that to use parse_object_buffer properly */
1533 oi->info.sizep = &oi->size;
1534 oi->info.typep = &oi->type;
1536 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1537 OBJECT_INFO_LOOKUP_REPLACE))
1538 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1539 oid_to_hex(&oi->oid), ref->refname);
1540 if (oi->info.disk_sizep && oi->disk_size < 0)
1541 BUG("Object size is less than zero.");
1543 if (oi->info.contentp) {
1544 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1548 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1549 oid_to_hex(&oi->oid), ref->refname);
1551 grab_values(ref->value, deref, *obj, oi->content);
1554 grab_common_values(ref->value, deref, oi);
1560 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1564 for (i = 0; worktrees[i]; i++) {
1565 if (worktrees[i]->head_ref) {
1566 struct ref_to_worktree_entry *entry;
1567 entry = xmalloc(sizeof(*entry));
1568 entry->wt = worktrees[i];
1569 hashmap_entry_init(&entry->ent,
1570 strhash(worktrees[i]->head_ref));
1572 hashmap_add(map, &entry->ent);
1577 static void lazy_init_worktree_map(void)
1579 if (ref_to_worktree_map.worktrees)
1582 ref_to_worktree_map.worktrees = get_worktrees(0);
1583 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1584 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1587 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1589 struct hashmap_entry entry, *e;
1590 struct ref_to_worktree_entry *lookup_result;
1592 lazy_init_worktree_map();
1594 hashmap_entry_init(&entry, strhash(ref->refname));
1595 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1600 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1602 return xstrdup(lookup_result->wt->path);
1606 * Parse the object referred by ref, and grab needed value.
1608 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1612 struct object_info empty = OBJECT_INFO_INIT;
1614 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1616 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1617 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1620 ref->symref = xstrdup("");
1623 /* Fill in specials first */
1624 for (i = 0; i < used_atom_cnt; i++) {
1625 struct used_atom *atom = &used_atom[i];
1626 const char *name = used_atom[i].name;
1627 struct atom_value *v = &ref->value[i];
1629 const char *refname;
1630 struct branch *branch = NULL;
1632 v->handler = append_atom;
1640 if (starts_with(name, "refname"))
1641 refname = get_refname(atom, ref);
1642 else if (!strcmp(name, "worktreepath")) {
1643 if (ref->kind == FILTER_REFS_BRANCHES)
1644 v->s = get_worktree_path(atom, ref);
1649 else if (starts_with(name, "symref"))
1650 refname = get_symref(atom, ref);
1651 else if (starts_with(name, "upstream")) {
1652 const char *branch_name;
1653 /* only local branches may have an upstream */
1654 if (!skip_prefix(ref->refname, "refs/heads/",
1659 branch = branch_get(branch_name);
1661 refname = branch_get_upstream(branch, NULL);
1663 fill_remote_ref_details(atom, refname, branch, &v->s);
1667 } else if (atom->u.remote_ref.push) {
1668 const char *branch_name;
1670 if (!skip_prefix(ref->refname, "refs/heads/",
1673 branch = branch_get(branch_name);
1675 if (atom->u.remote_ref.push_remote)
1678 refname = branch_get_push(branch, NULL);
1682 /* We will definitely re-init v->s on the next line. */
1684 fill_remote_ref_details(atom, refname, branch, &v->s);
1686 } else if (starts_with(name, "color:")) {
1687 v->s = xstrdup(atom->u.color);
1689 } else if (!strcmp(name, "flag")) {
1690 char buf[256], *cp = buf;
1691 if (ref->flag & REF_ISSYMREF)
1692 cp = copy_advance(cp, ",symref");
1693 if (ref->flag & REF_ISPACKED)
1694 cp = copy_advance(cp, ",packed");
1699 v->s = xstrdup(buf + 1);
1702 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1704 } else if (!strcmp(name, "HEAD")) {
1705 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1706 v->s = xstrdup("*");
1708 v->s = xstrdup(" ");
1710 } else if (starts_with(name, "align")) {
1711 v->handler = align_atom_handler;
1714 } else if (!strcmp(name, "end")) {
1715 v->handler = end_atom_handler;
1718 } else if (starts_with(name, "if")) {
1720 if (skip_prefix(name, "if:", &s))
1724 v->handler = if_atom_handler;
1726 } else if (!strcmp(name, "then")) {
1727 v->handler = then_atom_handler;
1730 } else if (!strcmp(name, "else")) {
1731 v->handler = else_atom_handler;
1738 v->s = xstrdup(refname);
1740 v->s = xstrfmt("%s^{}", refname);
1741 free((char *)refname);
1744 for (i = 0; i < used_atom_cnt; i++) {
1745 struct atom_value *v = &ref->value[i];
1746 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1747 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1748 oid_to_hex(&ref->objectname), ref->refname);
1752 oi.info.contentp = &oi.content;
1753 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1754 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1758 oi.oid = ref->objectname;
1759 if (get_object(ref, 0, &obj, &oi, err))
1763 * If there is no atom that wants to know about tagged
1764 * object, we are done.
1766 if (!need_tagged || (obj->type != OBJ_TAG))
1770 * If it is a tag object, see if we use a value that derefs
1771 * the object, and if we do grab the object it refers to.
1773 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
1776 * NEEDSWORK: This derefs tag only once, which
1777 * is good to deal with chains of trust, but
1778 * is not consistent with what deref_tag() does
1779 * which peels the onion to the core.
1781 return get_object(ref, 1, &obj, &oi_deref, err);
1785 * Given a ref, return the value for the atom. This lazily gets value
1786 * out of the object by calling populate value.
1788 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1789 struct atom_value **v, struct strbuf *err)
1792 if (populate_value(ref, err))
1794 fill_missing_values(ref->value);
1796 *v = &ref->value[atom];
1801 * Return 1 if the refname matches one of the patterns, otherwise 0.
1802 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1803 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1804 * matches "refs/heads/mas*", too).
1806 static int match_pattern(const struct ref_filter *filter, const char *refname)
1808 const char **patterns = filter->name_patterns;
1811 if (filter->ignore_case)
1812 flags |= WM_CASEFOLD;
1815 * When no '--format' option is given we need to skip the prefix
1816 * for matching refs of tags and branches.
1818 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1819 skip_prefix(refname, "refs/heads/", &refname) ||
1820 skip_prefix(refname, "refs/remotes/", &refname) ||
1821 skip_prefix(refname, "refs/", &refname));
1823 for (; *patterns; patterns++) {
1824 if (!wildmatch(*patterns, refname, flags))
1831 * Return 1 if the refname matches one of the patterns, otherwise 0.
1832 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1833 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1834 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1836 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1838 const char **pattern = filter->name_patterns;
1839 int namelen = strlen(refname);
1840 unsigned flags = WM_PATHNAME;
1842 if (filter->ignore_case)
1843 flags |= WM_CASEFOLD;
1845 for (; *pattern; pattern++) {
1846 const char *p = *pattern;
1847 int plen = strlen(p);
1849 if ((plen <= namelen) &&
1850 !strncmp(refname, p, plen) &&
1851 (refname[plen] == '\0' ||
1852 refname[plen] == '/' ||
1855 if (!wildmatch(p, refname, flags))
1861 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1862 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1864 if (!*filter->name_patterns)
1865 return 1; /* No pattern always matches */
1866 if (filter->match_as_path)
1867 return match_name_as_path(filter, refname);
1868 return match_pattern(filter, refname);
1871 static int qsort_strcmp(const void *va, const void *vb)
1873 const char *a = *(const char **)va;
1874 const char *b = *(const char **)vb;
1876 return strcmp(a, b);
1879 static void find_longest_prefixes_1(struct string_list *out,
1880 struct strbuf *prefix,
1881 const char **patterns, size_t nr)
1885 for (i = 0; i < nr; i++) {
1886 char c = patterns[i][prefix->len];
1887 if (!c || is_glob_special(c)) {
1888 string_list_append(out, prefix->buf);
1898 * Set "end" to the index of the element _after_ the last one
1901 for (end = i + 1; end < nr; end++) {
1902 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1906 strbuf_addch(prefix, patterns[i][prefix->len]);
1907 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1908 strbuf_setlen(prefix, prefix->len - 1);
1914 static void find_longest_prefixes(struct string_list *out,
1915 const char **patterns)
1917 struct argv_array sorted = ARGV_ARRAY_INIT;
1918 struct strbuf prefix = STRBUF_INIT;
1920 argv_array_pushv(&sorted, patterns);
1921 QSORT(sorted.argv, sorted.argc, qsort_strcmp);
1923 find_longest_prefixes_1(out, &prefix, sorted.argv, sorted.argc);
1925 argv_array_clear(&sorted);
1926 strbuf_release(&prefix);
1930 * This is the same as for_each_fullref_in(), but it tries to iterate
1931 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1932 * pattern match, so the callback still has to match each ref individually.
1934 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1939 struct string_list prefixes = STRING_LIST_INIT_DUP;
1940 struct string_list_item *prefix;
1943 if (!filter->match_as_path) {
1945 * in this case, the patterns are applied after
1946 * prefixes like "refs/heads/" etc. are stripped off,
1947 * so we have to look at everything:
1949 return for_each_fullref_in("", cb, cb_data, broken);
1952 if (filter->ignore_case) {
1954 * we can't handle case-insensitive comparisons,
1955 * so just return everything and let the caller
1958 return for_each_fullref_in("", cb, cb_data, broken);
1961 if (!filter->name_patterns[0]) {
1962 /* no patterns; we have to look at everything */
1963 return for_each_fullref_in("", cb, cb_data, broken);
1966 find_longest_prefixes(&prefixes, filter->name_patterns);
1968 for_each_string_list_item(prefix, &prefixes) {
1969 ret = for_each_fullref_in(prefix->string, cb, cb_data, broken);
1974 string_list_clear(&prefixes, 0);
1979 * Given a ref (oid, refname), check if the ref belongs to the array
1980 * of oids. If the given ref is a tag, check if the given tag points
1981 * at one of the oids in the given oid array.
1983 * 1. Only a single level of inderection is obtained, we might want to
1984 * change this to account for multiple levels (e.g. annotated tags
1985 * pointing to annotated tags pointing to a commit.)
1986 * 2. As the refs are cached we might know what refname peels to without
1987 * the need to parse the object via parse_object(). peel_ref() might be a
1988 * more efficient alternative to obtain the pointee.
1990 static const struct object_id *match_points_at(struct oid_array *points_at,
1991 const struct object_id *oid,
1992 const char *refname)
1994 const struct object_id *tagged_oid = NULL;
1997 if (oid_array_lookup(points_at, oid) >= 0)
1999 obj = parse_object(the_repository, oid);
2001 die(_("malformed object at '%s'"), refname);
2002 if (obj->type == OBJ_TAG)
2003 tagged_oid = get_tagged_oid((struct tag *)obj);
2004 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2010 * Allocate space for a new ref_array_item and copy the name and oid to it.
2012 * Callers can then fill in other struct members at their leisure.
2014 static struct ref_array_item *new_ref_array_item(const char *refname,
2015 const struct object_id *oid)
2017 struct ref_array_item *ref;
2019 FLEX_ALLOC_STR(ref, refname, refname);
2020 oidcpy(&ref->objectname, oid);
2025 struct ref_array_item *ref_array_push(struct ref_array *array,
2026 const char *refname,
2027 const struct object_id *oid)
2029 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2031 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2032 array->items[array->nr++] = ref;
2037 static int ref_kind_from_refname(const char *refname)
2045 { "refs/heads/" , FILTER_REFS_BRANCHES },
2046 { "refs/remotes/" , FILTER_REFS_REMOTES },
2047 { "refs/tags/", FILTER_REFS_TAGS}
2050 if (!strcmp(refname, "HEAD"))
2051 return FILTER_REFS_DETACHED_HEAD;
2053 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2054 if (starts_with(refname, ref_kind[i].prefix))
2055 return ref_kind[i].kind;
2058 return FILTER_REFS_OTHERS;
2061 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2063 if (filter->kind == FILTER_REFS_BRANCHES ||
2064 filter->kind == FILTER_REFS_REMOTES ||
2065 filter->kind == FILTER_REFS_TAGS)
2066 return filter->kind;
2067 return ref_kind_from_refname(refname);
2070 struct ref_filter_cbdata {
2071 struct ref_array *array;
2072 struct ref_filter *filter;
2073 struct contains_cache contains_cache;
2074 struct contains_cache no_contains_cache;
2078 * A call-back given to for_each_ref(). Filter refs and keep them for
2079 * later object processing.
2081 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2083 struct ref_filter_cbdata *ref_cbdata = cb_data;
2084 struct ref_filter *filter = ref_cbdata->filter;
2085 struct ref_array_item *ref;
2086 struct commit *commit = NULL;
2089 if (flag & REF_BAD_NAME) {
2090 warning(_("ignoring ref with broken name %s"), refname);
2094 if (flag & REF_ISBROKEN) {
2095 warning(_("ignoring broken ref %s"), refname);
2099 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2100 kind = filter_ref_kind(filter, refname);
2101 if (!(kind & filter->kind))
2104 if (!filter_pattern_match(filter, refname))
2107 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2111 * A merge filter is applied on refs pointing to commits. Hence
2112 * obtain the commit using the 'oid' available and discard all
2113 * non-commits early. The actual filtering is done later.
2115 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2116 commit = lookup_commit_reference_gently(the_repository, oid,
2120 /* We perform the filtering for the '--contains' option... */
2121 if (filter->with_commit &&
2122 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2124 /* ...or for the `--no-contains' option */
2125 if (filter->no_commit &&
2126 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2131 * We do not open the object yet; sort may only need refname
2132 * to do its job and the resulting list may yet to be pruned
2133 * by maxcount logic.
2135 ref = ref_array_push(ref_cbdata->array, refname, oid);
2136 ref->commit = commit;
2143 /* Free memory allocated for a ref_array_item */
2144 static void free_array_item(struct ref_array_item *item)
2146 free((char *)item->symref);
2149 for (i = 0; i < used_atom_cnt; i++)
2150 free((char *)item->value[i].s);
2156 /* Free all memory allocated for ref_array */
2157 void ref_array_clear(struct ref_array *array)
2161 for (i = 0; i < array->nr; i++)
2162 free_array_item(array->items[i]);
2163 FREE_AND_NULL(array->items);
2164 array->nr = array->alloc = 0;
2166 for (i = 0; i < used_atom_cnt; i++)
2167 free((char *)used_atom[i].name);
2168 FREE_AND_NULL(used_atom);
2171 if (ref_to_worktree_map.worktrees) {
2172 hashmap_free_entries(&(ref_to_worktree_map.map),
2173 struct ref_to_worktree_entry, ent);
2174 free_worktrees(ref_to_worktree_map.worktrees);
2175 ref_to_worktree_map.worktrees = NULL;
2179 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2181 struct rev_info revs;
2183 struct ref_filter *filter = ref_cbdata->filter;
2184 struct ref_array *array = ref_cbdata->array;
2185 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2187 repo_init_revisions(the_repository, &revs, NULL);
2189 for (i = 0; i < array->nr; i++) {
2190 struct ref_array_item *item = array->items[i];
2191 add_pending_object(&revs, &item->commit->object, item->refname);
2192 to_clear[i] = item->commit;
2195 filter->merge_commit->object.flags |= UNINTERESTING;
2196 add_pending_object(&revs, &filter->merge_commit->object, "");
2199 if (prepare_revision_walk(&revs))
2200 die(_("revision walk setup failed"));
2205 for (i = 0; i < old_nr; i++) {
2206 struct ref_array_item *item = array->items[i];
2207 struct commit *commit = item->commit;
2209 int is_merged = !!(commit->object.flags & UNINTERESTING);
2211 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2212 array->items[array->nr++] = array->items[i];
2214 free_array_item(item);
2217 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2218 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2223 * API for filtering a set of refs. Based on the type of refs the user
2224 * has requested, we iterate through those refs and apply filters
2225 * as per the given ref_filter structure and finally store the
2226 * filtered refs in the ref_array structure.
2228 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2230 struct ref_filter_cbdata ref_cbdata;
2232 unsigned int broken = 0;
2234 ref_cbdata.array = array;
2235 ref_cbdata.filter = filter;
2237 if (type & FILTER_REFS_INCLUDE_BROKEN)
2239 filter->kind = type & FILTER_REFS_KIND_MASK;
2241 init_contains_cache(&ref_cbdata.contains_cache);
2242 init_contains_cache(&ref_cbdata.no_contains_cache);
2244 /* Simple per-ref filtering */
2246 die("filter_refs: invalid type");
2249 * For common cases where we need only branches or remotes or tags,
2250 * we only iterate through those refs. If a mix of refs is needed,
2251 * we iterate over all refs and filter out required refs with the help
2252 * of filter_ref_kind().
2254 if (filter->kind == FILTER_REFS_BRANCHES)
2255 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2256 else if (filter->kind == FILTER_REFS_REMOTES)
2257 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2258 else if (filter->kind == FILTER_REFS_TAGS)
2259 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2260 else if (filter->kind & FILTER_REFS_ALL)
2261 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2262 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2263 head_ref(ref_filter_handler, &ref_cbdata);
2266 clear_contains_cache(&ref_cbdata.contains_cache);
2267 clear_contains_cache(&ref_cbdata.no_contains_cache);
2269 /* Filters that need revision walking */
2270 if (filter->merge_commit)
2271 do_merge_filter(&ref_cbdata);
2276 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2278 struct atom_value *va, *vb;
2280 cmp_type cmp_type = used_atom[s->atom].type;
2281 int (*cmp_fn)(const char *, const char *);
2282 struct strbuf err = STRBUF_INIT;
2284 if (get_ref_atom_value(a, s->atom, &va, &err))
2286 if (get_ref_atom_value(b, s->atom, &vb, &err))
2288 strbuf_release(&err);
2289 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2291 cmp = versioncmp(va->s, vb->s);
2292 else if (cmp_type == FIELD_STR)
2293 cmp = cmp_fn(va->s, vb->s);
2295 if (va->value < vb->value)
2297 else if (va->value == vb->value)
2298 cmp = cmp_fn(a->refname, b->refname);
2303 return (s->reverse) ? -cmp : cmp;
2306 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2308 struct ref_array_item *a = *((struct ref_array_item **)a_);
2309 struct ref_array_item *b = *((struct ref_array_item **)b_);
2310 struct ref_sorting *s;
2312 for (s = ref_sorting; s; s = s->next) {
2313 int cmp = cmp_ref_sorting(s, a, b);
2320 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2322 QSORT_S(array->items, array->nr, compare_refs, sorting);
2325 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2327 struct strbuf *s = &state->stack->output;
2329 while (*cp && (!ep || cp < ep)) {
2334 int ch = hex2chr(cp + 1);
2336 strbuf_addch(s, ch);
2342 strbuf_addch(s, *cp);
2347 int format_ref_array_item(struct ref_array_item *info,
2348 const struct ref_format *format,
2349 struct strbuf *final_buf,
2350 struct strbuf *error_buf)
2352 const char *cp, *sp, *ep;
2353 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2355 state.quote_style = format->quote_style;
2356 push_stack_element(&state.stack);
2358 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2359 struct atom_value *atomv;
2362 ep = strchr(sp, ')');
2364 append_literal(cp, sp, &state);
2365 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2366 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2367 atomv->handler(atomv, &state, error_buf)) {
2368 pop_stack_element(&state.stack);
2373 sp = cp + strlen(cp);
2374 append_literal(cp, sp, &state);
2376 if (format->need_color_reset_at_eol) {
2377 struct atom_value resetv;
2378 resetv.s = GIT_COLOR_RESET;
2379 if (append_atom(&resetv, &state, error_buf)) {
2380 pop_stack_element(&state.stack);
2384 if (state.stack->prev) {
2385 pop_stack_element(&state.stack);
2386 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2388 strbuf_addbuf(final_buf, &state.stack->output);
2389 pop_stack_element(&state.stack);
2393 void show_ref_array_item(struct ref_array_item *info,
2394 const struct ref_format *format)
2396 struct strbuf final_buf = STRBUF_INIT;
2397 struct strbuf error_buf = STRBUF_INIT;
2399 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2400 die("%s", error_buf.buf);
2401 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2402 strbuf_release(&error_buf);
2403 strbuf_release(&final_buf);
2407 void pretty_print_ref(const char *name, const struct object_id *oid,
2408 const struct ref_format *format)
2410 struct ref_array_item *ref_item;
2411 ref_item = new_ref_array_item(name, oid);
2412 ref_item->kind = ref_kind_from_refname(name);
2413 show_ref_array_item(ref_item, format);
2414 free_array_item(ref_item);
2417 static int parse_sorting_atom(const char *atom)
2420 * This parses an atom using a dummy ref_format, since we don't
2421 * actually care about the formatting details.
2423 struct ref_format dummy = REF_FORMAT_INIT;
2424 const char *end = atom + strlen(atom);
2425 struct strbuf err = STRBUF_INIT;
2426 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2429 strbuf_release(&err);
2433 /* If no sorting option is given, use refname to sort as default */
2434 struct ref_sorting *ref_default_sorting(void)
2436 static const char cstr_name[] = "refname";
2438 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2440 sorting->next = NULL;
2441 sorting->atom = parse_sorting_atom(cstr_name);
2445 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2447 struct ref_sorting *s;
2449 s = xcalloc(1, sizeof(*s));
2450 s->next = *sorting_tail;
2457 if (skip_prefix(arg, "version:", &arg) ||
2458 skip_prefix(arg, "v:", &arg))
2460 s->atom = parse_sorting_atom(arg);
2463 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2466 * NEEDSWORK: We should probably clear the list in this case, but we've
2467 * already munged the global used_atoms list, which would need to be
2470 BUG_ON_OPT_NEG(unset);
2472 parse_ref_sorting(opt->value, arg);
2476 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2478 struct ref_filter *rf = opt->value;
2479 struct object_id oid;
2480 int no_merged = starts_with(opt->long_name, "no");
2482 BUG_ON_OPT_NEG(unset);
2486 return error(_("option `%s' is incompatible with --merged"),
2489 return error(_("option `%s' is incompatible with --no-merged"),
2494 rf->merge = no_merged
2495 ? REF_FILTER_MERGED_OMIT
2496 : REF_FILTER_MERGED_INCLUDE;
2498 if (get_oid(arg, &oid))
2499 die(_("malformed object name %s"), arg);
2501 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2503 if (!rf->merge_commit)
2504 return error(_("option `%s' must point to a commit"), opt->long_name);