Sync with 2.39.4
[git.git] / ref-filter.c
blobf8203c6b05254b624cf98e6d4590d07064cbb101
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "refs.h"
5 #include "wildmatch.h"
6 #include "object-store.h"
7 #include "repository.h"
8 #include "commit.h"
9 #include "remote.h"
10 #include "color.h"
11 #include "tag.h"
12 #include "quote.h"
13 #include "ref-filter.h"
14 #include "revision.h"
15 #include "utf8.h"
16 #include "git-compat-util.h"
17 #include "version.h"
18 #include "trailer.h"
19 #include "wt-status.h"
20 #include "commit-slab.h"
21 #include "commit-graph.h"
22 #include "commit-reach.h"
23 #include "worktree.h"
24 #include "hashmap.h"
25 #include "strvec.h"
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, struct used_atom *atom,
286 const char *arg, struct strbuf *err)
288 struct string_list params = STRING_LIST_INIT_DUP;
289 int i;
291 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
292 atom->u.remote_ref.push = 1;
294 if (!arg) {
295 atom->u.remote_ref.option = RR_REF;
296 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
297 arg, atom->name, err);
300 atom->u.remote_ref.nobracket = 0;
301 string_list_split(&params, arg, ',', -1);
303 for (i = 0; i < params.nr; i++) {
304 const char *s = params.items[i].string;
306 if (!strcmp(s, "track"))
307 atom->u.remote_ref.option = RR_TRACK;
308 else if (!strcmp(s, "trackshort"))
309 atom->u.remote_ref.option = RR_TRACKSHORT;
310 else if (!strcmp(s, "nobracket"))
311 atom->u.remote_ref.nobracket = 1;
312 else if (!strcmp(s, "remotename")) {
313 atom->u.remote_ref.option = RR_REMOTE_NAME;
314 atom->u.remote_ref.push_remote = 1;
315 } else if (!strcmp(s, "remoteref")) {
316 atom->u.remote_ref.option = RR_REMOTE_REF;
317 atom->u.remote_ref.push_remote = 1;
318 } else {
319 atom->u.remote_ref.option = RR_REF;
320 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
321 arg, atom->name, err)) {
322 string_list_clear(&params, 0);
323 return -1;
328 string_list_clear(&params, 0);
329 return 0;
332 static int objecttype_atom_parser(struct ref_format *format, struct used_atom *atom,
333 const char *arg, struct strbuf *err)
335 if (arg)
336 return err_no_arg(err, "objecttype");
337 if (*atom->name == '*')
338 oi_deref.info.typep = &oi_deref.type;
339 else
340 oi.info.typep = &oi.type;
341 return 0;
344 static int objectsize_atom_parser(struct ref_format *format, struct used_atom *atom,
345 const char *arg, struct strbuf *err)
347 if (!arg) {
348 atom->u.objectsize.option = O_SIZE;
349 if (*atom->name == '*')
350 oi_deref.info.sizep = &oi_deref.size;
351 else
352 oi.info.sizep = &oi.size;
353 } else if (!strcmp(arg, "disk")) {
354 atom->u.objectsize.option = O_SIZE_DISK;
355 if (*atom->name == '*')
356 oi_deref.info.disk_sizep = &oi_deref.disk_size;
357 else
358 oi.info.disk_sizep = &oi.disk_size;
359 } else
360 return err_bad_arg(err, "objectsize", arg);
361 return 0;
364 static int deltabase_atom_parser(struct ref_format *format, struct used_atom *atom,
365 const char *arg, struct strbuf *err)
367 if (arg)
368 return err_no_arg(err, "deltabase");
369 if (*atom->name == '*')
370 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
371 else
372 oi.info.delta_base_oid = &oi.delta_base_oid;
373 return 0;
376 static int body_atom_parser(struct ref_format *format, struct used_atom *atom,
377 const char *arg, struct strbuf *err)
379 if (arg)
380 return err_no_arg(err, "body");
381 atom->u.contents.option = C_BODY_DEP;
382 return 0;
385 static int subject_atom_parser(struct ref_format *format, struct used_atom *atom,
386 const char *arg, struct strbuf *err)
388 if (!arg)
389 atom->u.contents.option = C_SUB;
390 else if (!strcmp(arg, "sanitize"))
391 atom->u.contents.option = C_SUB_SANITIZE;
392 else
393 return err_bad_arg(err, "subject", arg);
394 return 0;
397 static int trailers_atom_parser(struct ref_format *format, struct used_atom *atom,
398 const char *arg, struct strbuf *err)
400 atom->u.contents.trailer_opts.no_divider = 1;
402 if (arg) {
403 const char *argbuf = xstrfmt("%s)", arg);
404 char *invalid_arg = NULL;
406 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
407 &ref_trailer_buf.filter_list,
408 &ref_trailer_buf.sepbuf,
409 &ref_trailer_buf.kvsepbuf,
410 &argbuf, &invalid_arg)) {
411 if (!invalid_arg)
412 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
413 else
414 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
415 free((char *)invalid_arg);
416 return -1;
419 atom->u.contents.option = C_TRAILERS;
420 return 0;
423 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
424 const char *arg, struct strbuf *err)
426 if (!arg)
427 atom->u.contents.option = C_BARE;
428 else if (!strcmp(arg, "body"))
429 atom->u.contents.option = C_BODY;
430 else if (!strcmp(arg, "size"))
431 atom->u.contents.option = C_LENGTH;
432 else if (!strcmp(arg, "signature"))
433 atom->u.contents.option = C_SIG;
434 else if (!strcmp(arg, "subject"))
435 atom->u.contents.option = C_SUB;
436 else if (!strcmp(arg, "trailers")) {
437 if (trailers_atom_parser(format, atom, NULL, err))
438 return -1;
439 } else if (skip_prefix(arg, "trailers:", &arg)) {
440 if (trailers_atom_parser(format, atom, arg, err))
441 return -1;
442 } else if (skip_prefix(arg, "lines=", &arg)) {
443 atom->u.contents.option = C_LINES;
444 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
445 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
446 } else
447 return err_bad_arg(err, "contents", arg);
448 return 0;
451 static int raw_atom_parser(struct ref_format *format, struct used_atom *atom,
452 const char *arg, struct strbuf *err)
454 if (!arg)
455 atom->u.raw_data.option = RAW_BARE;
456 else if (!strcmp(arg, "size"))
457 atom->u.raw_data.option = RAW_LENGTH;
458 else
459 return err_bad_arg(err, "raw", arg);
460 return 0;
463 static int oid_atom_parser(struct ref_format *format, struct used_atom *atom,
464 const char *arg, struct strbuf *err)
466 if (!arg)
467 atom->u.oid.option = O_FULL;
468 else if (!strcmp(arg, "short"))
469 atom->u.oid.option = O_SHORT;
470 else if (skip_prefix(arg, "short=", &arg)) {
471 atom->u.oid.option = O_LENGTH;
472 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
473 atom->u.oid.length == 0)
474 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
475 if (atom->u.oid.length < MINIMUM_ABBREV)
476 atom->u.oid.length = MINIMUM_ABBREV;
477 } else
478 return err_bad_arg(err, atom->name, arg);
479 return 0;
482 static int person_email_atom_parser(struct ref_format *format, struct used_atom *atom,
483 const char *arg, struct strbuf *err)
485 if (!arg)
486 atom->u.email_option.option = EO_RAW;
487 else if (!strcmp(arg, "trim"))
488 atom->u.email_option.option = EO_TRIM;
489 else if (!strcmp(arg, "localpart"))
490 atom->u.email_option.option = EO_LOCALPART;
491 else
492 return err_bad_arg(err, atom->name, arg);
493 return 0;
496 static int refname_atom_parser(struct ref_format *format, struct used_atom *atom,
497 const char *arg, struct strbuf *err)
499 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
502 static align_type parse_align_position(const char *s)
504 if (!strcmp(s, "right"))
505 return ALIGN_RIGHT;
506 else if (!strcmp(s, "middle"))
507 return ALIGN_MIDDLE;
508 else if (!strcmp(s, "left"))
509 return ALIGN_LEFT;
510 return -1;
513 static int align_atom_parser(struct ref_format *format, struct used_atom *atom,
514 const char *arg, struct strbuf *err)
516 struct align *align = &atom->u.align;
517 struct string_list params = STRING_LIST_INIT_DUP;
518 int i;
519 unsigned int width = ~0U;
521 if (!arg)
522 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
524 align->position = ALIGN_LEFT;
526 string_list_split(&params, arg, ',', -1);
527 for (i = 0; i < params.nr; i++) {
528 const char *s = params.items[i].string;
529 int position;
531 if (skip_prefix(s, "position=", &s)) {
532 position = parse_align_position(s);
533 if (position < 0) {
534 strbuf_addf(err, _("unrecognized position:%s"), s);
535 string_list_clear(&params, 0);
536 return -1;
538 align->position = position;
539 } else if (skip_prefix(s, "width=", &s)) {
540 if (strtoul_ui(s, 10, &width)) {
541 strbuf_addf(err, _("unrecognized width:%s"), s);
542 string_list_clear(&params, 0);
543 return -1;
545 } else if (!strtoul_ui(s, 10, &width))
547 else if ((position = parse_align_position(s)) >= 0)
548 align->position = position;
549 else {
550 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
551 string_list_clear(&params, 0);
552 return -1;
556 if (width == ~0U) {
557 string_list_clear(&params, 0);
558 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
560 align->width = width;
561 string_list_clear(&params, 0);
562 return 0;
565 static int if_atom_parser(struct ref_format *format, struct used_atom *atom,
566 const char *arg, struct strbuf *err)
568 if (!arg) {
569 atom->u.if_then_else.cmp_status = COMPARE_NONE;
570 return 0;
571 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
572 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
573 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
574 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
575 } else
576 return err_bad_arg(err, "if", arg);
577 return 0;
580 static int rest_atom_parser(struct ref_format *format, struct used_atom *atom,
581 const char *arg, struct strbuf *err)
583 if (arg)
584 return err_no_arg(err, "rest");
585 format->use_rest = 1;
586 return 0;
589 static int head_atom_parser(struct ref_format *format, struct used_atom *atom,
590 const char *arg, struct strbuf *err)
592 if (arg)
593 return err_no_arg(err, "HEAD");
594 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
595 return 0;
598 static struct {
599 const char *name;
600 info_source source;
601 cmp_type cmp_type;
602 int (*parser)(struct ref_format *format, struct used_atom *atom,
603 const char *arg, struct strbuf *err);
604 } valid_atom[] = {
605 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
606 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
607 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
608 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
609 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
610 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
611 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
612 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
613 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
614 [ATOM_TYPE] = { "type", SOURCE_OBJ },
615 [ATOM_TAG] = { "tag", SOURCE_OBJ },
616 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
617 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
618 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
619 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
620 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
621 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
622 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
623 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
624 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
625 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
626 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
627 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
628 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
629 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
630 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
631 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
632 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
633 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
634 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
635 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
636 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
637 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
638 [ATOM_FLAG] = { "flag", SOURCE_NONE },
639 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
640 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
641 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
642 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
643 [ATOM_END] = { "end", SOURCE_NONE },
644 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
645 [ATOM_THEN] = { "then", SOURCE_NONE },
646 [ATOM_ELSE] = { "else", SOURCE_NONE },
647 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
649 * Please update $__git_ref_fieldlist in git-completion.bash
650 * when you add new atoms
654 #define REF_FORMATTING_STATE_INIT { 0 }
656 struct ref_formatting_stack {
657 struct ref_formatting_stack *prev;
658 struct strbuf output;
659 void (*at_end)(struct ref_formatting_stack **stack);
660 void *at_end_data;
663 struct ref_formatting_state {
664 int quote_style;
665 struct ref_formatting_stack *stack;
668 struct atom_value {
669 const char *s;
670 ssize_t s_size;
671 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
672 struct strbuf *err);
673 uintmax_t value; /* used for sorting when not FIELD_STR */
674 struct used_atom *atom;
677 #define ATOM_SIZE_UNSPECIFIED (-1)
679 #define ATOM_VALUE_INIT { \
680 .s_size = ATOM_SIZE_UNSPECIFIED \
684 * Used to parse format string and sort specifiers
686 static int parse_ref_filter_atom(struct ref_format *format,
687 const char *atom, const char *ep,
688 struct strbuf *err)
690 const char *sp;
691 const char *arg;
692 int i, at, atom_len;
694 sp = atom;
695 if (*sp == '*' && sp < ep)
696 sp++; /* deref */
697 if (ep <= sp)
698 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
699 (int)(ep-atom), atom);
702 * If the atom name has a colon, strip it and everything after
703 * it off - it specifies the format for this entry, and
704 * shouldn't be used for checking against the valid_atom
705 * table.
707 arg = memchr(sp, ':', ep - sp);
708 atom_len = (arg ? arg : ep) - sp;
710 /* Do we have the atom already used elsewhere? */
711 for (i = 0; i < used_atom_cnt; i++) {
712 int len = strlen(used_atom[i].name);
713 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
714 return i;
717 /* Is the atom a valid one? */
718 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
719 int len = strlen(valid_atom[i].name);
720 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
721 break;
724 if (ARRAY_SIZE(valid_atom) <= i)
725 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
726 (int)(ep-atom), atom);
727 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
728 return strbuf_addf_ret(err, -1,
729 _("not a git repository, but the field '%.*s' requires access to object data"),
730 (int)(ep-atom), atom);
732 /* Add it in, including the deref prefix */
733 at = used_atom_cnt;
734 used_atom_cnt++;
735 REALLOC_ARRAY(used_atom, used_atom_cnt);
736 used_atom[at].atom_type = i;
737 used_atom[at].name = xmemdupz(atom, ep - atom);
738 used_atom[at].type = valid_atom[i].cmp_type;
739 used_atom[at].source = valid_atom[i].source;
740 if (used_atom[at].source == SOURCE_OBJ) {
741 if (*atom == '*')
742 oi_deref.info.contentp = &oi_deref.content;
743 else
744 oi.info.contentp = &oi.content;
746 if (arg) {
747 arg = used_atom[at].name + (arg - atom) + 1;
748 if (!*arg) {
750 * Treat empty sub-arguments list as NULL (i.e.,
751 * "%(atom:)" is equivalent to "%(atom)").
753 arg = NULL;
756 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
757 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
758 return -1;
759 if (*atom == '*')
760 need_tagged = 1;
761 if (i == ATOM_SYMREF)
762 need_symref = 1;
763 return at;
766 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
768 switch (quote_style) {
769 case QUOTE_NONE:
770 if (len < 0)
771 strbuf_addstr(s, str);
772 else
773 strbuf_add(s, str, len);
774 break;
775 case QUOTE_SHELL:
776 sq_quote_buf(s, str);
777 break;
778 case QUOTE_PERL:
779 if (len < 0)
780 perl_quote_buf(s, str);
781 else
782 perl_quote_buf_with_len(s, str, len);
783 break;
784 case QUOTE_PYTHON:
785 python_quote_buf(s, str);
786 break;
787 case QUOTE_TCL:
788 tcl_quote_buf(s, str);
789 break;
793 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
794 struct strbuf *unused_err)
797 * Quote formatting is only done when the stack has a single
798 * element. Otherwise quote formatting is done on the
799 * element's entire output strbuf when the %(end) atom is
800 * encountered.
802 if (!state->stack->prev)
803 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
804 else if (v->s_size < 0)
805 strbuf_addstr(&state->stack->output, v->s);
806 else
807 strbuf_add(&state->stack->output, v->s, v->s_size);
808 return 0;
811 static void push_stack_element(struct ref_formatting_stack **stack)
813 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
815 strbuf_init(&s->output, 0);
816 s->prev = *stack;
817 *stack = s;
820 static void pop_stack_element(struct ref_formatting_stack **stack)
822 struct ref_formatting_stack *current = *stack;
823 struct ref_formatting_stack *prev = current->prev;
825 if (prev)
826 strbuf_addbuf(&prev->output, &current->output);
827 strbuf_release(&current->output);
828 free(current);
829 *stack = prev;
832 static void end_align_handler(struct ref_formatting_stack **stack)
834 struct ref_formatting_stack *cur = *stack;
835 struct align *align = (struct align *)cur->at_end_data;
836 struct strbuf s = STRBUF_INIT;
838 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
839 strbuf_swap(&cur->output, &s);
840 strbuf_release(&s);
843 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
844 struct strbuf *unused_err)
846 struct ref_formatting_stack *new_stack;
848 push_stack_element(&state->stack);
849 new_stack = state->stack;
850 new_stack->at_end = end_align_handler;
851 new_stack->at_end_data = &atomv->atom->u.align;
852 return 0;
855 static void if_then_else_handler(struct ref_formatting_stack **stack)
857 struct ref_formatting_stack *cur = *stack;
858 struct ref_formatting_stack *prev = cur->prev;
859 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
861 if (!if_then_else->then_atom_seen)
862 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
864 if (if_then_else->else_atom_seen) {
866 * There is an %(else) atom: we need to drop one state from the
867 * stack, either the %(else) branch if the condition is satisfied, or
868 * the %(then) branch if it isn't.
870 if (if_then_else->condition_satisfied) {
871 strbuf_reset(&cur->output);
872 pop_stack_element(&cur);
873 } else {
874 strbuf_swap(&cur->output, &prev->output);
875 strbuf_reset(&cur->output);
876 pop_stack_element(&cur);
878 } else if (!if_then_else->condition_satisfied) {
880 * No %(else) atom: just drop the %(then) branch if the
881 * condition is not satisfied.
883 strbuf_reset(&cur->output);
886 *stack = cur;
887 free(if_then_else);
890 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
891 struct strbuf *unused_err)
893 struct ref_formatting_stack *new_stack;
894 struct if_then_else *if_then_else = xcalloc(1,
895 sizeof(struct if_then_else));
897 if_then_else->str = atomv->atom->u.if_then_else.str;
898 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
900 push_stack_element(&state->stack);
901 new_stack = state->stack;
902 new_stack->at_end = if_then_else_handler;
903 new_stack->at_end_data = if_then_else;
904 return 0;
907 static int is_empty(struct strbuf *buf)
909 const char *cur = buf->buf;
910 const char *end = buf->buf + buf->len;
912 while (cur != end && (isspace(*cur)))
913 cur++;
915 return cur == end;
918 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
919 struct strbuf *err)
921 struct ref_formatting_stack *cur = state->stack;
922 struct if_then_else *if_then_else = NULL;
923 size_t str_len = 0;
925 if (cur->at_end == if_then_else_handler)
926 if_then_else = (struct if_then_else *)cur->at_end_data;
927 if (!if_then_else)
928 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
929 if (if_then_else->then_atom_seen)
930 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
931 if (if_then_else->else_atom_seen)
932 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
933 if_then_else->then_atom_seen = 1;
934 if (if_then_else->str)
935 str_len = strlen(if_then_else->str);
937 * If the 'equals' or 'notequals' attribute is used then
938 * perform the required comparison. If not, only non-empty
939 * strings satisfy the 'if' condition.
941 if (if_then_else->cmp_status == COMPARE_EQUAL) {
942 if (str_len == cur->output.len &&
943 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
944 if_then_else->condition_satisfied = 1;
945 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
946 if (str_len != cur->output.len ||
947 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
948 if_then_else->condition_satisfied = 1;
949 } else if (cur->output.len && !is_empty(&cur->output))
950 if_then_else->condition_satisfied = 1;
951 strbuf_reset(&cur->output);
952 return 0;
955 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
956 struct strbuf *err)
958 struct ref_formatting_stack *prev = state->stack;
959 struct if_then_else *if_then_else = NULL;
961 if (prev->at_end == if_then_else_handler)
962 if_then_else = (struct if_then_else *)prev->at_end_data;
963 if (!if_then_else)
964 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
965 if (!if_then_else->then_atom_seen)
966 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
967 if (if_then_else->else_atom_seen)
968 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
969 if_then_else->else_atom_seen = 1;
970 push_stack_element(&state->stack);
971 state->stack->at_end_data = prev->at_end_data;
972 state->stack->at_end = prev->at_end;
973 return 0;
976 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
977 struct strbuf *err)
979 struct ref_formatting_stack *current = state->stack;
980 struct strbuf s = STRBUF_INIT;
982 if (!current->at_end)
983 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
984 current->at_end(&state->stack);
986 /* Stack may have been popped within at_end(), hence reset the current pointer */
987 current = state->stack;
990 * Perform quote formatting when the stack element is that of
991 * a supporting atom. If nested then perform quote formatting
992 * only on the topmost supporting atom.
994 if (!current->prev->prev) {
995 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
996 strbuf_swap(&current->output, &s);
998 strbuf_release(&s);
999 pop_stack_element(&state->stack);
1000 return 0;
1004 * In a format string, find the next occurrence of %(atom).
1006 static const char *find_next(const char *cp)
1008 while (*cp) {
1009 if (*cp == '%') {
1011 * %( is the start of an atom;
1012 * %% is a quoted per-cent.
1014 if (cp[1] == '(')
1015 return cp;
1016 else if (cp[1] == '%')
1017 cp++; /* skip over two % */
1018 /* otherwise this is a singleton, literal % */
1020 cp++;
1022 return NULL;
1025 static int reject_atom(enum atom_type atom_type)
1027 return atom_type == ATOM_REST;
1031 * Make sure the format string is well formed, and parse out
1032 * the used atoms.
1034 int verify_ref_format(struct ref_format *format)
1036 const char *cp, *sp;
1038 format->need_color_reset_at_eol = 0;
1039 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1040 struct strbuf err = STRBUF_INIT;
1041 const char *color, *ep = strchr(sp, ')');
1042 int at;
1044 if (!ep)
1045 return error(_("malformed format string %s"), sp);
1046 /* sp points at "%(" and ep points at the closing ")" */
1047 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1048 if (at < 0)
1049 die("%s", err.buf);
1050 if (reject_atom(used_atom[at].atom_type))
1051 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1053 if ((format->quote_style == QUOTE_PYTHON ||
1054 format->quote_style == QUOTE_SHELL ||
1055 format->quote_style == QUOTE_TCL) &&
1056 used_atom[at].atom_type == ATOM_RAW &&
1057 used_atom[at].u.raw_data.option == RAW_BARE)
1058 die(_("--format=%.*s cannot be used with "
1059 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1060 cp = ep + 1;
1062 if (skip_prefix(used_atom[at].name, "color:", &color))
1063 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1064 strbuf_release(&err);
1066 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1067 format->need_color_reset_at_eol = 0;
1068 return 0;
1071 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1072 struct used_atom *atom)
1074 switch (atom->u.oid.option) {
1075 case O_FULL:
1076 return oid_to_hex(oid);
1077 case O_LENGTH:
1078 return find_unique_abbrev(oid, atom->u.oid.length);
1079 case O_SHORT:
1080 return find_unique_abbrev(oid, DEFAULT_ABBREV);
1081 default:
1082 BUG("unknown %%(%s) option", field);
1086 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1087 struct atom_value *v, struct used_atom *atom)
1089 if (starts_with(name, field)) {
1090 v->s = xstrdup(do_grab_oid(field, oid, atom));
1091 return 1;
1093 return 0;
1096 /* See grab_values */
1097 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1099 int i;
1101 for (i = 0; i < used_atom_cnt; i++) {
1102 const char *name = used_atom[i].name;
1103 enum atom_type atom_type = used_atom[i].atom_type;
1104 struct atom_value *v = &val[i];
1105 if (!!deref != (*name == '*'))
1106 continue;
1107 if (deref)
1108 name++;
1109 if (atom_type == ATOM_OBJECTTYPE)
1110 v->s = xstrdup(type_name(oi->type));
1111 else if (atom_type == ATOM_OBJECTSIZE) {
1112 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1113 v->value = oi->disk_size;
1114 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1115 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1116 v->value = oi->size;
1117 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1119 } else if (atom_type == ATOM_DELTABASE)
1120 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1121 else if (atom_type == ATOM_OBJECTNAME && deref)
1122 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1126 /* See grab_values */
1127 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1129 int i;
1130 struct tag *tag = (struct tag *) obj;
1132 for (i = 0; i < used_atom_cnt; i++) {
1133 const char *name = used_atom[i].name;
1134 enum atom_type atom_type = used_atom[i].atom_type;
1135 struct atom_value *v = &val[i];
1136 if (!!deref != (*name == '*'))
1137 continue;
1138 if (deref)
1139 name++;
1140 if (atom_type == ATOM_TAG)
1141 v->s = xstrdup(tag->tag);
1142 else if (atom_type == ATOM_TYPE && tag->tagged)
1143 v->s = xstrdup(type_name(tag->tagged->type));
1144 else if (atom_type == ATOM_OBJECT && tag->tagged)
1145 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1149 /* See grab_values */
1150 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1152 int i;
1153 struct commit *commit = (struct commit *) obj;
1155 for (i = 0; i < used_atom_cnt; i++) {
1156 const char *name = used_atom[i].name;
1157 enum atom_type atom_type = used_atom[i].atom_type;
1158 struct atom_value *v = &val[i];
1159 if (!!deref != (*name == '*'))
1160 continue;
1161 if (deref)
1162 name++;
1163 if (atom_type == ATOM_TREE &&
1164 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1165 continue;
1166 if (atom_type == ATOM_NUMPARENT) {
1167 v->value = commit_list_count(commit->parents);
1168 v->s = xstrfmt("%lu", (unsigned long)v->value);
1170 else if (atom_type == ATOM_PARENT) {
1171 struct commit_list *parents;
1172 struct strbuf s = STRBUF_INIT;
1173 for (parents = commit->parents; parents; parents = parents->next) {
1174 struct object_id *oid = &parents->item->object.oid;
1175 if (parents != commit->parents)
1176 strbuf_addch(&s, ' ');
1177 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1179 v->s = strbuf_detach(&s, NULL);
1184 static const char *find_wholine(const char *who, int wholen, const char *buf)
1186 const char *eol;
1187 while (*buf) {
1188 if (!strncmp(buf, who, wholen) &&
1189 buf[wholen] == ' ')
1190 return buf + wholen + 1;
1191 eol = strchr(buf, '\n');
1192 if (!eol)
1193 return "";
1194 eol++;
1195 if (*eol == '\n')
1196 return ""; /* end of header */
1197 buf = eol;
1199 return "";
1202 static const char *copy_line(const char *buf)
1204 const char *eol = strchrnul(buf, '\n');
1205 return xmemdupz(buf, eol - buf);
1208 static const char *copy_name(const char *buf)
1210 const char *cp;
1211 for (cp = buf; *cp && *cp != '\n'; cp++) {
1212 if (starts_with(cp, " <"))
1213 return xmemdupz(buf, cp - buf);
1215 return xstrdup("");
1218 static const char *copy_email(const char *buf, struct used_atom *atom)
1220 const char *email = strchr(buf, '<');
1221 const char *eoemail;
1222 if (!email)
1223 return xstrdup("");
1224 switch (atom->u.email_option.option) {
1225 case EO_RAW:
1226 eoemail = strchr(email, '>');
1227 if (eoemail)
1228 eoemail++;
1229 break;
1230 case EO_TRIM:
1231 email++;
1232 eoemail = strchr(email, '>');
1233 break;
1234 case EO_LOCALPART:
1235 email++;
1236 eoemail = strchr(email, '@');
1237 if (!eoemail)
1238 eoemail = strchr(email, '>');
1239 break;
1240 default:
1241 BUG("unknown email option");
1244 if (!eoemail)
1245 return xstrdup("");
1246 return xmemdupz(email, eoemail - email);
1249 static char *copy_subject(const char *buf, unsigned long len)
1251 struct strbuf sb = STRBUF_INIT;
1252 int i;
1254 for (i = 0; i < len; i++) {
1255 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1256 continue; /* ignore CR in CRLF */
1258 if (buf[i] == '\n')
1259 strbuf_addch(&sb, ' ');
1260 else
1261 strbuf_addch(&sb, buf[i]);
1263 return strbuf_detach(&sb, NULL);
1266 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1268 const char *eoemail = strstr(buf, "> ");
1269 char *zone;
1270 timestamp_t timestamp;
1271 long tz;
1272 struct date_mode date_mode = DATE_MODE_INIT;
1273 const char *formatp;
1276 * We got here because atomname ends in "date" or "date<something>";
1277 * it's not possible that <something> is not ":<format>" because
1278 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1279 * ":" means no format is specified, and use the default.
1281 formatp = strchr(atomname, ':');
1282 if (formatp) {
1283 formatp++;
1284 parse_date_format(formatp, &date_mode);
1287 if (!eoemail)
1288 goto bad;
1289 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1290 if (timestamp == TIME_MAX)
1291 goto bad;
1292 tz = strtol(zone, NULL, 10);
1293 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1294 goto bad;
1295 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1296 v->value = timestamp;
1297 date_mode_release(&date_mode);
1298 return;
1299 bad:
1300 v->s = xstrdup("");
1301 v->value = 0;
1304 /* See grab_values */
1305 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1307 int i;
1308 int wholen = strlen(who);
1309 const char *wholine = NULL;
1311 for (i = 0; i < used_atom_cnt; i++) {
1312 const char *name = used_atom[i].name;
1313 struct atom_value *v = &val[i];
1314 if (!!deref != (*name == '*'))
1315 continue;
1316 if (deref)
1317 name++;
1318 if (strncmp(who, name, wholen))
1319 continue;
1320 if (name[wholen] != 0 &&
1321 strcmp(name + wholen, "name") &&
1322 !starts_with(name + wholen, "email") &&
1323 !starts_with(name + wholen, "date"))
1324 continue;
1325 if (!wholine)
1326 wholine = find_wholine(who, wholen, buf);
1327 if (!wholine)
1328 return; /* no point looking for it */
1329 if (name[wholen] == 0)
1330 v->s = copy_line(wholine);
1331 else if (!strcmp(name + wholen, "name"))
1332 v->s = copy_name(wholine);
1333 else if (starts_with(name + wholen, "email"))
1334 v->s = copy_email(wholine, &used_atom[i]);
1335 else if (starts_with(name + wholen, "date"))
1336 grab_date(wholine, v, name);
1340 * For a tag or a commit object, if "creator" or "creatordate" is
1341 * requested, do something special.
1343 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1344 return; /* "author" for commit object is not wanted */
1345 if (!wholine)
1346 wholine = find_wholine(who, wholen, buf);
1347 if (!wholine)
1348 return;
1349 for (i = 0; i < used_atom_cnt; i++) {
1350 const char *name = used_atom[i].name;
1351 enum atom_type atom_type = used_atom[i].atom_type;
1352 struct atom_value *v = &val[i];
1353 if (!!deref != (*name == '*'))
1354 continue;
1355 if (deref)
1356 name++;
1358 if (atom_type == ATOM_CREATORDATE)
1359 grab_date(wholine, v, name);
1360 else if (atom_type == ATOM_CREATOR)
1361 v->s = copy_line(wholine);
1365 static void find_subpos(const char *buf,
1366 const char **sub, size_t *sublen,
1367 const char **body, size_t *bodylen,
1368 size_t *nonsiglen,
1369 const char **sig, size_t *siglen)
1371 struct strbuf payload = STRBUF_INIT;
1372 struct strbuf signature = STRBUF_INIT;
1373 const char *eol;
1374 const char *end = buf + strlen(buf);
1375 const char *sigstart;
1377 /* parse signature first; we might not even have a subject line */
1378 parse_signature(buf, end - buf, &payload, &signature);
1379 strbuf_release(&payload);
1381 /* skip past header until we hit empty line */
1382 while (*buf && *buf != '\n') {
1383 eol = strchrnul(buf, '\n');
1384 if (*eol)
1385 eol++;
1386 buf = eol;
1388 /* skip any empty lines */
1389 while (*buf == '\n')
1390 buf++;
1391 *sig = strbuf_detach(&signature, siglen);
1392 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1394 /* subject is first non-empty line */
1395 *sub = buf;
1396 /* subject goes to first empty line before signature begins */
1397 if ((eol = strstr(*sub, "\n\n")) ||
1398 (eol = strstr(*sub, "\r\n\r\n"))) {
1399 eol = eol < sigstart ? eol : sigstart;
1400 } else {
1401 /* treat whole message as subject */
1402 eol = sigstart;
1404 buf = eol;
1405 *sublen = buf - *sub;
1406 /* drop trailing newline, if present */
1407 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1408 (*sub)[*sublen - 1] == '\r'))
1409 *sublen -= 1;
1411 /* skip any empty lines */
1412 while (*buf == '\n' || *buf == '\r')
1413 buf++;
1414 *body = buf;
1415 *bodylen = strlen(buf);
1416 *nonsiglen = sigstart - buf;
1420 * If 'lines' is greater than 0, append that many lines from the given
1421 * 'buf' of length 'size' to the given strbuf.
1423 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1425 int i;
1426 const char *sp, *eol;
1427 size_t len;
1429 sp = buf;
1431 for (i = 0; i < lines && sp < buf + size; i++) {
1432 if (i)
1433 strbuf_addstr(out, "\n ");
1434 eol = memchr(sp, '\n', size - (sp - buf));
1435 len = eol ? eol - sp : size - (sp - buf);
1436 strbuf_add(out, sp, len);
1437 if (!eol)
1438 break;
1439 sp = eol + 1;
1443 /* See grab_values */
1444 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1446 int i;
1447 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1448 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1449 void *buf = data->content;
1451 for (i = 0; i < used_atom_cnt; i++) {
1452 struct used_atom *atom = &used_atom[i];
1453 const char *name = atom->name;
1454 struct atom_value *v = &val[i];
1455 enum atom_type atom_type = atom->atom_type;
1457 if (!!deref != (*name == '*'))
1458 continue;
1459 if (deref)
1460 name++;
1462 if (atom_type == ATOM_RAW) {
1463 unsigned long buf_size = data->size;
1465 if (atom->u.raw_data.option == RAW_BARE) {
1466 v->s = xmemdupz(buf, buf_size);
1467 v->s_size = buf_size;
1468 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1469 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1471 continue;
1474 if ((data->type != OBJ_TAG &&
1475 data->type != OBJ_COMMIT) ||
1476 (strcmp(name, "body") &&
1477 !starts_with(name, "subject") &&
1478 !starts_with(name, "trailers") &&
1479 !starts_with(name, "contents")))
1480 continue;
1481 if (!subpos)
1482 find_subpos(buf,
1483 &subpos, &sublen,
1484 &bodypos, &bodylen, &nonsiglen,
1485 &sigpos, &siglen);
1487 if (atom->u.contents.option == C_SUB)
1488 v->s = copy_subject(subpos, sublen);
1489 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1490 struct strbuf sb = STRBUF_INIT;
1491 format_sanitized_subject(&sb, subpos, sublen);
1492 v->s = strbuf_detach(&sb, NULL);
1493 } else if (atom->u.contents.option == C_BODY_DEP)
1494 v->s = xmemdupz(bodypos, bodylen);
1495 else if (atom->u.contents.option == C_LENGTH)
1496 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1497 else if (atom->u.contents.option == C_BODY)
1498 v->s = xmemdupz(bodypos, nonsiglen);
1499 else if (atom->u.contents.option == C_SIG)
1500 v->s = xmemdupz(sigpos, siglen);
1501 else if (atom->u.contents.option == C_LINES) {
1502 struct strbuf s = STRBUF_INIT;
1503 const char *contents_end = bodypos + nonsiglen;
1505 /* Size is the length of the message after removing the signature */
1506 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1507 v->s = strbuf_detach(&s, NULL);
1508 } else if (atom->u.contents.option == C_TRAILERS) {
1509 struct strbuf s = STRBUF_INIT;
1511 /* Format the trailer info according to the trailer_opts given */
1512 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1514 v->s = strbuf_detach(&s, NULL);
1515 } else if (atom->u.contents.option == C_BARE)
1516 v->s = xstrdup(subpos);
1519 free((void *)sigpos);
1523 * We want to have empty print-string for field requests
1524 * that do not apply (e.g. "authordate" for a tag object)
1526 static void fill_missing_values(struct atom_value *val)
1528 int i;
1529 for (i = 0; i < used_atom_cnt; i++) {
1530 struct atom_value *v = &val[i];
1531 if (!v->s)
1532 v->s = xstrdup("");
1537 * val is a list of atom_value to hold returned values. Extract
1538 * the values for atoms in used_atom array out of (obj, buf, sz).
1539 * when deref is false, (obj, buf, sz) is the object that is
1540 * pointed at by the ref itself; otherwise it is the object the
1541 * ref (which is a tag) refers to.
1543 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1545 void *buf = data->content;
1547 switch (obj->type) {
1548 case OBJ_TAG:
1549 grab_tag_values(val, deref, obj);
1550 grab_sub_body_contents(val, deref, data);
1551 grab_person("tagger", val, deref, buf);
1552 break;
1553 case OBJ_COMMIT:
1554 grab_commit_values(val, deref, obj);
1555 grab_sub_body_contents(val, deref, data);
1556 grab_person("author", val, deref, buf);
1557 grab_person("committer", val, deref, buf);
1558 break;
1559 case OBJ_TREE:
1560 /* grab_tree_values(val, deref, obj, buf, sz); */
1561 grab_sub_body_contents(val, deref, data);
1562 break;
1563 case OBJ_BLOB:
1564 /* grab_blob_values(val, deref, obj, buf, sz); */
1565 grab_sub_body_contents(val, deref, data);
1566 break;
1567 default:
1568 die("Eh? Object of type %d?", obj->type);
1572 static inline char *copy_advance(char *dst, const char *src)
1574 while (*src)
1575 *dst++ = *src++;
1576 return dst;
1579 static const char *lstrip_ref_components(const char *refname, int len)
1581 long remaining = len;
1582 const char *start = xstrdup(refname);
1583 const char *to_free = start;
1585 if (len < 0) {
1586 int i;
1587 const char *p = refname;
1589 /* Find total no of '/' separated path-components */
1590 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1593 * The number of components we need to strip is now
1594 * the total minus the components to be left (Plus one
1595 * because we count the number of '/', but the number
1596 * of components is one more than the no of '/').
1598 remaining = i + len + 1;
1601 while (remaining > 0) {
1602 switch (*start++) {
1603 case '\0':
1604 free((char *)to_free);
1605 return xstrdup("");
1606 case '/':
1607 remaining--;
1608 break;
1612 start = xstrdup(start);
1613 free((char *)to_free);
1614 return start;
1617 static const char *rstrip_ref_components(const char *refname, int len)
1619 long remaining = len;
1620 const char *start = xstrdup(refname);
1621 const char *to_free = start;
1623 if (len < 0) {
1624 int i;
1625 const char *p = refname;
1627 /* Find total no of '/' separated path-components */
1628 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1631 * The number of components we need to strip is now
1632 * the total minus the components to be left (Plus one
1633 * because we count the number of '/', but the number
1634 * of components is one more than the no of '/').
1636 remaining = i + len + 1;
1639 while (remaining-- > 0) {
1640 char *p = strrchr(start, '/');
1641 if (!p) {
1642 free((char *)to_free);
1643 return xstrdup("");
1644 } else
1645 p[0] = '\0';
1647 return start;
1650 static const char *show_ref(struct refname_atom *atom, const char *refname)
1652 if (atom->option == R_SHORT)
1653 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1654 else if (atom->option == R_LSTRIP)
1655 return lstrip_ref_components(refname, atom->lstrip);
1656 else if (atom->option == R_RSTRIP)
1657 return rstrip_ref_components(refname, atom->rstrip);
1658 else
1659 return xstrdup(refname);
1662 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1663 struct branch *branch, const char **s)
1665 int num_ours, num_theirs;
1666 if (atom->u.remote_ref.option == RR_REF)
1667 *s = show_ref(&atom->u.remote_ref.refname, refname);
1668 else if (atom->u.remote_ref.option == RR_TRACK) {
1669 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1670 NULL, atom->u.remote_ref.push,
1671 AHEAD_BEHIND_FULL) < 0) {
1672 *s = xstrdup(msgs.gone);
1673 } else if (!num_ours && !num_theirs)
1674 *s = xstrdup("");
1675 else if (!num_ours)
1676 *s = xstrfmt(msgs.behind, num_theirs);
1677 else if (!num_theirs)
1678 *s = xstrfmt(msgs.ahead, num_ours);
1679 else
1680 *s = xstrfmt(msgs.ahead_behind,
1681 num_ours, num_theirs);
1682 if (!atom->u.remote_ref.nobracket && *s[0]) {
1683 const char *to_free = *s;
1684 *s = xstrfmt("[%s]", *s);
1685 free((void *)to_free);
1687 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1688 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1689 NULL, atom->u.remote_ref.push,
1690 AHEAD_BEHIND_FULL) < 0) {
1691 *s = xstrdup("");
1692 return;
1694 if (!num_ours && !num_theirs)
1695 *s = xstrdup("=");
1696 else if (!num_ours)
1697 *s = xstrdup("<");
1698 else if (!num_theirs)
1699 *s = xstrdup(">");
1700 else
1701 *s = xstrdup("<>");
1702 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1703 int explicit;
1704 const char *remote = atom->u.remote_ref.push ?
1705 pushremote_for_branch(branch, &explicit) :
1706 remote_for_branch(branch, &explicit);
1707 *s = xstrdup(explicit ? remote : "");
1708 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1709 const char *merge;
1711 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1712 *s = xstrdup(merge ? merge : "");
1713 } else
1714 BUG("unhandled RR_* enum");
1717 char *get_head_description(void)
1719 struct strbuf desc = STRBUF_INIT;
1720 struct wt_status_state state;
1721 memset(&state, 0, sizeof(state));
1722 wt_status_get_state(the_repository, &state, 1);
1723 if (state.rebase_in_progress ||
1724 state.rebase_interactive_in_progress) {
1725 if (state.branch)
1726 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1727 state.branch);
1728 else
1729 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1730 state.detached_from);
1731 } else if (state.bisect_in_progress)
1732 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1733 state.branch);
1734 else if (state.detached_from) {
1735 if (state.detached_at)
1736 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1737 state.detached_from);
1738 else
1739 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1740 state.detached_from);
1741 } else
1742 strbuf_addstr(&desc, _("(no branch)"));
1744 wt_status_state_free_buffers(&state);
1746 return strbuf_detach(&desc, NULL);
1749 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1751 if (!ref->symref)
1752 return xstrdup("");
1753 else
1754 return show_ref(&atom->u.refname, ref->symref);
1757 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1759 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1760 return get_head_description();
1761 return show_ref(&atom->u.refname, ref->refname);
1764 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1765 struct expand_data *oi, struct strbuf *err)
1767 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1768 int eaten = 1;
1769 if (oi->info.contentp) {
1770 /* We need to know that to use parse_object_buffer properly */
1771 oi->info.sizep = &oi->size;
1772 oi->info.typep = &oi->type;
1774 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1775 OBJECT_INFO_LOOKUP_REPLACE))
1776 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1777 oid_to_hex(&oi->oid), ref->refname);
1778 if (oi->info.disk_sizep && oi->disk_size < 0)
1779 BUG("Object size is less than zero.");
1781 if (oi->info.contentp) {
1782 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1783 if (!*obj) {
1784 if (!eaten)
1785 free(oi->content);
1786 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1787 oid_to_hex(&oi->oid), ref->refname);
1789 grab_values(ref->value, deref, *obj, oi);
1792 grab_common_values(ref->value, deref, oi);
1793 if (!eaten)
1794 free(oi->content);
1795 return 0;
1798 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1800 int i;
1802 for (i = 0; worktrees[i]; i++) {
1803 if (worktrees[i]->head_ref) {
1804 struct ref_to_worktree_entry *entry;
1805 entry = xmalloc(sizeof(*entry));
1806 entry->wt = worktrees[i];
1807 hashmap_entry_init(&entry->ent,
1808 strhash(worktrees[i]->head_ref));
1810 hashmap_add(map, &entry->ent);
1815 static void lazy_init_worktree_map(void)
1817 if (ref_to_worktree_map.worktrees)
1818 return;
1820 ref_to_worktree_map.worktrees = get_worktrees();
1821 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1822 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1825 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1827 struct hashmap_entry entry, *e;
1828 struct ref_to_worktree_entry *lookup_result;
1830 lazy_init_worktree_map();
1832 hashmap_entry_init(&entry, strhash(ref->refname));
1833 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1835 if (!e)
1836 return xstrdup("");
1838 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1840 return xstrdup(lookup_result->wt->path);
1844 * Parse the object referred by ref, and grab needed value.
1846 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1848 struct object *obj;
1849 int i;
1850 struct object_info empty = OBJECT_INFO_INIT;
1852 CALLOC_ARRAY(ref->value, used_atom_cnt);
1854 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1855 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1856 NULL, NULL);
1857 if (!ref->symref)
1858 ref->symref = xstrdup("");
1861 /* Fill in specials first */
1862 for (i = 0; i < used_atom_cnt; i++) {
1863 struct used_atom *atom = &used_atom[i];
1864 enum atom_type atom_type = atom->atom_type;
1865 const char *name = used_atom[i].name;
1866 struct atom_value *v = &ref->value[i];
1867 int deref = 0;
1868 const char *refname;
1869 struct branch *branch = NULL;
1871 v->s_size = ATOM_SIZE_UNSPECIFIED;
1872 v->handler = append_atom;
1873 v->atom = atom;
1875 if (*name == '*') {
1876 deref = 1;
1877 name++;
1880 if (atom_type == ATOM_REFNAME)
1881 refname = get_refname(atom, ref);
1882 else if (atom_type == ATOM_WORKTREEPATH) {
1883 if (ref->kind == FILTER_REFS_BRANCHES)
1884 v->s = get_worktree_path(atom, ref);
1885 else
1886 v->s = xstrdup("");
1887 continue;
1889 else if (atom_type == ATOM_SYMREF)
1890 refname = get_symref(atom, ref);
1891 else if (atom_type == ATOM_UPSTREAM) {
1892 const char *branch_name;
1893 /* only local branches may have an upstream */
1894 if (!skip_prefix(ref->refname, "refs/heads/",
1895 &branch_name)) {
1896 v->s = xstrdup("");
1897 continue;
1899 branch = branch_get(branch_name);
1901 refname = branch_get_upstream(branch, NULL);
1902 if (refname)
1903 fill_remote_ref_details(atom, refname, branch, &v->s);
1904 else
1905 v->s = xstrdup("");
1906 continue;
1907 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1908 const char *branch_name;
1909 v->s = xstrdup("");
1910 if (!skip_prefix(ref->refname, "refs/heads/",
1911 &branch_name))
1912 continue;
1913 branch = branch_get(branch_name);
1915 if (atom->u.remote_ref.push_remote)
1916 refname = NULL;
1917 else {
1918 refname = branch_get_push(branch, NULL);
1919 if (!refname)
1920 continue;
1922 /* We will definitely re-init v->s on the next line. */
1923 free((char *)v->s);
1924 fill_remote_ref_details(atom, refname, branch, &v->s);
1925 continue;
1926 } else if (atom_type == ATOM_COLOR) {
1927 v->s = xstrdup(atom->u.color);
1928 continue;
1929 } else if (atom_type == ATOM_FLAG) {
1930 char buf[256], *cp = buf;
1931 if (ref->flag & REF_ISSYMREF)
1932 cp = copy_advance(cp, ",symref");
1933 if (ref->flag & REF_ISPACKED)
1934 cp = copy_advance(cp, ",packed");
1935 if (cp == buf)
1936 v->s = xstrdup("");
1937 else {
1938 *cp = '\0';
1939 v->s = xstrdup(buf + 1);
1941 continue;
1942 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1943 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1944 continue;
1945 } else if (atom_type == ATOM_HEAD) {
1946 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1947 v->s = xstrdup("*");
1948 else
1949 v->s = xstrdup(" ");
1950 continue;
1951 } else if (atom_type == ATOM_ALIGN) {
1952 v->handler = align_atom_handler;
1953 v->s = xstrdup("");
1954 continue;
1955 } else if (atom_type == ATOM_END) {
1956 v->handler = end_atom_handler;
1957 v->s = xstrdup("");
1958 continue;
1959 } else if (atom_type == ATOM_IF) {
1960 const char *s;
1961 if (skip_prefix(name, "if:", &s))
1962 v->s = xstrdup(s);
1963 else
1964 v->s = xstrdup("");
1965 v->handler = if_atom_handler;
1966 continue;
1967 } else if (atom_type == ATOM_THEN) {
1968 v->handler = then_atom_handler;
1969 v->s = xstrdup("");
1970 continue;
1971 } else if (atom_type == ATOM_ELSE) {
1972 v->handler = else_atom_handler;
1973 v->s = xstrdup("");
1974 continue;
1975 } else if (atom_type == ATOM_REST) {
1976 if (ref->rest)
1977 v->s = xstrdup(ref->rest);
1978 else
1979 v->s = xstrdup("");
1980 continue;
1981 } else
1982 continue;
1984 if (!deref)
1985 v->s = xstrdup(refname);
1986 else
1987 v->s = xstrfmt("%s^{}", refname);
1988 free((char *)refname);
1991 for (i = 0; i < used_atom_cnt; i++) {
1992 struct atom_value *v = &ref->value[i];
1993 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1994 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1995 oid_to_hex(&ref->objectname), ref->refname);
1998 if (need_tagged)
1999 oi.info.contentp = &oi.content;
2000 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2001 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2002 return 0;
2005 oi.oid = ref->objectname;
2006 if (get_object(ref, 0, &obj, &oi, err))
2007 return -1;
2010 * If there is no atom that wants to know about tagged
2011 * object, we are done.
2013 if (!need_tagged || (obj->type != OBJ_TAG))
2014 return 0;
2017 * If it is a tag object, see if we use a value that derefs
2018 * the object, and if we do grab the object it refers to.
2020 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2023 * NEEDSWORK: This derefs tag only once, which
2024 * is good to deal with chains of trust, but
2025 * is not consistent with what deref_tag() does
2026 * which peels the onion to the core.
2028 return get_object(ref, 1, &obj, &oi_deref, err);
2032 * Given a ref, return the value for the atom. This lazily gets value
2033 * out of the object by calling populate value.
2035 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2036 struct atom_value **v, struct strbuf *err)
2038 if (!ref->value) {
2039 if (populate_value(ref, err))
2040 return -1;
2041 fill_missing_values(ref->value);
2043 *v = &ref->value[atom];
2044 return 0;
2048 * Return 1 if the refname matches one of the patterns, otherwise 0.
2049 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2050 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2051 * matches "refs/heads/mas*", too).
2053 static int match_pattern(const struct ref_filter *filter, const char *refname)
2055 const char **patterns = filter->name_patterns;
2056 unsigned flags = 0;
2058 if (filter->ignore_case)
2059 flags |= WM_CASEFOLD;
2062 * When no '--format' option is given we need to skip the prefix
2063 * for matching refs of tags and branches.
2065 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2066 skip_prefix(refname, "refs/heads/", &refname) ||
2067 skip_prefix(refname, "refs/remotes/", &refname) ||
2068 skip_prefix(refname, "refs/", &refname));
2070 for (; *patterns; patterns++) {
2071 if (!wildmatch(*patterns, refname, flags))
2072 return 1;
2074 return 0;
2078 * Return 1 if the refname matches one of the patterns, otherwise 0.
2079 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2080 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2081 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2083 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2085 const char **pattern = filter->name_patterns;
2086 int namelen = strlen(refname);
2087 unsigned flags = WM_PATHNAME;
2089 if (filter->ignore_case)
2090 flags |= WM_CASEFOLD;
2092 for (; *pattern; pattern++) {
2093 const char *p = *pattern;
2094 int plen = strlen(p);
2096 if ((plen <= namelen) &&
2097 !strncmp(refname, p, plen) &&
2098 (refname[plen] == '\0' ||
2099 refname[plen] == '/' ||
2100 p[plen-1] == '/'))
2101 return 1;
2102 if (!wildmatch(p, refname, flags))
2103 return 1;
2105 return 0;
2108 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2109 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2111 if (!*filter->name_patterns)
2112 return 1; /* No pattern always matches */
2113 if (filter->match_as_path)
2114 return match_name_as_path(filter, refname);
2115 return match_pattern(filter, refname);
2119 * This is the same as for_each_fullref_in(), but it tries to iterate
2120 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2121 * pattern match, so the callback still has to match each ref individually.
2123 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2124 each_ref_fn cb,
2125 void *cb_data)
2127 if (!filter->match_as_path) {
2129 * in this case, the patterns are applied after
2130 * prefixes like "refs/heads/" etc. are stripped off,
2131 * so we have to look at everything:
2133 return for_each_fullref_in("", cb, cb_data);
2136 if (filter->ignore_case) {
2138 * we can't handle case-insensitive comparisons,
2139 * so just return everything and let the caller
2140 * sort it out.
2142 return for_each_fullref_in("", cb, cb_data);
2145 if (!filter->name_patterns[0]) {
2146 /* no patterns; we have to look at everything */
2147 return for_each_fullref_in("", cb, cb_data);
2150 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2151 NULL, filter->name_patterns,
2152 cb, cb_data);
2156 * Given a ref (oid, refname), check if the ref belongs to the array
2157 * of oids. If the given ref is a tag, check if the given tag points
2158 * at one of the oids in the given oid array.
2159 * NEEDSWORK:
2160 * 1. Only a single level of indirection is obtained, we might want to
2161 * change this to account for multiple levels (e.g. annotated tags
2162 * pointing to annotated tags pointing to a commit.)
2163 * 2. As the refs are cached we might know what refname peels to without
2164 * the need to parse the object via parse_object(). peel_ref() might be a
2165 * more efficient alternative to obtain the pointee.
2167 static const struct object_id *match_points_at(struct oid_array *points_at,
2168 const struct object_id *oid,
2169 const char *refname)
2171 const struct object_id *tagged_oid = NULL;
2172 struct object *obj;
2174 if (oid_array_lookup(points_at, oid) >= 0)
2175 return oid;
2176 obj = parse_object(the_repository, oid);
2177 if (!obj)
2178 die(_("malformed object at '%s'"), refname);
2179 if (obj->type == OBJ_TAG)
2180 tagged_oid = get_tagged_oid((struct tag *)obj);
2181 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2182 return tagged_oid;
2183 return NULL;
2187 * Allocate space for a new ref_array_item and copy the name and oid to it.
2189 * Callers can then fill in other struct members at their leisure.
2191 static struct ref_array_item *new_ref_array_item(const char *refname,
2192 const struct object_id *oid)
2194 struct ref_array_item *ref;
2196 FLEX_ALLOC_STR(ref, refname, refname);
2197 oidcpy(&ref->objectname, oid);
2198 ref->rest = NULL;
2200 return ref;
2203 struct ref_array_item *ref_array_push(struct ref_array *array,
2204 const char *refname,
2205 const struct object_id *oid)
2207 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2209 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2210 array->items[array->nr++] = ref;
2212 return ref;
2215 static int ref_kind_from_refname(const char *refname)
2217 unsigned int i;
2219 static struct {
2220 const char *prefix;
2221 unsigned int kind;
2222 } ref_kind[] = {
2223 { "refs/heads/" , FILTER_REFS_BRANCHES },
2224 { "refs/remotes/" , FILTER_REFS_REMOTES },
2225 { "refs/tags/", FILTER_REFS_TAGS}
2228 if (!strcmp(refname, "HEAD"))
2229 return FILTER_REFS_DETACHED_HEAD;
2231 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2232 if (starts_with(refname, ref_kind[i].prefix))
2233 return ref_kind[i].kind;
2236 return FILTER_REFS_OTHERS;
2239 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2241 if (filter->kind == FILTER_REFS_BRANCHES ||
2242 filter->kind == FILTER_REFS_REMOTES ||
2243 filter->kind == FILTER_REFS_TAGS)
2244 return filter->kind;
2245 return ref_kind_from_refname(refname);
2248 struct ref_filter_cbdata {
2249 struct ref_array *array;
2250 struct ref_filter *filter;
2251 struct contains_cache contains_cache;
2252 struct contains_cache no_contains_cache;
2256 * A call-back given to for_each_ref(). Filter refs and keep them for
2257 * later object processing.
2259 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2261 struct ref_filter_cbdata *ref_cbdata = cb_data;
2262 struct ref_filter *filter = ref_cbdata->filter;
2263 struct ref_array_item *ref;
2264 struct commit *commit = NULL;
2265 unsigned int kind;
2267 if (flag & REF_BAD_NAME) {
2268 warning(_("ignoring ref with broken name %s"), refname);
2269 return 0;
2272 if (flag & REF_ISBROKEN) {
2273 warning(_("ignoring broken ref %s"), refname);
2274 return 0;
2277 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2278 kind = filter_ref_kind(filter, refname);
2279 if (!(kind & filter->kind))
2280 return 0;
2282 if (!filter_pattern_match(filter, refname))
2283 return 0;
2285 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2286 return 0;
2289 * A merge filter is applied on refs pointing to commits. Hence
2290 * obtain the commit using the 'oid' available and discard all
2291 * non-commits early. The actual filtering is done later.
2293 if (filter->reachable_from || filter->unreachable_from ||
2294 filter->with_commit || filter->no_commit || filter->verbose) {
2295 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2296 if (!commit)
2297 return 0;
2298 /* We perform the filtering for the '--contains' option... */
2299 if (filter->with_commit &&
2300 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2301 return 0;
2302 /* ...or for the `--no-contains' option */
2303 if (filter->no_commit &&
2304 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2305 return 0;
2309 * We do not open the object yet; sort may only need refname
2310 * to do its job and the resulting list may yet to be pruned
2311 * by maxcount logic.
2313 ref = ref_array_push(ref_cbdata->array, refname, oid);
2314 ref->commit = commit;
2315 ref->flag = flag;
2316 ref->kind = kind;
2318 return 0;
2321 /* Free memory allocated for a ref_array_item */
2322 static void free_array_item(struct ref_array_item *item)
2324 free((char *)item->symref);
2325 if (item->value) {
2326 int i;
2327 for (i = 0; i < used_atom_cnt; i++)
2328 free((char *)item->value[i].s);
2329 free(item->value);
2331 free(item);
2334 /* Free all memory allocated for ref_array */
2335 void ref_array_clear(struct ref_array *array)
2337 int i;
2339 for (i = 0; i < array->nr; i++)
2340 free_array_item(array->items[i]);
2341 FREE_AND_NULL(array->items);
2342 array->nr = array->alloc = 0;
2344 for (i = 0; i < used_atom_cnt; i++) {
2345 struct used_atom *atom = &used_atom[i];
2346 if (atom->atom_type == ATOM_HEAD)
2347 free(atom->u.head);
2348 free((char *)atom->name);
2350 FREE_AND_NULL(used_atom);
2351 used_atom_cnt = 0;
2353 if (ref_to_worktree_map.worktrees) {
2354 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2355 struct ref_to_worktree_entry, ent);
2356 free_worktrees(ref_to_worktree_map.worktrees);
2357 ref_to_worktree_map.worktrees = NULL;
2361 #define EXCLUDE_REACHED 0
2362 #define INCLUDE_REACHED 1
2363 static void reach_filter(struct ref_array *array,
2364 struct commit_list *check_reachable,
2365 int include_reached)
2367 struct rev_info revs;
2368 int i, old_nr;
2369 struct commit **to_clear;
2370 struct commit_list *cr;
2372 if (!check_reachable)
2373 return;
2375 CALLOC_ARRAY(to_clear, array->nr);
2377 repo_init_revisions(the_repository, &revs, NULL);
2379 for (i = 0; i < array->nr; i++) {
2380 struct ref_array_item *item = array->items[i];
2381 add_pending_object(&revs, &item->commit->object, item->refname);
2382 to_clear[i] = item->commit;
2385 for (cr = check_reachable; cr; cr = cr->next) {
2386 struct commit *merge_commit = cr->item;
2387 merge_commit->object.flags |= UNINTERESTING;
2388 add_pending_object(&revs, &merge_commit->object, "");
2391 revs.limited = 1;
2392 if (prepare_revision_walk(&revs))
2393 die(_("revision walk setup failed"));
2395 old_nr = array->nr;
2396 array->nr = 0;
2398 for (i = 0; i < old_nr; i++) {
2399 struct ref_array_item *item = array->items[i];
2400 struct commit *commit = item->commit;
2402 int is_merged = !!(commit->object.flags & UNINTERESTING);
2404 if (is_merged == include_reached)
2405 array->items[array->nr++] = array->items[i];
2406 else
2407 free_array_item(item);
2410 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2412 while (check_reachable) {
2413 struct commit *merge_commit = pop_commit(&check_reachable);
2414 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2417 release_revisions(&revs);
2418 free(to_clear);
2422 * API for filtering a set of refs. Based on the type of refs the user
2423 * has requested, we iterate through those refs and apply filters
2424 * as per the given ref_filter structure and finally store the
2425 * filtered refs in the ref_array structure.
2427 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2429 struct ref_filter_cbdata ref_cbdata;
2430 int save_commit_buffer_orig;
2431 int ret = 0;
2433 ref_cbdata.array = array;
2434 ref_cbdata.filter = filter;
2436 filter->kind = type & FILTER_REFS_KIND_MASK;
2438 save_commit_buffer_orig = save_commit_buffer;
2439 save_commit_buffer = 0;
2441 init_contains_cache(&ref_cbdata.contains_cache);
2442 init_contains_cache(&ref_cbdata.no_contains_cache);
2444 /* Simple per-ref filtering */
2445 if (!filter->kind)
2446 die("filter_refs: invalid type");
2447 else {
2449 * For common cases where we need only branches or remotes or tags,
2450 * we only iterate through those refs. If a mix of refs is needed,
2451 * we iterate over all refs and filter out required refs with the help
2452 * of filter_ref_kind().
2454 if (filter->kind == FILTER_REFS_BRANCHES)
2455 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2456 else if (filter->kind == FILTER_REFS_REMOTES)
2457 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2458 else if (filter->kind == FILTER_REFS_TAGS)
2459 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2460 else if (filter->kind & FILTER_REFS_ALL)
2461 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2462 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2463 head_ref(ref_filter_handler, &ref_cbdata);
2466 clear_contains_cache(&ref_cbdata.contains_cache);
2467 clear_contains_cache(&ref_cbdata.no_contains_cache);
2469 /* Filters that need revision walking */
2470 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2471 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2473 save_commit_buffer = save_commit_buffer_orig;
2474 return ret;
2477 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2479 if (!(a->kind ^ b->kind))
2480 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2481 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2482 return -1;
2483 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2484 return 1;
2485 BUG("should have died in the xor check above");
2486 return 0;
2489 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2491 const char *s1 = vs1, *s2 = vs2;
2492 const char *end = s1 + n;
2494 for (; s1 < end; s1++, s2++) {
2495 int diff = tolower(*s1) - tolower(*s2);
2496 if (diff)
2497 return diff;
2499 return 0;
2502 struct ref_sorting {
2503 struct ref_sorting *next;
2504 int atom; /* index into used_atom array (internal) */
2505 enum ref_sorting_order sort_flags;
2508 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2510 struct atom_value *va, *vb;
2511 int cmp;
2512 int cmp_detached_head = 0;
2513 cmp_type cmp_type = used_atom[s->atom].type;
2514 struct strbuf err = STRBUF_INIT;
2516 if (get_ref_atom_value(a, s->atom, &va, &err))
2517 die("%s", err.buf);
2518 if (get_ref_atom_value(b, s->atom, &vb, &err))
2519 die("%s", err.buf);
2520 strbuf_release(&err);
2521 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2522 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2523 cmp = compare_detached_head(a, b);
2524 cmp_detached_head = 1;
2525 } else if (s->sort_flags & REF_SORTING_VERSION) {
2526 cmp = versioncmp(va->s, vb->s);
2527 } else if (cmp_type == FIELD_STR) {
2528 if (va->s_size < 0 && vb->s_size < 0) {
2529 int (*cmp_fn)(const char *, const char *);
2530 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2531 ? strcasecmp : strcmp;
2532 cmp = cmp_fn(va->s, vb->s);
2533 } else {
2534 size_t a_size = va->s_size < 0 ?
2535 strlen(va->s) : va->s_size;
2536 size_t b_size = vb->s_size < 0 ?
2537 strlen(vb->s) : vb->s_size;
2538 int (*cmp_fn)(const void *, const void *, size_t);
2539 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2540 ? memcasecmp : memcmp;
2542 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2543 a_size : b_size);
2544 if (!cmp) {
2545 if (a_size > b_size)
2546 cmp = 1;
2547 else if (a_size < b_size)
2548 cmp = -1;
2551 } else {
2552 if (va->value < vb->value)
2553 cmp = -1;
2554 else if (va->value == vb->value)
2555 cmp = 0;
2556 else
2557 cmp = 1;
2560 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2561 ? -cmp : cmp;
2564 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2566 struct ref_array_item *a = *((struct ref_array_item **)a_);
2567 struct ref_array_item *b = *((struct ref_array_item **)b_);
2568 struct ref_sorting *s;
2570 for (s = ref_sorting; s; s = s->next) {
2571 int cmp = cmp_ref_sorting(s, a, b);
2572 if (cmp)
2573 return cmp;
2575 s = ref_sorting;
2576 return s && s->sort_flags & REF_SORTING_ICASE ?
2577 strcasecmp(a->refname, b->refname) :
2578 strcmp(a->refname, b->refname);
2581 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2582 unsigned int mask, int on)
2584 for (; sorting; sorting = sorting->next) {
2585 if (on)
2586 sorting->sort_flags |= mask;
2587 else
2588 sorting->sort_flags &= ~mask;
2592 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2594 QSORT_S(array->items, array->nr, compare_refs, sorting);
2597 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2599 struct strbuf *s = &state->stack->output;
2601 while (*cp && (!ep || cp < ep)) {
2602 if (*cp == '%') {
2603 if (cp[1] == '%')
2604 cp++;
2605 else {
2606 int ch = hex2chr(cp + 1);
2607 if (0 <= ch) {
2608 strbuf_addch(s, ch);
2609 cp += 3;
2610 continue;
2614 strbuf_addch(s, *cp);
2615 cp++;
2619 int format_ref_array_item(struct ref_array_item *info,
2620 struct ref_format *format,
2621 struct strbuf *final_buf,
2622 struct strbuf *error_buf)
2624 const char *cp, *sp, *ep;
2625 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2627 state.quote_style = format->quote_style;
2628 push_stack_element(&state.stack);
2630 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2631 struct atom_value *atomv;
2632 int pos;
2634 ep = strchr(sp, ')');
2635 if (cp < sp)
2636 append_literal(cp, sp, &state);
2637 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2638 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2639 atomv->handler(atomv, &state, error_buf)) {
2640 pop_stack_element(&state.stack);
2641 return -1;
2644 if (*cp) {
2645 sp = cp + strlen(cp);
2646 append_literal(cp, sp, &state);
2648 if (format->need_color_reset_at_eol) {
2649 struct atom_value resetv = ATOM_VALUE_INIT;
2650 resetv.s = GIT_COLOR_RESET;
2651 if (append_atom(&resetv, &state, error_buf)) {
2652 pop_stack_element(&state.stack);
2653 return -1;
2656 if (state.stack->prev) {
2657 pop_stack_element(&state.stack);
2658 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2660 strbuf_addbuf(final_buf, &state.stack->output);
2661 pop_stack_element(&state.stack);
2662 return 0;
2665 void pretty_print_ref(const char *name, const struct object_id *oid,
2666 struct ref_format *format)
2668 struct ref_array_item *ref_item;
2669 struct strbuf output = STRBUF_INIT;
2670 struct strbuf err = STRBUF_INIT;
2672 ref_item = new_ref_array_item(name, oid);
2673 ref_item->kind = ref_kind_from_refname(name);
2674 if (format_ref_array_item(ref_item, format, &output, &err))
2675 die("%s", err.buf);
2676 fwrite(output.buf, 1, output.len, stdout);
2677 putchar('\n');
2679 strbuf_release(&err);
2680 strbuf_release(&output);
2681 free_array_item(ref_item);
2684 static int parse_sorting_atom(const char *atom)
2687 * This parses an atom using a dummy ref_format, since we don't
2688 * actually care about the formatting details.
2690 struct ref_format dummy = REF_FORMAT_INIT;
2691 const char *end = atom + strlen(atom);
2692 struct strbuf err = STRBUF_INIT;
2693 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2694 if (res < 0)
2695 die("%s", err.buf);
2696 strbuf_release(&err);
2697 return res;
2700 /* If no sorting option is given, use refname to sort as default */
2701 static struct ref_sorting *ref_default_sorting(void)
2703 static const char cstr_name[] = "refname";
2705 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2707 sorting->next = NULL;
2708 sorting->atom = parse_sorting_atom(cstr_name);
2709 return sorting;
2712 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2714 struct ref_sorting *s;
2716 CALLOC_ARRAY(s, 1);
2717 s->next = *sorting_tail;
2718 *sorting_tail = s;
2720 if (*arg == '-') {
2721 s->sort_flags |= REF_SORTING_REVERSE;
2722 arg++;
2724 if (skip_prefix(arg, "version:", &arg) ||
2725 skip_prefix(arg, "v:", &arg))
2726 s->sort_flags |= REF_SORTING_VERSION;
2727 s->atom = parse_sorting_atom(arg);
2730 struct ref_sorting *ref_sorting_options(struct string_list *options)
2732 struct string_list_item *item;
2733 struct ref_sorting *sorting = NULL, **tail = &sorting;
2735 if (!options->nr) {
2736 sorting = ref_default_sorting();
2737 } else {
2738 for_each_string_list_item(item, options)
2739 parse_ref_sorting(tail, item->string);
2743 * From here on, the ref_sorting list should be used to talk
2744 * about the sort order used for the output. The caller
2745 * should not touch the string form anymore.
2747 string_list_clear(options, 0);
2748 return sorting;
2751 void ref_sorting_release(struct ref_sorting *sorting)
2753 while (sorting) {
2754 struct ref_sorting *next = sorting->next;
2755 free(sorting);
2756 sorting = next;
2760 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2762 struct ref_filter *rf = opt->value;
2763 struct object_id oid;
2764 struct commit *merge_commit;
2766 BUG_ON_OPT_NEG(unset);
2768 if (get_oid(arg, &oid))
2769 die(_("malformed object name %s"), arg);
2771 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2773 if (!merge_commit)
2774 return error(_("option `%s' must point to a commit"), opt->long_name);
2776 if (starts_with(opt->long_name, "no"))
2777 commit_list_insert(merge_commit, &rf->unreachable_from);
2778 else
2779 commit_list_insert(merge_commit, &rf->reachable_from);
2781 return 0;