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