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