3 #include "parse-options.h"
6 #include "object-store.h"
7 #include "repository.h"
13 #include "ref-filter.h"
16 #include "git-compat-util.h"
19 #include "wt-status.h"
20 #include "commit-slab.h"
21 #include "commit-graph.h"
22 #include "commit-reach.h"
24 static struct ref_msg {
28 const char *ahead_behind;
30 /* Untranslated plumbing messages: */
37 void setup_ref_filter_porcelain_msg(void)
39 msgs.gone = _("gone");
40 msgs.ahead = _("ahead %d");
41 msgs.behind = _("behind %d");
42 msgs.ahead_behind = _("ahead %d, behind %d");
45 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
46 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
47 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
55 cmp_status cmp_status;
57 unsigned int then_atom_seen : 1,
59 condition_satisfied : 1;
63 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
67 static struct expand_data {
69 enum object_type type;
72 struct object_id delta_base_oid;
75 struct object_info info;
79 * An atom is a valid field atom listed below, possibly prefixed with
80 * a "*" to denote deref_tag().
82 * We parse given format string and sort specifiers, and make a list
83 * of properties that we need to extract out of objects. ref_array_item
84 * structure will hold an array of values extracted that can be
85 * indexed with the "atom number", which is an index into this
88 static struct used_atom {
93 char color[COLOR_MAXLEN];
97 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
99 struct refname_atom refname;
100 unsigned int nobracket : 1, push : 1, push_remote : 1;
103 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
104 struct process_trailer_options trailer_opts;
108 cmp_status cmp_status;
112 enum { O_FULL, O_LENGTH, O_SHORT } option;
115 struct refname_atom refname;
119 static int used_atom_cnt, need_tagged, need_symref;
122 * Expand string, append it to strbuf *sb, then return error code ret.
123 * Allow to save few lines of code.
125 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
129 strbuf_vaddf(sb, fmt, ap);
134 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
135 const char *color_value, struct strbuf *err)
138 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
139 if (color_parse(color_value, atom->u.color) < 0)
140 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
143 * We check this after we've parsed the color, which lets us complain
144 * about syntactically bogus color names even if they won't be used.
146 if (!want_color(format->use_color))
147 color_parse("", atom->u.color);
151 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
152 const char *name, struct strbuf *err)
155 atom->option = R_NORMAL;
156 else if (!strcmp(arg, "short"))
157 atom->option = R_SHORT;
158 else if (skip_prefix(arg, "lstrip=", &arg) ||
159 skip_prefix(arg, "strip=", &arg)) {
160 atom->option = R_LSTRIP;
161 if (strtol_i(arg, 10, &atom->lstrip))
162 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
163 } else if (skip_prefix(arg, "rstrip=", &arg)) {
164 atom->option = R_RSTRIP;
165 if (strtol_i(arg, 10, &atom->rstrip))
166 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
168 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
172 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
173 const char *arg, struct strbuf *err)
175 struct string_list params = STRING_LIST_INIT_DUP;
178 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
179 atom->u.remote_ref.push = 1;
182 atom->u.remote_ref.option = RR_REF;
183 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
184 arg, atom->name, err);
187 atom->u.remote_ref.nobracket = 0;
188 string_list_split(¶ms, arg, ',', -1);
190 for (i = 0; i < params.nr; i++) {
191 const char *s = params.items[i].string;
193 if (!strcmp(s, "track"))
194 atom->u.remote_ref.option = RR_TRACK;
195 else if (!strcmp(s, "trackshort"))
196 atom->u.remote_ref.option = RR_TRACKSHORT;
197 else if (!strcmp(s, "nobracket"))
198 atom->u.remote_ref.nobracket = 1;
199 else if (!strcmp(s, "remotename")) {
200 atom->u.remote_ref.option = RR_REMOTE_NAME;
201 atom->u.remote_ref.push_remote = 1;
202 } else if (!strcmp(s, "remoteref")) {
203 atom->u.remote_ref.option = RR_REMOTE_REF;
204 atom->u.remote_ref.push_remote = 1;
206 atom->u.remote_ref.option = RR_REF;
207 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
208 arg, atom->name, err)) {
209 string_list_clear(¶ms, 0);
215 string_list_clear(¶ms, 0);
219 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
220 const char *arg, struct strbuf *err)
223 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
224 if (*atom->name == '*')
225 oi_deref.info.typep = &oi_deref.type;
227 oi.info.typep = &oi.type;
231 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
232 const char *arg, struct strbuf *err)
235 return strbuf_addf_ret(err, -1, _("%%(objectsize) does not take arguments"));
236 if (*atom->name == '*')
237 oi_deref.info.sizep = &oi_deref.size;
239 oi.info.sizep = &oi.size;
243 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
244 const char *arg, struct strbuf *err)
247 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
248 atom->u.contents.option = C_BODY_DEP;
252 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
253 const char *arg, struct strbuf *err)
256 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
257 atom->u.contents.option = C_SUB;
261 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
262 const char *arg, struct strbuf *err)
264 struct string_list params = STRING_LIST_INIT_DUP;
268 string_list_split(¶ms, arg, ',', -1);
269 for (i = 0; i < params.nr; i++) {
270 const char *s = params.items[i].string;
271 if (!strcmp(s, "unfold"))
272 atom->u.contents.trailer_opts.unfold = 1;
273 else if (!strcmp(s, "only"))
274 atom->u.contents.trailer_opts.only_trailers = 1;
276 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
277 string_list_clear(¶ms, 0);
282 atom->u.contents.option = C_TRAILERS;
283 string_list_clear(¶ms, 0);
287 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
288 const char *arg, struct strbuf *err)
291 atom->u.contents.option = C_BARE;
292 else if (!strcmp(arg, "body"))
293 atom->u.contents.option = C_BODY;
294 else if (!strcmp(arg, "signature"))
295 atom->u.contents.option = C_SIG;
296 else if (!strcmp(arg, "subject"))
297 atom->u.contents.option = C_SUB;
298 else if (skip_prefix(arg, "trailers", &arg)) {
299 skip_prefix(arg, ":", &arg);
300 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
302 } else if (skip_prefix(arg, "lines=", &arg)) {
303 atom->u.contents.option = C_LINES;
304 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
305 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
307 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
311 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
312 const char *arg, struct strbuf *err)
315 atom->u.objectname.option = O_FULL;
316 else if (!strcmp(arg, "short"))
317 atom->u.objectname.option = O_SHORT;
318 else if (skip_prefix(arg, "short=", &arg)) {
319 atom->u.objectname.option = O_LENGTH;
320 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
321 atom->u.objectname.length == 0)
322 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
323 if (atom->u.objectname.length < MINIMUM_ABBREV)
324 atom->u.objectname.length = MINIMUM_ABBREV;
326 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
330 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
331 const char *arg, struct strbuf *err)
333 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
336 static align_type parse_align_position(const char *s)
338 if (!strcmp(s, "right"))
340 else if (!strcmp(s, "middle"))
342 else if (!strcmp(s, "left"))
347 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
348 const char *arg, struct strbuf *err)
350 struct align *align = &atom->u.align;
351 struct string_list params = STRING_LIST_INIT_DUP;
353 unsigned int width = ~0U;
356 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
358 align->position = ALIGN_LEFT;
360 string_list_split(¶ms, arg, ',', -1);
361 for (i = 0; i < params.nr; i++) {
362 const char *s = params.items[i].string;
365 if (skip_prefix(s, "position=", &s)) {
366 position = parse_align_position(s);
368 strbuf_addf(err, _("unrecognized position:%s"), s);
369 string_list_clear(¶ms, 0);
372 align->position = position;
373 } else if (skip_prefix(s, "width=", &s)) {
374 if (strtoul_ui(s, 10, &width)) {
375 strbuf_addf(err, _("unrecognized width:%s"), s);
376 string_list_clear(¶ms, 0);
379 } else if (!strtoul_ui(s, 10, &width))
381 else if ((position = parse_align_position(s)) >= 0)
382 align->position = position;
384 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
385 string_list_clear(¶ms, 0);
391 string_list_clear(¶ms, 0);
392 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
394 align->width = width;
395 string_list_clear(¶ms, 0);
399 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
400 const char *arg, struct strbuf *err)
403 atom->u.if_then_else.cmp_status = COMPARE_NONE;
405 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
406 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
407 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
408 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
410 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
414 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
415 const char *arg, struct strbuf *unused_err)
417 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
425 int (*parser)(const struct ref_format *format, struct used_atom *atom,
426 const char *arg, struct strbuf *err);
428 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
429 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
430 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
431 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
432 { "tree", SOURCE_OBJ },
433 { "parent", SOURCE_OBJ },
434 { "numparent", SOURCE_OBJ, FIELD_ULONG },
435 { "object", SOURCE_OBJ },
436 { "type", SOURCE_OBJ },
437 { "tag", SOURCE_OBJ },
438 { "author", SOURCE_OBJ },
439 { "authorname", SOURCE_OBJ },
440 { "authoremail", SOURCE_OBJ },
441 { "authordate", SOURCE_OBJ, FIELD_TIME },
442 { "committer", SOURCE_OBJ },
443 { "committername", SOURCE_OBJ },
444 { "committeremail", SOURCE_OBJ },
445 { "committerdate", SOURCE_OBJ, FIELD_TIME },
446 { "tagger", SOURCE_OBJ },
447 { "taggername", SOURCE_OBJ },
448 { "taggeremail", SOURCE_OBJ },
449 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
450 { "creator", SOURCE_OBJ },
451 { "creatordate", SOURCE_OBJ, FIELD_TIME },
452 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
453 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
454 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
455 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
456 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
457 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
458 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
459 { "flag", SOURCE_NONE },
460 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
461 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
462 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
463 { "end", SOURCE_NONE },
464 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
465 { "then", SOURCE_NONE },
466 { "else", SOURCE_NONE },
469 #define REF_FORMATTING_STATE_INIT { 0, NULL }
471 struct ref_formatting_stack {
472 struct ref_formatting_stack *prev;
473 struct strbuf output;
474 void (*at_end)(struct ref_formatting_stack **stack);
478 struct ref_formatting_state {
480 struct ref_formatting_stack *stack;
485 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
487 uintmax_t value; /* used for sorting when not FIELD_STR */
488 struct used_atom *atom;
492 * Used to parse format string and sort specifiers
494 static int parse_ref_filter_atom(const struct ref_format *format,
495 const char *atom, const char *ep,
503 if (*sp == '*' && sp < ep)
506 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
507 (int)(ep-atom), atom);
509 /* Do we have the atom already used elsewhere? */
510 for (i = 0; i < used_atom_cnt; i++) {
511 int len = strlen(used_atom[i].name);
512 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
517 * If the atom name has a colon, strip it and everything after
518 * it off - it specifies the format for this entry, and
519 * shouldn't be used for checking against the valid_atom
522 arg = memchr(sp, ':', ep - sp);
523 atom_len = (arg ? arg : ep) - sp;
525 /* Is the atom a valid one? */
526 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
527 int len = strlen(valid_atom[i].name);
528 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
532 if (ARRAY_SIZE(valid_atom) <= i)
533 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
534 (int)(ep-atom), atom);
536 /* Add it in, including the deref prefix */
539 REALLOC_ARRAY(used_atom, used_atom_cnt);
540 used_atom[at].name = xmemdupz(atom, ep - atom);
541 used_atom[at].type = valid_atom[i].cmp_type;
542 used_atom[at].source = valid_atom[i].source;
543 if (used_atom[at].source == SOURCE_OBJ) {
545 oi_deref.info.contentp = &oi_deref.content;
547 oi.info.contentp = &oi.content;
550 arg = used_atom[at].name + (arg - atom) + 1;
553 * Treat empty sub-arguments list as NULL (i.e.,
554 * "%(atom:)" is equivalent to "%(atom)").
559 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
560 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
564 if (!strcmp(valid_atom[i].name, "symref"))
569 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
571 switch (quote_style) {
573 strbuf_addstr(s, str);
576 sq_quote_buf(s, str);
579 perl_quote_buf(s, str);
582 python_quote_buf(s, str);
585 tcl_quote_buf(s, str);
590 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
591 struct strbuf *unused_err)
594 * Quote formatting is only done when the stack has a single
595 * element. Otherwise quote formatting is done on the
596 * element's entire output strbuf when the %(end) atom is
599 if (!state->stack->prev)
600 quote_formatting(&state->stack->output, v->s, state->quote_style);
602 strbuf_addstr(&state->stack->output, v->s);
606 static void push_stack_element(struct ref_formatting_stack **stack)
608 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
610 strbuf_init(&s->output, 0);
615 static void pop_stack_element(struct ref_formatting_stack **stack)
617 struct ref_formatting_stack *current = *stack;
618 struct ref_formatting_stack *prev = current->prev;
621 strbuf_addbuf(&prev->output, ¤t->output);
622 strbuf_release(¤t->output);
627 static void end_align_handler(struct ref_formatting_stack **stack)
629 struct ref_formatting_stack *cur = *stack;
630 struct align *align = (struct align *)cur->at_end_data;
631 struct strbuf s = STRBUF_INIT;
633 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
634 strbuf_swap(&cur->output, &s);
638 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
639 struct strbuf *unused_err)
641 struct ref_formatting_stack *new_stack;
643 push_stack_element(&state->stack);
644 new_stack = state->stack;
645 new_stack->at_end = end_align_handler;
646 new_stack->at_end_data = &atomv->atom->u.align;
650 static void if_then_else_handler(struct ref_formatting_stack **stack)
652 struct ref_formatting_stack *cur = *stack;
653 struct ref_formatting_stack *prev = cur->prev;
654 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
656 if (!if_then_else->then_atom_seen)
657 die(_("format: %%(if) atom used without a %%(then) atom"));
659 if (if_then_else->else_atom_seen) {
661 * There is an %(else) atom: we need to drop one state from the
662 * stack, either the %(else) branch if the condition is satisfied, or
663 * the %(then) branch if it isn't.
665 if (if_then_else->condition_satisfied) {
666 strbuf_reset(&cur->output);
667 pop_stack_element(&cur);
669 strbuf_swap(&cur->output, &prev->output);
670 strbuf_reset(&cur->output);
671 pop_stack_element(&cur);
673 } else if (!if_then_else->condition_satisfied) {
675 * No %(else) atom: just drop the %(then) branch if the
676 * condition is not satisfied.
678 strbuf_reset(&cur->output);
685 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
686 struct strbuf *unused_err)
688 struct ref_formatting_stack *new_stack;
689 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
691 if_then_else->str = atomv->atom->u.if_then_else.str;
692 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
694 push_stack_element(&state->stack);
695 new_stack = state->stack;
696 new_stack->at_end = if_then_else_handler;
697 new_stack->at_end_data = if_then_else;
701 static int is_empty(const char *s)
711 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
714 struct ref_formatting_stack *cur = state->stack;
715 struct if_then_else *if_then_else = NULL;
717 if (cur->at_end == if_then_else_handler)
718 if_then_else = (struct if_then_else *)cur->at_end_data;
720 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
721 if (if_then_else->then_atom_seen)
722 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
723 if (if_then_else->else_atom_seen)
724 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
725 if_then_else->then_atom_seen = 1;
727 * If the 'equals' or 'notequals' attribute is used then
728 * perform the required comparison. If not, only non-empty
729 * strings satisfy the 'if' condition.
731 if (if_then_else->cmp_status == COMPARE_EQUAL) {
732 if (!strcmp(if_then_else->str, cur->output.buf))
733 if_then_else->condition_satisfied = 1;
734 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
735 if (strcmp(if_then_else->str, cur->output.buf))
736 if_then_else->condition_satisfied = 1;
737 } else if (cur->output.len && !is_empty(cur->output.buf))
738 if_then_else->condition_satisfied = 1;
739 strbuf_reset(&cur->output);
743 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
746 struct ref_formatting_stack *prev = state->stack;
747 struct if_then_else *if_then_else = NULL;
749 if (prev->at_end == if_then_else_handler)
750 if_then_else = (struct if_then_else *)prev->at_end_data;
752 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
753 if (!if_then_else->then_atom_seen)
754 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
755 if (if_then_else->else_atom_seen)
756 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
757 if_then_else->else_atom_seen = 1;
758 push_stack_element(&state->stack);
759 state->stack->at_end_data = prev->at_end_data;
760 state->stack->at_end = prev->at_end;
764 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
767 struct ref_formatting_stack *current = state->stack;
768 struct strbuf s = STRBUF_INIT;
770 if (!current->at_end)
771 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
772 current->at_end(&state->stack);
774 /* Stack may have been popped within at_end(), hence reset the current pointer */
775 current = state->stack;
778 * Perform quote formatting when the stack element is that of
779 * a supporting atom. If nested then perform quote formatting
780 * only on the topmost supporting atom.
782 if (!current->prev->prev) {
783 quote_formatting(&s, current->output.buf, state->quote_style);
784 strbuf_swap(¤t->output, &s);
787 pop_stack_element(&state->stack);
792 * In a format string, find the next occurrence of %(atom).
794 static const char *find_next(const char *cp)
799 * %( is the start of an atom;
800 * %% is a quoted per-cent.
804 else if (cp[1] == '%')
805 cp++; /* skip over two % */
806 /* otherwise this is a singleton, literal % */
814 * Make sure the format string is well formed, and parse out
817 int verify_ref_format(struct ref_format *format)
821 format->need_color_reset_at_eol = 0;
822 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
823 struct strbuf err = STRBUF_INIT;
824 const char *color, *ep = strchr(sp, ')');
828 return error(_("malformed format string %s"), sp);
829 /* sp points at "%(" and ep points at the closing ")" */
830 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
835 if (skip_prefix(used_atom[at].name, "color:", &color))
836 format->need_color_reset_at_eol = !!strcmp(color, "reset");
837 strbuf_release(&err);
839 if (format->need_color_reset_at_eol && !want_color(format->use_color))
840 format->need_color_reset_at_eol = 0;
844 static int grab_objectname(const char *name, const struct object_id *oid,
845 struct atom_value *v, struct used_atom *atom)
847 if (starts_with(name, "objectname")) {
848 if (atom->u.objectname.option == O_SHORT) {
849 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
851 } else if (atom->u.objectname.option == O_FULL) {
852 v->s = xstrdup(oid_to_hex(oid));
854 } else if (atom->u.objectname.option == O_LENGTH) {
855 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
858 BUG("unknown %%(objectname) option");
863 /* See grab_values */
864 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
868 for (i = 0; i < used_atom_cnt; i++) {
869 const char *name = used_atom[i].name;
870 struct atom_value *v = &val[i];
871 if (!!deref != (*name == '*'))
875 if (!strcmp(name, "objecttype"))
876 v->s = type_name(oi->type);
877 else if (!strcmp(name, "objectsize")) {
879 v->s = xstrfmt("%lu", oi->size);
882 grab_objectname(name, &oi->oid, v, &used_atom[i]);
886 /* See grab_values */
887 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
890 struct tag *tag = (struct tag *) obj;
892 for (i = 0; i < used_atom_cnt; i++) {
893 const char *name = used_atom[i].name;
894 struct atom_value *v = &val[i];
895 if (!!deref != (*name == '*'))
899 if (!strcmp(name, "tag"))
901 else if (!strcmp(name, "type") && tag->tagged)
902 v->s = type_name(tag->tagged->type);
903 else if (!strcmp(name, "object") && tag->tagged)
904 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
908 /* See grab_values */
909 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
912 struct commit *commit = (struct commit *) obj;
914 for (i = 0; i < used_atom_cnt; i++) {
915 const char *name = used_atom[i].name;
916 struct atom_value *v = &val[i];
917 if (!!deref != (*name == '*'))
921 if (!strcmp(name, "tree")) {
922 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
924 else if (!strcmp(name, "numparent")) {
925 v->value = commit_list_count(commit->parents);
926 v->s = xstrfmt("%lu", (unsigned long)v->value);
928 else if (!strcmp(name, "parent")) {
929 struct commit_list *parents;
930 struct strbuf s = STRBUF_INIT;
931 for (parents = commit->parents; parents; parents = parents->next) {
932 struct commit *parent = parents->item;
933 if (parents != commit->parents)
934 strbuf_addch(&s, ' ');
935 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
937 v->s = strbuf_detach(&s, NULL);
942 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
946 if (!strncmp(buf, who, wholen) &&
948 return buf + wholen + 1;
949 eol = strchr(buf, '\n');
954 return ""; /* end of header */
960 static const char *copy_line(const char *buf)
962 const char *eol = strchrnul(buf, '\n');
963 return xmemdupz(buf, eol - buf);
966 static const char *copy_name(const char *buf)
969 for (cp = buf; *cp && *cp != '\n'; cp++) {
970 if (!strncmp(cp, " <", 2))
971 return xmemdupz(buf, cp - buf);
976 static const char *copy_email(const char *buf)
978 const char *email = strchr(buf, '<');
982 eoemail = strchr(email, '>');
985 return xmemdupz(email, eoemail + 1 - email);
988 static char *copy_subject(const char *buf, unsigned long len)
990 char *r = xmemdupz(buf, len);
993 for (i = 0; i < len; i++)
1000 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1002 const char *eoemail = strstr(buf, "> ");
1004 timestamp_t timestamp;
1006 struct date_mode date_mode = { DATE_NORMAL };
1007 const char *formatp;
1010 * We got here because atomname ends in "date" or "date<something>";
1011 * it's not possible that <something> is not ":<format>" because
1012 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1013 * ":" means no format is specified, and use the default.
1015 formatp = strchr(atomname, ':');
1016 if (formatp != NULL) {
1018 parse_date_format(formatp, &date_mode);
1023 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1024 if (timestamp == TIME_MAX)
1026 tz = strtol(zone, NULL, 10);
1027 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1029 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1030 v->value = timestamp;
1037 /* See grab_values */
1038 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1041 int wholen = strlen(who);
1042 const char *wholine = NULL;
1044 for (i = 0; i < used_atom_cnt; i++) {
1045 const char *name = used_atom[i].name;
1046 struct atom_value *v = &val[i];
1047 if (!!deref != (*name == '*'))
1051 if (strncmp(who, name, wholen))
1053 if (name[wholen] != 0 &&
1054 strcmp(name + wholen, "name") &&
1055 strcmp(name + wholen, "email") &&
1056 !starts_with(name + wholen, "date"))
1059 wholine = find_wholine(who, wholen, buf, sz);
1061 return; /* no point looking for it */
1062 if (name[wholen] == 0)
1063 v->s = copy_line(wholine);
1064 else if (!strcmp(name + wholen, "name"))
1065 v->s = copy_name(wholine);
1066 else if (!strcmp(name + wholen, "email"))
1067 v->s = copy_email(wholine);
1068 else if (starts_with(name + wholen, "date"))
1069 grab_date(wholine, v, name);
1073 * For a tag or a commit object, if "creator" or "creatordate" is
1074 * requested, do something special.
1076 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1077 return; /* "author" for commit object is not wanted */
1079 wholine = find_wholine(who, wholen, buf, sz);
1082 for (i = 0; i < used_atom_cnt; i++) {
1083 const char *name = used_atom[i].name;
1084 struct atom_value *v = &val[i];
1085 if (!!deref != (*name == '*'))
1090 if (starts_with(name, "creatordate"))
1091 grab_date(wholine, v, name);
1092 else if (!strcmp(name, "creator"))
1093 v->s = copy_line(wholine);
1097 static void find_subpos(const char *buf, unsigned long sz,
1098 const char **sub, unsigned long *sublen,
1099 const char **body, unsigned long *bodylen,
1100 unsigned long *nonsiglen,
1101 const char **sig, unsigned long *siglen)
1104 /* skip past header until we hit empty line */
1105 while (*buf && *buf != '\n') {
1106 eol = strchrnul(buf, '\n');
1111 /* skip any empty lines */
1112 while (*buf == '\n')
1115 /* parse signature first; we might not even have a subject line */
1116 *sig = buf + parse_signature(buf, strlen(buf));
1117 *siglen = strlen(*sig);
1119 /* subject is first non-empty line */
1121 /* subject goes to first empty line */
1122 while (buf < *sig && *buf && *buf != '\n') {
1123 eol = strchrnul(buf, '\n');
1128 *sublen = buf - *sub;
1129 /* drop trailing newline, if present */
1130 if (*sublen && (*sub)[*sublen - 1] == '\n')
1133 /* skip any empty lines */
1134 while (*buf == '\n')
1137 *bodylen = strlen(buf);
1138 *nonsiglen = *sig - buf;
1142 * If 'lines' is greater than 0, append that many lines from the given
1143 * 'buf' of length 'size' to the given strbuf.
1145 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1148 const char *sp, *eol;
1153 for (i = 0; i < lines && sp < buf + size; i++) {
1155 strbuf_addstr(out, "\n ");
1156 eol = memchr(sp, '\n', size - (sp - buf));
1157 len = eol ? eol - sp : size - (sp - buf);
1158 strbuf_add(out, sp, len);
1165 /* See grab_values */
1166 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1169 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1170 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1172 for (i = 0; i < used_atom_cnt; i++) {
1173 struct used_atom *atom = &used_atom[i];
1174 const char *name = atom->name;
1175 struct atom_value *v = &val[i];
1176 if (!!deref != (*name == '*'))
1180 if (strcmp(name, "subject") &&
1181 strcmp(name, "body") &&
1182 !starts_with(name, "trailers") &&
1183 !starts_with(name, "contents"))
1186 find_subpos(buf, sz,
1188 &bodypos, &bodylen, &nonsiglen,
1191 if (atom->u.contents.option == C_SUB)
1192 v->s = copy_subject(subpos, sublen);
1193 else if (atom->u.contents.option == C_BODY_DEP)
1194 v->s = xmemdupz(bodypos, bodylen);
1195 else if (atom->u.contents.option == C_BODY)
1196 v->s = xmemdupz(bodypos, nonsiglen);
1197 else if (atom->u.contents.option == C_SIG)
1198 v->s = xmemdupz(sigpos, siglen);
1199 else if (atom->u.contents.option == C_LINES) {
1200 struct strbuf s = STRBUF_INIT;
1201 const char *contents_end = bodylen + bodypos - siglen;
1203 /* Size is the length of the message after removing the signature */
1204 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1205 v->s = strbuf_detach(&s, NULL);
1206 } else if (atom->u.contents.option == C_TRAILERS) {
1207 struct strbuf s = STRBUF_INIT;
1209 /* Format the trailer info according to the trailer_opts given */
1210 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1212 v->s = strbuf_detach(&s, NULL);
1213 } else if (atom->u.contents.option == C_BARE)
1214 v->s = xstrdup(subpos);
1219 * We want to have empty print-string for field requests
1220 * that do not apply (e.g. "authordate" for a tag object)
1222 static void fill_missing_values(struct atom_value *val)
1225 for (i = 0; i < used_atom_cnt; i++) {
1226 struct atom_value *v = &val[i];
1233 * val is a list of atom_value to hold returned values. Extract
1234 * the values for atoms in used_atom array out of (obj, buf, sz).
1235 * when deref is false, (obj, buf, sz) is the object that is
1236 * pointed at by the ref itself; otherwise it is the object the
1237 * ref (which is a tag) refers to.
1239 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1241 switch (obj->type) {
1243 grab_tag_values(val, deref, obj, buf, sz);
1244 grab_sub_body_contents(val, deref, obj, buf, sz);
1245 grab_person("tagger", val, deref, obj, buf, sz);
1248 grab_commit_values(val, deref, obj, buf, sz);
1249 grab_sub_body_contents(val, deref, obj, buf, sz);
1250 grab_person("author", val, deref, obj, buf, sz);
1251 grab_person("committer", val, deref, obj, buf, sz);
1254 /* grab_tree_values(val, deref, obj, buf, sz); */
1257 /* grab_blob_values(val, deref, obj, buf, sz); */
1260 die("Eh? Object of type %d?", obj->type);
1264 static inline char *copy_advance(char *dst, const char *src)
1271 static const char *lstrip_ref_components(const char *refname, int len)
1273 long remaining = len;
1274 const char *start = refname;
1278 const char *p = refname;
1280 /* Find total no of '/' separated path-components */
1281 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1284 * The number of components we need to strip is now
1285 * the total minus the components to be left (Plus one
1286 * because we count the number of '/', but the number
1287 * of components is one more than the no of '/').
1289 remaining = i + len + 1;
1292 while (remaining > 0) {
1305 static const char *rstrip_ref_components(const char *refname, int len)
1307 long remaining = len;
1308 char *start = xstrdup(refname);
1312 const char *p = refname;
1314 /* Find total no of '/' separated path-components */
1315 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1318 * The number of components we need to strip is now
1319 * the total minus the components to be left (Plus one
1320 * because we count the number of '/', but the number
1321 * of components is one more than the no of '/').
1323 remaining = i + len + 1;
1326 while (remaining-- > 0) {
1327 char *p = strrchr(start, '/');
1336 static const char *show_ref(struct refname_atom *atom, const char *refname)
1338 if (atom->option == R_SHORT)
1339 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1340 else if (atom->option == R_LSTRIP)
1341 return lstrip_ref_components(refname, atom->lstrip);
1342 else if (atom->option == R_RSTRIP)
1343 return rstrip_ref_components(refname, atom->rstrip);
1348 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1349 struct branch *branch, const char **s)
1351 int num_ours, num_theirs;
1352 if (atom->u.remote_ref.option == RR_REF)
1353 *s = show_ref(&atom->u.remote_ref.refname, refname);
1354 else if (atom->u.remote_ref.option == RR_TRACK) {
1355 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1356 NULL, AHEAD_BEHIND_FULL) < 0) {
1357 *s = xstrdup(msgs.gone);
1358 } else if (!num_ours && !num_theirs)
1361 *s = xstrfmt(msgs.behind, num_theirs);
1362 else if (!num_theirs)
1363 *s = xstrfmt(msgs.ahead, num_ours);
1365 *s = xstrfmt(msgs.ahead_behind,
1366 num_ours, num_theirs);
1367 if (!atom->u.remote_ref.nobracket && *s[0]) {
1368 const char *to_free = *s;
1369 *s = xstrfmt("[%s]", *s);
1370 free((void *)to_free);
1372 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1373 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1374 NULL, AHEAD_BEHIND_FULL) < 0)
1377 if (!num_ours && !num_theirs)
1381 else if (!num_theirs)
1385 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1387 const char *remote = atom->u.remote_ref.push ?
1388 pushremote_for_branch(branch, &explicit) :
1389 remote_for_branch(branch, &explicit);
1391 *s = xstrdup(remote);
1394 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1398 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1401 *s = xstrdup(merge);
1405 BUG("unhandled RR_* enum");
1408 char *get_head_description(void)
1410 struct strbuf desc = STRBUF_INIT;
1411 struct wt_status_state state;
1412 memset(&state, 0, sizeof(state));
1413 wt_status_get_state(&state, 1);
1414 if (state.rebase_in_progress ||
1415 state.rebase_interactive_in_progress) {
1417 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1420 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1421 state.detached_from);
1422 } else if (state.bisect_in_progress)
1423 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1425 else if (state.detached_from) {
1426 if (state.detached_at)
1428 * TRANSLATORS: make sure this matches "HEAD
1429 * detached at " in wt-status.c
1431 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1432 state.detached_from);
1435 * TRANSLATORS: make sure this matches "HEAD
1436 * detached from " in wt-status.c
1438 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1439 state.detached_from);
1442 strbuf_addstr(&desc, _("(no branch)"));
1445 free(state.detached_from);
1446 return strbuf_detach(&desc, NULL);
1449 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1454 return show_ref(&atom->u.refname, ref->symref);
1457 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1459 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1460 return get_head_description();
1461 return show_ref(&atom->u.refname, ref->refname);
1464 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1465 struct expand_data *oi, struct strbuf *err)
1467 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1469 if (oi->info.contentp) {
1470 /* We need to know that to use parse_object_buffer properly */
1471 oi->info.sizep = &oi->size;
1472 oi->info.typep = &oi->type;
1474 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1475 OBJECT_INFO_LOOKUP_REPLACE))
1476 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1477 oid_to_hex(&oi->oid), ref->refname);
1479 if (oi->info.contentp) {
1480 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1484 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1485 oid_to_hex(&oi->oid), ref->refname);
1487 grab_values(ref->value, deref, *obj, oi->content, oi->size);
1490 grab_common_values(ref->value, deref, oi);
1497 * Parse the object referred by ref, and grab needed value.
1499 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1503 struct object_info empty = OBJECT_INFO_INIT;
1505 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1507 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1508 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1514 /* Fill in specials first */
1515 for (i = 0; i < used_atom_cnt; i++) {
1516 struct used_atom *atom = &used_atom[i];
1517 const char *name = used_atom[i].name;
1518 struct atom_value *v = &ref->value[i];
1520 const char *refname;
1521 struct branch *branch = NULL;
1523 v->handler = append_atom;
1531 if (starts_with(name, "refname"))
1532 refname = get_refname(atom, ref);
1533 else if (starts_with(name, "symref"))
1534 refname = get_symref(atom, ref);
1535 else if (starts_with(name, "upstream")) {
1536 const char *branch_name;
1538 /* only local branches may have an upstream */
1539 if (!skip_prefix(ref->refname, "refs/heads/",
1542 branch = branch_get(branch_name);
1544 refname = branch_get_upstream(branch, NULL);
1546 fill_remote_ref_details(atom, refname, branch, &v->s);
1548 } else if (atom->u.remote_ref.push) {
1549 const char *branch_name;
1551 if (!skip_prefix(ref->refname, "refs/heads/",
1554 branch = branch_get(branch_name);
1556 if (atom->u.remote_ref.push_remote)
1559 refname = branch_get_push(branch, NULL);
1563 fill_remote_ref_details(atom, refname, branch, &v->s);
1565 } else if (starts_with(name, "color:")) {
1566 v->s = atom->u.color;
1568 } else if (!strcmp(name, "flag")) {
1569 char buf[256], *cp = buf;
1570 if (ref->flag & REF_ISSYMREF)
1571 cp = copy_advance(cp, ",symref");
1572 if (ref->flag & REF_ISPACKED)
1573 cp = copy_advance(cp, ",packed");
1578 v->s = xstrdup(buf + 1);
1581 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1583 } else if (!strcmp(name, "HEAD")) {
1584 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1589 } else if (starts_with(name, "align")) {
1590 v->handler = align_atom_handler;
1593 } else if (!strcmp(name, "end")) {
1594 v->handler = end_atom_handler;
1597 } else if (starts_with(name, "if")) {
1600 if (skip_prefix(name, "if:", &s))
1602 v->handler = if_atom_handler;
1604 } else if (!strcmp(name, "then")) {
1605 v->handler = then_atom_handler;
1608 } else if (!strcmp(name, "else")) {
1609 v->handler = else_atom_handler;
1618 v->s = xstrfmt("%s^{}", refname);
1621 for (i = 0; i < used_atom_cnt; i++) {
1622 struct atom_value *v = &ref->value[i];
1623 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1624 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1625 oid_to_hex(&ref->objectname), ref->refname);
1629 oi.info.contentp = &oi.content;
1630 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1631 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1635 oi.oid = ref->objectname;
1636 if (get_object(ref, 0, &obj, &oi, err))
1640 * If there is no atom that wants to know about tagged
1641 * object, we are done.
1643 if (!need_tagged || (obj->type != OBJ_TAG))
1647 * If it is a tag object, see if we use a value that derefs
1648 * the object, and if we do grab the object it refers to.
1650 oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1653 * NEEDSWORK: This derefs tag only once, which
1654 * is good to deal with chains of trust, but
1655 * is not consistent with what deref_tag() does
1656 * which peels the onion to the core.
1658 return get_object(ref, 1, &obj, &oi_deref, err);
1662 * Given a ref, return the value for the atom. This lazily gets value
1663 * out of the object by calling populate value.
1665 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1666 struct atom_value **v, struct strbuf *err)
1669 if (populate_value(ref, err))
1671 fill_missing_values(ref->value);
1673 *v = &ref->value[atom];
1678 * Return 1 if the refname matches one of the patterns, otherwise 0.
1679 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1680 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1681 * matches "refs/heads/mas*", too).
1683 static int match_pattern(const struct ref_filter *filter, const char *refname)
1685 const char **patterns = filter->name_patterns;
1688 if (filter->ignore_case)
1689 flags |= WM_CASEFOLD;
1692 * When no '--format' option is given we need to skip the prefix
1693 * for matching refs of tags and branches.
1695 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1696 skip_prefix(refname, "refs/heads/", &refname) ||
1697 skip_prefix(refname, "refs/remotes/", &refname) ||
1698 skip_prefix(refname, "refs/", &refname));
1700 for (; *patterns; patterns++) {
1701 if (!wildmatch(*patterns, refname, flags))
1708 * Return 1 if the refname matches one of the patterns, otherwise 0.
1709 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1710 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1711 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1713 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1715 const char **pattern = filter->name_patterns;
1716 int namelen = strlen(refname);
1717 unsigned flags = WM_PATHNAME;
1719 if (filter->ignore_case)
1720 flags |= WM_CASEFOLD;
1722 for (; *pattern; pattern++) {
1723 const char *p = *pattern;
1724 int plen = strlen(p);
1726 if ((plen <= namelen) &&
1727 !strncmp(refname, p, plen) &&
1728 (refname[plen] == '\0' ||
1729 refname[plen] == '/' ||
1732 if (!wildmatch(p, refname, flags))
1738 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1739 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1741 if (!*filter->name_patterns)
1742 return 1; /* No pattern always matches */
1743 if (filter->match_as_path)
1744 return match_name_as_path(filter, refname);
1745 return match_pattern(filter, refname);
1749 * Find the longest prefix of pattern we can pass to
1750 * `for_each_fullref_in()`, namely the part of pattern preceding the
1751 * first glob character. (Note that `for_each_fullref_in()` is
1752 * perfectly happy working with a prefix that doesn't end at a
1753 * pathname component boundary.)
1755 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1759 for (p = pattern; *p && !is_glob_special(*p); p++)
1762 strbuf_add(out, pattern, p - pattern);
1766 * This is the same as for_each_fullref_in(), but it tries to iterate
1767 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1768 * pattern match, so the callback still has to match each ref individually.
1770 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1775 struct strbuf prefix = STRBUF_INIT;
1778 if (!filter->match_as_path) {
1780 * in this case, the patterns are applied after
1781 * prefixes like "refs/heads/" etc. are stripped off,
1782 * so we have to look at everything:
1784 return for_each_fullref_in("", cb, cb_data, broken);
1787 if (filter->ignore_case) {
1789 * we can't handle case-insensitive comparisons,
1790 * so just return everything and let the caller
1793 return for_each_fullref_in("", cb, cb_data, broken);
1796 if (!filter->name_patterns[0]) {
1797 /* no patterns; we have to look at everything */
1798 return for_each_fullref_in("", cb, cb_data, broken);
1801 if (filter->name_patterns[1]) {
1803 * multiple patterns; in theory this could still work as long
1804 * as the patterns are disjoint. We'd just make multiple calls
1805 * to for_each_ref(). But if they're not disjoint, we'd end up
1806 * reporting the same ref multiple times. So let's punt on that
1809 return for_each_fullref_in("", cb, cb_data, broken);
1812 find_longest_prefix(&prefix, filter->name_patterns[0]);
1814 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1815 strbuf_release(&prefix);
1820 * Given a ref (sha1, refname), check if the ref belongs to the array
1821 * of sha1s. If the given ref is a tag, check if the given tag points
1822 * at one of the sha1s in the given sha1 array.
1823 * the given sha1_array.
1825 * 1. Only a single level of inderection is obtained, we might want to
1826 * change this to account for multiple levels (e.g. annotated tags
1827 * pointing to annotated tags pointing to a commit.)
1828 * 2. As the refs are cached we might know what refname peels to without
1829 * the need to parse the object via parse_object(). peel_ref() might be a
1830 * more efficient alternative to obtain the pointee.
1832 static const struct object_id *match_points_at(struct oid_array *points_at,
1833 const struct object_id *oid,
1834 const char *refname)
1836 const struct object_id *tagged_oid = NULL;
1839 if (oid_array_lookup(points_at, oid) >= 0)
1841 obj = parse_object(the_repository, oid);
1843 die(_("malformed object at '%s'"), refname);
1844 if (obj->type == OBJ_TAG)
1845 tagged_oid = &((struct tag *)obj)->tagged->oid;
1846 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1852 * Allocate space for a new ref_array_item and copy the name and oid to it.
1854 * Callers can then fill in other struct members at their leisure.
1856 static struct ref_array_item *new_ref_array_item(const char *refname,
1857 const struct object_id *oid)
1859 struct ref_array_item *ref;
1861 FLEX_ALLOC_STR(ref, refname, refname);
1862 oidcpy(&ref->objectname, oid);
1867 struct ref_array_item *ref_array_push(struct ref_array *array,
1868 const char *refname,
1869 const struct object_id *oid)
1871 struct ref_array_item *ref = new_ref_array_item(refname, oid);
1873 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1874 array->items[array->nr++] = ref;
1879 static int ref_kind_from_refname(const char *refname)
1887 { "refs/heads/" , FILTER_REFS_BRANCHES },
1888 { "refs/remotes/" , FILTER_REFS_REMOTES },
1889 { "refs/tags/", FILTER_REFS_TAGS}
1892 if (!strcmp(refname, "HEAD"))
1893 return FILTER_REFS_DETACHED_HEAD;
1895 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1896 if (starts_with(refname, ref_kind[i].prefix))
1897 return ref_kind[i].kind;
1900 return FILTER_REFS_OTHERS;
1903 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1905 if (filter->kind == FILTER_REFS_BRANCHES ||
1906 filter->kind == FILTER_REFS_REMOTES ||
1907 filter->kind == FILTER_REFS_TAGS)
1908 return filter->kind;
1909 return ref_kind_from_refname(refname);
1912 struct ref_filter_cbdata {
1913 struct ref_array *array;
1914 struct ref_filter *filter;
1915 struct contains_cache contains_cache;
1916 struct contains_cache no_contains_cache;
1920 * A call-back given to for_each_ref(). Filter refs and keep them for
1921 * later object processing.
1923 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1925 struct ref_filter_cbdata *ref_cbdata = cb_data;
1926 struct ref_filter *filter = ref_cbdata->filter;
1927 struct ref_array_item *ref;
1928 struct commit *commit = NULL;
1931 if (flag & REF_BAD_NAME) {
1932 warning(_("ignoring ref with broken name %s"), refname);
1936 if (flag & REF_ISBROKEN) {
1937 warning(_("ignoring broken ref %s"), refname);
1941 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1942 kind = filter_ref_kind(filter, refname);
1943 if (!(kind & filter->kind))
1946 if (!filter_pattern_match(filter, refname))
1949 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1953 * A merge filter is applied on refs pointing to commits. Hence
1954 * obtain the commit using the 'oid' available and discard all
1955 * non-commits early. The actual filtering is done later.
1957 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1958 commit = lookup_commit_reference_gently(the_repository, oid,
1962 /* We perform the filtering for the '--contains' option... */
1963 if (filter->with_commit &&
1964 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1966 /* ...or for the `--no-contains' option */
1967 if (filter->no_commit &&
1968 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1973 * We do not open the object yet; sort may only need refname
1974 * to do its job and the resulting list may yet to be pruned
1975 * by maxcount logic.
1977 ref = ref_array_push(ref_cbdata->array, refname, oid);
1978 ref->commit = commit;
1985 /* Free memory allocated for a ref_array_item */
1986 static void free_array_item(struct ref_array_item *item)
1988 free((char *)item->symref);
1992 /* Free all memory allocated for ref_array */
1993 void ref_array_clear(struct ref_array *array)
1997 for (i = 0; i < array->nr; i++)
1998 free_array_item(array->items[i]);
1999 FREE_AND_NULL(array->items);
2000 array->nr = array->alloc = 0;
2003 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2005 struct rev_info revs;
2007 struct ref_filter *filter = ref_cbdata->filter;
2008 struct ref_array *array = ref_cbdata->array;
2009 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2011 init_revisions(&revs, NULL);
2013 for (i = 0; i < array->nr; i++) {
2014 struct ref_array_item *item = array->items[i];
2015 add_pending_object(&revs, &item->commit->object, item->refname);
2016 to_clear[i] = item->commit;
2019 filter->merge_commit->object.flags |= UNINTERESTING;
2020 add_pending_object(&revs, &filter->merge_commit->object, "");
2023 if (prepare_revision_walk(&revs))
2024 die(_("revision walk setup failed"));
2029 for (i = 0; i < old_nr; i++) {
2030 struct ref_array_item *item = array->items[i];
2031 struct commit *commit = item->commit;
2033 int is_merged = !!(commit->object.flags & UNINTERESTING);
2035 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2036 array->items[array->nr++] = array->items[i];
2038 free_array_item(item);
2041 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2042 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2047 * API for filtering a set of refs. Based on the type of refs the user
2048 * has requested, we iterate through those refs and apply filters
2049 * as per the given ref_filter structure and finally store the
2050 * filtered refs in the ref_array structure.
2052 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2054 struct ref_filter_cbdata ref_cbdata;
2056 unsigned int broken = 0;
2058 ref_cbdata.array = array;
2059 ref_cbdata.filter = filter;
2061 if (type & FILTER_REFS_INCLUDE_BROKEN)
2063 filter->kind = type & FILTER_REFS_KIND_MASK;
2065 init_contains_cache(&ref_cbdata.contains_cache);
2066 init_contains_cache(&ref_cbdata.no_contains_cache);
2068 /* Simple per-ref filtering */
2070 die("filter_refs: invalid type");
2073 * For common cases where we need only branches or remotes or tags,
2074 * we only iterate through those refs. If a mix of refs is needed,
2075 * we iterate over all refs and filter out required refs with the help
2076 * of filter_ref_kind().
2078 if (filter->kind == FILTER_REFS_BRANCHES)
2079 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2080 else if (filter->kind == FILTER_REFS_REMOTES)
2081 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2082 else if (filter->kind == FILTER_REFS_TAGS)
2083 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2084 else if (filter->kind & FILTER_REFS_ALL)
2085 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2086 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2087 head_ref(ref_filter_handler, &ref_cbdata);
2090 clear_contains_cache(&ref_cbdata.contains_cache);
2091 clear_contains_cache(&ref_cbdata.no_contains_cache);
2093 /* Filters that need revision walking */
2094 if (filter->merge_commit)
2095 do_merge_filter(&ref_cbdata);
2100 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2102 struct atom_value *va, *vb;
2104 cmp_type cmp_type = used_atom[s->atom].type;
2105 int (*cmp_fn)(const char *, const char *);
2106 struct strbuf err = STRBUF_INIT;
2108 if (get_ref_atom_value(a, s->atom, &va, &err))
2110 if (get_ref_atom_value(b, s->atom, &vb, &err))
2112 strbuf_release(&err);
2113 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2115 cmp = versioncmp(va->s, vb->s);
2116 else if (cmp_type == FIELD_STR)
2117 cmp = cmp_fn(va->s, vb->s);
2119 if (va->value < vb->value)
2121 else if (va->value == vb->value)
2122 cmp = cmp_fn(a->refname, b->refname);
2127 return (s->reverse) ? -cmp : cmp;
2130 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2132 struct ref_array_item *a = *((struct ref_array_item **)a_);
2133 struct ref_array_item *b = *((struct ref_array_item **)b_);
2134 struct ref_sorting *s;
2136 for (s = ref_sorting; s; s = s->next) {
2137 int cmp = cmp_ref_sorting(s, a, b);
2144 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2146 QSORT_S(array->items, array->nr, compare_refs, sorting);
2149 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2151 struct strbuf *s = &state->stack->output;
2153 while (*cp && (!ep || cp < ep)) {
2158 int ch = hex2chr(cp + 1);
2160 strbuf_addch(s, ch);
2166 strbuf_addch(s, *cp);
2171 int format_ref_array_item(struct ref_array_item *info,
2172 const struct ref_format *format,
2173 struct strbuf *final_buf,
2174 struct strbuf *error_buf)
2176 const char *cp, *sp, *ep;
2177 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2179 state.quote_style = format->quote_style;
2180 push_stack_element(&state.stack);
2182 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2183 struct atom_value *atomv;
2186 ep = strchr(sp, ')');
2188 append_literal(cp, sp, &state);
2189 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2190 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2191 atomv->handler(atomv, &state, error_buf)) {
2192 pop_stack_element(&state.stack);
2197 sp = cp + strlen(cp);
2198 append_literal(cp, sp, &state);
2200 if (format->need_color_reset_at_eol) {
2201 struct atom_value resetv;
2202 resetv.s = GIT_COLOR_RESET;
2203 if (append_atom(&resetv, &state, error_buf)) {
2204 pop_stack_element(&state.stack);
2208 if (state.stack->prev) {
2209 pop_stack_element(&state.stack);
2210 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2212 strbuf_addbuf(final_buf, &state.stack->output);
2213 pop_stack_element(&state.stack);
2217 void show_ref_array_item(struct ref_array_item *info,
2218 const struct ref_format *format)
2220 struct strbuf final_buf = STRBUF_INIT;
2221 struct strbuf error_buf = STRBUF_INIT;
2223 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2224 die("%s", error_buf.buf);
2225 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2226 strbuf_release(&error_buf);
2227 strbuf_release(&final_buf);
2231 void pretty_print_ref(const char *name, const struct object_id *oid,
2232 const struct ref_format *format)
2234 struct ref_array_item *ref_item;
2235 ref_item = new_ref_array_item(name, oid);
2236 ref_item->kind = ref_kind_from_refname(name);
2237 show_ref_array_item(ref_item, format);
2238 free_array_item(ref_item);
2241 static int parse_sorting_atom(const char *atom)
2244 * This parses an atom using a dummy ref_format, since we don't
2245 * actually care about the formatting details.
2247 struct ref_format dummy = REF_FORMAT_INIT;
2248 const char *end = atom + strlen(atom);
2249 struct strbuf err = STRBUF_INIT;
2250 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2253 strbuf_release(&err);
2257 /* If no sorting option is given, use refname to sort as default */
2258 struct ref_sorting *ref_default_sorting(void)
2260 static const char cstr_name[] = "refname";
2262 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2264 sorting->next = NULL;
2265 sorting->atom = parse_sorting_atom(cstr_name);
2269 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2271 struct ref_sorting *s;
2273 s = xcalloc(1, sizeof(*s));
2274 s->next = *sorting_tail;
2281 if (skip_prefix(arg, "version:", &arg) ||
2282 skip_prefix(arg, "v:", &arg))
2284 s->atom = parse_sorting_atom(arg);
2287 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2289 if (!arg) /* should --no-sort void the list ? */
2291 parse_ref_sorting(opt->value, arg);
2295 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2297 struct ref_filter *rf = opt->value;
2298 struct object_id oid;
2299 int no_merged = starts_with(opt->long_name, "no");
2303 return opterror(opt, "is incompatible with --merged", 0);
2305 return opterror(opt, "is incompatible with --no-merged", 0);
2309 rf->merge = no_merged
2310 ? REF_FILTER_MERGED_OMIT
2311 : REF_FILTER_MERGED_INCLUDE;
2313 if (get_oid(arg, &oid))
2314 die(_("malformed object name %s"), arg);
2316 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2318 if (!rf->merge_commit)
2319 return opterror(opt, "must point to a commit", 0);