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