Merge branch 'ld/git-p4-shelve-update-fix'
[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 "object-store.h"
7 #include "repository.h"
8 #include "commit.h"
9 #include "remote.h"
10 #include "color.h"
11 #include "tag.h"
12 #include "quote.h"
13 #include "ref-filter.h"
14 #include "revision.h"
15 #include "utf8.h"
16 #include "git-compat-util.h"
17 #include "version.h"
18 #include "trailer.h"
19 #include "wt-status.h"
20 #include "commit-slab.h"
21 #include "commit-graph.h"
22 #include "commit-reach.h"
23
24 static struct ref_msg {
25         const char *gone;
26         const char *ahead;
27         const char *behind;
28         const char *ahead_behind;
29 } msgs = {
30          /* Untranslated plumbing messages: */
31         "gone",
32         "ahead %d",
33         "behind %d",
34         "ahead %d, behind %d"
35 };
36
37 void setup_ref_filter_porcelain_msg(void)
38 {
39         msgs.gone = _("gone");
40         msgs.ahead = _("ahead %d");
41         msgs.behind = _("behind %d");
42         msgs.ahead_behind = _("ahead %d, behind %d");
43 }
44
45 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
46 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
47 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
48
49 struct align {
50         align_type position;
51         unsigned int width;
52 };
53
54 struct if_then_else {
55         cmp_status cmp_status;
56         const char *str;
57         unsigned int then_atom_seen : 1,
58                 else_atom_seen : 1,
59                 condition_satisfied : 1;
60 };
61
62 struct refname_atom {
63         enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
64         int lstrip, rstrip;
65 };
66
67 static struct expand_data {
68         struct object_id oid;
69         enum object_type type;
70         unsigned long size;
71         off_t disk_size;
72         struct object_id delta_base_oid;
73         void *content;
74
75         struct object_info info;
76 } oi, oi_deref;
77
78 /*
79  * An atom is a valid field atom listed below, possibly prefixed with
80  * a "*" to denote deref_tag().
81  *
82  * We parse given format string and sort specifiers, and make a list
83  * of properties that we need to extract out of objects.  ref_array_item
84  * structure will hold an array of values extracted that can be
85  * indexed with the "atom number", which is an index into this
86  * array.
87  */
88 static struct used_atom {
89         const char *name;
90         cmp_type type;
91         info_source source;
92         union {
93                 char color[COLOR_MAXLEN];
94                 struct align align;
95                 struct {
96                         enum {
97                                 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
98                         } option;
99                         struct refname_atom refname;
100                         unsigned int nobracket : 1, push : 1, push_remote : 1;
101                 } remote_ref;
102                 struct {
103                         enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
104                         struct process_trailer_options trailer_opts;
105                         unsigned int nlines;
106                 } contents;
107                 struct {
108                         cmp_status cmp_status;
109                         const char *str;
110                 } if_then_else;
111                 struct {
112                         enum { O_FULL, O_LENGTH, O_SHORT } option;
113                         unsigned int length;
114                 } objectname;
115                 struct refname_atom refname;
116                 char *head;
117         } u;
118 } *used_atom;
119 static int used_atom_cnt, need_tagged, need_symref;
120
121 /*
122  * Expand string, append it to strbuf *sb, then return error code ret.
123  * Allow to save few lines of code.
124  */
125 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
126 {
127         va_list ap;
128         va_start(ap, fmt);
129         strbuf_vaddf(sb, fmt, ap);
130         va_end(ap);
131         return ret;
132 }
133
134 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
135                              const char *color_value, struct strbuf *err)
136 {
137         if (!color_value)
138                 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
139         if (color_parse(color_value, atom->u.color) < 0)
140                 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
141                                        color_value);
142         /*
143          * We check this after we've parsed the color, which lets us complain
144          * about syntactically bogus color names even if they won't be used.
145          */
146         if (!want_color(format->use_color))
147                 color_parse("", atom->u.color);
148         return 0;
149 }
150
151 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
152                                          const char *name, struct strbuf *err)
153 {
154         if (!arg)
155                 atom->option = R_NORMAL;
156         else if (!strcmp(arg, "short"))
157                 atom->option = R_SHORT;
158         else if (skip_prefix(arg, "lstrip=", &arg) ||
159                  skip_prefix(arg, "strip=", &arg)) {
160                 atom->option = R_LSTRIP;
161                 if (strtol_i(arg, 10, &atom->lstrip))
162                         return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
163         } else if (skip_prefix(arg, "rstrip=", &arg)) {
164                 atom->option = R_RSTRIP;
165                 if (strtol_i(arg, 10, &atom->rstrip))
166                         return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
167         } else
168                 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
169         return 0;
170 }
171
172 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
173                                   const char *arg, struct strbuf *err)
174 {
175         struct string_list params = STRING_LIST_INIT_DUP;
176         int i;
177
178         if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
179                 atom->u.remote_ref.push = 1;
180
181         if (!arg) {
182                 atom->u.remote_ref.option = RR_REF;
183                 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
184                                                     arg, atom->name, err);
185         }
186
187         atom->u.remote_ref.nobracket = 0;
188         string_list_split(&params, arg, ',', -1);
189
190         for (i = 0; i < params.nr; i++) {
191                 const char *s = params.items[i].string;
192
193                 if (!strcmp(s, "track"))
194                         atom->u.remote_ref.option = RR_TRACK;
195                 else if (!strcmp(s, "trackshort"))
196                         atom->u.remote_ref.option = RR_TRACKSHORT;
197                 else if (!strcmp(s, "nobracket"))
198                         atom->u.remote_ref.nobracket = 1;
199                 else if (!strcmp(s, "remotename")) {
200                         atom->u.remote_ref.option = RR_REMOTE_NAME;
201                         atom->u.remote_ref.push_remote = 1;
202                 } else if (!strcmp(s, "remoteref")) {
203                         atom->u.remote_ref.option = RR_REMOTE_REF;
204                         atom->u.remote_ref.push_remote = 1;
205                 } else {
206                         atom->u.remote_ref.option = RR_REF;
207                         if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
208                                                          arg, atom->name, err)) {
209                                 string_list_clear(&params, 0);
210                                 return -1;
211                         }
212                 }
213         }
214
215         string_list_clear(&params, 0);
216         return 0;
217 }
218
219 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
220                                   const char *arg, struct strbuf *err)
221 {
222         if (arg)
223                 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
224         if (*atom->name == '*')
225                 oi_deref.info.typep = &oi_deref.type;
226         else
227                 oi.info.typep = &oi.type;
228         return 0;
229 }
230
231 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
232                                   const char *arg, struct strbuf *err)
233 {
234         if (!arg) {
235                 if (*atom->name == '*')
236                         oi_deref.info.sizep = &oi_deref.size;
237                 else
238                         oi.info.sizep = &oi.size;
239         } else if (!strcmp(arg, "disk")) {
240                 if (*atom->name == '*')
241                         oi_deref.info.disk_sizep = &oi_deref.disk_size;
242                 else
243                         oi.info.disk_sizep = &oi.disk_size;
244         } else
245                 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
246         return 0;
247 }
248
249 static int deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom,
250                                  const char *arg, struct strbuf *err)
251 {
252         if (arg)
253                 return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
254         if (*atom->name == '*')
255                 oi_deref.info.delta_base_sha1 = oi_deref.delta_base_oid.hash;
256         else
257                 oi.info.delta_base_sha1 = oi.delta_base_oid.hash;
258         return 0;
259 }
260
261 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
262                             const char *arg, struct strbuf *err)
263 {
264         if (arg)
265                 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
266         atom->u.contents.option = C_BODY_DEP;
267         return 0;
268 }
269
270 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
271                                const char *arg, struct strbuf *err)
272 {
273         if (arg)
274                 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
275         atom->u.contents.option = C_SUB;
276         return 0;
277 }
278
279 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
280                                 const char *arg, struct strbuf *err)
281 {
282         struct string_list params = STRING_LIST_INIT_DUP;
283         int i;
284
285         atom->u.contents.trailer_opts.no_divider = 1;
286
287         if (arg) {
288                 string_list_split(&params, arg, ',', -1);
289                 for (i = 0; i < params.nr; i++) {
290                         const char *s = params.items[i].string;
291                         if (!strcmp(s, "unfold"))
292                                 atom->u.contents.trailer_opts.unfold = 1;
293                         else if (!strcmp(s, "only"))
294                                 atom->u.contents.trailer_opts.only_trailers = 1;
295                         else {
296                                 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
297                                 string_list_clear(&params, 0);
298                                 return -1;
299                         }
300                 }
301         }
302         atom->u.contents.option = C_TRAILERS;
303         string_list_clear(&params, 0);
304         return 0;
305 }
306
307 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
308                                 const char *arg, struct strbuf *err)
309 {
310         if (!arg)
311                 atom->u.contents.option = C_BARE;
312         else if (!strcmp(arg, "body"))
313                 atom->u.contents.option = C_BODY;
314         else if (!strcmp(arg, "signature"))
315                 atom->u.contents.option = C_SIG;
316         else if (!strcmp(arg, "subject"))
317                 atom->u.contents.option = C_SUB;
318         else if (skip_prefix(arg, "trailers", &arg)) {
319                 skip_prefix(arg, ":", &arg);
320                 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
321                         return -1;
322         } else if (skip_prefix(arg, "lines=", &arg)) {
323                 atom->u.contents.option = C_LINES;
324                 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
325                         return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
326         } else
327                 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
328         return 0;
329 }
330
331 static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
332                                   const char *arg, struct strbuf *err)
333 {
334         if (!arg)
335                 atom->u.objectname.option = O_FULL;
336         else if (!strcmp(arg, "short"))
337                 atom->u.objectname.option = O_SHORT;
338         else if (skip_prefix(arg, "short=", &arg)) {
339                 atom->u.objectname.option = O_LENGTH;
340                 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
341                     atom->u.objectname.length == 0)
342                         return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
343                 if (atom->u.objectname.length < MINIMUM_ABBREV)
344                         atom->u.objectname.length = MINIMUM_ABBREV;
345         } else
346                 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
347         return 0;
348 }
349
350 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
351                                const char *arg, struct strbuf *err)
352 {
353         return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
354 }
355
356 static align_type parse_align_position(const char *s)
357 {
358         if (!strcmp(s, "right"))
359                 return ALIGN_RIGHT;
360         else if (!strcmp(s, "middle"))
361                 return ALIGN_MIDDLE;
362         else if (!strcmp(s, "left"))
363                 return ALIGN_LEFT;
364         return -1;
365 }
366
367 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
368                              const char *arg, struct strbuf *err)
369 {
370         struct align *align = &atom->u.align;
371         struct string_list params = STRING_LIST_INIT_DUP;
372         int i;
373         unsigned int width = ~0U;
374
375         if (!arg)
376                 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
377
378         align->position = ALIGN_LEFT;
379
380         string_list_split(&params, arg, ',', -1);
381         for (i = 0; i < params.nr; i++) {
382                 const char *s = params.items[i].string;
383                 int position;
384
385                 if (skip_prefix(s, "position=", &s)) {
386                         position = parse_align_position(s);
387                         if (position < 0) {
388                                 strbuf_addf(err, _("unrecognized position:%s"), s);
389                                 string_list_clear(&params, 0);
390                                 return -1;
391                         }
392                         align->position = position;
393                 } else if (skip_prefix(s, "width=", &s)) {
394                         if (strtoul_ui(s, 10, &width)) {
395                                 strbuf_addf(err, _("unrecognized width:%s"), s);
396                                 string_list_clear(&params, 0);
397                                 return -1;
398                         }
399                 } else if (!strtoul_ui(s, 10, &width))
400                         ;
401                 else if ((position = parse_align_position(s)) >= 0)
402                         align->position = position;
403                 else {
404                         strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
405                         string_list_clear(&params, 0);
406                         return -1;
407                 }
408         }
409
410         if (width == ~0U) {
411                 string_list_clear(&params, 0);
412                 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
413         }
414         align->width = width;
415         string_list_clear(&params, 0);
416         return 0;
417 }
418
419 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
420                           const char *arg, struct strbuf *err)
421 {
422         if (!arg) {
423                 atom->u.if_then_else.cmp_status = COMPARE_NONE;
424                 return 0;
425         } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
426                 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
427         } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
428                 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
429         } else
430                 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
431         return 0;
432 }
433
434 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
435                             const char *arg, struct strbuf *unused_err)
436 {
437         atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
438         return 0;
439 }
440
441 static struct {
442         const char *name;
443         info_source source;
444         cmp_type cmp_type;
445         int (*parser)(const struct ref_format *format, struct used_atom *atom,
446                       const char *arg, struct strbuf *err);
447 } valid_atom[] = {
448         { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
449         { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
450         { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
451         { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
452         { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
453         { "tree", SOURCE_OBJ },
454         { "parent", SOURCE_OBJ },
455         { "numparent", SOURCE_OBJ, FIELD_ULONG },
456         { "object", SOURCE_OBJ },
457         { "type", SOURCE_OBJ },
458         { "tag", SOURCE_OBJ },
459         { "author", SOURCE_OBJ },
460         { "authorname", SOURCE_OBJ },
461         { "authoremail", SOURCE_OBJ },
462         { "authordate", SOURCE_OBJ, FIELD_TIME },
463         { "committer", SOURCE_OBJ },
464         { "committername", SOURCE_OBJ },
465         { "committeremail", SOURCE_OBJ },
466         { "committerdate", SOURCE_OBJ, FIELD_TIME },
467         { "tagger", SOURCE_OBJ },
468         { "taggername", SOURCE_OBJ },
469         { "taggeremail", SOURCE_OBJ },
470         { "taggerdate", SOURCE_OBJ, FIELD_TIME },
471         { "creator", SOURCE_OBJ },
472         { "creatordate", SOURCE_OBJ, FIELD_TIME },
473         { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
474         { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
475         { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
476         { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
477         { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
478         { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
479         { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
480         { "flag", SOURCE_NONE },
481         { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
482         { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
483         { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
484         { "end", SOURCE_NONE },
485         { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
486         { "then", SOURCE_NONE },
487         { "else", SOURCE_NONE },
488 };
489
490 #define REF_FORMATTING_STATE_INIT  { 0, NULL }
491
492 struct ref_formatting_stack {
493         struct ref_formatting_stack *prev;
494         struct strbuf output;
495         void (*at_end)(struct ref_formatting_stack **stack);
496         void *at_end_data;
497 };
498
499 struct ref_formatting_state {
500         int quote_style;
501         struct ref_formatting_stack *stack;
502 };
503
504 struct atom_value {
505         const char *s;
506         int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
507                        struct strbuf *err);
508         uintmax_t value; /* used for sorting when not FIELD_STR */
509         struct used_atom *atom;
510 };
511
512 /*
513  * Used to parse format string and sort specifiers
514  */
515 static int parse_ref_filter_atom(const struct ref_format *format,
516                                  const char *atom, const char *ep,
517                                  struct strbuf *err)
518 {
519         const char *sp;
520         const char *arg;
521         int i, at, atom_len;
522
523         sp = atom;
524         if (*sp == '*' && sp < ep)
525                 sp++; /* deref */
526         if (ep <= sp)
527                 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
528                                        (int)(ep-atom), atom);
529
530         /* Do we have the atom already used elsewhere? */
531         for (i = 0; i < used_atom_cnt; i++) {
532                 int len = strlen(used_atom[i].name);
533                 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
534                         return i;
535         }
536
537         /*
538          * If the atom name has a colon, strip it and everything after
539          * it off - it specifies the format for this entry, and
540          * shouldn't be used for checking against the valid_atom
541          * table.
542          */
543         arg = memchr(sp, ':', ep - sp);
544         atom_len = (arg ? arg : ep) - sp;
545
546         /* Is the atom a valid one? */
547         for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
548                 int len = strlen(valid_atom[i].name);
549                 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
550                         break;
551         }
552
553         if (ARRAY_SIZE(valid_atom) <= i)
554                 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
555                                        (int)(ep-atom), atom);
556         if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
557                 return strbuf_addf_ret(err, -1,
558                                        _("not a git repository, but the field '%.*s' requires access to object data"),
559                                        (int)(ep-atom), atom);
560
561         /* Add it in, including the deref prefix */
562         at = used_atom_cnt;
563         used_atom_cnt++;
564         REALLOC_ARRAY(used_atom, used_atom_cnt);
565         used_atom[at].name = xmemdupz(atom, ep - atom);
566         used_atom[at].type = valid_atom[i].cmp_type;
567         used_atom[at].source = valid_atom[i].source;
568         if (used_atom[at].source == SOURCE_OBJ) {
569                 if (*atom == '*')
570                         oi_deref.info.contentp = &oi_deref.content;
571                 else
572                         oi.info.contentp = &oi.content;
573         }
574         if (arg) {
575                 arg = used_atom[at].name + (arg - atom) + 1;
576                 if (!*arg) {
577                         /*
578                          * Treat empty sub-arguments list as NULL (i.e.,
579                          * "%(atom:)" is equivalent to "%(atom)").
580                          */
581                         arg = NULL;
582                 }
583         }
584         memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
585         if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
586                 return -1;
587         if (*atom == '*')
588                 need_tagged = 1;
589         if (!strcmp(valid_atom[i].name, "symref"))
590                 need_symref = 1;
591         return at;
592 }
593
594 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
595 {
596         switch (quote_style) {
597         case QUOTE_NONE:
598                 strbuf_addstr(s, str);
599                 break;
600         case QUOTE_SHELL:
601                 sq_quote_buf(s, str);
602                 break;
603         case QUOTE_PERL:
604                 perl_quote_buf(s, str);
605                 break;
606         case QUOTE_PYTHON:
607                 python_quote_buf(s, str);
608                 break;
609         case QUOTE_TCL:
610                 tcl_quote_buf(s, str);
611                 break;
612         }
613 }
614
615 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
616                        struct strbuf *unused_err)
617 {
618         /*
619          * Quote formatting is only done when the stack has a single
620          * element. Otherwise quote formatting is done on the
621          * element's entire output strbuf when the %(end) atom is
622          * encountered.
623          */
624         if (!state->stack->prev)
625                 quote_formatting(&state->stack->output, v->s, state->quote_style);
626         else
627                 strbuf_addstr(&state->stack->output, v->s);
628         return 0;
629 }
630
631 static void push_stack_element(struct ref_formatting_stack **stack)
632 {
633         struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
634
635         strbuf_init(&s->output, 0);
636         s->prev = *stack;
637         *stack = s;
638 }
639
640 static void pop_stack_element(struct ref_formatting_stack **stack)
641 {
642         struct ref_formatting_stack *current = *stack;
643         struct ref_formatting_stack *prev = current->prev;
644
645         if (prev)
646                 strbuf_addbuf(&prev->output, &current->output);
647         strbuf_release(&current->output);
648         free(current);
649         *stack = prev;
650 }
651
652 static void end_align_handler(struct ref_formatting_stack **stack)
653 {
654         struct ref_formatting_stack *cur = *stack;
655         struct align *align = (struct align *)cur->at_end_data;
656         struct strbuf s = STRBUF_INIT;
657
658         strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
659         strbuf_swap(&cur->output, &s);
660         strbuf_release(&s);
661 }
662
663 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
664                               struct strbuf *unused_err)
665 {
666         struct ref_formatting_stack *new_stack;
667
668         push_stack_element(&state->stack);
669         new_stack = state->stack;
670         new_stack->at_end = end_align_handler;
671         new_stack->at_end_data = &atomv->atom->u.align;
672         return 0;
673 }
674
675 static void if_then_else_handler(struct ref_formatting_stack **stack)
676 {
677         struct ref_formatting_stack *cur = *stack;
678         struct ref_formatting_stack *prev = cur->prev;
679         struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
680
681         if (!if_then_else->then_atom_seen)
682                 die(_("format: %%(if) atom used without a %%(then) atom"));
683
684         if (if_then_else->else_atom_seen) {
685                 /*
686                  * There is an %(else) atom: we need to drop one state from the
687                  * stack, either the %(else) branch if the condition is satisfied, or
688                  * the %(then) branch if it isn't.
689                  */
690                 if (if_then_else->condition_satisfied) {
691                         strbuf_reset(&cur->output);
692                         pop_stack_element(&cur);
693                 } else {
694                         strbuf_swap(&cur->output, &prev->output);
695                         strbuf_reset(&cur->output);
696                         pop_stack_element(&cur);
697                 }
698         } else if (!if_then_else->condition_satisfied) {
699                 /*
700                  * No %(else) atom: just drop the %(then) branch if the
701                  * condition is not satisfied.
702                  */
703                 strbuf_reset(&cur->output);
704         }
705
706         *stack = cur;
707         free(if_then_else);
708 }
709
710 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
711                            struct strbuf *unused_err)
712 {
713         struct ref_formatting_stack *new_stack;
714         struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
715
716         if_then_else->str = atomv->atom->u.if_then_else.str;
717         if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
718
719         push_stack_element(&state->stack);
720         new_stack = state->stack;
721         new_stack->at_end = if_then_else_handler;
722         new_stack->at_end_data = if_then_else;
723         return 0;
724 }
725
726 static int is_empty(const char *s)
727 {
728         while (*s != '\0') {
729                 if (!isspace(*s))
730                         return 0;
731                 s++;
732         }
733         return 1;
734 }
735
736 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
737                              struct strbuf *err)
738 {
739         struct ref_formatting_stack *cur = state->stack;
740         struct if_then_else *if_then_else = NULL;
741
742         if (cur->at_end == if_then_else_handler)
743                 if_then_else = (struct if_then_else *)cur->at_end_data;
744         if (!if_then_else)
745                 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
746         if (if_then_else->then_atom_seen)
747                 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
748         if (if_then_else->else_atom_seen)
749                 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
750         if_then_else->then_atom_seen = 1;
751         /*
752          * If the 'equals' or 'notequals' attribute is used then
753          * perform the required comparison. If not, only non-empty
754          * strings satisfy the 'if' condition.
755          */
756         if (if_then_else->cmp_status == COMPARE_EQUAL) {
757                 if (!strcmp(if_then_else->str, cur->output.buf))
758                         if_then_else->condition_satisfied = 1;
759         } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
760                 if (strcmp(if_then_else->str, cur->output.buf))
761                         if_then_else->condition_satisfied = 1;
762         } else if (cur->output.len && !is_empty(cur->output.buf))
763                 if_then_else->condition_satisfied = 1;
764         strbuf_reset(&cur->output);
765         return 0;
766 }
767
768 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
769                              struct strbuf *err)
770 {
771         struct ref_formatting_stack *prev = state->stack;
772         struct if_then_else *if_then_else = NULL;
773
774         if (prev->at_end == if_then_else_handler)
775                 if_then_else = (struct if_then_else *)prev->at_end_data;
776         if (!if_then_else)
777                 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
778         if (!if_then_else->then_atom_seen)
779                 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
780         if (if_then_else->else_atom_seen)
781                 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
782         if_then_else->else_atom_seen = 1;
783         push_stack_element(&state->stack);
784         state->stack->at_end_data = prev->at_end_data;
785         state->stack->at_end = prev->at_end;
786         return 0;
787 }
788
789 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
790                             struct strbuf *err)
791 {
792         struct ref_formatting_stack *current = state->stack;
793         struct strbuf s = STRBUF_INIT;
794
795         if (!current->at_end)
796                 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
797         current->at_end(&state->stack);
798
799         /*  Stack may have been popped within at_end(), hence reset the current pointer */
800         current = state->stack;
801
802         /*
803          * Perform quote formatting when the stack element is that of
804          * a supporting atom. If nested then perform quote formatting
805          * only on the topmost supporting atom.
806          */
807         if (!current->prev->prev) {
808                 quote_formatting(&s, current->output.buf, state->quote_style);
809                 strbuf_swap(&current->output, &s);
810         }
811         strbuf_release(&s);
812         pop_stack_element(&state->stack);
813         return 0;
814 }
815
816 /*
817  * In a format string, find the next occurrence of %(atom).
818  */
819 static const char *find_next(const char *cp)
820 {
821         while (*cp) {
822                 if (*cp == '%') {
823                         /*
824                          * %( is the start of an atom;
825                          * %% is a quoted per-cent.
826                          */
827                         if (cp[1] == '(')
828                                 return cp;
829                         else if (cp[1] == '%')
830                                 cp++; /* skip over two % */
831                         /* otherwise this is a singleton, literal % */
832                 }
833                 cp++;
834         }
835         return NULL;
836 }
837
838 /*
839  * Make sure the format string is well formed, and parse out
840  * the used atoms.
841  */
842 int verify_ref_format(struct ref_format *format)
843 {
844         const char *cp, *sp;
845
846         format->need_color_reset_at_eol = 0;
847         for (cp = format->format; *cp && (sp = find_next(cp)); ) {
848                 struct strbuf err = STRBUF_INIT;
849                 const char *color, *ep = strchr(sp, ')');
850                 int at;
851
852                 if (!ep)
853                         return error(_("malformed format string %s"), sp);
854                 /* sp points at "%(" and ep points at the closing ")" */
855                 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
856                 if (at < 0)
857                         die("%s", err.buf);
858                 cp = ep + 1;
859
860                 if (skip_prefix(used_atom[at].name, "color:", &color))
861                         format->need_color_reset_at_eol = !!strcmp(color, "reset");
862                 strbuf_release(&err);
863         }
864         if (format->need_color_reset_at_eol && !want_color(format->use_color))
865                 format->need_color_reset_at_eol = 0;
866         return 0;
867 }
868
869 static int grab_objectname(const char *name, const struct object_id *oid,
870                            struct atom_value *v, struct used_atom *atom)
871 {
872         if (starts_with(name, "objectname")) {
873                 if (atom->u.objectname.option == O_SHORT) {
874                         v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
875                         return 1;
876                 } else if (atom->u.objectname.option == O_FULL) {
877                         v->s = xstrdup(oid_to_hex(oid));
878                         return 1;
879                 } else if (atom->u.objectname.option == O_LENGTH) {
880                         v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
881                         return 1;
882                 } else
883                         BUG("unknown %%(objectname) option");
884         }
885         return 0;
886 }
887
888 /* See grab_values */
889 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
890 {
891         int i;
892
893         for (i = 0; i < used_atom_cnt; i++) {
894                 const char *name = used_atom[i].name;
895                 struct atom_value *v = &val[i];
896                 if (!!deref != (*name == '*'))
897                         continue;
898                 if (deref)
899                         name++;
900                 if (!strcmp(name, "objecttype"))
901                         v->s = xstrdup(type_name(oi->type));
902                 else if (!strcmp(name, "objectsize:disk")) {
903                         v->value = oi->disk_size;
904                         v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
905                 } else if (!strcmp(name, "objectsize")) {
906                         v->value = oi->size;
907                         v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
908                 } else if (!strcmp(name, "deltabase"))
909                         v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
910                 else if (deref)
911                         grab_objectname(name, &oi->oid, v, &used_atom[i]);
912         }
913 }
914
915 /* See grab_values */
916 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
917 {
918         int i;
919         struct tag *tag = (struct tag *) obj;
920
921         for (i = 0; i < used_atom_cnt; i++) {
922                 const char *name = used_atom[i].name;
923                 struct atom_value *v = &val[i];
924                 if (!!deref != (*name == '*'))
925                         continue;
926                 if (deref)
927                         name++;
928                 if (!strcmp(name, "tag"))
929                         v->s = xstrdup(tag->tag);
930                 else if (!strcmp(name, "type") && tag->tagged)
931                         v->s = xstrdup(type_name(tag->tagged->type));
932                 else if (!strcmp(name, "object") && tag->tagged)
933                         v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
934         }
935 }
936
937 /* See grab_values */
938 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
939 {
940         int i;
941         struct commit *commit = (struct commit *) obj;
942
943         for (i = 0; i < used_atom_cnt; i++) {
944                 const char *name = used_atom[i].name;
945                 struct atom_value *v = &val[i];
946                 if (!!deref != (*name == '*'))
947                         continue;
948                 if (deref)
949                         name++;
950                 if (!strcmp(name, "tree")) {
951                         v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
952                 }
953                 else if (!strcmp(name, "numparent")) {
954                         v->value = commit_list_count(commit->parents);
955                         v->s = xstrfmt("%lu", (unsigned long)v->value);
956                 }
957                 else if (!strcmp(name, "parent")) {
958                         struct commit_list *parents;
959                         struct strbuf s = STRBUF_INIT;
960                         for (parents = commit->parents; parents; parents = parents->next) {
961                                 struct commit *parent = parents->item;
962                                 if (parents != commit->parents)
963                                         strbuf_addch(&s, ' ');
964                                 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
965                         }
966                         v->s = strbuf_detach(&s, NULL);
967                 }
968         }
969 }
970
971 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
972 {
973         const char *eol;
974         while (*buf) {
975                 if (!strncmp(buf, who, wholen) &&
976                     buf[wholen] == ' ')
977                         return buf + wholen + 1;
978                 eol = strchr(buf, '\n');
979                 if (!eol)
980                         return "";
981                 eol++;
982                 if (*eol == '\n')
983                         return ""; /* end of header */
984                 buf = eol;
985         }
986         return "";
987 }
988
989 static const char *copy_line(const char *buf)
990 {
991         const char *eol = strchrnul(buf, '\n');
992         return xmemdupz(buf, eol - buf);
993 }
994
995 static const char *copy_name(const char *buf)
996 {
997         const char *cp;
998         for (cp = buf; *cp && *cp != '\n'; cp++) {
999                 if (!strncmp(cp, " <", 2))
1000                         return xmemdupz(buf, cp - buf);
1001         }
1002         return "";
1003 }
1004
1005 static const char *copy_email(const char *buf)
1006 {
1007         const char *email = strchr(buf, '<');
1008         const char *eoemail;
1009         if (!email)
1010                 return "";
1011         eoemail = strchr(email, '>');
1012         if (!eoemail)
1013                 return "";
1014         return xmemdupz(email, eoemail + 1 - email);
1015 }
1016
1017 static char *copy_subject(const char *buf, unsigned long len)
1018 {
1019         char *r = xmemdupz(buf, len);
1020         int i;
1021
1022         for (i = 0; i < len; i++)
1023                 if (r[i] == '\n')
1024                         r[i] = ' ';
1025
1026         return r;
1027 }
1028
1029 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1030 {
1031         const char *eoemail = strstr(buf, "> ");
1032         char *zone;
1033         timestamp_t timestamp;
1034         long tz;
1035         struct date_mode date_mode = { DATE_NORMAL };
1036         const char *formatp;
1037
1038         /*
1039          * We got here because atomname ends in "date" or "date<something>";
1040          * it's not possible that <something> is not ":<format>" because
1041          * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1042          * ":" means no format is specified, and use the default.
1043          */
1044         formatp = strchr(atomname, ':');
1045         if (formatp != NULL) {
1046                 formatp++;
1047                 parse_date_format(formatp, &date_mode);
1048         }
1049
1050         if (!eoemail)
1051                 goto bad;
1052         timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1053         if (timestamp == TIME_MAX)
1054                 goto bad;
1055         tz = strtol(zone, NULL, 10);
1056         if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1057                 goto bad;
1058         v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1059         v->value = timestamp;
1060         return;
1061  bad:
1062         v->s = xstrdup("");
1063         v->value = 0;
1064 }
1065
1066 /* See grab_values */
1067 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1068 {
1069         int i;
1070         int wholen = strlen(who);
1071         const char *wholine = NULL;
1072
1073         for (i = 0; i < used_atom_cnt; i++) {
1074                 const char *name = used_atom[i].name;
1075                 struct atom_value *v = &val[i];
1076                 if (!!deref != (*name == '*'))
1077                         continue;
1078                 if (deref)
1079                         name++;
1080                 if (strncmp(who, name, wholen))
1081                         continue;
1082                 if (name[wholen] != 0 &&
1083                     strcmp(name + wholen, "name") &&
1084                     strcmp(name + wholen, "email") &&
1085                     !starts_with(name + wholen, "date"))
1086                         continue;
1087                 if (!wholine)
1088                         wholine = find_wholine(who, wholen, buf, sz);
1089                 if (!wholine)
1090                         return; /* no point looking for it */
1091                 if (name[wholen] == 0)
1092                         v->s = copy_line(wholine);
1093                 else if (!strcmp(name + wholen, "name"))
1094                         v->s = copy_name(wholine);
1095                 else if (!strcmp(name + wholen, "email"))
1096                         v->s = copy_email(wholine);
1097                 else if (starts_with(name + wholen, "date"))
1098                         grab_date(wholine, v, name);
1099         }
1100
1101         /*
1102          * For a tag or a commit object, if "creator" or "creatordate" is
1103          * requested, do something special.
1104          */
1105         if (strcmp(who, "tagger") && strcmp(who, "committer"))
1106                 return; /* "author" for commit object is not wanted */
1107         if (!wholine)
1108                 wholine = find_wholine(who, wholen, buf, sz);
1109         if (!wholine)
1110                 return;
1111         for (i = 0; i < used_atom_cnt; i++) {
1112                 const char *name = used_atom[i].name;
1113                 struct atom_value *v = &val[i];
1114                 if (!!deref != (*name == '*'))
1115                         continue;
1116                 if (deref)
1117                         name++;
1118
1119                 if (starts_with(name, "creatordate"))
1120                         grab_date(wholine, v, name);
1121                 else if (!strcmp(name, "creator"))
1122                         v->s = copy_line(wholine);
1123         }
1124 }
1125
1126 static void find_subpos(const char *buf, unsigned long sz,
1127                         const char **sub, unsigned long *sublen,
1128                         const char **body, unsigned long *bodylen,
1129                         unsigned long *nonsiglen,
1130                         const char **sig, unsigned long *siglen)
1131 {
1132         const char *eol;
1133         /* skip past header until we hit empty line */
1134         while (*buf && *buf != '\n') {
1135                 eol = strchrnul(buf, '\n');
1136                 if (*eol)
1137                         eol++;
1138                 buf = eol;
1139         }
1140         /* skip any empty lines */
1141         while (*buf == '\n')
1142                 buf++;
1143
1144         /* parse signature first; we might not even have a subject line */
1145         *sig = buf + parse_signature(buf, strlen(buf));
1146         *siglen = strlen(*sig);
1147
1148         /* subject is first non-empty line */
1149         *sub = buf;
1150         /* subject goes to first empty line */
1151         while (buf < *sig && *buf && *buf != '\n') {
1152                 eol = strchrnul(buf, '\n');
1153                 if (*eol)
1154                         eol++;
1155                 buf = eol;
1156         }
1157         *sublen = buf - *sub;
1158         /* drop trailing newline, if present */
1159         if (*sublen && (*sub)[*sublen - 1] == '\n')
1160                 *sublen -= 1;
1161
1162         /* skip any empty lines */
1163         while (*buf == '\n')
1164                 buf++;
1165         *body = buf;
1166         *bodylen = strlen(buf);
1167         *nonsiglen = *sig - buf;
1168 }
1169
1170 /*
1171  * If 'lines' is greater than 0, append that many lines from the given
1172  * 'buf' of length 'size' to the given strbuf.
1173  */
1174 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1175 {
1176         int i;
1177         const char *sp, *eol;
1178         size_t len;
1179
1180         sp = buf;
1181
1182         for (i = 0; i < lines && sp < buf + size; i++) {
1183                 if (i)
1184                         strbuf_addstr(out, "\n    ");
1185                 eol = memchr(sp, '\n', size - (sp - buf));
1186                 len = eol ? eol - sp : size - (sp - buf);
1187                 strbuf_add(out, sp, len);
1188                 if (!eol)
1189                         break;
1190                 sp = eol + 1;
1191         }
1192 }
1193
1194 /* See grab_values */
1195 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1196 {
1197         int i;
1198         const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1199         unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1200
1201         for (i = 0; i < used_atom_cnt; i++) {
1202                 struct used_atom *atom = &used_atom[i];
1203                 const char *name = atom->name;
1204                 struct atom_value *v = &val[i];
1205                 if (!!deref != (*name == '*'))
1206                         continue;
1207                 if (deref)
1208                         name++;
1209                 if (strcmp(name, "subject") &&
1210                     strcmp(name, "body") &&
1211                     !starts_with(name, "trailers") &&
1212                     !starts_with(name, "contents"))
1213                         continue;
1214                 if (!subpos)
1215                         find_subpos(buf, sz,
1216                                     &subpos, &sublen,
1217                                     &bodypos, &bodylen, &nonsiglen,
1218                                     &sigpos, &siglen);
1219
1220                 if (atom->u.contents.option == C_SUB)
1221                         v->s = copy_subject(subpos, sublen);
1222                 else if (atom->u.contents.option == C_BODY_DEP)
1223                         v->s = xmemdupz(bodypos, bodylen);
1224                 else if (atom->u.contents.option == C_BODY)
1225                         v->s = xmemdupz(bodypos, nonsiglen);
1226                 else if (atom->u.contents.option == C_SIG)
1227                         v->s = xmemdupz(sigpos, siglen);
1228                 else if (atom->u.contents.option == C_LINES) {
1229                         struct strbuf s = STRBUF_INIT;
1230                         const char *contents_end = bodylen + bodypos - siglen;
1231
1232                         /*  Size is the length of the message after removing the signature */
1233                         append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1234                         v->s = strbuf_detach(&s, NULL);
1235                 } else if (atom->u.contents.option == C_TRAILERS) {
1236                         struct strbuf s = STRBUF_INIT;
1237
1238                         /* Format the trailer info according to the trailer_opts given */
1239                         format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1240
1241                         v->s = strbuf_detach(&s, NULL);
1242                 } else if (atom->u.contents.option == C_BARE)
1243                         v->s = xstrdup(subpos);
1244         }
1245 }
1246
1247 /*
1248  * We want to have empty print-string for field requests
1249  * that do not apply (e.g. "authordate" for a tag object)
1250  */
1251 static void fill_missing_values(struct atom_value *val)
1252 {
1253         int i;
1254         for (i = 0; i < used_atom_cnt; i++) {
1255                 struct atom_value *v = &val[i];
1256                 if (v->s == NULL)
1257                         v->s = xstrdup("");
1258         }
1259 }
1260
1261 /*
1262  * val is a list of atom_value to hold returned values.  Extract
1263  * the values for atoms in used_atom array out of (obj, buf, sz).
1264  * when deref is false, (obj, buf, sz) is the object that is
1265  * pointed at by the ref itself; otherwise it is the object the
1266  * ref (which is a tag) refers to.
1267  */
1268 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1269 {
1270         switch (obj->type) {
1271         case OBJ_TAG:
1272                 grab_tag_values(val, deref, obj, buf, sz);
1273                 grab_sub_body_contents(val, deref, obj, buf, sz);
1274                 grab_person("tagger", val, deref, obj, buf, sz);
1275                 break;
1276         case OBJ_COMMIT:
1277                 grab_commit_values(val, deref, obj, buf, sz);
1278                 grab_sub_body_contents(val, deref, obj, buf, sz);
1279                 grab_person("author", val, deref, obj, buf, sz);
1280                 grab_person("committer", val, deref, obj, buf, sz);
1281                 break;
1282         case OBJ_TREE:
1283                 /* grab_tree_values(val, deref, obj, buf, sz); */
1284                 break;
1285         case OBJ_BLOB:
1286                 /* grab_blob_values(val, deref, obj, buf, sz); */
1287                 break;
1288         default:
1289                 die("Eh?  Object of type %d?", obj->type);
1290         }
1291 }
1292
1293 static inline char *copy_advance(char *dst, const char *src)
1294 {
1295         while (*src)
1296                 *dst++ = *src++;
1297         return dst;
1298 }
1299
1300 static const char *lstrip_ref_components(const char *refname, int len)
1301 {
1302         long remaining = len;
1303         const char *start = xstrdup(refname);
1304         const char *to_free = start;
1305
1306         if (len < 0) {
1307                 int i;
1308                 const char *p = refname;
1309
1310                 /* Find total no of '/' separated path-components */
1311                 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1312                         ;
1313                 /*
1314                  * The number of components we need to strip is now
1315                  * the total minus the components to be left (Plus one
1316                  * because we count the number of '/', but the number
1317                  * of components is one more than the no of '/').
1318                  */
1319                 remaining = i + len + 1;
1320         }
1321
1322         while (remaining > 0) {
1323                 switch (*start++) {
1324                 case '\0':
1325                         free((char *)to_free);
1326                         return xstrdup("");
1327                 case '/':
1328                         remaining--;
1329                         break;
1330                 }
1331         }
1332
1333         start = xstrdup(start);
1334         free((char *)to_free);
1335         return start;
1336 }
1337
1338 static const char *rstrip_ref_components(const char *refname, int len)
1339 {
1340         long remaining = len;
1341         const char *start = xstrdup(refname);
1342         const char *to_free = start;
1343
1344         if (len < 0) {
1345                 int i;
1346                 const char *p = refname;
1347
1348                 /* Find total no of '/' separated path-components */
1349                 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1350                         ;
1351                 /*
1352                  * The number of components we need to strip is now
1353                  * the total minus the components to be left (Plus one
1354                  * because we count the number of '/', but the number
1355                  * of components is one more than the no of '/').
1356                  */
1357                 remaining = i + len + 1;
1358         }
1359
1360         while (remaining-- > 0) {
1361                 char *p = strrchr(start, '/');
1362                 if (p == NULL) {
1363                         free((char *)to_free);
1364                         return xstrdup("");
1365                 } else
1366                         p[0] = '\0';
1367         }
1368         return start;
1369 }
1370
1371 static const char *show_ref(struct refname_atom *atom, const char *refname)
1372 {
1373         if (atom->option == R_SHORT)
1374                 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1375         else if (atom->option == R_LSTRIP)
1376                 return lstrip_ref_components(refname, atom->lstrip);
1377         else if (atom->option == R_RSTRIP)
1378                 return rstrip_ref_components(refname, atom->rstrip);
1379         else
1380                 return xstrdup(refname);
1381 }
1382
1383 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1384                                     struct branch *branch, const char **s)
1385 {
1386         int num_ours, num_theirs;
1387         if (atom->u.remote_ref.option == RR_REF)
1388                 *s = show_ref(&atom->u.remote_ref.refname, refname);
1389         else if (atom->u.remote_ref.option == RR_TRACK) {
1390                 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1391                                        NULL, AHEAD_BEHIND_FULL) < 0) {
1392                         *s = xstrdup(msgs.gone);
1393                 } else if (!num_ours && !num_theirs)
1394                         *s = xstrdup("");
1395                 else if (!num_ours)
1396                         *s = xstrfmt(msgs.behind, num_theirs);
1397                 else if (!num_theirs)
1398                         *s = xstrfmt(msgs.ahead, num_ours);
1399                 else
1400                         *s = xstrfmt(msgs.ahead_behind,
1401                                      num_ours, num_theirs);
1402                 if (!atom->u.remote_ref.nobracket && *s[0]) {
1403                         const char *to_free = *s;
1404                         *s = xstrfmt("[%s]", *s);
1405                         free((void *)to_free);
1406                 }
1407         } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1408                 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1409                                        NULL, AHEAD_BEHIND_FULL) < 0) {
1410                         *s = xstrdup("");
1411                         return;
1412                 }
1413                 if (!num_ours && !num_theirs)
1414                         *s = xstrdup("=");
1415                 else if (!num_ours)
1416                         *s = xstrdup("<");
1417                 else if (!num_theirs)
1418                         *s = xstrdup(">");
1419                 else
1420                         *s = xstrdup("<>");
1421         } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1422                 int explicit;
1423                 const char *remote = atom->u.remote_ref.push ?
1424                         pushremote_for_branch(branch, &explicit) :
1425                         remote_for_branch(branch, &explicit);
1426                 *s = xstrdup(explicit ? remote : "");
1427         } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1428                 int explicit;
1429                 const char *merge;
1430
1431                 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1432                                               &explicit);
1433                 *s = xstrdup(explicit ? merge : "");
1434         } else
1435                 BUG("unhandled RR_* enum");
1436 }
1437
1438 char *get_head_description(void)
1439 {
1440         struct strbuf desc = STRBUF_INIT;
1441         struct wt_status_state state;
1442         memset(&state, 0, sizeof(state));
1443         wt_status_get_state(the_repository, &state, 1);
1444         if (state.rebase_in_progress ||
1445             state.rebase_interactive_in_progress) {
1446                 if (state.branch)
1447                         strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1448                                     state.branch);
1449                 else
1450                         strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1451                                     state.detached_from);
1452         } else if (state.bisect_in_progress)
1453                 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1454                             state.branch);
1455         else if (state.detached_from) {
1456                 if (state.detached_at)
1457                         /*
1458                          * TRANSLATORS: make sure this matches "HEAD
1459                          * detached at " in wt-status.c
1460                          */
1461                         strbuf_addf(&desc, _("(HEAD detached at %s)"),
1462                                 state.detached_from);
1463                 else
1464                         /*
1465                          * TRANSLATORS: make sure this matches "HEAD
1466                          * detached from " in wt-status.c
1467                          */
1468                         strbuf_addf(&desc, _("(HEAD detached from %s)"),
1469                                 state.detached_from);
1470         }
1471         else
1472                 strbuf_addstr(&desc, _("(no branch)"));
1473         free(state.branch);
1474         free(state.onto);
1475         free(state.detached_from);
1476         return strbuf_detach(&desc, NULL);
1477 }
1478
1479 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1480 {
1481         if (!ref->symref)
1482                 return xstrdup("");
1483         else
1484                 return show_ref(&atom->u.refname, ref->symref);
1485 }
1486
1487 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1488 {
1489         if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1490                 return get_head_description();
1491         return show_ref(&atom->u.refname, ref->refname);
1492 }
1493
1494 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1495                       struct expand_data *oi, struct strbuf *err)
1496 {
1497         /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1498         int eaten = 1;
1499         if (oi->info.contentp) {
1500                 /* We need to know that to use parse_object_buffer properly */
1501                 oi->info.sizep = &oi->size;
1502                 oi->info.typep = &oi->type;
1503         }
1504         if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1505                                      OBJECT_INFO_LOOKUP_REPLACE))
1506                 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1507                                        oid_to_hex(&oi->oid), ref->refname);
1508         if (oi->info.disk_sizep && oi->disk_size < 0)
1509                 BUG("Object size is less than zero.");
1510
1511         if (oi->info.contentp) {
1512                 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1513                 if (!obj) {
1514                         if (!eaten)
1515                                 free(oi->content);
1516                         return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1517                                                oid_to_hex(&oi->oid), ref->refname);
1518                 }
1519                 grab_values(ref->value, deref, *obj, oi->content, oi->size);
1520         }
1521
1522         grab_common_values(ref->value, deref, oi);
1523         if (!eaten)
1524                 free(oi->content);
1525         return 0;
1526 }
1527
1528 /*
1529  * Parse the object referred by ref, and grab needed value.
1530  */
1531 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1532 {
1533         struct object *obj;
1534         int i;
1535         struct object_info empty = OBJECT_INFO_INIT;
1536
1537         ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1538
1539         if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1540                 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1541                                              NULL, NULL);
1542                 if (!ref->symref)
1543                         ref->symref = xstrdup("");
1544         }
1545
1546         /* Fill in specials first */
1547         for (i = 0; i < used_atom_cnt; i++) {
1548                 struct used_atom *atom = &used_atom[i];
1549                 const char *name = used_atom[i].name;
1550                 struct atom_value *v = &ref->value[i];
1551                 int deref = 0;
1552                 const char *refname;
1553                 struct branch *branch = NULL;
1554
1555                 v->handler = append_atom;
1556                 v->atom = atom;
1557
1558                 if (*name == '*') {
1559                         deref = 1;
1560                         name++;
1561                 }
1562
1563                 if (starts_with(name, "refname"))
1564                         refname = get_refname(atom, ref);
1565                 else if (starts_with(name, "symref"))
1566                         refname = get_symref(atom, ref);
1567                 else if (starts_with(name, "upstream")) {
1568                         const char *branch_name;
1569                         /* only local branches may have an upstream */
1570                         if (!skip_prefix(ref->refname, "refs/heads/",
1571                                          &branch_name)) {
1572                                 v->s = xstrdup("");
1573                                 continue;
1574                         }
1575                         branch = branch_get(branch_name);
1576
1577                         refname = branch_get_upstream(branch, NULL);
1578                         if (refname)
1579                                 fill_remote_ref_details(atom, refname, branch, &v->s);
1580                         else
1581                                 v->s = xstrdup("");
1582                         continue;
1583                 } else if (atom->u.remote_ref.push) {
1584                         const char *branch_name;
1585                         v->s = xstrdup("");
1586                         if (!skip_prefix(ref->refname, "refs/heads/",
1587                                          &branch_name))
1588                                 continue;
1589                         branch = branch_get(branch_name);
1590
1591                         if (atom->u.remote_ref.push_remote)
1592                                 refname = NULL;
1593                         else {
1594                                 refname = branch_get_push(branch, NULL);
1595                                 if (!refname)
1596                                         continue;
1597                         }
1598                         /* We will definitely re-init v->s on the next line. */
1599                         free((char *)v->s);
1600                         fill_remote_ref_details(atom, refname, branch, &v->s);
1601                         continue;
1602                 } else if (starts_with(name, "color:")) {
1603                         v->s = xstrdup(atom->u.color);
1604                         continue;
1605                 } else if (!strcmp(name, "flag")) {
1606                         char buf[256], *cp = buf;
1607                         if (ref->flag & REF_ISSYMREF)
1608                                 cp = copy_advance(cp, ",symref");
1609                         if (ref->flag & REF_ISPACKED)
1610                                 cp = copy_advance(cp, ",packed");
1611                         if (cp == buf)
1612                                 v->s = xstrdup("");
1613                         else {
1614                                 *cp = '\0';
1615                                 v->s = xstrdup(buf + 1);
1616                         }
1617                         continue;
1618                 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1619                         continue;
1620                 } else if (!strcmp(name, "HEAD")) {
1621                         if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1622                                 v->s = xstrdup("*");
1623                         else
1624                                 v->s = xstrdup(" ");
1625                         continue;
1626                 } else if (starts_with(name, "align")) {
1627                         v->handler = align_atom_handler;
1628                         v->s = xstrdup("");
1629                         continue;
1630                 } else if (!strcmp(name, "end")) {
1631                         v->handler = end_atom_handler;
1632                         v->s = xstrdup("");
1633                         continue;
1634                 } else if (starts_with(name, "if")) {
1635                         const char *s;
1636                         if (skip_prefix(name, "if:", &s))
1637                                 v->s = xstrdup(s);
1638                         else
1639                                 v->s = xstrdup("");
1640                         v->handler = if_atom_handler;
1641                         continue;
1642                 } else if (!strcmp(name, "then")) {
1643                         v->handler = then_atom_handler;
1644                         v->s = xstrdup("");
1645                         continue;
1646                 } else if (!strcmp(name, "else")) {
1647                         v->handler = else_atom_handler;
1648                         v->s = xstrdup("");
1649                         continue;
1650                 } else
1651                         continue;
1652
1653                 if (!deref)
1654                         v->s = xstrdup(refname);
1655                 else
1656                         v->s = xstrfmt("%s^{}", refname);
1657                 free((char *)refname);
1658         }
1659
1660         for (i = 0; i < used_atom_cnt; i++) {
1661                 struct atom_value *v = &ref->value[i];
1662                 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1663                         return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1664                                                oid_to_hex(&ref->objectname), ref->refname);
1665         }
1666
1667         if (need_tagged)
1668                 oi.info.contentp = &oi.content;
1669         if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1670             !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1671                 return 0;
1672
1673
1674         oi.oid = ref->objectname;
1675         if (get_object(ref, 0, &obj, &oi, err))
1676                 return -1;
1677
1678         /*
1679          * If there is no atom that wants to know about tagged
1680          * object, we are done.
1681          */
1682         if (!need_tagged || (obj->type != OBJ_TAG))
1683                 return 0;
1684
1685         /*
1686          * If it is a tag object, see if we use a value that derefs
1687          * the object, and if we do grab the object it refers to.
1688          */
1689         oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1690
1691         /*
1692          * NEEDSWORK: This derefs tag only once, which
1693          * is good to deal with chains of trust, but
1694          * is not consistent with what deref_tag() does
1695          * which peels the onion to the core.
1696          */
1697         return get_object(ref, 1, &obj, &oi_deref, err);
1698 }
1699
1700 /*
1701  * Given a ref, return the value for the atom.  This lazily gets value
1702  * out of the object by calling populate value.
1703  */
1704 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1705                               struct atom_value **v, struct strbuf *err)
1706 {
1707         if (!ref->value) {
1708                 if (populate_value(ref, err))
1709                         return -1;
1710                 fill_missing_values(ref->value);
1711         }
1712         *v = &ref->value[atom];
1713         return 0;
1714 }
1715
1716 /*
1717  * Return 1 if the refname matches one of the patterns, otherwise 0.
1718  * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1719  * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1720  * matches "refs/heads/mas*", too).
1721  */
1722 static int match_pattern(const struct ref_filter *filter, const char *refname)
1723 {
1724         const char **patterns = filter->name_patterns;
1725         unsigned flags = 0;
1726
1727         if (filter->ignore_case)
1728                 flags |= WM_CASEFOLD;
1729
1730         /*
1731          * When no '--format' option is given we need to skip the prefix
1732          * for matching refs of tags and branches.
1733          */
1734         (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1735                skip_prefix(refname, "refs/heads/", &refname) ||
1736                skip_prefix(refname, "refs/remotes/", &refname) ||
1737                skip_prefix(refname, "refs/", &refname));
1738
1739         for (; *patterns; patterns++) {
1740                 if (!wildmatch(*patterns, refname, flags))
1741                         return 1;
1742         }
1743         return 0;
1744 }
1745
1746 /*
1747  * Return 1 if the refname matches one of the patterns, otherwise 0.
1748  * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1749  * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1750  * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1751  */
1752 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1753 {
1754         const char **pattern = filter->name_patterns;
1755         int namelen = strlen(refname);
1756         unsigned flags = WM_PATHNAME;
1757
1758         if (filter->ignore_case)
1759                 flags |= WM_CASEFOLD;
1760
1761         for (; *pattern; pattern++) {
1762                 const char *p = *pattern;
1763                 int plen = strlen(p);
1764
1765                 if ((plen <= namelen) &&
1766                     !strncmp(refname, p, plen) &&
1767                     (refname[plen] == '\0' ||
1768                      refname[plen] == '/' ||
1769                      p[plen-1] == '/'))
1770                         return 1;
1771                 if (!wildmatch(p, refname, flags))
1772                         return 1;
1773         }
1774         return 0;
1775 }
1776
1777 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1778 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1779 {
1780         if (!*filter->name_patterns)
1781                 return 1; /* No pattern always matches */
1782         if (filter->match_as_path)
1783                 return match_name_as_path(filter, refname);
1784         return match_pattern(filter, refname);
1785 }
1786
1787 /*
1788  * Find the longest prefix of pattern we can pass to
1789  * `for_each_fullref_in()`, namely the part of pattern preceding the
1790  * first glob character. (Note that `for_each_fullref_in()` is
1791  * perfectly happy working with a prefix that doesn't end at a
1792  * pathname component boundary.)
1793  */
1794 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1795 {
1796         const char *p;
1797
1798         for (p = pattern; *p && !is_glob_special(*p); p++)
1799                 ;
1800
1801         strbuf_add(out, pattern, p - pattern);
1802 }
1803
1804 /*
1805  * This is the same as for_each_fullref_in(), but it tries to iterate
1806  * only over the patterns we'll care about. Note that it _doesn't_ do a full
1807  * pattern match, so the callback still has to match each ref individually.
1808  */
1809 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1810                                        each_ref_fn cb,
1811                                        void *cb_data,
1812                                        int broken)
1813 {
1814         struct strbuf prefix = STRBUF_INIT;
1815         int ret;
1816
1817         if (!filter->match_as_path) {
1818                 /*
1819                  * in this case, the patterns are applied after
1820                  * prefixes like "refs/heads/" etc. are stripped off,
1821                  * so we have to look at everything:
1822                  */
1823                 return for_each_fullref_in("", cb, cb_data, broken);
1824         }
1825
1826         if (filter->ignore_case) {
1827                 /*
1828                  * we can't handle case-insensitive comparisons,
1829                  * so just return everything and let the caller
1830                  * sort it out.
1831                  */
1832                 return for_each_fullref_in("", cb, cb_data, broken);
1833         }
1834
1835         if (!filter->name_patterns[0]) {
1836                 /* no patterns; we have to look at everything */
1837                 return for_each_fullref_in("", cb, cb_data, broken);
1838         }
1839
1840         if (filter->name_patterns[1]) {
1841                 /*
1842                  * multiple patterns; in theory this could still work as long
1843                  * as the patterns are disjoint. We'd just make multiple calls
1844                  * to for_each_ref(). But if they're not disjoint, we'd end up
1845                  * reporting the same ref multiple times. So let's punt on that
1846                  * for now.
1847                  */
1848                 return for_each_fullref_in("", cb, cb_data, broken);
1849         }
1850
1851         find_longest_prefix(&prefix, filter->name_patterns[0]);
1852
1853         ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1854         strbuf_release(&prefix);
1855         return ret;
1856 }
1857
1858 /*
1859  * Given a ref (sha1, refname), check if the ref belongs to the array
1860  * of sha1s. If the given ref is a tag, check if the given tag points
1861  * at one of the sha1s in the given sha1 array.
1862  * the given sha1_array.
1863  * NEEDSWORK:
1864  * 1. Only a single level of inderection is obtained, we might want to
1865  * change this to account for multiple levels (e.g. annotated tags
1866  * pointing to annotated tags pointing to a commit.)
1867  * 2. As the refs are cached we might know what refname peels to without
1868  * the need to parse the object via parse_object(). peel_ref() might be a
1869  * more efficient alternative to obtain the pointee.
1870  */
1871 static const struct object_id *match_points_at(struct oid_array *points_at,
1872                                                const struct object_id *oid,
1873                                                const char *refname)
1874 {
1875         const struct object_id *tagged_oid = NULL;
1876         struct object *obj;
1877
1878         if (oid_array_lookup(points_at, oid) >= 0)
1879                 return oid;
1880         obj = parse_object(the_repository, oid);
1881         if (!obj)
1882                 die(_("malformed object at '%s'"), refname);
1883         if (obj->type == OBJ_TAG)
1884                 tagged_oid = &((struct tag *)obj)->tagged->oid;
1885         if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1886                 return tagged_oid;
1887         return NULL;
1888 }
1889
1890 /*
1891  * Allocate space for a new ref_array_item and copy the name and oid to it.
1892  *
1893  * Callers can then fill in other struct members at their leisure.
1894  */
1895 static struct ref_array_item *new_ref_array_item(const char *refname,
1896                                                  const struct object_id *oid)
1897 {
1898         struct ref_array_item *ref;
1899
1900         FLEX_ALLOC_STR(ref, refname, refname);
1901         oidcpy(&ref->objectname, oid);
1902
1903         return ref;
1904 }
1905
1906 struct ref_array_item *ref_array_push(struct ref_array *array,
1907                                       const char *refname,
1908                                       const struct object_id *oid)
1909 {
1910         struct ref_array_item *ref = new_ref_array_item(refname, oid);
1911
1912         ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1913         array->items[array->nr++] = ref;
1914
1915         return ref;
1916 }
1917
1918 static int ref_kind_from_refname(const char *refname)
1919 {
1920         unsigned int i;
1921
1922         static struct {
1923                 const char *prefix;
1924                 unsigned int kind;
1925         } ref_kind[] = {
1926                 { "refs/heads/" , FILTER_REFS_BRANCHES },
1927                 { "refs/remotes/" , FILTER_REFS_REMOTES },
1928                 { "refs/tags/", FILTER_REFS_TAGS}
1929         };
1930
1931         if (!strcmp(refname, "HEAD"))
1932                 return FILTER_REFS_DETACHED_HEAD;
1933
1934         for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1935                 if (starts_with(refname, ref_kind[i].prefix))
1936                         return ref_kind[i].kind;
1937         }
1938
1939         return FILTER_REFS_OTHERS;
1940 }
1941
1942 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1943 {
1944         if (filter->kind == FILTER_REFS_BRANCHES ||
1945             filter->kind == FILTER_REFS_REMOTES ||
1946             filter->kind == FILTER_REFS_TAGS)
1947                 return filter->kind;
1948         return ref_kind_from_refname(refname);
1949 }
1950
1951 struct ref_filter_cbdata {
1952         struct ref_array *array;
1953         struct ref_filter *filter;
1954         struct contains_cache contains_cache;
1955         struct contains_cache no_contains_cache;
1956 };
1957
1958 /*
1959  * A call-back given to for_each_ref().  Filter refs and keep them for
1960  * later object processing.
1961  */
1962 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1963 {
1964         struct ref_filter_cbdata *ref_cbdata = cb_data;
1965         struct ref_filter *filter = ref_cbdata->filter;
1966         struct ref_array_item *ref;
1967         struct commit *commit = NULL;
1968         unsigned int kind;
1969
1970         if (flag & REF_BAD_NAME) {
1971                 warning(_("ignoring ref with broken name %s"), refname);
1972                 return 0;
1973         }
1974
1975         if (flag & REF_ISBROKEN) {
1976                 warning(_("ignoring broken ref %s"), refname);
1977                 return 0;
1978         }
1979
1980         /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1981         kind = filter_ref_kind(filter, refname);
1982         if (!(kind & filter->kind))
1983                 return 0;
1984
1985         if (!filter_pattern_match(filter, refname))
1986                 return 0;
1987
1988         if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1989                 return 0;
1990
1991         /*
1992          * A merge filter is applied on refs pointing to commits. Hence
1993          * obtain the commit using the 'oid' available and discard all
1994          * non-commits early. The actual filtering is done later.
1995          */
1996         if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1997                 commit = lookup_commit_reference_gently(the_repository, oid,
1998                                                         1);
1999                 if (!commit)
2000                         return 0;
2001                 /* We perform the filtering for the '--contains' option... */
2002                 if (filter->with_commit &&
2003                     !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2004                         return 0;
2005                 /* ...or for the `--no-contains' option */
2006                 if (filter->no_commit &&
2007                     commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2008                         return 0;
2009         }
2010
2011         /*
2012          * We do not open the object yet; sort may only need refname
2013          * to do its job and the resulting list may yet to be pruned
2014          * by maxcount logic.
2015          */
2016         ref = ref_array_push(ref_cbdata->array, refname, oid);
2017         ref->commit = commit;
2018         ref->flag = flag;
2019         ref->kind = kind;
2020
2021         return 0;
2022 }
2023
2024 /*  Free memory allocated for a ref_array_item */
2025 static void free_array_item(struct ref_array_item *item)
2026 {
2027         free((char *)item->symref);
2028         if (item->value) {
2029                 free((char *)item->value->s);
2030                 free(item->value);
2031         }
2032         free(item);
2033 }
2034
2035 /* Free all memory allocated for ref_array */
2036 void ref_array_clear(struct ref_array *array)
2037 {
2038         int i;
2039
2040         for (i = 0; i < used_atom_cnt; i++)
2041                 free((char *)used_atom[i].name);
2042         FREE_AND_NULL(used_atom);
2043         used_atom_cnt = 0;
2044         for (i = 0; i < array->nr; i++)
2045                 free_array_item(array->items[i]);
2046         FREE_AND_NULL(array->items);
2047         array->nr = array->alloc = 0;
2048 }
2049
2050 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2051 {
2052         struct rev_info revs;
2053         int i, old_nr;
2054         struct ref_filter *filter = ref_cbdata->filter;
2055         struct ref_array *array = ref_cbdata->array;
2056         struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2057
2058         repo_init_revisions(the_repository, &revs, NULL);
2059
2060         for (i = 0; i < array->nr; i++) {
2061                 struct ref_array_item *item = array->items[i];
2062                 add_pending_object(&revs, &item->commit->object, item->refname);
2063                 to_clear[i] = item->commit;
2064         }
2065
2066         filter->merge_commit->object.flags |= UNINTERESTING;
2067         add_pending_object(&revs, &filter->merge_commit->object, "");
2068
2069         revs.limited = 1;
2070         if (prepare_revision_walk(&revs))
2071                 die(_("revision walk setup failed"));
2072
2073         old_nr = array->nr;
2074         array->nr = 0;
2075
2076         for (i = 0; i < old_nr; i++) {
2077                 struct ref_array_item *item = array->items[i];
2078                 struct commit *commit = item->commit;
2079
2080                 int is_merged = !!(commit->object.flags & UNINTERESTING);
2081
2082                 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2083                         array->items[array->nr++] = array->items[i];
2084                 else
2085                         free_array_item(item);
2086         }
2087
2088         clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2089         clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2090         free(to_clear);
2091 }
2092
2093 /*
2094  * API for filtering a set of refs. Based on the type of refs the user
2095  * has requested, we iterate through those refs and apply filters
2096  * as per the given ref_filter structure and finally store the
2097  * filtered refs in the ref_array structure.
2098  */
2099 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2100 {
2101         struct ref_filter_cbdata ref_cbdata;
2102         int ret = 0;
2103         unsigned int broken = 0;
2104
2105         ref_cbdata.array = array;
2106         ref_cbdata.filter = filter;
2107
2108         if (type & FILTER_REFS_INCLUDE_BROKEN)
2109                 broken = 1;
2110         filter->kind = type & FILTER_REFS_KIND_MASK;
2111
2112         init_contains_cache(&ref_cbdata.contains_cache);
2113         init_contains_cache(&ref_cbdata.no_contains_cache);
2114
2115         /*  Simple per-ref filtering */
2116         if (!filter->kind)
2117                 die("filter_refs: invalid type");
2118         else {
2119                 /*
2120                  * For common cases where we need only branches or remotes or tags,
2121                  * we only iterate through those refs. If a mix of refs is needed,
2122                  * we iterate over all refs and filter out required refs with the help
2123                  * of filter_ref_kind().
2124                  */
2125                 if (filter->kind == FILTER_REFS_BRANCHES)
2126                         ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2127                 else if (filter->kind == FILTER_REFS_REMOTES)
2128                         ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2129                 else if (filter->kind == FILTER_REFS_TAGS)
2130                         ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2131                 else if (filter->kind & FILTER_REFS_ALL)
2132                         ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2133                 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2134                         head_ref(ref_filter_handler, &ref_cbdata);
2135         }
2136
2137         clear_contains_cache(&ref_cbdata.contains_cache);
2138         clear_contains_cache(&ref_cbdata.no_contains_cache);
2139
2140         /*  Filters that need revision walking */
2141         if (filter->merge_commit)
2142                 do_merge_filter(&ref_cbdata);
2143
2144         return ret;
2145 }
2146
2147 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2148 {
2149         struct atom_value *va, *vb;
2150         int cmp;
2151         cmp_type cmp_type = used_atom[s->atom].type;
2152         int (*cmp_fn)(const char *, const char *);
2153         struct strbuf err = STRBUF_INIT;
2154
2155         if (get_ref_atom_value(a, s->atom, &va, &err))
2156                 die("%s", err.buf);
2157         if (get_ref_atom_value(b, s->atom, &vb, &err))
2158                 die("%s", err.buf);
2159         strbuf_release(&err);
2160         cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2161         if (s->version)
2162                 cmp = versioncmp(va->s, vb->s);
2163         else if (cmp_type == FIELD_STR)
2164                 cmp = cmp_fn(va->s, vb->s);
2165         else {
2166                 if (va->value < vb->value)
2167                         cmp = -1;
2168                 else if (va->value == vb->value)
2169                         cmp = cmp_fn(a->refname, b->refname);
2170                 else
2171                         cmp = 1;
2172         }
2173
2174         return (s->reverse) ? -cmp : cmp;
2175 }
2176
2177 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2178 {
2179         struct ref_array_item *a = *((struct ref_array_item **)a_);
2180         struct ref_array_item *b = *((struct ref_array_item **)b_);
2181         struct ref_sorting *s;
2182
2183         for (s = ref_sorting; s; s = s->next) {
2184                 int cmp = cmp_ref_sorting(s, a, b);
2185                 if (cmp)
2186                         return cmp;
2187         }
2188         return 0;
2189 }
2190
2191 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2192 {
2193         QSORT_S(array->items, array->nr, compare_refs, sorting);
2194 }
2195
2196 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2197 {
2198         struct strbuf *s = &state->stack->output;
2199
2200         while (*cp && (!ep || cp < ep)) {
2201                 if (*cp == '%') {
2202                         if (cp[1] == '%')
2203                                 cp++;
2204                         else {
2205                                 int ch = hex2chr(cp + 1);
2206                                 if (0 <= ch) {
2207                                         strbuf_addch(s, ch);
2208                                         cp += 3;
2209                                         continue;
2210                                 }
2211                         }
2212                 }
2213                 strbuf_addch(s, *cp);
2214                 cp++;
2215         }
2216 }
2217
2218 int format_ref_array_item(struct ref_array_item *info,
2219                            const struct ref_format *format,
2220                            struct strbuf *final_buf,
2221                            struct strbuf *error_buf)
2222 {
2223         const char *cp, *sp, *ep;
2224         struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2225
2226         state.quote_style = format->quote_style;
2227         push_stack_element(&state.stack);
2228
2229         for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2230                 struct atom_value *atomv;
2231                 int pos;
2232
2233                 ep = strchr(sp, ')');
2234                 if (cp < sp)
2235                         append_literal(cp, sp, &state);
2236                 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2237                 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2238                     atomv->handler(atomv, &state, error_buf)) {
2239                         pop_stack_element(&state.stack);
2240                         return -1;
2241                 }
2242         }
2243         if (*cp) {
2244                 sp = cp + strlen(cp);
2245                 append_literal(cp, sp, &state);
2246         }
2247         if (format->need_color_reset_at_eol) {
2248                 struct atom_value resetv;
2249                 resetv.s = GIT_COLOR_RESET;
2250                 if (append_atom(&resetv, &state, error_buf)) {
2251                         pop_stack_element(&state.stack);
2252                         return -1;
2253                 }
2254         }
2255         if (state.stack->prev) {
2256                 pop_stack_element(&state.stack);
2257                 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2258         }
2259         strbuf_addbuf(final_buf, &state.stack->output);
2260         pop_stack_element(&state.stack);
2261         return 0;
2262 }
2263
2264 void show_ref_array_item(struct ref_array_item *info,
2265                          const struct ref_format *format)
2266 {
2267         struct strbuf final_buf = STRBUF_INIT;
2268         struct strbuf error_buf = STRBUF_INIT;
2269
2270         if (format_ref_array_item(info, format, &final_buf, &error_buf))
2271                 die("%s", error_buf.buf);
2272         fwrite(final_buf.buf, 1, final_buf.len, stdout);
2273         strbuf_release(&error_buf);
2274         strbuf_release(&final_buf);
2275         putchar('\n');
2276 }
2277
2278 void pretty_print_ref(const char *name, const struct object_id *oid,
2279                       const struct ref_format *format)
2280 {
2281         struct ref_array_item *ref_item;
2282         ref_item = new_ref_array_item(name, oid);
2283         ref_item->kind = ref_kind_from_refname(name);
2284         show_ref_array_item(ref_item, format);
2285         free_array_item(ref_item);
2286 }
2287
2288 static int parse_sorting_atom(const char *atom)
2289 {
2290         /*
2291          * This parses an atom using a dummy ref_format, since we don't
2292          * actually care about the formatting details.
2293          */
2294         struct ref_format dummy = REF_FORMAT_INIT;
2295         const char *end = atom + strlen(atom);
2296         struct strbuf err = STRBUF_INIT;
2297         int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2298         if (res < 0)
2299                 die("%s", err.buf);
2300         strbuf_release(&err);
2301         return res;
2302 }
2303
2304 /*  If no sorting option is given, use refname to sort as default */
2305 struct ref_sorting *ref_default_sorting(void)
2306 {
2307         static const char cstr_name[] = "refname";
2308
2309         struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2310
2311         sorting->next = NULL;
2312         sorting->atom = parse_sorting_atom(cstr_name);
2313         return sorting;
2314 }
2315
2316 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2317 {
2318         struct ref_sorting *s;
2319
2320         s = xcalloc(1, sizeof(*s));
2321         s->next = *sorting_tail;
2322         *sorting_tail = s;
2323
2324         if (*arg == '-') {
2325                 s->reverse = 1;
2326                 arg++;
2327         }
2328         if (skip_prefix(arg, "version:", &arg) ||
2329             skip_prefix(arg, "v:", &arg))
2330                 s->version = 1;
2331         s->atom = parse_sorting_atom(arg);
2332 }
2333
2334 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2335 {
2336         if (!arg) /* should --no-sort void the list ? */
2337                 return -1;
2338         parse_ref_sorting(opt->value, arg);
2339         return 0;
2340 }
2341
2342 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2343 {
2344         struct ref_filter *rf = opt->value;
2345         struct object_id oid;
2346         int no_merged = starts_with(opt->long_name, "no");
2347
2348         BUG_ON_OPT_NEG(unset);
2349
2350         if (rf->merge) {
2351                 if (no_merged) {
2352                         return error(_("option `%s' is incompatible with --merged"),
2353                                      opt->long_name);
2354                 } else {
2355                         return error(_("option `%s' is incompatible with --no-merged"),
2356                                      opt->long_name);
2357                 }
2358         }
2359
2360         rf->merge = no_merged
2361                 ? REF_FILTER_MERGED_OMIT
2362                 : REF_FILTER_MERGED_INCLUDE;
2363
2364         if (get_oid(arg, &oid))
2365                 die(_("malformed object name %s"), arg);
2366
2367         rf->merge_commit = lookup_commit_reference_gently(the_repository,
2368                                                           &oid, 0);
2369         if (!rf->merge_commit)
2370                 return error(_("option `%s' must point to a commit"), opt->long_name);
2371
2372         return 0;
2373 }