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