Merge branch 'maint-2.5' into maint-2.6
[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
13 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
14
15 static struct {
16         const char *name;
17         cmp_type cmp_type;
18 } valid_atom[] = {
19         { "refname" },
20         { "objecttype" },
21         { "objectsize", FIELD_ULONG },
22         { "objectname" },
23         { "tree" },
24         { "parent" },
25         { "numparent", FIELD_ULONG },
26         { "object" },
27         { "type" },
28         { "tag" },
29         { "author" },
30         { "authorname" },
31         { "authoremail" },
32         { "authordate", FIELD_TIME },
33         { "committer" },
34         { "committername" },
35         { "committeremail" },
36         { "committerdate", FIELD_TIME },
37         { "tagger" },
38         { "taggername" },
39         { "taggeremail" },
40         { "taggerdate", FIELD_TIME },
41         { "creator" },
42         { "creatordate", FIELD_TIME },
43         { "subject" },
44         { "body" },
45         { "contents" },
46         { "contents:subject" },
47         { "contents:body" },
48         { "contents:signature" },
49         { "upstream" },
50         { "push" },
51         { "symref" },
52         { "flag" },
53         { "HEAD" },
54         { "color" },
55 };
56
57 /*
58  * An atom is a valid field atom listed above, possibly prefixed with
59  * a "*" to denote deref_tag().
60  *
61  * We parse given format string and sort specifiers, and make a list
62  * of properties that we need to extract out of objects.  ref_array_item
63  * structure will hold an array of values extracted that can be
64  * indexed with the "atom number", which is an index into this
65  * array.
66  */
67 static const char **used_atom;
68 static cmp_type *used_atom_type;
69 static int used_atom_cnt, need_tagged, need_symref;
70 static int need_color_reset_at_eol;
71
72 /*
73  * Used to parse format string and sort specifiers
74  */
75 int parse_ref_filter_atom(const char *atom, const char *ep)
76 {
77         const char *sp;
78         int i, at;
79
80         sp = atom;
81         if (*sp == '*' && sp < ep)
82                 sp++; /* deref */
83         if (ep <= sp)
84                 die("malformed field name: %.*s", (int)(ep-atom), atom);
85
86         /* Do we have the atom already used elsewhere? */
87         for (i = 0; i < used_atom_cnt; i++) {
88                 int len = strlen(used_atom[i]);
89                 if (len == ep - atom && !memcmp(used_atom[i], atom, len))
90                         return i;
91         }
92
93         /* Is the atom a valid one? */
94         for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
95                 int len = strlen(valid_atom[i].name);
96                 /*
97                  * If the atom name has a colon, strip it and everything after
98                  * it off - it specifies the format for this entry, and
99                  * shouldn't be used for checking against the valid_atom
100                  * table.
101                  */
102                 const char *formatp = strchr(sp, ':');
103                 if (!formatp || ep < formatp)
104                         formatp = ep;
105                 if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
106                         break;
107         }
108
109         if (ARRAY_SIZE(valid_atom) <= i)
110                 die("unknown field name: %.*s", (int)(ep-atom), atom);
111
112         /* Add it in, including the deref prefix */
113         at = used_atom_cnt;
114         used_atom_cnt++;
115         REALLOC_ARRAY(used_atom, used_atom_cnt);
116         REALLOC_ARRAY(used_atom_type, used_atom_cnt);
117         used_atom[at] = xmemdupz(atom, ep - atom);
118         used_atom_type[at] = valid_atom[i].cmp_type;
119         if (*atom == '*')
120                 need_tagged = 1;
121         if (!strcmp(used_atom[at], "symref"))
122                 need_symref = 1;
123         return at;
124 }
125
126 /*
127  * In a format string, find the next occurrence of %(atom).
128  */
129 static const char *find_next(const char *cp)
130 {
131         while (*cp) {
132                 if (*cp == '%') {
133                         /*
134                          * %( is the start of an atom;
135                          * %% is a quoted per-cent.
136                          */
137                         if (cp[1] == '(')
138                                 return cp;
139                         else if (cp[1] == '%')
140                                 cp++; /* skip over two % */
141                         /* otherwise this is a singleton, literal % */
142                 }
143                 cp++;
144         }
145         return NULL;
146 }
147
148 /*
149  * Make sure the format string is well formed, and parse out
150  * the used atoms.
151  */
152 int verify_ref_format(const char *format)
153 {
154         const char *cp, *sp;
155
156         need_color_reset_at_eol = 0;
157         for (cp = format; *cp && (sp = find_next(cp)); ) {
158                 const char *color, *ep = strchr(sp, ')');
159                 int at;
160
161                 if (!ep)
162                         return error("malformed format string %s", sp);
163                 /* sp points at "%(" and ep points at the closing ")" */
164                 at = parse_ref_filter_atom(sp + 2, ep);
165                 cp = ep + 1;
166
167                 if (skip_prefix(used_atom[at], "color:", &color))
168                         need_color_reset_at_eol = !!strcmp(color, "reset");
169         }
170         return 0;
171 }
172
173 /*
174  * Given an object name, read the object data and size, and return a
175  * "struct object".  If the object data we are returning is also borrowed
176  * by the "struct object" representation, set *eaten as well---it is a
177  * signal from parse_object_buffer to us not to free the buffer.
178  */
179 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
180 {
181         enum object_type type;
182         void *buf = read_sha1_file(sha1, &type, sz);
183
184         if (buf)
185                 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
186         else
187                 *obj = NULL;
188         return buf;
189 }
190
191 static int grab_objectname(const char *name, const unsigned char *sha1,
192                             struct atom_value *v)
193 {
194         if (!strcmp(name, "objectname")) {
195                 char *s = xmalloc(41);
196                 strcpy(s, sha1_to_hex(sha1));
197                 v->s = s;
198                 return 1;
199         }
200         if (!strcmp(name, "objectname:short")) {
201                 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
202                 return 1;
203         }
204         return 0;
205 }
206
207 /* See grab_values */
208 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
209 {
210         int i;
211
212         for (i = 0; i < used_atom_cnt; i++) {
213                 const char *name = used_atom[i];
214                 struct atom_value *v = &val[i];
215                 if (!!deref != (*name == '*'))
216                         continue;
217                 if (deref)
218                         name++;
219                 if (!strcmp(name, "objecttype"))
220                         v->s = typename(obj->type);
221                 else if (!strcmp(name, "objectsize")) {
222                         char *s = xmalloc(40);
223                         sprintf(s, "%lu", sz);
224                         v->ul = sz;
225                         v->s = s;
226                 }
227                 else if (deref)
228                         grab_objectname(name, obj->sha1, v);
229         }
230 }
231
232 /* See grab_values */
233 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
234 {
235         int i;
236         struct tag *tag = (struct tag *) obj;
237
238         for (i = 0; i < used_atom_cnt; i++) {
239                 const char *name = used_atom[i];
240                 struct atom_value *v = &val[i];
241                 if (!!deref != (*name == '*'))
242                         continue;
243                 if (deref)
244                         name++;
245                 if (!strcmp(name, "tag"))
246                         v->s = tag->tag;
247                 else if (!strcmp(name, "type") && tag->tagged)
248                         v->s = typename(tag->tagged->type);
249                 else if (!strcmp(name, "object") && tag->tagged) {
250                         char *s = xmalloc(41);
251                         strcpy(s, sha1_to_hex(tag->tagged->sha1));
252                         v->s = s;
253                 }
254         }
255 }
256
257 /* See grab_values */
258 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
259 {
260         int i;
261         struct commit *commit = (struct commit *) obj;
262
263         for (i = 0; i < used_atom_cnt; i++) {
264                 const char *name = used_atom[i];
265                 struct atom_value *v = &val[i];
266                 if (!!deref != (*name == '*'))
267                         continue;
268                 if (deref)
269                         name++;
270                 if (!strcmp(name, "tree")) {
271                         char *s = xmalloc(41);
272                         strcpy(s, sha1_to_hex(commit->tree->object.sha1));
273                         v->s = s;
274                 }
275                 if (!strcmp(name, "numparent")) {
276                         char *s = xmalloc(40);
277                         v->ul = commit_list_count(commit->parents);
278                         sprintf(s, "%lu", v->ul);
279                         v->s = s;
280                 }
281                 else if (!strcmp(name, "parent")) {
282                         int num = commit_list_count(commit->parents);
283                         int i;
284                         struct commit_list *parents;
285                         char *s = xmalloc(41 * num + 1);
286                         v->s = s;
287                         for (i = 0, parents = commit->parents;
288                              parents;
289                              parents = parents->next, i = i + 41) {
290                                 struct commit *parent = parents->item;
291                                 strcpy(s+i, sha1_to_hex(parent->object.sha1));
292                                 if (parents->next)
293                                         s[i+40] = ' ';
294                         }
295                         if (!i)
296                                 *s = '\0';
297                 }
298         }
299 }
300
301 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
302 {
303         const char *eol;
304         while (*buf) {
305                 if (!strncmp(buf, who, wholen) &&
306                     buf[wholen] == ' ')
307                         return buf + wholen + 1;
308                 eol = strchr(buf, '\n');
309                 if (!eol)
310                         return "";
311                 eol++;
312                 if (*eol == '\n')
313                         return ""; /* end of header */
314                 buf = eol;
315         }
316         return "";
317 }
318
319 static const char *copy_line(const char *buf)
320 {
321         const char *eol = strchrnul(buf, '\n');
322         return xmemdupz(buf, eol - buf);
323 }
324
325 static const char *copy_name(const char *buf)
326 {
327         const char *cp;
328         for (cp = buf; *cp && *cp != '\n'; cp++) {
329                 if (!strncmp(cp, " <", 2))
330                         return xmemdupz(buf, cp - buf);
331         }
332         return "";
333 }
334
335 static const char *copy_email(const char *buf)
336 {
337         const char *email = strchr(buf, '<');
338         const char *eoemail;
339         if (!email)
340                 return "";
341         eoemail = strchr(email, '>');
342         if (!eoemail)
343                 return "";
344         return xmemdupz(email, eoemail + 1 - email);
345 }
346
347 static char *copy_subject(const char *buf, unsigned long len)
348 {
349         char *r = xmemdupz(buf, len);
350         int i;
351
352         for (i = 0; i < len; i++)
353                 if (r[i] == '\n')
354                         r[i] = ' ';
355
356         return r;
357 }
358
359 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
360 {
361         const char *eoemail = strstr(buf, "> ");
362         char *zone;
363         unsigned long timestamp;
364         long tz;
365         struct date_mode date_mode = { DATE_NORMAL };
366         const char *formatp;
367
368         /*
369          * We got here because atomname ends in "date" or "date<something>";
370          * it's not possible that <something> is not ":<format>" because
371          * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
372          * ":" means no format is specified, and use the default.
373          */
374         formatp = strchr(atomname, ':');
375         if (formatp != NULL) {
376                 formatp++;
377                 parse_date_format(formatp, &date_mode);
378         }
379
380         if (!eoemail)
381                 goto bad;
382         timestamp = strtoul(eoemail + 2, &zone, 10);
383         if (timestamp == ULONG_MAX)
384                 goto bad;
385         tz = strtol(zone, NULL, 10);
386         if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
387                 goto bad;
388         v->s = xstrdup(show_date(timestamp, tz, &date_mode));
389         v->ul = timestamp;
390         return;
391  bad:
392         v->s = "";
393         v->ul = 0;
394 }
395
396 /* See grab_values */
397 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
398 {
399         int i;
400         int wholen = strlen(who);
401         const char *wholine = NULL;
402
403         for (i = 0; i < used_atom_cnt; i++) {
404                 const char *name = used_atom[i];
405                 struct atom_value *v = &val[i];
406                 if (!!deref != (*name == '*'))
407                         continue;
408                 if (deref)
409                         name++;
410                 if (strncmp(who, name, wholen))
411                         continue;
412                 if (name[wholen] != 0 &&
413                     strcmp(name + wholen, "name") &&
414                     strcmp(name + wholen, "email") &&
415                     !starts_with(name + wholen, "date"))
416                         continue;
417                 if (!wholine)
418                         wholine = find_wholine(who, wholen, buf, sz);
419                 if (!wholine)
420                         return; /* no point looking for it */
421                 if (name[wholen] == 0)
422                         v->s = copy_line(wholine);
423                 else if (!strcmp(name + wholen, "name"))
424                         v->s = copy_name(wholine);
425                 else if (!strcmp(name + wholen, "email"))
426                         v->s = copy_email(wholine);
427                 else if (starts_with(name + wholen, "date"))
428                         grab_date(wholine, v, name);
429         }
430
431         /*
432          * For a tag or a commit object, if "creator" or "creatordate" is
433          * requested, do something special.
434          */
435         if (strcmp(who, "tagger") && strcmp(who, "committer"))
436                 return; /* "author" for commit object is not wanted */
437         if (!wholine)
438                 wholine = find_wholine(who, wholen, buf, sz);
439         if (!wholine)
440                 return;
441         for (i = 0; i < used_atom_cnt; i++) {
442                 const char *name = used_atom[i];
443                 struct atom_value *v = &val[i];
444                 if (!!deref != (*name == '*'))
445                         continue;
446                 if (deref)
447                         name++;
448
449                 if (starts_with(name, "creatordate"))
450                         grab_date(wholine, v, name);
451                 else if (!strcmp(name, "creator"))
452                         v->s = copy_line(wholine);
453         }
454 }
455
456 static void find_subpos(const char *buf, unsigned long sz,
457                         const char **sub, unsigned long *sublen,
458                         const char **body, unsigned long *bodylen,
459                         unsigned long *nonsiglen,
460                         const char **sig, unsigned long *siglen)
461 {
462         const char *eol;
463         /* skip past header until we hit empty line */
464         while (*buf && *buf != '\n') {
465                 eol = strchrnul(buf, '\n');
466                 if (*eol)
467                         eol++;
468                 buf = eol;
469         }
470         /* skip any empty lines */
471         while (*buf == '\n')
472                 buf++;
473
474         /* parse signature first; we might not even have a subject line */
475         *sig = buf + parse_signature(buf, strlen(buf));
476         *siglen = strlen(*sig);
477
478         /* subject is first non-empty line */
479         *sub = buf;
480         /* subject goes to first empty line */
481         while (buf < *sig && *buf && *buf != '\n') {
482                 eol = strchrnul(buf, '\n');
483                 if (*eol)
484                         eol++;
485                 buf = eol;
486         }
487         *sublen = buf - *sub;
488         /* drop trailing newline, if present */
489         if (*sublen && (*sub)[*sublen - 1] == '\n')
490                 *sublen -= 1;
491
492         /* skip any empty lines */
493         while (*buf == '\n')
494                 buf++;
495         *body = buf;
496         *bodylen = strlen(buf);
497         *nonsiglen = *sig - buf;
498 }
499
500 /* See grab_values */
501 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
502 {
503         int i;
504         const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
505         unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
506
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                 if (strcmp(name, "subject") &&
515                     strcmp(name, "body") &&
516                     strcmp(name, "contents") &&
517                     strcmp(name, "contents:subject") &&
518                     strcmp(name, "contents:body") &&
519                     strcmp(name, "contents:signature"))
520                         continue;
521                 if (!subpos)
522                         find_subpos(buf, sz,
523                                     &subpos, &sublen,
524                                     &bodypos, &bodylen, &nonsiglen,
525                                     &sigpos, &siglen);
526
527                 if (!strcmp(name, "subject"))
528                         v->s = copy_subject(subpos, sublen);
529                 else if (!strcmp(name, "contents:subject"))
530                         v->s = copy_subject(subpos, sublen);
531                 else if (!strcmp(name, "body"))
532                         v->s = xmemdupz(bodypos, bodylen);
533                 else if (!strcmp(name, "contents:body"))
534                         v->s = xmemdupz(bodypos, nonsiglen);
535                 else if (!strcmp(name, "contents:signature"))
536                         v->s = xmemdupz(sigpos, siglen);
537                 else if (!strcmp(name, "contents"))
538                         v->s = xstrdup(subpos);
539         }
540 }
541
542 /*
543  * We want to have empty print-string for field requests
544  * that do not apply (e.g. "authordate" for a tag object)
545  */
546 static void fill_missing_values(struct atom_value *val)
547 {
548         int i;
549         for (i = 0; i < used_atom_cnt; i++) {
550                 struct atom_value *v = &val[i];
551                 if (v->s == NULL)
552                         v->s = "";
553         }
554 }
555
556 /*
557  * val is a list of atom_value to hold returned values.  Extract
558  * the values for atoms in used_atom array out of (obj, buf, sz).
559  * when deref is false, (obj, buf, sz) is the object that is
560  * pointed at by the ref itself; otherwise it is the object the
561  * ref (which is a tag) refers to.
562  */
563 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
564 {
565         grab_common_values(val, deref, obj, buf, sz);
566         switch (obj->type) {
567         case OBJ_TAG:
568                 grab_tag_values(val, deref, obj, buf, sz);
569                 grab_sub_body_contents(val, deref, obj, buf, sz);
570                 grab_person("tagger", val, deref, obj, buf, sz);
571                 break;
572         case OBJ_COMMIT:
573                 grab_commit_values(val, deref, obj, buf, sz);
574                 grab_sub_body_contents(val, deref, obj, buf, sz);
575                 grab_person("author", val, deref, obj, buf, sz);
576                 grab_person("committer", val, deref, obj, buf, sz);
577                 break;
578         case OBJ_TREE:
579                 /* grab_tree_values(val, deref, obj, buf, sz); */
580                 break;
581         case OBJ_BLOB:
582                 /* grab_blob_values(val, deref, obj, buf, sz); */
583                 break;
584         default:
585                 die("Eh?  Object of type %d?", obj->type);
586         }
587 }
588
589 static inline char *copy_advance(char *dst, const char *src)
590 {
591         while (*src)
592                 *dst++ = *src++;
593         return dst;
594 }
595
596 /*
597  * Parse the object referred by ref, and grab needed value.
598  */
599 static void populate_value(struct ref_array_item *ref)
600 {
601         void *buf;
602         struct object *obj;
603         int eaten, i;
604         unsigned long size;
605         const unsigned char *tagged;
606
607         ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
608
609         if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
610                 unsigned char unused1[20];
611                 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
612                                              unused1, NULL);
613                 if (!ref->symref)
614                         ref->symref = "";
615         }
616
617         /* Fill in specials first */
618         for (i = 0; i < used_atom_cnt; i++) {
619                 const char *name = used_atom[i];
620                 struct atom_value *v = &ref->value[i];
621                 int deref = 0;
622                 const char *refname;
623                 const char *formatp;
624                 struct branch *branch = NULL;
625
626                 if (*name == '*') {
627                         deref = 1;
628                         name++;
629                 }
630
631                 if (starts_with(name, "refname"))
632                         refname = ref->refname;
633                 else if (starts_with(name, "symref"))
634                         refname = ref->symref ? ref->symref : "";
635                 else if (starts_with(name, "upstream")) {
636                         const char *branch_name;
637                         /* only local branches may have an upstream */
638                         if (!skip_prefix(ref->refname, "refs/heads/",
639                                          &branch_name))
640                                 continue;
641                         branch = branch_get(branch_name);
642
643                         refname = branch_get_upstream(branch, NULL);
644                         if (!refname)
645                                 continue;
646                 } else if (starts_with(name, "push")) {
647                         const char *branch_name;
648                         if (!skip_prefix(ref->refname, "refs/heads/",
649                                          &branch_name))
650                                 continue;
651                         branch = branch_get(branch_name);
652
653                         refname = branch_get_push(branch, NULL);
654                         if (!refname)
655                                 continue;
656                 } else if (starts_with(name, "color:")) {
657                         char color[COLOR_MAXLEN] = "";
658
659                         if (color_parse(name + 6, color) < 0)
660                                 die(_("unable to parse format"));
661                         v->s = xstrdup(color);
662                         continue;
663                 } else if (!strcmp(name, "flag")) {
664                         char buf[256], *cp = buf;
665                         if (ref->flag & REF_ISSYMREF)
666                                 cp = copy_advance(cp, ",symref");
667                         if (ref->flag & REF_ISPACKED)
668                                 cp = copy_advance(cp, ",packed");
669                         if (cp == buf)
670                                 v->s = "";
671                         else {
672                                 *cp = '\0';
673                                 v->s = xstrdup(buf + 1);
674                         }
675                         continue;
676                 } else if (!deref && grab_objectname(name, ref->objectname, v)) {
677                         continue;
678                 } else if (!strcmp(name, "HEAD")) {
679                         const char *head;
680                         unsigned char sha1[20];
681
682                         head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
683                                                   sha1, NULL);
684                         if (!strcmp(ref->refname, head))
685                                 v->s = "*";
686                         else
687                                 v->s = " ";
688                         continue;
689                 } else
690                         continue;
691
692                 formatp = strchr(name, ':');
693                 if (formatp) {
694                         int num_ours, num_theirs;
695
696                         formatp++;
697                         if (!strcmp(formatp, "short"))
698                                 refname = shorten_unambiguous_ref(refname,
699                                                       warn_ambiguous_refs);
700                         else if (!strcmp(formatp, "track") &&
701                                  (starts_with(name, "upstream") ||
702                                   starts_with(name, "push"))) {
703                                 char buf[40];
704
705                                 if (stat_tracking_info(branch, &num_ours,
706                                                        &num_theirs, NULL))
707                                         continue;
708
709                                 if (!num_ours && !num_theirs)
710                                         v->s = "";
711                                 else if (!num_ours) {
712                                         sprintf(buf, "[behind %d]", num_theirs);
713                                         v->s = xstrdup(buf);
714                                 } else if (!num_theirs) {
715                                         sprintf(buf, "[ahead %d]", num_ours);
716                                         v->s = xstrdup(buf);
717                                 } else {
718                                         sprintf(buf, "[ahead %d, behind %d]",
719                                                 num_ours, num_theirs);
720                                         v->s = xstrdup(buf);
721                                 }
722                                 continue;
723                         } else if (!strcmp(formatp, "trackshort") &&
724                                    (starts_with(name, "upstream") ||
725                                     starts_with(name, "push"))) {
726                                 assert(branch);
727
728                                 if (stat_tracking_info(branch, &num_ours,
729                                                         &num_theirs, NULL))
730                                         continue;
731
732                                 if (!num_ours && !num_theirs)
733                                         v->s = "=";
734                                 else if (!num_ours)
735                                         v->s = "<";
736                                 else if (!num_theirs)
737                                         v->s = ">";
738                                 else
739                                         v->s = "<>";
740                                 continue;
741                         } else
742                                 die("unknown %.*s format %s",
743                                     (int)(formatp - name), name, formatp);
744                 }
745
746                 if (!deref)
747                         v->s = refname;
748                 else {
749                         int len = strlen(refname);
750                         char *s = xmalloc(len + 4);
751                         sprintf(s, "%s^{}", refname);
752                         v->s = s;
753                 }
754         }
755
756         for (i = 0; i < used_atom_cnt; i++) {
757                 struct atom_value *v = &ref->value[i];
758                 if (v->s == NULL)
759                         goto need_obj;
760         }
761         return;
762
763  need_obj:
764         buf = get_obj(ref->objectname, &obj, &size, &eaten);
765         if (!buf)
766                 die("missing object %s for %s",
767                     sha1_to_hex(ref->objectname), ref->refname);
768         if (!obj)
769                 die("parse_object_buffer failed on %s for %s",
770                     sha1_to_hex(ref->objectname), ref->refname);
771
772         grab_values(ref->value, 0, obj, buf, size);
773         if (!eaten)
774                 free(buf);
775
776         /*
777          * If there is no atom that wants to know about tagged
778          * object, we are done.
779          */
780         if (!need_tagged || (obj->type != OBJ_TAG))
781                 return;
782
783         /*
784          * If it is a tag object, see if we use a value that derefs
785          * the object, and if we do grab the object it refers to.
786          */
787         tagged = ((struct tag *)obj)->tagged->sha1;
788
789         /*
790          * NEEDSWORK: This derefs tag only once, which
791          * is good to deal with chains of trust, but
792          * is not consistent with what deref_tag() does
793          * which peels the onion to the core.
794          */
795         buf = get_obj(tagged, &obj, &size, &eaten);
796         if (!buf)
797                 die("missing object %s for %s",
798                     sha1_to_hex(tagged), ref->refname);
799         if (!obj)
800                 die("parse_object_buffer failed on %s for %s",
801                     sha1_to_hex(tagged), ref->refname);
802         grab_values(ref->value, 1, obj, buf, size);
803         if (!eaten)
804                 free(buf);
805 }
806
807 /*
808  * Given a ref, return the value for the atom.  This lazily gets value
809  * out of the object by calling populate value.
810  */
811 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
812 {
813         if (!ref->value) {
814                 populate_value(ref);
815                 fill_missing_values(ref->value);
816         }
817         *v = &ref->value[atom];
818 }
819
820 /*
821  * Return 1 if the refname matches one of the patterns, otherwise 0.
822  * A pattern can be path prefix (e.g. a refname "refs/heads/master"
823  * matches a pattern "refs/heads/") or a wildcard (e.g. the same ref
824  * matches "refs/heads/m*",too).
825  */
826 static int match_name_as_path(const char **pattern, const char *refname)
827 {
828         int namelen = strlen(refname);
829         for (; *pattern; pattern++) {
830                 const char *p = *pattern;
831                 int plen = strlen(p);
832
833                 if ((plen <= namelen) &&
834                     !strncmp(refname, p, plen) &&
835                     (refname[plen] == '\0' ||
836                      refname[plen] == '/' ||
837                      p[plen-1] == '/'))
838                         return 1;
839                 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
840                         return 1;
841         }
842         return 0;
843 }
844
845 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
846 static struct ref_array_item *new_ref_array_item(const char *refname,
847                                                  const unsigned char *objectname,
848                                                  int flag)
849 {
850         size_t len = strlen(refname);
851         struct ref_array_item *ref = xcalloc(1, sizeof(struct ref_array_item) + len + 1);
852         memcpy(ref->refname, refname, len);
853         ref->refname[len] = '\0';
854         hashcpy(ref->objectname, objectname);
855         ref->flag = flag;
856
857         return ref;
858 }
859
860 /*
861  * A call-back given to for_each_ref().  Filter refs and keep them for
862  * later object processing.
863  */
864 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
865 {
866         struct ref_filter_cbdata *ref_cbdata = cb_data;
867         struct ref_filter *filter = ref_cbdata->filter;
868         struct ref_array_item *ref;
869
870         if (flag & REF_BAD_NAME) {
871                 warning("ignoring ref with broken name %s", refname);
872                 return 0;
873         }
874
875         if (flag & REF_ISBROKEN) {
876                 warning("ignoring broken ref %s", refname);
877                 return 0;
878         }
879
880         if (*filter->name_patterns && !match_name_as_path(filter->name_patterns, refname))
881                 return 0;
882
883         /*
884          * We do not open the object yet; sort may only need refname
885          * to do its job and the resulting list may yet to be pruned
886          * by maxcount logic.
887          */
888         ref = new_ref_array_item(refname, oid->hash, flag);
889
890         REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
891         ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
892         return 0;
893 }
894
895 /*  Free memory allocated for a ref_array_item */
896 static void free_array_item(struct ref_array_item *item)
897 {
898         free((char *)item->symref);
899         free(item);
900 }
901
902 /* Free all memory allocated for ref_array */
903 void ref_array_clear(struct ref_array *array)
904 {
905         int i;
906
907         for (i = 0; i < array->nr; i++)
908                 free_array_item(array->items[i]);
909         free(array->items);
910         array->items = NULL;
911         array->nr = array->alloc = 0;
912 }
913
914 /*
915  * API for filtering a set of refs. Based on the type of refs the user
916  * has requested, we iterate through those refs and apply filters
917  * as per the given ref_filter structure and finally store the
918  * filtered refs in the ref_array structure.
919  */
920 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
921 {
922         struct ref_filter_cbdata ref_cbdata;
923
924         ref_cbdata.array = array;
925         ref_cbdata.filter = filter;
926
927         if (type & (FILTER_REFS_ALL | FILTER_REFS_INCLUDE_BROKEN))
928                 return for_each_rawref(ref_filter_handler, &ref_cbdata);
929         else if (type & FILTER_REFS_ALL)
930                 return for_each_ref(ref_filter_handler, &ref_cbdata);
931         else
932                 die("filter_refs: invalid type");
933         return 0;
934 }
935
936 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
937 {
938         struct atom_value *va, *vb;
939         int cmp;
940         cmp_type cmp_type = used_atom_type[s->atom];
941
942         get_ref_atom_value(a, s->atom, &va);
943         get_ref_atom_value(b, s->atom, &vb);
944         switch (cmp_type) {
945         case FIELD_STR:
946                 cmp = strcmp(va->s, vb->s);
947                 break;
948         default:
949                 if (va->ul < vb->ul)
950                         cmp = -1;
951                 else if (va->ul == vb->ul)
952                         cmp = 0;
953                 else
954                         cmp = 1;
955                 break;
956         }
957         return (s->reverse) ? -cmp : cmp;
958 }
959
960 static struct ref_sorting *ref_sorting;
961 static int compare_refs(const void *a_, const void *b_)
962 {
963         struct ref_array_item *a = *((struct ref_array_item **)a_);
964         struct ref_array_item *b = *((struct ref_array_item **)b_);
965         struct ref_sorting *s;
966
967         for (s = ref_sorting; s; s = s->next) {
968                 int cmp = cmp_ref_sorting(s, a, b);
969                 if (cmp)
970                         return cmp;
971         }
972         return 0;
973 }
974
975 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
976 {
977         ref_sorting = sorting;
978         qsort(array->items, array->nr, sizeof(struct ref_array_item *), compare_refs);
979 }
980
981 static void print_value(struct atom_value *v, int quote_style)
982 {
983         struct strbuf sb = STRBUF_INIT;
984         switch (quote_style) {
985         case QUOTE_NONE:
986                 fputs(v->s, stdout);
987                 break;
988         case QUOTE_SHELL:
989                 sq_quote_buf(&sb, v->s);
990                 break;
991         case QUOTE_PERL:
992                 perl_quote_buf(&sb, v->s);
993                 break;
994         case QUOTE_PYTHON:
995                 python_quote_buf(&sb, v->s);
996                 break;
997         case QUOTE_TCL:
998                 tcl_quote_buf(&sb, v->s);
999                 break;
1000         }
1001         if (quote_style != QUOTE_NONE) {
1002                 fputs(sb.buf, stdout);
1003                 strbuf_release(&sb);
1004         }
1005 }
1006
1007 static int hex1(char ch)
1008 {
1009         if ('0' <= ch && ch <= '9')
1010                 return ch - '0';
1011         else if ('a' <= ch && ch <= 'f')
1012                 return ch - 'a' + 10;
1013         else if ('A' <= ch && ch <= 'F')
1014                 return ch - 'A' + 10;
1015         return -1;
1016 }
1017 static int hex2(const char *cp)
1018 {
1019         if (cp[0] && cp[1])
1020                 return (hex1(cp[0]) << 4) | hex1(cp[1]);
1021         else
1022                 return -1;
1023 }
1024
1025 static void emit(const char *cp, const char *ep)
1026 {
1027         while (*cp && (!ep || cp < ep)) {
1028                 if (*cp == '%') {
1029                         if (cp[1] == '%')
1030                                 cp++;
1031                         else {
1032                                 int ch = hex2(cp + 1);
1033                                 if (0 <= ch) {
1034                                         putchar(ch);
1035                                         cp += 3;
1036                                         continue;
1037                                 }
1038                         }
1039                 }
1040                 putchar(*cp);
1041                 cp++;
1042         }
1043 }
1044
1045 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
1046 {
1047         const char *cp, *sp, *ep;
1048
1049         for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1050                 struct atom_value *atomv;
1051
1052                 ep = strchr(sp, ')');
1053                 if (cp < sp)
1054                         emit(cp, sp);
1055                 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1056                 print_value(atomv, quote_style);
1057         }
1058         if (*cp) {
1059                 sp = cp + strlen(cp);
1060                 emit(cp, sp);
1061         }
1062         if (need_color_reset_at_eol) {
1063                 struct atom_value resetv;
1064                 char color[COLOR_MAXLEN] = "";
1065
1066                 if (color_parse("reset", color) < 0)
1067                         die("BUG: couldn't parse 'reset' as a color");
1068                 resetv.s = color;
1069                 print_value(&resetv, quote_style);
1070         }
1071         putchar('\n');
1072 }
1073
1074 /*  If no sorting option is given, use refname to sort as default */
1075 struct ref_sorting *ref_default_sorting(void)
1076 {
1077         static const char cstr_name[] = "refname";
1078
1079         struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
1080
1081         sorting->next = NULL;
1082         sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
1083         return sorting;
1084 }
1085
1086 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
1087 {
1088         struct ref_sorting **sorting_tail = opt->value;
1089         struct ref_sorting *s;
1090         int len;
1091
1092         if (!arg) /* should --no-sort void the list ? */
1093                 return -1;
1094
1095         s = xcalloc(1, sizeof(*s));
1096         s->next = *sorting_tail;
1097         *sorting_tail = s;
1098
1099         if (*arg == '-') {
1100                 s->reverse = 1;
1101                 arg++;
1102         }
1103         len = strlen(arg);
1104         s->atom = parse_ref_filter_atom(arg, arg+len);
1105         return 0;
1106 }