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