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