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