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