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