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