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