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