commit: use generation number in remove_redundant()
[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 #include "commit-graph.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_sha1_file(oid->hash, &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 unsigned char *sha1,
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(sha1, DEFAULT_ABBREV));
747                         return 1;
748                 } else if (atom->u.objectname.option == O_FULL) {
749                         v->s = xstrdup(sha1_to_hex(sha1));
750                         return 1;
751                 } else if (atom->u.objectname.option == O_LENGTH) {
752                         v->s = xstrdup(find_unique_abbrev(sha1, 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.hash, 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(get_commit_tree_oid(commit)));
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,
1254                                        &num_theirs, NULL)) {
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,
1272                                        &num_theirs, NULL))
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 /*
1359  * Parse the object referred by ref, and grab needed value.
1360  */
1361 static void populate_value(struct ref_array_item *ref)
1362 {
1363         void *buf;
1364         struct object *obj;
1365         int eaten, i;
1366         unsigned long size;
1367         const struct object_id *tagged;
1368
1369         ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1370
1371         if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1372                 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1373                                              NULL, NULL);
1374                 if (!ref->symref)
1375                         ref->symref = "";
1376         }
1377
1378         /* Fill in specials first */
1379         for (i = 0; i < used_atom_cnt; i++) {
1380                 struct used_atom *atom = &used_atom[i];
1381                 const char *name = used_atom[i].name;
1382                 struct atom_value *v = &ref->value[i];
1383                 int deref = 0;
1384                 const char *refname;
1385                 struct branch *branch = NULL;
1386
1387                 v->handler = append_atom;
1388                 v->atom = atom;
1389
1390                 if (*name == '*') {
1391                         deref = 1;
1392                         name++;
1393                 }
1394
1395                 if (starts_with(name, "refname"))
1396                         refname = get_refname(atom, ref);
1397                 else if (starts_with(name, "symref"))
1398                         refname = get_symref(atom, ref);
1399                 else if (starts_with(name, "upstream")) {
1400                         const char *branch_name;
1401                         /* only local branches may have an upstream */
1402                         if (!skip_prefix(ref->refname, "refs/heads/",
1403                                          &branch_name))
1404                                 continue;
1405                         branch = branch_get(branch_name);
1406
1407                         refname = branch_get_upstream(branch, NULL);
1408                         if (refname)
1409                                 fill_remote_ref_details(atom, refname, branch, &v->s);
1410                         continue;
1411                 } else if (atom->u.remote_ref.push) {
1412                         const char *branch_name;
1413                         if (!skip_prefix(ref->refname, "refs/heads/",
1414                                          &branch_name))
1415                                 continue;
1416                         branch = branch_get(branch_name);
1417
1418                         if (atom->u.remote_ref.push_remote)
1419                                 refname = NULL;
1420                         else {
1421                                 refname = branch_get_push(branch, NULL);
1422                                 if (!refname)
1423                                         continue;
1424                         }
1425                         fill_remote_ref_details(atom, refname, branch, &v->s);
1426                         continue;
1427                 } else if (starts_with(name, "color:")) {
1428                         v->s = atom->u.color;
1429                         continue;
1430                 } else if (!strcmp(name, "flag")) {
1431                         char buf[256], *cp = buf;
1432                         if (ref->flag & REF_ISSYMREF)
1433                                 cp = copy_advance(cp, ",symref");
1434                         if (ref->flag & REF_ISPACKED)
1435                                 cp = copy_advance(cp, ",packed");
1436                         if (cp == buf)
1437                                 v->s = "";
1438                         else {
1439                                 *cp = '\0';
1440                                 v->s = xstrdup(buf + 1);
1441                         }
1442                         continue;
1443                 } else if (!deref && grab_objectname(name, ref->objectname.hash, v, atom)) {
1444                         continue;
1445                 } else if (!strcmp(name, "HEAD")) {
1446                         if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1447                                 v->s = "*";
1448                         else
1449                                 v->s = " ";
1450                         continue;
1451                 } else if (starts_with(name, "align")) {
1452                         v->handler = align_atom_handler;
1453                         continue;
1454                 } else if (!strcmp(name, "end")) {
1455                         v->handler = end_atom_handler;
1456                         continue;
1457                 } else if (starts_with(name, "if")) {
1458                         const char *s;
1459
1460                         if (skip_prefix(name, "if:", &s))
1461                                 v->s = xstrdup(s);
1462                         v->handler = if_atom_handler;
1463                         continue;
1464                 } else if (!strcmp(name, "then")) {
1465                         v->handler = then_atom_handler;
1466                         continue;
1467                 } else if (!strcmp(name, "else")) {
1468                         v->handler = else_atom_handler;
1469                         continue;
1470                 } else
1471                         continue;
1472
1473                 if (!deref)
1474                         v->s = refname;
1475                 else
1476                         v->s = xstrfmt("%s^{}", refname);
1477         }
1478
1479         for (i = 0; i < used_atom_cnt; i++) {
1480                 struct atom_value *v = &ref->value[i];
1481                 if (v->s == NULL)
1482                         goto need_obj;
1483         }
1484         return;
1485
1486  need_obj:
1487         buf = get_obj(&ref->objectname, &obj, &size, &eaten);
1488         if (!buf)
1489                 die(_("missing object %s for %s"),
1490                     oid_to_hex(&ref->objectname), ref->refname);
1491         if (!obj)
1492                 die(_("parse_object_buffer failed on %s for %s"),
1493                     oid_to_hex(&ref->objectname), ref->refname);
1494
1495         grab_values(ref->value, 0, obj, buf, size);
1496         if (!eaten)
1497                 free(buf);
1498
1499         /*
1500          * If there is no atom that wants to know about tagged
1501          * object, we are done.
1502          */
1503         if (!need_tagged || (obj->type != OBJ_TAG))
1504                 return;
1505
1506         /*
1507          * If it is a tag object, see if we use a value that derefs
1508          * the object, and if we do grab the object it refers to.
1509          */
1510         tagged = &((struct tag *)obj)->tagged->oid;
1511
1512         /*
1513          * NEEDSWORK: This derefs tag only once, which
1514          * is good to deal with chains of trust, but
1515          * is not consistent with what deref_tag() does
1516          * which peels the onion to the core.
1517          */
1518         buf = get_obj(tagged, &obj, &size, &eaten);
1519         if (!buf)
1520                 die(_("missing object %s for %s"),
1521                     oid_to_hex(tagged), ref->refname);
1522         if (!obj)
1523                 die(_("parse_object_buffer failed on %s for %s"),
1524                     oid_to_hex(tagged), ref->refname);
1525         grab_values(ref->value, 1, obj, buf, size);
1526         if (!eaten)
1527                 free(buf);
1528 }
1529
1530 /*
1531  * Given a ref, return the value for the atom.  This lazily gets value
1532  * out of the object by calling populate value.
1533  */
1534 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1535 {
1536         if (!ref->value) {
1537                 populate_value(ref);
1538                 fill_missing_values(ref->value);
1539         }
1540         *v = &ref->value[atom];
1541 }
1542
1543 /*
1544  * Unknown has to be "0" here, because that's the default value for
1545  * contains_cache slab entries that have not yet been assigned.
1546  */
1547 enum contains_result {
1548         CONTAINS_UNKNOWN = 0,
1549         CONTAINS_NO,
1550         CONTAINS_YES
1551 };
1552
1553 define_commit_slab(contains_cache, enum contains_result);
1554
1555 struct ref_filter_cbdata {
1556         struct ref_array *array;
1557         struct ref_filter *filter;
1558         struct contains_cache contains_cache;
1559         struct contains_cache no_contains_cache;
1560 };
1561
1562 /*
1563  * Mimicking the real stack, this stack lives on the heap, avoiding stack
1564  * overflows.
1565  *
1566  * At each recursion step, the stack items points to the commits whose
1567  * ancestors are to be inspected.
1568  */
1569 struct contains_stack {
1570         int nr, alloc;
1571         struct contains_stack_entry {
1572                 struct commit *commit;
1573                 struct commit_list *parents;
1574         } *contains_stack;
1575 };
1576
1577 static int in_commit_list(const struct commit_list *want, struct commit *c)
1578 {
1579         for (; want; want = want->next)
1580                 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1581                         return 1;
1582         return 0;
1583 }
1584
1585 /*
1586  * Test whether the candidate is contained in the list.
1587  * Do not recurse to find out, though, but return -1 if inconclusive.
1588  */
1589 static enum contains_result contains_test(struct commit *candidate,
1590                                           const struct commit_list *want,
1591                                           struct contains_cache *cache,
1592                                           uint32_t cutoff)
1593 {
1594         enum contains_result *cached = contains_cache_at(cache, candidate);
1595
1596         /* If we already have the answer cached, return that. */
1597         if (*cached)
1598                 return *cached;
1599
1600         /* or are we it? */
1601         if (in_commit_list(want, candidate)) {
1602                 *cached = CONTAINS_YES;
1603                 return CONTAINS_YES;
1604         }
1605
1606         /* Otherwise, we don't know; prepare to recurse */
1607         parse_commit_or_die(candidate);
1608
1609         if (candidate->generation < cutoff)
1610                 return CONTAINS_NO;
1611
1612         return CONTAINS_UNKNOWN;
1613 }
1614
1615 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1616 {
1617         ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1618         contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1619         contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1620 }
1621
1622 static enum contains_result contains_tag_algo(struct commit *candidate,
1623                                               const struct commit_list *want,
1624                                               struct contains_cache *cache)
1625 {
1626         struct contains_stack contains_stack = { 0, 0, NULL };
1627         enum contains_result result;
1628         uint32_t cutoff = GENERATION_NUMBER_INFINITY;
1629         const struct commit_list *p;
1630
1631         for (p = want; p; p = p->next) {
1632                 struct commit *c = p->item;
1633                 load_commit_graph_info(c);
1634                 if (c->generation < cutoff)
1635                         cutoff = c->generation;
1636         }
1637
1638         result = contains_test(candidate, want, cache, cutoff);
1639         if (result != CONTAINS_UNKNOWN)
1640                 return result;
1641
1642         push_to_contains_stack(candidate, &contains_stack);
1643         while (contains_stack.nr) {
1644                 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1645                 struct commit *commit = entry->commit;
1646                 struct commit_list *parents = entry->parents;
1647
1648                 if (!parents) {
1649                         *contains_cache_at(cache, commit) = CONTAINS_NO;
1650                         contains_stack.nr--;
1651                 }
1652                 /*
1653                  * If we just popped the stack, parents->item has been marked,
1654                  * therefore contains_test will return a meaningful yes/no.
1655                  */
1656                 else switch (contains_test(parents->item, want, cache, cutoff)) {
1657                 case CONTAINS_YES:
1658                         *contains_cache_at(cache, commit) = CONTAINS_YES;
1659                         contains_stack.nr--;
1660                         break;
1661                 case CONTAINS_NO:
1662                         entry->parents = parents->next;
1663                         break;
1664                 case CONTAINS_UNKNOWN:
1665                         push_to_contains_stack(parents->item, &contains_stack);
1666                         break;
1667                 }
1668         }
1669         free(contains_stack.contains_stack);
1670         return contains_test(candidate, want, cache, cutoff);
1671 }
1672
1673 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1674                            struct commit_list *list, struct contains_cache *cache)
1675 {
1676         if (filter->with_commit_tag_algo)
1677                 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1678         return is_descendant_of(commit, list);
1679 }
1680
1681 /*
1682  * Return 1 if the refname matches one of the patterns, otherwise 0.
1683  * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1684  * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1685  * matches "refs/heads/mas*", too).
1686  */
1687 static int match_pattern(const struct ref_filter *filter, const char *refname)
1688 {
1689         const char **patterns = filter->name_patterns;
1690         unsigned flags = 0;
1691
1692         if (filter->ignore_case)
1693                 flags |= WM_CASEFOLD;
1694
1695         /*
1696          * When no '--format' option is given we need to skip the prefix
1697          * for matching refs of tags and branches.
1698          */
1699         (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1700                skip_prefix(refname, "refs/heads/", &refname) ||
1701                skip_prefix(refname, "refs/remotes/", &refname) ||
1702                skip_prefix(refname, "refs/", &refname));
1703
1704         for (; *patterns; patterns++) {
1705                 if (!wildmatch(*patterns, refname, flags))
1706                         return 1;
1707         }
1708         return 0;
1709 }
1710
1711 /*
1712  * Return 1 if the refname matches one of the patterns, otherwise 0.
1713  * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1714  * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1715  * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1716  */
1717 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1718 {
1719         const char **pattern = filter->name_patterns;
1720         int namelen = strlen(refname);
1721         unsigned flags = WM_PATHNAME;
1722
1723         if (filter->ignore_case)
1724                 flags |= WM_CASEFOLD;
1725
1726         for (; *pattern; pattern++) {
1727                 const char *p = *pattern;
1728                 int plen = strlen(p);
1729
1730                 if ((plen <= namelen) &&
1731                     !strncmp(refname, p, plen) &&
1732                     (refname[plen] == '\0' ||
1733                      refname[plen] == '/' ||
1734                      p[plen-1] == '/'))
1735                         return 1;
1736                 if (!wildmatch(p, refname, WM_PATHNAME))
1737                         return 1;
1738         }
1739         return 0;
1740 }
1741
1742 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1743 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1744 {
1745         if (!*filter->name_patterns)
1746                 return 1; /* No pattern always matches */
1747         if (filter->match_as_path)
1748                 return match_name_as_path(filter, refname);
1749         return match_pattern(filter, refname);
1750 }
1751
1752 /*
1753  * Find the longest prefix of pattern we can pass to
1754  * `for_each_fullref_in()`, namely the part of pattern preceding the
1755  * first glob character. (Note that `for_each_fullref_in()` is
1756  * perfectly happy working with a prefix that doesn't end at a
1757  * pathname component boundary.)
1758  */
1759 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1760 {
1761         const char *p;
1762
1763         for (p = pattern; *p && !is_glob_special(*p); p++)
1764                 ;
1765
1766         strbuf_add(out, pattern, p - pattern);
1767 }
1768
1769 /*
1770  * This is the same as for_each_fullref_in(), but it tries to iterate
1771  * only over the patterns we'll care about. Note that it _doesn't_ do a full
1772  * pattern match, so the callback still has to match each ref individually.
1773  */
1774 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1775                                        each_ref_fn cb,
1776                                        void *cb_data,
1777                                        int broken)
1778 {
1779         struct strbuf prefix = STRBUF_INIT;
1780         int ret;
1781
1782         if (!filter->match_as_path) {
1783                 /*
1784                  * in this case, the patterns are applied after
1785                  * prefixes like "refs/heads/" etc. are stripped off,
1786                  * so we have to look at everything:
1787                  */
1788                 return for_each_fullref_in("", cb, cb_data, broken);
1789         }
1790
1791         if (!filter->name_patterns[0]) {
1792                 /* no patterns; we have to look at everything */
1793                 return for_each_fullref_in("", cb, cb_data, broken);
1794         }
1795
1796         if (filter->name_patterns[1]) {
1797                 /*
1798                  * multiple patterns; in theory this could still work as long
1799                  * as the patterns are disjoint. We'd just make multiple calls
1800                  * to for_each_ref(). But if they're not disjoint, we'd end up
1801                  * reporting the same ref multiple times. So let's punt on that
1802                  * for now.
1803                  */
1804                 return for_each_fullref_in("", cb, cb_data, broken);
1805         }
1806
1807         find_longest_prefix(&prefix, filter->name_patterns[0]);
1808
1809         ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1810         strbuf_release(&prefix);
1811         return ret;
1812 }
1813
1814 /*
1815  * Given a ref (sha1, refname), check if the ref belongs to the array
1816  * of sha1s. If the given ref is a tag, check if the given tag points
1817  * at one of the sha1s in the given sha1 array.
1818  * the given sha1_array.
1819  * NEEDSWORK:
1820  * 1. Only a single level of inderection is obtained, we might want to
1821  * change this to account for multiple levels (e.g. annotated tags
1822  * pointing to annotated tags pointing to a commit.)
1823  * 2. As the refs are cached we might know what refname peels to without
1824  * the need to parse the object via parse_object(). peel_ref() might be a
1825  * more efficient alternative to obtain the pointee.
1826  */
1827 static const struct object_id *match_points_at(struct oid_array *points_at,
1828                                                const struct object_id *oid,
1829                                                const char *refname)
1830 {
1831         const struct object_id *tagged_oid = NULL;
1832         struct object *obj;
1833
1834         if (oid_array_lookup(points_at, oid) >= 0)
1835                 return oid;
1836         obj = parse_object(oid);
1837         if (!obj)
1838                 die(_("malformed object at '%s'"), refname);
1839         if (obj->type == OBJ_TAG)
1840                 tagged_oid = &((struct tag *)obj)->tagged->oid;
1841         if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1842                 return tagged_oid;
1843         return NULL;
1844 }
1845
1846 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1847 static struct ref_array_item *new_ref_array_item(const char *refname,
1848                                                  const unsigned char *objectname,
1849                                                  int flag)
1850 {
1851         struct ref_array_item *ref;
1852         FLEX_ALLOC_STR(ref, refname, refname);
1853         hashcpy(ref->objectname.hash, objectname);
1854         ref->flag = flag;
1855
1856         return ref;
1857 }
1858
1859 static int ref_kind_from_refname(const char *refname)
1860 {
1861         unsigned int i;
1862
1863         static struct {
1864                 const char *prefix;
1865                 unsigned int kind;
1866         } ref_kind[] = {
1867                 { "refs/heads/" , FILTER_REFS_BRANCHES },
1868                 { "refs/remotes/" , FILTER_REFS_REMOTES },
1869                 { "refs/tags/", FILTER_REFS_TAGS}
1870         };
1871
1872         if (!strcmp(refname, "HEAD"))
1873                 return FILTER_REFS_DETACHED_HEAD;
1874
1875         for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1876                 if (starts_with(refname, ref_kind[i].prefix))
1877                         return ref_kind[i].kind;
1878         }
1879
1880         return FILTER_REFS_OTHERS;
1881 }
1882
1883 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1884 {
1885         if (filter->kind == FILTER_REFS_BRANCHES ||
1886             filter->kind == FILTER_REFS_REMOTES ||
1887             filter->kind == FILTER_REFS_TAGS)
1888                 return filter->kind;
1889         return ref_kind_from_refname(refname);
1890 }
1891
1892 /*
1893  * A call-back given to for_each_ref().  Filter refs and keep them for
1894  * later object processing.
1895  */
1896 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1897 {
1898         struct ref_filter_cbdata *ref_cbdata = cb_data;
1899         struct ref_filter *filter = ref_cbdata->filter;
1900         struct ref_array_item *ref;
1901         struct commit *commit = NULL;
1902         unsigned int kind;
1903
1904         if (flag & REF_BAD_NAME) {
1905                 warning(_("ignoring ref with broken name %s"), refname);
1906                 return 0;
1907         }
1908
1909         if (flag & REF_ISBROKEN) {
1910                 warning(_("ignoring broken ref %s"), refname);
1911                 return 0;
1912         }
1913
1914         /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1915         kind = filter_ref_kind(filter, refname);
1916         if (!(kind & filter->kind))
1917                 return 0;
1918
1919         if (!filter_pattern_match(filter, refname))
1920                 return 0;
1921
1922         if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1923                 return 0;
1924
1925         /*
1926          * A merge filter is applied on refs pointing to commits. Hence
1927          * obtain the commit using the 'oid' available and discard all
1928          * non-commits early. The actual filtering is done later.
1929          */
1930         if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1931                 commit = lookup_commit_reference_gently(oid, 1);
1932                 if (!commit)
1933                         return 0;
1934                 /* We perform the filtering for the '--contains' option... */
1935                 if (filter->with_commit &&
1936                     !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1937                         return 0;
1938                 /* ...or for the `--no-contains' option */
1939                 if (filter->no_commit &&
1940                     commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1941                         return 0;
1942         }
1943
1944         /*
1945          * We do not open the object yet; sort may only need refname
1946          * to do its job and the resulting list may yet to be pruned
1947          * by maxcount logic.
1948          */
1949         ref = new_ref_array_item(refname, oid->hash, flag);
1950         ref->commit = commit;
1951
1952         REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1953         ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1954         ref->kind = kind;
1955         return 0;
1956 }
1957
1958 /*  Free memory allocated for a ref_array_item */
1959 static void free_array_item(struct ref_array_item *item)
1960 {
1961         free((char *)item->symref);
1962         free(item);
1963 }
1964
1965 /* Free all memory allocated for ref_array */
1966 void ref_array_clear(struct ref_array *array)
1967 {
1968         int i;
1969
1970         for (i = 0; i < array->nr; i++)
1971                 free_array_item(array->items[i]);
1972         FREE_AND_NULL(array->items);
1973         array->nr = array->alloc = 0;
1974 }
1975
1976 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1977 {
1978         struct rev_info revs;
1979         int i, old_nr;
1980         struct ref_filter *filter = ref_cbdata->filter;
1981         struct ref_array *array = ref_cbdata->array;
1982         struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1983
1984         init_revisions(&revs, NULL);
1985
1986         for (i = 0; i < array->nr; i++) {
1987                 struct ref_array_item *item = array->items[i];
1988                 add_pending_object(&revs, &item->commit->object, item->refname);
1989                 to_clear[i] = item->commit;
1990         }
1991
1992         filter->merge_commit->object.flags |= UNINTERESTING;
1993         add_pending_object(&revs, &filter->merge_commit->object, "");
1994
1995         revs.limited = 1;
1996         if (prepare_revision_walk(&revs))
1997                 die(_("revision walk setup failed"));
1998
1999         old_nr = array->nr;
2000         array->nr = 0;
2001
2002         for (i = 0; i < old_nr; i++) {
2003                 struct ref_array_item *item = array->items[i];
2004                 struct commit *commit = item->commit;
2005
2006                 int is_merged = !!(commit->object.flags & UNINTERESTING);
2007
2008                 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2009                         array->items[array->nr++] = array->items[i];
2010                 else
2011                         free_array_item(item);
2012         }
2013
2014         clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2015         clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2016         free(to_clear);
2017 }
2018
2019 /*
2020  * API for filtering a set of refs. Based on the type of refs the user
2021  * has requested, we iterate through those refs and apply filters
2022  * as per the given ref_filter structure and finally store the
2023  * filtered refs in the ref_array structure.
2024  */
2025 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2026 {
2027         struct ref_filter_cbdata ref_cbdata;
2028         int ret = 0;
2029         unsigned int broken = 0;
2030
2031         ref_cbdata.array = array;
2032         ref_cbdata.filter = filter;
2033
2034         if (type & FILTER_REFS_INCLUDE_BROKEN)
2035                 broken = 1;
2036         filter->kind = type & FILTER_REFS_KIND_MASK;
2037
2038         init_contains_cache(&ref_cbdata.contains_cache);
2039         init_contains_cache(&ref_cbdata.no_contains_cache);
2040
2041         /*  Simple per-ref filtering */
2042         if (!filter->kind)
2043                 die("filter_refs: invalid type");
2044         else {
2045                 /*
2046                  * For common cases where we need only branches or remotes or tags,
2047                  * we only iterate through those refs. If a mix of refs is needed,
2048                  * we iterate over all refs and filter out required refs with the help
2049                  * of filter_ref_kind().
2050                  */
2051                 if (filter->kind == FILTER_REFS_BRANCHES)
2052                         ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2053                 else if (filter->kind == FILTER_REFS_REMOTES)
2054                         ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2055                 else if (filter->kind == FILTER_REFS_TAGS)
2056                         ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2057                 else if (filter->kind & FILTER_REFS_ALL)
2058                         ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2059                 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2060                         head_ref(ref_filter_handler, &ref_cbdata);
2061         }
2062
2063         clear_contains_cache(&ref_cbdata.contains_cache);
2064         clear_contains_cache(&ref_cbdata.no_contains_cache);
2065
2066         /*  Filters that need revision walking */
2067         if (filter->merge_commit)
2068                 do_merge_filter(&ref_cbdata);
2069
2070         return ret;
2071 }
2072
2073 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2074 {
2075         struct atom_value *va, *vb;
2076         int cmp;
2077         cmp_type cmp_type = used_atom[s->atom].type;
2078         int (*cmp_fn)(const char *, const char *);
2079
2080         get_ref_atom_value(a, s->atom, &va);
2081         get_ref_atom_value(b, s->atom, &vb);
2082         cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2083         if (s->version)
2084                 cmp = versioncmp(va->s, vb->s);
2085         else if (cmp_type == FIELD_STR)
2086                 cmp = cmp_fn(va->s, vb->s);
2087         else {
2088                 if (va->value < vb->value)
2089                         cmp = -1;
2090                 else if (va->value == vb->value)
2091                         cmp = cmp_fn(a->refname, b->refname);
2092                 else
2093                         cmp = 1;
2094         }
2095
2096         return (s->reverse) ? -cmp : cmp;
2097 }
2098
2099 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2100 {
2101         struct ref_array_item *a = *((struct ref_array_item **)a_);
2102         struct ref_array_item *b = *((struct ref_array_item **)b_);
2103         struct ref_sorting *s;
2104
2105         for (s = ref_sorting; s; s = s->next) {
2106                 int cmp = cmp_ref_sorting(s, a, b);
2107                 if (cmp)
2108                         return cmp;
2109         }
2110         return 0;
2111 }
2112
2113 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2114 {
2115         QSORT_S(array->items, array->nr, compare_refs, sorting);
2116 }
2117
2118 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2119 {
2120         struct strbuf *s = &state->stack->output;
2121
2122         while (*cp && (!ep || cp < ep)) {
2123                 if (*cp == '%') {
2124                         if (cp[1] == '%')
2125                                 cp++;
2126                         else {
2127                                 int ch = hex2chr(cp + 1);
2128                                 if (0 <= ch) {
2129                                         strbuf_addch(s, ch);
2130                                         cp += 3;
2131                                         continue;
2132                                 }
2133                         }
2134                 }
2135                 strbuf_addch(s, *cp);
2136                 cp++;
2137         }
2138 }
2139
2140 void format_ref_array_item(struct ref_array_item *info,
2141                            const struct ref_format *format,
2142                            struct strbuf *final_buf)
2143 {
2144         const char *cp, *sp, *ep;
2145         struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2146
2147         state.quote_style = format->quote_style;
2148         push_stack_element(&state.stack);
2149
2150         for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2151                 struct atom_value *atomv;
2152
2153                 ep = strchr(sp, ')');
2154                 if (cp < sp)
2155                         append_literal(cp, sp, &state);
2156                 get_ref_atom_value(info,
2157                                    parse_ref_filter_atom(format, sp + 2, ep),
2158                                    &atomv);
2159                 atomv->handler(atomv, &state);
2160         }
2161         if (*cp) {
2162                 sp = cp + strlen(cp);
2163                 append_literal(cp, sp, &state);
2164         }
2165         if (format->need_color_reset_at_eol) {
2166                 struct atom_value resetv;
2167                 resetv.s = GIT_COLOR_RESET;
2168                 append_atom(&resetv, &state);
2169         }
2170         if (state.stack->prev)
2171                 die(_("format: %%(end) atom missing"));
2172         strbuf_addbuf(final_buf, &state.stack->output);
2173         pop_stack_element(&state.stack);
2174 }
2175
2176 void show_ref_array_item(struct ref_array_item *info,
2177                          const struct ref_format *format)
2178 {
2179         struct strbuf final_buf = STRBUF_INIT;
2180
2181         format_ref_array_item(info, format, &final_buf);
2182         fwrite(final_buf.buf, 1, final_buf.len, stdout);
2183         strbuf_release(&final_buf);
2184         putchar('\n');
2185 }
2186
2187 void pretty_print_ref(const char *name, const unsigned char *sha1,
2188                       const struct ref_format *format)
2189 {
2190         struct ref_array_item *ref_item;
2191         ref_item = new_ref_array_item(name, sha1, 0);
2192         ref_item->kind = ref_kind_from_refname(name);
2193         show_ref_array_item(ref_item, format);
2194         free_array_item(ref_item);
2195 }
2196
2197 static int parse_sorting_atom(const char *atom)
2198 {
2199         /*
2200          * This parses an atom using a dummy ref_format, since we don't
2201          * actually care about the formatting details.
2202          */
2203         struct ref_format dummy = REF_FORMAT_INIT;
2204         const char *end = atom + strlen(atom);
2205         return parse_ref_filter_atom(&dummy, atom, end);
2206 }
2207
2208 /*  If no sorting option is given, use refname to sort as default */
2209 struct ref_sorting *ref_default_sorting(void)
2210 {
2211         static const char cstr_name[] = "refname";
2212
2213         struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2214
2215         sorting->next = NULL;
2216         sorting->atom = parse_sorting_atom(cstr_name);
2217         return sorting;
2218 }
2219
2220 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2221 {
2222         struct ref_sorting *s;
2223
2224         s = xcalloc(1, sizeof(*s));
2225         s->next = *sorting_tail;
2226         *sorting_tail = s;
2227
2228         if (*arg == '-') {
2229                 s->reverse = 1;
2230                 arg++;
2231         }
2232         if (skip_prefix(arg, "version:", &arg) ||
2233             skip_prefix(arg, "v:", &arg))
2234                 s->version = 1;
2235         s->atom = parse_sorting_atom(arg);
2236 }
2237
2238 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2239 {
2240         if (!arg) /* should --no-sort void the list ? */
2241                 return -1;
2242         parse_ref_sorting(opt->value, arg);
2243         return 0;
2244 }
2245
2246 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2247 {
2248         struct ref_filter *rf = opt->value;
2249         struct object_id oid;
2250         int no_merged = starts_with(opt->long_name, "no");
2251
2252         if (rf->merge) {
2253                 if (no_merged) {
2254                         return opterror(opt, "is incompatible with --merged", 0);
2255                 } else {
2256                         return opterror(opt, "is incompatible with --no-merged", 0);
2257                 }
2258         }
2259
2260         rf->merge = no_merged
2261                 ? REF_FILTER_MERGED_OMIT
2262                 : REF_FILTER_MERGED_INCLUDE;
2263
2264         if (get_oid(arg, &oid))
2265                 die(_("malformed object name %s"), arg);
2266
2267         rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2268         if (!rf->merge_commit)
2269                 return opterror(opt, "must point to a commit", 0);
2270
2271         return 0;
2272 }