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