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