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