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