ref-filter: fill empty fields with empty values
[git.git] / ref-filter.c
blob27733ef013bed8dc2affa706b3389841cd16fe23
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "refs.h"
5 #include "wildmatch.h"
6 #include "commit.h"
7 #include "remote.h"
8 #include "color.h"
9 #include "tag.h"
10 #include "quote.h"
11 #include "ref-filter.h"
12 #include "revision.h"
13 #include "utf8.h"
14 #include "git-compat-util.h"
15 #include "version.h"
16 #include "trailer.h"
17 #include "wt-status.h"
18 #include "commit-slab.h"
19 #include "commit-graph.h"
21 static struct ref_msg {
22 const char *gone;
23 const char *ahead;
24 const char *behind;
25 const char *ahead_behind;
26 } msgs = {
27 /* Untranslated plumbing messages: */
28 "gone",
29 "ahead %d",
30 "behind %d",
31 "ahead %d, behind %d"
34 void setup_ref_filter_porcelain_msg(void)
36 msgs.gone = _("gone");
37 msgs.ahead = _("ahead %d");
38 msgs.behind = _("behind %d");
39 msgs.ahead_behind = _("ahead %d, behind %d");
42 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
43 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
44 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
46 struct align {
47 align_type position;
48 unsigned int width;
51 struct if_then_else {
52 cmp_status cmp_status;
53 const char *str;
54 unsigned int then_atom_seen : 1,
55 else_atom_seen : 1,
56 condition_satisfied : 1;
59 struct refname_atom {
60 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
61 int lstrip, rstrip;
65 * An atom is a valid field atom listed below, possibly prefixed with
66 * a "*" to denote deref_tag().
68 * We parse given format string and sort specifiers, and make a list
69 * of properties that we need to extract out of objects. ref_array_item
70 * structure will hold an array of values extracted that can be
71 * indexed with the "atom number", which is an index into this
72 * array.
74 static struct used_atom {
75 const char *name;
76 cmp_type type;
77 info_source source;
78 union {
79 char color[COLOR_MAXLEN];
80 struct align align;
81 struct {
82 enum {
83 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
84 } option;
85 struct refname_atom refname;
86 unsigned int nobracket : 1, push : 1, push_remote : 1;
87 } remote_ref;
88 struct {
89 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
90 struct process_trailer_options trailer_opts;
91 unsigned int nlines;
92 } contents;
93 struct {
94 cmp_status cmp_status;
95 const char *str;
96 } if_then_else;
97 struct {
98 enum { O_FULL, O_LENGTH, O_SHORT } option;
99 unsigned int length;
100 } objectname;
101 struct refname_atom refname;
102 char *head;
103 } u;
104 } *used_atom;
105 static int used_atom_cnt, need_tagged, need_symref;
108 * Expand string, append it to strbuf *sb, then return error code ret.
109 * Allow to save few lines of code.
111 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
113 va_list ap;
114 va_start(ap, fmt);
115 strbuf_vaddf(sb, fmt, ap);
116 va_end(ap);
117 return ret;
120 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
121 const char *color_value, struct strbuf *err)
123 if (!color_value)
124 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
125 if (color_parse(color_value, atom->u.color) < 0)
126 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
127 color_value);
129 * We check this after we've parsed the color, which lets us complain
130 * about syntactically bogus color names even if they won't be used.
132 if (!want_color(format->use_color))
133 color_parse("", atom->u.color);
134 return 0;
137 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
138 const char *name, struct strbuf *err)
140 if (!arg)
141 atom->option = R_NORMAL;
142 else if (!strcmp(arg, "short"))
143 atom->option = R_SHORT;
144 else if (skip_prefix(arg, "lstrip=", &arg) ||
145 skip_prefix(arg, "strip=", &arg)) {
146 atom->option = R_LSTRIP;
147 if (strtol_i(arg, 10, &atom->lstrip))
148 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
149 } else if (skip_prefix(arg, "rstrip=", &arg)) {
150 atom->option = R_RSTRIP;
151 if (strtol_i(arg, 10, &atom->rstrip))
152 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
153 } else
154 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
155 return 0;
158 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
159 const char *arg, struct strbuf *err)
161 struct string_list params = STRING_LIST_INIT_DUP;
162 int i;
164 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
165 atom->u.remote_ref.push = 1;
167 if (!arg) {
168 atom->u.remote_ref.option = RR_REF;
169 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
170 arg, atom->name, err);
173 atom->u.remote_ref.nobracket = 0;
174 string_list_split(&params, arg, ',', -1);
176 for (i = 0; i < params.nr; i++) {
177 const char *s = params.items[i].string;
179 if (!strcmp(s, "track"))
180 atom->u.remote_ref.option = RR_TRACK;
181 else if (!strcmp(s, "trackshort"))
182 atom->u.remote_ref.option = RR_TRACKSHORT;
183 else if (!strcmp(s, "nobracket"))
184 atom->u.remote_ref.nobracket = 1;
185 else if (!strcmp(s, "remotename")) {
186 atom->u.remote_ref.option = RR_REMOTE_NAME;
187 atom->u.remote_ref.push_remote = 1;
188 } else if (!strcmp(s, "remoteref")) {
189 atom->u.remote_ref.option = RR_REMOTE_REF;
190 atom->u.remote_ref.push_remote = 1;
191 } else {
192 atom->u.remote_ref.option = RR_REF;
193 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
194 arg, atom->name, err)) {
195 string_list_clear(&params, 0);
196 return -1;
201 string_list_clear(&params, 0);
202 return 0;
205 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
206 const char *arg, struct strbuf *err)
208 if (arg)
209 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
210 atom->u.contents.option = C_BODY_DEP;
211 return 0;
214 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
215 const char *arg, struct strbuf *err)
217 if (arg)
218 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
219 atom->u.contents.option = C_SUB;
220 return 0;
223 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
224 const char *arg, struct strbuf *err)
226 struct string_list params = STRING_LIST_INIT_DUP;
227 int i;
229 if (arg) {
230 string_list_split(&params, arg, ',', -1);
231 for (i = 0; i < params.nr; i++) {
232 const char *s = params.items[i].string;
233 if (!strcmp(s, "unfold"))
234 atom->u.contents.trailer_opts.unfold = 1;
235 else if (!strcmp(s, "only"))
236 atom->u.contents.trailer_opts.only_trailers = 1;
237 else {
238 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
239 string_list_clear(&params, 0);
240 return -1;
244 atom->u.contents.option = C_TRAILERS;
245 string_list_clear(&params, 0);
246 return 0;
249 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
250 const char *arg, struct strbuf *err)
252 if (!arg)
253 atom->u.contents.option = C_BARE;
254 else if (!strcmp(arg, "body"))
255 atom->u.contents.option = C_BODY;
256 else if (!strcmp(arg, "signature"))
257 atom->u.contents.option = C_SIG;
258 else if (!strcmp(arg, "subject"))
259 atom->u.contents.option = C_SUB;
260 else if (skip_prefix(arg, "trailers", &arg)) {
261 skip_prefix(arg, ":", &arg);
262 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
263 return -1;
264 } else if (skip_prefix(arg, "lines=", &arg)) {
265 atom->u.contents.option = C_LINES;
266 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
267 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
268 } else
269 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
270 return 0;
273 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
274 const char *arg, struct strbuf *err)
276 if (!arg)
277 atom->u.objectname.option = O_FULL;
278 else if (!strcmp(arg, "short"))
279 atom->u.objectname.option = O_SHORT;
280 else if (skip_prefix(arg, "short=", &arg)) {
281 atom->u.objectname.option = O_LENGTH;
282 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
283 atom->u.objectname.length == 0)
284 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
285 if (atom->u.objectname.length < MINIMUM_ABBREV)
286 atom->u.objectname.length = MINIMUM_ABBREV;
287 } else
288 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
289 return 0;
292 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
293 const char *arg, struct strbuf *err)
295 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
298 static align_type parse_align_position(const char *s)
300 if (!strcmp(s, "right"))
301 return ALIGN_RIGHT;
302 else if (!strcmp(s, "middle"))
303 return ALIGN_MIDDLE;
304 else if (!strcmp(s, "left"))
305 return ALIGN_LEFT;
306 return -1;
309 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
310 const char *arg, struct strbuf *err)
312 struct align *align = &atom->u.align;
313 struct string_list params = STRING_LIST_INIT_DUP;
314 int i;
315 unsigned int width = ~0U;
317 if (!arg)
318 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
320 align->position = ALIGN_LEFT;
322 string_list_split(&params, arg, ',', -1);
323 for (i = 0; i < params.nr; i++) {
324 const char *s = params.items[i].string;
325 int position;
327 if (skip_prefix(s, "position=", &s)) {
328 position = parse_align_position(s);
329 if (position < 0) {
330 strbuf_addf(err, _("unrecognized position:%s"), s);
331 string_list_clear(&params, 0);
332 return -1;
334 align->position = position;
335 } else if (skip_prefix(s, "width=", &s)) {
336 if (strtoul_ui(s, 10, &width)) {
337 strbuf_addf(err, _("unrecognized width:%s"), s);
338 string_list_clear(&params, 0);
339 return -1;
341 } else if (!strtoul_ui(s, 10, &width))
343 else if ((position = parse_align_position(s)) >= 0)
344 align->position = position;
345 else {
346 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
347 string_list_clear(&params, 0);
348 return -1;
352 if (width == ~0U) {
353 string_list_clear(&params, 0);
354 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
356 align->width = width;
357 string_list_clear(&params, 0);
358 return 0;
361 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
362 const char *arg, struct strbuf *err)
364 if (!arg) {
365 atom->u.if_then_else.cmp_status = COMPARE_NONE;
366 return 0;
367 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
368 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
369 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
370 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
371 } else
372 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
373 return 0;
376 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
377 const char *arg, struct strbuf *unused_err)
379 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
380 return 0;
383 static struct {
384 const char *name;
385 info_source source;
386 cmp_type cmp_type;
387 int (*parser)(const struct ref_format *format, struct used_atom *atom,
388 const char *arg, struct strbuf *err);
389 } valid_atom[] = {
390 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
391 { "objecttype", SOURCE_OTHER },
392 { "objectsize", SOURCE_OTHER, FIELD_ULONG },
393 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
394 { "tree", SOURCE_OBJ },
395 { "parent", SOURCE_OBJ },
396 { "numparent", SOURCE_OBJ, FIELD_ULONG },
397 { "object", SOURCE_OBJ },
398 { "type", SOURCE_OBJ },
399 { "tag", SOURCE_OBJ },
400 { "author", SOURCE_OBJ },
401 { "authorname", SOURCE_OBJ },
402 { "authoremail", SOURCE_OBJ },
403 { "authordate", SOURCE_OBJ, FIELD_TIME },
404 { "committer", SOURCE_OBJ },
405 { "committername", SOURCE_OBJ },
406 { "committeremail", SOURCE_OBJ },
407 { "committerdate", SOURCE_OBJ, FIELD_TIME },
408 { "tagger", SOURCE_OBJ },
409 { "taggername", SOURCE_OBJ },
410 { "taggeremail", SOURCE_OBJ },
411 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
412 { "creator", SOURCE_OBJ },
413 { "creatordate", SOURCE_OBJ, FIELD_TIME },
414 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
415 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
416 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
417 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
418 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
419 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
420 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
421 { "flag", SOURCE_NONE },
422 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
423 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
424 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
425 { "end", SOURCE_NONE },
426 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
427 { "then", SOURCE_NONE },
428 { "else", SOURCE_NONE },
431 #define REF_FORMATTING_STATE_INIT { 0, NULL }
433 struct ref_formatting_stack {
434 struct ref_formatting_stack *prev;
435 struct strbuf output;
436 void (*at_end)(struct ref_formatting_stack **stack);
437 void *at_end_data;
440 struct ref_formatting_state {
441 int quote_style;
442 struct ref_formatting_stack *stack;
445 struct atom_value {
446 const char *s;
447 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
448 struct strbuf *err);
449 uintmax_t value; /* used for sorting when not FIELD_STR */
450 struct used_atom *atom;
454 * Used to parse format string and sort specifiers
456 static int parse_ref_filter_atom(const struct ref_format *format,
457 const char *atom, const char *ep,
458 struct strbuf *err)
460 const char *sp;
461 const char *arg;
462 int i, at, atom_len;
464 sp = atom;
465 if (*sp == '*' && sp < ep)
466 sp++; /* deref */
467 if (ep <= sp)
468 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
469 (int)(ep-atom), atom);
471 /* Do we have the atom already used elsewhere? */
472 for (i = 0; i < used_atom_cnt; i++) {
473 int len = strlen(used_atom[i].name);
474 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
475 return i;
479 * If the atom name has a colon, strip it and everything after
480 * it off - it specifies the format for this entry, and
481 * shouldn't be used for checking against the valid_atom
482 * table.
484 arg = memchr(sp, ':', ep - sp);
485 atom_len = (arg ? arg : ep) - sp;
487 /* Is the atom a valid one? */
488 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
489 int len = strlen(valid_atom[i].name);
490 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
491 break;
494 if (ARRAY_SIZE(valid_atom) <= i)
495 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
496 (int)(ep-atom), atom);
498 /* Add it in, including the deref prefix */
499 at = used_atom_cnt;
500 used_atom_cnt++;
501 REALLOC_ARRAY(used_atom, used_atom_cnt);
502 used_atom[at].name = xmemdupz(atom, ep - atom);
503 used_atom[at].type = valid_atom[i].cmp_type;
504 used_atom[at].source = valid_atom[i].source;
505 if (arg) {
506 arg = used_atom[at].name + (arg - atom) + 1;
507 if (!*arg) {
509 * Treat empty sub-arguments list as NULL (i.e.,
510 * "%(atom:)" is equivalent to "%(atom)").
512 arg = NULL;
515 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
516 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
517 return -1;
518 if (*atom == '*')
519 need_tagged = 1;
520 if (!strcmp(valid_atom[i].name, "symref"))
521 need_symref = 1;
522 return at;
525 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
527 switch (quote_style) {
528 case QUOTE_NONE:
529 strbuf_addstr(s, str);
530 break;
531 case QUOTE_SHELL:
532 sq_quote_buf(s, str);
533 break;
534 case QUOTE_PERL:
535 perl_quote_buf(s, str);
536 break;
537 case QUOTE_PYTHON:
538 python_quote_buf(s, str);
539 break;
540 case QUOTE_TCL:
541 tcl_quote_buf(s, str);
542 break;
546 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
547 struct strbuf *unused_err)
550 * Quote formatting is only done when the stack has a single
551 * element. Otherwise quote formatting is done on the
552 * element's entire output strbuf when the %(end) atom is
553 * encountered.
555 if (!state->stack->prev)
556 quote_formatting(&state->stack->output, v->s, state->quote_style);
557 else
558 strbuf_addstr(&state->stack->output, v->s);
559 return 0;
562 static void push_stack_element(struct ref_formatting_stack **stack)
564 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
566 strbuf_init(&s->output, 0);
567 s->prev = *stack;
568 *stack = s;
571 static void pop_stack_element(struct ref_formatting_stack **stack)
573 struct ref_formatting_stack *current = *stack;
574 struct ref_formatting_stack *prev = current->prev;
576 if (prev)
577 strbuf_addbuf(&prev->output, &current->output);
578 strbuf_release(&current->output);
579 free(current);
580 *stack = prev;
583 static void end_align_handler(struct ref_formatting_stack **stack)
585 struct ref_formatting_stack *cur = *stack;
586 struct align *align = (struct align *)cur->at_end_data;
587 struct strbuf s = STRBUF_INIT;
589 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
590 strbuf_swap(&cur->output, &s);
591 strbuf_release(&s);
594 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
595 struct strbuf *unused_err)
597 struct ref_formatting_stack *new_stack;
599 push_stack_element(&state->stack);
600 new_stack = state->stack;
601 new_stack->at_end = end_align_handler;
602 new_stack->at_end_data = &atomv->atom->u.align;
603 return 0;
606 static void if_then_else_handler(struct ref_formatting_stack **stack)
608 struct ref_formatting_stack *cur = *stack;
609 struct ref_formatting_stack *prev = cur->prev;
610 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
612 if (!if_then_else->then_atom_seen)
613 die(_("format: %%(if) atom used without a %%(then) atom"));
615 if (if_then_else->else_atom_seen) {
617 * There is an %(else) atom: we need to drop one state from the
618 * stack, either the %(else) branch if the condition is satisfied, or
619 * the %(then) branch if it isn't.
621 if (if_then_else->condition_satisfied) {
622 strbuf_reset(&cur->output);
623 pop_stack_element(&cur);
624 } else {
625 strbuf_swap(&cur->output, &prev->output);
626 strbuf_reset(&cur->output);
627 pop_stack_element(&cur);
629 } else if (!if_then_else->condition_satisfied) {
631 * No %(else) atom: just drop the %(then) branch if the
632 * condition is not satisfied.
634 strbuf_reset(&cur->output);
637 *stack = cur;
638 free(if_then_else);
641 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
642 struct strbuf *unused_err)
644 struct ref_formatting_stack *new_stack;
645 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
647 if_then_else->str = atomv->atom->u.if_then_else.str;
648 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
650 push_stack_element(&state->stack);
651 new_stack = state->stack;
652 new_stack->at_end = if_then_else_handler;
653 new_stack->at_end_data = if_then_else;
654 return 0;
657 static int is_empty(const char *s)
659 while (*s != '\0') {
660 if (!isspace(*s))
661 return 0;
662 s++;
664 return 1;
667 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
668 struct strbuf *err)
670 struct ref_formatting_stack *cur = state->stack;
671 struct if_then_else *if_then_else = NULL;
673 if (cur->at_end == if_then_else_handler)
674 if_then_else = (struct if_then_else *)cur->at_end_data;
675 if (!if_then_else)
676 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
677 if (if_then_else->then_atom_seen)
678 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
679 if (if_then_else->else_atom_seen)
680 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
681 if_then_else->then_atom_seen = 1;
683 * If the 'equals' or 'notequals' attribute is used then
684 * perform the required comparison. If not, only non-empty
685 * strings satisfy the 'if' condition.
687 if (if_then_else->cmp_status == COMPARE_EQUAL) {
688 if (!strcmp(if_then_else->str, cur->output.buf))
689 if_then_else->condition_satisfied = 1;
690 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
691 if (strcmp(if_then_else->str, cur->output.buf))
692 if_then_else->condition_satisfied = 1;
693 } else if (cur->output.len && !is_empty(cur->output.buf))
694 if_then_else->condition_satisfied = 1;
695 strbuf_reset(&cur->output);
696 return 0;
699 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
700 struct strbuf *err)
702 struct ref_formatting_stack *prev = state->stack;
703 struct if_then_else *if_then_else = NULL;
705 if (prev->at_end == if_then_else_handler)
706 if_then_else = (struct if_then_else *)prev->at_end_data;
707 if (!if_then_else)
708 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
709 if (!if_then_else->then_atom_seen)
710 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
711 if (if_then_else->else_atom_seen)
712 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
713 if_then_else->else_atom_seen = 1;
714 push_stack_element(&state->stack);
715 state->stack->at_end_data = prev->at_end_data;
716 state->stack->at_end = prev->at_end;
717 return 0;
720 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
721 struct strbuf *err)
723 struct ref_formatting_stack *current = state->stack;
724 struct strbuf s = STRBUF_INIT;
726 if (!current->at_end)
727 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
728 current->at_end(&state->stack);
730 /* Stack may have been popped within at_end(), hence reset the current pointer */
731 current = state->stack;
734 * Perform quote formatting when the stack element is that of
735 * a supporting atom. If nested then perform quote formatting
736 * only on the topmost supporting atom.
738 if (!current->prev->prev) {
739 quote_formatting(&s, current->output.buf, state->quote_style);
740 strbuf_swap(&current->output, &s);
742 strbuf_release(&s);
743 pop_stack_element(&state->stack);
744 return 0;
748 * In a format string, find the next occurrence of %(atom).
750 static const char *find_next(const char *cp)
752 while (*cp) {
753 if (*cp == '%') {
755 * %( is the start of an atom;
756 * %% is a quoted per-cent.
758 if (cp[1] == '(')
759 return cp;
760 else if (cp[1] == '%')
761 cp++; /* skip over two % */
762 /* otherwise this is a singleton, literal % */
764 cp++;
766 return NULL;
770 * Make sure the format string is well formed, and parse out
771 * the used atoms.
773 int verify_ref_format(struct ref_format *format)
775 const char *cp, *sp;
777 format->need_color_reset_at_eol = 0;
778 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
779 struct strbuf err = STRBUF_INIT;
780 const char *color, *ep = strchr(sp, ')');
781 int at;
783 if (!ep)
784 return error(_("malformed format string %s"), sp);
785 /* sp points at "%(" and ep points at the closing ")" */
786 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
787 if (at < 0)
788 die("%s", err.buf);
789 cp = ep + 1;
791 if (skip_prefix(used_atom[at].name, "color:", &color))
792 format->need_color_reset_at_eol = !!strcmp(color, "reset");
793 strbuf_release(&err);
795 if (format->need_color_reset_at_eol && !want_color(format->use_color))
796 format->need_color_reset_at_eol = 0;
797 return 0;
801 * Given an object name, read the object data and size, and return a
802 * "struct object". If the object data we are returning is also borrowed
803 * by the "struct object" representation, set *eaten as well---it is a
804 * signal from parse_object_buffer to us not to free the buffer.
806 static void *get_obj(const struct object_id *oid, struct object **obj, unsigned long *sz, int *eaten)
808 enum object_type type;
809 void *buf = read_object_file(oid, &type, sz);
811 if (buf)
812 *obj = parse_object_buffer(oid, type, *sz, buf, eaten);
813 else
814 *obj = NULL;
815 return buf;
818 static int grab_objectname(const char *name, const struct object_id *oid,
819 struct atom_value *v, struct used_atom *atom)
821 if (starts_with(name, "objectname")) {
822 if (atom->u.objectname.option == O_SHORT) {
823 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
824 return 1;
825 } else if (atom->u.objectname.option == O_FULL) {
826 v->s = xstrdup(oid_to_hex(oid));
827 return 1;
828 } else if (atom->u.objectname.option == O_LENGTH) {
829 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
830 return 1;
831 } else
832 BUG("unknown %%(objectname) option");
834 return 0;
837 /* See grab_values */
838 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
840 int i;
842 for (i = 0; i < used_atom_cnt; i++) {
843 const char *name = used_atom[i].name;
844 struct atom_value *v = &val[i];
845 if (!!deref != (*name == '*'))
846 continue;
847 if (deref)
848 name++;
849 if (!strcmp(name, "objecttype"))
850 v->s = type_name(obj->type);
851 else if (!strcmp(name, "objectsize")) {
852 v->value = sz;
853 v->s = xstrfmt("%lu", sz);
855 else if (deref)
856 grab_objectname(name, &obj->oid, v, &used_atom[i]);
860 /* See grab_values */
861 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
863 int i;
864 struct tag *tag = (struct tag *) obj;
866 for (i = 0; i < used_atom_cnt; i++) {
867 const char *name = used_atom[i].name;
868 struct atom_value *v = &val[i];
869 if (!!deref != (*name == '*'))
870 continue;
871 if (deref)
872 name++;
873 if (!strcmp(name, "tag"))
874 v->s = tag->tag;
875 else if (!strcmp(name, "type") && tag->tagged)
876 v->s = type_name(tag->tagged->type);
877 else if (!strcmp(name, "object") && tag->tagged)
878 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
882 /* See grab_values */
883 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
885 int i;
886 struct commit *commit = (struct commit *) obj;
888 for (i = 0; i < used_atom_cnt; i++) {
889 const char *name = used_atom[i].name;
890 struct atom_value *v = &val[i];
891 if (!!deref != (*name == '*'))
892 continue;
893 if (deref)
894 name++;
895 if (!strcmp(name, "tree")) {
896 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
898 else if (!strcmp(name, "numparent")) {
899 v->value = commit_list_count(commit->parents);
900 v->s = xstrfmt("%lu", (unsigned long)v->value);
902 else if (!strcmp(name, "parent")) {
903 struct commit_list *parents;
904 struct strbuf s = STRBUF_INIT;
905 for (parents = commit->parents; parents; parents = parents->next) {
906 struct commit *parent = parents->item;
907 if (parents != commit->parents)
908 strbuf_addch(&s, ' ');
909 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
911 v->s = strbuf_detach(&s, NULL);
916 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
918 const char *eol;
919 while (*buf) {
920 if (!strncmp(buf, who, wholen) &&
921 buf[wholen] == ' ')
922 return buf + wholen + 1;
923 eol = strchr(buf, '\n');
924 if (!eol)
925 return "";
926 eol++;
927 if (*eol == '\n')
928 return ""; /* end of header */
929 buf = eol;
931 return "";
934 static const char *copy_line(const char *buf)
936 const char *eol = strchrnul(buf, '\n');
937 return xmemdupz(buf, eol - buf);
940 static const char *copy_name(const char *buf)
942 const char *cp;
943 for (cp = buf; *cp && *cp != '\n'; cp++) {
944 if (!strncmp(cp, " <", 2))
945 return xmemdupz(buf, cp - buf);
947 return "";
950 static const char *copy_email(const char *buf)
952 const char *email = strchr(buf, '<');
953 const char *eoemail;
954 if (!email)
955 return "";
956 eoemail = strchr(email, '>');
957 if (!eoemail)
958 return "";
959 return xmemdupz(email, eoemail + 1 - email);
962 static char *copy_subject(const char *buf, unsigned long len)
964 char *r = xmemdupz(buf, len);
965 int i;
967 for (i = 0; i < len; i++)
968 if (r[i] == '\n')
969 r[i] = ' ';
971 return r;
974 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
976 const char *eoemail = strstr(buf, "> ");
977 char *zone;
978 timestamp_t timestamp;
979 long tz;
980 struct date_mode date_mode = { DATE_NORMAL };
981 const char *formatp;
984 * We got here because atomname ends in "date" or "date<something>";
985 * it's not possible that <something> is not ":<format>" because
986 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
987 * ":" means no format is specified, and use the default.
989 formatp = strchr(atomname, ':');
990 if (formatp != NULL) {
991 formatp++;
992 parse_date_format(formatp, &date_mode);
995 if (!eoemail)
996 goto bad;
997 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
998 if (timestamp == TIME_MAX)
999 goto bad;
1000 tz = strtol(zone, NULL, 10);
1001 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1002 goto bad;
1003 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1004 v->value = timestamp;
1005 return;
1006 bad:
1007 v->s = "";
1008 v->value = 0;
1011 /* See grab_values */
1012 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1014 int i;
1015 int wholen = strlen(who);
1016 const char *wholine = NULL;
1018 for (i = 0; i < used_atom_cnt; i++) {
1019 const char *name = used_atom[i].name;
1020 struct atom_value *v = &val[i];
1021 if (!!deref != (*name == '*'))
1022 continue;
1023 if (deref)
1024 name++;
1025 if (strncmp(who, name, wholen))
1026 continue;
1027 if (name[wholen] != 0 &&
1028 strcmp(name + wholen, "name") &&
1029 strcmp(name + wholen, "email") &&
1030 !starts_with(name + wholen, "date"))
1031 continue;
1032 if (!wholine)
1033 wholine = find_wholine(who, wholen, buf, sz);
1034 if (!wholine)
1035 return; /* no point looking for it */
1036 if (name[wholen] == 0)
1037 v->s = copy_line(wholine);
1038 else if (!strcmp(name + wholen, "name"))
1039 v->s = copy_name(wholine);
1040 else if (!strcmp(name + wholen, "email"))
1041 v->s = copy_email(wholine);
1042 else if (starts_with(name + wholen, "date"))
1043 grab_date(wholine, v, name);
1047 * For a tag or a commit object, if "creator" or "creatordate" is
1048 * requested, do something special.
1050 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1051 return; /* "author" for commit object is not wanted */
1052 if (!wholine)
1053 wholine = find_wholine(who, wholen, buf, sz);
1054 if (!wholine)
1055 return;
1056 for (i = 0; i < used_atom_cnt; i++) {
1057 const char *name = used_atom[i].name;
1058 struct atom_value *v = &val[i];
1059 if (!!deref != (*name == '*'))
1060 continue;
1061 if (deref)
1062 name++;
1064 if (starts_with(name, "creatordate"))
1065 grab_date(wholine, v, name);
1066 else if (!strcmp(name, "creator"))
1067 v->s = copy_line(wholine);
1071 static void find_subpos(const char *buf, unsigned long sz,
1072 const char **sub, unsigned long *sublen,
1073 const char **body, unsigned long *bodylen,
1074 unsigned long *nonsiglen,
1075 const char **sig, unsigned long *siglen)
1077 const char *eol;
1078 /* skip past header until we hit empty line */
1079 while (*buf && *buf != '\n') {
1080 eol = strchrnul(buf, '\n');
1081 if (*eol)
1082 eol++;
1083 buf = eol;
1085 /* skip any empty lines */
1086 while (*buf == '\n')
1087 buf++;
1089 /* parse signature first; we might not even have a subject line */
1090 *sig = buf + parse_signature(buf, strlen(buf));
1091 *siglen = strlen(*sig);
1093 /* subject is first non-empty line */
1094 *sub = buf;
1095 /* subject goes to first empty line */
1096 while (buf < *sig && *buf && *buf != '\n') {
1097 eol = strchrnul(buf, '\n');
1098 if (*eol)
1099 eol++;
1100 buf = eol;
1102 *sublen = buf - *sub;
1103 /* drop trailing newline, if present */
1104 if (*sublen && (*sub)[*sublen - 1] == '\n')
1105 *sublen -= 1;
1107 /* skip any empty lines */
1108 while (*buf == '\n')
1109 buf++;
1110 *body = buf;
1111 *bodylen = strlen(buf);
1112 *nonsiglen = *sig - buf;
1116 * If 'lines' is greater than 0, append that many lines from the given
1117 * 'buf' of length 'size' to the given strbuf.
1119 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1121 int i;
1122 const char *sp, *eol;
1123 size_t len;
1125 sp = buf;
1127 for (i = 0; i < lines && sp < buf + size; i++) {
1128 if (i)
1129 strbuf_addstr(out, "\n ");
1130 eol = memchr(sp, '\n', size - (sp - buf));
1131 len = eol ? eol - sp : size - (sp - buf);
1132 strbuf_add(out, sp, len);
1133 if (!eol)
1134 break;
1135 sp = eol + 1;
1139 /* See grab_values */
1140 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1142 int i;
1143 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1144 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1146 for (i = 0; i < used_atom_cnt; i++) {
1147 struct used_atom *atom = &used_atom[i];
1148 const char *name = atom->name;
1149 struct atom_value *v = &val[i];
1150 if (!!deref != (*name == '*'))
1151 continue;
1152 if (deref)
1153 name++;
1154 if (strcmp(name, "subject") &&
1155 strcmp(name, "body") &&
1156 !starts_with(name, "trailers") &&
1157 !starts_with(name, "contents"))
1158 continue;
1159 if (!subpos)
1160 find_subpos(buf, sz,
1161 &subpos, &sublen,
1162 &bodypos, &bodylen, &nonsiglen,
1163 &sigpos, &siglen);
1165 if (atom->u.contents.option == C_SUB)
1166 v->s = copy_subject(subpos, sublen);
1167 else if (atom->u.contents.option == C_BODY_DEP)
1168 v->s = xmemdupz(bodypos, bodylen);
1169 else if (atom->u.contents.option == C_BODY)
1170 v->s = xmemdupz(bodypos, nonsiglen);
1171 else if (atom->u.contents.option == C_SIG)
1172 v->s = xmemdupz(sigpos, siglen);
1173 else if (atom->u.contents.option == C_LINES) {
1174 struct strbuf s = STRBUF_INIT;
1175 const char *contents_end = bodylen + bodypos - siglen;
1177 /* Size is the length of the message after removing the signature */
1178 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1179 v->s = strbuf_detach(&s, NULL);
1180 } else if (atom->u.contents.option == C_TRAILERS) {
1181 struct strbuf s = STRBUF_INIT;
1183 /* Format the trailer info according to the trailer_opts given */
1184 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1186 v->s = strbuf_detach(&s, NULL);
1187 } else if (atom->u.contents.option == C_BARE)
1188 v->s = xstrdup(subpos);
1193 * We want to have empty print-string for field requests
1194 * that do not apply (e.g. "authordate" for a tag object)
1196 static void fill_missing_values(struct atom_value *val)
1198 int i;
1199 for (i = 0; i < used_atom_cnt; i++) {
1200 struct atom_value *v = &val[i];
1201 if (v->s == NULL)
1202 v->s = "";
1207 * val is a list of atom_value to hold returned values. Extract
1208 * the values for atoms in used_atom array out of (obj, buf, sz).
1209 * when deref is false, (obj, buf, sz) is the object that is
1210 * pointed at by the ref itself; otherwise it is the object the
1211 * ref (which is a tag) refers to.
1213 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1215 grab_common_values(val, deref, obj, buf, sz);
1216 switch (obj->type) {
1217 case OBJ_TAG:
1218 grab_tag_values(val, deref, obj, buf, sz);
1219 grab_sub_body_contents(val, deref, obj, buf, sz);
1220 grab_person("tagger", val, deref, obj, buf, sz);
1221 break;
1222 case OBJ_COMMIT:
1223 grab_commit_values(val, deref, obj, buf, sz);
1224 grab_sub_body_contents(val, deref, obj, buf, sz);
1225 grab_person("author", val, deref, obj, buf, sz);
1226 grab_person("committer", val, deref, obj, buf, sz);
1227 break;
1228 case OBJ_TREE:
1229 /* grab_tree_values(val, deref, obj, buf, sz); */
1230 break;
1231 case OBJ_BLOB:
1232 /* grab_blob_values(val, deref, obj, buf, sz); */
1233 break;
1234 default:
1235 die("Eh? Object of type %d?", obj->type);
1239 static inline char *copy_advance(char *dst, const char *src)
1241 while (*src)
1242 *dst++ = *src++;
1243 return dst;
1246 static const char *lstrip_ref_components(const char *refname, int len)
1248 long remaining = len;
1249 const char *start = refname;
1251 if (len < 0) {
1252 int i;
1253 const char *p = refname;
1255 /* Find total no of '/' separated path-components */
1256 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1259 * The number of components we need to strip is now
1260 * the total minus the components to be left (Plus one
1261 * because we count the number of '/', but the number
1262 * of components is one more than the no of '/').
1264 remaining = i + len + 1;
1267 while (remaining > 0) {
1268 switch (*start++) {
1269 case '\0':
1270 return "";
1271 case '/':
1272 remaining--;
1273 break;
1277 return start;
1280 static const char *rstrip_ref_components(const char *refname, int len)
1282 long remaining = len;
1283 char *start = xstrdup(refname);
1285 if (len < 0) {
1286 int i;
1287 const char *p = refname;
1289 /* Find total no of '/' separated path-components */
1290 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1293 * The number of components we need to strip is now
1294 * the total minus the components to be left (Plus one
1295 * because we count the number of '/', but the number
1296 * of components is one more than the no of '/').
1298 remaining = i + len + 1;
1301 while (remaining-- > 0) {
1302 char *p = strrchr(start, '/');
1303 if (p == NULL)
1304 return "";
1305 else
1306 p[0] = '\0';
1308 return start;
1311 static const char *show_ref(struct refname_atom *atom, const char *refname)
1313 if (atom->option == R_SHORT)
1314 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1315 else if (atom->option == R_LSTRIP)
1316 return lstrip_ref_components(refname, atom->lstrip);
1317 else if (atom->option == R_RSTRIP)
1318 return rstrip_ref_components(refname, atom->rstrip);
1319 else
1320 return refname;
1323 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1324 struct branch *branch, const char **s)
1326 int num_ours, num_theirs;
1327 if (atom->u.remote_ref.option == RR_REF)
1328 *s = show_ref(&atom->u.remote_ref.refname, refname);
1329 else if (atom->u.remote_ref.option == RR_TRACK) {
1330 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1331 NULL, AHEAD_BEHIND_FULL) < 0) {
1332 *s = xstrdup(msgs.gone);
1333 } else if (!num_ours && !num_theirs)
1334 *s = "";
1335 else if (!num_ours)
1336 *s = xstrfmt(msgs.behind, num_theirs);
1337 else if (!num_theirs)
1338 *s = xstrfmt(msgs.ahead, num_ours);
1339 else
1340 *s = xstrfmt(msgs.ahead_behind,
1341 num_ours, num_theirs);
1342 if (!atom->u.remote_ref.nobracket && *s[0]) {
1343 const char *to_free = *s;
1344 *s = xstrfmt("[%s]", *s);
1345 free((void *)to_free);
1347 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1348 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1349 NULL, AHEAD_BEHIND_FULL) < 0)
1350 return;
1352 if (!num_ours && !num_theirs)
1353 *s = "=";
1354 else if (!num_ours)
1355 *s = "<";
1356 else if (!num_theirs)
1357 *s = ">";
1358 else
1359 *s = "<>";
1360 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1361 int explicit;
1362 const char *remote = atom->u.remote_ref.push ?
1363 pushremote_for_branch(branch, &explicit) :
1364 remote_for_branch(branch, &explicit);
1365 if (explicit)
1366 *s = xstrdup(remote);
1367 else
1368 *s = "";
1369 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1370 int explicit;
1371 const char *merge;
1373 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1374 &explicit);
1375 if (explicit)
1376 *s = xstrdup(merge);
1377 else
1378 *s = "";
1379 } else
1380 BUG("unhandled RR_* enum");
1383 char *get_head_description(void)
1385 struct strbuf desc = STRBUF_INIT;
1386 struct wt_status_state state;
1387 memset(&state, 0, sizeof(state));
1388 wt_status_get_state(&state, 1);
1389 if (state.rebase_in_progress ||
1390 state.rebase_interactive_in_progress) {
1391 if (state.branch)
1392 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1393 state.branch);
1394 else
1395 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1396 state.detached_from);
1397 } else if (state.bisect_in_progress)
1398 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1399 state.branch);
1400 else if (state.detached_from) {
1401 if (state.detached_at)
1403 * TRANSLATORS: make sure this matches "HEAD
1404 * detached at " in wt-status.c
1406 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1407 state.detached_from);
1408 else
1410 * TRANSLATORS: make sure this matches "HEAD
1411 * detached from " in wt-status.c
1413 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1414 state.detached_from);
1416 else
1417 strbuf_addstr(&desc, _("(no branch)"));
1418 free(state.branch);
1419 free(state.onto);
1420 free(state.detached_from);
1421 return strbuf_detach(&desc, NULL);
1424 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1426 if (!ref->symref)
1427 return "";
1428 else
1429 return show_ref(&atom->u.refname, ref->symref);
1432 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1434 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1435 return get_head_description();
1436 return show_ref(&atom->u.refname, ref->refname);
1439 static int get_object(struct ref_array_item *ref, const struct object_id *oid,
1440 int deref, struct object **obj, struct strbuf *err)
1442 int eaten;
1443 int ret = 0;
1444 unsigned long size;
1445 void *buf = get_obj(oid, obj, &size, &eaten);
1446 if (!buf)
1447 ret = strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1448 oid_to_hex(oid), ref->refname);
1449 else if (!*obj)
1450 ret = strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1451 oid_to_hex(oid), ref->refname);
1452 else
1453 grab_values(ref->value, deref, *obj, buf, size);
1454 if (!eaten)
1455 free(buf);
1456 return ret;
1460 * Parse the object referred by ref, and grab needed value.
1462 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1464 struct object *obj;
1465 int i;
1466 const struct object_id *tagged;
1468 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1470 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1471 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1472 NULL, NULL);
1473 if (!ref->symref)
1474 ref->symref = "";
1477 /* Fill in specials first */
1478 for (i = 0; i < used_atom_cnt; i++) {
1479 struct used_atom *atom = &used_atom[i];
1480 const char *name = used_atom[i].name;
1481 struct atom_value *v = &ref->value[i];
1482 int deref = 0;
1483 const char *refname;
1484 struct branch *branch = NULL;
1486 v->handler = append_atom;
1487 v->atom = atom;
1489 if (*name == '*') {
1490 deref = 1;
1491 name++;
1494 if (starts_with(name, "refname"))
1495 refname = get_refname(atom, ref);
1496 else if (starts_with(name, "symref"))
1497 refname = get_symref(atom, ref);
1498 else if (starts_with(name, "upstream")) {
1499 const char *branch_name;
1500 v->s = "";
1501 /* only local branches may have an upstream */
1502 if (!skip_prefix(ref->refname, "refs/heads/",
1503 &branch_name))
1504 continue;
1505 branch = branch_get(branch_name);
1507 refname = branch_get_upstream(branch, NULL);
1508 if (refname)
1509 fill_remote_ref_details(atom, refname, branch, &v->s);
1510 continue;
1511 } else if (atom->u.remote_ref.push) {
1512 const char *branch_name;
1513 v->s = "";
1514 if (!skip_prefix(ref->refname, "refs/heads/",
1515 &branch_name))
1516 continue;
1517 branch = branch_get(branch_name);
1519 if (atom->u.remote_ref.push_remote)
1520 refname = NULL;
1521 else {
1522 refname = branch_get_push(branch, NULL);
1523 if (!refname)
1524 continue;
1526 fill_remote_ref_details(atom, refname, branch, &v->s);
1527 continue;
1528 } else if (starts_with(name, "color:")) {
1529 v->s = atom->u.color;
1530 continue;
1531 } else if (!strcmp(name, "flag")) {
1532 char buf[256], *cp = buf;
1533 if (ref->flag & REF_ISSYMREF)
1534 cp = copy_advance(cp, ",symref");
1535 if (ref->flag & REF_ISPACKED)
1536 cp = copy_advance(cp, ",packed");
1537 if (cp == buf)
1538 v->s = "";
1539 else {
1540 *cp = '\0';
1541 v->s = xstrdup(buf + 1);
1543 continue;
1544 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1545 continue;
1546 } else if (!strcmp(name, "HEAD")) {
1547 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1548 v->s = "*";
1549 else
1550 v->s = " ";
1551 continue;
1552 } else if (starts_with(name, "align")) {
1553 v->handler = align_atom_handler;
1554 v->s = "";
1555 continue;
1556 } else if (!strcmp(name, "end")) {
1557 v->handler = end_atom_handler;
1558 v->s = "";
1559 continue;
1560 } else if (starts_with(name, "if")) {
1561 const char *s;
1562 v->s = "";
1563 if (skip_prefix(name, "if:", &s))
1564 v->s = xstrdup(s);
1565 v->handler = if_atom_handler;
1566 continue;
1567 } else if (!strcmp(name, "then")) {
1568 v->handler = then_atom_handler;
1569 v->s = "";
1570 continue;
1571 } else if (!strcmp(name, "else")) {
1572 v->handler = else_atom_handler;
1573 v->s = "";
1574 continue;
1575 } else
1576 continue;
1578 if (!deref)
1579 v->s = refname;
1580 else
1581 v->s = xstrfmt("%s^{}", refname);
1584 for (i = 0; i < used_atom_cnt; i++) {
1585 struct atom_value *v = &ref->value[i];
1586 if (v->s == NULL)
1587 break;
1589 if (used_atom_cnt <= i)
1590 return 0;
1592 if (get_object(ref, &ref->objectname, 0, &obj, err))
1593 return -1;
1596 * If there is no atom that wants to know about tagged
1597 * object, we are done.
1599 if (!need_tagged || (obj->type != OBJ_TAG))
1600 return 0;
1603 * If it is a tag object, see if we use a value that derefs
1604 * the object, and if we do grab the object it refers to.
1606 tagged = &((struct tag *)obj)->tagged->oid;
1609 * NEEDSWORK: This derefs tag only once, which
1610 * is good to deal with chains of trust, but
1611 * is not consistent with what deref_tag() does
1612 * which peels the onion to the core.
1614 return get_object(ref, tagged, 1, &obj, err);
1618 * Given a ref, return the value for the atom. This lazily gets value
1619 * out of the object by calling populate value.
1621 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1622 struct atom_value **v, struct strbuf *err)
1624 if (!ref->value) {
1625 if (populate_value(ref, err))
1626 return -1;
1627 fill_missing_values(ref->value);
1629 *v = &ref->value[atom];
1630 return 0;
1634 * Unknown has to be "0" here, because that's the default value for
1635 * contains_cache slab entries that have not yet been assigned.
1637 enum contains_result {
1638 CONTAINS_UNKNOWN = 0,
1639 CONTAINS_NO,
1640 CONTAINS_YES
1643 define_commit_slab(contains_cache, enum contains_result);
1645 struct ref_filter_cbdata {
1646 struct ref_array *array;
1647 struct ref_filter *filter;
1648 struct contains_cache contains_cache;
1649 struct contains_cache no_contains_cache;
1653 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1654 * overflows.
1656 * At each recursion step, the stack items points to the commits whose
1657 * ancestors are to be inspected.
1659 struct contains_stack {
1660 int nr, alloc;
1661 struct contains_stack_entry {
1662 struct commit *commit;
1663 struct commit_list *parents;
1664 } *contains_stack;
1667 static int in_commit_list(const struct commit_list *want, struct commit *c)
1669 for (; want; want = want->next)
1670 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1671 return 1;
1672 return 0;
1676 * Test whether the candidate is contained in the list.
1677 * Do not recurse to find out, though, but return -1 if inconclusive.
1679 static enum contains_result contains_test(struct commit *candidate,
1680 const struct commit_list *want,
1681 struct contains_cache *cache,
1682 uint32_t cutoff)
1684 enum contains_result *cached = contains_cache_at(cache, candidate);
1686 /* If we already have the answer cached, return that. */
1687 if (*cached)
1688 return *cached;
1690 /* or are we it? */
1691 if (in_commit_list(want, candidate)) {
1692 *cached = CONTAINS_YES;
1693 return CONTAINS_YES;
1696 /* Otherwise, we don't know; prepare to recurse */
1697 parse_commit_or_die(candidate);
1699 if (candidate->generation < cutoff)
1700 return CONTAINS_NO;
1702 return CONTAINS_UNKNOWN;
1705 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1707 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1708 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1709 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1712 static enum contains_result contains_tag_algo(struct commit *candidate,
1713 const struct commit_list *want,
1714 struct contains_cache *cache)
1716 struct contains_stack contains_stack = { 0, 0, NULL };
1717 enum contains_result result;
1718 uint32_t cutoff = GENERATION_NUMBER_INFINITY;
1719 const struct commit_list *p;
1721 for (p = want; p; p = p->next) {
1722 struct commit *c = p->item;
1723 load_commit_graph_info(c);
1724 if (c->generation < cutoff)
1725 cutoff = c->generation;
1728 result = contains_test(candidate, want, cache, cutoff);
1729 if (result != CONTAINS_UNKNOWN)
1730 return result;
1732 push_to_contains_stack(candidate, &contains_stack);
1733 while (contains_stack.nr) {
1734 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1735 struct commit *commit = entry->commit;
1736 struct commit_list *parents = entry->parents;
1738 if (!parents) {
1739 *contains_cache_at(cache, commit) = CONTAINS_NO;
1740 contains_stack.nr--;
1743 * If we just popped the stack, parents->item has been marked,
1744 * therefore contains_test will return a meaningful yes/no.
1746 else switch (contains_test(parents->item, want, cache, cutoff)) {
1747 case CONTAINS_YES:
1748 *contains_cache_at(cache, commit) = CONTAINS_YES;
1749 contains_stack.nr--;
1750 break;
1751 case CONTAINS_NO:
1752 entry->parents = parents->next;
1753 break;
1754 case CONTAINS_UNKNOWN:
1755 push_to_contains_stack(parents->item, &contains_stack);
1756 break;
1759 free(contains_stack.contains_stack);
1760 return contains_test(candidate, want, cache, cutoff);
1763 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1764 struct commit_list *list, struct contains_cache *cache)
1766 if (filter->with_commit_tag_algo)
1767 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1768 return is_descendant_of(commit, list);
1772 * Return 1 if the refname matches one of the patterns, otherwise 0.
1773 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1774 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1775 * matches "refs/heads/mas*", too).
1777 static int match_pattern(const struct ref_filter *filter, const char *refname)
1779 const char **patterns = filter->name_patterns;
1780 unsigned flags = 0;
1782 if (filter->ignore_case)
1783 flags |= WM_CASEFOLD;
1786 * When no '--format' option is given we need to skip the prefix
1787 * for matching refs of tags and branches.
1789 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1790 skip_prefix(refname, "refs/heads/", &refname) ||
1791 skip_prefix(refname, "refs/remotes/", &refname) ||
1792 skip_prefix(refname, "refs/", &refname));
1794 for (; *patterns; patterns++) {
1795 if (!wildmatch(*patterns, refname, flags))
1796 return 1;
1798 return 0;
1802 * Return 1 if the refname matches one of the patterns, otherwise 0.
1803 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1804 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1805 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1807 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1809 const char **pattern = filter->name_patterns;
1810 int namelen = strlen(refname);
1811 unsigned flags = WM_PATHNAME;
1813 if (filter->ignore_case)
1814 flags |= WM_CASEFOLD;
1816 for (; *pattern; pattern++) {
1817 const char *p = *pattern;
1818 int plen = strlen(p);
1820 if ((plen <= namelen) &&
1821 !strncmp(refname, p, plen) &&
1822 (refname[plen] == '\0' ||
1823 refname[plen] == '/' ||
1824 p[plen-1] == '/'))
1825 return 1;
1826 if (!wildmatch(p, refname, WM_PATHNAME))
1827 return 1;
1829 return 0;
1832 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1833 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1835 if (!*filter->name_patterns)
1836 return 1; /* No pattern always matches */
1837 if (filter->match_as_path)
1838 return match_name_as_path(filter, refname);
1839 return match_pattern(filter, refname);
1843 * Find the longest prefix of pattern we can pass to
1844 * `for_each_fullref_in()`, namely the part of pattern preceding the
1845 * first glob character. (Note that `for_each_fullref_in()` is
1846 * perfectly happy working with a prefix that doesn't end at a
1847 * pathname component boundary.)
1849 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1851 const char *p;
1853 for (p = pattern; *p && !is_glob_special(*p); p++)
1856 strbuf_add(out, pattern, p - pattern);
1860 * This is the same as for_each_fullref_in(), but it tries to iterate
1861 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1862 * pattern match, so the callback still has to match each ref individually.
1864 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1865 each_ref_fn cb,
1866 void *cb_data,
1867 int broken)
1869 struct strbuf prefix = STRBUF_INIT;
1870 int ret;
1872 if (!filter->match_as_path) {
1874 * in this case, the patterns are applied after
1875 * prefixes like "refs/heads/" etc. are stripped off,
1876 * so we have to look at everything:
1878 return for_each_fullref_in("", cb, cb_data, broken);
1881 if (!filter->name_patterns[0]) {
1882 /* no patterns; we have to look at everything */
1883 return for_each_fullref_in("", cb, cb_data, broken);
1886 if (filter->name_patterns[1]) {
1888 * multiple patterns; in theory this could still work as long
1889 * as the patterns are disjoint. We'd just make multiple calls
1890 * to for_each_ref(). But if they're not disjoint, we'd end up
1891 * reporting the same ref multiple times. So let's punt on that
1892 * for now.
1894 return for_each_fullref_in("", cb, cb_data, broken);
1897 find_longest_prefix(&prefix, filter->name_patterns[0]);
1899 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1900 strbuf_release(&prefix);
1901 return ret;
1905 * Given a ref (sha1, refname), check if the ref belongs to the array
1906 * of sha1s. If the given ref is a tag, check if the given tag points
1907 * at one of the sha1s in the given sha1 array.
1908 * the given sha1_array.
1909 * NEEDSWORK:
1910 * 1. Only a single level of inderection is obtained, we might want to
1911 * change this to account for multiple levels (e.g. annotated tags
1912 * pointing to annotated tags pointing to a commit.)
1913 * 2. As the refs are cached we might know what refname peels to without
1914 * the need to parse the object via parse_object(). peel_ref() might be a
1915 * more efficient alternative to obtain the pointee.
1917 static const struct object_id *match_points_at(struct oid_array *points_at,
1918 const struct object_id *oid,
1919 const char *refname)
1921 const struct object_id *tagged_oid = NULL;
1922 struct object *obj;
1924 if (oid_array_lookup(points_at, oid) >= 0)
1925 return oid;
1926 obj = parse_object(oid);
1927 if (!obj)
1928 die(_("malformed object at '%s'"), refname);
1929 if (obj->type == OBJ_TAG)
1930 tagged_oid = &((struct tag *)obj)->tagged->oid;
1931 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1932 return tagged_oid;
1933 return NULL;
1937 * Allocate space for a new ref_array_item and copy the name and oid to it.
1939 * Callers can then fill in other struct members at their leisure.
1941 static struct ref_array_item *new_ref_array_item(const char *refname,
1942 const struct object_id *oid)
1944 struct ref_array_item *ref;
1946 FLEX_ALLOC_STR(ref, refname, refname);
1947 oidcpy(&ref->objectname, oid);
1949 return ref;
1952 struct ref_array_item *ref_array_push(struct ref_array *array,
1953 const char *refname,
1954 const struct object_id *oid)
1956 struct ref_array_item *ref = new_ref_array_item(refname, oid);
1958 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1959 array->items[array->nr++] = ref;
1961 return ref;
1964 static int ref_kind_from_refname(const char *refname)
1966 unsigned int i;
1968 static struct {
1969 const char *prefix;
1970 unsigned int kind;
1971 } ref_kind[] = {
1972 { "refs/heads/" , FILTER_REFS_BRANCHES },
1973 { "refs/remotes/" , FILTER_REFS_REMOTES },
1974 { "refs/tags/", FILTER_REFS_TAGS}
1977 if (!strcmp(refname, "HEAD"))
1978 return FILTER_REFS_DETACHED_HEAD;
1980 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1981 if (starts_with(refname, ref_kind[i].prefix))
1982 return ref_kind[i].kind;
1985 return FILTER_REFS_OTHERS;
1988 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1990 if (filter->kind == FILTER_REFS_BRANCHES ||
1991 filter->kind == FILTER_REFS_REMOTES ||
1992 filter->kind == FILTER_REFS_TAGS)
1993 return filter->kind;
1994 return ref_kind_from_refname(refname);
1998 * A call-back given to for_each_ref(). Filter refs and keep them for
1999 * later object processing.
2001 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2003 struct ref_filter_cbdata *ref_cbdata = cb_data;
2004 struct ref_filter *filter = ref_cbdata->filter;
2005 struct ref_array_item *ref;
2006 struct commit *commit = NULL;
2007 unsigned int kind;
2009 if (flag & REF_BAD_NAME) {
2010 warning(_("ignoring ref with broken name %s"), refname);
2011 return 0;
2014 if (flag & REF_ISBROKEN) {
2015 warning(_("ignoring broken ref %s"), refname);
2016 return 0;
2019 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2020 kind = filter_ref_kind(filter, refname);
2021 if (!(kind & filter->kind))
2022 return 0;
2024 if (!filter_pattern_match(filter, refname))
2025 return 0;
2027 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2028 return 0;
2031 * A merge filter is applied on refs pointing to commits. Hence
2032 * obtain the commit using the 'oid' available and discard all
2033 * non-commits early. The actual filtering is done later.
2035 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2036 commit = lookup_commit_reference_gently(oid, 1);
2037 if (!commit)
2038 return 0;
2039 /* We perform the filtering for the '--contains' option... */
2040 if (filter->with_commit &&
2041 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2042 return 0;
2043 /* ...or for the `--no-contains' option */
2044 if (filter->no_commit &&
2045 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2046 return 0;
2050 * We do not open the object yet; sort may only need refname
2051 * to do its job and the resulting list may yet to be pruned
2052 * by maxcount logic.
2054 ref = ref_array_push(ref_cbdata->array, refname, oid);
2055 ref->commit = commit;
2056 ref->flag = flag;
2057 ref->kind = kind;
2059 return 0;
2062 /* Free memory allocated for a ref_array_item */
2063 static void free_array_item(struct ref_array_item *item)
2065 free((char *)item->symref);
2066 free(item);
2069 /* Free all memory allocated for ref_array */
2070 void ref_array_clear(struct ref_array *array)
2072 int i;
2074 for (i = 0; i < array->nr; i++)
2075 free_array_item(array->items[i]);
2076 FREE_AND_NULL(array->items);
2077 array->nr = array->alloc = 0;
2080 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2082 struct rev_info revs;
2083 int i, old_nr;
2084 struct ref_filter *filter = ref_cbdata->filter;
2085 struct ref_array *array = ref_cbdata->array;
2086 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2088 init_revisions(&revs, NULL);
2090 for (i = 0; i < array->nr; i++) {
2091 struct ref_array_item *item = array->items[i];
2092 add_pending_object(&revs, &item->commit->object, item->refname);
2093 to_clear[i] = item->commit;
2096 filter->merge_commit->object.flags |= UNINTERESTING;
2097 add_pending_object(&revs, &filter->merge_commit->object, "");
2099 revs.limited = 1;
2100 if (prepare_revision_walk(&revs))
2101 die(_("revision walk setup failed"));
2103 old_nr = array->nr;
2104 array->nr = 0;
2106 for (i = 0; i < old_nr; i++) {
2107 struct ref_array_item *item = array->items[i];
2108 struct commit *commit = item->commit;
2110 int is_merged = !!(commit->object.flags & UNINTERESTING);
2112 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2113 array->items[array->nr++] = array->items[i];
2114 else
2115 free_array_item(item);
2118 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2119 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2120 free(to_clear);
2124 * API for filtering a set of refs. Based on the type of refs the user
2125 * has requested, we iterate through those refs and apply filters
2126 * as per the given ref_filter structure and finally store the
2127 * filtered refs in the ref_array structure.
2129 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2131 struct ref_filter_cbdata ref_cbdata;
2132 int ret = 0;
2133 unsigned int broken = 0;
2135 ref_cbdata.array = array;
2136 ref_cbdata.filter = filter;
2138 if (type & FILTER_REFS_INCLUDE_BROKEN)
2139 broken = 1;
2140 filter->kind = type & FILTER_REFS_KIND_MASK;
2142 init_contains_cache(&ref_cbdata.contains_cache);
2143 init_contains_cache(&ref_cbdata.no_contains_cache);
2145 /* Simple per-ref filtering */
2146 if (!filter->kind)
2147 die("filter_refs: invalid type");
2148 else {
2150 * For common cases where we need only branches or remotes or tags,
2151 * we only iterate through those refs. If a mix of refs is needed,
2152 * we iterate over all refs and filter out required refs with the help
2153 * of filter_ref_kind().
2155 if (filter->kind == FILTER_REFS_BRANCHES)
2156 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2157 else if (filter->kind == FILTER_REFS_REMOTES)
2158 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2159 else if (filter->kind == FILTER_REFS_TAGS)
2160 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2161 else if (filter->kind & FILTER_REFS_ALL)
2162 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2163 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2164 head_ref(ref_filter_handler, &ref_cbdata);
2167 clear_contains_cache(&ref_cbdata.contains_cache);
2168 clear_contains_cache(&ref_cbdata.no_contains_cache);
2170 /* Filters that need revision walking */
2171 if (filter->merge_commit)
2172 do_merge_filter(&ref_cbdata);
2174 return ret;
2177 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2179 struct atom_value *va, *vb;
2180 int cmp;
2181 cmp_type cmp_type = used_atom[s->atom].type;
2182 int (*cmp_fn)(const char *, const char *);
2183 struct strbuf err = STRBUF_INIT;
2185 if (get_ref_atom_value(a, s->atom, &va, &err))
2186 die("%s", err.buf);
2187 if (get_ref_atom_value(b, s->atom, &vb, &err))
2188 die("%s", err.buf);
2189 strbuf_release(&err);
2190 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2191 if (s->version)
2192 cmp = versioncmp(va->s, vb->s);
2193 else if (cmp_type == FIELD_STR)
2194 cmp = cmp_fn(va->s, vb->s);
2195 else {
2196 if (va->value < vb->value)
2197 cmp = -1;
2198 else if (va->value == vb->value)
2199 cmp = cmp_fn(a->refname, b->refname);
2200 else
2201 cmp = 1;
2204 return (s->reverse) ? -cmp : cmp;
2207 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2209 struct ref_array_item *a = *((struct ref_array_item **)a_);
2210 struct ref_array_item *b = *((struct ref_array_item **)b_);
2211 struct ref_sorting *s;
2213 for (s = ref_sorting; s; s = s->next) {
2214 int cmp = cmp_ref_sorting(s, a, b);
2215 if (cmp)
2216 return cmp;
2218 return 0;
2221 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2223 QSORT_S(array->items, array->nr, compare_refs, sorting);
2226 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2228 struct strbuf *s = &state->stack->output;
2230 while (*cp && (!ep || cp < ep)) {
2231 if (*cp == '%') {
2232 if (cp[1] == '%')
2233 cp++;
2234 else {
2235 int ch = hex2chr(cp + 1);
2236 if (0 <= ch) {
2237 strbuf_addch(s, ch);
2238 cp += 3;
2239 continue;
2243 strbuf_addch(s, *cp);
2244 cp++;
2248 int format_ref_array_item(struct ref_array_item *info,
2249 const struct ref_format *format,
2250 struct strbuf *final_buf,
2251 struct strbuf *error_buf)
2253 const char *cp, *sp, *ep;
2254 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2256 state.quote_style = format->quote_style;
2257 push_stack_element(&state.stack);
2259 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2260 struct atom_value *atomv;
2261 int pos;
2263 ep = strchr(sp, ')');
2264 if (cp < sp)
2265 append_literal(cp, sp, &state);
2266 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2267 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2268 atomv->handler(atomv, &state, error_buf)) {
2269 pop_stack_element(&state.stack);
2270 return -1;
2273 if (*cp) {
2274 sp = cp + strlen(cp);
2275 append_literal(cp, sp, &state);
2277 if (format->need_color_reset_at_eol) {
2278 struct atom_value resetv;
2279 resetv.s = GIT_COLOR_RESET;
2280 if (append_atom(&resetv, &state, error_buf)) {
2281 pop_stack_element(&state.stack);
2282 return -1;
2285 if (state.stack->prev) {
2286 pop_stack_element(&state.stack);
2287 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2289 strbuf_addbuf(final_buf, &state.stack->output);
2290 pop_stack_element(&state.stack);
2291 return 0;
2294 void show_ref_array_item(struct ref_array_item *info,
2295 const struct ref_format *format)
2297 struct strbuf final_buf = STRBUF_INIT;
2298 struct strbuf error_buf = STRBUF_INIT;
2300 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2301 die("%s", error_buf.buf);
2302 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2303 strbuf_release(&error_buf);
2304 strbuf_release(&final_buf);
2305 putchar('\n');
2308 void pretty_print_ref(const char *name, const struct object_id *oid,
2309 const struct ref_format *format)
2311 struct ref_array_item *ref_item;
2312 ref_item = new_ref_array_item(name, oid);
2313 ref_item->kind = ref_kind_from_refname(name);
2314 show_ref_array_item(ref_item, format);
2315 free_array_item(ref_item);
2318 static int parse_sorting_atom(const char *atom)
2321 * This parses an atom using a dummy ref_format, since we don't
2322 * actually care about the formatting details.
2324 struct ref_format dummy = REF_FORMAT_INIT;
2325 const char *end = atom + strlen(atom);
2326 struct strbuf err = STRBUF_INIT;
2327 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2328 if (res < 0)
2329 die("%s", err.buf);
2330 strbuf_release(&err);
2331 return res;
2334 /* If no sorting option is given, use refname to sort as default */
2335 struct ref_sorting *ref_default_sorting(void)
2337 static const char cstr_name[] = "refname";
2339 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2341 sorting->next = NULL;
2342 sorting->atom = parse_sorting_atom(cstr_name);
2343 return sorting;
2346 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2348 struct ref_sorting *s;
2350 s = xcalloc(1, sizeof(*s));
2351 s->next = *sorting_tail;
2352 *sorting_tail = s;
2354 if (*arg == '-') {
2355 s->reverse = 1;
2356 arg++;
2358 if (skip_prefix(arg, "version:", &arg) ||
2359 skip_prefix(arg, "v:", &arg))
2360 s->version = 1;
2361 s->atom = parse_sorting_atom(arg);
2364 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2366 if (!arg) /* should --no-sort void the list ? */
2367 return -1;
2368 parse_ref_sorting(opt->value, arg);
2369 return 0;
2372 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2374 struct ref_filter *rf = opt->value;
2375 struct object_id oid;
2376 int no_merged = starts_with(opt->long_name, "no");
2378 if (rf->merge) {
2379 if (no_merged) {
2380 return opterror(opt, "is incompatible with --merged", 0);
2381 } else {
2382 return opterror(opt, "is incompatible with --no-merged", 0);
2386 rf->merge = no_merged
2387 ? REF_FILTER_MERGED_OMIT
2388 : REF_FILTER_MERGED_INCLUDE;
2390 if (get_oid(arg, &oid))
2391 die(_("malformed object name %s"), arg);
2393 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2394 if (!rf->merge_commit)
2395 return opterror(opt, "must point to a commit", 0);
2397 return 0;