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