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