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