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