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