Merge branch 'ab/remove-implicit-use-of-the-repository' into en/header-split-cache-h
[alt-git.git] / ref-filter.c
blobdf84bb7164339907cfab082815bbd3620db1747d
1 #include "cache.h"
2 #include "alloc.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "hex.h"
6 #include "parse-options.h"
7 #include "refs.h"
8 #include "wildmatch.h"
9 #include "object-store.h"
10 #include "repository.h"
11 #include "commit.h"
12 #include "remote.h"
13 #include "color.h"
14 #include "tag.h"
15 #include "quote.h"
16 #include "ref-filter.h"
17 #include "revision.h"
18 #include "utf8.h"
19 #include "version.h"
20 #include "trailer.h"
21 #include "wt-status.h"
22 #include "commit-slab.h"
23 #include "commit-graph.h"
24 #include "commit-reach.h"
25 #include "worktree.h"
26 #include "hashmap.h"
27 #include "strvec.h"
29 static struct ref_msg {
30 const char *gone;
31 const char *ahead;
32 const char *behind;
33 const char *ahead_behind;
34 } msgs = {
35 /* Untranslated plumbing messages: */
36 "gone",
37 "ahead %d",
38 "behind %d",
39 "ahead %d, behind %d"
42 void setup_ref_filter_porcelain_msg(void)
44 msgs.gone = _("gone");
45 msgs.ahead = _("ahead %d");
46 msgs.behind = _("behind %d");
47 msgs.ahead_behind = _("ahead %d, behind %d");
50 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
51 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
52 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
54 struct align {
55 align_type position;
56 unsigned int width;
59 struct if_then_else {
60 cmp_status cmp_status;
61 const char *str;
62 unsigned int then_atom_seen : 1,
63 else_atom_seen : 1,
64 condition_satisfied : 1;
67 struct refname_atom {
68 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
69 int lstrip, rstrip;
72 static struct ref_trailer_buf {
73 struct string_list filter_list;
74 struct strbuf sepbuf;
75 struct strbuf kvsepbuf;
76 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
78 static struct expand_data {
79 struct object_id oid;
80 enum object_type type;
81 unsigned long size;
82 off_t disk_size;
83 struct object_id delta_base_oid;
84 void *content;
86 struct object_info info;
87 } oi, oi_deref;
89 struct ref_to_worktree_entry {
90 struct hashmap_entry ent;
91 struct worktree *wt; /* key is wt->head_ref */
94 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
95 const struct hashmap_entry *eptr,
96 const struct hashmap_entry *kptr,
97 const void *keydata_aka_refname)
99 const struct ref_to_worktree_entry *e, *k;
101 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
102 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
104 return strcmp(e->wt->head_ref,
105 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
108 static struct ref_to_worktree_map {
109 struct hashmap map;
110 struct worktree **worktrees;
111 } ref_to_worktree_map;
114 * The enum atom_type is used as the index of valid_atom array.
115 * In the atom parsing stage, it will be passed to used_atom.atom_type
116 * as the identifier of the atom type. We can check the type of used_atom
117 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
119 enum atom_type {
120 ATOM_REFNAME,
121 ATOM_OBJECTTYPE,
122 ATOM_OBJECTSIZE,
123 ATOM_OBJECTNAME,
124 ATOM_DELTABASE,
125 ATOM_TREE,
126 ATOM_PARENT,
127 ATOM_NUMPARENT,
128 ATOM_OBJECT,
129 ATOM_TYPE,
130 ATOM_TAG,
131 ATOM_AUTHOR,
132 ATOM_AUTHORNAME,
133 ATOM_AUTHOREMAIL,
134 ATOM_AUTHORDATE,
135 ATOM_COMMITTER,
136 ATOM_COMMITTERNAME,
137 ATOM_COMMITTEREMAIL,
138 ATOM_COMMITTERDATE,
139 ATOM_TAGGER,
140 ATOM_TAGGERNAME,
141 ATOM_TAGGEREMAIL,
142 ATOM_TAGGERDATE,
143 ATOM_CREATOR,
144 ATOM_CREATORDATE,
145 ATOM_SUBJECT,
146 ATOM_BODY,
147 ATOM_TRAILERS,
148 ATOM_CONTENTS,
149 ATOM_RAW,
150 ATOM_UPSTREAM,
151 ATOM_PUSH,
152 ATOM_SYMREF,
153 ATOM_FLAG,
154 ATOM_HEAD,
155 ATOM_COLOR,
156 ATOM_WORKTREEPATH,
157 ATOM_ALIGN,
158 ATOM_END,
159 ATOM_IF,
160 ATOM_THEN,
161 ATOM_ELSE,
162 ATOM_REST,
166 * An atom is a valid field atom listed below, possibly prefixed with
167 * a "*" to denote deref_tag().
169 * We parse given format string and sort specifiers, and make a list
170 * of properties that we need to extract out of objects. ref_array_item
171 * structure will hold an array of values extracted that can be
172 * indexed with the "atom number", which is an index into this
173 * array.
175 static struct used_atom {
176 enum atom_type atom_type;
177 const char *name;
178 cmp_type type;
179 info_source source;
180 union {
181 char color[COLOR_MAXLEN];
182 struct align align;
183 struct {
184 enum {
185 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
186 } option;
187 struct refname_atom refname;
188 unsigned int nobracket : 1, push : 1, push_remote : 1;
189 } remote_ref;
190 struct {
191 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
192 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
193 struct process_trailer_options trailer_opts;
194 unsigned int nlines;
195 } contents;
196 struct {
197 enum { RAW_BARE, RAW_LENGTH } option;
198 } raw_data;
199 struct {
200 cmp_status cmp_status;
201 const char *str;
202 } if_then_else;
203 struct {
204 enum { O_FULL, O_LENGTH, O_SHORT } option;
205 unsigned int length;
206 } oid;
207 struct {
208 enum { O_SIZE, O_SIZE_DISK } option;
209 } objectsize;
210 struct email_option {
211 enum { EO_RAW, EO_TRIM, EO_LOCALPART } option;
212 } email_option;
213 struct refname_atom refname;
214 char *head;
215 } u;
216 } *used_atom;
217 static int used_atom_cnt, need_tagged, need_symref;
220 * Expand string, append it to strbuf *sb, then return error code ret.
221 * Allow to save few lines of code.
223 __attribute__((format (printf, 3, 4)))
224 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
226 va_list ap;
227 va_start(ap, fmt);
228 strbuf_vaddf(sb, fmt, ap);
229 va_end(ap);
230 return ret;
233 static int err_no_arg(struct strbuf *sb, const char *name)
235 size_t namelen = strchrnul(name, ':') - name;
236 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
237 (int)namelen, name);
238 return -1;
241 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
243 size_t namelen = strchrnul(name, ':') - name;
244 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
245 (int)namelen, name, arg);
246 return -1;
249 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
250 const char *color_value, struct strbuf *err)
252 if (!color_value)
253 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
254 if (color_parse(color_value, atom->u.color) < 0)
255 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
256 color_value);
258 * We check this after we've parsed the color, which lets us complain
259 * about syntactically bogus color names even if they won't be used.
261 if (!want_color(format->use_color))
262 color_parse("", atom->u.color);
263 return 0;
266 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
267 const char *name, struct strbuf *err)
269 if (!arg)
270 atom->option = R_NORMAL;
271 else if (!strcmp(arg, "short"))
272 atom->option = R_SHORT;
273 else if (skip_prefix(arg, "lstrip=", &arg) ||
274 skip_prefix(arg, "strip=", &arg)) {
275 atom->option = R_LSTRIP;
276 if (strtol_i(arg, 10, &atom->lstrip))
277 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
278 } else if (skip_prefix(arg, "rstrip=", &arg)) {
279 atom->option = R_RSTRIP;
280 if (strtol_i(arg, 10, &atom->rstrip))
281 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
282 } else
283 return err_bad_arg(err, name, arg);
284 return 0;
287 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
288 struct used_atom *atom,
289 const char *arg, struct strbuf *err)
291 struct string_list params = STRING_LIST_INIT_DUP;
292 int i;
294 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
295 atom->u.remote_ref.push = 1;
297 if (!arg) {
298 atom->u.remote_ref.option = RR_REF;
299 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
300 arg, atom->name, err);
303 atom->u.remote_ref.nobracket = 0;
304 string_list_split(&params, arg, ',', -1);
306 for (i = 0; i < params.nr; i++) {
307 const char *s = params.items[i].string;
309 if (!strcmp(s, "track"))
310 atom->u.remote_ref.option = RR_TRACK;
311 else if (!strcmp(s, "trackshort"))
312 atom->u.remote_ref.option = RR_TRACKSHORT;
313 else if (!strcmp(s, "nobracket"))
314 atom->u.remote_ref.nobracket = 1;
315 else if (!strcmp(s, "remotename")) {
316 atom->u.remote_ref.option = RR_REMOTE_NAME;
317 atom->u.remote_ref.push_remote = 1;
318 } else if (!strcmp(s, "remoteref")) {
319 atom->u.remote_ref.option = RR_REMOTE_REF;
320 atom->u.remote_ref.push_remote = 1;
321 } else {
322 atom->u.remote_ref.option = RR_REF;
323 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
324 arg, atom->name, err)) {
325 string_list_clear(&params, 0);
326 return -1;
331 string_list_clear(&params, 0);
332 return 0;
335 static int objecttype_atom_parser(struct ref_format *format UNUSED,
336 struct used_atom *atom,
337 const char *arg, struct strbuf *err)
339 if (arg)
340 return err_no_arg(err, "objecttype");
341 if (*atom->name == '*')
342 oi_deref.info.typep = &oi_deref.type;
343 else
344 oi.info.typep = &oi.type;
345 return 0;
348 static int objectsize_atom_parser(struct ref_format *format UNUSED,
349 struct used_atom *atom,
350 const char *arg, struct strbuf *err)
352 if (!arg) {
353 atom->u.objectsize.option = O_SIZE;
354 if (*atom->name == '*')
355 oi_deref.info.sizep = &oi_deref.size;
356 else
357 oi.info.sizep = &oi.size;
358 } else if (!strcmp(arg, "disk")) {
359 atom->u.objectsize.option = O_SIZE_DISK;
360 if (*atom->name == '*')
361 oi_deref.info.disk_sizep = &oi_deref.disk_size;
362 else
363 oi.info.disk_sizep = &oi.disk_size;
364 } else
365 return err_bad_arg(err, "objectsize", arg);
366 return 0;
369 static int deltabase_atom_parser(struct ref_format *format UNUSED,
370 struct used_atom *atom,
371 const char *arg, struct strbuf *err)
373 if (arg)
374 return err_no_arg(err, "deltabase");
375 if (*atom->name == '*')
376 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
377 else
378 oi.info.delta_base_oid = &oi.delta_base_oid;
379 return 0;
382 static int body_atom_parser(struct ref_format *format UNUSED,
383 struct used_atom *atom,
384 const char *arg, struct strbuf *err)
386 if (arg)
387 return err_no_arg(err, "body");
388 atom->u.contents.option = C_BODY_DEP;
389 return 0;
392 static int subject_atom_parser(struct ref_format *format UNUSED,
393 struct used_atom *atom,
394 const char *arg, struct strbuf *err)
396 if (!arg)
397 atom->u.contents.option = C_SUB;
398 else if (!strcmp(arg, "sanitize"))
399 atom->u.contents.option = C_SUB_SANITIZE;
400 else
401 return err_bad_arg(err, "subject", arg);
402 return 0;
405 static int trailers_atom_parser(struct ref_format *format UNUSED,
406 struct used_atom *atom,
407 const char *arg, struct strbuf *err)
409 atom->u.contents.trailer_opts.no_divider = 1;
411 if (arg) {
412 const char *argbuf = xstrfmt("%s)", arg);
413 char *invalid_arg = NULL;
415 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
416 &ref_trailer_buf.filter_list,
417 &ref_trailer_buf.sepbuf,
418 &ref_trailer_buf.kvsepbuf,
419 &argbuf, &invalid_arg)) {
420 if (!invalid_arg)
421 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
422 else
423 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
424 free((char *)invalid_arg);
425 return -1;
428 atom->u.contents.option = C_TRAILERS;
429 return 0;
432 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
433 const char *arg, struct strbuf *err)
435 if (!arg)
436 atom->u.contents.option = C_BARE;
437 else if (!strcmp(arg, "body"))
438 atom->u.contents.option = C_BODY;
439 else if (!strcmp(arg, "size"))
440 atom->u.contents.option = C_LENGTH;
441 else if (!strcmp(arg, "signature"))
442 atom->u.contents.option = C_SIG;
443 else if (!strcmp(arg, "subject"))
444 atom->u.contents.option = C_SUB;
445 else if (!strcmp(arg, "trailers")) {
446 if (trailers_atom_parser(format, atom, NULL, err))
447 return -1;
448 } else if (skip_prefix(arg, "trailers:", &arg)) {
449 if (trailers_atom_parser(format, atom, arg, err))
450 return -1;
451 } else if (skip_prefix(arg, "lines=", &arg)) {
452 atom->u.contents.option = C_LINES;
453 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
454 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
455 } else
456 return err_bad_arg(err, "contents", arg);
457 return 0;
460 static int raw_atom_parser(struct ref_format *format UNUSED,
461 struct used_atom *atom,
462 const char *arg, struct strbuf *err)
464 if (!arg)
465 atom->u.raw_data.option = RAW_BARE;
466 else if (!strcmp(arg, "size"))
467 atom->u.raw_data.option = RAW_LENGTH;
468 else
469 return err_bad_arg(err, "raw", arg);
470 return 0;
473 static int oid_atom_parser(struct ref_format *format UNUSED,
474 struct used_atom *atom,
475 const char *arg, struct strbuf *err)
477 if (!arg)
478 atom->u.oid.option = O_FULL;
479 else if (!strcmp(arg, "short"))
480 atom->u.oid.option = O_SHORT;
481 else if (skip_prefix(arg, "short=", &arg)) {
482 atom->u.oid.option = O_LENGTH;
483 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
484 atom->u.oid.length == 0)
485 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
486 if (atom->u.oid.length < MINIMUM_ABBREV)
487 atom->u.oid.length = MINIMUM_ABBREV;
488 } else
489 return err_bad_arg(err, atom->name, arg);
490 return 0;
493 static int person_email_atom_parser(struct ref_format *format UNUSED,
494 struct used_atom *atom,
495 const char *arg, struct strbuf *err)
497 if (!arg)
498 atom->u.email_option.option = EO_RAW;
499 else if (!strcmp(arg, "trim"))
500 atom->u.email_option.option = EO_TRIM;
501 else if (!strcmp(arg, "localpart"))
502 atom->u.email_option.option = EO_LOCALPART;
503 else
504 return err_bad_arg(err, atom->name, arg);
505 return 0;
508 static int refname_atom_parser(struct ref_format *format UNUSED,
509 struct used_atom *atom,
510 const char *arg, struct strbuf *err)
512 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
515 static align_type parse_align_position(const char *s)
517 if (!strcmp(s, "right"))
518 return ALIGN_RIGHT;
519 else if (!strcmp(s, "middle"))
520 return ALIGN_MIDDLE;
521 else if (!strcmp(s, "left"))
522 return ALIGN_LEFT;
523 return -1;
526 static int align_atom_parser(struct ref_format *format UNUSED,
527 struct used_atom *atom,
528 const char *arg, struct strbuf *err)
530 struct align *align = &atom->u.align;
531 struct string_list params = STRING_LIST_INIT_DUP;
532 int i;
533 unsigned int width = ~0U;
535 if (!arg)
536 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
538 align->position = ALIGN_LEFT;
540 string_list_split(&params, arg, ',', -1);
541 for (i = 0; i < params.nr; i++) {
542 const char *s = params.items[i].string;
543 int position;
545 if (skip_prefix(s, "position=", &s)) {
546 position = parse_align_position(s);
547 if (position < 0) {
548 strbuf_addf(err, _("unrecognized position:%s"), s);
549 string_list_clear(&params, 0);
550 return -1;
552 align->position = position;
553 } else if (skip_prefix(s, "width=", &s)) {
554 if (strtoul_ui(s, 10, &width)) {
555 strbuf_addf(err, _("unrecognized width:%s"), s);
556 string_list_clear(&params, 0);
557 return -1;
559 } else if (!strtoul_ui(s, 10, &width))
561 else if ((position = parse_align_position(s)) >= 0)
562 align->position = position;
563 else {
564 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
565 string_list_clear(&params, 0);
566 return -1;
570 if (width == ~0U) {
571 string_list_clear(&params, 0);
572 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
574 align->width = width;
575 string_list_clear(&params, 0);
576 return 0;
579 static int if_atom_parser(struct ref_format *format UNUSED,
580 struct used_atom *atom,
581 const char *arg, struct strbuf *err)
583 if (!arg) {
584 atom->u.if_then_else.cmp_status = COMPARE_NONE;
585 return 0;
586 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
587 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
588 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
589 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
590 } else
591 return err_bad_arg(err, "if", arg);
592 return 0;
595 static int rest_atom_parser(struct ref_format *format,
596 struct used_atom *atom UNUSED,
597 const char *arg, struct strbuf *err)
599 if (arg)
600 return err_no_arg(err, "rest");
601 format->use_rest = 1;
602 return 0;
605 static int head_atom_parser(struct ref_format *format UNUSED,
606 struct used_atom *atom,
607 const char *arg, struct strbuf *err)
609 if (arg)
610 return err_no_arg(err, "HEAD");
611 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
612 return 0;
615 static struct {
616 const char *name;
617 info_source source;
618 cmp_type cmp_type;
619 int (*parser)(struct ref_format *format, struct used_atom *atom,
620 const char *arg, struct strbuf *err);
621 } valid_atom[] = {
622 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
623 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
624 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
625 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
626 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
627 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
628 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
629 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
630 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
631 [ATOM_TYPE] = { "type", SOURCE_OBJ },
632 [ATOM_TAG] = { "tag", SOURCE_OBJ },
633 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
634 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
635 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
636 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
637 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
638 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
639 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
640 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
641 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
642 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
643 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
644 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
645 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
646 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
647 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
648 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
649 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
650 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
651 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
652 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
653 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
654 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
655 [ATOM_FLAG] = { "flag", SOURCE_NONE },
656 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
657 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
658 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
659 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
660 [ATOM_END] = { "end", SOURCE_NONE },
661 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
662 [ATOM_THEN] = { "then", SOURCE_NONE },
663 [ATOM_ELSE] = { "else", SOURCE_NONE },
664 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
666 * Please update $__git_ref_fieldlist in git-completion.bash
667 * when you add new atoms
671 #define REF_FORMATTING_STATE_INIT { 0 }
673 struct ref_formatting_stack {
674 struct ref_formatting_stack *prev;
675 struct strbuf output;
676 void (*at_end)(struct ref_formatting_stack **stack);
677 void *at_end_data;
680 struct ref_formatting_state {
681 int quote_style;
682 struct ref_formatting_stack *stack;
685 struct atom_value {
686 const char *s;
687 ssize_t s_size;
688 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
689 struct strbuf *err);
690 uintmax_t value; /* used for sorting when not FIELD_STR */
691 struct used_atom *atom;
694 #define ATOM_SIZE_UNSPECIFIED (-1)
696 #define ATOM_VALUE_INIT { \
697 .s_size = ATOM_SIZE_UNSPECIFIED \
701 * Used to parse format string and sort specifiers
703 static int parse_ref_filter_atom(struct ref_format *format,
704 const char *atom, const char *ep,
705 struct strbuf *err)
707 const char *sp;
708 const char *arg;
709 int i, at, atom_len;
711 sp = atom;
712 if (*sp == '*' && sp < ep)
713 sp++; /* deref */
714 if (ep <= sp)
715 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
716 (int)(ep-atom), atom);
719 * If the atom name has a colon, strip it and everything after
720 * it off - it specifies the format for this entry, and
721 * shouldn't be used for checking against the valid_atom
722 * table.
724 arg = memchr(sp, ':', ep - sp);
725 atom_len = (arg ? arg : ep) - sp;
727 /* Do we have the atom already used elsewhere? */
728 for (i = 0; i < used_atom_cnt; i++) {
729 int len = strlen(used_atom[i].name);
730 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
731 return i;
734 /* Is the atom a valid one? */
735 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
736 int len = strlen(valid_atom[i].name);
737 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
738 break;
741 if (ARRAY_SIZE(valid_atom) <= i)
742 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
743 (int)(ep-atom), atom);
744 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
745 return strbuf_addf_ret(err, -1,
746 _("not a git repository, but the field '%.*s' requires access to object data"),
747 (int)(ep-atom), atom);
749 /* Add it in, including the deref prefix */
750 at = used_atom_cnt;
751 used_atom_cnt++;
752 REALLOC_ARRAY(used_atom, used_atom_cnt);
753 used_atom[at].atom_type = i;
754 used_atom[at].name = xmemdupz(atom, ep - atom);
755 used_atom[at].type = valid_atom[i].cmp_type;
756 used_atom[at].source = valid_atom[i].source;
757 if (used_atom[at].source == SOURCE_OBJ) {
758 if (*atom == '*')
759 oi_deref.info.contentp = &oi_deref.content;
760 else
761 oi.info.contentp = &oi.content;
763 if (arg) {
764 arg = used_atom[at].name + (arg - atom) + 1;
765 if (!*arg) {
767 * Treat empty sub-arguments list as NULL (i.e.,
768 * "%(atom:)" is equivalent to "%(atom)").
770 arg = NULL;
773 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
774 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
775 return -1;
776 if (*atom == '*')
777 need_tagged = 1;
778 if (i == ATOM_SYMREF)
779 need_symref = 1;
780 return at;
783 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
785 switch (quote_style) {
786 case QUOTE_NONE:
787 if (len < 0)
788 strbuf_addstr(s, str);
789 else
790 strbuf_add(s, str, len);
791 break;
792 case QUOTE_SHELL:
793 sq_quote_buf(s, str);
794 break;
795 case QUOTE_PERL:
796 if (len < 0)
797 perl_quote_buf(s, str);
798 else
799 perl_quote_buf_with_len(s, str, len);
800 break;
801 case QUOTE_PYTHON:
802 python_quote_buf(s, str);
803 break;
804 case QUOTE_TCL:
805 tcl_quote_buf(s, str);
806 break;
810 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
811 struct strbuf *err UNUSED)
814 * Quote formatting is only done when the stack has a single
815 * element. Otherwise quote formatting is done on the
816 * element's entire output strbuf when the %(end) atom is
817 * encountered.
819 if (!state->stack->prev)
820 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
821 else if (v->s_size < 0)
822 strbuf_addstr(&state->stack->output, v->s);
823 else
824 strbuf_add(&state->stack->output, v->s, v->s_size);
825 return 0;
828 static void push_stack_element(struct ref_formatting_stack **stack)
830 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
832 strbuf_init(&s->output, 0);
833 s->prev = *stack;
834 *stack = s;
837 static void pop_stack_element(struct ref_formatting_stack **stack)
839 struct ref_formatting_stack *current = *stack;
840 struct ref_formatting_stack *prev = current->prev;
842 if (prev)
843 strbuf_addbuf(&prev->output, &current->output);
844 strbuf_release(&current->output);
845 free(current);
846 *stack = prev;
849 static void end_align_handler(struct ref_formatting_stack **stack)
851 struct ref_formatting_stack *cur = *stack;
852 struct align *align = (struct align *)cur->at_end_data;
853 struct strbuf s = STRBUF_INIT;
855 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
856 strbuf_swap(&cur->output, &s);
857 strbuf_release(&s);
860 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
861 struct strbuf *err UNUSED)
863 struct ref_formatting_stack *new_stack;
865 push_stack_element(&state->stack);
866 new_stack = state->stack;
867 new_stack->at_end = end_align_handler;
868 new_stack->at_end_data = &atomv->atom->u.align;
869 return 0;
872 static void if_then_else_handler(struct ref_formatting_stack **stack)
874 struct ref_formatting_stack *cur = *stack;
875 struct ref_formatting_stack *prev = cur->prev;
876 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
878 if (!if_then_else->then_atom_seen)
879 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
881 if (if_then_else->else_atom_seen) {
883 * There is an %(else) atom: we need to drop one state from the
884 * stack, either the %(else) branch if the condition is satisfied, or
885 * the %(then) branch if it isn't.
887 if (if_then_else->condition_satisfied) {
888 strbuf_reset(&cur->output);
889 pop_stack_element(&cur);
890 } else {
891 strbuf_swap(&cur->output, &prev->output);
892 strbuf_reset(&cur->output);
893 pop_stack_element(&cur);
895 } else if (!if_then_else->condition_satisfied) {
897 * No %(else) atom: just drop the %(then) branch if the
898 * condition is not satisfied.
900 strbuf_reset(&cur->output);
903 *stack = cur;
904 free(if_then_else);
907 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
908 struct strbuf *err UNUSED)
910 struct ref_formatting_stack *new_stack;
911 struct if_then_else *if_then_else = xcalloc(1,
912 sizeof(struct if_then_else));
914 if_then_else->str = atomv->atom->u.if_then_else.str;
915 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
917 push_stack_element(&state->stack);
918 new_stack = state->stack;
919 new_stack->at_end = if_then_else_handler;
920 new_stack->at_end_data = if_then_else;
921 return 0;
924 static int is_empty(struct strbuf *buf)
926 const char *cur = buf->buf;
927 const char *end = buf->buf + buf->len;
929 while (cur != end && (isspace(*cur)))
930 cur++;
932 return cur == end;
935 static int then_atom_handler(struct atom_value *atomv UNUSED,
936 struct ref_formatting_state *state,
937 struct strbuf *err)
939 struct ref_formatting_stack *cur = state->stack;
940 struct if_then_else *if_then_else = NULL;
941 size_t str_len = 0;
943 if (cur->at_end == if_then_else_handler)
944 if_then_else = (struct if_then_else *)cur->at_end_data;
945 if (!if_then_else)
946 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
947 if (if_then_else->then_atom_seen)
948 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
949 if (if_then_else->else_atom_seen)
950 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
951 if_then_else->then_atom_seen = 1;
952 if (if_then_else->str)
953 str_len = strlen(if_then_else->str);
955 * If the 'equals' or 'notequals' attribute is used then
956 * perform the required comparison. If not, only non-empty
957 * strings satisfy the 'if' condition.
959 if (if_then_else->cmp_status == COMPARE_EQUAL) {
960 if (str_len == cur->output.len &&
961 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
962 if_then_else->condition_satisfied = 1;
963 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
964 if (str_len != cur->output.len ||
965 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
966 if_then_else->condition_satisfied = 1;
967 } else if (cur->output.len && !is_empty(&cur->output))
968 if_then_else->condition_satisfied = 1;
969 strbuf_reset(&cur->output);
970 return 0;
973 static int else_atom_handler(struct atom_value *atomv UNUSED,
974 struct ref_formatting_state *state,
975 struct strbuf *err)
977 struct ref_formatting_stack *prev = state->stack;
978 struct if_then_else *if_then_else = NULL;
980 if (prev->at_end == if_then_else_handler)
981 if_then_else = (struct if_then_else *)prev->at_end_data;
982 if (!if_then_else)
983 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
984 if (!if_then_else->then_atom_seen)
985 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
986 if (if_then_else->else_atom_seen)
987 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
988 if_then_else->else_atom_seen = 1;
989 push_stack_element(&state->stack);
990 state->stack->at_end_data = prev->at_end_data;
991 state->stack->at_end = prev->at_end;
992 return 0;
995 static int end_atom_handler(struct atom_value *atomv UNUSED,
996 struct ref_formatting_state *state,
997 struct strbuf *err)
999 struct ref_formatting_stack *current = state->stack;
1000 struct strbuf s = STRBUF_INIT;
1002 if (!current->at_end)
1003 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1004 current->at_end(&state->stack);
1006 /* Stack may have been popped within at_end(), hence reset the current pointer */
1007 current = state->stack;
1010 * Perform quote formatting when the stack element is that of
1011 * a supporting atom. If nested then perform quote formatting
1012 * only on the topmost supporting atom.
1014 if (!current->prev->prev) {
1015 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1016 strbuf_swap(&current->output, &s);
1018 strbuf_release(&s);
1019 pop_stack_element(&state->stack);
1020 return 0;
1024 * In a format string, find the next occurrence of %(atom).
1026 static const char *find_next(const char *cp)
1028 while (*cp) {
1029 if (*cp == '%') {
1031 * %( is the start of an atom;
1032 * %% is a quoted per-cent.
1034 if (cp[1] == '(')
1035 return cp;
1036 else if (cp[1] == '%')
1037 cp++; /* skip over two % */
1038 /* otherwise this is a singleton, literal % */
1040 cp++;
1042 return NULL;
1045 static int reject_atom(enum atom_type atom_type)
1047 return atom_type == ATOM_REST;
1051 * Make sure the format string is well formed, and parse out
1052 * the used atoms.
1054 int verify_ref_format(struct ref_format *format)
1056 const char *cp, *sp;
1058 format->need_color_reset_at_eol = 0;
1059 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1060 struct strbuf err = STRBUF_INIT;
1061 const char *color, *ep = strchr(sp, ')');
1062 int at;
1064 if (!ep)
1065 return error(_("malformed format string %s"), sp);
1066 /* sp points at "%(" and ep points at the closing ")" */
1067 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1068 if (at < 0)
1069 die("%s", err.buf);
1070 if (reject_atom(used_atom[at].atom_type))
1071 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1073 if ((format->quote_style == QUOTE_PYTHON ||
1074 format->quote_style == QUOTE_SHELL ||
1075 format->quote_style == QUOTE_TCL) &&
1076 used_atom[at].atom_type == ATOM_RAW &&
1077 used_atom[at].u.raw_data.option == RAW_BARE)
1078 die(_("--format=%.*s cannot be used with "
1079 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1080 cp = ep + 1;
1082 if (skip_prefix(used_atom[at].name, "color:", &color))
1083 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1084 strbuf_release(&err);
1086 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1087 format->need_color_reset_at_eol = 0;
1088 return 0;
1091 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1092 struct used_atom *atom)
1094 switch (atom->u.oid.option) {
1095 case O_FULL:
1096 return oid_to_hex(oid);
1097 case O_LENGTH:
1098 return repo_find_unique_abbrev(the_repository, oid,
1099 atom->u.oid.length);
1100 case O_SHORT:
1101 return repo_find_unique_abbrev(the_repository, oid,
1102 DEFAULT_ABBREV);
1103 default:
1104 BUG("unknown %%(%s) option", field);
1108 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1109 struct atom_value *v, struct used_atom *atom)
1111 if (starts_with(name, field)) {
1112 v->s = xstrdup(do_grab_oid(field, oid, atom));
1113 return 1;
1115 return 0;
1118 /* See grab_values */
1119 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1121 int i;
1123 for (i = 0; i < used_atom_cnt; i++) {
1124 const char *name = used_atom[i].name;
1125 enum atom_type atom_type = used_atom[i].atom_type;
1126 struct atom_value *v = &val[i];
1127 if (!!deref != (*name == '*'))
1128 continue;
1129 if (deref)
1130 name++;
1131 if (atom_type == ATOM_OBJECTTYPE)
1132 v->s = xstrdup(type_name(oi->type));
1133 else if (atom_type == ATOM_OBJECTSIZE) {
1134 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1135 v->value = oi->disk_size;
1136 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1137 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1138 v->value = oi->size;
1139 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1141 } else if (atom_type == ATOM_DELTABASE)
1142 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1143 else if (atom_type == ATOM_OBJECTNAME && deref)
1144 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1148 /* See grab_values */
1149 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1151 int i;
1152 struct tag *tag = (struct tag *) obj;
1154 for (i = 0; i < used_atom_cnt; i++) {
1155 const char *name = used_atom[i].name;
1156 enum atom_type atom_type = used_atom[i].atom_type;
1157 struct atom_value *v = &val[i];
1158 if (!!deref != (*name == '*'))
1159 continue;
1160 if (deref)
1161 name++;
1162 if (atom_type == ATOM_TAG)
1163 v->s = xstrdup(tag->tag);
1164 else if (atom_type == ATOM_TYPE && tag->tagged)
1165 v->s = xstrdup(type_name(tag->tagged->type));
1166 else if (atom_type == ATOM_OBJECT && tag->tagged)
1167 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1171 /* See grab_values */
1172 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1174 int i;
1175 struct commit *commit = (struct commit *) obj;
1177 for (i = 0; i < used_atom_cnt; i++) {
1178 const char *name = used_atom[i].name;
1179 enum atom_type atom_type = used_atom[i].atom_type;
1180 struct atom_value *v = &val[i];
1181 if (!!deref != (*name == '*'))
1182 continue;
1183 if (deref)
1184 name++;
1185 if (atom_type == ATOM_TREE &&
1186 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1187 continue;
1188 if (atom_type == ATOM_NUMPARENT) {
1189 v->value = commit_list_count(commit->parents);
1190 v->s = xstrfmt("%lu", (unsigned long)v->value);
1192 else if (atom_type == ATOM_PARENT) {
1193 struct commit_list *parents;
1194 struct strbuf s = STRBUF_INIT;
1195 for (parents = commit->parents; parents; parents = parents->next) {
1196 struct object_id *oid = &parents->item->object.oid;
1197 if (parents != commit->parents)
1198 strbuf_addch(&s, ' ');
1199 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1201 v->s = strbuf_detach(&s, NULL);
1206 static const char *find_wholine(const char *who, int wholen, const char *buf)
1208 const char *eol;
1209 while (*buf) {
1210 if (!strncmp(buf, who, wholen) &&
1211 buf[wholen] == ' ')
1212 return buf + wholen + 1;
1213 eol = strchr(buf, '\n');
1214 if (!eol)
1215 return "";
1216 eol++;
1217 if (*eol == '\n')
1218 return ""; /* end of header */
1219 buf = eol;
1221 return "";
1224 static const char *copy_line(const char *buf)
1226 const char *eol = strchrnul(buf, '\n');
1227 return xmemdupz(buf, eol - buf);
1230 static const char *copy_name(const char *buf)
1232 const char *cp;
1233 for (cp = buf; *cp && *cp != '\n'; cp++) {
1234 if (starts_with(cp, " <"))
1235 return xmemdupz(buf, cp - buf);
1237 return xstrdup("");
1240 static const char *copy_email(const char *buf, struct used_atom *atom)
1242 const char *email = strchr(buf, '<');
1243 const char *eoemail;
1244 if (!email)
1245 return xstrdup("");
1246 switch (atom->u.email_option.option) {
1247 case EO_RAW:
1248 eoemail = strchr(email, '>');
1249 if (eoemail)
1250 eoemail++;
1251 break;
1252 case EO_TRIM:
1253 email++;
1254 eoemail = strchr(email, '>');
1255 break;
1256 case EO_LOCALPART:
1257 email++;
1258 eoemail = strchr(email, '@');
1259 if (!eoemail)
1260 eoemail = strchr(email, '>');
1261 break;
1262 default:
1263 BUG("unknown email option");
1266 if (!eoemail)
1267 return xstrdup("");
1268 return xmemdupz(email, eoemail - email);
1271 static char *copy_subject(const char *buf, unsigned long len)
1273 struct strbuf sb = STRBUF_INIT;
1274 int i;
1276 for (i = 0; i < len; i++) {
1277 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1278 continue; /* ignore CR in CRLF */
1280 if (buf[i] == '\n')
1281 strbuf_addch(&sb, ' ');
1282 else
1283 strbuf_addch(&sb, buf[i]);
1285 return strbuf_detach(&sb, NULL);
1288 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1290 const char *eoemail = strstr(buf, "> ");
1291 char *zone;
1292 timestamp_t timestamp;
1293 long tz;
1294 struct date_mode date_mode = DATE_MODE_INIT;
1295 const char *formatp;
1298 * We got here because atomname ends in "date" or "date<something>";
1299 * it's not possible that <something> is not ":<format>" because
1300 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1301 * ":" means no format is specified, and use the default.
1303 formatp = strchr(atomname, ':');
1304 if (formatp) {
1305 formatp++;
1306 parse_date_format(formatp, &date_mode);
1309 if (!eoemail)
1310 goto bad;
1311 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1312 if (timestamp == TIME_MAX)
1313 goto bad;
1314 tz = strtol(zone, NULL, 10);
1315 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1316 goto bad;
1317 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1318 v->value = timestamp;
1319 date_mode_release(&date_mode);
1320 return;
1321 bad:
1322 v->s = xstrdup("");
1323 v->value = 0;
1326 /* See grab_values */
1327 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1329 int i;
1330 int wholen = strlen(who);
1331 const char *wholine = NULL;
1333 for (i = 0; i < used_atom_cnt; i++) {
1334 const char *name = used_atom[i].name;
1335 struct atom_value *v = &val[i];
1336 if (!!deref != (*name == '*'))
1337 continue;
1338 if (deref)
1339 name++;
1340 if (strncmp(who, name, wholen))
1341 continue;
1342 if (name[wholen] != 0 &&
1343 strcmp(name + wholen, "name") &&
1344 !starts_with(name + wholen, "email") &&
1345 !starts_with(name + wholen, "date"))
1346 continue;
1347 if (!wholine)
1348 wholine = find_wholine(who, wholen, buf);
1349 if (!wholine)
1350 return; /* no point looking for it */
1351 if (name[wholen] == 0)
1352 v->s = copy_line(wholine);
1353 else if (!strcmp(name + wholen, "name"))
1354 v->s = copy_name(wholine);
1355 else if (starts_with(name + wholen, "email"))
1356 v->s = copy_email(wholine, &used_atom[i]);
1357 else if (starts_with(name + wholen, "date"))
1358 grab_date(wholine, v, name);
1362 * For a tag or a commit object, if "creator" or "creatordate" is
1363 * requested, do something special.
1365 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1366 return; /* "author" for commit object is not wanted */
1367 if (!wholine)
1368 wholine = find_wholine(who, wholen, buf);
1369 if (!wholine)
1370 return;
1371 for (i = 0; i < used_atom_cnt; i++) {
1372 const char *name = used_atom[i].name;
1373 enum atom_type atom_type = used_atom[i].atom_type;
1374 struct atom_value *v = &val[i];
1375 if (!!deref != (*name == '*'))
1376 continue;
1377 if (deref)
1378 name++;
1380 if (atom_type == ATOM_CREATORDATE)
1381 grab_date(wholine, v, name);
1382 else if (atom_type == ATOM_CREATOR)
1383 v->s = copy_line(wholine);
1387 static void find_subpos(const char *buf,
1388 const char **sub, size_t *sublen,
1389 const char **body, size_t *bodylen,
1390 size_t *nonsiglen,
1391 const char **sig, size_t *siglen)
1393 struct strbuf payload = STRBUF_INIT;
1394 struct strbuf signature = STRBUF_INIT;
1395 const char *eol;
1396 const char *end = buf + strlen(buf);
1397 const char *sigstart;
1399 /* parse signature first; we might not even have a subject line */
1400 parse_signature(buf, end - buf, &payload, &signature);
1401 strbuf_release(&payload);
1403 /* skip past header until we hit empty line */
1404 while (*buf && *buf != '\n') {
1405 eol = strchrnul(buf, '\n');
1406 if (*eol)
1407 eol++;
1408 buf = eol;
1410 /* skip any empty lines */
1411 while (*buf == '\n')
1412 buf++;
1413 *sig = strbuf_detach(&signature, siglen);
1414 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1416 /* subject is first non-empty line */
1417 *sub = buf;
1418 /* subject goes to first empty line before signature begins */
1419 if ((eol = strstr(*sub, "\n\n")) ||
1420 (eol = strstr(*sub, "\r\n\r\n"))) {
1421 eol = eol < sigstart ? eol : sigstart;
1422 } else {
1423 /* treat whole message as subject */
1424 eol = sigstart;
1426 buf = eol;
1427 *sublen = buf - *sub;
1428 /* drop trailing newline, if present */
1429 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1430 (*sub)[*sublen - 1] == '\r'))
1431 *sublen -= 1;
1433 /* skip any empty lines */
1434 while (*buf == '\n' || *buf == '\r')
1435 buf++;
1436 *body = buf;
1437 *bodylen = strlen(buf);
1438 *nonsiglen = sigstart - buf;
1442 * If 'lines' is greater than 0, append that many lines from the given
1443 * 'buf' of length 'size' to the given strbuf.
1445 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1447 int i;
1448 const char *sp, *eol;
1449 size_t len;
1451 sp = buf;
1453 for (i = 0; i < lines && sp < buf + size; i++) {
1454 if (i)
1455 strbuf_addstr(out, "\n ");
1456 eol = memchr(sp, '\n', size - (sp - buf));
1457 len = eol ? eol - sp : size - (sp - buf);
1458 strbuf_add(out, sp, len);
1459 if (!eol)
1460 break;
1461 sp = eol + 1;
1465 /* See grab_values */
1466 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1468 int i;
1469 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1470 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1471 void *buf = data->content;
1473 for (i = 0; i < used_atom_cnt; i++) {
1474 struct used_atom *atom = &used_atom[i];
1475 const char *name = atom->name;
1476 struct atom_value *v = &val[i];
1477 enum atom_type atom_type = atom->atom_type;
1479 if (!!deref != (*name == '*'))
1480 continue;
1481 if (deref)
1482 name++;
1484 if (atom_type == ATOM_RAW) {
1485 unsigned long buf_size = data->size;
1487 if (atom->u.raw_data.option == RAW_BARE) {
1488 v->s = xmemdupz(buf, buf_size);
1489 v->s_size = buf_size;
1490 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1491 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1493 continue;
1496 if ((data->type != OBJ_TAG &&
1497 data->type != OBJ_COMMIT) ||
1498 (strcmp(name, "body") &&
1499 !starts_with(name, "subject") &&
1500 !starts_with(name, "trailers") &&
1501 !starts_with(name, "contents")))
1502 continue;
1503 if (!subpos)
1504 find_subpos(buf,
1505 &subpos, &sublen,
1506 &bodypos, &bodylen, &nonsiglen,
1507 &sigpos, &siglen);
1509 if (atom->u.contents.option == C_SUB)
1510 v->s = copy_subject(subpos, sublen);
1511 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1512 struct strbuf sb = STRBUF_INIT;
1513 format_sanitized_subject(&sb, subpos, sublen);
1514 v->s = strbuf_detach(&sb, NULL);
1515 } else if (atom->u.contents.option == C_BODY_DEP)
1516 v->s = xmemdupz(bodypos, bodylen);
1517 else if (atom->u.contents.option == C_LENGTH)
1518 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1519 else if (atom->u.contents.option == C_BODY)
1520 v->s = xmemdupz(bodypos, nonsiglen);
1521 else if (atom->u.contents.option == C_SIG)
1522 v->s = xmemdupz(sigpos, siglen);
1523 else if (atom->u.contents.option == C_LINES) {
1524 struct strbuf s = STRBUF_INIT;
1525 const char *contents_end = bodypos + nonsiglen;
1527 /* Size is the length of the message after removing the signature */
1528 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1529 v->s = strbuf_detach(&s, NULL);
1530 } else if (atom->u.contents.option == C_TRAILERS) {
1531 struct strbuf s = STRBUF_INIT;
1533 /* Format the trailer info according to the trailer_opts given */
1534 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1536 v->s = strbuf_detach(&s, NULL);
1537 } else if (atom->u.contents.option == C_BARE)
1538 v->s = xstrdup(subpos);
1541 free((void *)sigpos);
1545 * We want to have empty print-string for field requests
1546 * that do not apply (e.g. "authordate" for a tag object)
1548 static void fill_missing_values(struct atom_value *val)
1550 int i;
1551 for (i = 0; i < used_atom_cnt; i++) {
1552 struct atom_value *v = &val[i];
1553 if (!v->s)
1554 v->s = xstrdup("");
1559 * val is a list of atom_value to hold returned values. Extract
1560 * the values for atoms in used_atom array out of (obj, buf, sz).
1561 * when deref is false, (obj, buf, sz) is the object that is
1562 * pointed at by the ref itself; otherwise it is the object the
1563 * ref (which is a tag) refers to.
1565 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1567 void *buf = data->content;
1569 switch (obj->type) {
1570 case OBJ_TAG:
1571 grab_tag_values(val, deref, obj);
1572 grab_sub_body_contents(val, deref, data);
1573 grab_person("tagger", val, deref, buf);
1574 break;
1575 case OBJ_COMMIT:
1576 grab_commit_values(val, deref, obj);
1577 grab_sub_body_contents(val, deref, data);
1578 grab_person("author", val, deref, buf);
1579 grab_person("committer", val, deref, buf);
1580 break;
1581 case OBJ_TREE:
1582 /* grab_tree_values(val, deref, obj, buf, sz); */
1583 grab_sub_body_contents(val, deref, data);
1584 break;
1585 case OBJ_BLOB:
1586 /* grab_blob_values(val, deref, obj, buf, sz); */
1587 grab_sub_body_contents(val, deref, data);
1588 break;
1589 default:
1590 die("Eh? Object of type %d?", obj->type);
1594 static inline char *copy_advance(char *dst, const char *src)
1596 while (*src)
1597 *dst++ = *src++;
1598 return dst;
1601 static const char *lstrip_ref_components(const char *refname, int len)
1603 long remaining = len;
1604 const char *start = xstrdup(refname);
1605 const char *to_free = start;
1607 if (len < 0) {
1608 int i;
1609 const char *p = refname;
1611 /* Find total no of '/' separated path-components */
1612 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1615 * The number of components we need to strip is now
1616 * the total minus the components to be left (Plus one
1617 * because we count the number of '/', but the number
1618 * of components is one more than the no of '/').
1620 remaining = i + len + 1;
1623 while (remaining > 0) {
1624 switch (*start++) {
1625 case '\0':
1626 free((char *)to_free);
1627 return xstrdup("");
1628 case '/':
1629 remaining--;
1630 break;
1634 start = xstrdup(start);
1635 free((char *)to_free);
1636 return start;
1639 static const char *rstrip_ref_components(const char *refname, int len)
1641 long remaining = len;
1642 const char *start = xstrdup(refname);
1643 const char *to_free = start;
1645 if (len < 0) {
1646 int i;
1647 const char *p = refname;
1649 /* Find total no of '/' separated path-components */
1650 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1653 * The number of components we need to strip is now
1654 * the total minus the components to be left (Plus one
1655 * because we count the number of '/', but the number
1656 * of components is one more than the no of '/').
1658 remaining = i + len + 1;
1661 while (remaining-- > 0) {
1662 char *p = strrchr(start, '/');
1663 if (!p) {
1664 free((char *)to_free);
1665 return xstrdup("");
1666 } else
1667 p[0] = '\0';
1669 return start;
1672 static const char *show_ref(struct refname_atom *atom, const char *refname)
1674 if (atom->option == R_SHORT)
1675 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1676 else if (atom->option == R_LSTRIP)
1677 return lstrip_ref_components(refname, atom->lstrip);
1678 else if (atom->option == R_RSTRIP)
1679 return rstrip_ref_components(refname, atom->rstrip);
1680 else
1681 return xstrdup(refname);
1684 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1685 struct branch *branch, const char **s)
1687 int num_ours, num_theirs;
1688 if (atom->u.remote_ref.option == RR_REF)
1689 *s = show_ref(&atom->u.remote_ref.refname, refname);
1690 else if (atom->u.remote_ref.option == RR_TRACK) {
1691 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1692 NULL, atom->u.remote_ref.push,
1693 AHEAD_BEHIND_FULL) < 0) {
1694 *s = xstrdup(msgs.gone);
1695 } else if (!num_ours && !num_theirs)
1696 *s = xstrdup("");
1697 else if (!num_ours)
1698 *s = xstrfmt(msgs.behind, num_theirs);
1699 else if (!num_theirs)
1700 *s = xstrfmt(msgs.ahead, num_ours);
1701 else
1702 *s = xstrfmt(msgs.ahead_behind,
1703 num_ours, num_theirs);
1704 if (!atom->u.remote_ref.nobracket && *s[0]) {
1705 const char *to_free = *s;
1706 *s = xstrfmt("[%s]", *s);
1707 free((void *)to_free);
1709 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1710 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1711 NULL, atom->u.remote_ref.push,
1712 AHEAD_BEHIND_FULL) < 0) {
1713 *s = xstrdup("");
1714 return;
1716 if (!num_ours && !num_theirs)
1717 *s = xstrdup("=");
1718 else if (!num_ours)
1719 *s = xstrdup("<");
1720 else if (!num_theirs)
1721 *s = xstrdup(">");
1722 else
1723 *s = xstrdup("<>");
1724 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1725 int explicit;
1726 const char *remote = atom->u.remote_ref.push ?
1727 pushremote_for_branch(branch, &explicit) :
1728 remote_for_branch(branch, &explicit);
1729 *s = xstrdup(explicit ? remote : "");
1730 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1731 const char *merge;
1733 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1734 *s = xstrdup(merge ? merge : "");
1735 } else
1736 BUG("unhandled RR_* enum");
1739 char *get_head_description(void)
1741 struct strbuf desc = STRBUF_INIT;
1742 struct wt_status_state state;
1743 memset(&state, 0, sizeof(state));
1744 wt_status_get_state(the_repository, &state, 1);
1745 if (state.rebase_in_progress ||
1746 state.rebase_interactive_in_progress) {
1747 if (state.branch)
1748 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1749 state.branch);
1750 else
1751 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1752 state.detached_from);
1753 } else if (state.bisect_in_progress)
1754 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1755 state.branch);
1756 else if (state.detached_from) {
1757 if (state.detached_at)
1758 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1759 state.detached_from);
1760 else
1761 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1762 state.detached_from);
1763 } else
1764 strbuf_addstr(&desc, _("(no branch)"));
1766 wt_status_state_free_buffers(&state);
1768 return strbuf_detach(&desc, NULL);
1771 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1773 if (!ref->symref)
1774 return xstrdup("");
1775 else
1776 return show_ref(&atom->u.refname, ref->symref);
1779 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1781 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1782 return get_head_description();
1783 return show_ref(&atom->u.refname, ref->refname);
1786 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1787 struct expand_data *oi, struct strbuf *err)
1789 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1790 int eaten = 1;
1791 if (oi->info.contentp) {
1792 /* We need to know that to use parse_object_buffer properly */
1793 oi->info.sizep = &oi->size;
1794 oi->info.typep = &oi->type;
1796 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1797 OBJECT_INFO_LOOKUP_REPLACE))
1798 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1799 oid_to_hex(&oi->oid), ref->refname);
1800 if (oi->info.disk_sizep && oi->disk_size < 0)
1801 BUG("Object size is less than zero.");
1803 if (oi->info.contentp) {
1804 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1805 if (!*obj) {
1806 if (!eaten)
1807 free(oi->content);
1808 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1809 oid_to_hex(&oi->oid), ref->refname);
1811 grab_values(ref->value, deref, *obj, oi);
1814 grab_common_values(ref->value, deref, oi);
1815 if (!eaten)
1816 free(oi->content);
1817 return 0;
1820 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1822 int i;
1824 for (i = 0; worktrees[i]; i++) {
1825 if (worktrees[i]->head_ref) {
1826 struct ref_to_worktree_entry *entry;
1827 entry = xmalloc(sizeof(*entry));
1828 entry->wt = worktrees[i];
1829 hashmap_entry_init(&entry->ent,
1830 strhash(worktrees[i]->head_ref));
1832 hashmap_add(map, &entry->ent);
1837 static void lazy_init_worktree_map(void)
1839 if (ref_to_worktree_map.worktrees)
1840 return;
1842 ref_to_worktree_map.worktrees = get_worktrees();
1843 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1844 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1847 static char *get_worktree_path(const struct ref_array_item *ref)
1849 struct hashmap_entry entry, *e;
1850 struct ref_to_worktree_entry *lookup_result;
1852 lazy_init_worktree_map();
1854 hashmap_entry_init(&entry, strhash(ref->refname));
1855 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1857 if (!e)
1858 return xstrdup("");
1860 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1862 return xstrdup(lookup_result->wt->path);
1866 * Parse the object referred by ref, and grab needed value.
1868 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1870 struct object *obj;
1871 int i;
1872 struct object_info empty = OBJECT_INFO_INIT;
1874 CALLOC_ARRAY(ref->value, used_atom_cnt);
1876 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1877 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1878 NULL, NULL);
1879 if (!ref->symref)
1880 ref->symref = xstrdup("");
1883 /* Fill in specials first */
1884 for (i = 0; i < used_atom_cnt; i++) {
1885 struct used_atom *atom = &used_atom[i];
1886 enum atom_type atom_type = atom->atom_type;
1887 const char *name = used_atom[i].name;
1888 struct atom_value *v = &ref->value[i];
1889 int deref = 0;
1890 const char *refname;
1891 struct branch *branch = NULL;
1893 v->s_size = ATOM_SIZE_UNSPECIFIED;
1894 v->handler = append_atom;
1895 v->atom = atom;
1897 if (*name == '*') {
1898 deref = 1;
1899 name++;
1902 if (atom_type == ATOM_REFNAME)
1903 refname = get_refname(atom, ref);
1904 else if (atom_type == ATOM_WORKTREEPATH) {
1905 if (ref->kind == FILTER_REFS_BRANCHES)
1906 v->s = get_worktree_path(ref);
1907 else
1908 v->s = xstrdup("");
1909 continue;
1911 else if (atom_type == ATOM_SYMREF)
1912 refname = get_symref(atom, ref);
1913 else if (atom_type == ATOM_UPSTREAM) {
1914 const char *branch_name;
1915 /* only local branches may have an upstream */
1916 if (!skip_prefix(ref->refname, "refs/heads/",
1917 &branch_name)) {
1918 v->s = xstrdup("");
1919 continue;
1921 branch = branch_get(branch_name);
1923 refname = branch_get_upstream(branch, NULL);
1924 if (refname)
1925 fill_remote_ref_details(atom, refname, branch, &v->s);
1926 else
1927 v->s = xstrdup("");
1928 continue;
1929 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1930 const char *branch_name;
1931 v->s = xstrdup("");
1932 if (!skip_prefix(ref->refname, "refs/heads/",
1933 &branch_name))
1934 continue;
1935 branch = branch_get(branch_name);
1937 if (atom->u.remote_ref.push_remote)
1938 refname = NULL;
1939 else {
1940 refname = branch_get_push(branch, NULL);
1941 if (!refname)
1942 continue;
1944 /* We will definitely re-init v->s on the next line. */
1945 free((char *)v->s);
1946 fill_remote_ref_details(atom, refname, branch, &v->s);
1947 continue;
1948 } else if (atom_type == ATOM_COLOR) {
1949 v->s = xstrdup(atom->u.color);
1950 continue;
1951 } else if (atom_type == ATOM_FLAG) {
1952 char buf[256], *cp = buf;
1953 if (ref->flag & REF_ISSYMREF)
1954 cp = copy_advance(cp, ",symref");
1955 if (ref->flag & REF_ISPACKED)
1956 cp = copy_advance(cp, ",packed");
1957 if (cp == buf)
1958 v->s = xstrdup("");
1959 else {
1960 *cp = '\0';
1961 v->s = xstrdup(buf + 1);
1963 continue;
1964 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1965 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1966 continue;
1967 } else if (atom_type == ATOM_HEAD) {
1968 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1969 v->s = xstrdup("*");
1970 else
1971 v->s = xstrdup(" ");
1972 continue;
1973 } else if (atom_type == ATOM_ALIGN) {
1974 v->handler = align_atom_handler;
1975 v->s = xstrdup("");
1976 continue;
1977 } else if (atom_type == ATOM_END) {
1978 v->handler = end_atom_handler;
1979 v->s = xstrdup("");
1980 continue;
1981 } else if (atom_type == ATOM_IF) {
1982 const char *s;
1983 if (skip_prefix(name, "if:", &s))
1984 v->s = xstrdup(s);
1985 else
1986 v->s = xstrdup("");
1987 v->handler = if_atom_handler;
1988 continue;
1989 } else if (atom_type == ATOM_THEN) {
1990 v->handler = then_atom_handler;
1991 v->s = xstrdup("");
1992 continue;
1993 } else if (atom_type == ATOM_ELSE) {
1994 v->handler = else_atom_handler;
1995 v->s = xstrdup("");
1996 continue;
1997 } else if (atom_type == ATOM_REST) {
1998 if (ref->rest)
1999 v->s = xstrdup(ref->rest);
2000 else
2001 v->s = xstrdup("");
2002 continue;
2003 } else
2004 continue;
2006 if (!deref)
2007 v->s = xstrdup(refname);
2008 else
2009 v->s = xstrfmt("%s^{}", refname);
2010 free((char *)refname);
2013 for (i = 0; i < used_atom_cnt; i++) {
2014 struct atom_value *v = &ref->value[i];
2015 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2016 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2017 oid_to_hex(&ref->objectname), ref->refname);
2020 if (need_tagged)
2021 oi.info.contentp = &oi.content;
2022 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2023 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2024 return 0;
2027 oi.oid = ref->objectname;
2028 if (get_object(ref, 0, &obj, &oi, err))
2029 return -1;
2032 * If there is no atom that wants to know about tagged
2033 * object, we are done.
2035 if (!need_tagged || (obj->type != OBJ_TAG))
2036 return 0;
2039 * If it is a tag object, see if we use a value that derefs
2040 * the object, and if we do grab the object it refers to.
2042 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2045 * NEEDSWORK: This derefs tag only once, which
2046 * is good to deal with chains of trust, but
2047 * is not consistent with what deref_tag() does
2048 * which peels the onion to the core.
2050 return get_object(ref, 1, &obj, &oi_deref, err);
2054 * Given a ref, return the value for the atom. This lazily gets value
2055 * out of the object by calling populate value.
2057 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2058 struct atom_value **v, struct strbuf *err)
2060 if (!ref->value) {
2061 if (populate_value(ref, err))
2062 return -1;
2063 fill_missing_values(ref->value);
2065 *v = &ref->value[atom];
2066 return 0;
2070 * Return 1 if the refname matches one of the patterns, otherwise 0.
2071 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2072 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2073 * matches "refs/heads/mas*", too).
2075 static int match_pattern(const struct ref_filter *filter, const char *refname)
2077 const char **patterns = filter->name_patterns;
2078 unsigned flags = 0;
2080 if (filter->ignore_case)
2081 flags |= WM_CASEFOLD;
2084 * When no '--format' option is given we need to skip the prefix
2085 * for matching refs of tags and branches.
2087 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2088 skip_prefix(refname, "refs/heads/", &refname) ||
2089 skip_prefix(refname, "refs/remotes/", &refname) ||
2090 skip_prefix(refname, "refs/", &refname));
2092 for (; *patterns; patterns++) {
2093 if (!wildmatch(*patterns, refname, flags))
2094 return 1;
2096 return 0;
2100 * Return 1 if the refname matches one of the patterns, otherwise 0.
2101 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2102 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2103 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2105 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2107 const char **pattern = filter->name_patterns;
2108 int namelen = strlen(refname);
2109 unsigned flags = WM_PATHNAME;
2111 if (filter->ignore_case)
2112 flags |= WM_CASEFOLD;
2114 for (; *pattern; pattern++) {
2115 const char *p = *pattern;
2116 int plen = strlen(p);
2118 if ((plen <= namelen) &&
2119 !strncmp(refname, p, plen) &&
2120 (refname[plen] == '\0' ||
2121 refname[plen] == '/' ||
2122 p[plen-1] == '/'))
2123 return 1;
2124 if (!wildmatch(p, refname, flags))
2125 return 1;
2127 return 0;
2130 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2131 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2133 if (!*filter->name_patterns)
2134 return 1; /* No pattern always matches */
2135 if (filter->match_as_path)
2136 return match_name_as_path(filter, refname);
2137 return match_pattern(filter, refname);
2141 * This is the same as for_each_fullref_in(), but it tries to iterate
2142 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2143 * pattern match, so the callback still has to match each ref individually.
2145 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2146 each_ref_fn cb,
2147 void *cb_data)
2149 if (!filter->match_as_path) {
2151 * in this case, the patterns are applied after
2152 * prefixes like "refs/heads/" etc. are stripped off,
2153 * so we have to look at everything:
2155 return for_each_fullref_in("", cb, cb_data);
2158 if (filter->ignore_case) {
2160 * we can't handle case-insensitive comparisons,
2161 * so just return everything and let the caller
2162 * sort it out.
2164 return for_each_fullref_in("", cb, cb_data);
2167 if (!filter->name_patterns[0]) {
2168 /* no patterns; we have to look at everything */
2169 return for_each_fullref_in("", cb, cb_data);
2172 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2173 NULL, filter->name_patterns,
2174 cb, cb_data);
2178 * Given a ref (oid, refname), check if the ref belongs to the array
2179 * of oids. If the given ref is a tag, check if the given tag points
2180 * at one of the oids in the given oid array.
2181 * NEEDSWORK:
2182 * 1. Only a single level of indirection is obtained, we might want to
2183 * change this to account for multiple levels (e.g. annotated tags
2184 * pointing to annotated tags pointing to a commit.)
2185 * 2. As the refs are cached we might know what refname peels to without
2186 * the need to parse the object via parse_object(). peel_ref() might be a
2187 * more efficient alternative to obtain the pointee.
2189 static const struct object_id *match_points_at(struct oid_array *points_at,
2190 const struct object_id *oid,
2191 const char *refname)
2193 const struct object_id *tagged_oid = NULL;
2194 struct object *obj;
2196 if (oid_array_lookup(points_at, oid) >= 0)
2197 return oid;
2198 obj = parse_object(the_repository, oid);
2199 if (!obj)
2200 die(_("malformed object at '%s'"), refname);
2201 if (obj->type == OBJ_TAG)
2202 tagged_oid = get_tagged_oid((struct tag *)obj);
2203 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2204 return tagged_oid;
2205 return NULL;
2209 * Allocate space for a new ref_array_item and copy the name and oid to it.
2211 * Callers can then fill in other struct members at their leisure.
2213 static struct ref_array_item *new_ref_array_item(const char *refname,
2214 const struct object_id *oid)
2216 struct ref_array_item *ref;
2218 FLEX_ALLOC_STR(ref, refname, refname);
2219 oidcpy(&ref->objectname, oid);
2220 ref->rest = NULL;
2222 return ref;
2225 struct ref_array_item *ref_array_push(struct ref_array *array,
2226 const char *refname,
2227 const struct object_id *oid)
2229 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2231 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2232 array->items[array->nr++] = ref;
2234 return ref;
2237 static int ref_kind_from_refname(const char *refname)
2239 unsigned int i;
2241 static struct {
2242 const char *prefix;
2243 unsigned int kind;
2244 } ref_kind[] = {
2245 { "refs/heads/" , FILTER_REFS_BRANCHES },
2246 { "refs/remotes/" , FILTER_REFS_REMOTES },
2247 { "refs/tags/", FILTER_REFS_TAGS}
2250 if (!strcmp(refname, "HEAD"))
2251 return FILTER_REFS_DETACHED_HEAD;
2253 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2254 if (starts_with(refname, ref_kind[i].prefix))
2255 return ref_kind[i].kind;
2258 return FILTER_REFS_OTHERS;
2261 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2263 if (filter->kind == FILTER_REFS_BRANCHES ||
2264 filter->kind == FILTER_REFS_REMOTES ||
2265 filter->kind == FILTER_REFS_TAGS)
2266 return filter->kind;
2267 return ref_kind_from_refname(refname);
2270 struct ref_filter_cbdata {
2271 struct ref_array *array;
2272 struct ref_filter *filter;
2273 struct contains_cache contains_cache;
2274 struct contains_cache no_contains_cache;
2278 * A call-back given to for_each_ref(). Filter refs and keep them for
2279 * later object processing.
2281 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2283 struct ref_filter_cbdata *ref_cbdata = cb_data;
2284 struct ref_filter *filter = ref_cbdata->filter;
2285 struct ref_array_item *ref;
2286 struct commit *commit = NULL;
2287 unsigned int kind;
2289 if (flag & REF_BAD_NAME) {
2290 warning(_("ignoring ref with broken name %s"), refname);
2291 return 0;
2294 if (flag & REF_ISBROKEN) {
2295 warning(_("ignoring broken ref %s"), refname);
2296 return 0;
2299 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2300 kind = filter_ref_kind(filter, refname);
2301 if (!(kind & filter->kind))
2302 return 0;
2304 if (!filter_pattern_match(filter, refname))
2305 return 0;
2307 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2308 return 0;
2311 * A merge filter is applied on refs pointing to commits. Hence
2312 * obtain the commit using the 'oid' available and discard all
2313 * non-commits early. The actual filtering is done later.
2315 if (filter->reachable_from || filter->unreachable_from ||
2316 filter->with_commit || filter->no_commit || filter->verbose) {
2317 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2318 if (!commit)
2319 return 0;
2320 /* We perform the filtering for the '--contains' option... */
2321 if (filter->with_commit &&
2322 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2323 return 0;
2324 /* ...or for the `--no-contains' option */
2325 if (filter->no_commit &&
2326 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2327 return 0;
2331 * We do not open the object yet; sort may only need refname
2332 * to do its job and the resulting list may yet to be pruned
2333 * by maxcount logic.
2335 ref = ref_array_push(ref_cbdata->array, refname, oid);
2336 ref->commit = commit;
2337 ref->flag = flag;
2338 ref->kind = kind;
2340 return 0;
2343 /* Free memory allocated for a ref_array_item */
2344 static void free_array_item(struct ref_array_item *item)
2346 free((char *)item->symref);
2347 if (item->value) {
2348 int i;
2349 for (i = 0; i < used_atom_cnt; i++)
2350 free((char *)item->value[i].s);
2351 free(item->value);
2353 free(item);
2356 /* Free all memory allocated for ref_array */
2357 void ref_array_clear(struct ref_array *array)
2359 int i;
2361 for (i = 0; i < array->nr; i++)
2362 free_array_item(array->items[i]);
2363 FREE_AND_NULL(array->items);
2364 array->nr = array->alloc = 0;
2366 for (i = 0; i < used_atom_cnt; i++) {
2367 struct used_atom *atom = &used_atom[i];
2368 if (atom->atom_type == ATOM_HEAD)
2369 free(atom->u.head);
2370 free((char *)atom->name);
2372 FREE_AND_NULL(used_atom);
2373 used_atom_cnt = 0;
2375 if (ref_to_worktree_map.worktrees) {
2376 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2377 struct ref_to_worktree_entry, ent);
2378 free_worktrees(ref_to_worktree_map.worktrees);
2379 ref_to_worktree_map.worktrees = NULL;
2383 #define EXCLUDE_REACHED 0
2384 #define INCLUDE_REACHED 1
2385 static void reach_filter(struct ref_array *array,
2386 struct commit_list *check_reachable,
2387 int include_reached)
2389 struct rev_info revs;
2390 int i, old_nr;
2391 struct commit **to_clear;
2392 struct commit_list *cr;
2394 if (!check_reachable)
2395 return;
2397 CALLOC_ARRAY(to_clear, array->nr);
2399 repo_init_revisions(the_repository, &revs, NULL);
2401 for (i = 0; i < array->nr; i++) {
2402 struct ref_array_item *item = array->items[i];
2403 add_pending_object(&revs, &item->commit->object, item->refname);
2404 to_clear[i] = item->commit;
2407 for (cr = check_reachable; cr; cr = cr->next) {
2408 struct commit *merge_commit = cr->item;
2409 merge_commit->object.flags |= UNINTERESTING;
2410 add_pending_object(&revs, &merge_commit->object, "");
2413 revs.limited = 1;
2414 if (prepare_revision_walk(&revs))
2415 die(_("revision walk setup failed"));
2417 old_nr = array->nr;
2418 array->nr = 0;
2420 for (i = 0; i < old_nr; i++) {
2421 struct ref_array_item *item = array->items[i];
2422 struct commit *commit = item->commit;
2424 int is_merged = !!(commit->object.flags & UNINTERESTING);
2426 if (is_merged == include_reached)
2427 array->items[array->nr++] = array->items[i];
2428 else
2429 free_array_item(item);
2432 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2434 while (check_reachable) {
2435 struct commit *merge_commit = pop_commit(&check_reachable);
2436 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2439 release_revisions(&revs);
2440 free(to_clear);
2444 * API for filtering a set of refs. Based on the type of refs the user
2445 * has requested, we iterate through those refs and apply filters
2446 * as per the given ref_filter structure and finally store the
2447 * filtered refs in the ref_array structure.
2449 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2451 struct ref_filter_cbdata ref_cbdata;
2452 int save_commit_buffer_orig;
2453 int ret = 0;
2455 ref_cbdata.array = array;
2456 ref_cbdata.filter = filter;
2458 filter->kind = type & FILTER_REFS_KIND_MASK;
2460 save_commit_buffer_orig = save_commit_buffer;
2461 save_commit_buffer = 0;
2463 init_contains_cache(&ref_cbdata.contains_cache);
2464 init_contains_cache(&ref_cbdata.no_contains_cache);
2466 /* Simple per-ref filtering */
2467 if (!filter->kind)
2468 die("filter_refs: invalid type");
2469 else {
2471 * For common cases where we need only branches or remotes or tags,
2472 * we only iterate through those refs. If a mix of refs is needed,
2473 * we iterate over all refs and filter out required refs with the help
2474 * of filter_ref_kind().
2476 if (filter->kind == FILTER_REFS_BRANCHES)
2477 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2478 else if (filter->kind == FILTER_REFS_REMOTES)
2479 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2480 else if (filter->kind == FILTER_REFS_TAGS)
2481 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2482 else if (filter->kind & FILTER_REFS_ALL)
2483 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2484 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2485 head_ref(ref_filter_handler, &ref_cbdata);
2488 clear_contains_cache(&ref_cbdata.contains_cache);
2489 clear_contains_cache(&ref_cbdata.no_contains_cache);
2491 /* Filters that need revision walking */
2492 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2493 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2495 save_commit_buffer = save_commit_buffer_orig;
2496 return ret;
2499 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2501 if (!(a->kind ^ b->kind))
2502 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2503 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2504 return -1;
2505 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2506 return 1;
2507 BUG("should have died in the xor check above");
2508 return 0;
2511 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2513 const char *s1 = vs1, *s2 = vs2;
2514 const char *end = s1 + n;
2516 for (; s1 < end; s1++, s2++) {
2517 int diff = tolower(*s1) - tolower(*s2);
2518 if (diff)
2519 return diff;
2521 return 0;
2524 struct ref_sorting {
2525 struct ref_sorting *next;
2526 int atom; /* index into used_atom array (internal) */
2527 enum ref_sorting_order sort_flags;
2530 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2532 struct atom_value *va, *vb;
2533 int cmp;
2534 int cmp_detached_head = 0;
2535 cmp_type cmp_type = used_atom[s->atom].type;
2536 struct strbuf err = STRBUF_INIT;
2538 if (get_ref_atom_value(a, s->atom, &va, &err))
2539 die("%s", err.buf);
2540 if (get_ref_atom_value(b, s->atom, &vb, &err))
2541 die("%s", err.buf);
2542 strbuf_release(&err);
2543 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2544 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2545 cmp = compare_detached_head(a, b);
2546 cmp_detached_head = 1;
2547 } else if (s->sort_flags & REF_SORTING_VERSION) {
2548 cmp = versioncmp(va->s, vb->s);
2549 } else if (cmp_type == FIELD_STR) {
2550 if (va->s_size < 0 && vb->s_size < 0) {
2551 int (*cmp_fn)(const char *, const char *);
2552 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2553 ? strcasecmp : strcmp;
2554 cmp = cmp_fn(va->s, vb->s);
2555 } else {
2556 size_t a_size = va->s_size < 0 ?
2557 strlen(va->s) : va->s_size;
2558 size_t b_size = vb->s_size < 0 ?
2559 strlen(vb->s) : vb->s_size;
2560 int (*cmp_fn)(const void *, const void *, size_t);
2561 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2562 ? memcasecmp : memcmp;
2564 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2565 a_size : b_size);
2566 if (!cmp) {
2567 if (a_size > b_size)
2568 cmp = 1;
2569 else if (a_size < b_size)
2570 cmp = -1;
2573 } else {
2574 if (va->value < vb->value)
2575 cmp = -1;
2576 else if (va->value == vb->value)
2577 cmp = 0;
2578 else
2579 cmp = 1;
2582 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2583 ? -cmp : cmp;
2586 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2588 struct ref_array_item *a = *((struct ref_array_item **)a_);
2589 struct ref_array_item *b = *((struct ref_array_item **)b_);
2590 struct ref_sorting *s;
2592 for (s = ref_sorting; s; s = s->next) {
2593 int cmp = cmp_ref_sorting(s, a, b);
2594 if (cmp)
2595 return cmp;
2597 s = ref_sorting;
2598 return s && s->sort_flags & REF_SORTING_ICASE ?
2599 strcasecmp(a->refname, b->refname) :
2600 strcmp(a->refname, b->refname);
2603 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2604 unsigned int mask, int on)
2606 for (; sorting; sorting = sorting->next) {
2607 if (on)
2608 sorting->sort_flags |= mask;
2609 else
2610 sorting->sort_flags &= ~mask;
2614 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2616 QSORT_S(array->items, array->nr, compare_refs, sorting);
2619 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2621 struct strbuf *s = &state->stack->output;
2623 while (*cp && (!ep || cp < ep)) {
2624 if (*cp == '%') {
2625 if (cp[1] == '%')
2626 cp++;
2627 else {
2628 int ch = hex2chr(cp + 1);
2629 if (0 <= ch) {
2630 strbuf_addch(s, ch);
2631 cp += 3;
2632 continue;
2636 strbuf_addch(s, *cp);
2637 cp++;
2641 int format_ref_array_item(struct ref_array_item *info,
2642 struct ref_format *format,
2643 struct strbuf *final_buf,
2644 struct strbuf *error_buf)
2646 const char *cp, *sp, *ep;
2647 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2649 state.quote_style = format->quote_style;
2650 push_stack_element(&state.stack);
2652 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2653 struct atom_value *atomv;
2654 int pos;
2656 ep = strchr(sp, ')');
2657 if (cp < sp)
2658 append_literal(cp, sp, &state);
2659 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2660 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2661 atomv->handler(atomv, &state, error_buf)) {
2662 pop_stack_element(&state.stack);
2663 return -1;
2666 if (*cp) {
2667 sp = cp + strlen(cp);
2668 append_literal(cp, sp, &state);
2670 if (format->need_color_reset_at_eol) {
2671 struct atom_value resetv = ATOM_VALUE_INIT;
2672 resetv.s = GIT_COLOR_RESET;
2673 if (append_atom(&resetv, &state, error_buf)) {
2674 pop_stack_element(&state.stack);
2675 return -1;
2678 if (state.stack->prev) {
2679 pop_stack_element(&state.stack);
2680 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2682 strbuf_addbuf(final_buf, &state.stack->output);
2683 pop_stack_element(&state.stack);
2684 return 0;
2687 void pretty_print_ref(const char *name, const struct object_id *oid,
2688 struct ref_format *format)
2690 struct ref_array_item *ref_item;
2691 struct strbuf output = STRBUF_INIT;
2692 struct strbuf err = STRBUF_INIT;
2694 ref_item = new_ref_array_item(name, oid);
2695 ref_item->kind = ref_kind_from_refname(name);
2696 if (format_ref_array_item(ref_item, format, &output, &err))
2697 die("%s", err.buf);
2698 fwrite(output.buf, 1, output.len, stdout);
2699 putchar('\n');
2701 strbuf_release(&err);
2702 strbuf_release(&output);
2703 free_array_item(ref_item);
2706 static int parse_sorting_atom(const char *atom)
2709 * This parses an atom using a dummy ref_format, since we don't
2710 * actually care about the formatting details.
2712 struct ref_format dummy = REF_FORMAT_INIT;
2713 const char *end = atom + strlen(atom);
2714 struct strbuf err = STRBUF_INIT;
2715 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2716 if (res < 0)
2717 die("%s", err.buf);
2718 strbuf_release(&err);
2719 return res;
2722 /* If no sorting option is given, use refname to sort as default */
2723 static struct ref_sorting *ref_default_sorting(void)
2725 static const char cstr_name[] = "refname";
2727 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2729 sorting->next = NULL;
2730 sorting->atom = parse_sorting_atom(cstr_name);
2731 return sorting;
2734 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2736 struct ref_sorting *s;
2738 CALLOC_ARRAY(s, 1);
2739 s->next = *sorting_tail;
2740 *sorting_tail = s;
2742 if (*arg == '-') {
2743 s->sort_flags |= REF_SORTING_REVERSE;
2744 arg++;
2746 if (skip_prefix(arg, "version:", &arg) ||
2747 skip_prefix(arg, "v:", &arg))
2748 s->sort_flags |= REF_SORTING_VERSION;
2749 s->atom = parse_sorting_atom(arg);
2752 struct ref_sorting *ref_sorting_options(struct string_list *options)
2754 struct string_list_item *item;
2755 struct ref_sorting *sorting = NULL, **tail = &sorting;
2757 if (!options->nr) {
2758 sorting = ref_default_sorting();
2759 } else {
2760 for_each_string_list_item(item, options)
2761 parse_ref_sorting(tail, item->string);
2765 * From here on, the ref_sorting list should be used to talk
2766 * about the sort order used for the output. The caller
2767 * should not touch the string form anymore.
2769 string_list_clear(options, 0);
2770 return sorting;
2773 void ref_sorting_release(struct ref_sorting *sorting)
2775 while (sorting) {
2776 struct ref_sorting *next = sorting->next;
2777 free(sorting);
2778 sorting = next;
2782 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2784 struct ref_filter *rf = opt->value;
2785 struct object_id oid;
2786 struct commit *merge_commit;
2788 BUG_ON_OPT_NEG(unset);
2790 if (repo_get_oid(the_repository, arg, &oid))
2791 die(_("malformed object name %s"), arg);
2793 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2795 if (!merge_commit)
2796 return error(_("option `%s' must point to a commit"), opt->long_name);
2798 if (starts_with(opt->long_name, "no"))
2799 commit_list_insert(merge_commit, &rf->unreachable_from);
2800 else
2801 commit_list_insert(merge_commit, &rf->reachable_from);
2803 return 0;