cache.h: remove expand_user_path()
[alt-git.git] / ref-filter.c
blob9a830bedef0f8eedfcc1caaf7aa8d44b0caa1a8a
1 #include "cache.h"
2 #include "alloc.h"
3 #include "gettext.h"
4 #include "hex.h"
5 #include "parse-options.h"
6 #include "refs.h"
7 #include "wildmatch.h"
8 #include "object-store.h"
9 #include "repository.h"
10 #include "commit.h"
11 #include "remote.h"
12 #include "color.h"
13 #include "tag.h"
14 #include "quote.h"
15 #include "ref-filter.h"
16 #include "revision.h"
17 #include "utf8.h"
18 #include "version.h"
19 #include "trailer.h"
20 #include "wt-status.h"
21 #include "commit-slab.h"
22 #include "commit-graph.h"
23 #include "commit-reach.h"
24 #include "worktree.h"
25 #include "hashmap.h"
26 #include "strvec.h"
28 static struct ref_msg {
29 const char *gone;
30 const char *ahead;
31 const char *behind;
32 const char *ahead_behind;
33 } msgs = {
34 /* Untranslated plumbing messages: */
35 "gone",
36 "ahead %d",
37 "behind %d",
38 "ahead %d, behind %d"
41 void setup_ref_filter_porcelain_msg(void)
43 msgs.gone = _("gone");
44 msgs.ahead = _("ahead %d");
45 msgs.behind = _("behind %d");
46 msgs.ahead_behind = _("ahead %d, behind %d");
49 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
50 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
51 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
53 struct align {
54 align_type position;
55 unsigned int width;
58 struct if_then_else {
59 cmp_status cmp_status;
60 const char *str;
61 unsigned int then_atom_seen : 1,
62 else_atom_seen : 1,
63 condition_satisfied : 1;
66 struct refname_atom {
67 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
68 int lstrip, rstrip;
71 static struct ref_trailer_buf {
72 struct string_list filter_list;
73 struct strbuf sepbuf;
74 struct strbuf kvsepbuf;
75 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
77 static struct expand_data {
78 struct object_id oid;
79 enum object_type type;
80 unsigned long size;
81 off_t disk_size;
82 struct object_id delta_base_oid;
83 void *content;
85 struct object_info info;
86 } oi, oi_deref;
88 struct ref_to_worktree_entry {
89 struct hashmap_entry ent;
90 struct worktree *wt; /* key is wt->head_ref */
93 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
94 const struct hashmap_entry *eptr,
95 const struct hashmap_entry *kptr,
96 const void *keydata_aka_refname)
98 const struct ref_to_worktree_entry *e, *k;
100 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
101 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
103 return strcmp(e->wt->head_ref,
104 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
107 static struct ref_to_worktree_map {
108 struct hashmap map;
109 struct worktree **worktrees;
110 } ref_to_worktree_map;
113 * The enum atom_type is used as the index of valid_atom array.
114 * In the atom parsing stage, it will be passed to used_atom.atom_type
115 * as the identifier of the atom type. We can check the type of used_atom
116 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
118 enum atom_type {
119 ATOM_REFNAME,
120 ATOM_OBJECTTYPE,
121 ATOM_OBJECTSIZE,
122 ATOM_OBJECTNAME,
123 ATOM_DELTABASE,
124 ATOM_TREE,
125 ATOM_PARENT,
126 ATOM_NUMPARENT,
127 ATOM_OBJECT,
128 ATOM_TYPE,
129 ATOM_TAG,
130 ATOM_AUTHOR,
131 ATOM_AUTHORNAME,
132 ATOM_AUTHOREMAIL,
133 ATOM_AUTHORDATE,
134 ATOM_COMMITTER,
135 ATOM_COMMITTERNAME,
136 ATOM_COMMITTEREMAIL,
137 ATOM_COMMITTERDATE,
138 ATOM_TAGGER,
139 ATOM_TAGGERNAME,
140 ATOM_TAGGEREMAIL,
141 ATOM_TAGGERDATE,
142 ATOM_CREATOR,
143 ATOM_CREATORDATE,
144 ATOM_SUBJECT,
145 ATOM_BODY,
146 ATOM_TRAILERS,
147 ATOM_CONTENTS,
148 ATOM_RAW,
149 ATOM_UPSTREAM,
150 ATOM_PUSH,
151 ATOM_SYMREF,
152 ATOM_FLAG,
153 ATOM_HEAD,
154 ATOM_COLOR,
155 ATOM_WORKTREEPATH,
156 ATOM_ALIGN,
157 ATOM_END,
158 ATOM_IF,
159 ATOM_THEN,
160 ATOM_ELSE,
161 ATOM_REST,
165 * An atom is a valid field atom listed below, possibly prefixed with
166 * a "*" to denote deref_tag().
168 * We parse given format string and sort specifiers, and make a list
169 * of properties that we need to extract out of objects. ref_array_item
170 * structure will hold an array of values extracted that can be
171 * indexed with the "atom number", which is an index into this
172 * array.
174 static struct used_atom {
175 enum atom_type atom_type;
176 const char *name;
177 cmp_type type;
178 info_source source;
179 union {
180 char color[COLOR_MAXLEN];
181 struct align align;
182 struct {
183 enum {
184 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
185 } option;
186 struct refname_atom refname;
187 unsigned int nobracket : 1, push : 1, push_remote : 1;
188 } remote_ref;
189 struct {
190 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
191 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
192 struct process_trailer_options trailer_opts;
193 unsigned int nlines;
194 } contents;
195 struct {
196 enum { RAW_BARE, RAW_LENGTH } option;
197 } raw_data;
198 struct {
199 cmp_status cmp_status;
200 const char *str;
201 } if_then_else;
202 struct {
203 enum { O_FULL, O_LENGTH, O_SHORT } option;
204 unsigned int length;
205 } oid;
206 struct {
207 enum { O_SIZE, O_SIZE_DISK } option;
208 } objectsize;
209 struct email_option {
210 enum { EO_RAW, EO_TRIM, EO_LOCALPART } option;
211 } email_option;
212 struct refname_atom refname;
213 char *head;
214 } u;
215 } *used_atom;
216 static int used_atom_cnt, need_tagged, need_symref;
219 * Expand string, append it to strbuf *sb, then return error code ret.
220 * Allow to save few lines of code.
222 __attribute__((format (printf, 3, 4)))
223 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
225 va_list ap;
226 va_start(ap, fmt);
227 strbuf_vaddf(sb, fmt, ap);
228 va_end(ap);
229 return ret;
232 static int err_no_arg(struct strbuf *sb, const char *name)
234 size_t namelen = strchrnul(name, ':') - name;
235 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
236 (int)namelen, name);
237 return -1;
240 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
242 size_t namelen = strchrnul(name, ':') - name;
243 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
244 (int)namelen, name, arg);
245 return -1;
248 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
249 const char *color_value, struct strbuf *err)
251 if (!color_value)
252 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
253 if (color_parse(color_value, atom->u.color) < 0)
254 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
255 color_value);
257 * We check this after we've parsed the color, which lets us complain
258 * about syntactically bogus color names even if they won't be used.
260 if (!want_color(format->use_color))
261 color_parse("", atom->u.color);
262 return 0;
265 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
266 const char *name, struct strbuf *err)
268 if (!arg)
269 atom->option = R_NORMAL;
270 else if (!strcmp(arg, "short"))
271 atom->option = R_SHORT;
272 else if (skip_prefix(arg, "lstrip=", &arg) ||
273 skip_prefix(arg, "strip=", &arg)) {
274 atom->option = R_LSTRIP;
275 if (strtol_i(arg, 10, &atom->lstrip))
276 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
277 } else if (skip_prefix(arg, "rstrip=", &arg)) {
278 atom->option = R_RSTRIP;
279 if (strtol_i(arg, 10, &atom->rstrip))
280 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
281 } else
282 return err_bad_arg(err, name, arg);
283 return 0;
286 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
287 struct used_atom *atom,
288 const char *arg, struct strbuf *err)
290 struct string_list params = STRING_LIST_INIT_DUP;
291 int i;
293 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
294 atom->u.remote_ref.push = 1;
296 if (!arg) {
297 atom->u.remote_ref.option = RR_REF;
298 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
299 arg, atom->name, err);
302 atom->u.remote_ref.nobracket = 0;
303 string_list_split(&params, arg, ',', -1);
305 for (i = 0; i < params.nr; i++) {
306 const char *s = params.items[i].string;
308 if (!strcmp(s, "track"))
309 atom->u.remote_ref.option = RR_TRACK;
310 else if (!strcmp(s, "trackshort"))
311 atom->u.remote_ref.option = RR_TRACKSHORT;
312 else if (!strcmp(s, "nobracket"))
313 atom->u.remote_ref.nobracket = 1;
314 else if (!strcmp(s, "remotename")) {
315 atom->u.remote_ref.option = RR_REMOTE_NAME;
316 atom->u.remote_ref.push_remote = 1;
317 } else if (!strcmp(s, "remoteref")) {
318 atom->u.remote_ref.option = RR_REMOTE_REF;
319 atom->u.remote_ref.push_remote = 1;
320 } else {
321 atom->u.remote_ref.option = RR_REF;
322 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
323 arg, atom->name, err)) {
324 string_list_clear(&params, 0);
325 return -1;
330 string_list_clear(&params, 0);
331 return 0;
334 static int objecttype_atom_parser(struct ref_format *format UNUSED,
335 struct used_atom *atom,
336 const char *arg, struct strbuf *err)
338 if (arg)
339 return err_no_arg(err, "objecttype");
340 if (*atom->name == '*')
341 oi_deref.info.typep = &oi_deref.type;
342 else
343 oi.info.typep = &oi.type;
344 return 0;
347 static int objectsize_atom_parser(struct ref_format *format UNUSED,
348 struct used_atom *atom,
349 const char *arg, struct strbuf *err)
351 if (!arg) {
352 atom->u.objectsize.option = O_SIZE;
353 if (*atom->name == '*')
354 oi_deref.info.sizep = &oi_deref.size;
355 else
356 oi.info.sizep = &oi.size;
357 } else if (!strcmp(arg, "disk")) {
358 atom->u.objectsize.option = O_SIZE_DISK;
359 if (*atom->name == '*')
360 oi_deref.info.disk_sizep = &oi_deref.disk_size;
361 else
362 oi.info.disk_sizep = &oi.disk_size;
363 } else
364 return err_bad_arg(err, "objectsize", arg);
365 return 0;
368 static int deltabase_atom_parser(struct ref_format *format UNUSED,
369 struct used_atom *atom,
370 const char *arg, struct strbuf *err)
372 if (arg)
373 return err_no_arg(err, "deltabase");
374 if (*atom->name == '*')
375 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
376 else
377 oi.info.delta_base_oid = &oi.delta_base_oid;
378 return 0;
381 static int body_atom_parser(struct ref_format *format UNUSED,
382 struct used_atom *atom,
383 const char *arg, struct strbuf *err)
385 if (arg)
386 return err_no_arg(err, "body");
387 atom->u.contents.option = C_BODY_DEP;
388 return 0;
391 static int subject_atom_parser(struct ref_format *format UNUSED,
392 struct used_atom *atom,
393 const char *arg, struct strbuf *err)
395 if (!arg)
396 atom->u.contents.option = C_SUB;
397 else if (!strcmp(arg, "sanitize"))
398 atom->u.contents.option = C_SUB_SANITIZE;
399 else
400 return err_bad_arg(err, "subject", arg);
401 return 0;
404 static int trailers_atom_parser(struct ref_format *format UNUSED,
405 struct used_atom *atom,
406 const char *arg, struct strbuf *err)
408 atom->u.contents.trailer_opts.no_divider = 1;
410 if (arg) {
411 const char *argbuf = xstrfmt("%s)", arg);
412 char *invalid_arg = NULL;
414 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
415 &ref_trailer_buf.filter_list,
416 &ref_trailer_buf.sepbuf,
417 &ref_trailer_buf.kvsepbuf,
418 &argbuf, &invalid_arg)) {
419 if (!invalid_arg)
420 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
421 else
422 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
423 free((char *)invalid_arg);
424 return -1;
427 atom->u.contents.option = C_TRAILERS;
428 return 0;
431 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
432 const char *arg, struct strbuf *err)
434 if (!arg)
435 atom->u.contents.option = C_BARE;
436 else if (!strcmp(arg, "body"))
437 atom->u.contents.option = C_BODY;
438 else if (!strcmp(arg, "size"))
439 atom->u.contents.option = C_LENGTH;
440 else if (!strcmp(arg, "signature"))
441 atom->u.contents.option = C_SIG;
442 else if (!strcmp(arg, "subject"))
443 atom->u.contents.option = C_SUB;
444 else if (!strcmp(arg, "trailers")) {
445 if (trailers_atom_parser(format, atom, NULL, err))
446 return -1;
447 } else if (skip_prefix(arg, "trailers:", &arg)) {
448 if (trailers_atom_parser(format, atom, arg, err))
449 return -1;
450 } else if (skip_prefix(arg, "lines=", &arg)) {
451 atom->u.contents.option = C_LINES;
452 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
453 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
454 } else
455 return err_bad_arg(err, "contents", arg);
456 return 0;
459 static int raw_atom_parser(struct ref_format *format UNUSED,
460 struct used_atom *atom,
461 const char *arg, struct strbuf *err)
463 if (!arg)
464 atom->u.raw_data.option = RAW_BARE;
465 else if (!strcmp(arg, "size"))
466 atom->u.raw_data.option = RAW_LENGTH;
467 else
468 return err_bad_arg(err, "raw", arg);
469 return 0;
472 static int oid_atom_parser(struct ref_format *format UNUSED,
473 struct used_atom *atom,
474 const char *arg, struct strbuf *err)
476 if (!arg)
477 atom->u.oid.option = O_FULL;
478 else if (!strcmp(arg, "short"))
479 atom->u.oid.option = O_SHORT;
480 else if (skip_prefix(arg, "short=", &arg)) {
481 atom->u.oid.option = O_LENGTH;
482 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
483 atom->u.oid.length == 0)
484 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
485 if (atom->u.oid.length < MINIMUM_ABBREV)
486 atom->u.oid.length = MINIMUM_ABBREV;
487 } else
488 return err_bad_arg(err, atom->name, arg);
489 return 0;
492 static int person_email_atom_parser(struct ref_format *format UNUSED,
493 struct used_atom *atom,
494 const char *arg, struct strbuf *err)
496 if (!arg)
497 atom->u.email_option.option = EO_RAW;
498 else if (!strcmp(arg, "trim"))
499 atom->u.email_option.option = EO_TRIM;
500 else if (!strcmp(arg, "localpart"))
501 atom->u.email_option.option = EO_LOCALPART;
502 else
503 return err_bad_arg(err, atom->name, arg);
504 return 0;
507 static int refname_atom_parser(struct ref_format *format UNUSED,
508 struct used_atom *atom,
509 const char *arg, struct strbuf *err)
511 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
514 static align_type parse_align_position(const char *s)
516 if (!strcmp(s, "right"))
517 return ALIGN_RIGHT;
518 else if (!strcmp(s, "middle"))
519 return ALIGN_MIDDLE;
520 else if (!strcmp(s, "left"))
521 return ALIGN_LEFT;
522 return -1;
525 static int align_atom_parser(struct ref_format *format UNUSED,
526 struct used_atom *atom,
527 const char *arg, struct strbuf *err)
529 struct align *align = &atom->u.align;
530 struct string_list params = STRING_LIST_INIT_DUP;
531 int i;
532 unsigned int width = ~0U;
534 if (!arg)
535 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
537 align->position = ALIGN_LEFT;
539 string_list_split(&params, arg, ',', -1);
540 for (i = 0; i < params.nr; i++) {
541 const char *s = params.items[i].string;
542 int position;
544 if (skip_prefix(s, "position=", &s)) {
545 position = parse_align_position(s);
546 if (position < 0) {
547 strbuf_addf(err, _("unrecognized position:%s"), s);
548 string_list_clear(&params, 0);
549 return -1;
551 align->position = position;
552 } else if (skip_prefix(s, "width=", &s)) {
553 if (strtoul_ui(s, 10, &width)) {
554 strbuf_addf(err, _("unrecognized width:%s"), s);
555 string_list_clear(&params, 0);
556 return -1;
558 } else if (!strtoul_ui(s, 10, &width))
560 else if ((position = parse_align_position(s)) >= 0)
561 align->position = position;
562 else {
563 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
564 string_list_clear(&params, 0);
565 return -1;
569 if (width == ~0U) {
570 string_list_clear(&params, 0);
571 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
573 align->width = width;
574 string_list_clear(&params, 0);
575 return 0;
578 static int if_atom_parser(struct ref_format *format UNUSED,
579 struct used_atom *atom,
580 const char *arg, struct strbuf *err)
582 if (!arg) {
583 atom->u.if_then_else.cmp_status = COMPARE_NONE;
584 return 0;
585 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
586 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
587 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
588 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
589 } else
590 return err_bad_arg(err, "if", arg);
591 return 0;
594 static int rest_atom_parser(struct ref_format *format,
595 struct used_atom *atom UNUSED,
596 const char *arg, struct strbuf *err)
598 if (arg)
599 return err_no_arg(err, "rest");
600 format->use_rest = 1;
601 return 0;
604 static int head_atom_parser(struct ref_format *format UNUSED,
605 struct used_atom *atom,
606 const char *arg, struct strbuf *err)
608 if (arg)
609 return err_no_arg(err, "HEAD");
610 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
611 return 0;
614 static struct {
615 const char *name;
616 info_source source;
617 cmp_type cmp_type;
618 int (*parser)(struct ref_format *format, struct used_atom *atom,
619 const char *arg, struct strbuf *err);
620 } valid_atom[] = {
621 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
622 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
623 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
624 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
625 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
626 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
627 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
628 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
629 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
630 [ATOM_TYPE] = { "type", SOURCE_OBJ },
631 [ATOM_TAG] = { "tag", SOURCE_OBJ },
632 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
633 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
634 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
635 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
636 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
637 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
638 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
639 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
640 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
641 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
642 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
643 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
644 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
645 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
646 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
647 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
648 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
649 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
650 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
651 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
652 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
653 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
654 [ATOM_FLAG] = { "flag", SOURCE_NONE },
655 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
656 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
657 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
658 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
659 [ATOM_END] = { "end", SOURCE_NONE },
660 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
661 [ATOM_THEN] = { "then", SOURCE_NONE },
662 [ATOM_ELSE] = { "else", SOURCE_NONE },
663 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
665 * Please update $__git_ref_fieldlist in git-completion.bash
666 * when you add new atoms
670 #define REF_FORMATTING_STATE_INIT { 0 }
672 struct ref_formatting_stack {
673 struct ref_formatting_stack *prev;
674 struct strbuf output;
675 void (*at_end)(struct ref_formatting_stack **stack);
676 void *at_end_data;
679 struct ref_formatting_state {
680 int quote_style;
681 struct ref_formatting_stack *stack;
684 struct atom_value {
685 const char *s;
686 ssize_t s_size;
687 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
688 struct strbuf *err);
689 uintmax_t value; /* used for sorting when not FIELD_STR */
690 struct used_atom *atom;
693 #define ATOM_SIZE_UNSPECIFIED (-1)
695 #define ATOM_VALUE_INIT { \
696 .s_size = ATOM_SIZE_UNSPECIFIED \
700 * Used to parse format string and sort specifiers
702 static int parse_ref_filter_atom(struct ref_format *format,
703 const char *atom, const char *ep,
704 struct strbuf *err)
706 const char *sp;
707 const char *arg;
708 int i, at, atom_len;
710 sp = atom;
711 if (*sp == '*' && sp < ep)
712 sp++; /* deref */
713 if (ep <= sp)
714 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
715 (int)(ep-atom), atom);
718 * If the atom name has a colon, strip it and everything after
719 * it off - it specifies the format for this entry, and
720 * shouldn't be used for checking against the valid_atom
721 * table.
723 arg = memchr(sp, ':', ep - sp);
724 atom_len = (arg ? arg : ep) - sp;
726 /* Do we have the atom already used elsewhere? */
727 for (i = 0; i < used_atom_cnt; i++) {
728 int len = strlen(used_atom[i].name);
729 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
730 return i;
733 /* Is the atom a valid one? */
734 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
735 int len = strlen(valid_atom[i].name);
736 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
737 break;
740 if (ARRAY_SIZE(valid_atom) <= i)
741 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
742 (int)(ep-atom), atom);
743 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
744 return strbuf_addf_ret(err, -1,
745 _("not a git repository, but the field '%.*s' requires access to object data"),
746 (int)(ep-atom), atom);
748 /* Add it in, including the deref prefix */
749 at = used_atom_cnt;
750 used_atom_cnt++;
751 REALLOC_ARRAY(used_atom, used_atom_cnt);
752 used_atom[at].atom_type = i;
753 used_atom[at].name = xmemdupz(atom, ep - atom);
754 used_atom[at].type = valid_atom[i].cmp_type;
755 used_atom[at].source = valid_atom[i].source;
756 if (used_atom[at].source == SOURCE_OBJ) {
757 if (*atom == '*')
758 oi_deref.info.contentp = &oi_deref.content;
759 else
760 oi.info.contentp = &oi.content;
762 if (arg) {
763 arg = used_atom[at].name + (arg - atom) + 1;
764 if (!*arg) {
766 * Treat empty sub-arguments list as NULL (i.e.,
767 * "%(atom:)" is equivalent to "%(atom)").
769 arg = NULL;
772 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
773 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
774 return -1;
775 if (*atom == '*')
776 need_tagged = 1;
777 if (i == ATOM_SYMREF)
778 need_symref = 1;
779 return at;
782 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
784 switch (quote_style) {
785 case QUOTE_NONE:
786 if (len < 0)
787 strbuf_addstr(s, str);
788 else
789 strbuf_add(s, str, len);
790 break;
791 case QUOTE_SHELL:
792 sq_quote_buf(s, str);
793 break;
794 case QUOTE_PERL:
795 if (len < 0)
796 perl_quote_buf(s, str);
797 else
798 perl_quote_buf_with_len(s, str, len);
799 break;
800 case QUOTE_PYTHON:
801 python_quote_buf(s, str);
802 break;
803 case QUOTE_TCL:
804 tcl_quote_buf(s, str);
805 break;
809 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
810 struct strbuf *err UNUSED)
813 * Quote formatting is only done when the stack has a single
814 * element. Otherwise quote formatting is done on the
815 * element's entire output strbuf when the %(end) atom is
816 * encountered.
818 if (!state->stack->prev)
819 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
820 else if (v->s_size < 0)
821 strbuf_addstr(&state->stack->output, v->s);
822 else
823 strbuf_add(&state->stack->output, v->s, v->s_size);
824 return 0;
827 static void push_stack_element(struct ref_formatting_stack **stack)
829 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
831 strbuf_init(&s->output, 0);
832 s->prev = *stack;
833 *stack = s;
836 static void pop_stack_element(struct ref_formatting_stack **stack)
838 struct ref_formatting_stack *current = *stack;
839 struct ref_formatting_stack *prev = current->prev;
841 if (prev)
842 strbuf_addbuf(&prev->output, &current->output);
843 strbuf_release(&current->output);
844 free(current);
845 *stack = prev;
848 static void end_align_handler(struct ref_formatting_stack **stack)
850 struct ref_formatting_stack *cur = *stack;
851 struct align *align = (struct align *)cur->at_end_data;
852 struct strbuf s = STRBUF_INIT;
854 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
855 strbuf_swap(&cur->output, &s);
856 strbuf_release(&s);
859 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
860 struct strbuf *err UNUSED)
862 struct ref_formatting_stack *new_stack;
864 push_stack_element(&state->stack);
865 new_stack = state->stack;
866 new_stack->at_end = end_align_handler;
867 new_stack->at_end_data = &atomv->atom->u.align;
868 return 0;
871 static void if_then_else_handler(struct ref_formatting_stack **stack)
873 struct ref_formatting_stack *cur = *stack;
874 struct ref_formatting_stack *prev = cur->prev;
875 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
877 if (!if_then_else->then_atom_seen)
878 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
880 if (if_then_else->else_atom_seen) {
882 * There is an %(else) atom: we need to drop one state from the
883 * stack, either the %(else) branch if the condition is satisfied, or
884 * the %(then) branch if it isn't.
886 if (if_then_else->condition_satisfied) {
887 strbuf_reset(&cur->output);
888 pop_stack_element(&cur);
889 } else {
890 strbuf_swap(&cur->output, &prev->output);
891 strbuf_reset(&cur->output);
892 pop_stack_element(&cur);
894 } else if (!if_then_else->condition_satisfied) {
896 * No %(else) atom: just drop the %(then) branch if the
897 * condition is not satisfied.
899 strbuf_reset(&cur->output);
902 *stack = cur;
903 free(if_then_else);
906 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
907 struct strbuf *err UNUSED)
909 struct ref_formatting_stack *new_stack;
910 struct if_then_else *if_then_else = xcalloc(1,
911 sizeof(struct if_then_else));
913 if_then_else->str = atomv->atom->u.if_then_else.str;
914 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
916 push_stack_element(&state->stack);
917 new_stack = state->stack;
918 new_stack->at_end = if_then_else_handler;
919 new_stack->at_end_data = if_then_else;
920 return 0;
923 static int is_empty(struct strbuf *buf)
925 const char *cur = buf->buf;
926 const char *end = buf->buf + buf->len;
928 while (cur != end && (isspace(*cur)))
929 cur++;
931 return cur == end;
934 static int then_atom_handler(struct atom_value *atomv UNUSED,
935 struct ref_formatting_state *state,
936 struct strbuf *err)
938 struct ref_formatting_stack *cur = state->stack;
939 struct if_then_else *if_then_else = NULL;
940 size_t str_len = 0;
942 if (cur->at_end == if_then_else_handler)
943 if_then_else = (struct if_then_else *)cur->at_end_data;
944 if (!if_then_else)
945 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
946 if (if_then_else->then_atom_seen)
947 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
948 if (if_then_else->else_atom_seen)
949 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
950 if_then_else->then_atom_seen = 1;
951 if (if_then_else->str)
952 str_len = strlen(if_then_else->str);
954 * If the 'equals' or 'notequals' attribute is used then
955 * perform the required comparison. If not, only non-empty
956 * strings satisfy the 'if' condition.
958 if (if_then_else->cmp_status == COMPARE_EQUAL) {
959 if (str_len == cur->output.len &&
960 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
961 if_then_else->condition_satisfied = 1;
962 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
963 if (str_len != cur->output.len ||
964 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
965 if_then_else->condition_satisfied = 1;
966 } else if (cur->output.len && !is_empty(&cur->output))
967 if_then_else->condition_satisfied = 1;
968 strbuf_reset(&cur->output);
969 return 0;
972 static int else_atom_handler(struct atom_value *atomv UNUSED,
973 struct ref_formatting_state *state,
974 struct strbuf *err)
976 struct ref_formatting_stack *prev = state->stack;
977 struct if_then_else *if_then_else = NULL;
979 if (prev->at_end == if_then_else_handler)
980 if_then_else = (struct if_then_else *)prev->at_end_data;
981 if (!if_then_else)
982 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
983 if (!if_then_else->then_atom_seen)
984 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
985 if (if_then_else->else_atom_seen)
986 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
987 if_then_else->else_atom_seen = 1;
988 push_stack_element(&state->stack);
989 state->stack->at_end_data = prev->at_end_data;
990 state->stack->at_end = prev->at_end;
991 return 0;
994 static int end_atom_handler(struct atom_value *atomv UNUSED,
995 struct ref_formatting_state *state,
996 struct strbuf *err)
998 struct ref_formatting_stack *current = state->stack;
999 struct strbuf s = STRBUF_INIT;
1001 if (!current->at_end)
1002 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1003 current->at_end(&state->stack);
1005 /* Stack may have been popped within at_end(), hence reset the current pointer */
1006 current = state->stack;
1009 * Perform quote formatting when the stack element is that of
1010 * a supporting atom. If nested then perform quote formatting
1011 * only on the topmost supporting atom.
1013 if (!current->prev->prev) {
1014 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1015 strbuf_swap(&current->output, &s);
1017 strbuf_release(&s);
1018 pop_stack_element(&state->stack);
1019 return 0;
1023 * In a format string, find the next occurrence of %(atom).
1025 static const char *find_next(const char *cp)
1027 while (*cp) {
1028 if (*cp == '%') {
1030 * %( is the start of an atom;
1031 * %% is a quoted per-cent.
1033 if (cp[1] == '(')
1034 return cp;
1035 else if (cp[1] == '%')
1036 cp++; /* skip over two % */
1037 /* otherwise this is a singleton, literal % */
1039 cp++;
1041 return NULL;
1044 static int reject_atom(enum atom_type atom_type)
1046 return atom_type == ATOM_REST;
1050 * Make sure the format string is well formed, and parse out
1051 * the used atoms.
1053 int verify_ref_format(struct ref_format *format)
1055 const char *cp, *sp;
1057 format->need_color_reset_at_eol = 0;
1058 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1059 struct strbuf err = STRBUF_INIT;
1060 const char *color, *ep = strchr(sp, ')');
1061 int at;
1063 if (!ep)
1064 return error(_("malformed format string %s"), sp);
1065 /* sp points at "%(" and ep points at the closing ")" */
1066 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1067 if (at < 0)
1068 die("%s", err.buf);
1069 if (reject_atom(used_atom[at].atom_type))
1070 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1072 if ((format->quote_style == QUOTE_PYTHON ||
1073 format->quote_style == QUOTE_SHELL ||
1074 format->quote_style == QUOTE_TCL) &&
1075 used_atom[at].atom_type == ATOM_RAW &&
1076 used_atom[at].u.raw_data.option == RAW_BARE)
1077 die(_("--format=%.*s cannot be used with "
1078 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1079 cp = ep + 1;
1081 if (skip_prefix(used_atom[at].name, "color:", &color))
1082 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1083 strbuf_release(&err);
1085 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1086 format->need_color_reset_at_eol = 0;
1087 return 0;
1090 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1091 struct used_atom *atom)
1093 switch (atom->u.oid.option) {
1094 case O_FULL:
1095 return oid_to_hex(oid);
1096 case O_LENGTH:
1097 return find_unique_abbrev(oid, atom->u.oid.length);
1098 case O_SHORT:
1099 return find_unique_abbrev(oid, DEFAULT_ABBREV);
1100 default:
1101 BUG("unknown %%(%s) option", field);
1105 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1106 struct atom_value *v, struct used_atom *atom)
1108 if (starts_with(name, field)) {
1109 v->s = xstrdup(do_grab_oid(field, oid, atom));
1110 return 1;
1112 return 0;
1115 /* See grab_values */
1116 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1118 int i;
1120 for (i = 0; i < used_atom_cnt; i++) {
1121 const char *name = used_atom[i].name;
1122 enum atom_type atom_type = used_atom[i].atom_type;
1123 struct atom_value *v = &val[i];
1124 if (!!deref != (*name == '*'))
1125 continue;
1126 if (deref)
1127 name++;
1128 if (atom_type == ATOM_OBJECTTYPE)
1129 v->s = xstrdup(type_name(oi->type));
1130 else if (atom_type == ATOM_OBJECTSIZE) {
1131 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1132 v->value = oi->disk_size;
1133 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1134 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1135 v->value = oi->size;
1136 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1138 } else if (atom_type == ATOM_DELTABASE)
1139 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1140 else if (atom_type == ATOM_OBJECTNAME && deref)
1141 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1145 /* See grab_values */
1146 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1148 int i;
1149 struct tag *tag = (struct tag *) obj;
1151 for (i = 0; i < used_atom_cnt; i++) {
1152 const char *name = used_atom[i].name;
1153 enum atom_type atom_type = used_atom[i].atom_type;
1154 struct atom_value *v = &val[i];
1155 if (!!deref != (*name == '*'))
1156 continue;
1157 if (deref)
1158 name++;
1159 if (atom_type == ATOM_TAG)
1160 v->s = xstrdup(tag->tag);
1161 else if (atom_type == ATOM_TYPE && tag->tagged)
1162 v->s = xstrdup(type_name(tag->tagged->type));
1163 else if (atom_type == ATOM_OBJECT && tag->tagged)
1164 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1168 /* See grab_values */
1169 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1171 int i;
1172 struct commit *commit = (struct commit *) obj;
1174 for (i = 0; i < used_atom_cnt; i++) {
1175 const char *name = used_atom[i].name;
1176 enum atom_type atom_type = used_atom[i].atom_type;
1177 struct atom_value *v = &val[i];
1178 if (!!deref != (*name == '*'))
1179 continue;
1180 if (deref)
1181 name++;
1182 if (atom_type == ATOM_TREE &&
1183 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1184 continue;
1185 if (atom_type == ATOM_NUMPARENT) {
1186 v->value = commit_list_count(commit->parents);
1187 v->s = xstrfmt("%lu", (unsigned long)v->value);
1189 else if (atom_type == ATOM_PARENT) {
1190 struct commit_list *parents;
1191 struct strbuf s = STRBUF_INIT;
1192 for (parents = commit->parents; parents; parents = parents->next) {
1193 struct object_id *oid = &parents->item->object.oid;
1194 if (parents != commit->parents)
1195 strbuf_addch(&s, ' ');
1196 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1198 v->s = strbuf_detach(&s, NULL);
1203 static const char *find_wholine(const char *who, int wholen, const char *buf)
1205 const char *eol;
1206 while (*buf) {
1207 if (!strncmp(buf, who, wholen) &&
1208 buf[wholen] == ' ')
1209 return buf + wholen + 1;
1210 eol = strchr(buf, '\n');
1211 if (!eol)
1212 return "";
1213 eol++;
1214 if (*eol == '\n')
1215 return ""; /* end of header */
1216 buf = eol;
1218 return "";
1221 static const char *copy_line(const char *buf)
1223 const char *eol = strchrnul(buf, '\n');
1224 return xmemdupz(buf, eol - buf);
1227 static const char *copy_name(const char *buf)
1229 const char *cp;
1230 for (cp = buf; *cp && *cp != '\n'; cp++) {
1231 if (starts_with(cp, " <"))
1232 return xmemdupz(buf, cp - buf);
1234 return xstrdup("");
1237 static const char *copy_email(const char *buf, struct used_atom *atom)
1239 const char *email = strchr(buf, '<');
1240 const char *eoemail;
1241 if (!email)
1242 return xstrdup("");
1243 switch (atom->u.email_option.option) {
1244 case EO_RAW:
1245 eoemail = strchr(email, '>');
1246 if (eoemail)
1247 eoemail++;
1248 break;
1249 case EO_TRIM:
1250 email++;
1251 eoemail = strchr(email, '>');
1252 break;
1253 case EO_LOCALPART:
1254 email++;
1255 eoemail = strchr(email, '@');
1256 if (!eoemail)
1257 eoemail = strchr(email, '>');
1258 break;
1259 default:
1260 BUG("unknown email option");
1263 if (!eoemail)
1264 return xstrdup("");
1265 return xmemdupz(email, eoemail - email);
1268 static char *copy_subject(const char *buf, unsigned long len)
1270 struct strbuf sb = STRBUF_INIT;
1271 int i;
1273 for (i = 0; i < len; i++) {
1274 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1275 continue; /* ignore CR in CRLF */
1277 if (buf[i] == '\n')
1278 strbuf_addch(&sb, ' ');
1279 else
1280 strbuf_addch(&sb, buf[i]);
1282 return strbuf_detach(&sb, NULL);
1285 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1287 const char *eoemail = strstr(buf, "> ");
1288 char *zone;
1289 timestamp_t timestamp;
1290 long tz;
1291 struct date_mode date_mode = DATE_MODE_INIT;
1292 const char *formatp;
1295 * We got here because atomname ends in "date" or "date<something>";
1296 * it's not possible that <something> is not ":<format>" because
1297 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1298 * ":" means no format is specified, and use the default.
1300 formatp = strchr(atomname, ':');
1301 if (formatp) {
1302 formatp++;
1303 parse_date_format(formatp, &date_mode);
1306 if (!eoemail)
1307 goto bad;
1308 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1309 if (timestamp == TIME_MAX)
1310 goto bad;
1311 tz = strtol(zone, NULL, 10);
1312 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1313 goto bad;
1314 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1315 v->value = timestamp;
1316 date_mode_release(&date_mode);
1317 return;
1318 bad:
1319 v->s = xstrdup("");
1320 v->value = 0;
1323 /* See grab_values */
1324 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1326 int i;
1327 int wholen = strlen(who);
1328 const char *wholine = NULL;
1330 for (i = 0; i < used_atom_cnt; i++) {
1331 const char *name = used_atom[i].name;
1332 struct atom_value *v = &val[i];
1333 if (!!deref != (*name == '*'))
1334 continue;
1335 if (deref)
1336 name++;
1337 if (strncmp(who, name, wholen))
1338 continue;
1339 if (name[wholen] != 0 &&
1340 strcmp(name + wholen, "name") &&
1341 !starts_with(name + wholen, "email") &&
1342 !starts_with(name + wholen, "date"))
1343 continue;
1344 if (!wholine)
1345 wholine = find_wholine(who, wholen, buf);
1346 if (!wholine)
1347 return; /* no point looking for it */
1348 if (name[wholen] == 0)
1349 v->s = copy_line(wholine);
1350 else if (!strcmp(name + wholen, "name"))
1351 v->s = copy_name(wholine);
1352 else if (starts_with(name + wholen, "email"))
1353 v->s = copy_email(wholine, &used_atom[i]);
1354 else if (starts_with(name + wholen, "date"))
1355 grab_date(wholine, v, name);
1359 * For a tag or a commit object, if "creator" or "creatordate" is
1360 * requested, do something special.
1362 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1363 return; /* "author" for commit object is not wanted */
1364 if (!wholine)
1365 wholine = find_wholine(who, wholen, buf);
1366 if (!wholine)
1367 return;
1368 for (i = 0; i < used_atom_cnt; i++) {
1369 const char *name = used_atom[i].name;
1370 enum atom_type atom_type = used_atom[i].atom_type;
1371 struct atom_value *v = &val[i];
1372 if (!!deref != (*name == '*'))
1373 continue;
1374 if (deref)
1375 name++;
1377 if (atom_type == ATOM_CREATORDATE)
1378 grab_date(wholine, v, name);
1379 else if (atom_type == ATOM_CREATOR)
1380 v->s = copy_line(wholine);
1384 static void find_subpos(const char *buf,
1385 const char **sub, size_t *sublen,
1386 const char **body, size_t *bodylen,
1387 size_t *nonsiglen,
1388 const char **sig, size_t *siglen)
1390 struct strbuf payload = STRBUF_INIT;
1391 struct strbuf signature = STRBUF_INIT;
1392 const char *eol;
1393 const char *end = buf + strlen(buf);
1394 const char *sigstart;
1396 /* parse signature first; we might not even have a subject line */
1397 parse_signature(buf, end - buf, &payload, &signature);
1398 strbuf_release(&payload);
1400 /* skip past header until we hit empty line */
1401 while (*buf && *buf != '\n') {
1402 eol = strchrnul(buf, '\n');
1403 if (*eol)
1404 eol++;
1405 buf = eol;
1407 /* skip any empty lines */
1408 while (*buf == '\n')
1409 buf++;
1410 *sig = strbuf_detach(&signature, siglen);
1411 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1413 /* subject is first non-empty line */
1414 *sub = buf;
1415 /* subject goes to first empty line before signature begins */
1416 if ((eol = strstr(*sub, "\n\n")) ||
1417 (eol = strstr(*sub, "\r\n\r\n"))) {
1418 eol = eol < sigstart ? eol : sigstart;
1419 } else {
1420 /* treat whole message as subject */
1421 eol = sigstart;
1423 buf = eol;
1424 *sublen = buf - *sub;
1425 /* drop trailing newline, if present */
1426 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1427 (*sub)[*sublen - 1] == '\r'))
1428 *sublen -= 1;
1430 /* skip any empty lines */
1431 while (*buf == '\n' || *buf == '\r')
1432 buf++;
1433 *body = buf;
1434 *bodylen = strlen(buf);
1435 *nonsiglen = sigstart - buf;
1439 * If 'lines' is greater than 0, append that many lines from the given
1440 * 'buf' of length 'size' to the given strbuf.
1442 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1444 int i;
1445 const char *sp, *eol;
1446 size_t len;
1448 sp = buf;
1450 for (i = 0; i < lines && sp < buf + size; i++) {
1451 if (i)
1452 strbuf_addstr(out, "\n ");
1453 eol = memchr(sp, '\n', size - (sp - buf));
1454 len = eol ? eol - sp : size - (sp - buf);
1455 strbuf_add(out, sp, len);
1456 if (!eol)
1457 break;
1458 sp = eol + 1;
1462 /* See grab_values */
1463 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1465 int i;
1466 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1467 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1468 void *buf = data->content;
1470 for (i = 0; i < used_atom_cnt; i++) {
1471 struct used_atom *atom = &used_atom[i];
1472 const char *name = atom->name;
1473 struct atom_value *v = &val[i];
1474 enum atom_type atom_type = atom->atom_type;
1476 if (!!deref != (*name == '*'))
1477 continue;
1478 if (deref)
1479 name++;
1481 if (atom_type == ATOM_RAW) {
1482 unsigned long buf_size = data->size;
1484 if (atom->u.raw_data.option == RAW_BARE) {
1485 v->s = xmemdupz(buf, buf_size);
1486 v->s_size = buf_size;
1487 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1488 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1490 continue;
1493 if ((data->type != OBJ_TAG &&
1494 data->type != OBJ_COMMIT) ||
1495 (strcmp(name, "body") &&
1496 !starts_with(name, "subject") &&
1497 !starts_with(name, "trailers") &&
1498 !starts_with(name, "contents")))
1499 continue;
1500 if (!subpos)
1501 find_subpos(buf,
1502 &subpos, &sublen,
1503 &bodypos, &bodylen, &nonsiglen,
1504 &sigpos, &siglen);
1506 if (atom->u.contents.option == C_SUB)
1507 v->s = copy_subject(subpos, sublen);
1508 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1509 struct strbuf sb = STRBUF_INIT;
1510 format_sanitized_subject(&sb, subpos, sublen);
1511 v->s = strbuf_detach(&sb, NULL);
1512 } else if (atom->u.contents.option == C_BODY_DEP)
1513 v->s = xmemdupz(bodypos, bodylen);
1514 else if (atom->u.contents.option == C_LENGTH)
1515 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1516 else if (atom->u.contents.option == C_BODY)
1517 v->s = xmemdupz(bodypos, nonsiglen);
1518 else if (atom->u.contents.option == C_SIG)
1519 v->s = xmemdupz(sigpos, siglen);
1520 else if (atom->u.contents.option == C_LINES) {
1521 struct strbuf s = STRBUF_INIT;
1522 const char *contents_end = bodypos + nonsiglen;
1524 /* Size is the length of the message after removing the signature */
1525 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1526 v->s = strbuf_detach(&s, NULL);
1527 } else if (atom->u.contents.option == C_TRAILERS) {
1528 struct strbuf s = STRBUF_INIT;
1530 /* Format the trailer info according to the trailer_opts given */
1531 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1533 v->s = strbuf_detach(&s, NULL);
1534 } else if (atom->u.contents.option == C_BARE)
1535 v->s = xstrdup(subpos);
1538 free((void *)sigpos);
1542 * We want to have empty print-string for field requests
1543 * that do not apply (e.g. "authordate" for a tag object)
1545 static void fill_missing_values(struct atom_value *val)
1547 int i;
1548 for (i = 0; i < used_atom_cnt; i++) {
1549 struct atom_value *v = &val[i];
1550 if (!v->s)
1551 v->s = xstrdup("");
1556 * val is a list of atom_value to hold returned values. Extract
1557 * the values for atoms in used_atom array out of (obj, buf, sz).
1558 * when deref is false, (obj, buf, sz) is the object that is
1559 * pointed at by the ref itself; otherwise it is the object the
1560 * ref (which is a tag) refers to.
1562 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1564 void *buf = data->content;
1566 switch (obj->type) {
1567 case OBJ_TAG:
1568 grab_tag_values(val, deref, obj);
1569 grab_sub_body_contents(val, deref, data);
1570 grab_person("tagger", val, deref, buf);
1571 break;
1572 case OBJ_COMMIT:
1573 grab_commit_values(val, deref, obj);
1574 grab_sub_body_contents(val, deref, data);
1575 grab_person("author", val, deref, buf);
1576 grab_person("committer", val, deref, buf);
1577 break;
1578 case OBJ_TREE:
1579 /* grab_tree_values(val, deref, obj, buf, sz); */
1580 grab_sub_body_contents(val, deref, data);
1581 break;
1582 case OBJ_BLOB:
1583 /* grab_blob_values(val, deref, obj, buf, sz); */
1584 grab_sub_body_contents(val, deref, data);
1585 break;
1586 default:
1587 die("Eh? Object of type %d?", obj->type);
1591 static inline char *copy_advance(char *dst, const char *src)
1593 while (*src)
1594 *dst++ = *src++;
1595 return dst;
1598 static const char *lstrip_ref_components(const char *refname, int len)
1600 long remaining = len;
1601 const char *start = xstrdup(refname);
1602 const char *to_free = start;
1604 if (len < 0) {
1605 int i;
1606 const char *p = refname;
1608 /* Find total no of '/' separated path-components */
1609 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1612 * The number of components we need to strip is now
1613 * the total minus the components to be left (Plus one
1614 * because we count the number of '/', but the number
1615 * of components is one more than the no of '/').
1617 remaining = i + len + 1;
1620 while (remaining > 0) {
1621 switch (*start++) {
1622 case '\0':
1623 free((char *)to_free);
1624 return xstrdup("");
1625 case '/':
1626 remaining--;
1627 break;
1631 start = xstrdup(start);
1632 free((char *)to_free);
1633 return start;
1636 static const char *rstrip_ref_components(const char *refname, int len)
1638 long remaining = len;
1639 const char *start = xstrdup(refname);
1640 const char *to_free = start;
1642 if (len < 0) {
1643 int i;
1644 const char *p = refname;
1646 /* Find total no of '/' separated path-components */
1647 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1650 * The number of components we need to strip is now
1651 * the total minus the components to be left (Plus one
1652 * because we count the number of '/', but the number
1653 * of components is one more than the no of '/').
1655 remaining = i + len + 1;
1658 while (remaining-- > 0) {
1659 char *p = strrchr(start, '/');
1660 if (!p) {
1661 free((char *)to_free);
1662 return xstrdup("");
1663 } else
1664 p[0] = '\0';
1666 return start;
1669 static const char *show_ref(struct refname_atom *atom, const char *refname)
1671 if (atom->option == R_SHORT)
1672 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1673 else if (atom->option == R_LSTRIP)
1674 return lstrip_ref_components(refname, atom->lstrip);
1675 else if (atom->option == R_RSTRIP)
1676 return rstrip_ref_components(refname, atom->rstrip);
1677 else
1678 return xstrdup(refname);
1681 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1682 struct branch *branch, const char **s)
1684 int num_ours, num_theirs;
1685 if (atom->u.remote_ref.option == RR_REF)
1686 *s = show_ref(&atom->u.remote_ref.refname, refname);
1687 else if (atom->u.remote_ref.option == RR_TRACK) {
1688 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1689 NULL, atom->u.remote_ref.push,
1690 AHEAD_BEHIND_FULL) < 0) {
1691 *s = xstrdup(msgs.gone);
1692 } else if (!num_ours && !num_theirs)
1693 *s = xstrdup("");
1694 else if (!num_ours)
1695 *s = xstrfmt(msgs.behind, num_theirs);
1696 else if (!num_theirs)
1697 *s = xstrfmt(msgs.ahead, num_ours);
1698 else
1699 *s = xstrfmt(msgs.ahead_behind,
1700 num_ours, num_theirs);
1701 if (!atom->u.remote_ref.nobracket && *s[0]) {
1702 const char *to_free = *s;
1703 *s = xstrfmt("[%s]", *s);
1704 free((void *)to_free);
1706 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1707 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1708 NULL, atom->u.remote_ref.push,
1709 AHEAD_BEHIND_FULL) < 0) {
1710 *s = xstrdup("");
1711 return;
1713 if (!num_ours && !num_theirs)
1714 *s = xstrdup("=");
1715 else if (!num_ours)
1716 *s = xstrdup("<");
1717 else if (!num_theirs)
1718 *s = xstrdup(">");
1719 else
1720 *s = xstrdup("<>");
1721 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1722 int explicit;
1723 const char *remote = atom->u.remote_ref.push ?
1724 pushremote_for_branch(branch, &explicit) :
1725 remote_for_branch(branch, &explicit);
1726 *s = xstrdup(explicit ? remote : "");
1727 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1728 const char *merge;
1730 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1731 *s = xstrdup(merge ? merge : "");
1732 } else
1733 BUG("unhandled RR_* enum");
1736 char *get_head_description(void)
1738 struct strbuf desc = STRBUF_INIT;
1739 struct wt_status_state state;
1740 memset(&state, 0, sizeof(state));
1741 wt_status_get_state(the_repository, &state, 1);
1742 if (state.rebase_in_progress ||
1743 state.rebase_interactive_in_progress) {
1744 if (state.branch)
1745 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1746 state.branch);
1747 else
1748 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1749 state.detached_from);
1750 } else if (state.bisect_in_progress)
1751 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1752 state.branch);
1753 else if (state.detached_from) {
1754 if (state.detached_at)
1755 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1756 state.detached_from);
1757 else
1758 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1759 state.detached_from);
1760 } else
1761 strbuf_addstr(&desc, _("(no branch)"));
1763 wt_status_state_free_buffers(&state);
1765 return strbuf_detach(&desc, NULL);
1768 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1770 if (!ref->symref)
1771 return xstrdup("");
1772 else
1773 return show_ref(&atom->u.refname, ref->symref);
1776 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1778 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1779 return get_head_description();
1780 return show_ref(&atom->u.refname, ref->refname);
1783 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1784 struct expand_data *oi, struct strbuf *err)
1786 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1787 int eaten = 1;
1788 if (oi->info.contentp) {
1789 /* We need to know that to use parse_object_buffer properly */
1790 oi->info.sizep = &oi->size;
1791 oi->info.typep = &oi->type;
1793 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1794 OBJECT_INFO_LOOKUP_REPLACE))
1795 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1796 oid_to_hex(&oi->oid), ref->refname);
1797 if (oi->info.disk_sizep && oi->disk_size < 0)
1798 BUG("Object size is less than zero.");
1800 if (oi->info.contentp) {
1801 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1802 if (!*obj) {
1803 if (!eaten)
1804 free(oi->content);
1805 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1806 oid_to_hex(&oi->oid), ref->refname);
1808 grab_values(ref->value, deref, *obj, oi);
1811 grab_common_values(ref->value, deref, oi);
1812 if (!eaten)
1813 free(oi->content);
1814 return 0;
1817 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1819 int i;
1821 for (i = 0; worktrees[i]; i++) {
1822 if (worktrees[i]->head_ref) {
1823 struct ref_to_worktree_entry *entry;
1824 entry = xmalloc(sizeof(*entry));
1825 entry->wt = worktrees[i];
1826 hashmap_entry_init(&entry->ent,
1827 strhash(worktrees[i]->head_ref));
1829 hashmap_add(map, &entry->ent);
1834 static void lazy_init_worktree_map(void)
1836 if (ref_to_worktree_map.worktrees)
1837 return;
1839 ref_to_worktree_map.worktrees = get_worktrees();
1840 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1841 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1844 static char *get_worktree_path(const struct ref_array_item *ref)
1846 struct hashmap_entry entry, *e;
1847 struct ref_to_worktree_entry *lookup_result;
1849 lazy_init_worktree_map();
1851 hashmap_entry_init(&entry, strhash(ref->refname));
1852 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1854 if (!e)
1855 return xstrdup("");
1857 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1859 return xstrdup(lookup_result->wt->path);
1863 * Parse the object referred by ref, and grab needed value.
1865 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1867 struct object *obj;
1868 int i;
1869 struct object_info empty = OBJECT_INFO_INIT;
1871 CALLOC_ARRAY(ref->value, used_atom_cnt);
1873 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1874 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1875 NULL, NULL);
1876 if (!ref->symref)
1877 ref->symref = xstrdup("");
1880 /* Fill in specials first */
1881 for (i = 0; i < used_atom_cnt; i++) {
1882 struct used_atom *atom = &used_atom[i];
1883 enum atom_type atom_type = atom->atom_type;
1884 const char *name = used_atom[i].name;
1885 struct atom_value *v = &ref->value[i];
1886 int deref = 0;
1887 const char *refname;
1888 struct branch *branch = NULL;
1890 v->s_size = ATOM_SIZE_UNSPECIFIED;
1891 v->handler = append_atom;
1892 v->atom = atom;
1894 if (*name == '*') {
1895 deref = 1;
1896 name++;
1899 if (atom_type == ATOM_REFNAME)
1900 refname = get_refname(atom, ref);
1901 else if (atom_type == ATOM_WORKTREEPATH) {
1902 if (ref->kind == FILTER_REFS_BRANCHES)
1903 v->s = get_worktree_path(ref);
1904 else
1905 v->s = xstrdup("");
1906 continue;
1908 else if (atom_type == ATOM_SYMREF)
1909 refname = get_symref(atom, ref);
1910 else if (atom_type == ATOM_UPSTREAM) {
1911 const char *branch_name;
1912 /* only local branches may have an upstream */
1913 if (!skip_prefix(ref->refname, "refs/heads/",
1914 &branch_name)) {
1915 v->s = xstrdup("");
1916 continue;
1918 branch = branch_get(branch_name);
1920 refname = branch_get_upstream(branch, NULL);
1921 if (refname)
1922 fill_remote_ref_details(atom, refname, branch, &v->s);
1923 else
1924 v->s = xstrdup("");
1925 continue;
1926 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1927 const char *branch_name;
1928 v->s = xstrdup("");
1929 if (!skip_prefix(ref->refname, "refs/heads/",
1930 &branch_name))
1931 continue;
1932 branch = branch_get(branch_name);
1934 if (atom->u.remote_ref.push_remote)
1935 refname = NULL;
1936 else {
1937 refname = branch_get_push(branch, NULL);
1938 if (!refname)
1939 continue;
1941 /* We will definitely re-init v->s on the next line. */
1942 free((char *)v->s);
1943 fill_remote_ref_details(atom, refname, branch, &v->s);
1944 continue;
1945 } else if (atom_type == ATOM_COLOR) {
1946 v->s = xstrdup(atom->u.color);
1947 continue;
1948 } else if (atom_type == ATOM_FLAG) {
1949 char buf[256], *cp = buf;
1950 if (ref->flag & REF_ISSYMREF)
1951 cp = copy_advance(cp, ",symref");
1952 if (ref->flag & REF_ISPACKED)
1953 cp = copy_advance(cp, ",packed");
1954 if (cp == buf)
1955 v->s = xstrdup("");
1956 else {
1957 *cp = '\0';
1958 v->s = xstrdup(buf + 1);
1960 continue;
1961 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1962 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1963 continue;
1964 } else if (atom_type == ATOM_HEAD) {
1965 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1966 v->s = xstrdup("*");
1967 else
1968 v->s = xstrdup(" ");
1969 continue;
1970 } else if (atom_type == ATOM_ALIGN) {
1971 v->handler = align_atom_handler;
1972 v->s = xstrdup("");
1973 continue;
1974 } else if (atom_type == ATOM_END) {
1975 v->handler = end_atom_handler;
1976 v->s = xstrdup("");
1977 continue;
1978 } else if (atom_type == ATOM_IF) {
1979 const char *s;
1980 if (skip_prefix(name, "if:", &s))
1981 v->s = xstrdup(s);
1982 else
1983 v->s = xstrdup("");
1984 v->handler = if_atom_handler;
1985 continue;
1986 } else if (atom_type == ATOM_THEN) {
1987 v->handler = then_atom_handler;
1988 v->s = xstrdup("");
1989 continue;
1990 } else if (atom_type == ATOM_ELSE) {
1991 v->handler = else_atom_handler;
1992 v->s = xstrdup("");
1993 continue;
1994 } else if (atom_type == ATOM_REST) {
1995 if (ref->rest)
1996 v->s = xstrdup(ref->rest);
1997 else
1998 v->s = xstrdup("");
1999 continue;
2000 } else
2001 continue;
2003 if (!deref)
2004 v->s = xstrdup(refname);
2005 else
2006 v->s = xstrfmt("%s^{}", refname);
2007 free((char *)refname);
2010 for (i = 0; i < used_atom_cnt; i++) {
2011 struct atom_value *v = &ref->value[i];
2012 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2013 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2014 oid_to_hex(&ref->objectname), ref->refname);
2017 if (need_tagged)
2018 oi.info.contentp = &oi.content;
2019 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2020 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2021 return 0;
2024 oi.oid = ref->objectname;
2025 if (get_object(ref, 0, &obj, &oi, err))
2026 return -1;
2029 * If there is no atom that wants to know about tagged
2030 * object, we are done.
2032 if (!need_tagged || (obj->type != OBJ_TAG))
2033 return 0;
2036 * If it is a tag object, see if we use a value that derefs
2037 * the object, and if we do grab the object it refers to.
2039 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2042 * NEEDSWORK: This derefs tag only once, which
2043 * is good to deal with chains of trust, but
2044 * is not consistent with what deref_tag() does
2045 * which peels the onion to the core.
2047 return get_object(ref, 1, &obj, &oi_deref, err);
2051 * Given a ref, return the value for the atom. This lazily gets value
2052 * out of the object by calling populate value.
2054 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2055 struct atom_value **v, struct strbuf *err)
2057 if (!ref->value) {
2058 if (populate_value(ref, err))
2059 return -1;
2060 fill_missing_values(ref->value);
2062 *v = &ref->value[atom];
2063 return 0;
2067 * Return 1 if the refname matches one of the patterns, otherwise 0.
2068 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2069 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2070 * matches "refs/heads/mas*", too).
2072 static int match_pattern(const struct ref_filter *filter, const char *refname)
2074 const char **patterns = filter->name_patterns;
2075 unsigned flags = 0;
2077 if (filter->ignore_case)
2078 flags |= WM_CASEFOLD;
2081 * When no '--format' option is given we need to skip the prefix
2082 * for matching refs of tags and branches.
2084 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2085 skip_prefix(refname, "refs/heads/", &refname) ||
2086 skip_prefix(refname, "refs/remotes/", &refname) ||
2087 skip_prefix(refname, "refs/", &refname));
2089 for (; *patterns; patterns++) {
2090 if (!wildmatch(*patterns, refname, flags))
2091 return 1;
2093 return 0;
2097 * Return 1 if the refname matches one of the patterns, otherwise 0.
2098 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2099 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2100 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2102 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2104 const char **pattern = filter->name_patterns;
2105 int namelen = strlen(refname);
2106 unsigned flags = WM_PATHNAME;
2108 if (filter->ignore_case)
2109 flags |= WM_CASEFOLD;
2111 for (; *pattern; pattern++) {
2112 const char *p = *pattern;
2113 int plen = strlen(p);
2115 if ((plen <= namelen) &&
2116 !strncmp(refname, p, plen) &&
2117 (refname[plen] == '\0' ||
2118 refname[plen] == '/' ||
2119 p[plen-1] == '/'))
2120 return 1;
2121 if (!wildmatch(p, refname, flags))
2122 return 1;
2124 return 0;
2127 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2128 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2130 if (!*filter->name_patterns)
2131 return 1; /* No pattern always matches */
2132 if (filter->match_as_path)
2133 return match_name_as_path(filter, refname);
2134 return match_pattern(filter, refname);
2138 * This is the same as for_each_fullref_in(), but it tries to iterate
2139 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2140 * pattern match, so the callback still has to match each ref individually.
2142 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2143 each_ref_fn cb,
2144 void *cb_data)
2146 if (!filter->match_as_path) {
2148 * in this case, the patterns are applied after
2149 * prefixes like "refs/heads/" etc. are stripped off,
2150 * so we have to look at everything:
2152 return for_each_fullref_in("", cb, cb_data);
2155 if (filter->ignore_case) {
2157 * we can't handle case-insensitive comparisons,
2158 * so just return everything and let the caller
2159 * sort it out.
2161 return for_each_fullref_in("", cb, cb_data);
2164 if (!filter->name_patterns[0]) {
2165 /* no patterns; we have to look at everything */
2166 return for_each_fullref_in("", cb, cb_data);
2169 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2170 NULL, filter->name_patterns,
2171 cb, cb_data);
2175 * Given a ref (oid, refname), check if the ref belongs to the array
2176 * of oids. If the given ref is a tag, check if the given tag points
2177 * at one of the oids in the given oid array.
2178 * NEEDSWORK:
2179 * 1. Only a single level of indirection is obtained, we might want to
2180 * change this to account for multiple levels (e.g. annotated tags
2181 * pointing to annotated tags pointing to a commit.)
2182 * 2. As the refs are cached we might know what refname peels to without
2183 * the need to parse the object via parse_object(). peel_ref() might be a
2184 * more efficient alternative to obtain the pointee.
2186 static const struct object_id *match_points_at(struct oid_array *points_at,
2187 const struct object_id *oid,
2188 const char *refname)
2190 const struct object_id *tagged_oid = NULL;
2191 struct object *obj;
2193 if (oid_array_lookup(points_at, oid) >= 0)
2194 return oid;
2195 obj = parse_object(the_repository, oid);
2196 if (!obj)
2197 die(_("malformed object at '%s'"), refname);
2198 if (obj->type == OBJ_TAG)
2199 tagged_oid = get_tagged_oid((struct tag *)obj);
2200 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2201 return tagged_oid;
2202 return NULL;
2206 * Allocate space for a new ref_array_item and copy the name and oid to it.
2208 * Callers can then fill in other struct members at their leisure.
2210 static struct ref_array_item *new_ref_array_item(const char *refname,
2211 const struct object_id *oid)
2213 struct ref_array_item *ref;
2215 FLEX_ALLOC_STR(ref, refname, refname);
2216 oidcpy(&ref->objectname, oid);
2217 ref->rest = NULL;
2219 return ref;
2222 struct ref_array_item *ref_array_push(struct ref_array *array,
2223 const char *refname,
2224 const struct object_id *oid)
2226 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2228 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2229 array->items[array->nr++] = ref;
2231 return ref;
2234 static int ref_kind_from_refname(const char *refname)
2236 unsigned int i;
2238 static struct {
2239 const char *prefix;
2240 unsigned int kind;
2241 } ref_kind[] = {
2242 { "refs/heads/" , FILTER_REFS_BRANCHES },
2243 { "refs/remotes/" , FILTER_REFS_REMOTES },
2244 { "refs/tags/", FILTER_REFS_TAGS}
2247 if (!strcmp(refname, "HEAD"))
2248 return FILTER_REFS_DETACHED_HEAD;
2250 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2251 if (starts_with(refname, ref_kind[i].prefix))
2252 return ref_kind[i].kind;
2255 return FILTER_REFS_OTHERS;
2258 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2260 if (filter->kind == FILTER_REFS_BRANCHES ||
2261 filter->kind == FILTER_REFS_REMOTES ||
2262 filter->kind == FILTER_REFS_TAGS)
2263 return filter->kind;
2264 return ref_kind_from_refname(refname);
2267 struct ref_filter_cbdata {
2268 struct ref_array *array;
2269 struct ref_filter *filter;
2270 struct contains_cache contains_cache;
2271 struct contains_cache no_contains_cache;
2275 * A call-back given to for_each_ref(). Filter refs and keep them for
2276 * later object processing.
2278 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2280 struct ref_filter_cbdata *ref_cbdata = cb_data;
2281 struct ref_filter *filter = ref_cbdata->filter;
2282 struct ref_array_item *ref;
2283 struct commit *commit = NULL;
2284 unsigned int kind;
2286 if (flag & REF_BAD_NAME) {
2287 warning(_("ignoring ref with broken name %s"), refname);
2288 return 0;
2291 if (flag & REF_ISBROKEN) {
2292 warning(_("ignoring broken ref %s"), refname);
2293 return 0;
2296 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2297 kind = filter_ref_kind(filter, refname);
2298 if (!(kind & filter->kind))
2299 return 0;
2301 if (!filter_pattern_match(filter, refname))
2302 return 0;
2304 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2305 return 0;
2308 * A merge filter is applied on refs pointing to commits. Hence
2309 * obtain the commit using the 'oid' available and discard all
2310 * non-commits early. The actual filtering is done later.
2312 if (filter->reachable_from || filter->unreachable_from ||
2313 filter->with_commit || filter->no_commit || filter->verbose) {
2314 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2315 if (!commit)
2316 return 0;
2317 /* We perform the filtering for the '--contains' option... */
2318 if (filter->with_commit &&
2319 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2320 return 0;
2321 /* ...or for the `--no-contains' option */
2322 if (filter->no_commit &&
2323 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2324 return 0;
2328 * We do not open the object yet; sort may only need refname
2329 * to do its job and the resulting list may yet to be pruned
2330 * by maxcount logic.
2332 ref = ref_array_push(ref_cbdata->array, refname, oid);
2333 ref->commit = commit;
2334 ref->flag = flag;
2335 ref->kind = kind;
2337 return 0;
2340 /* Free memory allocated for a ref_array_item */
2341 static void free_array_item(struct ref_array_item *item)
2343 free((char *)item->symref);
2344 if (item->value) {
2345 int i;
2346 for (i = 0; i < used_atom_cnt; i++)
2347 free((char *)item->value[i].s);
2348 free(item->value);
2350 free(item);
2353 /* Free all memory allocated for ref_array */
2354 void ref_array_clear(struct ref_array *array)
2356 int i;
2358 for (i = 0; i < array->nr; i++)
2359 free_array_item(array->items[i]);
2360 FREE_AND_NULL(array->items);
2361 array->nr = array->alloc = 0;
2363 for (i = 0; i < used_atom_cnt; i++) {
2364 struct used_atom *atom = &used_atom[i];
2365 if (atom->atom_type == ATOM_HEAD)
2366 free(atom->u.head);
2367 free((char *)atom->name);
2369 FREE_AND_NULL(used_atom);
2370 used_atom_cnt = 0;
2372 if (ref_to_worktree_map.worktrees) {
2373 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2374 struct ref_to_worktree_entry, ent);
2375 free_worktrees(ref_to_worktree_map.worktrees);
2376 ref_to_worktree_map.worktrees = NULL;
2380 #define EXCLUDE_REACHED 0
2381 #define INCLUDE_REACHED 1
2382 static void reach_filter(struct ref_array *array,
2383 struct commit_list *check_reachable,
2384 int include_reached)
2386 struct rev_info revs;
2387 int i, old_nr;
2388 struct commit **to_clear;
2389 struct commit_list *cr;
2391 if (!check_reachable)
2392 return;
2394 CALLOC_ARRAY(to_clear, array->nr);
2396 repo_init_revisions(the_repository, &revs, NULL);
2398 for (i = 0; i < array->nr; i++) {
2399 struct ref_array_item *item = array->items[i];
2400 add_pending_object(&revs, &item->commit->object, item->refname);
2401 to_clear[i] = item->commit;
2404 for (cr = check_reachable; cr; cr = cr->next) {
2405 struct commit *merge_commit = cr->item;
2406 merge_commit->object.flags |= UNINTERESTING;
2407 add_pending_object(&revs, &merge_commit->object, "");
2410 revs.limited = 1;
2411 if (prepare_revision_walk(&revs))
2412 die(_("revision walk setup failed"));
2414 old_nr = array->nr;
2415 array->nr = 0;
2417 for (i = 0; i < old_nr; i++) {
2418 struct ref_array_item *item = array->items[i];
2419 struct commit *commit = item->commit;
2421 int is_merged = !!(commit->object.flags & UNINTERESTING);
2423 if (is_merged == include_reached)
2424 array->items[array->nr++] = array->items[i];
2425 else
2426 free_array_item(item);
2429 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2431 while (check_reachable) {
2432 struct commit *merge_commit = pop_commit(&check_reachable);
2433 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2436 release_revisions(&revs);
2437 free(to_clear);
2441 * API for filtering a set of refs. Based on the type of refs the user
2442 * has requested, we iterate through those refs and apply filters
2443 * as per the given ref_filter structure and finally store the
2444 * filtered refs in the ref_array structure.
2446 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2448 struct ref_filter_cbdata ref_cbdata;
2449 int save_commit_buffer_orig;
2450 int ret = 0;
2452 ref_cbdata.array = array;
2453 ref_cbdata.filter = filter;
2455 filter->kind = type & FILTER_REFS_KIND_MASK;
2457 save_commit_buffer_orig = save_commit_buffer;
2458 save_commit_buffer = 0;
2460 init_contains_cache(&ref_cbdata.contains_cache);
2461 init_contains_cache(&ref_cbdata.no_contains_cache);
2463 /* Simple per-ref filtering */
2464 if (!filter->kind)
2465 die("filter_refs: invalid type");
2466 else {
2468 * For common cases where we need only branches or remotes or tags,
2469 * we only iterate through those refs. If a mix of refs is needed,
2470 * we iterate over all refs and filter out required refs with the help
2471 * of filter_ref_kind().
2473 if (filter->kind == FILTER_REFS_BRANCHES)
2474 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2475 else if (filter->kind == FILTER_REFS_REMOTES)
2476 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2477 else if (filter->kind == FILTER_REFS_TAGS)
2478 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2479 else if (filter->kind & FILTER_REFS_ALL)
2480 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2481 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2482 head_ref(ref_filter_handler, &ref_cbdata);
2485 clear_contains_cache(&ref_cbdata.contains_cache);
2486 clear_contains_cache(&ref_cbdata.no_contains_cache);
2488 /* Filters that need revision walking */
2489 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2490 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2492 save_commit_buffer = save_commit_buffer_orig;
2493 return ret;
2496 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2498 if (!(a->kind ^ b->kind))
2499 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2500 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2501 return -1;
2502 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2503 return 1;
2504 BUG("should have died in the xor check above");
2505 return 0;
2508 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2510 const char *s1 = vs1, *s2 = vs2;
2511 const char *end = s1 + n;
2513 for (; s1 < end; s1++, s2++) {
2514 int diff = tolower(*s1) - tolower(*s2);
2515 if (diff)
2516 return diff;
2518 return 0;
2521 struct ref_sorting {
2522 struct ref_sorting *next;
2523 int atom; /* index into used_atom array (internal) */
2524 enum ref_sorting_order sort_flags;
2527 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2529 struct atom_value *va, *vb;
2530 int cmp;
2531 int cmp_detached_head = 0;
2532 cmp_type cmp_type = used_atom[s->atom].type;
2533 struct strbuf err = STRBUF_INIT;
2535 if (get_ref_atom_value(a, s->atom, &va, &err))
2536 die("%s", err.buf);
2537 if (get_ref_atom_value(b, s->atom, &vb, &err))
2538 die("%s", err.buf);
2539 strbuf_release(&err);
2540 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2541 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2542 cmp = compare_detached_head(a, b);
2543 cmp_detached_head = 1;
2544 } else if (s->sort_flags & REF_SORTING_VERSION) {
2545 cmp = versioncmp(va->s, vb->s);
2546 } else if (cmp_type == FIELD_STR) {
2547 if (va->s_size < 0 && vb->s_size < 0) {
2548 int (*cmp_fn)(const char *, const char *);
2549 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2550 ? strcasecmp : strcmp;
2551 cmp = cmp_fn(va->s, vb->s);
2552 } else {
2553 size_t a_size = va->s_size < 0 ?
2554 strlen(va->s) : va->s_size;
2555 size_t b_size = vb->s_size < 0 ?
2556 strlen(vb->s) : vb->s_size;
2557 int (*cmp_fn)(const void *, const void *, size_t);
2558 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2559 ? memcasecmp : memcmp;
2561 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2562 a_size : b_size);
2563 if (!cmp) {
2564 if (a_size > b_size)
2565 cmp = 1;
2566 else if (a_size < b_size)
2567 cmp = -1;
2570 } else {
2571 if (va->value < vb->value)
2572 cmp = -1;
2573 else if (va->value == vb->value)
2574 cmp = 0;
2575 else
2576 cmp = 1;
2579 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2580 ? -cmp : cmp;
2583 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2585 struct ref_array_item *a = *((struct ref_array_item **)a_);
2586 struct ref_array_item *b = *((struct ref_array_item **)b_);
2587 struct ref_sorting *s;
2589 for (s = ref_sorting; s; s = s->next) {
2590 int cmp = cmp_ref_sorting(s, a, b);
2591 if (cmp)
2592 return cmp;
2594 s = ref_sorting;
2595 return s && s->sort_flags & REF_SORTING_ICASE ?
2596 strcasecmp(a->refname, b->refname) :
2597 strcmp(a->refname, b->refname);
2600 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2601 unsigned int mask, int on)
2603 for (; sorting; sorting = sorting->next) {
2604 if (on)
2605 sorting->sort_flags |= mask;
2606 else
2607 sorting->sort_flags &= ~mask;
2611 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2613 QSORT_S(array->items, array->nr, compare_refs, sorting);
2616 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2618 struct strbuf *s = &state->stack->output;
2620 while (*cp && (!ep || cp < ep)) {
2621 if (*cp == '%') {
2622 if (cp[1] == '%')
2623 cp++;
2624 else {
2625 int ch = hex2chr(cp + 1);
2626 if (0 <= ch) {
2627 strbuf_addch(s, ch);
2628 cp += 3;
2629 continue;
2633 strbuf_addch(s, *cp);
2634 cp++;
2638 int format_ref_array_item(struct ref_array_item *info,
2639 struct ref_format *format,
2640 struct strbuf *final_buf,
2641 struct strbuf *error_buf)
2643 const char *cp, *sp, *ep;
2644 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2646 state.quote_style = format->quote_style;
2647 push_stack_element(&state.stack);
2649 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2650 struct atom_value *atomv;
2651 int pos;
2653 ep = strchr(sp, ')');
2654 if (cp < sp)
2655 append_literal(cp, sp, &state);
2656 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2657 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2658 atomv->handler(atomv, &state, error_buf)) {
2659 pop_stack_element(&state.stack);
2660 return -1;
2663 if (*cp) {
2664 sp = cp + strlen(cp);
2665 append_literal(cp, sp, &state);
2667 if (format->need_color_reset_at_eol) {
2668 struct atom_value resetv = ATOM_VALUE_INIT;
2669 resetv.s = GIT_COLOR_RESET;
2670 if (append_atom(&resetv, &state, error_buf)) {
2671 pop_stack_element(&state.stack);
2672 return -1;
2675 if (state.stack->prev) {
2676 pop_stack_element(&state.stack);
2677 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2679 strbuf_addbuf(final_buf, &state.stack->output);
2680 pop_stack_element(&state.stack);
2681 return 0;
2684 void pretty_print_ref(const char *name, const struct object_id *oid,
2685 struct ref_format *format)
2687 struct ref_array_item *ref_item;
2688 struct strbuf output = STRBUF_INIT;
2689 struct strbuf err = STRBUF_INIT;
2691 ref_item = new_ref_array_item(name, oid);
2692 ref_item->kind = ref_kind_from_refname(name);
2693 if (format_ref_array_item(ref_item, format, &output, &err))
2694 die("%s", err.buf);
2695 fwrite(output.buf, 1, output.len, stdout);
2696 putchar('\n');
2698 strbuf_release(&err);
2699 strbuf_release(&output);
2700 free_array_item(ref_item);
2703 static int parse_sorting_atom(const char *atom)
2706 * This parses an atom using a dummy ref_format, since we don't
2707 * actually care about the formatting details.
2709 struct ref_format dummy = REF_FORMAT_INIT;
2710 const char *end = atom + strlen(atom);
2711 struct strbuf err = STRBUF_INIT;
2712 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2713 if (res < 0)
2714 die("%s", err.buf);
2715 strbuf_release(&err);
2716 return res;
2719 /* If no sorting option is given, use refname to sort as default */
2720 static struct ref_sorting *ref_default_sorting(void)
2722 static const char cstr_name[] = "refname";
2724 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2726 sorting->next = NULL;
2727 sorting->atom = parse_sorting_atom(cstr_name);
2728 return sorting;
2731 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2733 struct ref_sorting *s;
2735 CALLOC_ARRAY(s, 1);
2736 s->next = *sorting_tail;
2737 *sorting_tail = s;
2739 if (*arg == '-') {
2740 s->sort_flags |= REF_SORTING_REVERSE;
2741 arg++;
2743 if (skip_prefix(arg, "version:", &arg) ||
2744 skip_prefix(arg, "v:", &arg))
2745 s->sort_flags |= REF_SORTING_VERSION;
2746 s->atom = parse_sorting_atom(arg);
2749 struct ref_sorting *ref_sorting_options(struct string_list *options)
2751 struct string_list_item *item;
2752 struct ref_sorting *sorting = NULL, **tail = &sorting;
2754 if (!options->nr) {
2755 sorting = ref_default_sorting();
2756 } else {
2757 for_each_string_list_item(item, options)
2758 parse_ref_sorting(tail, item->string);
2762 * From here on, the ref_sorting list should be used to talk
2763 * about the sort order used for the output. The caller
2764 * should not touch the string form anymore.
2766 string_list_clear(options, 0);
2767 return sorting;
2770 void ref_sorting_release(struct ref_sorting *sorting)
2772 while (sorting) {
2773 struct ref_sorting *next = sorting->next;
2774 free(sorting);
2775 sorting = next;
2779 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2781 struct ref_filter *rf = opt->value;
2782 struct object_id oid;
2783 struct commit *merge_commit;
2785 BUG_ON_OPT_NEG(unset);
2787 if (get_oid(arg, &oid))
2788 die(_("malformed object name %s"), arg);
2790 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2792 if (!merge_commit)
2793 return error(_("option `%s' must point to a commit"), opt->long_name);
2795 if (starts_with(opt->long_name, "no"))
2796 commit_list_insert(merge_commit, &rf->unreachable_from);
2797 else
2798 commit_list_insert(merge_commit, &rf->reachable_from);
2800 return 0;