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