ref-filter: use correct branch for %(push:track)
[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, atom->u.remote_ref.push,
1392                                        AHEAD_BEHIND_FULL) < 0) {
1393                         *s = xstrdup(msgs.gone);
1394                 } else if (!num_ours && !num_theirs)
1395                         *s = xstrdup("");
1396                 else if (!num_ours)
1397                         *s = xstrfmt(msgs.behind, num_theirs);
1398                 else if (!num_theirs)
1399                         *s = xstrfmt(msgs.ahead, num_ours);
1400                 else
1401                         *s = xstrfmt(msgs.ahead_behind,
1402                                      num_ours, num_theirs);
1403                 if (!atom->u.remote_ref.nobracket && *s[0]) {
1404                         const char *to_free = *s;
1405                         *s = xstrfmt("[%s]", *s);
1406                         free((void *)to_free);
1407                 }
1408         } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1409                 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1410                                        NULL, atom->u.remote_ref.push,
1411                                        AHEAD_BEHIND_FULL) < 0) {
1412                         *s = xstrdup("");
1413                         return;
1414                 }
1415                 if (!num_ours && !num_theirs)
1416                         *s = xstrdup("=");
1417                 else if (!num_ours)
1418                         *s = xstrdup("<");
1419                 else if (!num_theirs)
1420                         *s = xstrdup(">");
1421                 else
1422                         *s = xstrdup("<>");
1423         } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1424                 int explicit;
1425                 const char *remote = atom->u.remote_ref.push ?
1426                         pushremote_for_branch(branch, &explicit) :
1427                         remote_for_branch(branch, &explicit);
1428                 *s = xstrdup(explicit ? remote : "");
1429         } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1430                 int explicit;
1431                 const char *merge;
1432
1433                 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1434                                               &explicit);
1435                 *s = xstrdup(explicit ? merge : "");
1436         } else
1437                 BUG("unhandled RR_* enum");
1438 }
1439
1440 char *get_head_description(void)
1441 {
1442         struct strbuf desc = STRBUF_INIT;
1443         struct wt_status_state state;
1444         memset(&state, 0, sizeof(state));
1445         wt_status_get_state(the_repository, &state, 1);
1446         if (state.rebase_in_progress ||
1447             state.rebase_interactive_in_progress) {
1448                 if (state.branch)
1449                         strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1450                                     state.branch);
1451                 else
1452                         strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1453                                     state.detached_from);
1454         } else if (state.bisect_in_progress)
1455                 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1456                             state.branch);
1457         else if (state.detached_from) {
1458                 if (state.detached_at)
1459                         /*
1460                          * TRANSLATORS: make sure this matches "HEAD
1461                          * detached at " in wt-status.c
1462                          */
1463                         strbuf_addf(&desc, _("(HEAD detached at %s)"),
1464                                 state.detached_from);
1465                 else
1466                         /*
1467                          * TRANSLATORS: make sure this matches "HEAD
1468                          * detached from " in wt-status.c
1469                          */
1470                         strbuf_addf(&desc, _("(HEAD detached from %s)"),
1471                                 state.detached_from);
1472         }
1473         else
1474                 strbuf_addstr(&desc, _("(no branch)"));
1475         free(state.branch);
1476         free(state.onto);
1477         free(state.detached_from);
1478         return strbuf_detach(&desc, NULL);
1479 }
1480
1481 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1482 {
1483         if (!ref->symref)
1484                 return xstrdup("");
1485         else
1486                 return show_ref(&atom->u.refname, ref->symref);
1487 }
1488
1489 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1490 {
1491         if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1492                 return get_head_description();
1493         return show_ref(&atom->u.refname, ref->refname);
1494 }
1495
1496 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1497                       struct expand_data *oi, struct strbuf *err)
1498 {
1499         /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1500         int eaten = 1;
1501         if (oi->info.contentp) {
1502                 /* We need to know that to use parse_object_buffer properly */
1503                 oi->info.sizep = &oi->size;
1504                 oi->info.typep = &oi->type;
1505         }
1506         if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1507                                      OBJECT_INFO_LOOKUP_REPLACE))
1508                 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1509                                        oid_to_hex(&oi->oid), ref->refname);
1510         if (oi->info.disk_sizep && oi->disk_size < 0)
1511                 BUG("Object size is less than zero.");
1512
1513         if (oi->info.contentp) {
1514                 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1515                 if (!obj) {
1516                         if (!eaten)
1517                                 free(oi->content);
1518                         return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1519                                                oid_to_hex(&oi->oid), ref->refname);
1520                 }
1521                 grab_values(ref->value, deref, *obj, oi->content, oi->size);
1522         }
1523
1524         grab_common_values(ref->value, deref, oi);
1525         if (!eaten)
1526                 free(oi->content);
1527         return 0;
1528 }
1529
1530 /*
1531  * Parse the object referred by ref, and grab needed value.
1532  */
1533 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1534 {
1535         struct object *obj;
1536         int i;
1537         struct object_info empty = OBJECT_INFO_INIT;
1538
1539         ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1540
1541         if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1542                 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1543                                              NULL, NULL);
1544                 if (!ref->symref)
1545                         ref->symref = xstrdup("");
1546         }
1547
1548         /* Fill in specials first */
1549         for (i = 0; i < used_atom_cnt; i++) {
1550                 struct used_atom *atom = &used_atom[i];
1551                 const char *name = used_atom[i].name;
1552                 struct atom_value *v = &ref->value[i];
1553                 int deref = 0;
1554                 const char *refname;
1555                 struct branch *branch = NULL;
1556
1557                 v->handler = append_atom;
1558                 v->atom = atom;
1559
1560                 if (*name == '*') {
1561                         deref = 1;
1562                         name++;
1563                 }
1564
1565                 if (starts_with(name, "refname"))
1566                         refname = get_refname(atom, ref);
1567                 else if (starts_with(name, "symref"))
1568                         refname = get_symref(atom, ref);
1569                 else if (starts_with(name, "upstream")) {
1570                         const char *branch_name;
1571                         /* only local branches may have an upstream */
1572                         if (!skip_prefix(ref->refname, "refs/heads/",
1573                                          &branch_name)) {
1574                                 v->s = xstrdup("");
1575                                 continue;
1576                         }
1577                         branch = branch_get(branch_name);
1578
1579                         refname = branch_get_upstream(branch, NULL);
1580                         if (refname)
1581                                 fill_remote_ref_details(atom, refname, branch, &v->s);
1582                         else
1583                                 v->s = xstrdup("");
1584                         continue;
1585                 } else if (atom->u.remote_ref.push) {
1586                         const char *branch_name;
1587                         v->s = xstrdup("");
1588                         if (!skip_prefix(ref->refname, "refs/heads/",
1589                                          &branch_name))
1590                                 continue;
1591                         branch = branch_get(branch_name);
1592
1593                         if (atom->u.remote_ref.push_remote)
1594                                 refname = NULL;
1595                         else {
1596                                 refname = branch_get_push(branch, NULL);
1597                                 if (!refname)
1598                                         continue;
1599                         }
1600                         /* We will definitely re-init v->s on the next line. */
1601                         free((char *)v->s);
1602                         fill_remote_ref_details(atom, refname, branch, &v->s);
1603                         continue;
1604                 } else if (starts_with(name, "color:")) {
1605                         v->s = xstrdup(atom->u.color);
1606                         continue;
1607                 } else if (!strcmp(name, "flag")) {
1608                         char buf[256], *cp = buf;
1609                         if (ref->flag & REF_ISSYMREF)
1610                                 cp = copy_advance(cp, ",symref");
1611                         if (ref->flag & REF_ISPACKED)
1612                                 cp = copy_advance(cp, ",packed");
1613                         if (cp == buf)
1614                                 v->s = xstrdup("");
1615                         else {
1616                                 *cp = '\0';
1617                                 v->s = xstrdup(buf + 1);
1618                         }
1619                         continue;
1620                 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1621                         continue;
1622                 } else if (!strcmp(name, "HEAD")) {
1623                         if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1624                                 v->s = xstrdup("*");
1625                         else
1626                                 v->s = xstrdup(" ");
1627                         continue;
1628                 } else if (starts_with(name, "align")) {
1629                         v->handler = align_atom_handler;
1630                         v->s = xstrdup("");
1631                         continue;
1632                 } else if (!strcmp(name, "end")) {
1633                         v->handler = end_atom_handler;
1634                         v->s = xstrdup("");
1635                         continue;
1636                 } else if (starts_with(name, "if")) {
1637                         const char *s;
1638                         if (skip_prefix(name, "if:", &s))
1639                                 v->s = xstrdup(s);
1640                         else
1641                                 v->s = xstrdup("");
1642                         v->handler = if_atom_handler;
1643                         continue;
1644                 } else if (!strcmp(name, "then")) {
1645                         v->handler = then_atom_handler;
1646                         v->s = xstrdup("");
1647                         continue;
1648                 } else if (!strcmp(name, "else")) {
1649                         v->handler = else_atom_handler;
1650                         v->s = xstrdup("");
1651                         continue;
1652                 } else
1653                         continue;
1654
1655                 if (!deref)
1656                         v->s = xstrdup(refname);
1657                 else
1658                         v->s = xstrfmt("%s^{}", refname);
1659                 free((char *)refname);
1660         }
1661
1662         for (i = 0; i < used_atom_cnt; i++) {
1663                 struct atom_value *v = &ref->value[i];
1664                 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1665                         return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1666                                                oid_to_hex(&ref->objectname), ref->refname);
1667         }
1668
1669         if (need_tagged)
1670                 oi.info.contentp = &oi.content;
1671         if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1672             !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1673                 return 0;
1674
1675
1676         oi.oid = ref->objectname;
1677         if (get_object(ref, 0, &obj, &oi, err))
1678                 return -1;
1679
1680         /*
1681          * If there is no atom that wants to know about tagged
1682          * object, we are done.
1683          */
1684         if (!need_tagged || (obj->type != OBJ_TAG))
1685                 return 0;
1686
1687         /*
1688          * If it is a tag object, see if we use a value that derefs
1689          * the object, and if we do grab the object it refers to.
1690          */
1691         oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1692
1693         /*
1694          * NEEDSWORK: This derefs tag only once, which
1695          * is good to deal with chains of trust, but
1696          * is not consistent with what deref_tag() does
1697          * which peels the onion to the core.
1698          */
1699         return get_object(ref, 1, &obj, &oi_deref, err);
1700 }
1701
1702 /*
1703  * Given a ref, return the value for the atom.  This lazily gets value
1704  * out of the object by calling populate value.
1705  */
1706 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1707                               struct atom_value **v, struct strbuf *err)
1708 {
1709         if (!ref->value) {
1710                 if (populate_value(ref, err))
1711                         return -1;
1712                 fill_missing_values(ref->value);
1713         }
1714         *v = &ref->value[atom];
1715         return 0;
1716 }
1717
1718 /*
1719  * Return 1 if the refname matches one of the patterns, otherwise 0.
1720  * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1721  * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1722  * matches "refs/heads/mas*", too).
1723  */
1724 static int match_pattern(const struct ref_filter *filter, const char *refname)
1725 {
1726         const char **patterns = filter->name_patterns;
1727         unsigned flags = 0;
1728
1729         if (filter->ignore_case)
1730                 flags |= WM_CASEFOLD;
1731
1732         /*
1733          * When no '--format' option is given we need to skip the prefix
1734          * for matching refs of tags and branches.
1735          */
1736         (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1737                skip_prefix(refname, "refs/heads/", &refname) ||
1738                skip_prefix(refname, "refs/remotes/", &refname) ||
1739                skip_prefix(refname, "refs/", &refname));
1740
1741         for (; *patterns; patterns++) {
1742                 if (!wildmatch(*patterns, refname, flags))
1743                         return 1;
1744         }
1745         return 0;
1746 }
1747
1748 /*
1749  * Return 1 if the refname matches one of the patterns, otherwise 0.
1750  * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1751  * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1752  * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1753  */
1754 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1755 {
1756         const char **pattern = filter->name_patterns;
1757         int namelen = strlen(refname);
1758         unsigned flags = WM_PATHNAME;
1759
1760         if (filter->ignore_case)
1761                 flags |= WM_CASEFOLD;
1762
1763         for (; *pattern; pattern++) {
1764                 const char *p = *pattern;
1765                 int plen = strlen(p);
1766
1767                 if ((plen <= namelen) &&
1768                     !strncmp(refname, p, plen) &&
1769                     (refname[plen] == '\0' ||
1770                      refname[plen] == '/' ||
1771                      p[plen-1] == '/'))
1772                         return 1;
1773                 if (!wildmatch(p, refname, flags))
1774                         return 1;
1775         }
1776         return 0;
1777 }
1778
1779 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1780 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1781 {
1782         if (!*filter->name_patterns)
1783                 return 1; /* No pattern always matches */
1784         if (filter->match_as_path)
1785                 return match_name_as_path(filter, refname);
1786         return match_pattern(filter, refname);
1787 }
1788
1789 /*
1790  * Find the longest prefix of pattern we can pass to
1791  * `for_each_fullref_in()`, namely the part of pattern preceding the
1792  * first glob character. (Note that `for_each_fullref_in()` is
1793  * perfectly happy working with a prefix that doesn't end at a
1794  * pathname component boundary.)
1795  */
1796 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1797 {
1798         const char *p;
1799
1800         for (p = pattern; *p && !is_glob_special(*p); p++)
1801                 ;
1802
1803         strbuf_add(out, pattern, p - pattern);
1804 }
1805
1806 /*
1807  * This is the same as for_each_fullref_in(), but it tries to iterate
1808  * only over the patterns we'll care about. Note that it _doesn't_ do a full
1809  * pattern match, so the callback still has to match each ref individually.
1810  */
1811 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1812                                        each_ref_fn cb,
1813                                        void *cb_data,
1814                                        int broken)
1815 {
1816         struct strbuf prefix = STRBUF_INIT;
1817         int ret;
1818
1819         if (!filter->match_as_path) {
1820                 /*
1821                  * in this case, the patterns are applied after
1822                  * prefixes like "refs/heads/" etc. are stripped off,
1823                  * so we have to look at everything:
1824                  */
1825                 return for_each_fullref_in("", cb, cb_data, broken);
1826         }
1827
1828         if (filter->ignore_case) {
1829                 /*
1830                  * we can't handle case-insensitive comparisons,
1831                  * so just return everything and let the caller
1832                  * sort it out.
1833                  */
1834                 return for_each_fullref_in("", cb, cb_data, broken);
1835         }
1836
1837         if (!filter->name_patterns[0]) {
1838                 /* no patterns; we have to look at everything */
1839                 return for_each_fullref_in("", cb, cb_data, broken);
1840         }
1841
1842         if (filter->name_patterns[1]) {
1843                 /*
1844                  * multiple patterns; in theory this could still work as long
1845                  * as the patterns are disjoint. We'd just make multiple calls
1846                  * to for_each_ref(). But if they're not disjoint, we'd end up
1847                  * reporting the same ref multiple times. So let's punt on that
1848                  * for now.
1849                  */
1850                 return for_each_fullref_in("", cb, cb_data, broken);
1851         }
1852
1853         find_longest_prefix(&prefix, filter->name_patterns[0]);
1854
1855         ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1856         strbuf_release(&prefix);
1857         return ret;
1858 }
1859
1860 /*
1861  * Given a ref (sha1, refname), check if the ref belongs to the array
1862  * of sha1s. If the given ref is a tag, check if the given tag points
1863  * at one of the sha1s in the given sha1 array.
1864  * the given sha1_array.
1865  * NEEDSWORK:
1866  * 1. Only a single level of inderection is obtained, we might want to
1867  * change this to account for multiple levels (e.g. annotated tags
1868  * pointing to annotated tags pointing to a commit.)
1869  * 2. As the refs are cached we might know what refname peels to without
1870  * the need to parse the object via parse_object(). peel_ref() might be a
1871  * more efficient alternative to obtain the pointee.
1872  */
1873 static const struct object_id *match_points_at(struct oid_array *points_at,
1874                                                const struct object_id *oid,
1875                                                const char *refname)
1876 {
1877         const struct object_id *tagged_oid = NULL;
1878         struct object *obj;
1879
1880         if (oid_array_lookup(points_at, oid) >= 0)
1881                 return oid;
1882         obj = parse_object(the_repository, oid);
1883         if (!obj)
1884                 die(_("malformed object at '%s'"), refname);
1885         if (obj->type == OBJ_TAG)
1886                 tagged_oid = &((struct tag *)obj)->tagged->oid;
1887         if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1888                 return tagged_oid;
1889         return NULL;
1890 }
1891
1892 /*
1893  * Allocate space for a new ref_array_item and copy the name and oid to it.
1894  *
1895  * Callers can then fill in other struct members at their leisure.
1896  */
1897 static struct ref_array_item *new_ref_array_item(const char *refname,
1898                                                  const struct object_id *oid)
1899 {
1900         struct ref_array_item *ref;
1901
1902         FLEX_ALLOC_STR(ref, refname, refname);
1903         oidcpy(&ref->objectname, oid);
1904
1905         return ref;
1906 }
1907
1908 struct ref_array_item *ref_array_push(struct ref_array *array,
1909                                       const char *refname,
1910                                       const struct object_id *oid)
1911 {
1912         struct ref_array_item *ref = new_ref_array_item(refname, oid);
1913
1914         ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1915         array->items[array->nr++] = ref;
1916
1917         return ref;
1918 }
1919
1920 static int ref_kind_from_refname(const char *refname)
1921 {
1922         unsigned int i;
1923
1924         static struct {
1925                 const char *prefix;
1926                 unsigned int kind;
1927         } ref_kind[] = {
1928                 { "refs/heads/" , FILTER_REFS_BRANCHES },
1929                 { "refs/remotes/" , FILTER_REFS_REMOTES },
1930                 { "refs/tags/", FILTER_REFS_TAGS}
1931         };
1932
1933         if (!strcmp(refname, "HEAD"))
1934                 return FILTER_REFS_DETACHED_HEAD;
1935
1936         for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1937                 if (starts_with(refname, ref_kind[i].prefix))
1938                         return ref_kind[i].kind;
1939         }
1940
1941         return FILTER_REFS_OTHERS;
1942 }
1943
1944 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1945 {
1946         if (filter->kind == FILTER_REFS_BRANCHES ||
1947             filter->kind == FILTER_REFS_REMOTES ||
1948             filter->kind == FILTER_REFS_TAGS)
1949                 return filter->kind;
1950         return ref_kind_from_refname(refname);
1951 }
1952
1953 struct ref_filter_cbdata {
1954         struct ref_array *array;
1955         struct ref_filter *filter;
1956         struct contains_cache contains_cache;
1957         struct contains_cache no_contains_cache;
1958 };
1959
1960 /*
1961  * A call-back given to for_each_ref().  Filter refs and keep them for
1962  * later object processing.
1963  */
1964 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1965 {
1966         struct ref_filter_cbdata *ref_cbdata = cb_data;
1967         struct ref_filter *filter = ref_cbdata->filter;
1968         struct ref_array_item *ref;
1969         struct commit *commit = NULL;
1970         unsigned int kind;
1971
1972         if (flag & REF_BAD_NAME) {
1973                 warning(_("ignoring ref with broken name %s"), refname);
1974                 return 0;
1975         }
1976
1977         if (flag & REF_ISBROKEN) {
1978                 warning(_("ignoring broken ref %s"), refname);
1979                 return 0;
1980         }
1981
1982         /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1983         kind = filter_ref_kind(filter, refname);
1984         if (!(kind & filter->kind))
1985                 return 0;
1986
1987         if (!filter_pattern_match(filter, refname))
1988                 return 0;
1989
1990         if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1991                 return 0;
1992
1993         /*
1994          * A merge filter is applied on refs pointing to commits. Hence
1995          * obtain the commit using the 'oid' available and discard all
1996          * non-commits early. The actual filtering is done later.
1997          */
1998         if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1999                 commit = lookup_commit_reference_gently(the_repository, oid,
2000                                                         1);
2001                 if (!commit)
2002                         return 0;
2003                 /* We perform the filtering for the '--contains' option... */
2004                 if (filter->with_commit &&
2005                     !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2006                         return 0;
2007                 /* ...or for the `--no-contains' option */
2008                 if (filter->no_commit &&
2009                     commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2010                         return 0;
2011         }
2012
2013         /*
2014          * We do not open the object yet; sort may only need refname
2015          * to do its job and the resulting list may yet to be pruned
2016          * by maxcount logic.
2017          */
2018         ref = ref_array_push(ref_cbdata->array, refname, oid);
2019         ref->commit = commit;
2020         ref->flag = flag;
2021         ref->kind = kind;
2022
2023         return 0;
2024 }
2025
2026 /*  Free memory allocated for a ref_array_item */
2027 static void free_array_item(struct ref_array_item *item)
2028 {
2029         free((char *)item->symref);
2030         if (item->value) {
2031                 free((char *)item->value->s);
2032                 free(item->value);
2033         }
2034         free(item);
2035 }
2036
2037 /* Free all memory allocated for ref_array */
2038 void ref_array_clear(struct ref_array *array)
2039 {
2040         int i;
2041
2042         for (i = 0; i < used_atom_cnt; i++)
2043                 free((char *)used_atom[i].name);
2044         FREE_AND_NULL(used_atom);
2045         used_atom_cnt = 0;
2046         for (i = 0; i < array->nr; i++)
2047                 free_array_item(array->items[i]);
2048         FREE_AND_NULL(array->items);
2049         array->nr = array->alloc = 0;
2050 }
2051
2052 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2053 {
2054         struct rev_info revs;
2055         int i, old_nr;
2056         struct ref_filter *filter = ref_cbdata->filter;
2057         struct ref_array *array = ref_cbdata->array;
2058         struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2059
2060         repo_init_revisions(the_repository, &revs, NULL);
2061
2062         for (i = 0; i < array->nr; i++) {
2063                 struct ref_array_item *item = array->items[i];
2064                 add_pending_object(&revs, &item->commit->object, item->refname);
2065                 to_clear[i] = item->commit;
2066         }
2067
2068         filter->merge_commit->object.flags |= UNINTERESTING;
2069         add_pending_object(&revs, &filter->merge_commit->object, "");
2070
2071         revs.limited = 1;
2072         if (prepare_revision_walk(&revs))
2073                 die(_("revision walk setup failed"));
2074
2075         old_nr = array->nr;
2076         array->nr = 0;
2077
2078         for (i = 0; i < old_nr; i++) {
2079                 struct ref_array_item *item = array->items[i];
2080                 struct commit *commit = item->commit;
2081
2082                 int is_merged = !!(commit->object.flags & UNINTERESTING);
2083
2084                 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2085                         array->items[array->nr++] = array->items[i];
2086                 else
2087                         free_array_item(item);
2088         }
2089
2090         clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2091         clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2092         free(to_clear);
2093 }
2094
2095 /*
2096  * API for filtering a set of refs. Based on the type of refs the user
2097  * has requested, we iterate through those refs and apply filters
2098  * as per the given ref_filter structure and finally store the
2099  * filtered refs in the ref_array structure.
2100  */
2101 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2102 {
2103         struct ref_filter_cbdata ref_cbdata;
2104         int ret = 0;
2105         unsigned int broken = 0;
2106
2107         ref_cbdata.array = array;
2108         ref_cbdata.filter = filter;
2109
2110         if (type & FILTER_REFS_INCLUDE_BROKEN)
2111                 broken = 1;
2112         filter->kind = type & FILTER_REFS_KIND_MASK;
2113
2114         init_contains_cache(&ref_cbdata.contains_cache);
2115         init_contains_cache(&ref_cbdata.no_contains_cache);
2116
2117         /*  Simple per-ref filtering */
2118         if (!filter->kind)
2119                 die("filter_refs: invalid type");
2120         else {
2121                 /*
2122                  * For common cases where we need only branches or remotes or tags,
2123                  * we only iterate through those refs. If a mix of refs is needed,
2124                  * we iterate over all refs and filter out required refs with the help
2125                  * of filter_ref_kind().
2126                  */
2127                 if (filter->kind == FILTER_REFS_BRANCHES)
2128                         ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2129                 else if (filter->kind == FILTER_REFS_REMOTES)
2130                         ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2131                 else if (filter->kind == FILTER_REFS_TAGS)
2132                         ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2133                 else if (filter->kind & FILTER_REFS_ALL)
2134                         ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2135                 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2136                         head_ref(ref_filter_handler, &ref_cbdata);
2137         }
2138
2139         clear_contains_cache(&ref_cbdata.contains_cache);
2140         clear_contains_cache(&ref_cbdata.no_contains_cache);
2141
2142         /*  Filters that need revision walking */
2143         if (filter->merge_commit)
2144                 do_merge_filter(&ref_cbdata);
2145
2146         return ret;
2147 }
2148
2149 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2150 {
2151         struct atom_value *va, *vb;
2152         int cmp;
2153         cmp_type cmp_type = used_atom[s->atom].type;
2154         int (*cmp_fn)(const char *, const char *);
2155         struct strbuf err = STRBUF_INIT;
2156
2157         if (get_ref_atom_value(a, s->atom, &va, &err))
2158                 die("%s", err.buf);
2159         if (get_ref_atom_value(b, s->atom, &vb, &err))
2160                 die("%s", err.buf);
2161         strbuf_release(&err);
2162         cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2163         if (s->version)
2164                 cmp = versioncmp(va->s, vb->s);
2165         else if (cmp_type == FIELD_STR)
2166                 cmp = cmp_fn(va->s, vb->s);
2167         else {
2168                 if (va->value < vb->value)
2169                         cmp = -1;
2170                 else if (va->value == vb->value)
2171                         cmp = cmp_fn(a->refname, b->refname);
2172                 else
2173                         cmp = 1;
2174         }
2175
2176         return (s->reverse) ? -cmp : cmp;
2177 }
2178
2179 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2180 {
2181         struct ref_array_item *a = *((struct ref_array_item **)a_);
2182         struct ref_array_item *b = *((struct ref_array_item **)b_);
2183         struct ref_sorting *s;
2184
2185         for (s = ref_sorting; s; s = s->next) {
2186                 int cmp = cmp_ref_sorting(s, a, b);
2187                 if (cmp)
2188                         return cmp;
2189         }
2190         return 0;
2191 }
2192
2193 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2194 {
2195         QSORT_S(array->items, array->nr, compare_refs, sorting);
2196 }
2197
2198 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2199 {
2200         struct strbuf *s = &state->stack->output;
2201
2202         while (*cp && (!ep || cp < ep)) {
2203                 if (*cp == '%') {
2204                         if (cp[1] == '%')
2205                                 cp++;
2206                         else {
2207                                 int ch = hex2chr(cp + 1);
2208                                 if (0 <= ch) {
2209                                         strbuf_addch(s, ch);
2210                                         cp += 3;
2211                                         continue;
2212                                 }
2213                         }
2214                 }
2215                 strbuf_addch(s, *cp);
2216                 cp++;
2217         }
2218 }
2219
2220 int format_ref_array_item(struct ref_array_item *info,
2221                            const struct ref_format *format,
2222                            struct strbuf *final_buf,
2223                            struct strbuf *error_buf)
2224 {
2225         const char *cp, *sp, *ep;
2226         struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2227
2228         state.quote_style = format->quote_style;
2229         push_stack_element(&state.stack);
2230
2231         for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2232                 struct atom_value *atomv;
2233                 int pos;
2234
2235                 ep = strchr(sp, ')');
2236                 if (cp < sp)
2237                         append_literal(cp, sp, &state);
2238                 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2239                 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2240                     atomv->handler(atomv, &state, error_buf)) {
2241                         pop_stack_element(&state.stack);
2242                         return -1;
2243                 }
2244         }
2245         if (*cp) {
2246                 sp = cp + strlen(cp);
2247                 append_literal(cp, sp, &state);
2248         }
2249         if (format->need_color_reset_at_eol) {
2250                 struct atom_value resetv;
2251                 resetv.s = GIT_COLOR_RESET;
2252                 if (append_atom(&resetv, &state, error_buf)) {
2253                         pop_stack_element(&state.stack);
2254                         return -1;
2255                 }
2256         }
2257         if (state.stack->prev) {
2258                 pop_stack_element(&state.stack);
2259                 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2260         }
2261         strbuf_addbuf(final_buf, &state.stack->output);
2262         pop_stack_element(&state.stack);
2263         return 0;
2264 }
2265
2266 void show_ref_array_item(struct ref_array_item *info,
2267                          const struct ref_format *format)
2268 {
2269         struct strbuf final_buf = STRBUF_INIT;
2270         struct strbuf error_buf = STRBUF_INIT;
2271
2272         if (format_ref_array_item(info, format, &final_buf, &error_buf))
2273                 die("%s", error_buf.buf);
2274         fwrite(final_buf.buf, 1, final_buf.len, stdout);
2275         strbuf_release(&error_buf);
2276         strbuf_release(&final_buf);
2277         putchar('\n');
2278 }
2279
2280 void pretty_print_ref(const char *name, const struct object_id *oid,
2281                       const struct ref_format *format)
2282 {
2283         struct ref_array_item *ref_item;
2284         ref_item = new_ref_array_item(name, oid);
2285         ref_item->kind = ref_kind_from_refname(name);
2286         show_ref_array_item(ref_item, format);
2287         free_array_item(ref_item);
2288 }
2289
2290 static int parse_sorting_atom(const char *atom)
2291 {
2292         /*
2293          * This parses an atom using a dummy ref_format, since we don't
2294          * actually care about the formatting details.
2295          */
2296         struct ref_format dummy = REF_FORMAT_INIT;
2297         const char *end = atom + strlen(atom);
2298         struct strbuf err = STRBUF_INIT;
2299         int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2300         if (res < 0)
2301                 die("%s", err.buf);
2302         strbuf_release(&err);
2303         return res;
2304 }
2305
2306 /*  If no sorting option is given, use refname to sort as default */
2307 struct ref_sorting *ref_default_sorting(void)
2308 {
2309         static const char cstr_name[] = "refname";
2310
2311         struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2312
2313         sorting->next = NULL;
2314         sorting->atom = parse_sorting_atom(cstr_name);
2315         return sorting;
2316 }
2317
2318 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2319 {
2320         struct ref_sorting *s;
2321
2322         s = xcalloc(1, sizeof(*s));
2323         s->next = *sorting_tail;
2324         *sorting_tail = s;
2325
2326         if (*arg == '-') {
2327                 s->reverse = 1;
2328                 arg++;
2329         }
2330         if (skip_prefix(arg, "version:", &arg) ||
2331             skip_prefix(arg, "v:", &arg))
2332                 s->version = 1;
2333         s->atom = parse_sorting_atom(arg);
2334 }
2335
2336 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2337 {
2338         if (!arg) /* should --no-sort void the list ? */
2339                 return -1;
2340         parse_ref_sorting(opt->value, arg);
2341         return 0;
2342 }
2343
2344 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2345 {
2346         struct ref_filter *rf = opt->value;
2347         struct object_id oid;
2348         int no_merged = starts_with(opt->long_name, "no");
2349
2350         BUG_ON_OPT_NEG(unset);
2351
2352         if (rf->merge) {
2353                 if (no_merged) {
2354                         return error(_("option `%s' is incompatible with --merged"),
2355                                      opt->long_name);
2356                 } else {
2357                         return error(_("option `%s' is incompatible with --no-merged"),
2358                                      opt->long_name);
2359                 }
2360         }
2361
2362         rf->merge = no_merged
2363                 ? REF_FILTER_MERGED_OMIT
2364                 : REF_FILTER_MERGED_INCLUDE;
2365
2366         if (get_oid(arg, &oid))
2367                 die(_("malformed object name %s"), arg);
2368
2369         rf->merge_commit = lookup_commit_reference_gently(the_repository,
2370                                                           &oid, 0);
2371         if (!rf->merge_commit)
2372                 return error(_("option `%s' must point to a commit"), opt->long_name);
2373
2374         return 0;
2375 }