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