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