ref-filter: make %(upstream:track) prints "[gone]" for invalid upstreams
[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                         *s = "[gone]";
1078                         return;
1079                 }
1080
1081                 if (!num_ours && !num_theirs)
1082                         *s = "";
1083                 else if (!num_ours)
1084                         *s = xstrfmt("[behind %d]", num_theirs);
1085                 else if (!num_theirs)
1086                         *s = xstrfmt("[ahead %d]", num_ours);
1087                 else
1088                         *s = xstrfmt("[ahead %d, behind %d]",
1089                                      num_ours, num_theirs);
1090         } else if (atom->u.remote_ref == RR_TRACKSHORT) {
1091                 if (stat_tracking_info(branch, &num_ours,
1092                                        &num_theirs, NULL))
1093                         return;
1094
1095                 if (!num_ours && !num_theirs)
1096                         *s = "=";
1097                 else if (!num_ours)
1098                         *s = "<";
1099                 else if (!num_theirs)
1100                         *s = ">";
1101                 else
1102                         *s = "<>";
1103         } else /* RR_NORMAL */
1104                 *s = refname;
1105 }
1106
1107 char *get_head_description(void)
1108 {
1109         struct strbuf desc = STRBUF_INIT;
1110         struct wt_status_state state;
1111         memset(&state, 0, sizeof(state));
1112         wt_status_get_state(&state, 1);
1113         if (state.rebase_in_progress ||
1114             state.rebase_interactive_in_progress)
1115                 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1116                             state.branch);
1117         else if (state.bisect_in_progress)
1118                 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1119                             state.branch);
1120         else if (state.detached_from) {
1121                 /* TRANSLATORS: make sure these match _("HEAD detached at ")
1122                    and _("HEAD detached from ") in wt-status.c */
1123                 if (state.detached_at)
1124                         strbuf_addf(&desc, _("(HEAD detached at %s)"),
1125                                 state.detached_from);
1126                 else
1127                         strbuf_addf(&desc, _("(HEAD detached from %s)"),
1128                                 state.detached_from);
1129         }
1130         else
1131                 strbuf_addstr(&desc, _("(no branch)"));
1132         free(state.branch);
1133         free(state.onto);
1134         free(state.detached_from);
1135         return strbuf_detach(&desc, NULL);
1136 }
1137
1138 /*
1139  * Parse the object referred by ref, and grab needed value.
1140  */
1141 static void populate_value(struct ref_array_item *ref)
1142 {
1143         void *buf;
1144         struct object *obj;
1145         int eaten, i;
1146         unsigned long size;
1147         const unsigned char *tagged;
1148
1149         ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1150
1151         if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1152                 unsigned char unused1[20];
1153                 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1154                                              unused1, NULL);
1155                 if (!ref->symref)
1156                         ref->symref = "";
1157         }
1158
1159         /* Fill in specials first */
1160         for (i = 0; i < used_atom_cnt; i++) {
1161                 struct used_atom *atom = &used_atom[i];
1162                 const char *name = used_atom[i].name;
1163                 struct atom_value *v = &ref->value[i];
1164                 int deref = 0;
1165                 const char *refname;
1166                 const char *formatp;
1167                 struct branch *branch = NULL;
1168
1169                 v->handler = append_atom;
1170                 v->atom = atom;
1171
1172                 if (*name == '*') {
1173                         deref = 1;
1174                         name++;
1175                 }
1176
1177                 if (starts_with(name, "refname")) {
1178                         refname = ref->refname;
1179                         if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1180                                 refname = get_head_description();
1181                 } else if (starts_with(name, "symref"))
1182                         refname = ref->symref ? ref->symref : "";
1183                 else if (starts_with(name, "upstream")) {
1184                         const char *branch_name;
1185                         /* only local branches may have an upstream */
1186                         if (!skip_prefix(ref->refname, "refs/heads/",
1187                                          &branch_name))
1188                                 continue;
1189                         branch = branch_get(branch_name);
1190
1191                         refname = branch_get_upstream(branch, NULL);
1192                         if (refname)
1193                                 fill_remote_ref_details(atom, refname, branch, &v->s);
1194                         continue;
1195                 } else if (starts_with(name, "push")) {
1196                         const char *branch_name;
1197                         if (!skip_prefix(ref->refname, "refs/heads/",
1198                                          &branch_name))
1199                                 continue;
1200                         branch = branch_get(branch_name);
1201
1202                         refname = branch_get_push(branch, NULL);
1203                         if (!refname)
1204                                 continue;
1205                         fill_remote_ref_details(atom, refname, branch, &v->s);
1206                         continue;
1207                 } else if (starts_with(name, "color:")) {
1208                         v->s = atom->u.color;
1209                         continue;
1210                 } else if (!strcmp(name, "flag")) {
1211                         char buf[256], *cp = buf;
1212                         if (ref->flag & REF_ISSYMREF)
1213                                 cp = copy_advance(cp, ",symref");
1214                         if (ref->flag & REF_ISPACKED)
1215                                 cp = copy_advance(cp, ",packed");
1216                         if (cp == buf)
1217                                 v->s = "";
1218                         else {
1219                                 *cp = '\0';
1220                                 v->s = xstrdup(buf + 1);
1221                         }
1222                         continue;
1223                 } else if (!deref && grab_objectname(name, ref->objectname, v, atom)) {
1224                         continue;
1225                 } else if (!strcmp(name, "HEAD")) {
1226                         const char *head;
1227                         unsigned char sha1[20];
1228
1229                         head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1230                                                   sha1, NULL);
1231                         if (head && !strcmp(ref->refname, head))
1232                                 v->s = "*";
1233                         else
1234                                 v->s = " ";
1235                         continue;
1236                 } else if (starts_with(name, "align")) {
1237                         v->handler = align_atom_handler;
1238                         continue;
1239                 } else if (!strcmp(name, "end")) {
1240                         v->handler = end_atom_handler;
1241                         continue;
1242                 } else if (starts_with(name, "if")) {
1243                         const char *s;
1244
1245                         if (skip_prefix(name, "if:", &s))
1246                                 v->s = xstrdup(s);
1247                         v->handler = if_atom_handler;
1248                         continue;
1249                 } else if (!strcmp(name, "then")) {
1250                         v->handler = then_atom_handler;
1251                         continue;
1252                 } else if (!strcmp(name, "else")) {
1253                         v->handler = else_atom_handler;
1254                         continue;
1255                 } else
1256                         continue;
1257
1258                 formatp = strchr(name, ':');
1259                 if (formatp) {
1260                         const char *arg;
1261
1262                         formatp++;
1263                         if (!strcmp(formatp, "short"))
1264                                 refname = shorten_unambiguous_ref(refname,
1265                                                       warn_ambiguous_refs);
1266                         else if (skip_prefix(formatp, "strip=", &arg))
1267                                 refname = strip_ref_components(refname, arg);
1268                         else
1269                                 die(_("unknown %.*s format %s"),
1270                                     (int)(formatp - name), name, formatp);
1271                 }
1272
1273                 if (!deref)
1274                         v->s = refname;
1275                 else
1276                         v->s = xstrfmt("%s^{}", refname);
1277         }
1278
1279         for (i = 0; i < used_atom_cnt; i++) {
1280                 struct atom_value *v = &ref->value[i];
1281                 if (v->s == NULL)
1282                         goto need_obj;
1283         }
1284         return;
1285
1286  need_obj:
1287         buf = get_obj(ref->objectname, &obj, &size, &eaten);
1288         if (!buf)
1289                 die(_("missing object %s for %s"),
1290                     sha1_to_hex(ref->objectname), ref->refname);
1291         if (!obj)
1292                 die(_("parse_object_buffer failed on %s for %s"),
1293                     sha1_to_hex(ref->objectname), ref->refname);
1294
1295         grab_values(ref->value, 0, obj, buf, size);
1296         if (!eaten)
1297                 free(buf);
1298
1299         /*
1300          * If there is no atom that wants to know about tagged
1301          * object, we are done.
1302          */
1303         if (!need_tagged || (obj->type != OBJ_TAG))
1304                 return;
1305
1306         /*
1307          * If it is a tag object, see if we use a value that derefs
1308          * the object, and if we do grab the object it refers to.
1309          */
1310         tagged = ((struct tag *)obj)->tagged->oid.hash;
1311
1312         /*
1313          * NEEDSWORK: This derefs tag only once, which
1314          * is good to deal with chains of trust, but
1315          * is not consistent with what deref_tag() does
1316          * which peels the onion to the core.
1317          */
1318         buf = get_obj(tagged, &obj, &size, &eaten);
1319         if (!buf)
1320                 die(_("missing object %s for %s"),
1321                     sha1_to_hex(tagged), ref->refname);
1322         if (!obj)
1323                 die(_("parse_object_buffer failed on %s for %s"),
1324                     sha1_to_hex(tagged), ref->refname);
1325         grab_values(ref->value, 1, obj, buf, size);
1326         if (!eaten)
1327                 free(buf);
1328 }
1329
1330 /*
1331  * Given a ref, return the value for the atom.  This lazily gets value
1332  * out of the object by calling populate value.
1333  */
1334 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1335 {
1336         if (!ref->value) {
1337                 populate_value(ref);
1338                 fill_missing_values(ref->value);
1339         }
1340         *v = &ref->value[atom];
1341 }
1342
1343 enum contains_result {
1344         CONTAINS_UNKNOWN = -1,
1345         CONTAINS_NO = 0,
1346         CONTAINS_YES = 1
1347 };
1348
1349 /*
1350  * Mimicking the real stack, this stack lives on the heap, avoiding stack
1351  * overflows.
1352  *
1353  * At each recursion step, the stack items points to the commits whose
1354  * ancestors are to be inspected.
1355  */
1356 struct contains_stack {
1357         int nr, alloc;
1358         struct contains_stack_entry {
1359                 struct commit *commit;
1360                 struct commit_list *parents;
1361         } *contains_stack;
1362 };
1363
1364 static int in_commit_list(const struct commit_list *want, struct commit *c)
1365 {
1366         for (; want; want = want->next)
1367                 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1368                         return 1;
1369         return 0;
1370 }
1371
1372 /*
1373  * Test whether the candidate or one of its parents is contained in the list.
1374  * Do not recurse to find out, though, but return -1 if inconclusive.
1375  */
1376 static enum contains_result contains_test(struct commit *candidate,
1377                             const struct commit_list *want)
1378 {
1379         /* was it previously marked as containing a want commit? */
1380         if (candidate->object.flags & TMP_MARK)
1381                 return 1;
1382         /* or marked as not possibly containing a want commit? */
1383         if (candidate->object.flags & UNINTERESTING)
1384                 return 0;
1385         /* or are we it? */
1386         if (in_commit_list(want, candidate)) {
1387                 candidate->object.flags |= TMP_MARK;
1388                 return 1;
1389         }
1390
1391         if (parse_commit(candidate) < 0)
1392                 return 0;
1393
1394         return -1;
1395 }
1396
1397 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1398 {
1399         ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1400         contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1401         contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1402 }
1403
1404 static enum contains_result contains_tag_algo(struct commit *candidate,
1405                 const struct commit_list *want)
1406 {
1407         struct contains_stack contains_stack = { 0, 0, NULL };
1408         int result = contains_test(candidate, want);
1409
1410         if (result != CONTAINS_UNKNOWN)
1411                 return result;
1412
1413         push_to_contains_stack(candidate, &contains_stack);
1414         while (contains_stack.nr) {
1415                 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1416                 struct commit *commit = entry->commit;
1417                 struct commit_list *parents = entry->parents;
1418
1419                 if (!parents) {
1420                         commit->object.flags |= UNINTERESTING;
1421                         contains_stack.nr--;
1422                 }
1423                 /*
1424                  * If we just popped the stack, parents->item has been marked,
1425                  * therefore contains_test will return a meaningful 0 or 1.
1426                  */
1427                 else switch (contains_test(parents->item, want)) {
1428                 case CONTAINS_YES:
1429                         commit->object.flags |= TMP_MARK;
1430                         contains_stack.nr--;
1431                         break;
1432                 case CONTAINS_NO:
1433                         entry->parents = parents->next;
1434                         break;
1435                 case CONTAINS_UNKNOWN:
1436                         push_to_contains_stack(parents->item, &contains_stack);
1437                         break;
1438                 }
1439         }
1440         free(contains_stack.contains_stack);
1441         return contains_test(candidate, want);
1442 }
1443
1444 static int commit_contains(struct ref_filter *filter, struct commit *commit)
1445 {
1446         if (filter->with_commit_tag_algo)
1447                 return contains_tag_algo(commit, filter->with_commit);
1448         return is_descendant_of(commit, filter->with_commit);
1449 }
1450
1451 /*
1452  * Return 1 if the refname matches one of the patterns, otherwise 0.
1453  * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1454  * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1455  * matches "refs/heads/mas*", too).
1456  */
1457 static int match_pattern(const struct ref_filter *filter, const char *refname)
1458 {
1459         const char **patterns = filter->name_patterns;
1460         unsigned flags = 0;
1461
1462         if (filter->ignore_case)
1463                 flags |= WM_CASEFOLD;
1464
1465         /*
1466          * When no '--format' option is given we need to skip the prefix
1467          * for matching refs of tags and branches.
1468          */
1469         (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1470                skip_prefix(refname, "refs/heads/", &refname) ||
1471                skip_prefix(refname, "refs/remotes/", &refname) ||
1472                skip_prefix(refname, "refs/", &refname));
1473
1474         for (; *patterns; patterns++) {
1475                 if (!wildmatch(*patterns, refname, flags, NULL))
1476                         return 1;
1477         }
1478         return 0;
1479 }
1480
1481 /*
1482  * Return 1 if the refname matches one of the patterns, otherwise 0.
1483  * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1484  * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1485  * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1486  */
1487 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1488 {
1489         const char **pattern = filter->name_patterns;
1490         int namelen = strlen(refname);
1491         unsigned flags = WM_PATHNAME;
1492
1493         if (filter->ignore_case)
1494                 flags |= WM_CASEFOLD;
1495
1496         for (; *pattern; pattern++) {
1497                 const char *p = *pattern;
1498                 int plen = strlen(p);
1499
1500                 if ((plen <= namelen) &&
1501                     !strncmp(refname, p, plen) &&
1502                     (refname[plen] == '\0' ||
1503                      refname[plen] == '/' ||
1504                      p[plen-1] == '/'))
1505                         return 1;
1506                 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1507                         return 1;
1508         }
1509         return 0;
1510 }
1511
1512 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1513 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1514 {
1515         if (!*filter->name_patterns)
1516                 return 1; /* No pattern always matches */
1517         if (filter->match_as_path)
1518                 return match_name_as_path(filter, refname);
1519         return match_pattern(filter, refname);
1520 }
1521
1522 /*
1523  * Given a ref (sha1, refname), check if the ref belongs to the array
1524  * of sha1s. If the given ref is a tag, check if the given tag points
1525  * at one of the sha1s in the given sha1 array.
1526  * the given sha1_array.
1527  * NEEDSWORK:
1528  * 1. Only a single level of inderection is obtained, we might want to
1529  * change this to account for multiple levels (e.g. annotated tags
1530  * pointing to annotated tags pointing to a commit.)
1531  * 2. As the refs are cached we might know what refname peels to without
1532  * the need to parse the object via parse_object(). peel_ref() might be a
1533  * more efficient alternative to obtain the pointee.
1534  */
1535 static const unsigned char *match_points_at(struct sha1_array *points_at,
1536                                             const unsigned char *sha1,
1537                                             const char *refname)
1538 {
1539         const unsigned char *tagged_sha1 = NULL;
1540         struct object *obj;
1541
1542         if (sha1_array_lookup(points_at, sha1) >= 0)
1543                 return sha1;
1544         obj = parse_object(sha1);
1545         if (!obj)
1546                 die(_("malformed object at '%s'"), refname);
1547         if (obj->type == OBJ_TAG)
1548                 tagged_sha1 = ((struct tag *)obj)->tagged->oid.hash;
1549         if (tagged_sha1 && sha1_array_lookup(points_at, tagged_sha1) >= 0)
1550                 return tagged_sha1;
1551         return NULL;
1552 }
1553
1554 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1555 static struct ref_array_item *new_ref_array_item(const char *refname,
1556                                                  const unsigned char *objectname,
1557                                                  int flag)
1558 {
1559         struct ref_array_item *ref;
1560         FLEX_ALLOC_STR(ref, refname, refname);
1561         hashcpy(ref->objectname, objectname);
1562         ref->flag = flag;
1563
1564         return ref;
1565 }
1566
1567 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1568 {
1569         unsigned int i;
1570
1571         static struct {
1572                 const char *prefix;
1573                 unsigned int kind;
1574         } ref_kind[] = {
1575                 { "refs/heads/" , FILTER_REFS_BRANCHES },
1576                 { "refs/remotes/" , FILTER_REFS_REMOTES },
1577                 { "refs/tags/", FILTER_REFS_TAGS}
1578         };
1579
1580         if (filter->kind == FILTER_REFS_BRANCHES ||
1581             filter->kind == FILTER_REFS_REMOTES ||
1582             filter->kind == FILTER_REFS_TAGS)
1583                 return filter->kind;
1584         else if (!strcmp(refname, "HEAD"))
1585                 return FILTER_REFS_DETACHED_HEAD;
1586
1587         for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1588                 if (starts_with(refname, ref_kind[i].prefix))
1589                         return ref_kind[i].kind;
1590         }
1591
1592         return FILTER_REFS_OTHERS;
1593 }
1594
1595 /*
1596  * A call-back given to for_each_ref().  Filter refs and keep them for
1597  * later object processing.
1598  */
1599 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1600 {
1601         struct ref_filter_cbdata *ref_cbdata = cb_data;
1602         struct ref_filter *filter = ref_cbdata->filter;
1603         struct ref_array_item *ref;
1604         struct commit *commit = NULL;
1605         unsigned int kind;
1606
1607         if (flag & REF_BAD_NAME) {
1608                 warning(_("ignoring ref with broken name %s"), refname);
1609                 return 0;
1610         }
1611
1612         if (flag & REF_ISBROKEN) {
1613                 warning(_("ignoring broken ref %s"), refname);
1614                 return 0;
1615         }
1616
1617         /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1618         kind = filter_ref_kind(filter, refname);
1619         if (!(kind & filter->kind))
1620                 return 0;
1621
1622         if (!filter_pattern_match(filter, refname))
1623                 return 0;
1624
1625         if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1626                 return 0;
1627
1628         /*
1629          * A merge filter is applied on refs pointing to commits. Hence
1630          * obtain the commit using the 'oid' available and discard all
1631          * non-commits early. The actual filtering is done later.
1632          */
1633         if (filter->merge_commit || filter->with_commit || filter->verbose) {
1634                 commit = lookup_commit_reference_gently(oid->hash, 1);
1635                 if (!commit)
1636                         return 0;
1637                 /* We perform the filtering for the '--contains' option */
1638                 if (filter->with_commit &&
1639                     !commit_contains(filter, commit))
1640                         return 0;
1641         }
1642
1643         /*
1644          * We do not open the object yet; sort may only need refname
1645          * to do its job and the resulting list may yet to be pruned
1646          * by maxcount logic.
1647          */
1648         ref = new_ref_array_item(refname, oid->hash, flag);
1649         ref->commit = commit;
1650
1651         REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1652         ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1653         ref->kind = kind;
1654         return 0;
1655 }
1656
1657 /*  Free memory allocated for a ref_array_item */
1658 static void free_array_item(struct ref_array_item *item)
1659 {
1660         free((char *)item->symref);
1661         free(item);
1662 }
1663
1664 /* Free all memory allocated for ref_array */
1665 void ref_array_clear(struct ref_array *array)
1666 {
1667         int i;
1668
1669         for (i = 0; i < array->nr; i++)
1670                 free_array_item(array->items[i]);
1671         free(array->items);
1672         array->items = NULL;
1673         array->nr = array->alloc = 0;
1674 }
1675
1676 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1677 {
1678         struct rev_info revs;
1679         int i, old_nr;
1680         struct ref_filter *filter = ref_cbdata->filter;
1681         struct ref_array *array = ref_cbdata->array;
1682         struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1683
1684         init_revisions(&revs, NULL);
1685
1686         for (i = 0; i < array->nr; i++) {
1687                 struct ref_array_item *item = array->items[i];
1688                 add_pending_object(&revs, &item->commit->object, item->refname);
1689                 to_clear[i] = item->commit;
1690         }
1691
1692         filter->merge_commit->object.flags |= UNINTERESTING;
1693         add_pending_object(&revs, &filter->merge_commit->object, "");
1694
1695         revs.limited = 1;
1696         if (prepare_revision_walk(&revs))
1697                 die(_("revision walk setup failed"));
1698
1699         old_nr = array->nr;
1700         array->nr = 0;
1701
1702         for (i = 0; i < old_nr; i++) {
1703                 struct ref_array_item *item = array->items[i];
1704                 struct commit *commit = item->commit;
1705
1706                 int is_merged = !!(commit->object.flags & UNINTERESTING);
1707
1708                 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1709                         array->items[array->nr++] = array->items[i];
1710                 else
1711                         free_array_item(item);
1712         }
1713
1714         for (i = 0; i < old_nr; i++)
1715                 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1716         clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1717         free(to_clear);
1718 }
1719
1720 /*
1721  * API for filtering a set of refs. Based on the type of refs the user
1722  * has requested, we iterate through those refs and apply filters
1723  * as per the given ref_filter structure and finally store the
1724  * filtered refs in the ref_array structure.
1725  */
1726 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1727 {
1728         struct ref_filter_cbdata ref_cbdata;
1729         int ret = 0;
1730         unsigned int broken = 0;
1731
1732         ref_cbdata.array = array;
1733         ref_cbdata.filter = filter;
1734
1735         if (type & FILTER_REFS_INCLUDE_BROKEN)
1736                 broken = 1;
1737         filter->kind = type & FILTER_REFS_KIND_MASK;
1738
1739         /*  Simple per-ref filtering */
1740         if (!filter->kind)
1741                 die("filter_refs: invalid type");
1742         else {
1743                 /*
1744                  * For common cases where we need only branches or remotes or tags,
1745                  * we only iterate through those refs. If a mix of refs is needed,
1746                  * we iterate over all refs and filter out required refs with the help
1747                  * of filter_ref_kind().
1748                  */
1749                 if (filter->kind == FILTER_REFS_BRANCHES)
1750                         ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1751                 else if (filter->kind == FILTER_REFS_REMOTES)
1752                         ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1753                 else if (filter->kind == FILTER_REFS_TAGS)
1754                         ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1755                 else if (filter->kind & FILTER_REFS_ALL)
1756                         ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1757                 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1758                         head_ref(ref_filter_handler, &ref_cbdata);
1759         }
1760
1761
1762         /*  Filters that need revision walking */
1763         if (filter->merge_commit)
1764                 do_merge_filter(&ref_cbdata);
1765
1766         return ret;
1767 }
1768
1769 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1770 {
1771         struct atom_value *va, *vb;
1772         int cmp;
1773         cmp_type cmp_type = used_atom[s->atom].type;
1774         int (*cmp_fn)(const char *, const char *);
1775
1776         get_ref_atom_value(a, s->atom, &va);
1777         get_ref_atom_value(b, s->atom, &vb);
1778         cmp_fn = s->ignore_case ? strcasecmp : strcmp;
1779         if (s->version)
1780                 cmp = versioncmp(va->s, vb->s);
1781         else if (cmp_type == FIELD_STR)
1782                 cmp = cmp_fn(va->s, vb->s);
1783         else {
1784                 if (va->ul < vb->ul)
1785                         cmp = -1;
1786                 else if (va->ul == vb->ul)
1787                         cmp = cmp_fn(a->refname, b->refname);
1788                 else
1789                         cmp = 1;
1790         }
1791
1792         return (s->reverse) ? -cmp : cmp;
1793 }
1794
1795 static struct ref_sorting *ref_sorting;
1796 static int compare_refs(const void *a_, const void *b_)
1797 {
1798         struct ref_array_item *a = *((struct ref_array_item **)a_);
1799         struct ref_array_item *b = *((struct ref_array_item **)b_);
1800         struct ref_sorting *s;
1801
1802         for (s = ref_sorting; s; s = s->next) {
1803                 int cmp = cmp_ref_sorting(s, a, b);
1804                 if (cmp)
1805                         return cmp;
1806         }
1807         return 0;
1808 }
1809
1810 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1811 {
1812         ref_sorting = sorting;
1813         QSORT(array->items, array->nr, compare_refs);
1814 }
1815
1816 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1817 {
1818         struct strbuf *s = &state->stack->output;
1819
1820         while (*cp && (!ep || cp < ep)) {
1821                 if (*cp == '%') {
1822                         if (cp[1] == '%')
1823                                 cp++;
1824                         else {
1825                                 int ch = hex2chr(cp + 1);
1826                                 if (0 <= ch) {
1827                                         strbuf_addch(s, ch);
1828                                         cp += 3;
1829                                         continue;
1830                                 }
1831                         }
1832                 }
1833                 strbuf_addch(s, *cp);
1834                 cp++;
1835         }
1836 }
1837
1838 void format_ref_array_item(struct ref_array_item *info, const char *format,
1839                            int quote_style, struct strbuf *final_buf)
1840 {
1841         const char *cp, *sp, *ep;
1842         struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1843
1844         state.quote_style = quote_style;
1845         push_stack_element(&state.stack);
1846
1847         for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1848                 struct atom_value *atomv;
1849
1850                 ep = strchr(sp, ')');
1851                 if (cp < sp)
1852                         append_literal(cp, sp, &state);
1853                 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1854                 atomv->handler(atomv, &state);
1855         }
1856         if (*cp) {
1857                 sp = cp + strlen(cp);
1858                 append_literal(cp, sp, &state);
1859         }
1860         if (need_color_reset_at_eol) {
1861                 struct atom_value resetv;
1862                 char color[COLOR_MAXLEN] = "";
1863
1864                 if (color_parse("reset", color) < 0)
1865                         die("BUG: couldn't parse 'reset' as a color");
1866                 resetv.s = color;
1867                 append_atom(&resetv, &state);
1868         }
1869         if (state.stack->prev)
1870                 die(_("format: %%(end) atom missing"));
1871         strbuf_addbuf(final_buf, &state.stack->output);
1872         pop_stack_element(&state.stack);
1873 }
1874
1875 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
1876 {
1877         struct strbuf final_buf = STRBUF_INIT;
1878
1879         format_ref_array_item(info, format, quote_style, &final_buf);
1880         fwrite(final_buf.buf, 1, final_buf.len, stdout);
1881         strbuf_release(&final_buf);
1882         putchar('\n');
1883 }
1884
1885 /*  If no sorting option is given, use refname to sort as default */
1886 struct ref_sorting *ref_default_sorting(void)
1887 {
1888         static const char cstr_name[] = "refname";
1889
1890         struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
1891
1892         sorting->next = NULL;
1893         sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
1894         return sorting;
1895 }
1896
1897 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
1898 {
1899         struct ref_sorting **sorting_tail = opt->value;
1900         struct ref_sorting *s;
1901         int len;
1902
1903         if (!arg) /* should --no-sort void the list ? */
1904                 return -1;
1905
1906         s = xcalloc(1, sizeof(*s));
1907         s->next = *sorting_tail;
1908         *sorting_tail = s;
1909
1910         if (*arg == '-') {
1911                 s->reverse = 1;
1912                 arg++;
1913         }
1914         if (skip_prefix(arg, "version:", &arg) ||
1915             skip_prefix(arg, "v:", &arg))
1916                 s->version = 1;
1917         len = strlen(arg);
1918         s->atom = parse_ref_filter_atom(arg, arg+len);
1919         return 0;
1920 }
1921
1922 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
1923 {
1924         struct ref_filter *rf = opt->value;
1925         unsigned char sha1[20];
1926
1927         rf->merge = starts_with(opt->long_name, "no")
1928                 ? REF_FILTER_MERGED_OMIT
1929                 : REF_FILTER_MERGED_INCLUDE;
1930
1931         if (get_sha1(arg, sha1))
1932                 die(_("malformed object name %s"), arg);
1933
1934         rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
1935         if (!rf->merge_commit)
1936                 return opterror(opt, "must point to a commit", 0);
1937
1938         return 0;
1939 }