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