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