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