Merge branch 'rj/bisect-already-used-branch'
[git/debian.git] / ref-filter.c
blobed802778da7208377d9054f2de1805f91be39509
1 #include "git-compat-util.h"
2 #include "alloc.h"
3 #include "hex.h"
4 #include "parse-options.h"
5 #include "refs.h"
6 #include "wildmatch.h"
7 #include "object-store.h"
8 #include "repository.h"
9 #include "commit.h"
10 #include "remote.h"
11 #include "color.h"
12 #include "tag.h"
13 #include "quote.h"
14 #include "ref-filter.h"
15 #include "revision.h"
16 #include "utf8.h"
17 #include "version.h"
18 #include "trailer.h"
19 #include "wt-status.h"
20 #include "commit-slab.h"
21 #include "commit-graph.h"
22 #include "commit-reach.h"
23 #include "worktree.h"
24 #include "hashmap.h"
25 #include "strvec.h"
27 static struct ref_msg {
28 const char *gone;
29 const char *ahead;
30 const char *behind;
31 const char *ahead_behind;
32 } msgs = {
33 /* Untranslated plumbing messages: */
34 "gone",
35 "ahead %d",
36 "behind %d",
37 "ahead %d, behind %d"
40 void setup_ref_filter_porcelain_msg(void)
42 msgs.gone = _("gone");
43 msgs.ahead = _("ahead %d");
44 msgs.behind = _("behind %d");
45 msgs.ahead_behind = _("ahead %d, behind %d");
48 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
49 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
50 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
52 struct align {
53 align_type position;
54 unsigned int width;
57 struct if_then_else {
58 cmp_status cmp_status;
59 const char *str;
60 unsigned int then_atom_seen : 1,
61 else_atom_seen : 1,
62 condition_satisfied : 1;
65 struct refname_atom {
66 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
67 int lstrip, rstrip;
70 static struct ref_trailer_buf {
71 struct string_list filter_list;
72 struct strbuf sepbuf;
73 struct strbuf kvsepbuf;
74 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
76 static struct expand_data {
77 struct object_id oid;
78 enum object_type type;
79 unsigned long size;
80 off_t disk_size;
81 struct object_id delta_base_oid;
82 void *content;
84 struct object_info info;
85 } oi, oi_deref;
87 struct ref_to_worktree_entry {
88 struct hashmap_entry ent;
89 struct worktree *wt; /* key is wt->head_ref */
92 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
93 const struct hashmap_entry *eptr,
94 const struct hashmap_entry *kptr,
95 const void *keydata_aka_refname)
97 const struct ref_to_worktree_entry *e, *k;
99 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
100 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
102 return strcmp(e->wt->head_ref,
103 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
106 static struct ref_to_worktree_map {
107 struct hashmap map;
108 struct worktree **worktrees;
109 } ref_to_worktree_map;
112 * The enum atom_type is used as the index of valid_atom array.
113 * In the atom parsing stage, it will be passed to used_atom.atom_type
114 * as the identifier of the atom type. We can check the type of used_atom
115 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
117 enum atom_type {
118 ATOM_REFNAME,
119 ATOM_OBJECTTYPE,
120 ATOM_OBJECTSIZE,
121 ATOM_OBJECTNAME,
122 ATOM_DELTABASE,
123 ATOM_TREE,
124 ATOM_PARENT,
125 ATOM_NUMPARENT,
126 ATOM_OBJECT,
127 ATOM_TYPE,
128 ATOM_TAG,
129 ATOM_AUTHOR,
130 ATOM_AUTHORNAME,
131 ATOM_AUTHOREMAIL,
132 ATOM_AUTHORDATE,
133 ATOM_COMMITTER,
134 ATOM_COMMITTERNAME,
135 ATOM_COMMITTEREMAIL,
136 ATOM_COMMITTERDATE,
137 ATOM_TAGGER,
138 ATOM_TAGGERNAME,
139 ATOM_TAGGEREMAIL,
140 ATOM_TAGGERDATE,
141 ATOM_CREATOR,
142 ATOM_CREATORDATE,
143 ATOM_SUBJECT,
144 ATOM_BODY,
145 ATOM_TRAILERS,
146 ATOM_CONTENTS,
147 ATOM_RAW,
148 ATOM_UPSTREAM,
149 ATOM_PUSH,
150 ATOM_SYMREF,
151 ATOM_FLAG,
152 ATOM_HEAD,
153 ATOM_COLOR,
154 ATOM_WORKTREEPATH,
155 ATOM_ALIGN,
156 ATOM_END,
157 ATOM_IF,
158 ATOM_THEN,
159 ATOM_ELSE,
160 ATOM_REST,
164 * An atom is a valid field atom listed below, possibly prefixed with
165 * a "*" to denote deref_tag().
167 * We parse given format string and sort specifiers, and make a list
168 * of properties that we need to extract out of objects. ref_array_item
169 * structure will hold an array of values extracted that can be
170 * indexed with the "atom number", which is an index into this
171 * array.
173 static struct used_atom {
174 enum atom_type atom_type;
175 const char *name;
176 cmp_type type;
177 info_source source;
178 union {
179 char color[COLOR_MAXLEN];
180 struct align align;
181 struct {
182 enum {
183 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
184 } option;
185 struct refname_atom refname;
186 unsigned int nobracket : 1, push : 1, push_remote : 1;
187 } remote_ref;
188 struct {
189 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
190 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
191 struct process_trailer_options trailer_opts;
192 unsigned int nlines;
193 } contents;
194 struct {
195 enum { RAW_BARE, RAW_LENGTH } option;
196 } raw_data;
197 struct {
198 cmp_status cmp_status;
199 const char *str;
200 } if_then_else;
201 struct {
202 enum { O_FULL, O_LENGTH, O_SHORT } option;
203 unsigned int length;
204 } oid;
205 struct {
206 enum { O_SIZE, O_SIZE_DISK } option;
207 } objectsize;
208 struct email_option {
209 enum { EO_RAW, EO_TRIM, EO_LOCALPART } option;
210 } email_option;
211 struct refname_atom refname;
212 char *head;
213 } u;
214 } *used_atom;
215 static int used_atom_cnt, need_tagged, need_symref;
218 * Expand string, append it to strbuf *sb, then return error code ret.
219 * Allow to save few lines of code.
221 __attribute__((format (printf, 3, 4)))
222 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
224 va_list ap;
225 va_start(ap, fmt);
226 strbuf_vaddf(sb, fmt, ap);
227 va_end(ap);
228 return ret;
231 static int err_no_arg(struct strbuf *sb, const char *name)
233 size_t namelen = strchrnul(name, ':') - name;
234 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
235 (int)namelen, name);
236 return -1;
239 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
241 size_t namelen = strchrnul(name, ':') - name;
242 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
243 (int)namelen, name, arg);
244 return -1;
247 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
248 const char *color_value, struct strbuf *err)
250 if (!color_value)
251 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
252 if (color_parse(color_value, atom->u.color) < 0)
253 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
254 color_value);
256 * We check this after we've parsed the color, which lets us complain
257 * about syntactically bogus color names even if they won't be used.
259 if (!want_color(format->use_color))
260 color_parse("", atom->u.color);
261 return 0;
264 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
265 const char *name, struct strbuf *err)
267 if (!arg)
268 atom->option = R_NORMAL;
269 else if (!strcmp(arg, "short"))
270 atom->option = R_SHORT;
271 else if (skip_prefix(arg, "lstrip=", &arg) ||
272 skip_prefix(arg, "strip=", &arg)) {
273 atom->option = R_LSTRIP;
274 if (strtol_i(arg, 10, &atom->lstrip))
275 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
276 } else if (skip_prefix(arg, "rstrip=", &arg)) {
277 atom->option = R_RSTRIP;
278 if (strtol_i(arg, 10, &atom->rstrip))
279 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
280 } else
281 return err_bad_arg(err, name, arg);
282 return 0;
285 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
286 struct used_atom *atom,
287 const char *arg, struct strbuf *err)
289 struct string_list params = STRING_LIST_INIT_DUP;
290 int i;
292 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
293 atom->u.remote_ref.push = 1;
295 if (!arg) {
296 atom->u.remote_ref.option = RR_REF;
297 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
298 arg, atom->name, err);
301 atom->u.remote_ref.nobracket = 0;
302 string_list_split(&params, arg, ',', -1);
304 for (i = 0; i < params.nr; i++) {
305 const char *s = params.items[i].string;
307 if (!strcmp(s, "track"))
308 atom->u.remote_ref.option = RR_TRACK;
309 else if (!strcmp(s, "trackshort"))
310 atom->u.remote_ref.option = RR_TRACKSHORT;
311 else if (!strcmp(s, "nobracket"))
312 atom->u.remote_ref.nobracket = 1;
313 else if (!strcmp(s, "remotename")) {
314 atom->u.remote_ref.option = RR_REMOTE_NAME;
315 atom->u.remote_ref.push_remote = 1;
316 } else if (!strcmp(s, "remoteref")) {
317 atom->u.remote_ref.option = RR_REMOTE_REF;
318 atom->u.remote_ref.push_remote = 1;
319 } else {
320 atom->u.remote_ref.option = RR_REF;
321 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
322 arg, atom->name, err)) {
323 string_list_clear(&params, 0);
324 return -1;
329 string_list_clear(&params, 0);
330 return 0;
333 static int objecttype_atom_parser(struct ref_format *format UNUSED,
334 struct used_atom *atom,
335 const char *arg, struct strbuf *err)
337 if (arg)
338 return err_no_arg(err, "objecttype");
339 if (*atom->name == '*')
340 oi_deref.info.typep = &oi_deref.type;
341 else
342 oi.info.typep = &oi.type;
343 return 0;
346 static int objectsize_atom_parser(struct ref_format *format UNUSED,
347 struct used_atom *atom,
348 const char *arg, struct strbuf *err)
350 if (!arg) {
351 atom->u.objectsize.option = O_SIZE;
352 if (*atom->name == '*')
353 oi_deref.info.sizep = &oi_deref.size;
354 else
355 oi.info.sizep = &oi.size;
356 } else if (!strcmp(arg, "disk")) {
357 atom->u.objectsize.option = O_SIZE_DISK;
358 if (*atom->name == '*')
359 oi_deref.info.disk_sizep = &oi_deref.disk_size;
360 else
361 oi.info.disk_sizep = &oi.disk_size;
362 } else
363 return err_bad_arg(err, "objectsize", arg);
364 return 0;
367 static int deltabase_atom_parser(struct ref_format *format UNUSED,
368 struct used_atom *atom,
369 const char *arg, struct strbuf *err)
371 if (arg)
372 return err_no_arg(err, "deltabase");
373 if (*atom->name == '*')
374 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
375 else
376 oi.info.delta_base_oid = &oi.delta_base_oid;
377 return 0;
380 static int body_atom_parser(struct ref_format *format UNUSED,
381 struct used_atom *atom,
382 const char *arg, struct strbuf *err)
384 if (arg)
385 return err_no_arg(err, "body");
386 atom->u.contents.option = C_BODY_DEP;
387 return 0;
390 static int subject_atom_parser(struct ref_format *format UNUSED,
391 struct used_atom *atom,
392 const char *arg, struct strbuf *err)
394 if (!arg)
395 atom->u.contents.option = C_SUB;
396 else if (!strcmp(arg, "sanitize"))
397 atom->u.contents.option = C_SUB_SANITIZE;
398 else
399 return err_bad_arg(err, "subject", arg);
400 return 0;
403 static int trailers_atom_parser(struct ref_format *format UNUSED,
404 struct used_atom *atom,
405 const char *arg, struct strbuf *err)
407 atom->u.contents.trailer_opts.no_divider = 1;
409 if (arg) {
410 const char *argbuf = xstrfmt("%s)", arg);
411 char *invalid_arg = NULL;
413 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
414 &ref_trailer_buf.filter_list,
415 &ref_trailer_buf.sepbuf,
416 &ref_trailer_buf.kvsepbuf,
417 &argbuf, &invalid_arg)) {
418 if (!invalid_arg)
419 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
420 else
421 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
422 free((char *)invalid_arg);
423 return -1;
426 atom->u.contents.option = C_TRAILERS;
427 return 0;
430 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
431 const char *arg, struct strbuf *err)
433 if (!arg)
434 atom->u.contents.option = C_BARE;
435 else if (!strcmp(arg, "body"))
436 atom->u.contents.option = C_BODY;
437 else if (!strcmp(arg, "size"))
438 atom->u.contents.option = C_LENGTH;
439 else if (!strcmp(arg, "signature"))
440 atom->u.contents.option = C_SIG;
441 else if (!strcmp(arg, "subject"))
442 atom->u.contents.option = C_SUB;
443 else if (!strcmp(arg, "trailers")) {
444 if (trailers_atom_parser(format, atom, NULL, err))
445 return -1;
446 } else if (skip_prefix(arg, "trailers:", &arg)) {
447 if (trailers_atom_parser(format, atom, arg, err))
448 return -1;
449 } else if (skip_prefix(arg, "lines=", &arg)) {
450 atom->u.contents.option = C_LINES;
451 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
452 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
453 } else
454 return err_bad_arg(err, "contents", arg);
455 return 0;
458 static int raw_atom_parser(struct ref_format *format UNUSED,
459 struct used_atom *atom,
460 const char *arg, struct strbuf *err)
462 if (!arg)
463 atom->u.raw_data.option = RAW_BARE;
464 else if (!strcmp(arg, "size"))
465 atom->u.raw_data.option = RAW_LENGTH;
466 else
467 return err_bad_arg(err, "raw", arg);
468 return 0;
471 static int oid_atom_parser(struct ref_format *format UNUSED,
472 struct used_atom *atom,
473 const char *arg, struct strbuf *err)
475 if (!arg)
476 atom->u.oid.option = O_FULL;
477 else if (!strcmp(arg, "short"))
478 atom->u.oid.option = O_SHORT;
479 else if (skip_prefix(arg, "short=", &arg)) {
480 atom->u.oid.option = O_LENGTH;
481 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
482 atom->u.oid.length == 0)
483 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
484 if (atom->u.oid.length < MINIMUM_ABBREV)
485 atom->u.oid.length = MINIMUM_ABBREV;
486 } else
487 return err_bad_arg(err, atom->name, arg);
488 return 0;
491 static int person_email_atom_parser(struct ref_format *format UNUSED,
492 struct used_atom *atom,
493 const char *arg, struct strbuf *err)
495 if (!arg)
496 atom->u.email_option.option = EO_RAW;
497 else if (!strcmp(arg, "trim"))
498 atom->u.email_option.option = EO_TRIM;
499 else if (!strcmp(arg, "localpart"))
500 atom->u.email_option.option = EO_LOCALPART;
501 else
502 return err_bad_arg(err, atom->name, arg);
503 return 0;
506 static int refname_atom_parser(struct ref_format *format UNUSED,
507 struct used_atom *atom,
508 const char *arg, struct strbuf *err)
510 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
513 static align_type parse_align_position(const char *s)
515 if (!strcmp(s, "right"))
516 return ALIGN_RIGHT;
517 else if (!strcmp(s, "middle"))
518 return ALIGN_MIDDLE;
519 else if (!strcmp(s, "left"))
520 return ALIGN_LEFT;
521 return -1;
524 static int align_atom_parser(struct ref_format *format UNUSED,
525 struct used_atom *atom,
526 const char *arg, struct strbuf *err)
528 struct align *align = &atom->u.align;
529 struct string_list params = STRING_LIST_INIT_DUP;
530 int i;
531 unsigned int width = ~0U;
533 if (!arg)
534 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
536 align->position = ALIGN_LEFT;
538 string_list_split(&params, arg, ',', -1);
539 for (i = 0; i < params.nr; i++) {
540 const char *s = params.items[i].string;
541 int position;
543 if (skip_prefix(s, "position=", &s)) {
544 position = parse_align_position(s);
545 if (position < 0) {
546 strbuf_addf(err, _("unrecognized position:%s"), s);
547 string_list_clear(&params, 0);
548 return -1;
550 align->position = position;
551 } else if (skip_prefix(s, "width=", &s)) {
552 if (strtoul_ui(s, 10, &width)) {
553 strbuf_addf(err, _("unrecognized width:%s"), s);
554 string_list_clear(&params, 0);
555 return -1;
557 } else if (!strtoul_ui(s, 10, &width))
559 else if ((position = parse_align_position(s)) >= 0)
560 align->position = position;
561 else {
562 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
563 string_list_clear(&params, 0);
564 return -1;
568 if (width == ~0U) {
569 string_list_clear(&params, 0);
570 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
572 align->width = width;
573 string_list_clear(&params, 0);
574 return 0;
577 static int if_atom_parser(struct ref_format *format UNUSED,
578 struct used_atom *atom,
579 const char *arg, struct strbuf *err)
581 if (!arg) {
582 atom->u.if_then_else.cmp_status = COMPARE_NONE;
583 return 0;
584 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
585 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
586 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
587 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
588 } else
589 return err_bad_arg(err, "if", arg);
590 return 0;
593 static int rest_atom_parser(struct ref_format *format,
594 struct used_atom *atom UNUSED,
595 const char *arg, struct strbuf *err)
597 if (arg)
598 return err_no_arg(err, "rest");
599 format->use_rest = 1;
600 return 0;
603 static int head_atom_parser(struct ref_format *format UNUSED,
604 struct used_atom *atom,
605 const char *arg, struct strbuf *err)
607 if (arg)
608 return err_no_arg(err, "HEAD");
609 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
610 return 0;
613 static struct {
614 const char *name;
615 info_source source;
616 cmp_type cmp_type;
617 int (*parser)(struct ref_format *format, struct used_atom *atom,
618 const char *arg, struct strbuf *err);
619 } valid_atom[] = {
620 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
621 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
622 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
623 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
624 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
625 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
626 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
627 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
628 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
629 [ATOM_TYPE] = { "type", SOURCE_OBJ },
630 [ATOM_TAG] = { "tag", SOURCE_OBJ },
631 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
632 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
633 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
634 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
635 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
636 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
637 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
638 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
639 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
640 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
641 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
642 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
643 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
644 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
645 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
646 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
647 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
648 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
649 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
650 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
651 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
652 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
653 [ATOM_FLAG] = { "flag", SOURCE_NONE },
654 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
655 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
656 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
657 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
658 [ATOM_END] = { "end", SOURCE_NONE },
659 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
660 [ATOM_THEN] = { "then", SOURCE_NONE },
661 [ATOM_ELSE] = { "else", SOURCE_NONE },
662 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
664 * Please update $__git_ref_fieldlist in git-completion.bash
665 * when you add new atoms
669 #define REF_FORMATTING_STATE_INIT { 0 }
671 struct ref_formatting_stack {
672 struct ref_formatting_stack *prev;
673 struct strbuf output;
674 void (*at_end)(struct ref_formatting_stack **stack);
675 void *at_end_data;
678 struct ref_formatting_state {
679 int quote_style;
680 struct ref_formatting_stack *stack;
683 struct atom_value {
684 const char *s;
685 ssize_t s_size;
686 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
687 struct strbuf *err);
688 uintmax_t value; /* used for sorting when not FIELD_STR */
689 struct used_atom *atom;
692 #define ATOM_SIZE_UNSPECIFIED (-1)
694 #define ATOM_VALUE_INIT { \
695 .s_size = ATOM_SIZE_UNSPECIFIED \
699 * Used to parse format string and sort specifiers
701 static int parse_ref_filter_atom(struct ref_format *format,
702 const char *atom, const char *ep,
703 struct strbuf *err)
705 const char *sp;
706 const char *arg;
707 int i, at, atom_len;
709 sp = atom;
710 if (*sp == '*' && sp < ep)
711 sp++; /* deref */
712 if (ep <= sp)
713 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
714 (int)(ep-atom), atom);
717 * If the atom name has a colon, strip it and everything after
718 * it off - it specifies the format for this entry, and
719 * shouldn't be used for checking against the valid_atom
720 * table.
722 arg = memchr(sp, ':', ep - sp);
723 atom_len = (arg ? arg : ep) - sp;
725 /* Do we have the atom already used elsewhere? */
726 for (i = 0; i < used_atom_cnt; i++) {
727 int len = strlen(used_atom[i].name);
728 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
729 return i;
732 /* Is the atom a valid one? */
733 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
734 int len = strlen(valid_atom[i].name);
735 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
736 break;
739 if (ARRAY_SIZE(valid_atom) <= i)
740 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
741 (int)(ep-atom), atom);
742 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
743 return strbuf_addf_ret(err, -1,
744 _("not a git repository, but the field '%.*s' requires access to object data"),
745 (int)(ep-atom), atom);
747 /* Add it in, including the deref prefix */
748 at = used_atom_cnt;
749 used_atom_cnt++;
750 REALLOC_ARRAY(used_atom, used_atom_cnt);
751 used_atom[at].atom_type = i;
752 used_atom[at].name = xmemdupz(atom, ep - atom);
753 used_atom[at].type = valid_atom[i].cmp_type;
754 used_atom[at].source = valid_atom[i].source;
755 if (used_atom[at].source == SOURCE_OBJ) {
756 if (*atom == '*')
757 oi_deref.info.contentp = &oi_deref.content;
758 else
759 oi.info.contentp = &oi.content;
761 if (arg) {
762 arg = used_atom[at].name + (arg - atom) + 1;
763 if (!*arg) {
765 * Treat empty sub-arguments list as NULL (i.e.,
766 * "%(atom:)" is equivalent to "%(atom)").
768 arg = NULL;
771 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
772 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
773 return -1;
774 if (*atom == '*')
775 need_tagged = 1;
776 if (i == ATOM_SYMREF)
777 need_symref = 1;
778 return at;
781 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
783 switch (quote_style) {
784 case QUOTE_NONE:
785 if (len < 0)
786 strbuf_addstr(s, str);
787 else
788 strbuf_add(s, str, len);
789 break;
790 case QUOTE_SHELL:
791 sq_quote_buf(s, str);
792 break;
793 case QUOTE_PERL:
794 if (len < 0)
795 perl_quote_buf(s, str);
796 else
797 perl_quote_buf_with_len(s, str, len);
798 break;
799 case QUOTE_PYTHON:
800 python_quote_buf(s, str);
801 break;
802 case QUOTE_TCL:
803 tcl_quote_buf(s, str);
804 break;
808 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
809 struct strbuf *err UNUSED)
812 * Quote formatting is only done when the stack has a single
813 * element. Otherwise quote formatting is done on the
814 * element's entire output strbuf when the %(end) atom is
815 * encountered.
817 if (!state->stack->prev)
818 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
819 else if (v->s_size < 0)
820 strbuf_addstr(&state->stack->output, v->s);
821 else
822 strbuf_add(&state->stack->output, v->s, v->s_size);
823 return 0;
826 static void push_stack_element(struct ref_formatting_stack **stack)
828 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
830 strbuf_init(&s->output, 0);
831 s->prev = *stack;
832 *stack = s;
835 static void pop_stack_element(struct ref_formatting_stack **stack)
837 struct ref_formatting_stack *current = *stack;
838 struct ref_formatting_stack *prev = current->prev;
840 if (prev)
841 strbuf_addbuf(&prev->output, &current->output);
842 strbuf_release(&current->output);
843 free(current);
844 *stack = prev;
847 static void end_align_handler(struct ref_formatting_stack **stack)
849 struct ref_formatting_stack *cur = *stack;
850 struct align *align = (struct align *)cur->at_end_data;
851 struct strbuf s = STRBUF_INIT;
853 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
854 strbuf_swap(&cur->output, &s);
855 strbuf_release(&s);
858 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
859 struct strbuf *err UNUSED)
861 struct ref_formatting_stack *new_stack;
863 push_stack_element(&state->stack);
864 new_stack = state->stack;
865 new_stack->at_end = end_align_handler;
866 new_stack->at_end_data = &atomv->atom->u.align;
867 return 0;
870 static void if_then_else_handler(struct ref_formatting_stack **stack)
872 struct ref_formatting_stack *cur = *stack;
873 struct ref_formatting_stack *prev = cur->prev;
874 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
876 if (!if_then_else->then_atom_seen)
877 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
879 if (if_then_else->else_atom_seen) {
881 * There is an %(else) atom: we need to drop one state from the
882 * stack, either the %(else) branch if the condition is satisfied, or
883 * the %(then) branch if it isn't.
885 if (if_then_else->condition_satisfied) {
886 strbuf_reset(&cur->output);
887 pop_stack_element(&cur);
888 } else {
889 strbuf_swap(&cur->output, &prev->output);
890 strbuf_reset(&cur->output);
891 pop_stack_element(&cur);
893 } else if (!if_then_else->condition_satisfied) {
895 * No %(else) atom: just drop the %(then) branch if the
896 * condition is not satisfied.
898 strbuf_reset(&cur->output);
901 *stack = cur;
902 free(if_then_else);
905 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
906 struct strbuf *err UNUSED)
908 struct ref_formatting_stack *new_stack;
909 struct if_then_else *if_then_else = xcalloc(1,
910 sizeof(struct if_then_else));
912 if_then_else->str = atomv->atom->u.if_then_else.str;
913 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
915 push_stack_element(&state->stack);
916 new_stack = state->stack;
917 new_stack->at_end = if_then_else_handler;
918 new_stack->at_end_data = if_then_else;
919 return 0;
922 static int is_empty(struct strbuf *buf)
924 const char *cur = buf->buf;
925 const char *end = buf->buf + buf->len;
927 while (cur != end && (isspace(*cur)))
928 cur++;
930 return cur == end;
933 static int then_atom_handler(struct atom_value *atomv UNUSED,
934 struct ref_formatting_state *state,
935 struct strbuf *err)
937 struct ref_formatting_stack *cur = state->stack;
938 struct if_then_else *if_then_else = NULL;
939 size_t str_len = 0;
941 if (cur->at_end == if_then_else_handler)
942 if_then_else = (struct if_then_else *)cur->at_end_data;
943 if (!if_then_else)
944 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
945 if (if_then_else->then_atom_seen)
946 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
947 if (if_then_else->else_atom_seen)
948 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
949 if_then_else->then_atom_seen = 1;
950 if (if_then_else->str)
951 str_len = strlen(if_then_else->str);
953 * If the 'equals' or 'notequals' attribute is used then
954 * perform the required comparison. If not, only non-empty
955 * strings satisfy the 'if' condition.
957 if (if_then_else->cmp_status == COMPARE_EQUAL) {
958 if (str_len == cur->output.len &&
959 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
960 if_then_else->condition_satisfied = 1;
961 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
962 if (str_len != cur->output.len ||
963 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
964 if_then_else->condition_satisfied = 1;
965 } else if (cur->output.len && !is_empty(&cur->output))
966 if_then_else->condition_satisfied = 1;
967 strbuf_reset(&cur->output);
968 return 0;
971 static int else_atom_handler(struct atom_value *atomv UNUSED,
972 struct ref_formatting_state *state,
973 struct strbuf *err)
975 struct ref_formatting_stack *prev = state->stack;
976 struct if_then_else *if_then_else = NULL;
978 if (prev->at_end == if_then_else_handler)
979 if_then_else = (struct if_then_else *)prev->at_end_data;
980 if (!if_then_else)
981 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
982 if (!if_then_else->then_atom_seen)
983 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
984 if (if_then_else->else_atom_seen)
985 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
986 if_then_else->else_atom_seen = 1;
987 push_stack_element(&state->stack);
988 state->stack->at_end_data = prev->at_end_data;
989 state->stack->at_end = prev->at_end;
990 return 0;
993 static int end_atom_handler(struct atom_value *atomv UNUSED,
994 struct ref_formatting_state *state,
995 struct strbuf *err)
997 struct ref_formatting_stack *current = state->stack;
998 struct strbuf s = STRBUF_INIT;
1000 if (!current->at_end)
1001 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1002 current->at_end(&state->stack);
1004 /* Stack may have been popped within at_end(), hence reset the current pointer */
1005 current = state->stack;
1008 * Perform quote formatting when the stack element is that of
1009 * a supporting atom. If nested then perform quote formatting
1010 * only on the topmost supporting atom.
1012 if (!current->prev->prev) {
1013 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1014 strbuf_swap(&current->output, &s);
1016 strbuf_release(&s);
1017 pop_stack_element(&state->stack);
1018 return 0;
1022 * In a format string, find the next occurrence of %(atom).
1024 static const char *find_next(const char *cp)
1026 while (*cp) {
1027 if (*cp == '%') {
1029 * %( is the start of an atom;
1030 * %% is a quoted per-cent.
1032 if (cp[1] == '(')
1033 return cp;
1034 else if (cp[1] == '%')
1035 cp++; /* skip over two % */
1036 /* otherwise this is a singleton, literal % */
1038 cp++;
1040 return NULL;
1043 static int reject_atom(enum atom_type atom_type)
1045 return atom_type == ATOM_REST;
1049 * Make sure the format string is well formed, and parse out
1050 * the used atoms.
1052 int verify_ref_format(struct ref_format *format)
1054 const char *cp, *sp;
1056 format->need_color_reset_at_eol = 0;
1057 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1058 struct strbuf err = STRBUF_INIT;
1059 const char *color, *ep = strchr(sp, ')');
1060 int at;
1062 if (!ep)
1063 return error(_("malformed format string %s"), sp);
1064 /* sp points at "%(" and ep points at the closing ")" */
1065 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1066 if (at < 0)
1067 die("%s", err.buf);
1068 if (reject_atom(used_atom[at].atom_type))
1069 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1071 if ((format->quote_style == QUOTE_PYTHON ||
1072 format->quote_style == QUOTE_SHELL ||
1073 format->quote_style == QUOTE_TCL) &&
1074 used_atom[at].atom_type == ATOM_RAW &&
1075 used_atom[at].u.raw_data.option == RAW_BARE)
1076 die(_("--format=%.*s cannot be used with "
1077 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1078 cp = ep + 1;
1080 if (skip_prefix(used_atom[at].name, "color:", &color))
1081 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1082 strbuf_release(&err);
1084 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1085 format->need_color_reset_at_eol = 0;
1086 return 0;
1089 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1090 struct used_atom *atom)
1092 switch (atom->u.oid.option) {
1093 case O_FULL:
1094 return oid_to_hex(oid);
1095 case O_LENGTH:
1096 return find_unique_abbrev(oid, atom->u.oid.length);
1097 case O_SHORT:
1098 return find_unique_abbrev(oid, DEFAULT_ABBREV);
1099 default:
1100 BUG("unknown %%(%s) option", field);
1104 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1105 struct atom_value *v, struct used_atom *atom)
1107 if (starts_with(name, field)) {
1108 v->s = xstrdup(do_grab_oid(field, oid, atom));
1109 return 1;
1111 return 0;
1114 /* See grab_values */
1115 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1117 int i;
1119 for (i = 0; i < used_atom_cnt; i++) {
1120 const char *name = used_atom[i].name;
1121 enum atom_type atom_type = used_atom[i].atom_type;
1122 struct atom_value *v = &val[i];
1123 if (!!deref != (*name == '*'))
1124 continue;
1125 if (deref)
1126 name++;
1127 if (atom_type == ATOM_OBJECTTYPE)
1128 v->s = xstrdup(type_name(oi->type));
1129 else if (atom_type == ATOM_OBJECTSIZE) {
1130 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1131 v->value = oi->disk_size;
1132 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1133 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1134 v->value = oi->size;
1135 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1137 } else if (atom_type == ATOM_DELTABASE)
1138 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1139 else if (atom_type == ATOM_OBJECTNAME && deref)
1140 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1144 /* See grab_values */
1145 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1147 int i;
1148 struct tag *tag = (struct tag *) obj;
1150 for (i = 0; i < used_atom_cnt; i++) {
1151 const char *name = used_atom[i].name;
1152 enum atom_type atom_type = used_atom[i].atom_type;
1153 struct atom_value *v = &val[i];
1154 if (!!deref != (*name == '*'))
1155 continue;
1156 if (deref)
1157 name++;
1158 if (atom_type == ATOM_TAG)
1159 v->s = xstrdup(tag->tag);
1160 else if (atom_type == ATOM_TYPE && tag->tagged)
1161 v->s = xstrdup(type_name(tag->tagged->type));
1162 else if (atom_type == ATOM_OBJECT && tag->tagged)
1163 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1167 /* See grab_values */
1168 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1170 int i;
1171 struct commit *commit = (struct commit *) obj;
1173 for (i = 0; i < used_atom_cnt; i++) {
1174 const char *name = used_atom[i].name;
1175 enum atom_type atom_type = used_atom[i].atom_type;
1176 struct atom_value *v = &val[i];
1177 if (!!deref != (*name == '*'))
1178 continue;
1179 if (deref)
1180 name++;
1181 if (atom_type == ATOM_TREE &&
1182 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1183 continue;
1184 if (atom_type == ATOM_NUMPARENT) {
1185 v->value = commit_list_count(commit->parents);
1186 v->s = xstrfmt("%lu", (unsigned long)v->value);
1188 else if (atom_type == ATOM_PARENT) {
1189 struct commit_list *parents;
1190 struct strbuf s = STRBUF_INIT;
1191 for (parents = commit->parents; parents; parents = parents->next) {
1192 struct object_id *oid = &parents->item->object.oid;
1193 if (parents != commit->parents)
1194 strbuf_addch(&s, ' ');
1195 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1197 v->s = strbuf_detach(&s, NULL);
1202 static const char *find_wholine(const char *who, int wholen, const char *buf)
1204 const char *eol;
1205 while (*buf) {
1206 if (!strncmp(buf, who, wholen) &&
1207 buf[wholen] == ' ')
1208 return buf + wholen + 1;
1209 eol = strchr(buf, '\n');
1210 if (!eol)
1211 return "";
1212 eol++;
1213 if (*eol == '\n')
1214 return ""; /* end of header */
1215 buf = eol;
1217 return "";
1220 static const char *copy_line(const char *buf)
1222 const char *eol = strchrnul(buf, '\n');
1223 return xmemdupz(buf, eol - buf);
1226 static const char *copy_name(const char *buf)
1228 const char *cp;
1229 for (cp = buf; *cp && *cp != '\n'; cp++) {
1230 if (starts_with(cp, " <"))
1231 return xmemdupz(buf, cp - buf);
1233 return xstrdup("");
1236 static const char *copy_email(const char *buf, struct used_atom *atom)
1238 const char *email = strchr(buf, '<');
1239 const char *eoemail;
1240 if (!email)
1241 return xstrdup("");
1242 switch (atom->u.email_option.option) {
1243 case EO_RAW:
1244 eoemail = strchr(email, '>');
1245 if (eoemail)
1246 eoemail++;
1247 break;
1248 case EO_TRIM:
1249 email++;
1250 eoemail = strchr(email, '>');
1251 break;
1252 case EO_LOCALPART:
1253 email++;
1254 eoemail = strchr(email, '@');
1255 if (!eoemail)
1256 eoemail = strchr(email, '>');
1257 break;
1258 default:
1259 BUG("unknown email option");
1262 if (!eoemail)
1263 return xstrdup("");
1264 return xmemdupz(email, eoemail - email);
1267 static char *copy_subject(const char *buf, unsigned long len)
1269 struct strbuf sb = STRBUF_INIT;
1270 int i;
1272 for (i = 0; i < len; i++) {
1273 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1274 continue; /* ignore CR in CRLF */
1276 if (buf[i] == '\n')
1277 strbuf_addch(&sb, ' ');
1278 else
1279 strbuf_addch(&sb, buf[i]);
1281 return strbuf_detach(&sb, NULL);
1284 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1286 const char *eoemail = strstr(buf, "> ");
1287 char *zone;
1288 timestamp_t timestamp;
1289 long tz;
1290 struct date_mode date_mode = DATE_MODE_INIT;
1291 const char *formatp;
1294 * We got here because atomname ends in "date" or "date<something>";
1295 * it's not possible that <something> is not ":<format>" because
1296 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1297 * ":" means no format is specified, and use the default.
1299 formatp = strchr(atomname, ':');
1300 if (formatp) {
1301 formatp++;
1302 parse_date_format(formatp, &date_mode);
1305 if (!eoemail)
1306 goto bad;
1307 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1308 if (timestamp == TIME_MAX)
1309 goto bad;
1310 tz = strtol(zone, NULL, 10);
1311 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1312 goto bad;
1313 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1314 v->value = timestamp;
1315 date_mode_release(&date_mode);
1316 return;
1317 bad:
1318 v->s = xstrdup("");
1319 v->value = 0;
1322 /* See grab_values */
1323 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1325 int i;
1326 int wholen = strlen(who);
1327 const char *wholine = NULL;
1329 for (i = 0; i < used_atom_cnt; i++) {
1330 const char *name = used_atom[i].name;
1331 struct atom_value *v = &val[i];
1332 if (!!deref != (*name == '*'))
1333 continue;
1334 if (deref)
1335 name++;
1336 if (strncmp(who, name, wholen))
1337 continue;
1338 if (name[wholen] != 0 &&
1339 strcmp(name + wholen, "name") &&
1340 !starts_with(name + wholen, "email") &&
1341 !starts_with(name + wholen, "date"))
1342 continue;
1343 if (!wholine)
1344 wholine = find_wholine(who, wholen, buf);
1345 if (!wholine)
1346 return; /* no point looking for it */
1347 if (name[wholen] == 0)
1348 v->s = copy_line(wholine);
1349 else if (!strcmp(name + wholen, "name"))
1350 v->s = copy_name(wholine);
1351 else if (starts_with(name + wholen, "email"))
1352 v->s = copy_email(wholine, &used_atom[i]);
1353 else if (starts_with(name + wholen, "date"))
1354 grab_date(wholine, v, name);
1358 * For a tag or a commit object, if "creator" or "creatordate" is
1359 * requested, do something special.
1361 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1362 return; /* "author" for commit object is not wanted */
1363 if (!wholine)
1364 wholine = find_wholine(who, wholen, buf);
1365 if (!wholine)
1366 return;
1367 for (i = 0; i < used_atom_cnt; i++) {
1368 const char *name = used_atom[i].name;
1369 enum atom_type atom_type = used_atom[i].atom_type;
1370 struct atom_value *v = &val[i];
1371 if (!!deref != (*name == '*'))
1372 continue;
1373 if (deref)
1374 name++;
1376 if (atom_type == ATOM_CREATORDATE)
1377 grab_date(wholine, v, name);
1378 else if (atom_type == ATOM_CREATOR)
1379 v->s = copy_line(wholine);
1383 static void find_subpos(const char *buf,
1384 const char **sub, size_t *sublen,
1385 const char **body, size_t *bodylen,
1386 size_t *nonsiglen,
1387 const char **sig, size_t *siglen)
1389 struct strbuf payload = STRBUF_INIT;
1390 struct strbuf signature = STRBUF_INIT;
1391 const char *eol;
1392 const char *end = buf + strlen(buf);
1393 const char *sigstart;
1395 /* parse signature first; we might not even have a subject line */
1396 parse_signature(buf, end - buf, &payload, &signature);
1397 strbuf_release(&payload);
1399 /* skip past header until we hit empty line */
1400 while (*buf && *buf != '\n') {
1401 eol = strchrnul(buf, '\n');
1402 if (*eol)
1403 eol++;
1404 buf = eol;
1406 /* skip any empty lines */
1407 while (*buf == '\n')
1408 buf++;
1409 *sig = strbuf_detach(&signature, siglen);
1410 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1412 /* subject is first non-empty line */
1413 *sub = buf;
1414 /* subject goes to first empty line before signature begins */
1415 if ((eol = strstr(*sub, "\n\n")) ||
1416 (eol = strstr(*sub, "\r\n\r\n"))) {
1417 eol = eol < sigstart ? eol : sigstart;
1418 } else {
1419 /* treat whole message as subject */
1420 eol = sigstart;
1422 buf = eol;
1423 *sublen = buf - *sub;
1424 /* drop trailing newline, if present */
1425 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1426 (*sub)[*sublen - 1] == '\r'))
1427 *sublen -= 1;
1429 /* skip any empty lines */
1430 while (*buf == '\n' || *buf == '\r')
1431 buf++;
1432 *body = buf;
1433 *bodylen = strlen(buf);
1434 *nonsiglen = sigstart - buf;
1438 * If 'lines' is greater than 0, append that many lines from the given
1439 * 'buf' of length 'size' to the given strbuf.
1441 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1443 int i;
1444 const char *sp, *eol;
1445 size_t len;
1447 sp = buf;
1449 for (i = 0; i < lines && sp < buf + size; i++) {
1450 if (i)
1451 strbuf_addstr(out, "\n ");
1452 eol = memchr(sp, '\n', size - (sp - buf));
1453 len = eol ? eol - sp : size - (sp - buf);
1454 strbuf_add(out, sp, len);
1455 if (!eol)
1456 break;
1457 sp = eol + 1;
1461 /* See grab_values */
1462 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1464 int i;
1465 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1466 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1467 void *buf = data->content;
1469 for (i = 0; i < used_atom_cnt; i++) {
1470 struct used_atom *atom = &used_atom[i];
1471 const char *name = atom->name;
1472 struct atom_value *v = &val[i];
1473 enum atom_type atom_type = atom->atom_type;
1475 if (!!deref != (*name == '*'))
1476 continue;
1477 if (deref)
1478 name++;
1480 if (atom_type == ATOM_RAW) {
1481 unsigned long buf_size = data->size;
1483 if (atom->u.raw_data.option == RAW_BARE) {
1484 v->s = xmemdupz(buf, buf_size);
1485 v->s_size = buf_size;
1486 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1487 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1489 continue;
1492 if ((data->type != OBJ_TAG &&
1493 data->type != OBJ_COMMIT) ||
1494 (strcmp(name, "body") &&
1495 !starts_with(name, "subject") &&
1496 !starts_with(name, "trailers") &&
1497 !starts_with(name, "contents")))
1498 continue;
1499 if (!subpos)
1500 find_subpos(buf,
1501 &subpos, &sublen,
1502 &bodypos, &bodylen, &nonsiglen,
1503 &sigpos, &siglen);
1505 if (atom->u.contents.option == C_SUB)
1506 v->s = copy_subject(subpos, sublen);
1507 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1508 struct strbuf sb = STRBUF_INIT;
1509 format_sanitized_subject(&sb, subpos, sublen);
1510 v->s = strbuf_detach(&sb, NULL);
1511 } else if (atom->u.contents.option == C_BODY_DEP)
1512 v->s = xmemdupz(bodypos, bodylen);
1513 else if (atom->u.contents.option == C_LENGTH)
1514 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1515 else if (atom->u.contents.option == C_BODY)
1516 v->s = xmemdupz(bodypos, nonsiglen);
1517 else if (atom->u.contents.option == C_SIG)
1518 v->s = xmemdupz(sigpos, siglen);
1519 else if (atom->u.contents.option == C_LINES) {
1520 struct strbuf s = STRBUF_INIT;
1521 const char *contents_end = bodypos + nonsiglen;
1523 /* Size is the length of the message after removing the signature */
1524 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1525 v->s = strbuf_detach(&s, NULL);
1526 } else if (atom->u.contents.option == C_TRAILERS) {
1527 struct strbuf s = STRBUF_INIT;
1529 /* Format the trailer info according to the trailer_opts given */
1530 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1532 v->s = strbuf_detach(&s, NULL);
1533 } else if (atom->u.contents.option == C_BARE)
1534 v->s = xstrdup(subpos);
1537 free((void *)sigpos);
1541 * We want to have empty print-string for field requests
1542 * that do not apply (e.g. "authordate" for a tag object)
1544 static void fill_missing_values(struct atom_value *val)
1546 int i;
1547 for (i = 0; i < used_atom_cnt; i++) {
1548 struct atom_value *v = &val[i];
1549 if (!v->s)
1550 v->s = xstrdup("");
1555 * val is a list of atom_value to hold returned values. Extract
1556 * the values for atoms in used_atom array out of (obj, buf, sz).
1557 * when deref is false, (obj, buf, sz) is the object that is
1558 * pointed at by the ref itself; otherwise it is the object the
1559 * ref (which is a tag) refers to.
1561 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1563 void *buf = data->content;
1565 switch (obj->type) {
1566 case OBJ_TAG:
1567 grab_tag_values(val, deref, obj);
1568 grab_sub_body_contents(val, deref, data);
1569 grab_person("tagger", val, deref, buf);
1570 break;
1571 case OBJ_COMMIT:
1572 grab_commit_values(val, deref, obj);
1573 grab_sub_body_contents(val, deref, data);
1574 grab_person("author", val, deref, buf);
1575 grab_person("committer", val, deref, buf);
1576 break;
1577 case OBJ_TREE:
1578 /* grab_tree_values(val, deref, obj, buf, sz); */
1579 grab_sub_body_contents(val, deref, data);
1580 break;
1581 case OBJ_BLOB:
1582 /* grab_blob_values(val, deref, obj, buf, sz); */
1583 grab_sub_body_contents(val, deref, data);
1584 break;
1585 default:
1586 die("Eh? Object of type %d?", obj->type);
1590 static inline char *copy_advance(char *dst, const char *src)
1592 while (*src)
1593 *dst++ = *src++;
1594 return dst;
1597 static const char *lstrip_ref_components(const char *refname, int len)
1599 long remaining = len;
1600 const char *start = xstrdup(refname);
1601 const char *to_free = start;
1603 if (len < 0) {
1604 int i;
1605 const char *p = refname;
1607 /* Find total no of '/' separated path-components */
1608 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1611 * The number of components we need to strip is now
1612 * the total minus the components to be left (Plus one
1613 * because we count the number of '/', but the number
1614 * of components is one more than the no of '/').
1616 remaining = i + len + 1;
1619 while (remaining > 0) {
1620 switch (*start++) {
1621 case '\0':
1622 free((char *)to_free);
1623 return xstrdup("");
1624 case '/':
1625 remaining--;
1626 break;
1630 start = xstrdup(start);
1631 free((char *)to_free);
1632 return start;
1635 static const char *rstrip_ref_components(const char *refname, int len)
1637 long remaining = len;
1638 const char *start = xstrdup(refname);
1639 const char *to_free = start;
1641 if (len < 0) {
1642 int i;
1643 const char *p = refname;
1645 /* Find total no of '/' separated path-components */
1646 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1649 * The number of components we need to strip is now
1650 * the total minus the components to be left (Plus one
1651 * because we count the number of '/', but the number
1652 * of components is one more than the no of '/').
1654 remaining = i + len + 1;
1657 while (remaining-- > 0) {
1658 char *p = strrchr(start, '/');
1659 if (!p) {
1660 free((char *)to_free);
1661 return xstrdup("");
1662 } else
1663 p[0] = '\0';
1665 return start;
1668 static const char *show_ref(struct refname_atom *atom, const char *refname)
1670 if (atom->option == R_SHORT)
1671 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1672 else if (atom->option == R_LSTRIP)
1673 return lstrip_ref_components(refname, atom->lstrip);
1674 else if (atom->option == R_RSTRIP)
1675 return rstrip_ref_components(refname, atom->rstrip);
1676 else
1677 return xstrdup(refname);
1680 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1681 struct branch *branch, const char **s)
1683 int num_ours, num_theirs;
1684 if (atom->u.remote_ref.option == RR_REF)
1685 *s = show_ref(&atom->u.remote_ref.refname, refname);
1686 else if (atom->u.remote_ref.option == RR_TRACK) {
1687 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1688 NULL, atom->u.remote_ref.push,
1689 AHEAD_BEHIND_FULL) < 0) {
1690 *s = xstrdup(msgs.gone);
1691 } else if (!num_ours && !num_theirs)
1692 *s = xstrdup("");
1693 else if (!num_ours)
1694 *s = xstrfmt(msgs.behind, num_theirs);
1695 else if (!num_theirs)
1696 *s = xstrfmt(msgs.ahead, num_ours);
1697 else
1698 *s = xstrfmt(msgs.ahead_behind,
1699 num_ours, num_theirs);
1700 if (!atom->u.remote_ref.nobracket && *s[0]) {
1701 const char *to_free = *s;
1702 *s = xstrfmt("[%s]", *s);
1703 free((void *)to_free);
1705 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1706 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1707 NULL, atom->u.remote_ref.push,
1708 AHEAD_BEHIND_FULL) < 0) {
1709 *s = xstrdup("");
1710 return;
1712 if (!num_ours && !num_theirs)
1713 *s = xstrdup("=");
1714 else if (!num_ours)
1715 *s = xstrdup("<");
1716 else if (!num_theirs)
1717 *s = xstrdup(">");
1718 else
1719 *s = xstrdup("<>");
1720 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1721 int explicit;
1722 const char *remote = atom->u.remote_ref.push ?
1723 pushremote_for_branch(branch, &explicit) :
1724 remote_for_branch(branch, &explicit);
1725 *s = xstrdup(explicit ? remote : "");
1726 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1727 const char *merge;
1729 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1730 *s = xstrdup(merge ? merge : "");
1731 } else
1732 BUG("unhandled RR_* enum");
1735 char *get_head_description(void)
1737 struct strbuf desc = STRBUF_INIT;
1738 struct wt_status_state state;
1739 memset(&state, 0, sizeof(state));
1740 wt_status_get_state(the_repository, &state, 1);
1741 if (state.rebase_in_progress ||
1742 state.rebase_interactive_in_progress) {
1743 if (state.branch)
1744 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1745 state.branch);
1746 else
1747 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1748 state.detached_from);
1749 } else if (state.bisect_in_progress)
1750 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1751 state.branch);
1752 else if (state.detached_from) {
1753 if (state.detached_at)
1754 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1755 state.detached_from);
1756 else
1757 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1758 state.detached_from);
1759 } else
1760 strbuf_addstr(&desc, _("(no branch)"));
1762 wt_status_state_free_buffers(&state);
1764 return strbuf_detach(&desc, NULL);
1767 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1769 if (!ref->symref)
1770 return xstrdup("");
1771 else
1772 return show_ref(&atom->u.refname, ref->symref);
1775 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1777 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1778 return get_head_description();
1779 return show_ref(&atom->u.refname, ref->refname);
1782 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1783 struct expand_data *oi, struct strbuf *err)
1785 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1786 int eaten = 1;
1787 if (oi->info.contentp) {
1788 /* We need to know that to use parse_object_buffer properly */
1789 oi->info.sizep = &oi->size;
1790 oi->info.typep = &oi->type;
1792 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1793 OBJECT_INFO_LOOKUP_REPLACE))
1794 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1795 oid_to_hex(&oi->oid), ref->refname);
1796 if (oi->info.disk_sizep && oi->disk_size < 0)
1797 BUG("Object size is less than zero.");
1799 if (oi->info.contentp) {
1800 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1801 if (!*obj) {
1802 if (!eaten)
1803 free(oi->content);
1804 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1805 oid_to_hex(&oi->oid), ref->refname);
1807 grab_values(ref->value, deref, *obj, oi);
1810 grab_common_values(ref->value, deref, oi);
1811 if (!eaten)
1812 free(oi->content);
1813 return 0;
1816 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1818 int i;
1820 for (i = 0; worktrees[i]; i++) {
1821 if (worktrees[i]->head_ref) {
1822 struct ref_to_worktree_entry *entry;
1823 entry = xmalloc(sizeof(*entry));
1824 entry->wt = worktrees[i];
1825 hashmap_entry_init(&entry->ent,
1826 strhash(worktrees[i]->head_ref));
1828 hashmap_add(map, &entry->ent);
1833 static void lazy_init_worktree_map(void)
1835 if (ref_to_worktree_map.worktrees)
1836 return;
1838 ref_to_worktree_map.worktrees = get_worktrees();
1839 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1840 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1843 static char *get_worktree_path(const struct ref_array_item *ref)
1845 struct hashmap_entry entry, *e;
1846 struct ref_to_worktree_entry *lookup_result;
1848 lazy_init_worktree_map();
1850 hashmap_entry_init(&entry, strhash(ref->refname));
1851 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1853 if (!e)
1854 return xstrdup("");
1856 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1858 return xstrdup(lookup_result->wt->path);
1862 * Parse the object referred by ref, and grab needed value.
1864 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1866 struct object *obj;
1867 int i;
1868 struct object_info empty = OBJECT_INFO_INIT;
1870 CALLOC_ARRAY(ref->value, used_atom_cnt);
1872 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1873 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1874 NULL, NULL);
1875 if (!ref->symref)
1876 ref->symref = xstrdup("");
1879 /* Fill in specials first */
1880 for (i = 0; i < used_atom_cnt; i++) {
1881 struct used_atom *atom = &used_atom[i];
1882 enum atom_type atom_type = atom->atom_type;
1883 const char *name = used_atom[i].name;
1884 struct atom_value *v = &ref->value[i];
1885 int deref = 0;
1886 const char *refname;
1887 struct branch *branch = NULL;
1889 v->s_size = ATOM_SIZE_UNSPECIFIED;
1890 v->handler = append_atom;
1891 v->atom = atom;
1893 if (*name == '*') {
1894 deref = 1;
1895 name++;
1898 if (atom_type == ATOM_REFNAME)
1899 refname = get_refname(atom, ref);
1900 else if (atom_type == ATOM_WORKTREEPATH) {
1901 if (ref->kind == FILTER_REFS_BRANCHES)
1902 v->s = get_worktree_path(ref);
1903 else
1904 v->s = xstrdup("");
1905 continue;
1907 else if (atom_type == ATOM_SYMREF)
1908 refname = get_symref(atom, ref);
1909 else if (atom_type == ATOM_UPSTREAM) {
1910 const char *branch_name;
1911 /* only local branches may have an upstream */
1912 if (!skip_prefix(ref->refname, "refs/heads/",
1913 &branch_name)) {
1914 v->s = xstrdup("");
1915 continue;
1917 branch = branch_get(branch_name);
1919 refname = branch_get_upstream(branch, NULL);
1920 if (refname)
1921 fill_remote_ref_details(atom, refname, branch, &v->s);
1922 else
1923 v->s = xstrdup("");
1924 continue;
1925 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1926 const char *branch_name;
1927 v->s = xstrdup("");
1928 if (!skip_prefix(ref->refname, "refs/heads/",
1929 &branch_name))
1930 continue;
1931 branch = branch_get(branch_name);
1933 if (atom->u.remote_ref.push_remote)
1934 refname = NULL;
1935 else {
1936 refname = branch_get_push(branch, NULL);
1937 if (!refname)
1938 continue;
1940 /* We will definitely re-init v->s on the next line. */
1941 free((char *)v->s);
1942 fill_remote_ref_details(atom, refname, branch, &v->s);
1943 continue;
1944 } else if (atom_type == ATOM_COLOR) {
1945 v->s = xstrdup(atom->u.color);
1946 continue;
1947 } else if (atom_type == ATOM_FLAG) {
1948 char buf[256], *cp = buf;
1949 if (ref->flag & REF_ISSYMREF)
1950 cp = copy_advance(cp, ",symref");
1951 if (ref->flag & REF_ISPACKED)
1952 cp = copy_advance(cp, ",packed");
1953 if (cp == buf)
1954 v->s = xstrdup("");
1955 else {
1956 *cp = '\0';
1957 v->s = xstrdup(buf + 1);
1959 continue;
1960 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1961 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1962 continue;
1963 } else if (atom_type == ATOM_HEAD) {
1964 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1965 v->s = xstrdup("*");
1966 else
1967 v->s = xstrdup(" ");
1968 continue;
1969 } else if (atom_type == ATOM_ALIGN) {
1970 v->handler = align_atom_handler;
1971 v->s = xstrdup("");
1972 continue;
1973 } else if (atom_type == ATOM_END) {
1974 v->handler = end_atom_handler;
1975 v->s = xstrdup("");
1976 continue;
1977 } else if (atom_type == ATOM_IF) {
1978 const char *s;
1979 if (skip_prefix(name, "if:", &s))
1980 v->s = xstrdup(s);
1981 else
1982 v->s = xstrdup("");
1983 v->handler = if_atom_handler;
1984 continue;
1985 } else if (atom_type == ATOM_THEN) {
1986 v->handler = then_atom_handler;
1987 v->s = xstrdup("");
1988 continue;
1989 } else if (atom_type == ATOM_ELSE) {
1990 v->handler = else_atom_handler;
1991 v->s = xstrdup("");
1992 continue;
1993 } else if (atom_type == ATOM_REST) {
1994 if (ref->rest)
1995 v->s = xstrdup(ref->rest);
1996 else
1997 v->s = xstrdup("");
1998 continue;
1999 } else
2000 continue;
2002 if (!deref)
2003 v->s = xstrdup(refname);
2004 else
2005 v->s = xstrfmt("%s^{}", refname);
2006 free((char *)refname);
2009 for (i = 0; i < used_atom_cnt; i++) {
2010 struct atom_value *v = &ref->value[i];
2011 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2012 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2013 oid_to_hex(&ref->objectname), ref->refname);
2016 if (need_tagged)
2017 oi.info.contentp = &oi.content;
2018 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2019 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2020 return 0;
2023 oi.oid = ref->objectname;
2024 if (get_object(ref, 0, &obj, &oi, err))
2025 return -1;
2028 * If there is no atom that wants to know about tagged
2029 * object, we are done.
2031 if (!need_tagged || (obj->type != OBJ_TAG))
2032 return 0;
2035 * If it is a tag object, see if we use a value that derefs
2036 * the object, and if we do grab the object it refers to.
2038 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2041 * NEEDSWORK: This derefs tag only once, which
2042 * is good to deal with chains of trust, but
2043 * is not consistent with what deref_tag() does
2044 * which peels the onion to the core.
2046 return get_object(ref, 1, &obj, &oi_deref, err);
2050 * Given a ref, return the value for the atom. This lazily gets value
2051 * out of the object by calling populate value.
2053 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2054 struct atom_value **v, struct strbuf *err)
2056 if (!ref->value) {
2057 if (populate_value(ref, err))
2058 return -1;
2059 fill_missing_values(ref->value);
2061 *v = &ref->value[atom];
2062 return 0;
2066 * Return 1 if the refname matches one of the patterns, otherwise 0.
2067 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2068 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2069 * matches "refs/heads/mas*", too).
2071 static int match_pattern(const struct ref_filter *filter, const char *refname)
2073 const char **patterns = filter->name_patterns;
2074 unsigned flags = 0;
2076 if (filter->ignore_case)
2077 flags |= WM_CASEFOLD;
2080 * When no '--format' option is given we need to skip the prefix
2081 * for matching refs of tags and branches.
2083 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2084 skip_prefix(refname, "refs/heads/", &refname) ||
2085 skip_prefix(refname, "refs/remotes/", &refname) ||
2086 skip_prefix(refname, "refs/", &refname));
2088 for (; *patterns; patterns++) {
2089 if (!wildmatch(*patterns, refname, flags))
2090 return 1;
2092 return 0;
2096 * Return 1 if the refname matches one of the patterns, otherwise 0.
2097 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2098 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2099 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2101 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2103 const char **pattern = filter->name_patterns;
2104 int namelen = strlen(refname);
2105 unsigned flags = WM_PATHNAME;
2107 if (filter->ignore_case)
2108 flags |= WM_CASEFOLD;
2110 for (; *pattern; pattern++) {
2111 const char *p = *pattern;
2112 int plen = strlen(p);
2114 if ((plen <= namelen) &&
2115 !strncmp(refname, p, plen) &&
2116 (refname[plen] == '\0' ||
2117 refname[plen] == '/' ||
2118 p[plen-1] == '/'))
2119 return 1;
2120 if (!wildmatch(p, refname, flags))
2121 return 1;
2123 return 0;
2126 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2127 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2129 if (!*filter->name_patterns)
2130 return 1; /* No pattern always matches */
2131 if (filter->match_as_path)
2132 return match_name_as_path(filter, refname);
2133 return match_pattern(filter, refname);
2137 * This is the same as for_each_fullref_in(), but it tries to iterate
2138 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2139 * pattern match, so the callback still has to match each ref individually.
2141 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2142 each_ref_fn cb,
2143 void *cb_data)
2145 if (!filter->match_as_path) {
2147 * in this case, the patterns are applied after
2148 * prefixes like "refs/heads/" etc. are stripped off,
2149 * so we have to look at everything:
2151 return for_each_fullref_in("", cb, cb_data);
2154 if (filter->ignore_case) {
2156 * we can't handle case-insensitive comparisons,
2157 * so just return everything and let the caller
2158 * sort it out.
2160 return for_each_fullref_in("", cb, cb_data);
2163 if (!filter->name_patterns[0]) {
2164 /* no patterns; we have to look at everything */
2165 return for_each_fullref_in("", cb, cb_data);
2168 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2169 NULL, filter->name_patterns,
2170 cb, cb_data);
2174 * Given a ref (oid, refname), check if the ref belongs to the array
2175 * of oids. If the given ref is a tag, check if the given tag points
2176 * at one of the oids in the given oid array.
2177 * NEEDSWORK:
2178 * 1. Only a single level of indirection is obtained, we might want to
2179 * change this to account for multiple levels (e.g. annotated tags
2180 * pointing to annotated tags pointing to a commit.)
2181 * 2. As the refs are cached we might know what refname peels to without
2182 * the need to parse the object via parse_object(). peel_ref() might be a
2183 * more efficient alternative to obtain the pointee.
2185 static const struct object_id *match_points_at(struct oid_array *points_at,
2186 const struct object_id *oid,
2187 const char *refname)
2189 const struct object_id *tagged_oid = NULL;
2190 struct object *obj;
2192 if (oid_array_lookup(points_at, oid) >= 0)
2193 return oid;
2194 obj = parse_object(the_repository, oid);
2195 if (!obj)
2196 die(_("malformed object at '%s'"), refname);
2197 if (obj->type == OBJ_TAG)
2198 tagged_oid = get_tagged_oid((struct tag *)obj);
2199 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2200 return tagged_oid;
2201 return NULL;
2205 * Allocate space for a new ref_array_item and copy the name and oid to it.
2207 * Callers can then fill in other struct members at their leisure.
2209 static struct ref_array_item *new_ref_array_item(const char *refname,
2210 const struct object_id *oid)
2212 struct ref_array_item *ref;
2214 FLEX_ALLOC_STR(ref, refname, refname);
2215 oidcpy(&ref->objectname, oid);
2216 ref->rest = NULL;
2218 return ref;
2221 struct ref_array_item *ref_array_push(struct ref_array *array,
2222 const char *refname,
2223 const struct object_id *oid)
2225 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2227 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2228 array->items[array->nr++] = ref;
2230 return ref;
2233 static int ref_kind_from_refname(const char *refname)
2235 unsigned int i;
2237 static struct {
2238 const char *prefix;
2239 unsigned int kind;
2240 } ref_kind[] = {
2241 { "refs/heads/" , FILTER_REFS_BRANCHES },
2242 { "refs/remotes/" , FILTER_REFS_REMOTES },
2243 { "refs/tags/", FILTER_REFS_TAGS}
2246 if (!strcmp(refname, "HEAD"))
2247 return FILTER_REFS_DETACHED_HEAD;
2249 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2250 if (starts_with(refname, ref_kind[i].prefix))
2251 return ref_kind[i].kind;
2254 return FILTER_REFS_OTHERS;
2257 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2259 if (filter->kind == FILTER_REFS_BRANCHES ||
2260 filter->kind == FILTER_REFS_REMOTES ||
2261 filter->kind == FILTER_REFS_TAGS)
2262 return filter->kind;
2263 return ref_kind_from_refname(refname);
2266 struct ref_filter_cbdata {
2267 struct ref_array *array;
2268 struct ref_filter *filter;
2269 struct contains_cache contains_cache;
2270 struct contains_cache no_contains_cache;
2274 * A call-back given to for_each_ref(). Filter refs and keep them for
2275 * later object processing.
2277 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2279 struct ref_filter_cbdata *ref_cbdata = cb_data;
2280 struct ref_filter *filter = ref_cbdata->filter;
2281 struct ref_array_item *ref;
2282 struct commit *commit = NULL;
2283 unsigned int kind;
2285 if (flag & REF_BAD_NAME) {
2286 warning(_("ignoring ref with broken name %s"), refname);
2287 return 0;
2290 if (flag & REF_ISBROKEN) {
2291 warning(_("ignoring broken ref %s"), refname);
2292 return 0;
2295 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2296 kind = filter_ref_kind(filter, refname);
2297 if (!(kind & filter->kind))
2298 return 0;
2300 if (!filter_pattern_match(filter, refname))
2301 return 0;
2303 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2304 return 0;
2307 * A merge filter is applied on refs pointing to commits. Hence
2308 * obtain the commit using the 'oid' available and discard all
2309 * non-commits early. The actual filtering is done later.
2311 if (filter->reachable_from || filter->unreachable_from ||
2312 filter->with_commit || filter->no_commit || filter->verbose) {
2313 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2314 if (!commit)
2315 return 0;
2316 /* We perform the filtering for the '--contains' option... */
2317 if (filter->with_commit &&
2318 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2319 return 0;
2320 /* ...or for the `--no-contains' option */
2321 if (filter->no_commit &&
2322 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2323 return 0;
2327 * We do not open the object yet; sort may only need refname
2328 * to do its job and the resulting list may yet to be pruned
2329 * by maxcount logic.
2331 ref = ref_array_push(ref_cbdata->array, refname, oid);
2332 ref->commit = commit;
2333 ref->flag = flag;
2334 ref->kind = kind;
2336 return 0;
2339 /* Free memory allocated for a ref_array_item */
2340 static void free_array_item(struct ref_array_item *item)
2342 free((char *)item->symref);
2343 if (item->value) {
2344 int i;
2345 for (i = 0; i < used_atom_cnt; i++)
2346 free((char *)item->value[i].s);
2347 free(item->value);
2349 free(item);
2352 /* Free all memory allocated for ref_array */
2353 void ref_array_clear(struct ref_array *array)
2355 int i;
2357 for (i = 0; i < array->nr; i++)
2358 free_array_item(array->items[i]);
2359 FREE_AND_NULL(array->items);
2360 array->nr = array->alloc = 0;
2362 for (i = 0; i < used_atom_cnt; i++) {
2363 struct used_atom *atom = &used_atom[i];
2364 if (atom->atom_type == ATOM_HEAD)
2365 free(atom->u.head);
2366 free((char *)atom->name);
2368 FREE_AND_NULL(used_atom);
2369 used_atom_cnt = 0;
2371 if (ref_to_worktree_map.worktrees) {
2372 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2373 struct ref_to_worktree_entry, ent);
2374 free_worktrees(ref_to_worktree_map.worktrees);
2375 ref_to_worktree_map.worktrees = NULL;
2379 #define EXCLUDE_REACHED 0
2380 #define INCLUDE_REACHED 1
2381 static void reach_filter(struct ref_array *array,
2382 struct commit_list *check_reachable,
2383 int include_reached)
2385 struct rev_info revs;
2386 int i, old_nr;
2387 struct commit **to_clear;
2388 struct commit_list *cr;
2390 if (!check_reachable)
2391 return;
2393 CALLOC_ARRAY(to_clear, array->nr);
2395 repo_init_revisions(the_repository, &revs, NULL);
2397 for (i = 0; i < array->nr; i++) {
2398 struct ref_array_item *item = array->items[i];
2399 add_pending_object(&revs, &item->commit->object, item->refname);
2400 to_clear[i] = item->commit;
2403 for (cr = check_reachable; cr; cr = cr->next) {
2404 struct commit *merge_commit = cr->item;
2405 merge_commit->object.flags |= UNINTERESTING;
2406 add_pending_object(&revs, &merge_commit->object, "");
2409 revs.limited = 1;
2410 if (prepare_revision_walk(&revs))
2411 die(_("revision walk setup failed"));
2413 old_nr = array->nr;
2414 array->nr = 0;
2416 for (i = 0; i < old_nr; i++) {
2417 struct ref_array_item *item = array->items[i];
2418 struct commit *commit = item->commit;
2420 int is_merged = !!(commit->object.flags & UNINTERESTING);
2422 if (is_merged == include_reached)
2423 array->items[array->nr++] = array->items[i];
2424 else
2425 free_array_item(item);
2428 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2430 while (check_reachable) {
2431 struct commit *merge_commit = pop_commit(&check_reachable);
2432 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2435 release_revisions(&revs);
2436 free(to_clear);
2440 * API for filtering a set of refs. Based on the type of refs the user
2441 * has requested, we iterate through those refs and apply filters
2442 * as per the given ref_filter structure and finally store the
2443 * filtered refs in the ref_array structure.
2445 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2447 struct ref_filter_cbdata ref_cbdata;
2448 int save_commit_buffer_orig;
2449 int ret = 0;
2451 ref_cbdata.array = array;
2452 ref_cbdata.filter = filter;
2454 filter->kind = type & FILTER_REFS_KIND_MASK;
2456 save_commit_buffer_orig = save_commit_buffer;
2457 save_commit_buffer = 0;
2459 init_contains_cache(&ref_cbdata.contains_cache);
2460 init_contains_cache(&ref_cbdata.no_contains_cache);
2462 /* Simple per-ref filtering */
2463 if (!filter->kind)
2464 die("filter_refs: invalid type");
2465 else {
2467 * For common cases where we need only branches or remotes or tags,
2468 * we only iterate through those refs. If a mix of refs is needed,
2469 * we iterate over all refs and filter out required refs with the help
2470 * of filter_ref_kind().
2472 if (filter->kind == FILTER_REFS_BRANCHES)
2473 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2474 else if (filter->kind == FILTER_REFS_REMOTES)
2475 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2476 else if (filter->kind == FILTER_REFS_TAGS)
2477 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2478 else if (filter->kind & FILTER_REFS_ALL)
2479 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2480 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2481 head_ref(ref_filter_handler, &ref_cbdata);
2484 clear_contains_cache(&ref_cbdata.contains_cache);
2485 clear_contains_cache(&ref_cbdata.no_contains_cache);
2487 /* Filters that need revision walking */
2488 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2489 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2491 save_commit_buffer = save_commit_buffer_orig;
2492 return ret;
2495 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2497 if (!(a->kind ^ b->kind))
2498 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2499 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2500 return -1;
2501 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2502 return 1;
2503 BUG("should have died in the xor check above");
2504 return 0;
2507 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2509 const char *s1 = vs1, *s2 = vs2;
2510 const char *end = s1 + n;
2512 for (; s1 < end; s1++, s2++) {
2513 int diff = tolower(*s1) - tolower(*s2);
2514 if (diff)
2515 return diff;
2517 return 0;
2520 struct ref_sorting {
2521 struct ref_sorting *next;
2522 int atom; /* index into used_atom array (internal) */
2523 enum ref_sorting_order sort_flags;
2526 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2528 struct atom_value *va, *vb;
2529 int cmp;
2530 int cmp_detached_head = 0;
2531 cmp_type cmp_type = used_atom[s->atom].type;
2532 struct strbuf err = STRBUF_INIT;
2534 if (get_ref_atom_value(a, s->atom, &va, &err))
2535 die("%s", err.buf);
2536 if (get_ref_atom_value(b, s->atom, &vb, &err))
2537 die("%s", err.buf);
2538 strbuf_release(&err);
2539 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2540 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2541 cmp = compare_detached_head(a, b);
2542 cmp_detached_head = 1;
2543 } else if (s->sort_flags & REF_SORTING_VERSION) {
2544 cmp = versioncmp(va->s, vb->s);
2545 } else if (cmp_type == FIELD_STR) {
2546 if (va->s_size < 0 && vb->s_size < 0) {
2547 int (*cmp_fn)(const char *, const char *);
2548 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2549 ? strcasecmp : strcmp;
2550 cmp = cmp_fn(va->s, vb->s);
2551 } else {
2552 size_t a_size = va->s_size < 0 ?
2553 strlen(va->s) : va->s_size;
2554 size_t b_size = vb->s_size < 0 ?
2555 strlen(vb->s) : vb->s_size;
2556 int (*cmp_fn)(const void *, const void *, size_t);
2557 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2558 ? memcasecmp : memcmp;
2560 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2561 a_size : b_size);
2562 if (!cmp) {
2563 if (a_size > b_size)
2564 cmp = 1;
2565 else if (a_size < b_size)
2566 cmp = -1;
2569 } else {
2570 if (va->value < vb->value)
2571 cmp = -1;
2572 else if (va->value == vb->value)
2573 cmp = 0;
2574 else
2575 cmp = 1;
2578 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2579 ? -cmp : cmp;
2582 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2584 struct ref_array_item *a = *((struct ref_array_item **)a_);
2585 struct ref_array_item *b = *((struct ref_array_item **)b_);
2586 struct ref_sorting *s;
2588 for (s = ref_sorting; s; s = s->next) {
2589 int cmp = cmp_ref_sorting(s, a, b);
2590 if (cmp)
2591 return cmp;
2593 s = ref_sorting;
2594 return s && s->sort_flags & REF_SORTING_ICASE ?
2595 strcasecmp(a->refname, b->refname) :
2596 strcmp(a->refname, b->refname);
2599 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2600 unsigned int mask, int on)
2602 for (; sorting; sorting = sorting->next) {
2603 if (on)
2604 sorting->sort_flags |= mask;
2605 else
2606 sorting->sort_flags &= ~mask;
2610 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2612 QSORT_S(array->items, array->nr, compare_refs, sorting);
2615 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2617 struct strbuf *s = &state->stack->output;
2619 while (*cp && (!ep || cp < ep)) {
2620 if (*cp == '%') {
2621 if (cp[1] == '%')
2622 cp++;
2623 else {
2624 int ch = hex2chr(cp + 1);
2625 if (0 <= ch) {
2626 strbuf_addch(s, ch);
2627 cp += 3;
2628 continue;
2632 strbuf_addch(s, *cp);
2633 cp++;
2637 int format_ref_array_item(struct ref_array_item *info,
2638 struct ref_format *format,
2639 struct strbuf *final_buf,
2640 struct strbuf *error_buf)
2642 const char *cp, *sp, *ep;
2643 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2645 state.quote_style = format->quote_style;
2646 push_stack_element(&state.stack);
2648 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2649 struct atom_value *atomv;
2650 int pos;
2652 ep = strchr(sp, ')');
2653 if (cp < sp)
2654 append_literal(cp, sp, &state);
2655 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2656 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2657 atomv->handler(atomv, &state, error_buf)) {
2658 pop_stack_element(&state.stack);
2659 return -1;
2662 if (*cp) {
2663 sp = cp + strlen(cp);
2664 append_literal(cp, sp, &state);
2666 if (format->need_color_reset_at_eol) {
2667 struct atom_value resetv = ATOM_VALUE_INIT;
2668 resetv.s = GIT_COLOR_RESET;
2669 if (append_atom(&resetv, &state, error_buf)) {
2670 pop_stack_element(&state.stack);
2671 return -1;
2674 if (state.stack->prev) {
2675 pop_stack_element(&state.stack);
2676 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2678 strbuf_addbuf(final_buf, &state.stack->output);
2679 pop_stack_element(&state.stack);
2680 return 0;
2683 void pretty_print_ref(const char *name, const struct object_id *oid,
2684 struct ref_format *format)
2686 struct ref_array_item *ref_item;
2687 struct strbuf output = STRBUF_INIT;
2688 struct strbuf err = STRBUF_INIT;
2690 ref_item = new_ref_array_item(name, oid);
2691 ref_item->kind = ref_kind_from_refname(name);
2692 if (format_ref_array_item(ref_item, format, &output, &err))
2693 die("%s", err.buf);
2694 fwrite(output.buf, 1, output.len, stdout);
2695 putchar('\n');
2697 strbuf_release(&err);
2698 strbuf_release(&output);
2699 free_array_item(ref_item);
2702 static int parse_sorting_atom(const char *atom)
2705 * This parses an atom using a dummy ref_format, since we don't
2706 * actually care about the formatting details.
2708 struct ref_format dummy = REF_FORMAT_INIT;
2709 const char *end = atom + strlen(atom);
2710 struct strbuf err = STRBUF_INIT;
2711 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2712 if (res < 0)
2713 die("%s", err.buf);
2714 strbuf_release(&err);
2715 return res;
2718 /* If no sorting option is given, use refname to sort as default */
2719 static struct ref_sorting *ref_default_sorting(void)
2721 static const char cstr_name[] = "refname";
2723 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2725 sorting->next = NULL;
2726 sorting->atom = parse_sorting_atom(cstr_name);
2727 return sorting;
2730 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2732 struct ref_sorting *s;
2734 CALLOC_ARRAY(s, 1);
2735 s->next = *sorting_tail;
2736 *sorting_tail = s;
2738 if (*arg == '-') {
2739 s->sort_flags |= REF_SORTING_REVERSE;
2740 arg++;
2742 if (skip_prefix(arg, "version:", &arg) ||
2743 skip_prefix(arg, "v:", &arg))
2744 s->sort_flags |= REF_SORTING_VERSION;
2745 s->atom = parse_sorting_atom(arg);
2748 struct ref_sorting *ref_sorting_options(struct string_list *options)
2750 struct string_list_item *item;
2751 struct ref_sorting *sorting = NULL, **tail = &sorting;
2753 if (!options->nr) {
2754 sorting = ref_default_sorting();
2755 } else {
2756 for_each_string_list_item(item, options)
2757 parse_ref_sorting(tail, item->string);
2761 * From here on, the ref_sorting list should be used to talk
2762 * about the sort order used for the output. The caller
2763 * should not touch the string form anymore.
2765 string_list_clear(options, 0);
2766 return sorting;
2769 void ref_sorting_release(struct ref_sorting *sorting)
2771 while (sorting) {
2772 struct ref_sorting *next = sorting->next;
2773 free(sorting);
2774 sorting = next;
2778 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2780 struct ref_filter *rf = opt->value;
2781 struct object_id oid;
2782 struct commit *merge_commit;
2784 BUG_ON_OPT_NEG(unset);
2786 if (get_oid(arg, &oid))
2787 die(_("malformed object name %s"), arg);
2789 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2791 if (!merge_commit)
2792 return error(_("option `%s' must point to a commit"), opt->long_name);
2794 if (starts_with(opt->long_name, "no"))
2795 commit_list_insert(merge_commit, &rf->unreachable_from);
2796 else
2797 commit_list_insert(merge_commit, &rf->reachable_from);
2799 return 0;