Merge branch 'nd/complete-config-vars'
[alt-git.git] / ref-filter.c
blobfa3685d91f0464a28ef13102a1672215d4ec5177
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;
45 struct align {
46 align_type position;
47 unsigned int width;
50 struct if_then_else {
51 cmp_status cmp_status;
52 const char *str;
53 unsigned int then_atom_seen : 1,
54 else_atom_seen : 1,
55 condition_satisfied : 1;
58 struct refname_atom {
59 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
60 int lstrip, rstrip;
64 * An atom is a valid field atom listed below, possibly prefixed with
65 * a "*" to denote deref_tag().
67 * We parse given format string and sort specifiers, and make a list
68 * of properties that we need to extract out of objects. ref_array_item
69 * structure will hold an array of values extracted that can be
70 * indexed with the "atom number", which is an index into this
71 * array.
73 static struct used_atom {
74 const char *name;
75 cmp_type type;
76 union {
77 char color[COLOR_MAXLEN];
78 struct align align;
79 struct {
80 enum {
81 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
82 } option;
83 struct refname_atom refname;
84 unsigned int nobracket : 1, push : 1, push_remote : 1;
85 } remote_ref;
86 struct {
87 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
88 struct process_trailer_options trailer_opts;
89 unsigned int nlines;
90 } contents;
91 struct {
92 cmp_status cmp_status;
93 const char *str;
94 } if_then_else;
95 struct {
96 enum { O_FULL, O_LENGTH, O_SHORT } option;
97 unsigned int length;
98 } objectname;
99 struct refname_atom refname;
100 char *head;
101 } u;
102 } *used_atom;
103 static int used_atom_cnt, need_tagged, need_symref;
106 * Expand string, append it to strbuf *sb, then return error code ret.
107 * Allow to save few lines of code.
109 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
111 va_list ap;
112 va_start(ap, fmt);
113 strbuf_vaddf(sb, fmt, ap);
114 va_end(ap);
115 return ret;
118 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
119 const char *color_value, struct strbuf *err)
121 if (!color_value)
122 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
123 if (color_parse(color_value, atom->u.color) < 0)
124 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
125 color_value);
127 * We check this after we've parsed the color, which lets us complain
128 * about syntactically bogus color names even if they won't be used.
130 if (!want_color(format->use_color))
131 color_parse("", atom->u.color);
132 return 0;
135 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
136 const char *name, struct strbuf *err)
138 if (!arg)
139 atom->option = R_NORMAL;
140 else if (!strcmp(arg, "short"))
141 atom->option = R_SHORT;
142 else if (skip_prefix(arg, "lstrip=", &arg) ||
143 skip_prefix(arg, "strip=", &arg)) {
144 atom->option = R_LSTRIP;
145 if (strtol_i(arg, 10, &atom->lstrip))
146 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
147 } else if (skip_prefix(arg, "rstrip=", &arg)) {
148 atom->option = R_RSTRIP;
149 if (strtol_i(arg, 10, &atom->rstrip))
150 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
151 } else
152 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
153 return 0;
156 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
157 const char *arg, struct strbuf *err)
159 struct string_list params = STRING_LIST_INIT_DUP;
160 int i;
162 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
163 atom->u.remote_ref.push = 1;
165 if (!arg) {
166 atom->u.remote_ref.option = RR_REF;
167 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
168 arg, atom->name, err);
171 atom->u.remote_ref.nobracket = 0;
172 string_list_split(&params, arg, ',', -1);
174 for (i = 0; i < params.nr; i++) {
175 const char *s = params.items[i].string;
177 if (!strcmp(s, "track"))
178 atom->u.remote_ref.option = RR_TRACK;
179 else if (!strcmp(s, "trackshort"))
180 atom->u.remote_ref.option = RR_TRACKSHORT;
181 else if (!strcmp(s, "nobracket"))
182 atom->u.remote_ref.nobracket = 1;
183 else if (!strcmp(s, "remotename")) {
184 atom->u.remote_ref.option = RR_REMOTE_NAME;
185 atom->u.remote_ref.push_remote = 1;
186 } else if (!strcmp(s, "remoteref")) {
187 atom->u.remote_ref.option = RR_REMOTE_REF;
188 atom->u.remote_ref.push_remote = 1;
189 } else {
190 atom->u.remote_ref.option = RR_REF;
191 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
192 arg, atom->name, err)) {
193 string_list_clear(&params, 0);
194 return -1;
199 string_list_clear(&params, 0);
200 return 0;
203 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
204 const char *arg, struct strbuf *err)
206 if (arg)
207 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
208 atom->u.contents.option = C_BODY_DEP;
209 return 0;
212 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
213 const char *arg, struct strbuf *err)
215 if (arg)
216 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
217 atom->u.contents.option = C_SUB;
218 return 0;
221 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
222 const char *arg, struct strbuf *err)
224 struct string_list params = STRING_LIST_INIT_DUP;
225 int i;
227 if (arg) {
228 string_list_split(&params, arg, ',', -1);
229 for (i = 0; i < params.nr; i++) {
230 const char *s = params.items[i].string;
231 if (!strcmp(s, "unfold"))
232 atom->u.contents.trailer_opts.unfold = 1;
233 else if (!strcmp(s, "only"))
234 atom->u.contents.trailer_opts.only_trailers = 1;
235 else {
236 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
237 string_list_clear(&params, 0);
238 return -1;
242 atom->u.contents.option = C_TRAILERS;
243 string_list_clear(&params, 0);
244 return 0;
247 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
248 const char *arg, struct strbuf *err)
250 if (!arg)
251 atom->u.contents.option = C_BARE;
252 else if (!strcmp(arg, "body"))
253 atom->u.contents.option = C_BODY;
254 else if (!strcmp(arg, "signature"))
255 atom->u.contents.option = C_SIG;
256 else if (!strcmp(arg, "subject"))
257 atom->u.contents.option = C_SUB;
258 else if (skip_prefix(arg, "trailers", &arg)) {
259 skip_prefix(arg, ":", &arg);
260 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
261 return -1;
262 } else if (skip_prefix(arg, "lines=", &arg)) {
263 atom->u.contents.option = C_LINES;
264 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
265 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
266 } else
267 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
268 return 0;
271 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
272 const char *arg, struct strbuf *err)
274 if (!arg)
275 atom->u.objectname.option = O_FULL;
276 else if (!strcmp(arg, "short"))
277 atom->u.objectname.option = O_SHORT;
278 else if (skip_prefix(arg, "short=", &arg)) {
279 atom->u.objectname.option = O_LENGTH;
280 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
281 atom->u.objectname.length == 0)
282 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
283 if (atom->u.objectname.length < MINIMUM_ABBREV)
284 atom->u.objectname.length = MINIMUM_ABBREV;
285 } else
286 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
287 return 0;
290 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
291 const char *arg, struct strbuf *err)
293 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
296 static align_type parse_align_position(const char *s)
298 if (!strcmp(s, "right"))
299 return ALIGN_RIGHT;
300 else if (!strcmp(s, "middle"))
301 return ALIGN_MIDDLE;
302 else if (!strcmp(s, "left"))
303 return ALIGN_LEFT;
304 return -1;
307 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
308 const char *arg, struct strbuf *err)
310 struct align *align = &atom->u.align;
311 struct string_list params = STRING_LIST_INIT_DUP;
312 int i;
313 unsigned int width = ~0U;
315 if (!arg)
316 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
318 align->position = ALIGN_LEFT;
320 string_list_split(&params, arg, ',', -1);
321 for (i = 0; i < params.nr; i++) {
322 const char *s = params.items[i].string;
323 int position;
325 if (skip_prefix(s, "position=", &s)) {
326 position = parse_align_position(s);
327 if (position < 0) {
328 strbuf_addf(err, _("unrecognized position:%s"), s);
329 string_list_clear(&params, 0);
330 return -1;
332 align->position = position;
333 } else if (skip_prefix(s, "width=", &s)) {
334 if (strtoul_ui(s, 10, &width)) {
335 strbuf_addf(err, _("unrecognized width:%s"), s);
336 string_list_clear(&params, 0);
337 return -1;
339 } else if (!strtoul_ui(s, 10, &width))
341 else if ((position = parse_align_position(s)) >= 0)
342 align->position = position;
343 else {
344 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
345 string_list_clear(&params, 0);
346 return -1;
350 if (width == ~0U) {
351 string_list_clear(&params, 0);
352 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
354 align->width = width;
355 string_list_clear(&params, 0);
356 return 0;
359 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
360 const char *arg, struct strbuf *err)
362 if (!arg) {
363 atom->u.if_then_else.cmp_status = COMPARE_NONE;
364 return 0;
365 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
366 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
367 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
368 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
369 } else
370 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
371 return 0;
374 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
375 const char *arg, struct strbuf *unused_err)
377 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
378 return 0;
381 static struct {
382 const char *name;
383 cmp_type cmp_type;
384 int (*parser)(const struct ref_format *format, struct used_atom *atom,
385 const char *arg, struct strbuf *err);
386 } valid_atom[] = {
387 { "refname" , FIELD_STR, refname_atom_parser },
388 { "objecttype" },
389 { "objectsize", FIELD_ULONG },
390 { "objectname", FIELD_STR, objectname_atom_parser },
391 { "tree" },
392 { "parent" },
393 { "numparent", FIELD_ULONG },
394 { "object" },
395 { "type" },
396 { "tag" },
397 { "author" },
398 { "authorname" },
399 { "authoremail" },
400 { "authordate", FIELD_TIME },
401 { "committer" },
402 { "committername" },
403 { "committeremail" },
404 { "committerdate", FIELD_TIME },
405 { "tagger" },
406 { "taggername" },
407 { "taggeremail" },
408 { "taggerdate", FIELD_TIME },
409 { "creator" },
410 { "creatordate", FIELD_TIME },
411 { "subject", FIELD_STR, subject_atom_parser },
412 { "body", FIELD_STR, body_atom_parser },
413 { "trailers", FIELD_STR, trailers_atom_parser },
414 { "contents", FIELD_STR, contents_atom_parser },
415 { "upstream", FIELD_STR, remote_ref_atom_parser },
416 { "push", FIELD_STR, remote_ref_atom_parser },
417 { "symref", FIELD_STR, refname_atom_parser },
418 { "flag" },
419 { "HEAD", FIELD_STR, head_atom_parser },
420 { "color", FIELD_STR, color_atom_parser },
421 { "align", FIELD_STR, align_atom_parser },
422 { "end" },
423 { "if", FIELD_STR, if_atom_parser },
424 { "then" },
425 { "else" },
428 #define REF_FORMATTING_STATE_INIT { 0, NULL }
430 struct ref_formatting_stack {
431 struct ref_formatting_stack *prev;
432 struct strbuf output;
433 void (*at_end)(struct ref_formatting_stack **stack);
434 void *at_end_data;
437 struct ref_formatting_state {
438 int quote_style;
439 struct ref_formatting_stack *stack;
442 struct atom_value {
443 const char *s;
444 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
445 struct strbuf *err);
446 uintmax_t value; /* used for sorting when not FIELD_STR */
447 struct used_atom *atom;
451 * Used to parse format string and sort specifiers
453 static int parse_ref_filter_atom(const struct ref_format *format,
454 const char *atom, const char *ep,
455 struct strbuf *err)
457 const char *sp;
458 const char *arg;
459 int i, at, atom_len;
461 sp = atom;
462 if (*sp == '*' && sp < ep)
463 sp++; /* deref */
464 if (ep <= sp)
465 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
466 (int)(ep-atom), atom);
468 /* Do we have the atom already used elsewhere? */
469 for (i = 0; i < used_atom_cnt; i++) {
470 int len = strlen(used_atom[i].name);
471 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
472 return i;
476 * If the atom name has a colon, strip it and everything after
477 * it off - it specifies the format for this entry, and
478 * shouldn't be used for checking against the valid_atom
479 * table.
481 arg = memchr(sp, ':', ep - sp);
482 atom_len = (arg ? arg : ep) - sp;
484 /* Is the atom a valid one? */
485 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
486 int len = strlen(valid_atom[i].name);
487 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
488 break;
491 if (ARRAY_SIZE(valid_atom) <= i)
492 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
493 (int)(ep-atom), atom);
495 /* Add it in, including the deref prefix */
496 at = used_atom_cnt;
497 used_atom_cnt++;
498 REALLOC_ARRAY(used_atom, used_atom_cnt);
499 used_atom[at].name = xmemdupz(atom, ep - atom);
500 used_atom[at].type = valid_atom[i].cmp_type;
501 if (arg) {
502 arg = used_atom[at].name + (arg - atom) + 1;
503 if (!*arg) {
505 * Treat empty sub-arguments list as NULL (i.e.,
506 * "%(atom:)" is equivalent to "%(atom)").
508 arg = NULL;
511 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
512 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
513 return -1;
514 if (*atom == '*')
515 need_tagged = 1;
516 if (!strcmp(valid_atom[i].name, "symref"))
517 need_symref = 1;
518 return at;
521 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
523 switch (quote_style) {
524 case QUOTE_NONE:
525 strbuf_addstr(s, str);
526 break;
527 case QUOTE_SHELL:
528 sq_quote_buf(s, str);
529 break;
530 case QUOTE_PERL:
531 perl_quote_buf(s, str);
532 break;
533 case QUOTE_PYTHON:
534 python_quote_buf(s, str);
535 break;
536 case QUOTE_TCL:
537 tcl_quote_buf(s, str);
538 break;
542 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
543 struct strbuf *unused_err)
546 * Quote formatting is only done when the stack has a single
547 * element. Otherwise quote formatting is done on the
548 * element's entire output strbuf when the %(end) atom is
549 * encountered.
551 if (!state->stack->prev)
552 quote_formatting(&state->stack->output, v->s, state->quote_style);
553 else
554 strbuf_addstr(&state->stack->output, v->s);
555 return 0;
558 static void push_stack_element(struct ref_formatting_stack **stack)
560 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
562 strbuf_init(&s->output, 0);
563 s->prev = *stack;
564 *stack = s;
567 static void pop_stack_element(struct ref_formatting_stack **stack)
569 struct ref_formatting_stack *current = *stack;
570 struct ref_formatting_stack *prev = current->prev;
572 if (prev)
573 strbuf_addbuf(&prev->output, &current->output);
574 strbuf_release(&current->output);
575 free(current);
576 *stack = prev;
579 static void end_align_handler(struct ref_formatting_stack **stack)
581 struct ref_formatting_stack *cur = *stack;
582 struct align *align = (struct align *)cur->at_end_data;
583 struct strbuf s = STRBUF_INIT;
585 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
586 strbuf_swap(&cur->output, &s);
587 strbuf_release(&s);
590 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
591 struct strbuf *unused_err)
593 struct ref_formatting_stack *new_stack;
595 push_stack_element(&state->stack);
596 new_stack = state->stack;
597 new_stack->at_end = end_align_handler;
598 new_stack->at_end_data = &atomv->atom->u.align;
599 return 0;
602 static void if_then_else_handler(struct ref_formatting_stack **stack)
604 struct ref_formatting_stack *cur = *stack;
605 struct ref_formatting_stack *prev = cur->prev;
606 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
608 if (!if_then_else->then_atom_seen)
609 die(_("format: %%(if) atom used without a %%(then) atom"));
611 if (if_then_else->else_atom_seen) {
613 * There is an %(else) atom: we need to drop one state from the
614 * stack, either the %(else) branch if the condition is satisfied, or
615 * the %(then) branch if it isn't.
617 if (if_then_else->condition_satisfied) {
618 strbuf_reset(&cur->output);
619 pop_stack_element(&cur);
620 } else {
621 strbuf_swap(&cur->output, &prev->output);
622 strbuf_reset(&cur->output);
623 pop_stack_element(&cur);
625 } else if (!if_then_else->condition_satisfied) {
627 * No %(else) atom: just drop the %(then) branch if the
628 * condition is not satisfied.
630 strbuf_reset(&cur->output);
633 *stack = cur;
634 free(if_then_else);
637 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
638 struct strbuf *unused_err)
640 struct ref_formatting_stack *new_stack;
641 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
643 if_then_else->str = atomv->atom->u.if_then_else.str;
644 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
646 push_stack_element(&state->stack);
647 new_stack = state->stack;
648 new_stack->at_end = if_then_else_handler;
649 new_stack->at_end_data = if_then_else;
650 return 0;
653 static int is_empty(const char *s)
655 while (*s != '\0') {
656 if (!isspace(*s))
657 return 0;
658 s++;
660 return 1;
663 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
664 struct strbuf *err)
666 struct ref_formatting_stack *cur = state->stack;
667 struct if_then_else *if_then_else = NULL;
669 if (cur->at_end == if_then_else_handler)
670 if_then_else = (struct if_then_else *)cur->at_end_data;
671 if (!if_then_else)
672 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
673 if (if_then_else->then_atom_seen)
674 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
675 if (if_then_else->else_atom_seen)
676 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
677 if_then_else->then_atom_seen = 1;
679 * If the 'equals' or 'notequals' attribute is used then
680 * perform the required comparison. If not, only non-empty
681 * strings satisfy the 'if' condition.
683 if (if_then_else->cmp_status == COMPARE_EQUAL) {
684 if (!strcmp(if_then_else->str, cur->output.buf))
685 if_then_else->condition_satisfied = 1;
686 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
687 if (strcmp(if_then_else->str, cur->output.buf))
688 if_then_else->condition_satisfied = 1;
689 } else if (cur->output.len && !is_empty(cur->output.buf))
690 if_then_else->condition_satisfied = 1;
691 strbuf_reset(&cur->output);
692 return 0;
695 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
696 struct strbuf *err)
698 struct ref_formatting_stack *prev = state->stack;
699 struct if_then_else *if_then_else = NULL;
701 if (prev->at_end == if_then_else_handler)
702 if_then_else = (struct if_then_else *)prev->at_end_data;
703 if (!if_then_else)
704 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
705 if (!if_then_else->then_atom_seen)
706 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
707 if (if_then_else->else_atom_seen)
708 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
709 if_then_else->else_atom_seen = 1;
710 push_stack_element(&state->stack);
711 state->stack->at_end_data = prev->at_end_data;
712 state->stack->at_end = prev->at_end;
713 return 0;
716 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
717 struct strbuf *err)
719 struct ref_formatting_stack *current = state->stack;
720 struct strbuf s = STRBUF_INIT;
722 if (!current->at_end)
723 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
724 current->at_end(&state->stack);
726 /* Stack may have been popped within at_end(), hence reset the current pointer */
727 current = state->stack;
730 * Perform quote formatting when the stack element is that of
731 * a supporting atom. If nested then perform quote formatting
732 * only on the topmost supporting atom.
734 if (!current->prev->prev) {
735 quote_formatting(&s, current->output.buf, state->quote_style);
736 strbuf_swap(&current->output, &s);
738 strbuf_release(&s);
739 pop_stack_element(&state->stack);
740 return 0;
744 * In a format string, find the next occurrence of %(atom).
746 static const char *find_next(const char *cp)
748 while (*cp) {
749 if (*cp == '%') {
751 * %( is the start of an atom;
752 * %% is a quoted per-cent.
754 if (cp[1] == '(')
755 return cp;
756 else if (cp[1] == '%')
757 cp++; /* skip over two % */
758 /* otherwise this is a singleton, literal % */
760 cp++;
762 return NULL;
766 * Make sure the format string is well formed, and parse out
767 * the used atoms.
769 int verify_ref_format(struct ref_format *format)
771 const char *cp, *sp;
773 format->need_color_reset_at_eol = 0;
774 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
775 struct strbuf err = STRBUF_INIT;
776 const char *color, *ep = strchr(sp, ')');
777 int at;
779 if (!ep)
780 return error(_("malformed format string %s"), sp);
781 /* sp points at "%(" and ep points at the closing ")" */
782 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
783 if (at < 0)
784 die("%s", err.buf);
785 cp = ep + 1;
787 if (skip_prefix(used_atom[at].name, "color:", &color))
788 format->need_color_reset_at_eol = !!strcmp(color, "reset");
789 strbuf_release(&err);
791 if (format->need_color_reset_at_eol && !want_color(format->use_color))
792 format->need_color_reset_at_eol = 0;
793 return 0;
797 * Given an object name, read the object data and size, and return a
798 * "struct object". If the object data we are returning is also borrowed
799 * by the "struct object" representation, set *eaten as well---it is a
800 * signal from parse_object_buffer to us not to free the buffer.
802 static void *get_obj(const struct object_id *oid, struct object **obj, unsigned long *sz, int *eaten)
804 enum object_type type;
805 void *buf = read_object_file(oid, &type, sz);
807 if (buf)
808 *obj = parse_object_buffer(oid, type, *sz, buf, eaten);
809 else
810 *obj = NULL;
811 return buf;
814 static int grab_objectname(const char *name, const struct object_id *oid,
815 struct atom_value *v, struct used_atom *atom)
817 if (starts_with(name, "objectname")) {
818 if (atom->u.objectname.option == O_SHORT) {
819 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
820 return 1;
821 } else if (atom->u.objectname.option == O_FULL) {
822 v->s = xstrdup(oid_to_hex(oid));
823 return 1;
824 } else if (atom->u.objectname.option == O_LENGTH) {
825 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
826 return 1;
827 } else
828 BUG("unknown %%(objectname) option");
830 return 0;
833 /* See grab_values */
834 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
836 int i;
838 for (i = 0; i < used_atom_cnt; i++) {
839 const char *name = used_atom[i].name;
840 struct atom_value *v = &val[i];
841 if (!!deref != (*name == '*'))
842 continue;
843 if (deref)
844 name++;
845 if (!strcmp(name, "objecttype"))
846 v->s = type_name(obj->type);
847 else if (!strcmp(name, "objectsize")) {
848 v->value = sz;
849 v->s = xstrfmt("%lu", sz);
851 else if (deref)
852 grab_objectname(name, &obj->oid, v, &used_atom[i]);
856 /* See grab_values */
857 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
859 int i;
860 struct tag *tag = (struct tag *) obj;
862 for (i = 0; i < used_atom_cnt; i++) {
863 const char *name = used_atom[i].name;
864 struct atom_value *v = &val[i];
865 if (!!deref != (*name == '*'))
866 continue;
867 if (deref)
868 name++;
869 if (!strcmp(name, "tag"))
870 v->s = tag->tag;
871 else if (!strcmp(name, "type") && tag->tagged)
872 v->s = type_name(tag->tagged->type);
873 else if (!strcmp(name, "object") && tag->tagged)
874 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
878 /* See grab_values */
879 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
881 int i;
882 struct commit *commit = (struct commit *) obj;
884 for (i = 0; i < used_atom_cnt; i++) {
885 const char *name = used_atom[i].name;
886 struct atom_value *v = &val[i];
887 if (!!deref != (*name == '*'))
888 continue;
889 if (deref)
890 name++;
891 if (!strcmp(name, "tree")) {
892 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
894 else if (!strcmp(name, "numparent")) {
895 v->value = commit_list_count(commit->parents);
896 v->s = xstrfmt("%lu", (unsigned long)v->value);
898 else if (!strcmp(name, "parent")) {
899 struct commit_list *parents;
900 struct strbuf s = STRBUF_INIT;
901 for (parents = commit->parents; parents; parents = parents->next) {
902 struct commit *parent = parents->item;
903 if (parents != commit->parents)
904 strbuf_addch(&s, ' ');
905 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
907 v->s = strbuf_detach(&s, NULL);
912 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
914 const char *eol;
915 while (*buf) {
916 if (!strncmp(buf, who, wholen) &&
917 buf[wholen] == ' ')
918 return buf + wholen + 1;
919 eol = strchr(buf, '\n');
920 if (!eol)
921 return "";
922 eol++;
923 if (*eol == '\n')
924 return ""; /* end of header */
925 buf = eol;
927 return "";
930 static const char *copy_line(const char *buf)
932 const char *eol = strchrnul(buf, '\n');
933 return xmemdupz(buf, eol - buf);
936 static const char *copy_name(const char *buf)
938 const char *cp;
939 for (cp = buf; *cp && *cp != '\n'; cp++) {
940 if (!strncmp(cp, " <", 2))
941 return xmemdupz(buf, cp - buf);
943 return "";
946 static const char *copy_email(const char *buf)
948 const char *email = strchr(buf, '<');
949 const char *eoemail;
950 if (!email)
951 return "";
952 eoemail = strchr(email, '>');
953 if (!eoemail)
954 return "";
955 return xmemdupz(email, eoemail + 1 - email);
958 static char *copy_subject(const char *buf, unsigned long len)
960 char *r = xmemdupz(buf, len);
961 int i;
963 for (i = 0; i < len; i++)
964 if (r[i] == '\n')
965 r[i] = ' ';
967 return r;
970 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
972 const char *eoemail = strstr(buf, "> ");
973 char *zone;
974 timestamp_t timestamp;
975 long tz;
976 struct date_mode date_mode = { DATE_NORMAL };
977 const char *formatp;
980 * We got here because atomname ends in "date" or "date<something>";
981 * it's not possible that <something> is not ":<format>" because
982 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
983 * ":" means no format is specified, and use the default.
985 formatp = strchr(atomname, ':');
986 if (formatp != NULL) {
987 formatp++;
988 parse_date_format(formatp, &date_mode);
991 if (!eoemail)
992 goto bad;
993 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
994 if (timestamp == TIME_MAX)
995 goto bad;
996 tz = strtol(zone, NULL, 10);
997 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
998 goto bad;
999 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1000 v->value = timestamp;
1001 return;
1002 bad:
1003 v->s = "";
1004 v->value = 0;
1007 /* See grab_values */
1008 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1010 int i;
1011 int wholen = strlen(who);
1012 const char *wholine = NULL;
1014 for (i = 0; i < used_atom_cnt; i++) {
1015 const char *name = used_atom[i].name;
1016 struct atom_value *v = &val[i];
1017 if (!!deref != (*name == '*'))
1018 continue;
1019 if (deref)
1020 name++;
1021 if (strncmp(who, name, wholen))
1022 continue;
1023 if (name[wholen] != 0 &&
1024 strcmp(name + wholen, "name") &&
1025 strcmp(name + wholen, "email") &&
1026 !starts_with(name + wholen, "date"))
1027 continue;
1028 if (!wholine)
1029 wholine = find_wholine(who, wholen, buf, sz);
1030 if (!wholine)
1031 return; /* no point looking for it */
1032 if (name[wholen] == 0)
1033 v->s = copy_line(wholine);
1034 else if (!strcmp(name + wholen, "name"))
1035 v->s = copy_name(wholine);
1036 else if (!strcmp(name + wholen, "email"))
1037 v->s = copy_email(wholine);
1038 else if (starts_with(name + wholen, "date"))
1039 grab_date(wholine, v, name);
1043 * For a tag or a commit object, if "creator" or "creatordate" is
1044 * requested, do something special.
1046 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1047 return; /* "author" for commit object is not wanted */
1048 if (!wholine)
1049 wholine = find_wholine(who, wholen, buf, sz);
1050 if (!wholine)
1051 return;
1052 for (i = 0; i < used_atom_cnt; i++) {
1053 const char *name = used_atom[i].name;
1054 struct atom_value *v = &val[i];
1055 if (!!deref != (*name == '*'))
1056 continue;
1057 if (deref)
1058 name++;
1060 if (starts_with(name, "creatordate"))
1061 grab_date(wholine, v, name);
1062 else if (!strcmp(name, "creator"))
1063 v->s = copy_line(wholine);
1067 static void find_subpos(const char *buf, unsigned long sz,
1068 const char **sub, unsigned long *sublen,
1069 const char **body, unsigned long *bodylen,
1070 unsigned long *nonsiglen,
1071 const char **sig, unsigned long *siglen)
1073 const char *eol;
1074 /* skip past header until we hit empty line */
1075 while (*buf && *buf != '\n') {
1076 eol = strchrnul(buf, '\n');
1077 if (*eol)
1078 eol++;
1079 buf = eol;
1081 /* skip any empty lines */
1082 while (*buf == '\n')
1083 buf++;
1085 /* parse signature first; we might not even have a subject line */
1086 *sig = buf + parse_signature(buf, strlen(buf));
1087 *siglen = strlen(*sig);
1089 /* subject is first non-empty line */
1090 *sub = buf;
1091 /* subject goes to first empty line */
1092 while (buf < *sig && *buf && *buf != '\n') {
1093 eol = strchrnul(buf, '\n');
1094 if (*eol)
1095 eol++;
1096 buf = eol;
1098 *sublen = buf - *sub;
1099 /* drop trailing newline, if present */
1100 if (*sublen && (*sub)[*sublen - 1] == '\n')
1101 *sublen -= 1;
1103 /* skip any empty lines */
1104 while (*buf == '\n')
1105 buf++;
1106 *body = buf;
1107 *bodylen = strlen(buf);
1108 *nonsiglen = *sig - buf;
1112 * If 'lines' is greater than 0, append that many lines from the given
1113 * 'buf' of length 'size' to the given strbuf.
1115 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1117 int i;
1118 const char *sp, *eol;
1119 size_t len;
1121 sp = buf;
1123 for (i = 0; i < lines && sp < buf + size; i++) {
1124 if (i)
1125 strbuf_addstr(out, "\n ");
1126 eol = memchr(sp, '\n', size - (sp - buf));
1127 len = eol ? eol - sp : size - (sp - buf);
1128 strbuf_add(out, sp, len);
1129 if (!eol)
1130 break;
1131 sp = eol + 1;
1135 /* See grab_values */
1136 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1138 int i;
1139 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1140 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1142 for (i = 0; i < used_atom_cnt; i++) {
1143 struct used_atom *atom = &used_atom[i];
1144 const char *name = atom->name;
1145 struct atom_value *v = &val[i];
1146 if (!!deref != (*name == '*'))
1147 continue;
1148 if (deref)
1149 name++;
1150 if (strcmp(name, "subject") &&
1151 strcmp(name, "body") &&
1152 !starts_with(name, "trailers") &&
1153 !starts_with(name, "contents"))
1154 continue;
1155 if (!subpos)
1156 find_subpos(buf, sz,
1157 &subpos, &sublen,
1158 &bodypos, &bodylen, &nonsiglen,
1159 &sigpos, &siglen);
1161 if (atom->u.contents.option == C_SUB)
1162 v->s = copy_subject(subpos, sublen);
1163 else if (atom->u.contents.option == C_BODY_DEP)
1164 v->s = xmemdupz(bodypos, bodylen);
1165 else if (atom->u.contents.option == C_BODY)
1166 v->s = xmemdupz(bodypos, nonsiglen);
1167 else if (atom->u.contents.option == C_SIG)
1168 v->s = xmemdupz(sigpos, siglen);
1169 else if (atom->u.contents.option == C_LINES) {
1170 struct strbuf s = STRBUF_INIT;
1171 const char *contents_end = bodylen + bodypos - siglen;
1173 /* Size is the length of the message after removing the signature */
1174 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1175 v->s = strbuf_detach(&s, NULL);
1176 } else if (atom->u.contents.option == C_TRAILERS) {
1177 struct strbuf s = STRBUF_INIT;
1179 /* Format the trailer info according to the trailer_opts given */
1180 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1182 v->s = strbuf_detach(&s, NULL);
1183 } else if (atom->u.contents.option == C_BARE)
1184 v->s = xstrdup(subpos);
1189 * We want to have empty print-string for field requests
1190 * that do not apply (e.g. "authordate" for a tag object)
1192 static void fill_missing_values(struct atom_value *val)
1194 int i;
1195 for (i = 0; i < used_atom_cnt; i++) {
1196 struct atom_value *v = &val[i];
1197 if (v->s == NULL)
1198 v->s = "";
1203 * val is a list of atom_value to hold returned values. Extract
1204 * the values for atoms in used_atom array out of (obj, buf, sz).
1205 * when deref is false, (obj, buf, sz) is the object that is
1206 * pointed at by the ref itself; otherwise it is the object the
1207 * ref (which is a tag) refers to.
1209 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1211 grab_common_values(val, deref, obj, buf, sz);
1212 switch (obj->type) {
1213 case OBJ_TAG:
1214 grab_tag_values(val, deref, obj, buf, sz);
1215 grab_sub_body_contents(val, deref, obj, buf, sz);
1216 grab_person("tagger", val, deref, obj, buf, sz);
1217 break;
1218 case OBJ_COMMIT:
1219 grab_commit_values(val, deref, obj, buf, sz);
1220 grab_sub_body_contents(val, deref, obj, buf, sz);
1221 grab_person("author", val, deref, obj, buf, sz);
1222 grab_person("committer", val, deref, obj, buf, sz);
1223 break;
1224 case OBJ_TREE:
1225 /* grab_tree_values(val, deref, obj, buf, sz); */
1226 break;
1227 case OBJ_BLOB:
1228 /* grab_blob_values(val, deref, obj, buf, sz); */
1229 break;
1230 default:
1231 die("Eh? Object of type %d?", obj->type);
1235 static inline char *copy_advance(char *dst, const char *src)
1237 while (*src)
1238 *dst++ = *src++;
1239 return dst;
1242 static const char *lstrip_ref_components(const char *refname, int len)
1244 long remaining = len;
1245 const char *start = refname;
1247 if (len < 0) {
1248 int i;
1249 const char *p = refname;
1251 /* Find total no of '/' separated path-components */
1252 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1255 * The number of components we need to strip is now
1256 * the total minus the components to be left (Plus one
1257 * because we count the number of '/', but the number
1258 * of components is one more than the no of '/').
1260 remaining = i + len + 1;
1263 while (remaining > 0) {
1264 switch (*start++) {
1265 case '\0':
1266 return "";
1267 case '/':
1268 remaining--;
1269 break;
1273 return start;
1276 static const char *rstrip_ref_components(const char *refname, int len)
1278 long remaining = len;
1279 char *start = xstrdup(refname);
1281 if (len < 0) {
1282 int i;
1283 const char *p = refname;
1285 /* Find total no of '/' separated path-components */
1286 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1289 * The number of components we need to strip is now
1290 * the total minus the components to be left (Plus one
1291 * because we count the number of '/', but the number
1292 * of components is one more than the no of '/').
1294 remaining = i + len + 1;
1297 while (remaining-- > 0) {
1298 char *p = strrchr(start, '/');
1299 if (p == NULL)
1300 return "";
1301 else
1302 p[0] = '\0';
1304 return start;
1307 static const char *show_ref(struct refname_atom *atom, const char *refname)
1309 if (atom->option == R_SHORT)
1310 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1311 else if (atom->option == R_LSTRIP)
1312 return lstrip_ref_components(refname, atom->lstrip);
1313 else if (atom->option == R_RSTRIP)
1314 return rstrip_ref_components(refname, atom->rstrip);
1315 else
1316 return refname;
1319 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1320 struct branch *branch, const char **s)
1322 int num_ours, num_theirs;
1323 if (atom->u.remote_ref.option == RR_REF)
1324 *s = show_ref(&atom->u.remote_ref.refname, refname);
1325 else if (atom->u.remote_ref.option == RR_TRACK) {
1326 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1327 NULL, AHEAD_BEHIND_FULL) < 0) {
1328 *s = xstrdup(msgs.gone);
1329 } else if (!num_ours && !num_theirs)
1330 *s = "";
1331 else if (!num_ours)
1332 *s = xstrfmt(msgs.behind, num_theirs);
1333 else if (!num_theirs)
1334 *s = xstrfmt(msgs.ahead, num_ours);
1335 else
1336 *s = xstrfmt(msgs.ahead_behind,
1337 num_ours, num_theirs);
1338 if (!atom->u.remote_ref.nobracket && *s[0]) {
1339 const char *to_free = *s;
1340 *s = xstrfmt("[%s]", *s);
1341 free((void *)to_free);
1343 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1344 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1345 NULL, AHEAD_BEHIND_FULL) < 0)
1346 return;
1348 if (!num_ours && !num_theirs)
1349 *s = "=";
1350 else if (!num_ours)
1351 *s = "<";
1352 else if (!num_theirs)
1353 *s = ">";
1354 else
1355 *s = "<>";
1356 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1357 int explicit;
1358 const char *remote = atom->u.remote_ref.push ?
1359 pushremote_for_branch(branch, &explicit) :
1360 remote_for_branch(branch, &explicit);
1361 if (explicit)
1362 *s = xstrdup(remote);
1363 else
1364 *s = "";
1365 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1366 int explicit;
1367 const char *merge;
1369 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1370 &explicit);
1371 if (explicit)
1372 *s = xstrdup(merge);
1373 else
1374 *s = "";
1375 } else
1376 BUG("unhandled RR_* enum");
1379 char *get_head_description(void)
1381 struct strbuf desc = STRBUF_INIT;
1382 struct wt_status_state state;
1383 memset(&state, 0, sizeof(state));
1384 wt_status_get_state(&state, 1);
1385 if (state.rebase_in_progress ||
1386 state.rebase_interactive_in_progress) {
1387 if (state.branch)
1388 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1389 state.branch);
1390 else
1391 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1392 state.detached_from);
1393 } else if (state.bisect_in_progress)
1394 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1395 state.branch);
1396 else if (state.detached_from) {
1397 if (state.detached_at)
1399 * TRANSLATORS: make sure this matches "HEAD
1400 * detached at " in wt-status.c
1402 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1403 state.detached_from);
1404 else
1406 * TRANSLATORS: make sure this matches "HEAD
1407 * detached from " in wt-status.c
1409 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1410 state.detached_from);
1412 else
1413 strbuf_addstr(&desc, _("(no branch)"));
1414 free(state.branch);
1415 free(state.onto);
1416 free(state.detached_from);
1417 return strbuf_detach(&desc, NULL);
1420 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1422 if (!ref->symref)
1423 return "";
1424 else
1425 return show_ref(&atom->u.refname, ref->symref);
1428 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1430 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1431 return get_head_description();
1432 return show_ref(&atom->u.refname, ref->refname);
1435 static int get_object(struct ref_array_item *ref, const struct object_id *oid,
1436 int deref, struct object **obj, struct strbuf *err)
1438 int eaten;
1439 int ret = 0;
1440 unsigned long size;
1441 void *buf = get_obj(oid, obj, &size, &eaten);
1442 if (!buf)
1443 ret = strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1444 oid_to_hex(oid), ref->refname);
1445 else if (!*obj)
1446 ret = strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1447 oid_to_hex(oid), ref->refname);
1448 else
1449 grab_values(ref->value, deref, *obj, buf, size);
1450 if (!eaten)
1451 free(buf);
1452 return ret;
1456 * Parse the object referred by ref, and grab needed value.
1458 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1460 struct object *obj;
1461 int i;
1462 const struct object_id *tagged;
1464 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1466 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1467 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1468 NULL, NULL);
1469 if (!ref->symref)
1470 ref->symref = "";
1473 /* Fill in specials first */
1474 for (i = 0; i < used_atom_cnt; i++) {
1475 struct used_atom *atom = &used_atom[i];
1476 const char *name = used_atom[i].name;
1477 struct atom_value *v = &ref->value[i];
1478 int deref = 0;
1479 const char *refname;
1480 struct branch *branch = NULL;
1482 v->handler = append_atom;
1483 v->atom = atom;
1485 if (*name == '*') {
1486 deref = 1;
1487 name++;
1490 if (starts_with(name, "refname"))
1491 refname = get_refname(atom, ref);
1492 else if (starts_with(name, "symref"))
1493 refname = get_symref(atom, ref);
1494 else if (starts_with(name, "upstream")) {
1495 const char *branch_name;
1496 /* only local branches may have an upstream */
1497 if (!skip_prefix(ref->refname, "refs/heads/",
1498 &branch_name))
1499 continue;
1500 branch = branch_get(branch_name);
1502 refname = branch_get_upstream(branch, NULL);
1503 if (refname)
1504 fill_remote_ref_details(atom, refname, branch, &v->s);
1505 continue;
1506 } else if (atom->u.remote_ref.push) {
1507 const char *branch_name;
1508 if (!skip_prefix(ref->refname, "refs/heads/",
1509 &branch_name))
1510 continue;
1511 branch = branch_get(branch_name);
1513 if (atom->u.remote_ref.push_remote)
1514 refname = NULL;
1515 else {
1516 refname = branch_get_push(branch, NULL);
1517 if (!refname)
1518 continue;
1520 fill_remote_ref_details(atom, refname, branch, &v->s);
1521 continue;
1522 } else if (starts_with(name, "color:")) {
1523 v->s = atom->u.color;
1524 continue;
1525 } else if (!strcmp(name, "flag")) {
1526 char buf[256], *cp = buf;
1527 if (ref->flag & REF_ISSYMREF)
1528 cp = copy_advance(cp, ",symref");
1529 if (ref->flag & REF_ISPACKED)
1530 cp = copy_advance(cp, ",packed");
1531 if (cp == buf)
1532 v->s = "";
1533 else {
1534 *cp = '\0';
1535 v->s = xstrdup(buf + 1);
1537 continue;
1538 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1539 continue;
1540 } else if (!strcmp(name, "HEAD")) {
1541 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1542 v->s = "*";
1543 else
1544 v->s = " ";
1545 continue;
1546 } else if (starts_with(name, "align")) {
1547 v->handler = align_atom_handler;
1548 continue;
1549 } else if (!strcmp(name, "end")) {
1550 v->handler = end_atom_handler;
1551 continue;
1552 } else if (starts_with(name, "if")) {
1553 const char *s;
1555 if (skip_prefix(name, "if:", &s))
1556 v->s = xstrdup(s);
1557 v->handler = if_atom_handler;
1558 continue;
1559 } else if (!strcmp(name, "then")) {
1560 v->handler = then_atom_handler;
1561 continue;
1562 } else if (!strcmp(name, "else")) {
1563 v->handler = else_atom_handler;
1564 continue;
1565 } else
1566 continue;
1568 if (!deref)
1569 v->s = refname;
1570 else
1571 v->s = xstrfmt("%s^{}", refname);
1574 for (i = 0; i < used_atom_cnt; i++) {
1575 struct atom_value *v = &ref->value[i];
1576 if (v->s == NULL)
1577 break;
1579 if (used_atom_cnt <= i)
1580 return 0;
1582 if (get_object(ref, &ref->objectname, 0, &obj, err))
1583 return -1;
1586 * If there is no atom that wants to know about tagged
1587 * object, we are done.
1589 if (!need_tagged || (obj->type != OBJ_TAG))
1590 return 0;
1593 * If it is a tag object, see if we use a value that derefs
1594 * the object, and if we do grab the object it refers to.
1596 tagged = &((struct tag *)obj)->tagged->oid;
1599 * NEEDSWORK: This derefs tag only once, which
1600 * is good to deal with chains of trust, but
1601 * is not consistent with what deref_tag() does
1602 * which peels the onion to the core.
1604 return get_object(ref, tagged, 1, &obj, err);
1608 * Given a ref, return the value for the atom. This lazily gets value
1609 * out of the object by calling populate value.
1611 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1612 struct atom_value **v, struct strbuf *err)
1614 if (!ref->value) {
1615 if (populate_value(ref, err))
1616 return -1;
1617 fill_missing_values(ref->value);
1619 *v = &ref->value[atom];
1620 return 0;
1624 * Unknown has to be "0" here, because that's the default value for
1625 * contains_cache slab entries that have not yet been assigned.
1627 enum contains_result {
1628 CONTAINS_UNKNOWN = 0,
1629 CONTAINS_NO,
1630 CONTAINS_YES
1633 define_commit_slab(contains_cache, enum contains_result);
1635 struct ref_filter_cbdata {
1636 struct ref_array *array;
1637 struct ref_filter *filter;
1638 struct contains_cache contains_cache;
1639 struct contains_cache no_contains_cache;
1643 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1644 * overflows.
1646 * At each recursion step, the stack items points to the commits whose
1647 * ancestors are to be inspected.
1649 struct contains_stack {
1650 int nr, alloc;
1651 struct contains_stack_entry {
1652 struct commit *commit;
1653 struct commit_list *parents;
1654 } *contains_stack;
1657 static int in_commit_list(const struct commit_list *want, struct commit *c)
1659 for (; want; want = want->next)
1660 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1661 return 1;
1662 return 0;
1666 * Test whether the candidate is contained in the list.
1667 * Do not recurse to find out, though, but return -1 if inconclusive.
1669 static enum contains_result contains_test(struct commit *candidate,
1670 const struct commit_list *want,
1671 struct contains_cache *cache,
1672 uint32_t cutoff)
1674 enum contains_result *cached = contains_cache_at(cache, candidate);
1676 /* If we already have the answer cached, return that. */
1677 if (*cached)
1678 return *cached;
1680 /* or are we it? */
1681 if (in_commit_list(want, candidate)) {
1682 *cached = CONTAINS_YES;
1683 return CONTAINS_YES;
1686 /* Otherwise, we don't know; prepare to recurse */
1687 parse_commit_or_die(candidate);
1689 if (candidate->generation < cutoff)
1690 return CONTAINS_NO;
1692 return CONTAINS_UNKNOWN;
1695 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1697 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1698 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1699 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1702 static enum contains_result contains_tag_algo(struct commit *candidate,
1703 const struct commit_list *want,
1704 struct contains_cache *cache)
1706 struct contains_stack contains_stack = { 0, 0, NULL };
1707 enum contains_result result;
1708 uint32_t cutoff = GENERATION_NUMBER_INFINITY;
1709 const struct commit_list *p;
1711 for (p = want; p; p = p->next) {
1712 struct commit *c = p->item;
1713 load_commit_graph_info(c);
1714 if (c->generation < cutoff)
1715 cutoff = c->generation;
1718 result = contains_test(candidate, want, cache, cutoff);
1719 if (result != CONTAINS_UNKNOWN)
1720 return result;
1722 push_to_contains_stack(candidate, &contains_stack);
1723 while (contains_stack.nr) {
1724 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1725 struct commit *commit = entry->commit;
1726 struct commit_list *parents = entry->parents;
1728 if (!parents) {
1729 *contains_cache_at(cache, commit) = CONTAINS_NO;
1730 contains_stack.nr--;
1733 * If we just popped the stack, parents->item has been marked,
1734 * therefore contains_test will return a meaningful yes/no.
1736 else switch (contains_test(parents->item, want, cache, cutoff)) {
1737 case CONTAINS_YES:
1738 *contains_cache_at(cache, commit) = CONTAINS_YES;
1739 contains_stack.nr--;
1740 break;
1741 case CONTAINS_NO:
1742 entry->parents = parents->next;
1743 break;
1744 case CONTAINS_UNKNOWN:
1745 push_to_contains_stack(parents->item, &contains_stack);
1746 break;
1749 free(contains_stack.contains_stack);
1750 return contains_test(candidate, want, cache, cutoff);
1753 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1754 struct commit_list *list, struct contains_cache *cache)
1756 if (filter->with_commit_tag_algo)
1757 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1758 return is_descendant_of(commit, list);
1762 * Return 1 if the refname matches one of the patterns, otherwise 0.
1763 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1764 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1765 * matches "refs/heads/mas*", too).
1767 static int match_pattern(const struct ref_filter *filter, const char *refname)
1769 const char **patterns = filter->name_patterns;
1770 unsigned flags = 0;
1772 if (filter->ignore_case)
1773 flags |= WM_CASEFOLD;
1776 * When no '--format' option is given we need to skip the prefix
1777 * for matching refs of tags and branches.
1779 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1780 skip_prefix(refname, "refs/heads/", &refname) ||
1781 skip_prefix(refname, "refs/remotes/", &refname) ||
1782 skip_prefix(refname, "refs/", &refname));
1784 for (; *patterns; patterns++) {
1785 if (!wildmatch(*patterns, refname, flags))
1786 return 1;
1788 return 0;
1792 * Return 1 if the refname matches one of the patterns, otherwise 0.
1793 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1794 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1795 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1797 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1799 const char **pattern = filter->name_patterns;
1800 int namelen = strlen(refname);
1801 unsigned flags = WM_PATHNAME;
1803 if (filter->ignore_case)
1804 flags |= WM_CASEFOLD;
1806 for (; *pattern; pattern++) {
1807 const char *p = *pattern;
1808 int plen = strlen(p);
1810 if ((plen <= namelen) &&
1811 !strncmp(refname, p, plen) &&
1812 (refname[plen] == '\0' ||
1813 refname[plen] == '/' ||
1814 p[plen-1] == '/'))
1815 return 1;
1816 if (!wildmatch(p, refname, WM_PATHNAME))
1817 return 1;
1819 return 0;
1822 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1823 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1825 if (!*filter->name_patterns)
1826 return 1; /* No pattern always matches */
1827 if (filter->match_as_path)
1828 return match_name_as_path(filter, refname);
1829 return match_pattern(filter, refname);
1833 * Find the longest prefix of pattern we can pass to
1834 * `for_each_fullref_in()`, namely the part of pattern preceding the
1835 * first glob character. (Note that `for_each_fullref_in()` is
1836 * perfectly happy working with a prefix that doesn't end at a
1837 * pathname component boundary.)
1839 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1841 const char *p;
1843 for (p = pattern; *p && !is_glob_special(*p); p++)
1846 strbuf_add(out, pattern, p - pattern);
1850 * This is the same as for_each_fullref_in(), but it tries to iterate
1851 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1852 * pattern match, so the callback still has to match each ref individually.
1854 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1855 each_ref_fn cb,
1856 void *cb_data,
1857 int broken)
1859 struct strbuf prefix = STRBUF_INIT;
1860 int ret;
1862 if (!filter->match_as_path) {
1864 * in this case, the patterns are applied after
1865 * prefixes like "refs/heads/" etc. are stripped off,
1866 * so we have to look at everything:
1868 return for_each_fullref_in("", cb, cb_data, broken);
1871 if (!filter->name_patterns[0]) {
1872 /* no patterns; we have to look at everything */
1873 return for_each_fullref_in("", cb, cb_data, broken);
1876 if (filter->name_patterns[1]) {
1878 * multiple patterns; in theory this could still work as long
1879 * as the patterns are disjoint. We'd just make multiple calls
1880 * to for_each_ref(). But if they're not disjoint, we'd end up
1881 * reporting the same ref multiple times. So let's punt on that
1882 * for now.
1884 return for_each_fullref_in("", cb, cb_data, broken);
1887 find_longest_prefix(&prefix, filter->name_patterns[0]);
1889 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1890 strbuf_release(&prefix);
1891 return ret;
1895 * Given a ref (sha1, refname), check if the ref belongs to the array
1896 * of sha1s. If the given ref is a tag, check if the given tag points
1897 * at one of the sha1s in the given sha1 array.
1898 * the given sha1_array.
1899 * NEEDSWORK:
1900 * 1. Only a single level of inderection is obtained, we might want to
1901 * change this to account for multiple levels (e.g. annotated tags
1902 * pointing to annotated tags pointing to a commit.)
1903 * 2. As the refs are cached we might know what refname peels to without
1904 * the need to parse the object via parse_object(). peel_ref() might be a
1905 * more efficient alternative to obtain the pointee.
1907 static const struct object_id *match_points_at(struct oid_array *points_at,
1908 const struct object_id *oid,
1909 const char *refname)
1911 const struct object_id *tagged_oid = NULL;
1912 struct object *obj;
1914 if (oid_array_lookup(points_at, oid) >= 0)
1915 return oid;
1916 obj = parse_object(oid);
1917 if (!obj)
1918 die(_("malformed object at '%s'"), refname);
1919 if (obj->type == OBJ_TAG)
1920 tagged_oid = &((struct tag *)obj)->tagged->oid;
1921 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1922 return tagged_oid;
1923 return NULL;
1927 * Allocate space for a new ref_array_item and copy the name and oid to it.
1929 * Callers can then fill in other struct members at their leisure.
1931 static struct ref_array_item *new_ref_array_item(const char *refname,
1932 const struct object_id *oid)
1934 struct ref_array_item *ref;
1936 FLEX_ALLOC_STR(ref, refname, refname);
1937 oidcpy(&ref->objectname, oid);
1939 return ref;
1942 struct ref_array_item *ref_array_push(struct ref_array *array,
1943 const char *refname,
1944 const struct object_id *oid)
1946 struct ref_array_item *ref = new_ref_array_item(refname, oid);
1948 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1949 array->items[array->nr++] = ref;
1951 return ref;
1954 static int ref_kind_from_refname(const char *refname)
1956 unsigned int i;
1958 static struct {
1959 const char *prefix;
1960 unsigned int kind;
1961 } ref_kind[] = {
1962 { "refs/heads/" , FILTER_REFS_BRANCHES },
1963 { "refs/remotes/" , FILTER_REFS_REMOTES },
1964 { "refs/tags/", FILTER_REFS_TAGS}
1967 if (!strcmp(refname, "HEAD"))
1968 return FILTER_REFS_DETACHED_HEAD;
1970 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1971 if (starts_with(refname, ref_kind[i].prefix))
1972 return ref_kind[i].kind;
1975 return FILTER_REFS_OTHERS;
1978 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1980 if (filter->kind == FILTER_REFS_BRANCHES ||
1981 filter->kind == FILTER_REFS_REMOTES ||
1982 filter->kind == FILTER_REFS_TAGS)
1983 return filter->kind;
1984 return ref_kind_from_refname(refname);
1988 * A call-back given to for_each_ref(). Filter refs and keep them for
1989 * later object processing.
1991 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1993 struct ref_filter_cbdata *ref_cbdata = cb_data;
1994 struct ref_filter *filter = ref_cbdata->filter;
1995 struct ref_array_item *ref;
1996 struct commit *commit = NULL;
1997 unsigned int kind;
1999 if (flag & REF_BAD_NAME) {
2000 warning(_("ignoring ref with broken name %s"), refname);
2001 return 0;
2004 if (flag & REF_ISBROKEN) {
2005 warning(_("ignoring broken ref %s"), refname);
2006 return 0;
2009 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2010 kind = filter_ref_kind(filter, refname);
2011 if (!(kind & filter->kind))
2012 return 0;
2014 if (!filter_pattern_match(filter, refname))
2015 return 0;
2017 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2018 return 0;
2021 * A merge filter is applied on refs pointing to commits. Hence
2022 * obtain the commit using the 'oid' available and discard all
2023 * non-commits early. The actual filtering is done later.
2025 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
2026 commit = lookup_commit_reference_gently(oid, 1);
2027 if (!commit)
2028 return 0;
2029 /* We perform the filtering for the '--contains' option... */
2030 if (filter->with_commit &&
2031 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2032 return 0;
2033 /* ...or for the `--no-contains' option */
2034 if (filter->no_commit &&
2035 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2036 return 0;
2040 * We do not open the object yet; sort may only need refname
2041 * to do its job and the resulting list may yet to be pruned
2042 * by maxcount logic.
2044 ref = ref_array_push(ref_cbdata->array, refname, oid);
2045 ref->commit = commit;
2046 ref->flag = flag;
2047 ref->kind = kind;
2049 return 0;
2052 /* Free memory allocated for a ref_array_item */
2053 static void free_array_item(struct ref_array_item *item)
2055 free((char *)item->symref);
2056 free(item);
2059 /* Free all memory allocated for ref_array */
2060 void ref_array_clear(struct ref_array *array)
2062 int i;
2064 for (i = 0; i < array->nr; i++)
2065 free_array_item(array->items[i]);
2066 FREE_AND_NULL(array->items);
2067 array->nr = array->alloc = 0;
2070 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2072 struct rev_info revs;
2073 int i, old_nr;
2074 struct ref_filter *filter = ref_cbdata->filter;
2075 struct ref_array *array = ref_cbdata->array;
2076 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2078 init_revisions(&revs, NULL);
2080 for (i = 0; i < array->nr; i++) {
2081 struct ref_array_item *item = array->items[i];
2082 add_pending_object(&revs, &item->commit->object, item->refname);
2083 to_clear[i] = item->commit;
2086 filter->merge_commit->object.flags |= UNINTERESTING;
2087 add_pending_object(&revs, &filter->merge_commit->object, "");
2089 revs.limited = 1;
2090 if (prepare_revision_walk(&revs))
2091 die(_("revision walk setup failed"));
2093 old_nr = array->nr;
2094 array->nr = 0;
2096 for (i = 0; i < old_nr; i++) {
2097 struct ref_array_item *item = array->items[i];
2098 struct commit *commit = item->commit;
2100 int is_merged = !!(commit->object.flags & UNINTERESTING);
2102 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2103 array->items[array->nr++] = array->items[i];
2104 else
2105 free_array_item(item);
2108 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2109 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2110 free(to_clear);
2114 * API for filtering a set of refs. Based on the type of refs the user
2115 * has requested, we iterate through those refs and apply filters
2116 * as per the given ref_filter structure and finally store the
2117 * filtered refs in the ref_array structure.
2119 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2121 struct ref_filter_cbdata ref_cbdata;
2122 int ret = 0;
2123 unsigned int broken = 0;
2125 ref_cbdata.array = array;
2126 ref_cbdata.filter = filter;
2128 if (type & FILTER_REFS_INCLUDE_BROKEN)
2129 broken = 1;
2130 filter->kind = type & FILTER_REFS_KIND_MASK;
2132 init_contains_cache(&ref_cbdata.contains_cache);
2133 init_contains_cache(&ref_cbdata.no_contains_cache);
2135 /* Simple per-ref filtering */
2136 if (!filter->kind)
2137 die("filter_refs: invalid type");
2138 else {
2140 * For common cases where we need only branches or remotes or tags,
2141 * we only iterate through those refs. If a mix of refs is needed,
2142 * we iterate over all refs and filter out required refs with the help
2143 * of filter_ref_kind().
2145 if (filter->kind == FILTER_REFS_BRANCHES)
2146 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2147 else if (filter->kind == FILTER_REFS_REMOTES)
2148 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2149 else if (filter->kind == FILTER_REFS_TAGS)
2150 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2151 else if (filter->kind & FILTER_REFS_ALL)
2152 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2153 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2154 head_ref(ref_filter_handler, &ref_cbdata);
2157 clear_contains_cache(&ref_cbdata.contains_cache);
2158 clear_contains_cache(&ref_cbdata.no_contains_cache);
2160 /* Filters that need revision walking */
2161 if (filter->merge_commit)
2162 do_merge_filter(&ref_cbdata);
2164 return ret;
2167 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2169 struct atom_value *va, *vb;
2170 int cmp;
2171 cmp_type cmp_type = used_atom[s->atom].type;
2172 int (*cmp_fn)(const char *, const char *);
2173 struct strbuf err = STRBUF_INIT;
2175 if (get_ref_atom_value(a, s->atom, &va, &err))
2176 die("%s", err.buf);
2177 if (get_ref_atom_value(b, s->atom, &vb, &err))
2178 die("%s", err.buf);
2179 strbuf_release(&err);
2180 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2181 if (s->version)
2182 cmp = versioncmp(va->s, vb->s);
2183 else if (cmp_type == FIELD_STR)
2184 cmp = cmp_fn(va->s, vb->s);
2185 else {
2186 if (va->value < vb->value)
2187 cmp = -1;
2188 else if (va->value == vb->value)
2189 cmp = cmp_fn(a->refname, b->refname);
2190 else
2191 cmp = 1;
2194 return (s->reverse) ? -cmp : cmp;
2197 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2199 struct ref_array_item *a = *((struct ref_array_item **)a_);
2200 struct ref_array_item *b = *((struct ref_array_item **)b_);
2201 struct ref_sorting *s;
2203 for (s = ref_sorting; s; s = s->next) {
2204 int cmp = cmp_ref_sorting(s, a, b);
2205 if (cmp)
2206 return cmp;
2208 return 0;
2211 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2213 QSORT_S(array->items, array->nr, compare_refs, sorting);
2216 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2218 struct strbuf *s = &state->stack->output;
2220 while (*cp && (!ep || cp < ep)) {
2221 if (*cp == '%') {
2222 if (cp[1] == '%')
2223 cp++;
2224 else {
2225 int ch = hex2chr(cp + 1);
2226 if (0 <= ch) {
2227 strbuf_addch(s, ch);
2228 cp += 3;
2229 continue;
2233 strbuf_addch(s, *cp);
2234 cp++;
2238 int format_ref_array_item(struct ref_array_item *info,
2239 const struct ref_format *format,
2240 struct strbuf *final_buf,
2241 struct strbuf *error_buf)
2243 const char *cp, *sp, *ep;
2244 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2246 state.quote_style = format->quote_style;
2247 push_stack_element(&state.stack);
2249 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2250 struct atom_value *atomv;
2251 int pos;
2253 ep = strchr(sp, ')');
2254 if (cp < sp)
2255 append_literal(cp, sp, &state);
2256 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2257 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2258 atomv->handler(atomv, &state, error_buf)) {
2259 pop_stack_element(&state.stack);
2260 return -1;
2263 if (*cp) {
2264 sp = cp + strlen(cp);
2265 append_literal(cp, sp, &state);
2267 if (format->need_color_reset_at_eol) {
2268 struct atom_value resetv;
2269 resetv.s = GIT_COLOR_RESET;
2270 if (append_atom(&resetv, &state, error_buf)) {
2271 pop_stack_element(&state.stack);
2272 return -1;
2275 if (state.stack->prev) {
2276 pop_stack_element(&state.stack);
2277 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2279 strbuf_addbuf(final_buf, &state.stack->output);
2280 pop_stack_element(&state.stack);
2281 return 0;
2284 void show_ref_array_item(struct ref_array_item *info,
2285 const struct ref_format *format)
2287 struct strbuf final_buf = STRBUF_INIT;
2288 struct strbuf error_buf = STRBUF_INIT;
2290 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2291 die("%s", error_buf.buf);
2292 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2293 strbuf_release(&error_buf);
2294 strbuf_release(&final_buf);
2295 putchar('\n');
2298 void pretty_print_ref(const char *name, const struct object_id *oid,
2299 const struct ref_format *format)
2301 struct ref_array_item *ref_item;
2302 ref_item = new_ref_array_item(name, oid);
2303 ref_item->kind = ref_kind_from_refname(name);
2304 show_ref_array_item(ref_item, format);
2305 free_array_item(ref_item);
2308 static int parse_sorting_atom(const char *atom)
2311 * This parses an atom using a dummy ref_format, since we don't
2312 * actually care about the formatting details.
2314 struct ref_format dummy = REF_FORMAT_INIT;
2315 const char *end = atom + strlen(atom);
2316 struct strbuf err = STRBUF_INIT;
2317 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2318 if (res < 0)
2319 die("%s", err.buf);
2320 strbuf_release(&err);
2321 return res;
2324 /* If no sorting option is given, use refname to sort as default */
2325 struct ref_sorting *ref_default_sorting(void)
2327 static const char cstr_name[] = "refname";
2329 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2331 sorting->next = NULL;
2332 sorting->atom = parse_sorting_atom(cstr_name);
2333 return sorting;
2336 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2338 struct ref_sorting *s;
2340 s = xcalloc(1, sizeof(*s));
2341 s->next = *sorting_tail;
2342 *sorting_tail = s;
2344 if (*arg == '-') {
2345 s->reverse = 1;
2346 arg++;
2348 if (skip_prefix(arg, "version:", &arg) ||
2349 skip_prefix(arg, "v:", &arg))
2350 s->version = 1;
2351 s->atom = parse_sorting_atom(arg);
2354 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2356 if (!arg) /* should --no-sort void the list ? */
2357 return -1;
2358 parse_ref_sorting(opt->value, arg);
2359 return 0;
2362 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2364 struct ref_filter *rf = opt->value;
2365 struct object_id oid;
2366 int no_merged = starts_with(opt->long_name, "no");
2368 if (rf->merge) {
2369 if (no_merged) {
2370 return opterror(opt, "is incompatible with --merged", 0);
2371 } else {
2372 return opterror(opt, "is incompatible with --no-merged", 0);
2376 rf->merge = no_merged
2377 ? REF_FILTER_MERGED_OMIT
2378 : REF_FILTER_MERGED_INCLUDE;
2380 if (get_oid(arg, &oid))
2381 die(_("malformed object name %s"), arg);
2383 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2384 if (!rf->merge_commit)
2385 return opterror(opt, "must point to a commit", 0);
2387 return 0;