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