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