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