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