ref-filter.c: parse trailers arguments with %(contents) atom
[git] / ref-filter.c
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
20 static struct ref_msg {
21         const char *gone;
22         const char *ahead;
23         const char *behind;
24         const char *ahead_behind;
25 } msgs = {
26          /* Untranslated plumbing messages: */
27         "gone",
28         "ahead %d",
29         "behind %d",
30         "ahead %d, behind %d"
31 };
32
33 void setup_ref_filter_porcelain_msg(void)
34 {
35         msgs.gone = _("gone");
36         msgs.ahead = _("ahead %d");
37         msgs.behind = _("behind %d");
38         msgs.ahead_behind = _("ahead %d, behind %d");
39 }
40
41 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
42 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
43
44 struct align {
45         align_type position;
46         unsigned int width;
47 };
48
49 struct if_then_else {
50         cmp_status cmp_status;
51         const char *str;
52         unsigned int then_atom_seen : 1,
53                 else_atom_seen : 1,
54                 condition_satisfied : 1;
55 };
56
57 struct refname_atom {
58         enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
59         int lstrip, rstrip;
60 };
61
62 /*
63  * An atom is a valid field atom listed below, possibly prefixed with
64  * a "*" to denote deref_tag().
65  *
66  * We parse given format string and sort specifiers, and make a list
67  * of properties that we need to extract out of objects.  ref_array_item
68  * structure will hold an array of values extracted that can be
69  * indexed with the "atom number", which is an index into this
70  * array.
71  */
72 static struct used_atom {
73         const char *name;
74         cmp_type type;
75         union {
76                 char color[COLOR_MAXLEN];
77                 struct align align;
78                 struct {
79                         enum { RR_REF, RR_TRACK, RR_TRACKSHORT } option;
80                         struct refname_atom refname;
81                         unsigned int nobracket : 1;
82                 } remote_ref;
83                 struct {
84                         enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
85                         struct process_trailer_options trailer_opts;
86                         unsigned int nlines;
87                 } contents;
88                 struct {
89                         cmp_status cmp_status;
90                         const char *str;
91                 } if_then_else;
92                 struct {
93                         enum { O_FULL, O_LENGTH, O_SHORT } option;
94                         unsigned int length;
95                 } objectname;
96                 struct refname_atom refname;
97                 char *head;
98         } u;
99 } *used_atom;
100 static int used_atom_cnt, need_tagged, need_symref;
101
102 static void color_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *color_value)
103 {
104         if (!color_value)
105                 die(_("expected format: %%(color:<color>)"));
106         if (color_parse(color_value, atom->u.color) < 0)
107                 die(_("unrecognized color: %%(color:%s)"), color_value);
108         /*
109          * We check this after we've parsed the color, which lets us complain
110          * about syntactically bogus color names even if they won't be used.
111          */
112         if (!want_color(format->use_color))
113                 color_parse("", atom->u.color);
114 }
115
116 static void refname_atom_parser_internal(struct refname_atom *atom,
117                                          const char *arg, const char *name)
118 {
119         if (!arg)
120                 atom->option = R_NORMAL;
121         else if (!strcmp(arg, "short"))
122                 atom->option = R_SHORT;
123         else if (skip_prefix(arg, "lstrip=", &arg) ||
124                  skip_prefix(arg, "strip=", &arg)) {
125                 atom->option = R_LSTRIP;
126                 if (strtol_i(arg, 10, &atom->lstrip))
127                         die(_("Integer value expected refname:lstrip=%s"), arg);
128         } else if (skip_prefix(arg, "rstrip=", &arg)) {
129                 atom->option = R_RSTRIP;
130                 if (strtol_i(arg, 10, &atom->rstrip))
131                         die(_("Integer value expected refname:rstrip=%s"), arg);
132         } else
133                 die(_("unrecognized %%(%s) argument: %s"), name, arg);
134 }
135
136 static void remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
137 {
138         struct string_list params = STRING_LIST_INIT_DUP;
139         int i;
140
141         if (!arg) {
142                 atom->u.remote_ref.option = RR_REF;
143                 refname_atom_parser_internal(&atom->u.remote_ref.refname,
144                                              arg, atom->name);
145                 return;
146         }
147
148         atom->u.remote_ref.nobracket = 0;
149         string_list_split(&params, arg, ',', -1);
150
151         for (i = 0; i < params.nr; i++) {
152                 const char *s = params.items[i].string;
153
154                 if (!strcmp(s, "track"))
155                         atom->u.remote_ref.option = RR_TRACK;
156                 else if (!strcmp(s, "trackshort"))
157                         atom->u.remote_ref.option = RR_TRACKSHORT;
158                 else if (!strcmp(s, "nobracket"))
159                         atom->u.remote_ref.nobracket = 1;
160                 else {
161                         atom->u.remote_ref.option = RR_REF;
162                         refname_atom_parser_internal(&atom->u.remote_ref.refname,
163                                                      arg, atom->name);
164                 }
165         }
166
167         string_list_clear(&params, 0);
168 }
169
170 static void body_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
171 {
172         if (arg)
173                 die(_("%%(body) does not take arguments"));
174         atom->u.contents.option = C_BODY_DEP;
175 }
176
177 static void subject_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
178 {
179         if (arg)
180                 die(_("%%(subject) does not take arguments"));
181         atom->u.contents.option = C_SUB;
182 }
183
184 static void trailers_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
185 {
186         struct string_list params = STRING_LIST_INIT_DUP;
187         int i;
188
189         if (arg) {
190                 string_list_split(&params, arg, ',', -1);
191                 for (i = 0; i < params.nr; i++) {
192                         const char *s = params.items[i].string;
193                         if (!strcmp(s, "unfold"))
194                                 atom->u.contents.trailer_opts.unfold = 1;
195                         else if (!strcmp(s, "only"))
196                                 atom->u.contents.trailer_opts.only_trailers = 1;
197                         else
198                                 die(_("unknown %%(trailers) argument: %s"), s);
199                 }
200         }
201         atom->u.contents.option = C_TRAILERS;
202         string_list_clear(&params, 0);
203 }
204
205 static void contents_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
206 {
207         if (!arg)
208                 atom->u.contents.option = C_BARE;
209         else if (!strcmp(arg, "body"))
210                 atom->u.contents.option = C_BODY;
211         else if (!strcmp(arg, "signature"))
212                 atom->u.contents.option = C_SIG;
213         else if (!strcmp(arg, "subject"))
214                 atom->u.contents.option = C_SUB;
215         else if (skip_prefix(arg, "trailers", &arg)) {
216                 skip_prefix(arg, ":", &arg);
217                 trailers_atom_parser(format, atom, *arg ? arg : NULL);
218         } else if (skip_prefix(arg, "lines=", &arg)) {
219                 atom->u.contents.option = C_LINES;
220                 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
221                         die(_("positive value expected contents:lines=%s"), arg);
222         } else
223                 die(_("unrecognized %%(contents) argument: %s"), arg);
224 }
225
226 static void objectname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
227 {
228         if (!arg)
229                 atom->u.objectname.option = O_FULL;
230         else if (!strcmp(arg, "short"))
231                 atom->u.objectname.option = O_SHORT;
232         else if (skip_prefix(arg, "short=", &arg)) {
233                 atom->u.objectname.option = O_LENGTH;
234                 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
235                     atom->u.objectname.length == 0)
236                         die(_("positive value expected objectname:short=%s"), arg);
237                 if (atom->u.objectname.length < MINIMUM_ABBREV)
238                         atom->u.objectname.length = MINIMUM_ABBREV;
239         } else
240                 die(_("unrecognized %%(objectname) argument: %s"), arg);
241 }
242
243 static void refname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
244 {
245         refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
246 }
247
248 static align_type parse_align_position(const char *s)
249 {
250         if (!strcmp(s, "right"))
251                 return ALIGN_RIGHT;
252         else if (!strcmp(s, "middle"))
253                 return ALIGN_MIDDLE;
254         else if (!strcmp(s, "left"))
255                 return ALIGN_LEFT;
256         return -1;
257 }
258
259 static void align_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
260 {
261         struct align *align = &atom->u.align;
262         struct string_list params = STRING_LIST_INIT_DUP;
263         int i;
264         unsigned int width = ~0U;
265
266         if (!arg)
267                 die(_("expected format: %%(align:<width>,<position>)"));
268
269         align->position = ALIGN_LEFT;
270
271         string_list_split(&params, arg, ',', -1);
272         for (i = 0; i < params.nr; i++) {
273                 const char *s = params.items[i].string;
274                 int position;
275
276                 if (skip_prefix(s, "position=", &s)) {
277                         position = parse_align_position(s);
278                         if (position < 0)
279                                 die(_("unrecognized position:%s"), s);
280                         align->position = position;
281                 } else if (skip_prefix(s, "width=", &s)) {
282                         if (strtoul_ui(s, 10, &width))
283                                 die(_("unrecognized width:%s"), s);
284                 } else if (!strtoul_ui(s, 10, &width))
285                         ;
286                 else if ((position = parse_align_position(s)) >= 0)
287                         align->position = position;
288                 else
289                         die(_("unrecognized %%(align) argument: %s"), s);
290         }
291
292         if (width == ~0U)
293                 die(_("positive width expected with the %%(align) atom"));
294         align->width = width;
295         string_list_clear(&params, 0);
296 }
297
298 static void if_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
299 {
300         if (!arg) {
301                 atom->u.if_then_else.cmp_status = COMPARE_NONE;
302                 return;
303         } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
304                 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
305         } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
306                 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
307         } else {
308                 die(_("unrecognized %%(if) argument: %s"), arg);
309         }
310 }
311
312 static void head_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
313 {
314         struct object_id unused;
315
316         atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, unused.hash, NULL);
317 }
318
319 static struct {
320         const char *name;
321         cmp_type cmp_type;
322         void (*parser)(const struct ref_format *format, struct used_atom *atom, const char *arg);
323 } valid_atom[] = {
324         { "refname" , FIELD_STR, refname_atom_parser },
325         { "objecttype" },
326         { "objectsize", FIELD_ULONG },
327         { "objectname", FIELD_STR, objectname_atom_parser },
328         { "tree" },
329         { "parent" },
330         { "numparent", FIELD_ULONG },
331         { "object" },
332         { "type" },
333         { "tag" },
334         { "author" },
335         { "authorname" },
336         { "authoremail" },
337         { "authordate", FIELD_TIME },
338         { "committer" },
339         { "committername" },
340         { "committeremail" },
341         { "committerdate", FIELD_TIME },
342         { "tagger" },
343         { "taggername" },
344         { "taggeremail" },
345         { "taggerdate", FIELD_TIME },
346         { "creator" },
347         { "creatordate", FIELD_TIME },
348         { "subject", FIELD_STR, subject_atom_parser },
349         { "body", FIELD_STR, body_atom_parser },
350         { "trailers", FIELD_STR, trailers_atom_parser },
351         { "contents", FIELD_STR, contents_atom_parser },
352         { "upstream", FIELD_STR, remote_ref_atom_parser },
353         { "push", FIELD_STR, remote_ref_atom_parser },
354         { "symref", FIELD_STR, refname_atom_parser },
355         { "flag" },
356         { "HEAD", FIELD_STR, head_atom_parser },
357         { "color", FIELD_STR, color_atom_parser },
358         { "align", FIELD_STR, align_atom_parser },
359         { "end" },
360         { "if", FIELD_STR, if_atom_parser },
361         { "then" },
362         { "else" },
363 };
364
365 #define REF_FORMATTING_STATE_INIT  { 0, NULL }
366
367 struct ref_formatting_stack {
368         struct ref_formatting_stack *prev;
369         struct strbuf output;
370         void (*at_end)(struct ref_formatting_stack **stack);
371         void *at_end_data;
372 };
373
374 struct ref_formatting_state {
375         int quote_style;
376         struct ref_formatting_stack *stack;
377 };
378
379 struct atom_value {
380         const char *s;
381         void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
382         uintmax_t value; /* used for sorting when not FIELD_STR */
383         struct used_atom *atom;
384 };
385
386 /*
387  * Used to parse format string and sort specifiers
388  */
389 static int parse_ref_filter_atom(const struct ref_format *format,
390                                  const char *atom, const char *ep)
391 {
392         const char *sp;
393         const char *arg;
394         int i, at, atom_len;
395
396         sp = atom;
397         if (*sp == '*' && sp < ep)
398                 sp++; /* deref */
399         if (ep <= sp)
400                 die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
401
402         /* Do we have the atom already used elsewhere? */
403         for (i = 0; i < used_atom_cnt; i++) {
404                 int len = strlen(used_atom[i].name);
405                 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
406                         return i;
407         }
408
409         /*
410          * If the atom name has a colon, strip it and everything after
411          * it off - it specifies the format for this entry, and
412          * shouldn't be used for checking against the valid_atom
413          * table.
414          */
415         arg = memchr(sp, ':', ep - sp);
416         atom_len = (arg ? arg : ep) - sp;
417
418         /* Is the atom a valid one? */
419         for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
420                 int len = strlen(valid_atom[i].name);
421                 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
422                         break;
423         }
424
425         if (ARRAY_SIZE(valid_atom) <= i)
426                 die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
427
428         /* Add it in, including the deref prefix */
429         at = used_atom_cnt;
430         used_atom_cnt++;
431         REALLOC_ARRAY(used_atom, used_atom_cnt);
432         used_atom[at].name = xmemdupz(atom, ep - atom);
433         used_atom[at].type = valid_atom[i].cmp_type;
434         if (arg)
435                 arg = used_atom[at].name + (arg - atom) + 1;
436         memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
437         if (valid_atom[i].parser)
438                 valid_atom[i].parser(format, &used_atom[at], arg);
439         if (*atom == '*')
440                 need_tagged = 1;
441         if (!strcmp(valid_atom[i].name, "symref"))
442                 need_symref = 1;
443         return at;
444 }
445
446 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
447 {
448         switch (quote_style) {
449         case QUOTE_NONE:
450                 strbuf_addstr(s, str);
451                 break;
452         case QUOTE_SHELL:
453                 sq_quote_buf(s, str);
454                 break;
455         case QUOTE_PERL:
456                 perl_quote_buf(s, str);
457                 break;
458         case QUOTE_PYTHON:
459                 python_quote_buf(s, str);
460                 break;
461         case QUOTE_TCL:
462                 tcl_quote_buf(s, str);
463                 break;
464         }
465 }
466
467 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
468 {
469         /*
470          * Quote formatting is only done when the stack has a single
471          * element. Otherwise quote formatting is done on the
472          * element's entire output strbuf when the %(end) atom is
473          * encountered.
474          */
475         if (!state->stack->prev)
476                 quote_formatting(&state->stack->output, v->s, state->quote_style);
477         else
478                 strbuf_addstr(&state->stack->output, v->s);
479 }
480
481 static void push_stack_element(struct ref_formatting_stack **stack)
482 {
483         struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
484
485         strbuf_init(&s->output, 0);
486         s->prev = *stack;
487         *stack = s;
488 }
489
490 static void pop_stack_element(struct ref_formatting_stack **stack)
491 {
492         struct ref_formatting_stack *current = *stack;
493         struct ref_formatting_stack *prev = current->prev;
494
495         if (prev)
496                 strbuf_addbuf(&prev->output, &current->output);
497         strbuf_release(&current->output);
498         free(current);
499         *stack = prev;
500 }
501
502 static void end_align_handler(struct ref_formatting_stack **stack)
503 {
504         struct ref_formatting_stack *cur = *stack;
505         struct align *align = (struct align *)cur->at_end_data;
506         struct strbuf s = STRBUF_INIT;
507
508         strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
509         strbuf_swap(&cur->output, &s);
510         strbuf_release(&s);
511 }
512
513 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
514 {
515         struct ref_formatting_stack *new;
516
517         push_stack_element(&state->stack);
518         new = state->stack;
519         new->at_end = end_align_handler;
520         new->at_end_data = &atomv->atom->u.align;
521 }
522
523 static void if_then_else_handler(struct ref_formatting_stack **stack)
524 {
525         struct ref_formatting_stack *cur = *stack;
526         struct ref_formatting_stack *prev = cur->prev;
527         struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
528
529         if (!if_then_else->then_atom_seen)
530                 die(_("format: %%(if) atom used without a %%(then) atom"));
531
532         if (if_then_else->else_atom_seen) {
533                 /*
534                  * There is an %(else) atom: we need to drop one state from the
535                  * stack, either the %(else) branch if the condition is satisfied, or
536                  * the %(then) branch if it isn't.
537                  */
538                 if (if_then_else->condition_satisfied) {
539                         strbuf_reset(&cur->output);
540                         pop_stack_element(&cur);
541                 } else {
542                         strbuf_swap(&cur->output, &prev->output);
543                         strbuf_reset(&cur->output);
544                         pop_stack_element(&cur);
545                 }
546         } else if (!if_then_else->condition_satisfied) {
547                 /*
548                  * No %(else) atom: just drop the %(then) branch if the
549                  * condition is not satisfied.
550                  */
551                 strbuf_reset(&cur->output);
552         }
553
554         *stack = cur;
555         free(if_then_else);
556 }
557
558 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
559 {
560         struct ref_formatting_stack *new;
561         struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
562
563         if_then_else->str = atomv->atom->u.if_then_else.str;
564         if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
565
566         push_stack_element(&state->stack);
567         new = state->stack;
568         new->at_end = if_then_else_handler;
569         new->at_end_data = if_then_else;
570 }
571
572 static int is_empty(const char *s)
573 {
574         while (*s != '\0') {
575                 if (!isspace(*s))
576                         return 0;
577                 s++;
578         }
579         return 1;
580 }
581
582 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
583 {
584         struct ref_formatting_stack *cur = state->stack;
585         struct if_then_else *if_then_else = NULL;
586
587         if (cur->at_end == if_then_else_handler)
588                 if_then_else = (struct if_then_else *)cur->at_end_data;
589         if (!if_then_else)
590                 die(_("format: %%(then) atom used without an %%(if) atom"));
591         if (if_then_else->then_atom_seen)
592                 die(_("format: %%(then) atom used more than once"));
593         if (if_then_else->else_atom_seen)
594                 die(_("format: %%(then) atom used after %%(else)"));
595         if_then_else->then_atom_seen = 1;
596         /*
597          * If the 'equals' or 'notequals' attribute is used then
598          * perform the required comparison. If not, only non-empty
599          * strings satisfy the 'if' condition.
600          */
601         if (if_then_else->cmp_status == COMPARE_EQUAL) {
602                 if (!strcmp(if_then_else->str, cur->output.buf))
603                         if_then_else->condition_satisfied = 1;
604         } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
605                 if (strcmp(if_then_else->str, cur->output.buf))
606                         if_then_else->condition_satisfied = 1;
607         } else if (cur->output.len && !is_empty(cur->output.buf))
608                 if_then_else->condition_satisfied = 1;
609         strbuf_reset(&cur->output);
610 }
611
612 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
613 {
614         struct ref_formatting_stack *prev = state->stack;
615         struct if_then_else *if_then_else = NULL;
616
617         if (prev->at_end == if_then_else_handler)
618                 if_then_else = (struct if_then_else *)prev->at_end_data;
619         if (!if_then_else)
620                 die(_("format: %%(else) atom used without an %%(if) atom"));
621         if (!if_then_else->then_atom_seen)
622                 die(_("format: %%(else) atom used without a %%(then) atom"));
623         if (if_then_else->else_atom_seen)
624                 die(_("format: %%(else) atom used more than once"));
625         if_then_else->else_atom_seen = 1;
626         push_stack_element(&state->stack);
627         state->stack->at_end_data = prev->at_end_data;
628         state->stack->at_end = prev->at_end;
629 }
630
631 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
632 {
633         struct ref_formatting_stack *current = state->stack;
634         struct strbuf s = STRBUF_INIT;
635
636         if (!current->at_end)
637                 die(_("format: %%(end) atom used without corresponding atom"));
638         current->at_end(&state->stack);
639
640         /*  Stack may have been popped within at_end(), hence reset the current pointer */
641         current = state->stack;
642
643         /*
644          * Perform quote formatting when the stack element is that of
645          * a supporting atom. If nested then perform quote formatting
646          * only on the topmost supporting atom.
647          */
648         if (!current->prev->prev) {
649                 quote_formatting(&s, current->output.buf, state->quote_style);
650                 strbuf_swap(&current->output, &s);
651         }
652         strbuf_release(&s);
653         pop_stack_element(&state->stack);
654 }
655
656 /*
657  * In a format string, find the next occurrence of %(atom).
658  */
659 static const char *find_next(const char *cp)
660 {
661         while (*cp) {
662                 if (*cp == '%') {
663                         /*
664                          * %( is the start of an atom;
665                          * %% is a quoted per-cent.
666                          */
667                         if (cp[1] == '(')
668                                 return cp;
669                         else if (cp[1] == '%')
670                                 cp++; /* skip over two % */
671                         /* otherwise this is a singleton, literal % */
672                 }
673                 cp++;
674         }
675         return NULL;
676 }
677
678 /*
679  * Make sure the format string is well formed, and parse out
680  * the used atoms.
681  */
682 int verify_ref_format(struct ref_format *format)
683 {
684         const char *cp, *sp;
685
686         format->need_color_reset_at_eol = 0;
687         for (cp = format->format; *cp && (sp = find_next(cp)); ) {
688                 const char *color, *ep = strchr(sp, ')');
689                 int at;
690
691                 if (!ep)
692                         return error(_("malformed format string %s"), sp);
693                 /* sp points at "%(" and ep points at the closing ")" */
694                 at = parse_ref_filter_atom(format, sp + 2, ep);
695                 cp = ep + 1;
696
697                 if (skip_prefix(used_atom[at].name, "color:", &color))
698                         format->need_color_reset_at_eol = !!strcmp(color, "reset");
699         }
700         if (format->need_color_reset_at_eol && !want_color(format->use_color))
701                 format->need_color_reset_at_eol = 0;
702         return 0;
703 }
704
705 /*
706  * Given an object name, read the object data and size, and return a
707  * "struct object".  If the object data we are returning is also borrowed
708  * by the "struct object" representation, set *eaten as well---it is a
709  * signal from parse_object_buffer to us not to free the buffer.
710  */
711 static void *get_obj(const struct object_id *oid, struct object **obj, unsigned long *sz, int *eaten)
712 {
713         enum object_type type;
714         void *buf = read_sha1_file(oid->hash, &type, sz);
715
716         if (buf)
717                 *obj = parse_object_buffer(oid, type, *sz, buf, eaten);
718         else
719                 *obj = NULL;
720         return buf;
721 }
722
723 static int grab_objectname(const char *name, const unsigned char *sha1,
724                            struct atom_value *v, struct used_atom *atom)
725 {
726         if (starts_with(name, "objectname")) {
727                 if (atom->u.objectname.option == O_SHORT) {
728                         v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
729                         return 1;
730                 } else if (atom->u.objectname.option == O_FULL) {
731                         v->s = xstrdup(sha1_to_hex(sha1));
732                         return 1;
733                 } else if (atom->u.objectname.option == O_LENGTH) {
734                         v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
735                         return 1;
736                 } else
737                         die("BUG: unknown %%(objectname) option");
738         }
739         return 0;
740 }
741
742 /* See grab_values */
743 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
744 {
745         int i;
746
747         for (i = 0; i < used_atom_cnt; i++) {
748                 const char *name = used_atom[i].name;
749                 struct atom_value *v = &val[i];
750                 if (!!deref != (*name == '*'))
751                         continue;
752                 if (deref)
753                         name++;
754                 if (!strcmp(name, "objecttype"))
755                         v->s = typename(obj->type);
756                 else if (!strcmp(name, "objectsize")) {
757                         v->value = sz;
758                         v->s = xstrfmt("%lu", sz);
759                 }
760                 else if (deref)
761                         grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
762         }
763 }
764
765 /* See grab_values */
766 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
767 {
768         int i;
769         struct tag *tag = (struct tag *) obj;
770
771         for (i = 0; i < used_atom_cnt; i++) {
772                 const char *name = used_atom[i].name;
773                 struct atom_value *v = &val[i];
774                 if (!!deref != (*name == '*'))
775                         continue;
776                 if (deref)
777                         name++;
778                 if (!strcmp(name, "tag"))
779                         v->s = tag->tag;
780                 else if (!strcmp(name, "type") && tag->tagged)
781                         v->s = typename(tag->tagged->type);
782                 else if (!strcmp(name, "object") && tag->tagged)
783                         v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
784         }
785 }
786
787 /* See grab_values */
788 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
789 {
790         int i;
791         struct commit *commit = (struct commit *) obj;
792
793         for (i = 0; i < used_atom_cnt; i++) {
794                 const char *name = used_atom[i].name;
795                 struct atom_value *v = &val[i];
796                 if (!!deref != (*name == '*'))
797                         continue;
798                 if (deref)
799                         name++;
800                 if (!strcmp(name, "tree")) {
801                         v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
802                 }
803                 else if (!strcmp(name, "numparent")) {
804                         v->value = commit_list_count(commit->parents);
805                         v->s = xstrfmt("%lu", (unsigned long)v->value);
806                 }
807                 else if (!strcmp(name, "parent")) {
808                         struct commit_list *parents;
809                         struct strbuf s = STRBUF_INIT;
810                         for (parents = commit->parents; parents; parents = parents->next) {
811                                 struct commit *parent = parents->item;
812                                 if (parents != commit->parents)
813                                         strbuf_addch(&s, ' ');
814                                 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
815                         }
816                         v->s = strbuf_detach(&s, NULL);
817                 }
818         }
819 }
820
821 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
822 {
823         const char *eol;
824         while (*buf) {
825                 if (!strncmp(buf, who, wholen) &&
826                     buf[wholen] == ' ')
827                         return buf + wholen + 1;
828                 eol = strchr(buf, '\n');
829                 if (!eol)
830                         return "";
831                 eol++;
832                 if (*eol == '\n')
833                         return ""; /* end of header */
834                 buf = eol;
835         }
836         return "";
837 }
838
839 static const char *copy_line(const char *buf)
840 {
841         const char *eol = strchrnul(buf, '\n');
842         return xmemdupz(buf, eol - buf);
843 }
844
845 static const char *copy_name(const char *buf)
846 {
847         const char *cp;
848         for (cp = buf; *cp && *cp != '\n'; cp++) {
849                 if (!strncmp(cp, " <", 2))
850                         return xmemdupz(buf, cp - buf);
851         }
852         return "";
853 }
854
855 static const char *copy_email(const char *buf)
856 {
857         const char *email = strchr(buf, '<');
858         const char *eoemail;
859         if (!email)
860                 return "";
861         eoemail = strchr(email, '>');
862         if (!eoemail)
863                 return "";
864         return xmemdupz(email, eoemail + 1 - email);
865 }
866
867 static char *copy_subject(const char *buf, unsigned long len)
868 {
869         char *r = xmemdupz(buf, len);
870         int i;
871
872         for (i = 0; i < len; i++)
873                 if (r[i] == '\n')
874                         r[i] = ' ';
875
876         return r;
877 }
878
879 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
880 {
881         const char *eoemail = strstr(buf, "> ");
882         char *zone;
883         timestamp_t timestamp;
884         long tz;
885         struct date_mode date_mode = { DATE_NORMAL };
886         const char *formatp;
887
888         /*
889          * We got here because atomname ends in "date" or "date<something>";
890          * it's not possible that <something> is not ":<format>" because
891          * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
892          * ":" means no format is specified, and use the default.
893          */
894         formatp = strchr(atomname, ':');
895         if (formatp != NULL) {
896                 formatp++;
897                 parse_date_format(formatp, &date_mode);
898         }
899
900         if (!eoemail)
901                 goto bad;
902         timestamp = parse_timestamp(eoemail + 2, &zone, 10);
903         if (timestamp == TIME_MAX)
904                 goto bad;
905         tz = strtol(zone, NULL, 10);
906         if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
907                 goto bad;
908         v->s = xstrdup(show_date(timestamp, tz, &date_mode));
909         v->value = timestamp;
910         return;
911  bad:
912         v->s = "";
913         v->value = 0;
914 }
915
916 /* See grab_values */
917 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
918 {
919         int i;
920         int wholen = strlen(who);
921         const char *wholine = NULL;
922
923         for (i = 0; i < used_atom_cnt; i++) {
924                 const char *name = used_atom[i].name;
925                 struct atom_value *v = &val[i];
926                 if (!!deref != (*name == '*'))
927                         continue;
928                 if (deref)
929                         name++;
930                 if (strncmp(who, name, wholen))
931                         continue;
932                 if (name[wholen] != 0 &&
933                     strcmp(name + wholen, "name") &&
934                     strcmp(name + wholen, "email") &&
935                     !starts_with(name + wholen, "date"))
936                         continue;
937                 if (!wholine)
938                         wholine = find_wholine(who, wholen, buf, sz);
939                 if (!wholine)
940                         return; /* no point looking for it */
941                 if (name[wholen] == 0)
942                         v->s = copy_line(wholine);
943                 else if (!strcmp(name + wholen, "name"))
944                         v->s = copy_name(wholine);
945                 else if (!strcmp(name + wholen, "email"))
946                         v->s = copy_email(wholine);
947                 else if (starts_with(name + wholen, "date"))
948                         grab_date(wholine, v, name);
949         }
950
951         /*
952          * For a tag or a commit object, if "creator" or "creatordate" is
953          * requested, do something special.
954          */
955         if (strcmp(who, "tagger") && strcmp(who, "committer"))
956                 return; /* "author" for commit object is not wanted */
957         if (!wholine)
958                 wholine = find_wholine(who, wholen, buf, sz);
959         if (!wholine)
960                 return;
961         for (i = 0; i < used_atom_cnt; i++) {
962                 const char *name = used_atom[i].name;
963                 struct atom_value *v = &val[i];
964                 if (!!deref != (*name == '*'))
965                         continue;
966                 if (deref)
967                         name++;
968
969                 if (starts_with(name, "creatordate"))
970                         grab_date(wholine, v, name);
971                 else if (!strcmp(name, "creator"))
972                         v->s = copy_line(wholine);
973         }
974 }
975
976 static void find_subpos(const char *buf, unsigned long sz,
977                         const char **sub, unsigned long *sublen,
978                         const char **body, unsigned long *bodylen,
979                         unsigned long *nonsiglen,
980                         const char **sig, unsigned long *siglen)
981 {
982         const char *eol;
983         /* skip past header until we hit empty line */
984         while (*buf && *buf != '\n') {
985                 eol = strchrnul(buf, '\n');
986                 if (*eol)
987                         eol++;
988                 buf = eol;
989         }
990         /* skip any empty lines */
991         while (*buf == '\n')
992                 buf++;
993
994         /* parse signature first; we might not even have a subject line */
995         *sig = buf + parse_signature(buf, strlen(buf));
996         *siglen = strlen(*sig);
997
998         /* subject is first non-empty line */
999         *sub = buf;
1000         /* subject goes to first empty line */
1001         while (buf < *sig && *buf && *buf != '\n') {
1002                 eol = strchrnul(buf, '\n');
1003                 if (*eol)
1004                         eol++;
1005                 buf = eol;
1006         }
1007         *sublen = buf - *sub;
1008         /* drop trailing newline, if present */
1009         if (*sublen && (*sub)[*sublen - 1] == '\n')
1010                 *sublen -= 1;
1011
1012         /* skip any empty lines */
1013         while (*buf == '\n')
1014                 buf++;
1015         *body = buf;
1016         *bodylen = strlen(buf);
1017         *nonsiglen = *sig - buf;
1018 }
1019
1020 /*
1021  * If 'lines' is greater than 0, append that many lines from the given
1022  * 'buf' of length 'size' to the given strbuf.
1023  */
1024 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1025 {
1026         int i;
1027         const char *sp, *eol;
1028         size_t len;
1029
1030         sp = buf;
1031
1032         for (i = 0; i < lines && sp < buf + size; i++) {
1033                 if (i)
1034                         strbuf_addstr(out, "\n    ");
1035                 eol = memchr(sp, '\n', size - (sp - buf));
1036                 len = eol ? eol - sp : size - (sp - buf);
1037                 strbuf_add(out, sp, len);
1038                 if (!eol)
1039                         break;
1040                 sp = eol + 1;
1041         }
1042 }
1043
1044 /* See grab_values */
1045 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1046 {
1047         int i;
1048         const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1049         unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1050
1051         for (i = 0; i < used_atom_cnt; i++) {
1052                 struct used_atom *atom = &used_atom[i];
1053                 const char *name = atom->name;
1054                 struct atom_value *v = &val[i];
1055                 if (!!deref != (*name == '*'))
1056                         continue;
1057                 if (deref)
1058                         name++;
1059                 if (strcmp(name, "subject") &&
1060                     strcmp(name, "body") &&
1061                     !starts_with(name, "trailers") &&
1062                     !starts_with(name, "contents"))
1063                         continue;
1064                 if (!subpos)
1065                         find_subpos(buf, sz,
1066                                     &subpos, &sublen,
1067                                     &bodypos, &bodylen, &nonsiglen,
1068                                     &sigpos, &siglen);
1069
1070                 if (atom->u.contents.option == C_SUB)
1071                         v->s = copy_subject(subpos, sublen);
1072                 else if (atom->u.contents.option == C_BODY_DEP)
1073                         v->s = xmemdupz(bodypos, bodylen);
1074                 else if (atom->u.contents.option == C_BODY)
1075                         v->s = xmemdupz(bodypos, nonsiglen);
1076                 else if (atom->u.contents.option == C_SIG)
1077                         v->s = xmemdupz(sigpos, siglen);
1078                 else if (atom->u.contents.option == C_LINES) {
1079                         struct strbuf s = STRBUF_INIT;
1080                         const char *contents_end = bodylen + bodypos - siglen;
1081
1082                         /*  Size is the length of the message after removing the signature */
1083                         append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1084                         v->s = strbuf_detach(&s, NULL);
1085                 } else if (atom->u.contents.option == C_TRAILERS) {
1086                         struct strbuf s = STRBUF_INIT;
1087
1088                         /* Format the trailer info according to the trailer_opts given */
1089                         format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1090
1091                         v->s = strbuf_detach(&s, NULL);
1092                 } else if (atom->u.contents.option == C_BARE)
1093                         v->s = xstrdup(subpos);
1094         }
1095 }
1096
1097 /*
1098  * We want to have empty print-string for field requests
1099  * that do not apply (e.g. "authordate" for a tag object)
1100  */
1101 static void fill_missing_values(struct atom_value *val)
1102 {
1103         int i;
1104         for (i = 0; i < used_atom_cnt; i++) {
1105                 struct atom_value *v = &val[i];
1106                 if (v->s == NULL)
1107                         v->s = "";
1108         }
1109 }
1110
1111 /*
1112  * val is a list of atom_value to hold returned values.  Extract
1113  * the values for atoms in used_atom array out of (obj, buf, sz).
1114  * when deref is false, (obj, buf, sz) is the object that is
1115  * pointed at by the ref itself; otherwise it is the object the
1116  * ref (which is a tag) refers to.
1117  */
1118 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1119 {
1120         grab_common_values(val, deref, obj, buf, sz);
1121         switch (obj->type) {
1122         case OBJ_TAG:
1123                 grab_tag_values(val, deref, obj, buf, sz);
1124                 grab_sub_body_contents(val, deref, obj, buf, sz);
1125                 grab_person("tagger", val, deref, obj, buf, sz);
1126                 break;
1127         case OBJ_COMMIT:
1128                 grab_commit_values(val, deref, obj, buf, sz);
1129                 grab_sub_body_contents(val, deref, obj, buf, sz);
1130                 grab_person("author", val, deref, obj, buf, sz);
1131                 grab_person("committer", val, deref, obj, buf, sz);
1132                 break;
1133         case OBJ_TREE:
1134                 /* grab_tree_values(val, deref, obj, buf, sz); */
1135                 break;
1136         case OBJ_BLOB:
1137                 /* grab_blob_values(val, deref, obj, buf, sz); */
1138                 break;
1139         default:
1140                 die("Eh?  Object of type %d?", obj->type);
1141         }
1142 }
1143
1144 static inline char *copy_advance(char *dst, const char *src)
1145 {
1146         while (*src)
1147                 *dst++ = *src++;
1148         return dst;
1149 }
1150
1151 static const char *lstrip_ref_components(const char *refname, int len)
1152 {
1153         long remaining = len;
1154         const char *start = refname;
1155
1156         if (len < 0) {
1157                 int i;
1158                 const char *p = refname;
1159
1160                 /* Find total no of '/' separated path-components */
1161                 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1162                         ;
1163                 /*
1164                  * The number of components we need to strip is now
1165                  * the total minus the components to be left (Plus one
1166                  * because we count the number of '/', but the number
1167                  * of components is one more than the no of '/').
1168                  */
1169                 remaining = i + len + 1;
1170         }
1171
1172         while (remaining > 0) {
1173                 switch (*start++) {
1174                 case '\0':
1175                         return "";
1176                 case '/':
1177                         remaining--;
1178                         break;
1179                 }
1180         }
1181
1182         return start;
1183 }
1184
1185 static const char *rstrip_ref_components(const char *refname, int len)
1186 {
1187         long remaining = len;
1188         char *start = xstrdup(refname);
1189
1190         if (len < 0) {
1191                 int i;
1192                 const char *p = refname;
1193
1194                 /* Find total no of '/' separated path-components */
1195                 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1196                         ;
1197                 /*
1198                  * The number of components we need to strip is now
1199                  * the total minus the components to be left (Plus one
1200                  * because we count the number of '/', but the number
1201                  * of components is one more than the no of '/').
1202                  */
1203                 remaining = i + len + 1;
1204         }
1205
1206         while (remaining-- > 0) {
1207                 char *p = strrchr(start, '/');
1208                 if (p == NULL)
1209                         return "";
1210                 else
1211                         p[0] = '\0';
1212         }
1213         return start;
1214 }
1215
1216 static const char *show_ref(struct refname_atom *atom, const char *refname)
1217 {
1218         if (atom->option == R_SHORT)
1219                 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1220         else if (atom->option == R_LSTRIP)
1221                 return lstrip_ref_components(refname, atom->lstrip);
1222         else if (atom->option == R_RSTRIP)
1223                 return rstrip_ref_components(refname, atom->rstrip);
1224         else
1225                 return refname;
1226 }
1227
1228 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1229                                     struct branch *branch, const char **s)
1230 {
1231         int num_ours, num_theirs;
1232         if (atom->u.remote_ref.option == RR_REF)
1233                 *s = show_ref(&atom->u.remote_ref.refname, refname);
1234         else if (atom->u.remote_ref.option == RR_TRACK) {
1235                 if (stat_tracking_info(branch, &num_ours,
1236                                        &num_theirs, NULL)) {
1237                         *s = xstrdup(msgs.gone);
1238                 } else if (!num_ours && !num_theirs)
1239                         *s = "";
1240                 else if (!num_ours)
1241                         *s = xstrfmt(msgs.behind, num_theirs);
1242                 else if (!num_theirs)
1243                         *s = xstrfmt(msgs.ahead, num_ours);
1244                 else
1245                         *s = xstrfmt(msgs.ahead_behind,
1246                                      num_ours, num_theirs);
1247                 if (!atom->u.remote_ref.nobracket && *s[0]) {
1248                         const char *to_free = *s;
1249                         *s = xstrfmt("[%s]", *s);
1250                         free((void *)to_free);
1251                 }
1252         } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1253                 if (stat_tracking_info(branch, &num_ours,
1254                                        &num_theirs, NULL))
1255                         return;
1256
1257                 if (!num_ours && !num_theirs)
1258                         *s = "=";
1259                 else if (!num_ours)
1260                         *s = "<";
1261                 else if (!num_theirs)
1262                         *s = ">";
1263                 else
1264                         *s = "<>";
1265         } else
1266                 die("BUG: unhandled RR_* enum");
1267 }
1268
1269 char *get_head_description(void)
1270 {
1271         struct strbuf desc = STRBUF_INIT;
1272         struct wt_status_state state;
1273         memset(&state, 0, sizeof(state));
1274         wt_status_get_state(&state, 1);
1275         if (state.rebase_in_progress ||
1276             state.rebase_interactive_in_progress)
1277                 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1278                             state.branch);
1279         else if (state.bisect_in_progress)
1280                 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1281                             state.branch);
1282         else if (state.detached_from) {
1283                 if (state.detached_at)
1284                         /*
1285                          * TRANSLATORS: make sure this matches "HEAD
1286                          * detached at " in wt-status.c
1287                          */
1288                         strbuf_addf(&desc, _("(HEAD detached at %s)"),
1289                                 state.detached_from);
1290                 else
1291                         /*
1292                          * TRANSLATORS: make sure this matches "HEAD
1293                          * detached from " in wt-status.c
1294                          */
1295                         strbuf_addf(&desc, _("(HEAD detached from %s)"),
1296                                 state.detached_from);
1297         }
1298         else
1299                 strbuf_addstr(&desc, _("(no branch)"));
1300         free(state.branch);
1301         free(state.onto);
1302         free(state.detached_from);
1303         return strbuf_detach(&desc, NULL);
1304 }
1305
1306 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1307 {
1308         if (!ref->symref)
1309                 return "";
1310         else
1311                 return show_ref(&atom->u.refname, ref->symref);
1312 }
1313
1314 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1315 {
1316         if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1317                 return get_head_description();
1318         return show_ref(&atom->u.refname, ref->refname);
1319 }
1320
1321 /*
1322  * Parse the object referred by ref, and grab needed value.
1323  */
1324 static void populate_value(struct ref_array_item *ref)
1325 {
1326         void *buf;
1327         struct object *obj;
1328         int eaten, i;
1329         unsigned long size;
1330         const struct object_id *tagged;
1331
1332         ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1333
1334         if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1335                 struct object_id unused1;
1336                 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1337                                              unused1.hash, NULL);
1338                 if (!ref->symref)
1339                         ref->symref = "";
1340         }
1341
1342         /* Fill in specials first */
1343         for (i = 0; i < used_atom_cnt; i++) {
1344                 struct used_atom *atom = &used_atom[i];
1345                 const char *name = used_atom[i].name;
1346                 struct atom_value *v = &ref->value[i];
1347                 int deref = 0;
1348                 const char *refname;
1349                 struct branch *branch = NULL;
1350
1351                 v->handler = append_atom;
1352                 v->atom = atom;
1353
1354                 if (*name == '*') {
1355                         deref = 1;
1356                         name++;
1357                 }
1358
1359                 if (starts_with(name, "refname"))
1360                         refname = get_refname(atom, ref);
1361                 else if (starts_with(name, "symref"))
1362                         refname = get_symref(atom, ref);
1363                 else if (starts_with(name, "upstream")) {
1364                         const char *branch_name;
1365                         /* only local branches may have an upstream */
1366                         if (!skip_prefix(ref->refname, "refs/heads/",
1367                                          &branch_name))
1368                                 continue;
1369                         branch = branch_get(branch_name);
1370
1371                         refname = branch_get_upstream(branch, NULL);
1372                         if (refname)
1373                                 fill_remote_ref_details(atom, refname, branch, &v->s);
1374                         continue;
1375                 } else if (starts_with(name, "push")) {
1376                         const char *branch_name;
1377                         if (!skip_prefix(ref->refname, "refs/heads/",
1378                                          &branch_name))
1379                                 continue;
1380                         branch = branch_get(branch_name);
1381
1382                         refname = branch_get_push(branch, NULL);
1383                         if (!refname)
1384                                 continue;
1385                         fill_remote_ref_details(atom, refname, branch, &v->s);
1386                         continue;
1387                 } else if (starts_with(name, "color:")) {
1388                         v->s = atom->u.color;
1389                         continue;
1390                 } else if (!strcmp(name, "flag")) {
1391                         char buf[256], *cp = buf;
1392                         if (ref->flag & REF_ISSYMREF)
1393                                 cp = copy_advance(cp, ",symref");
1394                         if (ref->flag & REF_ISPACKED)
1395                                 cp = copy_advance(cp, ",packed");
1396                         if (cp == buf)
1397                                 v->s = "";
1398                         else {
1399                                 *cp = '\0';
1400                                 v->s = xstrdup(buf + 1);
1401                         }
1402                         continue;
1403                 } else if (!deref && grab_objectname(name, ref->objectname.hash, v, atom)) {
1404                         continue;
1405                 } else if (!strcmp(name, "HEAD")) {
1406                         if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1407                                 v->s = "*";
1408                         else
1409                                 v->s = " ";
1410                         continue;
1411                 } else if (starts_with(name, "align")) {
1412                         v->handler = align_atom_handler;
1413                         continue;
1414                 } else if (!strcmp(name, "end")) {
1415                         v->handler = end_atom_handler;
1416                         continue;
1417                 } else if (starts_with(name, "if")) {
1418                         const char *s;
1419
1420                         if (skip_prefix(name, "if:", &s))
1421                                 v->s = xstrdup(s);
1422                         v->handler = if_atom_handler;
1423                         continue;
1424                 } else if (!strcmp(name, "then")) {
1425                         v->handler = then_atom_handler;
1426                         continue;
1427                 } else if (!strcmp(name, "else")) {
1428                         v->handler = else_atom_handler;
1429                         continue;
1430                 } else
1431                         continue;
1432
1433                 if (!deref)
1434                         v->s = refname;
1435                 else
1436                         v->s = xstrfmt("%s^{}", refname);
1437         }
1438
1439         for (i = 0; i < used_atom_cnt; i++) {
1440                 struct atom_value *v = &ref->value[i];
1441                 if (v->s == NULL)
1442                         goto need_obj;
1443         }
1444         return;
1445
1446  need_obj:
1447         buf = get_obj(&ref->objectname, &obj, &size, &eaten);
1448         if (!buf)
1449                 die(_("missing object %s for %s"),
1450                     oid_to_hex(&ref->objectname), ref->refname);
1451         if (!obj)
1452                 die(_("parse_object_buffer failed on %s for %s"),
1453                     oid_to_hex(&ref->objectname), ref->refname);
1454
1455         grab_values(ref->value, 0, obj, buf, size);
1456         if (!eaten)
1457                 free(buf);
1458
1459         /*
1460          * If there is no atom that wants to know about tagged
1461          * object, we are done.
1462          */
1463         if (!need_tagged || (obj->type != OBJ_TAG))
1464                 return;
1465
1466         /*
1467          * If it is a tag object, see if we use a value that derefs
1468          * the object, and if we do grab the object it refers to.
1469          */
1470         tagged = &((struct tag *)obj)->tagged->oid;
1471
1472         /*
1473          * NEEDSWORK: This derefs tag only once, which
1474          * is good to deal with chains of trust, but
1475          * is not consistent with what deref_tag() does
1476          * which peels the onion to the core.
1477          */
1478         buf = get_obj(tagged, &obj, &size, &eaten);
1479         if (!buf)
1480                 die(_("missing object %s for %s"),
1481                     oid_to_hex(tagged), ref->refname);
1482         if (!obj)
1483                 die(_("parse_object_buffer failed on %s for %s"),
1484                     oid_to_hex(tagged), ref->refname);
1485         grab_values(ref->value, 1, obj, buf, size);
1486         if (!eaten)
1487                 free(buf);
1488 }
1489
1490 /*
1491  * Given a ref, return the value for the atom.  This lazily gets value
1492  * out of the object by calling populate value.
1493  */
1494 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1495 {
1496         if (!ref->value) {
1497                 populate_value(ref);
1498                 fill_missing_values(ref->value);
1499         }
1500         *v = &ref->value[atom];
1501 }
1502
1503 /*
1504  * Unknown has to be "0" here, because that's the default value for
1505  * contains_cache slab entries that have not yet been assigned.
1506  */
1507 enum contains_result {
1508         CONTAINS_UNKNOWN = 0,
1509         CONTAINS_NO,
1510         CONTAINS_YES
1511 };
1512
1513 define_commit_slab(contains_cache, enum contains_result);
1514
1515 struct ref_filter_cbdata {
1516         struct ref_array *array;
1517         struct ref_filter *filter;
1518         struct contains_cache contains_cache;
1519         struct contains_cache no_contains_cache;
1520 };
1521
1522 /*
1523  * Mimicking the real stack, this stack lives on the heap, avoiding stack
1524  * overflows.
1525  *
1526  * At each recursion step, the stack items points to the commits whose
1527  * ancestors are to be inspected.
1528  */
1529 struct contains_stack {
1530         int nr, alloc;
1531         struct contains_stack_entry {
1532                 struct commit *commit;
1533                 struct commit_list *parents;
1534         } *contains_stack;
1535 };
1536
1537 static int in_commit_list(const struct commit_list *want, struct commit *c)
1538 {
1539         for (; want; want = want->next)
1540                 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1541                         return 1;
1542         return 0;
1543 }
1544
1545 /*
1546  * Test whether the candidate or one of its parents is contained in the list.
1547  * Do not recurse to find out, though, but return -1 if inconclusive.
1548  */
1549 static enum contains_result contains_test(struct commit *candidate,
1550                                           const struct commit_list *want,
1551                                           struct contains_cache *cache)
1552 {
1553         enum contains_result *cached = contains_cache_at(cache, candidate);
1554
1555         /* If we already have the answer cached, return that. */
1556         if (*cached)
1557                 return *cached;
1558
1559         /* or are we it? */
1560         if (in_commit_list(want, candidate)) {
1561                 *cached = CONTAINS_YES;
1562                 return CONTAINS_YES;
1563         }
1564
1565         /* Otherwise, we don't know; prepare to recurse */
1566         parse_commit_or_die(candidate);
1567         return CONTAINS_UNKNOWN;
1568 }
1569
1570 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1571 {
1572         ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1573         contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1574         contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1575 }
1576
1577 static enum contains_result contains_tag_algo(struct commit *candidate,
1578                                               const struct commit_list *want,
1579                                               struct contains_cache *cache)
1580 {
1581         struct contains_stack contains_stack = { 0, 0, NULL };
1582         enum contains_result result = contains_test(candidate, want, cache);
1583
1584         if (result != CONTAINS_UNKNOWN)
1585                 return result;
1586
1587         push_to_contains_stack(candidate, &contains_stack);
1588         while (contains_stack.nr) {
1589                 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1590                 struct commit *commit = entry->commit;
1591                 struct commit_list *parents = entry->parents;
1592
1593                 if (!parents) {
1594                         *contains_cache_at(cache, commit) = CONTAINS_NO;
1595                         contains_stack.nr--;
1596                 }
1597                 /*
1598                  * If we just popped the stack, parents->item has been marked,
1599                  * therefore contains_test will return a meaningful yes/no.
1600                  */
1601                 else switch (contains_test(parents->item, want, cache)) {
1602                 case CONTAINS_YES:
1603                         *contains_cache_at(cache, commit) = CONTAINS_YES;
1604                         contains_stack.nr--;
1605                         break;
1606                 case CONTAINS_NO:
1607                         entry->parents = parents->next;
1608                         break;
1609                 case CONTAINS_UNKNOWN:
1610                         push_to_contains_stack(parents->item, &contains_stack);
1611                         break;
1612                 }
1613         }
1614         free(contains_stack.contains_stack);
1615         return contains_test(candidate, want, cache);
1616 }
1617
1618 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1619                            struct commit_list *list, struct contains_cache *cache)
1620 {
1621         if (filter->with_commit_tag_algo)
1622                 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1623         return is_descendant_of(commit, list);
1624 }
1625
1626 /*
1627  * Return 1 if the refname matches one of the patterns, otherwise 0.
1628  * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1629  * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1630  * matches "refs/heads/mas*", too).
1631  */
1632 static int match_pattern(const struct ref_filter *filter, const char *refname)
1633 {
1634         const char **patterns = filter->name_patterns;
1635         unsigned flags = 0;
1636
1637         if (filter->ignore_case)
1638                 flags |= WM_CASEFOLD;
1639
1640         /*
1641          * When no '--format' option is given we need to skip the prefix
1642          * for matching refs of tags and branches.
1643          */
1644         (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1645                skip_prefix(refname, "refs/heads/", &refname) ||
1646                skip_prefix(refname, "refs/remotes/", &refname) ||
1647                skip_prefix(refname, "refs/", &refname));
1648
1649         for (; *patterns; patterns++) {
1650                 if (!wildmatch(*patterns, refname, flags))
1651                         return 1;
1652         }
1653         return 0;
1654 }
1655
1656 /*
1657  * Return 1 if the refname matches one of the patterns, otherwise 0.
1658  * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1659  * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1660  * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1661  */
1662 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1663 {
1664         const char **pattern = filter->name_patterns;
1665         int namelen = strlen(refname);
1666         unsigned flags = WM_PATHNAME;
1667
1668         if (filter->ignore_case)
1669                 flags |= WM_CASEFOLD;
1670
1671         for (; *pattern; pattern++) {
1672                 const char *p = *pattern;
1673                 int plen = strlen(p);
1674
1675                 if ((plen <= namelen) &&
1676                     !strncmp(refname, p, plen) &&
1677                     (refname[plen] == '\0' ||
1678                      refname[plen] == '/' ||
1679                      p[plen-1] == '/'))
1680                         return 1;
1681                 if (!wildmatch(p, refname, WM_PATHNAME))
1682                         return 1;
1683         }
1684         return 0;
1685 }
1686
1687 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1688 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1689 {
1690         if (!*filter->name_patterns)
1691                 return 1; /* No pattern always matches */
1692         if (filter->match_as_path)
1693                 return match_name_as_path(filter, refname);
1694         return match_pattern(filter, refname);
1695 }
1696
1697 /*
1698  * Find the longest prefix of pattern we can pass to
1699  * `for_each_fullref_in()`, namely the part of pattern preceding the
1700  * first glob character. (Note that `for_each_fullref_in()` is
1701  * perfectly happy working with a prefix that doesn't end at a
1702  * pathname component boundary.)
1703  */
1704 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1705 {
1706         const char *p;
1707
1708         for (p = pattern; *p && !is_glob_special(*p); p++)
1709                 ;
1710
1711         strbuf_add(out, pattern, p - pattern);
1712 }
1713
1714 /*
1715  * This is the same as for_each_fullref_in(), but it tries to iterate
1716  * only over the patterns we'll care about. Note that it _doesn't_ do a full
1717  * pattern match, so the callback still has to match each ref individually.
1718  */
1719 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1720                                        each_ref_fn cb,
1721                                        void *cb_data,
1722                                        int broken)
1723 {
1724         struct strbuf prefix = STRBUF_INIT;
1725         int ret;
1726
1727         if (!filter->match_as_path) {
1728                 /*
1729                  * in this case, the patterns are applied after
1730                  * prefixes like "refs/heads/" etc. are stripped off,
1731                  * so we have to look at everything:
1732                  */
1733                 return for_each_fullref_in("", cb, cb_data, broken);
1734         }
1735
1736         if (!filter->name_patterns[0]) {
1737                 /* no patterns; we have to look at everything */
1738                 return for_each_fullref_in("", cb, cb_data, broken);
1739         }
1740
1741         if (filter->name_patterns[1]) {
1742                 /*
1743                  * multiple patterns; in theory this could still work as long
1744                  * as the patterns are disjoint. We'd just make multiple calls
1745                  * to for_each_ref(). But if they're not disjoint, we'd end up
1746                  * reporting the same ref multiple times. So let's punt on that
1747                  * for now.
1748                  */
1749                 return for_each_fullref_in("", cb, cb_data, broken);
1750         }
1751
1752         find_longest_prefix(&prefix, filter->name_patterns[0]);
1753
1754         ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1755         strbuf_release(&prefix);
1756         return ret;
1757 }
1758
1759 /*
1760  * Given a ref (sha1, refname), check if the ref belongs to the array
1761  * of sha1s. If the given ref is a tag, check if the given tag points
1762  * at one of the sha1s in the given sha1 array.
1763  * the given sha1_array.
1764  * NEEDSWORK:
1765  * 1. Only a single level of inderection is obtained, we might want to
1766  * change this to account for multiple levels (e.g. annotated tags
1767  * pointing to annotated tags pointing to a commit.)
1768  * 2. As the refs are cached we might know what refname peels to without
1769  * the need to parse the object via parse_object(). peel_ref() might be a
1770  * more efficient alternative to obtain the pointee.
1771  */
1772 static const struct object_id *match_points_at(struct oid_array *points_at,
1773                                                const struct object_id *oid,
1774                                                const char *refname)
1775 {
1776         const struct object_id *tagged_oid = NULL;
1777         struct object *obj;
1778
1779         if (oid_array_lookup(points_at, oid) >= 0)
1780                 return oid;
1781         obj = parse_object(oid);
1782         if (!obj)
1783                 die(_("malformed object at '%s'"), refname);
1784         if (obj->type == OBJ_TAG)
1785                 tagged_oid = &((struct tag *)obj)->tagged->oid;
1786         if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1787                 return tagged_oid;
1788         return NULL;
1789 }
1790
1791 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1792 static struct ref_array_item *new_ref_array_item(const char *refname,
1793                                                  const unsigned char *objectname,
1794                                                  int flag)
1795 {
1796         struct ref_array_item *ref;
1797         FLEX_ALLOC_STR(ref, refname, refname);
1798         hashcpy(ref->objectname.hash, objectname);
1799         ref->flag = flag;
1800
1801         return ref;
1802 }
1803
1804 static int ref_kind_from_refname(const char *refname)
1805 {
1806         unsigned int i;
1807
1808         static struct {
1809                 const char *prefix;
1810                 unsigned int kind;
1811         } ref_kind[] = {
1812                 { "refs/heads/" , FILTER_REFS_BRANCHES },
1813                 { "refs/remotes/" , FILTER_REFS_REMOTES },
1814                 { "refs/tags/", FILTER_REFS_TAGS}
1815         };
1816
1817         if (!strcmp(refname, "HEAD"))
1818                 return FILTER_REFS_DETACHED_HEAD;
1819
1820         for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1821                 if (starts_with(refname, ref_kind[i].prefix))
1822                         return ref_kind[i].kind;
1823         }
1824
1825         return FILTER_REFS_OTHERS;
1826 }
1827
1828 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1829 {
1830         if (filter->kind == FILTER_REFS_BRANCHES ||
1831             filter->kind == FILTER_REFS_REMOTES ||
1832             filter->kind == FILTER_REFS_TAGS)
1833                 return filter->kind;
1834         return ref_kind_from_refname(refname);
1835 }
1836
1837 /*
1838  * A call-back given to for_each_ref().  Filter refs and keep them for
1839  * later object processing.
1840  */
1841 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1842 {
1843         struct ref_filter_cbdata *ref_cbdata = cb_data;
1844         struct ref_filter *filter = ref_cbdata->filter;
1845         struct ref_array_item *ref;
1846         struct commit *commit = NULL;
1847         unsigned int kind;
1848
1849         if (flag & REF_BAD_NAME) {
1850                 warning(_("ignoring ref with broken name %s"), refname);
1851                 return 0;
1852         }
1853
1854         if (flag & REF_ISBROKEN) {
1855                 warning(_("ignoring broken ref %s"), refname);
1856                 return 0;
1857         }
1858
1859         /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1860         kind = filter_ref_kind(filter, refname);
1861         if (!(kind & filter->kind))
1862                 return 0;
1863
1864         if (!filter_pattern_match(filter, refname))
1865                 return 0;
1866
1867         if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1868                 return 0;
1869
1870         /*
1871          * A merge filter is applied on refs pointing to commits. Hence
1872          * obtain the commit using the 'oid' available and discard all
1873          * non-commits early. The actual filtering is done later.
1874          */
1875         if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1876                 commit = lookup_commit_reference_gently(oid, 1);
1877                 if (!commit)
1878                         return 0;
1879                 /* We perform the filtering for the '--contains' option... */
1880                 if (filter->with_commit &&
1881                     !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1882                         return 0;
1883                 /* ...or for the `--no-contains' option */
1884                 if (filter->no_commit &&
1885                     commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1886                         return 0;
1887         }
1888
1889         /*
1890          * We do not open the object yet; sort may only need refname
1891          * to do its job and the resulting list may yet to be pruned
1892          * by maxcount logic.
1893          */
1894         ref = new_ref_array_item(refname, oid->hash, flag);
1895         ref->commit = commit;
1896
1897         REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1898         ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1899         ref->kind = kind;
1900         return 0;
1901 }
1902
1903 /*  Free memory allocated for a ref_array_item */
1904 static void free_array_item(struct ref_array_item *item)
1905 {
1906         free((char *)item->symref);
1907         free(item);
1908 }
1909
1910 /* Free all memory allocated for ref_array */
1911 void ref_array_clear(struct ref_array *array)
1912 {
1913         int i;
1914
1915         for (i = 0; i < array->nr; i++)
1916                 free_array_item(array->items[i]);
1917         FREE_AND_NULL(array->items);
1918         array->nr = array->alloc = 0;
1919 }
1920
1921 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1922 {
1923         struct rev_info revs;
1924         int i, old_nr;
1925         struct ref_filter *filter = ref_cbdata->filter;
1926         struct ref_array *array = ref_cbdata->array;
1927         struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1928
1929         init_revisions(&revs, NULL);
1930
1931         for (i = 0; i < array->nr; i++) {
1932                 struct ref_array_item *item = array->items[i];
1933                 add_pending_object(&revs, &item->commit->object, item->refname);
1934                 to_clear[i] = item->commit;
1935         }
1936
1937         filter->merge_commit->object.flags |= UNINTERESTING;
1938         add_pending_object(&revs, &filter->merge_commit->object, "");
1939
1940         revs.limited = 1;
1941         if (prepare_revision_walk(&revs))
1942                 die(_("revision walk setup failed"));
1943
1944         old_nr = array->nr;
1945         array->nr = 0;
1946
1947         for (i = 0; i < old_nr; i++) {
1948                 struct ref_array_item *item = array->items[i];
1949                 struct commit *commit = item->commit;
1950
1951                 int is_merged = !!(commit->object.flags & UNINTERESTING);
1952
1953                 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1954                         array->items[array->nr++] = array->items[i];
1955                 else
1956                         free_array_item(item);
1957         }
1958
1959         for (i = 0; i < old_nr; i++)
1960                 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1961         clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1962         free(to_clear);
1963 }
1964
1965 /*
1966  * API for filtering a set of refs. Based on the type of refs the user
1967  * has requested, we iterate through those refs and apply filters
1968  * as per the given ref_filter structure and finally store the
1969  * filtered refs in the ref_array structure.
1970  */
1971 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1972 {
1973         struct ref_filter_cbdata ref_cbdata;
1974         int ret = 0;
1975         unsigned int broken = 0;
1976
1977         ref_cbdata.array = array;
1978         ref_cbdata.filter = filter;
1979
1980         if (type & FILTER_REFS_INCLUDE_BROKEN)
1981                 broken = 1;
1982         filter->kind = type & FILTER_REFS_KIND_MASK;
1983
1984         init_contains_cache(&ref_cbdata.contains_cache);
1985         init_contains_cache(&ref_cbdata.no_contains_cache);
1986
1987         /*  Simple per-ref filtering */
1988         if (!filter->kind)
1989                 die("filter_refs: invalid type");
1990         else {
1991                 /*
1992                  * For common cases where we need only branches or remotes or tags,
1993                  * we only iterate through those refs. If a mix of refs is needed,
1994                  * we iterate over all refs and filter out required refs with the help
1995                  * of filter_ref_kind().
1996                  */
1997                 if (filter->kind == FILTER_REFS_BRANCHES)
1998                         ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1999                 else if (filter->kind == FILTER_REFS_REMOTES)
2000                         ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2001                 else if (filter->kind == FILTER_REFS_TAGS)
2002                         ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2003                 else if (filter->kind & FILTER_REFS_ALL)
2004                         ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2005                 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2006                         head_ref(ref_filter_handler, &ref_cbdata);
2007         }
2008
2009         clear_contains_cache(&ref_cbdata.contains_cache);
2010         clear_contains_cache(&ref_cbdata.no_contains_cache);
2011
2012         /*  Filters that need revision walking */
2013         if (filter->merge_commit)
2014                 do_merge_filter(&ref_cbdata);
2015
2016         return ret;
2017 }
2018
2019 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2020 {
2021         struct atom_value *va, *vb;
2022         int cmp;
2023         cmp_type cmp_type = used_atom[s->atom].type;
2024         int (*cmp_fn)(const char *, const char *);
2025
2026         get_ref_atom_value(a, s->atom, &va);
2027         get_ref_atom_value(b, s->atom, &vb);
2028         cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2029         if (s->version)
2030                 cmp = versioncmp(va->s, vb->s);
2031         else if (cmp_type == FIELD_STR)
2032                 cmp = cmp_fn(va->s, vb->s);
2033         else {
2034                 if (va->value < vb->value)
2035                         cmp = -1;
2036                 else if (va->value == vb->value)
2037                         cmp = cmp_fn(a->refname, b->refname);
2038                 else
2039                         cmp = 1;
2040         }
2041
2042         return (s->reverse) ? -cmp : cmp;
2043 }
2044
2045 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2046 {
2047         struct ref_array_item *a = *((struct ref_array_item **)a_);
2048         struct ref_array_item *b = *((struct ref_array_item **)b_);
2049         struct ref_sorting *s;
2050
2051         for (s = ref_sorting; s; s = s->next) {
2052                 int cmp = cmp_ref_sorting(s, a, b);
2053                 if (cmp)
2054                         return cmp;
2055         }
2056         return 0;
2057 }
2058
2059 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2060 {
2061         QSORT_S(array->items, array->nr, compare_refs, sorting);
2062 }
2063
2064 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2065 {
2066         struct strbuf *s = &state->stack->output;
2067
2068         while (*cp && (!ep || cp < ep)) {
2069                 if (*cp == '%') {
2070                         if (cp[1] == '%')
2071                                 cp++;
2072                         else {
2073                                 int ch = hex2chr(cp + 1);
2074                                 if (0 <= ch) {
2075                                         strbuf_addch(s, ch);
2076                                         cp += 3;
2077                                         continue;
2078                                 }
2079                         }
2080                 }
2081                 strbuf_addch(s, *cp);
2082                 cp++;
2083         }
2084 }
2085
2086 void format_ref_array_item(struct ref_array_item *info,
2087                            const struct ref_format *format,
2088                            struct strbuf *final_buf)
2089 {
2090         const char *cp, *sp, *ep;
2091         struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2092
2093         state.quote_style = format->quote_style;
2094         push_stack_element(&state.stack);
2095
2096         for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2097                 struct atom_value *atomv;
2098
2099                 ep = strchr(sp, ')');
2100                 if (cp < sp)
2101                         append_literal(cp, sp, &state);
2102                 get_ref_atom_value(info,
2103                                    parse_ref_filter_atom(format, sp + 2, ep),
2104                                    &atomv);
2105                 atomv->handler(atomv, &state);
2106         }
2107         if (*cp) {
2108                 sp = cp + strlen(cp);
2109                 append_literal(cp, sp, &state);
2110         }
2111         if (format->need_color_reset_at_eol) {
2112                 struct atom_value resetv;
2113                 resetv.s = GIT_COLOR_RESET;
2114                 append_atom(&resetv, &state);
2115         }
2116         if (state.stack->prev)
2117                 die(_("format: %%(end) atom missing"));
2118         strbuf_addbuf(final_buf, &state.stack->output);
2119         pop_stack_element(&state.stack);
2120 }
2121
2122 void show_ref_array_item(struct ref_array_item *info,
2123                          const struct ref_format *format)
2124 {
2125         struct strbuf final_buf = STRBUF_INIT;
2126
2127         format_ref_array_item(info, format, &final_buf);
2128         fwrite(final_buf.buf, 1, final_buf.len, stdout);
2129         strbuf_release(&final_buf);
2130         putchar('\n');
2131 }
2132
2133 void pretty_print_ref(const char *name, const unsigned char *sha1,
2134                       const struct ref_format *format)
2135 {
2136         struct ref_array_item *ref_item;
2137         ref_item = new_ref_array_item(name, sha1, 0);
2138         ref_item->kind = ref_kind_from_refname(name);
2139         show_ref_array_item(ref_item, format);
2140         free_array_item(ref_item);
2141 }
2142
2143 static int parse_sorting_atom(const char *atom)
2144 {
2145         /*
2146          * This parses an atom using a dummy ref_format, since we don't
2147          * actually care about the formatting details.
2148          */
2149         struct ref_format dummy = REF_FORMAT_INIT;
2150         const char *end = atom + strlen(atom);
2151         return parse_ref_filter_atom(&dummy, atom, end);
2152 }
2153
2154 /*  If no sorting option is given, use refname to sort as default */
2155 struct ref_sorting *ref_default_sorting(void)
2156 {
2157         static const char cstr_name[] = "refname";
2158
2159         struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2160
2161         sorting->next = NULL;
2162         sorting->atom = parse_sorting_atom(cstr_name);
2163         return sorting;
2164 }
2165
2166 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2167 {
2168         struct ref_sorting *s;
2169
2170         s = xcalloc(1, sizeof(*s));
2171         s->next = *sorting_tail;
2172         *sorting_tail = s;
2173
2174         if (*arg == '-') {
2175                 s->reverse = 1;
2176                 arg++;
2177         }
2178         if (skip_prefix(arg, "version:", &arg) ||
2179             skip_prefix(arg, "v:", &arg))
2180                 s->version = 1;
2181         s->atom = parse_sorting_atom(arg);
2182 }
2183
2184 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2185 {
2186         if (!arg) /* should --no-sort void the list ? */
2187                 return -1;
2188         parse_ref_sorting(opt->value, arg);
2189         return 0;
2190 }
2191
2192 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2193 {
2194         struct ref_filter *rf = opt->value;
2195         struct object_id oid;
2196         int no_merged = starts_with(opt->long_name, "no");
2197
2198         if (rf->merge) {
2199                 if (no_merged) {
2200                         return opterror(opt, "is incompatible with --merged", 0);
2201                 } else {
2202                         return opterror(opt, "is incompatible with --no-merged", 0);
2203                 }
2204         }
2205
2206         rf->merge = no_merged
2207                 ? REF_FILTER_MERGED_OMIT
2208                 : REF_FILTER_MERGED_INCLUDE;
2209
2210         if (get_oid(arg, &oid))
2211                 die(_("malformed object name %s"), arg);
2212
2213         rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2214         if (!rf->merge_commit)
2215                 return opterror(opt, "must point to a commit", 0);
2216
2217         return 0;
2218 }