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