diff-lib: stop calling diff_setup_done() in do_diff_cache()
[alt-git.git] / ref-filter.c
blobcaf10ab23eb49520d674654c52e585fb2d96307a
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 color_atom_parser(struct ref_format *format, struct used_atom *atom,
232 const char *color_value, struct strbuf *err)
234 if (!color_value)
235 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
236 if (color_parse(color_value, atom->u.color) < 0)
237 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
238 color_value);
240 * We check this after we've parsed the color, which lets us complain
241 * about syntactically bogus color names even if they won't be used.
243 if (!want_color(format->use_color))
244 color_parse("", atom->u.color);
245 return 0;
248 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
249 const char *name, struct strbuf *err)
251 if (!arg)
252 atom->option = R_NORMAL;
253 else if (!strcmp(arg, "short"))
254 atom->option = R_SHORT;
255 else if (skip_prefix(arg, "lstrip=", &arg) ||
256 skip_prefix(arg, "strip=", &arg)) {
257 atom->option = R_LSTRIP;
258 if (strtol_i(arg, 10, &atom->lstrip))
259 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
260 } else if (skip_prefix(arg, "rstrip=", &arg)) {
261 atom->option = R_RSTRIP;
262 if (strtol_i(arg, 10, &atom->rstrip))
263 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
264 } else
265 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
266 return 0;
269 static int remote_ref_atom_parser(struct ref_format *format, struct used_atom *atom,
270 const char *arg, struct strbuf *err)
272 struct string_list params = STRING_LIST_INIT_DUP;
273 int i;
275 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
276 atom->u.remote_ref.push = 1;
278 if (!arg) {
279 atom->u.remote_ref.option = RR_REF;
280 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
281 arg, atom->name, err);
284 atom->u.remote_ref.nobracket = 0;
285 string_list_split(&params, arg, ',', -1);
287 for (i = 0; i < params.nr; i++) {
288 const char *s = params.items[i].string;
290 if (!strcmp(s, "track"))
291 atom->u.remote_ref.option = RR_TRACK;
292 else if (!strcmp(s, "trackshort"))
293 atom->u.remote_ref.option = RR_TRACKSHORT;
294 else if (!strcmp(s, "nobracket"))
295 atom->u.remote_ref.nobracket = 1;
296 else if (!strcmp(s, "remotename")) {
297 atom->u.remote_ref.option = RR_REMOTE_NAME;
298 atom->u.remote_ref.push_remote = 1;
299 } else if (!strcmp(s, "remoteref")) {
300 atom->u.remote_ref.option = RR_REMOTE_REF;
301 atom->u.remote_ref.push_remote = 1;
302 } else {
303 atom->u.remote_ref.option = RR_REF;
304 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
305 arg, atom->name, err)) {
306 string_list_clear(&params, 0);
307 return -1;
312 string_list_clear(&params, 0);
313 return 0;
316 static int objecttype_atom_parser(struct ref_format *format, struct used_atom *atom,
317 const char *arg, struct strbuf *err)
319 if (arg)
320 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
321 if (*atom->name == '*')
322 oi_deref.info.typep = &oi_deref.type;
323 else
324 oi.info.typep = &oi.type;
325 return 0;
328 static int objectsize_atom_parser(struct ref_format *format, struct used_atom *atom,
329 const char *arg, struct strbuf *err)
331 if (!arg) {
332 atom->u.objectsize.option = O_SIZE;
333 if (*atom->name == '*')
334 oi_deref.info.sizep = &oi_deref.size;
335 else
336 oi.info.sizep = &oi.size;
337 } else if (!strcmp(arg, "disk")) {
338 atom->u.objectsize.option = O_SIZE_DISK;
339 if (*atom->name == '*')
340 oi_deref.info.disk_sizep = &oi_deref.disk_size;
341 else
342 oi.info.disk_sizep = &oi.disk_size;
343 } else
344 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), "objectsize", arg);
345 return 0;
348 static int deltabase_atom_parser(struct ref_format *format, struct used_atom *atom,
349 const char *arg, struct strbuf *err)
351 if (arg)
352 return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
353 if (*atom->name == '*')
354 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
355 else
356 oi.info.delta_base_oid = &oi.delta_base_oid;
357 return 0;
360 static int body_atom_parser(struct ref_format *format, struct used_atom *atom,
361 const char *arg, struct strbuf *err)
363 if (arg)
364 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
365 atom->u.contents.option = C_BODY_DEP;
366 return 0;
369 static int subject_atom_parser(struct ref_format *format, struct used_atom *atom,
370 const char *arg, struct strbuf *err)
372 if (!arg)
373 atom->u.contents.option = C_SUB;
374 else if (!strcmp(arg, "sanitize"))
375 atom->u.contents.option = C_SUB_SANITIZE;
376 else
377 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), "subject", arg);
378 return 0;
381 static int trailers_atom_parser(struct ref_format *format, struct used_atom *atom,
382 const char *arg, struct strbuf *err)
384 atom->u.contents.trailer_opts.no_divider = 1;
386 if (arg) {
387 const char *argbuf = xstrfmt("%s)", arg);
388 char *invalid_arg = NULL;
390 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
391 &ref_trailer_buf.filter_list,
392 &ref_trailer_buf.sepbuf,
393 &ref_trailer_buf.kvsepbuf,
394 &argbuf, &invalid_arg)) {
395 if (!invalid_arg)
396 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
397 else
398 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
399 free((char *)invalid_arg);
400 return -1;
403 atom->u.contents.option = C_TRAILERS;
404 return 0;
407 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
408 const char *arg, struct strbuf *err)
410 if (!arg)
411 atom->u.contents.option = C_BARE;
412 else if (!strcmp(arg, "body"))
413 atom->u.contents.option = C_BODY;
414 else if (!strcmp(arg, "size"))
415 atom->u.contents.option = C_LENGTH;
416 else if (!strcmp(arg, "signature"))
417 atom->u.contents.option = C_SIG;
418 else if (!strcmp(arg, "subject"))
419 atom->u.contents.option = C_SUB;
420 else if (!strcmp(arg, "trailers")) {
421 if (trailers_atom_parser(format, atom, NULL, err))
422 return -1;
423 } else if (skip_prefix(arg, "trailers:", &arg)) {
424 if (trailers_atom_parser(format, atom, arg, err))
425 return -1;
426 } else if (skip_prefix(arg, "lines=", &arg)) {
427 atom->u.contents.option = C_LINES;
428 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
429 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
430 } else
431 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), "contents", arg);
432 return 0;
435 static int raw_atom_parser(struct ref_format *format, struct used_atom *atom,
436 const char *arg, struct strbuf *err)
438 if (!arg)
439 atom->u.raw_data.option = RAW_BARE;
440 else if (!strcmp(arg, "size"))
441 atom->u.raw_data.option = RAW_LENGTH;
442 else
443 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), "raw", arg);
444 return 0;
447 static int oid_atom_parser(struct ref_format *format, struct used_atom *atom,
448 const char *arg, struct strbuf *err)
450 if (!arg)
451 atom->u.oid.option = O_FULL;
452 else if (!strcmp(arg, "short"))
453 atom->u.oid.option = O_SHORT;
454 else if (skip_prefix(arg, "short=", &arg)) {
455 atom->u.oid.option = O_LENGTH;
456 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
457 atom->u.oid.length == 0)
458 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
459 if (atom->u.oid.length < MINIMUM_ABBREV)
460 atom->u.oid.length = MINIMUM_ABBREV;
461 } else
462 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), atom->name, arg);
463 return 0;
466 static int person_email_atom_parser(struct ref_format *format, struct used_atom *atom,
467 const char *arg, struct strbuf *err)
469 if (!arg)
470 atom->u.email_option.option = EO_RAW;
471 else if (!strcmp(arg, "trim"))
472 atom->u.email_option.option = EO_TRIM;
473 else if (!strcmp(arg, "localpart"))
474 atom->u.email_option.option = EO_LOCALPART;
475 else
476 return strbuf_addf_ret(err, -1, _("unrecognized email option: %s"), arg);
477 return 0;
480 static int refname_atom_parser(struct ref_format *format, struct used_atom *atom,
481 const char *arg, struct strbuf *err)
483 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
486 static align_type parse_align_position(const char *s)
488 if (!strcmp(s, "right"))
489 return ALIGN_RIGHT;
490 else if (!strcmp(s, "middle"))
491 return ALIGN_MIDDLE;
492 else if (!strcmp(s, "left"))
493 return ALIGN_LEFT;
494 return -1;
497 static int align_atom_parser(struct ref_format *format, struct used_atom *atom,
498 const char *arg, struct strbuf *err)
500 struct align *align = &atom->u.align;
501 struct string_list params = STRING_LIST_INIT_DUP;
502 int i;
503 unsigned int width = ~0U;
505 if (!arg)
506 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
508 align->position = ALIGN_LEFT;
510 string_list_split(&params, arg, ',', -1);
511 for (i = 0; i < params.nr; i++) {
512 const char *s = params.items[i].string;
513 int position;
515 if (skip_prefix(s, "position=", &s)) {
516 position = parse_align_position(s);
517 if (position < 0) {
518 strbuf_addf(err, _("unrecognized position:%s"), s);
519 string_list_clear(&params, 0);
520 return -1;
522 align->position = position;
523 } else if (skip_prefix(s, "width=", &s)) {
524 if (strtoul_ui(s, 10, &width)) {
525 strbuf_addf(err, _("unrecognized width:%s"), s);
526 string_list_clear(&params, 0);
527 return -1;
529 } else if (!strtoul_ui(s, 10, &width))
531 else if ((position = parse_align_position(s)) >= 0)
532 align->position = position;
533 else {
534 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
535 string_list_clear(&params, 0);
536 return -1;
540 if (width == ~0U) {
541 string_list_clear(&params, 0);
542 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
544 align->width = width;
545 string_list_clear(&params, 0);
546 return 0;
549 static int if_atom_parser(struct ref_format *format, struct used_atom *atom,
550 const char *arg, struct strbuf *err)
552 if (!arg) {
553 atom->u.if_then_else.cmp_status = COMPARE_NONE;
554 return 0;
555 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
556 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
557 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
558 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
559 } else
560 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), "if", arg);
561 return 0;
564 static int rest_atom_parser(struct ref_format *format, struct used_atom *atom,
565 const char *arg, struct strbuf *err)
567 if (arg)
568 return strbuf_addf_ret(err, -1, _("%%(rest) does not take arguments"));
569 format->use_rest = 1;
570 return 0;
573 static int head_atom_parser(struct ref_format *format, struct used_atom *atom,
574 const char *arg, struct strbuf *unused_err)
576 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
577 return 0;
580 static struct {
581 const char *name;
582 info_source source;
583 cmp_type cmp_type;
584 int (*parser)(struct ref_format *format, struct used_atom *atom,
585 const char *arg, struct strbuf *err);
586 } valid_atom[] = {
587 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
588 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
589 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
590 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
591 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
592 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
593 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
594 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
595 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
596 [ATOM_TYPE] = { "type", SOURCE_OBJ },
597 [ATOM_TAG] = { "tag", SOURCE_OBJ },
598 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
599 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
600 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
601 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
602 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
603 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
604 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
605 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
606 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
607 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
608 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
609 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
610 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
611 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
612 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
613 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
614 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
615 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
616 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
617 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
618 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
619 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
620 [ATOM_FLAG] = { "flag", SOURCE_NONE },
621 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
622 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
623 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
624 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
625 [ATOM_END] = { "end", SOURCE_NONE },
626 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
627 [ATOM_THEN] = { "then", SOURCE_NONE },
628 [ATOM_ELSE] = { "else", SOURCE_NONE },
629 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
631 * Please update $__git_ref_fieldlist in git-completion.bash
632 * when you add new atoms
636 #define REF_FORMATTING_STATE_INIT { 0 }
638 struct ref_formatting_stack {
639 struct ref_formatting_stack *prev;
640 struct strbuf output;
641 void (*at_end)(struct ref_formatting_stack **stack);
642 void *at_end_data;
645 struct ref_formatting_state {
646 int quote_style;
647 struct ref_formatting_stack *stack;
650 struct atom_value {
651 const char *s;
652 ssize_t s_size;
653 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
654 struct strbuf *err);
655 uintmax_t value; /* used for sorting when not FIELD_STR */
656 struct used_atom *atom;
659 #define ATOM_SIZE_UNSPECIFIED (-1)
661 #define ATOM_VALUE_INIT { \
662 .s_size = ATOM_SIZE_UNSPECIFIED \
666 * Used to parse format string and sort specifiers
668 static int parse_ref_filter_atom(struct ref_format *format,
669 const char *atom, const char *ep,
670 struct strbuf *err)
672 const char *sp;
673 const char *arg;
674 int i, at, atom_len;
676 sp = atom;
677 if (*sp == '*' && sp < ep)
678 sp++; /* deref */
679 if (ep <= sp)
680 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
681 (int)(ep-atom), atom);
684 * If the atom name has a colon, strip it and everything after
685 * it off - it specifies the format for this entry, and
686 * shouldn't be used for checking against the valid_atom
687 * table.
689 arg = memchr(sp, ':', ep - sp);
690 atom_len = (arg ? arg : ep) - sp;
692 /* Do we have the atom already used elsewhere? */
693 for (i = 0; i < used_atom_cnt; i++) {
694 int len = strlen(used_atom[i].name);
695 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
696 return i;
699 /* Is the atom a valid one? */
700 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
701 int len = strlen(valid_atom[i].name);
702 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
703 break;
706 if (ARRAY_SIZE(valid_atom) <= i)
707 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
708 (int)(ep-atom), atom);
709 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
710 return strbuf_addf_ret(err, -1,
711 _("not a git repository, but the field '%.*s' requires access to object data"),
712 (int)(ep-atom), atom);
714 /* Add it in, including the deref prefix */
715 at = used_atom_cnt;
716 used_atom_cnt++;
717 REALLOC_ARRAY(used_atom, used_atom_cnt);
718 used_atom[at].atom_type = i;
719 used_atom[at].name = xmemdupz(atom, ep - atom);
720 used_atom[at].type = valid_atom[i].cmp_type;
721 used_atom[at].source = valid_atom[i].source;
722 if (used_atom[at].source == SOURCE_OBJ) {
723 if (*atom == '*')
724 oi_deref.info.contentp = &oi_deref.content;
725 else
726 oi.info.contentp = &oi.content;
728 if (arg) {
729 arg = used_atom[at].name + (arg - atom) + 1;
730 if (!*arg) {
732 * Treat empty sub-arguments list as NULL (i.e.,
733 * "%(atom:)" is equivalent to "%(atom)").
735 arg = NULL;
738 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
739 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
740 return -1;
741 if (*atom == '*')
742 need_tagged = 1;
743 if (i == ATOM_SYMREF)
744 need_symref = 1;
745 return at;
748 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
750 switch (quote_style) {
751 case QUOTE_NONE:
752 if (len < 0)
753 strbuf_addstr(s, str);
754 else
755 strbuf_add(s, str, len);
756 break;
757 case QUOTE_SHELL:
758 sq_quote_buf(s, str);
759 break;
760 case QUOTE_PERL:
761 if (len < 0)
762 perl_quote_buf(s, str);
763 else
764 perl_quote_buf_with_len(s, str, len);
765 break;
766 case QUOTE_PYTHON:
767 python_quote_buf(s, str);
768 break;
769 case QUOTE_TCL:
770 tcl_quote_buf(s, str);
771 break;
775 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
776 struct strbuf *unused_err)
779 * Quote formatting is only done when the stack has a single
780 * element. Otherwise quote formatting is done on the
781 * element's entire output strbuf when the %(end) atom is
782 * encountered.
784 if (!state->stack->prev)
785 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
786 else if (v->s_size < 0)
787 strbuf_addstr(&state->stack->output, v->s);
788 else
789 strbuf_add(&state->stack->output, v->s, v->s_size);
790 return 0;
793 static void push_stack_element(struct ref_formatting_stack **stack)
795 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
797 strbuf_init(&s->output, 0);
798 s->prev = *stack;
799 *stack = s;
802 static void pop_stack_element(struct ref_formatting_stack **stack)
804 struct ref_formatting_stack *current = *stack;
805 struct ref_formatting_stack *prev = current->prev;
807 if (prev)
808 strbuf_addbuf(&prev->output, &current->output);
809 strbuf_release(&current->output);
810 free(current);
811 *stack = prev;
814 static void end_align_handler(struct ref_formatting_stack **stack)
816 struct ref_formatting_stack *cur = *stack;
817 struct align *align = (struct align *)cur->at_end_data;
818 struct strbuf s = STRBUF_INIT;
820 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
821 strbuf_swap(&cur->output, &s);
822 strbuf_release(&s);
825 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
826 struct strbuf *unused_err)
828 struct ref_formatting_stack *new_stack;
830 push_stack_element(&state->stack);
831 new_stack = state->stack;
832 new_stack->at_end = end_align_handler;
833 new_stack->at_end_data = &atomv->atom->u.align;
834 return 0;
837 static void if_then_else_handler(struct ref_formatting_stack **stack)
839 struct ref_formatting_stack *cur = *stack;
840 struct ref_formatting_stack *prev = cur->prev;
841 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
843 if (!if_then_else->then_atom_seen)
844 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
846 if (if_then_else->else_atom_seen) {
848 * There is an %(else) atom: we need to drop one state from the
849 * stack, either the %(else) branch if the condition is satisfied, or
850 * the %(then) branch if it isn't.
852 if (if_then_else->condition_satisfied) {
853 strbuf_reset(&cur->output);
854 pop_stack_element(&cur);
855 } else {
856 strbuf_swap(&cur->output, &prev->output);
857 strbuf_reset(&cur->output);
858 pop_stack_element(&cur);
860 } else if (!if_then_else->condition_satisfied) {
862 * No %(else) atom: just drop the %(then) branch if the
863 * condition is not satisfied.
865 strbuf_reset(&cur->output);
868 *stack = cur;
869 free(if_then_else);
872 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
873 struct strbuf *unused_err)
875 struct ref_formatting_stack *new_stack;
876 struct if_then_else *if_then_else = xcalloc(1,
877 sizeof(struct if_then_else));
879 if_then_else->str = atomv->atom->u.if_then_else.str;
880 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
882 push_stack_element(&state->stack);
883 new_stack = state->stack;
884 new_stack->at_end = if_then_else_handler;
885 new_stack->at_end_data = if_then_else;
886 return 0;
889 static int is_empty(struct strbuf *buf)
891 const char *cur = buf->buf;
892 const char *end = buf->buf + buf->len;
894 while (cur != end && (isspace(*cur)))
895 cur++;
897 return cur == end;
900 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
901 struct strbuf *err)
903 struct ref_formatting_stack *cur = state->stack;
904 struct if_then_else *if_then_else = NULL;
905 size_t str_len = 0;
907 if (cur->at_end == if_then_else_handler)
908 if_then_else = (struct if_then_else *)cur->at_end_data;
909 if (!if_then_else)
910 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
911 if (if_then_else->then_atom_seen)
912 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
913 if (if_then_else->else_atom_seen)
914 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
915 if_then_else->then_atom_seen = 1;
916 if (if_then_else->str)
917 str_len = strlen(if_then_else->str);
919 * If the 'equals' or 'notequals' attribute is used then
920 * perform the required comparison. If not, only non-empty
921 * strings satisfy the 'if' condition.
923 if (if_then_else->cmp_status == COMPARE_EQUAL) {
924 if (str_len == cur->output.len &&
925 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
926 if_then_else->condition_satisfied = 1;
927 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
928 if (str_len != cur->output.len ||
929 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
930 if_then_else->condition_satisfied = 1;
931 } else if (cur->output.len && !is_empty(&cur->output))
932 if_then_else->condition_satisfied = 1;
933 strbuf_reset(&cur->output);
934 return 0;
937 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
938 struct strbuf *err)
940 struct ref_formatting_stack *prev = state->stack;
941 struct if_then_else *if_then_else = NULL;
943 if (prev->at_end == if_then_else_handler)
944 if_then_else = (struct if_then_else *)prev->at_end_data;
945 if (!if_then_else)
946 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
947 if (!if_then_else->then_atom_seen)
948 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
949 if (if_then_else->else_atom_seen)
950 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
951 if_then_else->else_atom_seen = 1;
952 push_stack_element(&state->stack);
953 state->stack->at_end_data = prev->at_end_data;
954 state->stack->at_end = prev->at_end;
955 return 0;
958 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
959 struct strbuf *err)
961 struct ref_formatting_stack *current = state->stack;
962 struct strbuf s = STRBUF_INIT;
964 if (!current->at_end)
965 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
966 current->at_end(&state->stack);
968 /* Stack may have been popped within at_end(), hence reset the current pointer */
969 current = state->stack;
972 * Perform quote formatting when the stack element is that of
973 * a supporting atom. If nested then perform quote formatting
974 * only on the topmost supporting atom.
976 if (!current->prev->prev) {
977 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
978 strbuf_swap(&current->output, &s);
980 strbuf_release(&s);
981 pop_stack_element(&state->stack);
982 return 0;
986 * In a format string, find the next occurrence of %(atom).
988 static const char *find_next(const char *cp)
990 while (*cp) {
991 if (*cp == '%') {
993 * %( is the start of an atom;
994 * %% is a quoted per-cent.
996 if (cp[1] == '(')
997 return cp;
998 else if (cp[1] == '%')
999 cp++; /* skip over two % */
1000 /* otherwise this is a singleton, literal % */
1002 cp++;
1004 return NULL;
1007 static int reject_atom(enum atom_type atom_type)
1009 return atom_type == ATOM_REST;
1013 * Make sure the format string is well formed, and parse out
1014 * the used atoms.
1016 int verify_ref_format(struct ref_format *format)
1018 const char *cp, *sp;
1020 format->need_color_reset_at_eol = 0;
1021 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1022 struct strbuf err = STRBUF_INIT;
1023 const char *color, *ep = strchr(sp, ')');
1024 int at;
1026 if (!ep)
1027 return error(_("malformed format string %s"), sp);
1028 /* sp points at "%(" and ep points at the closing ")" */
1029 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1030 if (at < 0)
1031 die("%s", err.buf);
1032 if (reject_atom(used_atom[at].atom_type))
1033 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1035 if ((format->quote_style == QUOTE_PYTHON ||
1036 format->quote_style == QUOTE_SHELL ||
1037 format->quote_style == QUOTE_TCL) &&
1038 used_atom[at].atom_type == ATOM_RAW &&
1039 used_atom[at].u.raw_data.option == RAW_BARE)
1040 die(_("--format=%.*s cannot be used with "
1041 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1042 cp = ep + 1;
1044 if (skip_prefix(used_atom[at].name, "color:", &color))
1045 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1046 strbuf_release(&err);
1048 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1049 format->need_color_reset_at_eol = 0;
1050 return 0;
1053 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1054 struct used_atom *atom)
1056 switch (atom->u.oid.option) {
1057 case O_FULL:
1058 return oid_to_hex(oid);
1059 case O_LENGTH:
1060 return find_unique_abbrev(oid, atom->u.oid.length);
1061 case O_SHORT:
1062 return find_unique_abbrev(oid, DEFAULT_ABBREV);
1063 default:
1064 BUG("unknown %%(%s) option", field);
1068 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1069 struct atom_value *v, struct used_atom *atom)
1071 if (starts_with(name, field)) {
1072 v->s = xstrdup(do_grab_oid(field, oid, atom));
1073 return 1;
1075 return 0;
1078 /* See grab_values */
1079 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1081 int i;
1083 for (i = 0; i < used_atom_cnt; i++) {
1084 const char *name = used_atom[i].name;
1085 enum atom_type atom_type = used_atom[i].atom_type;
1086 struct atom_value *v = &val[i];
1087 if (!!deref != (*name == '*'))
1088 continue;
1089 if (deref)
1090 name++;
1091 if (atom_type == ATOM_OBJECTTYPE)
1092 v->s = xstrdup(type_name(oi->type));
1093 else if (atom_type == ATOM_OBJECTSIZE) {
1094 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1095 v->value = oi->disk_size;
1096 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1097 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1098 v->value = oi->size;
1099 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1101 } else if (atom_type == ATOM_DELTABASE)
1102 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1103 else if (atom_type == ATOM_OBJECTNAME && deref)
1104 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1108 /* See grab_values */
1109 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1111 int i;
1112 struct tag *tag = (struct tag *) obj;
1114 for (i = 0; i < used_atom_cnt; i++) {
1115 const char *name = used_atom[i].name;
1116 enum atom_type atom_type = used_atom[i].atom_type;
1117 struct atom_value *v = &val[i];
1118 if (!!deref != (*name == '*'))
1119 continue;
1120 if (deref)
1121 name++;
1122 if (atom_type == ATOM_TAG)
1123 v->s = xstrdup(tag->tag);
1124 else if (atom_type == ATOM_TYPE && tag->tagged)
1125 v->s = xstrdup(type_name(tag->tagged->type));
1126 else if (atom_type == ATOM_OBJECT && tag->tagged)
1127 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1131 /* See grab_values */
1132 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1134 int i;
1135 struct commit *commit = (struct commit *) obj;
1137 for (i = 0; i < used_atom_cnt; i++) {
1138 const char *name = used_atom[i].name;
1139 enum atom_type atom_type = used_atom[i].atom_type;
1140 struct atom_value *v = &val[i];
1141 if (!!deref != (*name == '*'))
1142 continue;
1143 if (deref)
1144 name++;
1145 if (atom_type == ATOM_TREE &&
1146 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1147 continue;
1148 if (atom_type == ATOM_NUMPARENT) {
1149 v->value = commit_list_count(commit->parents);
1150 v->s = xstrfmt("%lu", (unsigned long)v->value);
1152 else if (atom_type == ATOM_PARENT) {
1153 struct commit_list *parents;
1154 struct strbuf s = STRBUF_INIT;
1155 for (parents = commit->parents; parents; parents = parents->next) {
1156 struct object_id *oid = &parents->item->object.oid;
1157 if (parents != commit->parents)
1158 strbuf_addch(&s, ' ');
1159 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1161 v->s = strbuf_detach(&s, NULL);
1166 static const char *find_wholine(const char *who, int wholen, const char *buf)
1168 const char *eol;
1169 while (*buf) {
1170 if (!strncmp(buf, who, wholen) &&
1171 buf[wholen] == ' ')
1172 return buf + wholen + 1;
1173 eol = strchr(buf, '\n');
1174 if (!eol)
1175 return "";
1176 eol++;
1177 if (*eol == '\n')
1178 return ""; /* end of header */
1179 buf = eol;
1181 return "";
1184 static const char *copy_line(const char *buf)
1186 const char *eol = strchrnul(buf, '\n');
1187 return xmemdupz(buf, eol - buf);
1190 static const char *copy_name(const char *buf)
1192 const char *cp;
1193 for (cp = buf; *cp && *cp != '\n'; cp++) {
1194 if (!strncmp(cp, " <", 2))
1195 return xmemdupz(buf, cp - buf);
1197 return xstrdup("");
1200 static const char *copy_email(const char *buf, struct used_atom *atom)
1202 const char *email = strchr(buf, '<');
1203 const char *eoemail;
1204 if (!email)
1205 return xstrdup("");
1206 switch (atom->u.email_option.option) {
1207 case EO_RAW:
1208 eoemail = strchr(email, '>');
1209 if (eoemail)
1210 eoemail++;
1211 break;
1212 case EO_TRIM:
1213 email++;
1214 eoemail = strchr(email, '>');
1215 break;
1216 case EO_LOCALPART:
1217 email++;
1218 eoemail = strchr(email, '@');
1219 if (!eoemail)
1220 eoemail = strchr(email, '>');
1221 break;
1222 default:
1223 BUG("unknown email option");
1226 if (!eoemail)
1227 return xstrdup("");
1228 return xmemdupz(email, eoemail - email);
1231 static char *copy_subject(const char *buf, unsigned long len)
1233 struct strbuf sb = STRBUF_INIT;
1234 int i;
1236 for (i = 0; i < len; i++) {
1237 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1238 continue; /* ignore CR in CRLF */
1240 if (buf[i] == '\n')
1241 strbuf_addch(&sb, ' ');
1242 else
1243 strbuf_addch(&sb, buf[i]);
1245 return strbuf_detach(&sb, NULL);
1248 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1250 const char *eoemail = strstr(buf, "> ");
1251 char *zone;
1252 timestamp_t timestamp;
1253 long tz;
1254 struct date_mode date_mode = DATE_MODE_INIT;
1255 const char *formatp;
1258 * We got here because atomname ends in "date" or "date<something>";
1259 * it's not possible that <something> is not ":<format>" because
1260 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1261 * ":" means no format is specified, and use the default.
1263 formatp = strchr(atomname, ':');
1264 if (formatp) {
1265 formatp++;
1266 parse_date_format(formatp, &date_mode);
1269 if (!eoemail)
1270 goto bad;
1271 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1272 if (timestamp == TIME_MAX)
1273 goto bad;
1274 tz = strtol(zone, NULL, 10);
1275 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1276 goto bad;
1277 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1278 v->value = timestamp;
1279 date_mode_release(&date_mode);
1280 return;
1281 bad:
1282 v->s = xstrdup("");
1283 v->value = 0;
1286 /* See grab_values */
1287 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1289 int i;
1290 int wholen = strlen(who);
1291 const char *wholine = NULL;
1293 for (i = 0; i < used_atom_cnt; i++) {
1294 const char *name = used_atom[i].name;
1295 struct atom_value *v = &val[i];
1296 if (!!deref != (*name == '*'))
1297 continue;
1298 if (deref)
1299 name++;
1300 if (strncmp(who, name, wholen))
1301 continue;
1302 if (name[wholen] != 0 &&
1303 strcmp(name + wholen, "name") &&
1304 !starts_with(name + wholen, "email") &&
1305 !starts_with(name + wholen, "date"))
1306 continue;
1307 if (!wholine)
1308 wholine = find_wholine(who, wholen, buf);
1309 if (!wholine)
1310 return; /* no point looking for it */
1311 if (name[wholen] == 0)
1312 v->s = copy_line(wholine);
1313 else if (!strcmp(name + wholen, "name"))
1314 v->s = copy_name(wholine);
1315 else if (starts_with(name + wholen, "email"))
1316 v->s = copy_email(wholine, &used_atom[i]);
1317 else if (starts_with(name + wholen, "date"))
1318 grab_date(wholine, v, name);
1322 * For a tag or a commit object, if "creator" or "creatordate" is
1323 * requested, do something special.
1325 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1326 return; /* "author" for commit object is not wanted */
1327 if (!wholine)
1328 wholine = find_wholine(who, wholen, buf);
1329 if (!wholine)
1330 return;
1331 for (i = 0; i < used_atom_cnt; i++) {
1332 const char *name = used_atom[i].name;
1333 enum atom_type atom_type = used_atom[i].atom_type;
1334 struct atom_value *v = &val[i];
1335 if (!!deref != (*name == '*'))
1336 continue;
1337 if (deref)
1338 name++;
1340 if (atom_type == ATOM_CREATORDATE)
1341 grab_date(wholine, v, name);
1342 else if (atom_type == ATOM_CREATOR)
1343 v->s = copy_line(wholine);
1347 static void find_subpos(const char *buf,
1348 const char **sub, size_t *sublen,
1349 const char **body, size_t *bodylen,
1350 size_t *nonsiglen,
1351 const char **sig, size_t *siglen)
1353 struct strbuf payload = STRBUF_INIT;
1354 struct strbuf signature = STRBUF_INIT;
1355 const char *eol;
1356 const char *end = buf + strlen(buf);
1357 const char *sigstart;
1359 /* parse signature first; we might not even have a subject line */
1360 parse_signature(buf, end - buf, &payload, &signature);
1361 strbuf_release(&payload);
1363 /* skip past header until we hit empty line */
1364 while (*buf && *buf != '\n') {
1365 eol = strchrnul(buf, '\n');
1366 if (*eol)
1367 eol++;
1368 buf = eol;
1370 /* skip any empty lines */
1371 while (*buf == '\n')
1372 buf++;
1373 *sig = strbuf_detach(&signature, siglen);
1374 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1376 /* subject is first non-empty line */
1377 *sub = buf;
1378 /* subject goes to first empty line before signature begins */
1379 if ((eol = strstr(*sub, "\n\n")) ||
1380 (eol = strstr(*sub, "\r\n\r\n"))) {
1381 eol = eol < sigstart ? eol : sigstart;
1382 } else {
1383 /* treat whole message as subject */
1384 eol = sigstart;
1386 buf = eol;
1387 *sublen = buf - *sub;
1388 /* drop trailing newline, if present */
1389 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1390 (*sub)[*sublen - 1] == '\r'))
1391 *sublen -= 1;
1393 /* skip any empty lines */
1394 while (*buf == '\n' || *buf == '\r')
1395 buf++;
1396 *body = buf;
1397 *bodylen = strlen(buf);
1398 *nonsiglen = sigstart - buf;
1402 * If 'lines' is greater than 0, append that many lines from the given
1403 * 'buf' of length 'size' to the given strbuf.
1405 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1407 int i;
1408 const char *sp, *eol;
1409 size_t len;
1411 sp = buf;
1413 for (i = 0; i < lines && sp < buf + size; i++) {
1414 if (i)
1415 strbuf_addstr(out, "\n ");
1416 eol = memchr(sp, '\n', size - (sp - buf));
1417 len = eol ? eol - sp : size - (sp - buf);
1418 strbuf_add(out, sp, len);
1419 if (!eol)
1420 break;
1421 sp = eol + 1;
1425 /* See grab_values */
1426 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1428 int i;
1429 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1430 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1431 void *buf = data->content;
1433 for (i = 0; i < used_atom_cnt; i++) {
1434 struct used_atom *atom = &used_atom[i];
1435 const char *name = atom->name;
1436 struct atom_value *v = &val[i];
1437 enum atom_type atom_type = atom->atom_type;
1439 if (!!deref != (*name == '*'))
1440 continue;
1441 if (deref)
1442 name++;
1444 if (atom_type == ATOM_RAW) {
1445 unsigned long buf_size = data->size;
1447 if (atom->u.raw_data.option == RAW_BARE) {
1448 v->s = xmemdupz(buf, buf_size);
1449 v->s_size = buf_size;
1450 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1451 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1453 continue;
1456 if ((data->type != OBJ_TAG &&
1457 data->type != OBJ_COMMIT) ||
1458 (strcmp(name, "body") &&
1459 !starts_with(name, "subject") &&
1460 !starts_with(name, "trailers") &&
1461 !starts_with(name, "contents")))
1462 continue;
1463 if (!subpos)
1464 find_subpos(buf,
1465 &subpos, &sublen,
1466 &bodypos, &bodylen, &nonsiglen,
1467 &sigpos, &siglen);
1469 if (atom->u.contents.option == C_SUB)
1470 v->s = copy_subject(subpos, sublen);
1471 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1472 struct strbuf sb = STRBUF_INIT;
1473 format_sanitized_subject(&sb, subpos, sublen);
1474 v->s = strbuf_detach(&sb, NULL);
1475 } else if (atom->u.contents.option == C_BODY_DEP)
1476 v->s = xmemdupz(bodypos, bodylen);
1477 else if (atom->u.contents.option == C_LENGTH)
1478 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1479 else if (atom->u.contents.option == C_BODY)
1480 v->s = xmemdupz(bodypos, nonsiglen);
1481 else if (atom->u.contents.option == C_SIG)
1482 v->s = xmemdupz(sigpos, siglen);
1483 else if (atom->u.contents.option == C_LINES) {
1484 struct strbuf s = STRBUF_INIT;
1485 const char *contents_end = bodypos + nonsiglen;
1487 /* Size is the length of the message after removing the signature */
1488 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1489 v->s = strbuf_detach(&s, NULL);
1490 } else if (atom->u.contents.option == C_TRAILERS) {
1491 struct strbuf s = STRBUF_INIT;
1493 /* Format the trailer info according to the trailer_opts given */
1494 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1496 v->s = strbuf_detach(&s, NULL);
1497 } else if (atom->u.contents.option == C_BARE)
1498 v->s = xstrdup(subpos);
1501 free((void *)sigpos);
1505 * We want to have empty print-string for field requests
1506 * that do not apply (e.g. "authordate" for a tag object)
1508 static void fill_missing_values(struct atom_value *val)
1510 int i;
1511 for (i = 0; i < used_atom_cnt; i++) {
1512 struct atom_value *v = &val[i];
1513 if (!v->s)
1514 v->s = xstrdup("");
1519 * val is a list of atom_value to hold returned values. Extract
1520 * the values for atoms in used_atom array out of (obj, buf, sz).
1521 * when deref is false, (obj, buf, sz) is the object that is
1522 * pointed at by the ref itself; otherwise it is the object the
1523 * ref (which is a tag) refers to.
1525 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1527 void *buf = data->content;
1529 switch (obj->type) {
1530 case OBJ_TAG:
1531 grab_tag_values(val, deref, obj);
1532 grab_sub_body_contents(val, deref, data);
1533 grab_person("tagger", val, deref, buf);
1534 break;
1535 case OBJ_COMMIT:
1536 grab_commit_values(val, deref, obj);
1537 grab_sub_body_contents(val, deref, data);
1538 grab_person("author", val, deref, buf);
1539 grab_person("committer", val, deref, buf);
1540 break;
1541 case OBJ_TREE:
1542 /* grab_tree_values(val, deref, obj, buf, sz); */
1543 grab_sub_body_contents(val, deref, data);
1544 break;
1545 case OBJ_BLOB:
1546 /* grab_blob_values(val, deref, obj, buf, sz); */
1547 grab_sub_body_contents(val, deref, data);
1548 break;
1549 default:
1550 die("Eh? Object of type %d?", obj->type);
1554 static inline char *copy_advance(char *dst, const char *src)
1556 while (*src)
1557 *dst++ = *src++;
1558 return dst;
1561 static const char *lstrip_ref_components(const char *refname, int len)
1563 long remaining = len;
1564 const char *start = xstrdup(refname);
1565 const char *to_free = start;
1567 if (len < 0) {
1568 int i;
1569 const char *p = refname;
1571 /* Find total no of '/' separated path-components */
1572 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1575 * The number of components we need to strip is now
1576 * the total minus the components to be left (Plus one
1577 * because we count the number of '/', but the number
1578 * of components is one more than the no of '/').
1580 remaining = i + len + 1;
1583 while (remaining > 0) {
1584 switch (*start++) {
1585 case '\0':
1586 free((char *)to_free);
1587 return xstrdup("");
1588 case '/':
1589 remaining--;
1590 break;
1594 start = xstrdup(start);
1595 free((char *)to_free);
1596 return start;
1599 static const char *rstrip_ref_components(const char *refname, int len)
1601 long remaining = len;
1602 const char *start = xstrdup(refname);
1603 const char *to_free = start;
1605 if (len < 0) {
1606 int i;
1607 const char *p = refname;
1609 /* Find total no of '/' separated path-components */
1610 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1613 * The number of components we need to strip is now
1614 * the total minus the components to be left (Plus one
1615 * because we count the number of '/', but the number
1616 * of components is one more than the no of '/').
1618 remaining = i + len + 1;
1621 while (remaining-- > 0) {
1622 char *p = strrchr(start, '/');
1623 if (!p) {
1624 free((char *)to_free);
1625 return xstrdup("");
1626 } else
1627 p[0] = '\0';
1629 return start;
1632 static const char *show_ref(struct refname_atom *atom, const char *refname)
1634 if (atom->option == R_SHORT)
1635 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1636 else if (atom->option == R_LSTRIP)
1637 return lstrip_ref_components(refname, atom->lstrip);
1638 else if (atom->option == R_RSTRIP)
1639 return rstrip_ref_components(refname, atom->rstrip);
1640 else
1641 return xstrdup(refname);
1644 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1645 struct branch *branch, const char **s)
1647 int num_ours, num_theirs;
1648 if (atom->u.remote_ref.option == RR_REF)
1649 *s = show_ref(&atom->u.remote_ref.refname, refname);
1650 else if (atom->u.remote_ref.option == RR_TRACK) {
1651 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1652 NULL, atom->u.remote_ref.push,
1653 AHEAD_BEHIND_FULL) < 0) {
1654 *s = xstrdup(msgs.gone);
1655 } else if (!num_ours && !num_theirs)
1656 *s = xstrdup("");
1657 else if (!num_ours)
1658 *s = xstrfmt(msgs.behind, num_theirs);
1659 else if (!num_theirs)
1660 *s = xstrfmt(msgs.ahead, num_ours);
1661 else
1662 *s = xstrfmt(msgs.ahead_behind,
1663 num_ours, num_theirs);
1664 if (!atom->u.remote_ref.nobracket && *s[0]) {
1665 const char *to_free = *s;
1666 *s = xstrfmt("[%s]", *s);
1667 free((void *)to_free);
1669 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1670 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1671 NULL, atom->u.remote_ref.push,
1672 AHEAD_BEHIND_FULL) < 0) {
1673 *s = xstrdup("");
1674 return;
1676 if (!num_ours && !num_theirs)
1677 *s = xstrdup("=");
1678 else if (!num_ours)
1679 *s = xstrdup("<");
1680 else if (!num_theirs)
1681 *s = xstrdup(">");
1682 else
1683 *s = xstrdup("<>");
1684 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1685 int explicit;
1686 const char *remote = atom->u.remote_ref.push ?
1687 pushremote_for_branch(branch, &explicit) :
1688 remote_for_branch(branch, &explicit);
1689 *s = xstrdup(explicit ? remote : "");
1690 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1691 const char *merge;
1693 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1694 *s = xstrdup(merge ? merge : "");
1695 } else
1696 BUG("unhandled RR_* enum");
1699 char *get_head_description(void)
1701 struct strbuf desc = STRBUF_INIT;
1702 struct wt_status_state state;
1703 memset(&state, 0, sizeof(state));
1704 wt_status_get_state(the_repository, &state, 1);
1705 if (state.rebase_in_progress ||
1706 state.rebase_interactive_in_progress) {
1707 if (state.branch)
1708 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1709 state.branch);
1710 else
1711 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1712 state.detached_from);
1713 } else if (state.bisect_in_progress)
1714 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1715 state.branch);
1716 else if (state.detached_from) {
1717 if (state.detached_at)
1718 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1719 state.detached_from);
1720 else
1721 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1722 state.detached_from);
1723 } else
1724 strbuf_addstr(&desc, _("(no branch)"));
1726 wt_status_state_free_buffers(&state);
1728 return strbuf_detach(&desc, NULL);
1731 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1733 if (!ref->symref)
1734 return xstrdup("");
1735 else
1736 return show_ref(&atom->u.refname, ref->symref);
1739 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1741 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1742 return get_head_description();
1743 return show_ref(&atom->u.refname, ref->refname);
1746 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1747 struct expand_data *oi, struct strbuf *err)
1749 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1750 int eaten = 1;
1751 if (oi->info.contentp) {
1752 /* We need to know that to use parse_object_buffer properly */
1753 oi->info.sizep = &oi->size;
1754 oi->info.typep = &oi->type;
1756 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1757 OBJECT_INFO_LOOKUP_REPLACE))
1758 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1759 oid_to_hex(&oi->oid), ref->refname);
1760 if (oi->info.disk_sizep && oi->disk_size < 0)
1761 BUG("Object size is less than zero.");
1763 if (oi->info.contentp) {
1764 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1765 if (!*obj) {
1766 if (!eaten)
1767 free(oi->content);
1768 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1769 oid_to_hex(&oi->oid), ref->refname);
1771 grab_values(ref->value, deref, *obj, oi);
1774 grab_common_values(ref->value, deref, oi);
1775 if (!eaten)
1776 free(oi->content);
1777 return 0;
1780 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1782 int i;
1784 for (i = 0; worktrees[i]; i++) {
1785 if (worktrees[i]->head_ref) {
1786 struct ref_to_worktree_entry *entry;
1787 entry = xmalloc(sizeof(*entry));
1788 entry->wt = worktrees[i];
1789 hashmap_entry_init(&entry->ent,
1790 strhash(worktrees[i]->head_ref));
1792 hashmap_add(map, &entry->ent);
1797 static void lazy_init_worktree_map(void)
1799 if (ref_to_worktree_map.worktrees)
1800 return;
1802 ref_to_worktree_map.worktrees = get_worktrees();
1803 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1804 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1807 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1809 struct hashmap_entry entry, *e;
1810 struct ref_to_worktree_entry *lookup_result;
1812 lazy_init_worktree_map();
1814 hashmap_entry_init(&entry, strhash(ref->refname));
1815 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1817 if (!e)
1818 return xstrdup("");
1820 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1822 return xstrdup(lookup_result->wt->path);
1826 * Parse the object referred by ref, and grab needed value.
1828 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1830 struct object *obj;
1831 int i;
1832 struct object_info empty = OBJECT_INFO_INIT;
1834 CALLOC_ARRAY(ref->value, used_atom_cnt);
1836 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1837 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1838 NULL, NULL);
1839 if (!ref->symref)
1840 ref->symref = xstrdup("");
1843 /* Fill in specials first */
1844 for (i = 0; i < used_atom_cnt; i++) {
1845 struct used_atom *atom = &used_atom[i];
1846 enum atom_type atom_type = atom->atom_type;
1847 const char *name = used_atom[i].name;
1848 struct atom_value *v = &ref->value[i];
1849 int deref = 0;
1850 const char *refname;
1851 struct branch *branch = NULL;
1853 v->s_size = ATOM_SIZE_UNSPECIFIED;
1854 v->handler = append_atom;
1855 v->atom = atom;
1857 if (*name == '*') {
1858 deref = 1;
1859 name++;
1862 if (atom_type == ATOM_REFNAME)
1863 refname = get_refname(atom, ref);
1864 else if (atom_type == ATOM_WORKTREEPATH) {
1865 if (ref->kind == FILTER_REFS_BRANCHES)
1866 v->s = get_worktree_path(atom, ref);
1867 else
1868 v->s = xstrdup("");
1869 continue;
1871 else if (atom_type == ATOM_SYMREF)
1872 refname = get_symref(atom, ref);
1873 else if (atom_type == ATOM_UPSTREAM) {
1874 const char *branch_name;
1875 /* only local branches may have an upstream */
1876 if (!skip_prefix(ref->refname, "refs/heads/",
1877 &branch_name)) {
1878 v->s = xstrdup("");
1879 continue;
1881 branch = branch_get(branch_name);
1883 refname = branch_get_upstream(branch, NULL);
1884 if (refname)
1885 fill_remote_ref_details(atom, refname, branch, &v->s);
1886 else
1887 v->s = xstrdup("");
1888 continue;
1889 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1890 const char *branch_name;
1891 v->s = xstrdup("");
1892 if (!skip_prefix(ref->refname, "refs/heads/",
1893 &branch_name))
1894 continue;
1895 branch = branch_get(branch_name);
1897 if (atom->u.remote_ref.push_remote)
1898 refname = NULL;
1899 else {
1900 refname = branch_get_push(branch, NULL);
1901 if (!refname)
1902 continue;
1904 /* We will definitely re-init v->s on the next line. */
1905 free((char *)v->s);
1906 fill_remote_ref_details(atom, refname, branch, &v->s);
1907 continue;
1908 } else if (atom_type == ATOM_COLOR) {
1909 v->s = xstrdup(atom->u.color);
1910 continue;
1911 } else if (atom_type == ATOM_FLAG) {
1912 char buf[256], *cp = buf;
1913 if (ref->flag & REF_ISSYMREF)
1914 cp = copy_advance(cp, ",symref");
1915 if (ref->flag & REF_ISPACKED)
1916 cp = copy_advance(cp, ",packed");
1917 if (cp == buf)
1918 v->s = xstrdup("");
1919 else {
1920 *cp = '\0';
1921 v->s = xstrdup(buf + 1);
1923 continue;
1924 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1925 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1926 continue;
1927 } else if (atom_type == ATOM_HEAD) {
1928 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1929 v->s = xstrdup("*");
1930 else
1931 v->s = xstrdup(" ");
1932 continue;
1933 } else if (atom_type == ATOM_ALIGN) {
1934 v->handler = align_atom_handler;
1935 v->s = xstrdup("");
1936 continue;
1937 } else if (atom_type == ATOM_END) {
1938 v->handler = end_atom_handler;
1939 v->s = xstrdup("");
1940 continue;
1941 } else if (atom_type == ATOM_IF) {
1942 const char *s;
1943 if (skip_prefix(name, "if:", &s))
1944 v->s = xstrdup(s);
1945 else
1946 v->s = xstrdup("");
1947 v->handler = if_atom_handler;
1948 continue;
1949 } else if (atom_type == ATOM_THEN) {
1950 v->handler = then_atom_handler;
1951 v->s = xstrdup("");
1952 continue;
1953 } else if (atom_type == ATOM_ELSE) {
1954 v->handler = else_atom_handler;
1955 v->s = xstrdup("");
1956 continue;
1957 } else if (atom_type == ATOM_REST) {
1958 if (ref->rest)
1959 v->s = xstrdup(ref->rest);
1960 else
1961 v->s = xstrdup("");
1962 continue;
1963 } else
1964 continue;
1966 if (!deref)
1967 v->s = xstrdup(refname);
1968 else
1969 v->s = xstrfmt("%s^{}", refname);
1970 free((char *)refname);
1973 for (i = 0; i < used_atom_cnt; i++) {
1974 struct atom_value *v = &ref->value[i];
1975 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1976 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1977 oid_to_hex(&ref->objectname), ref->refname);
1980 if (need_tagged)
1981 oi.info.contentp = &oi.content;
1982 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1983 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1984 return 0;
1987 oi.oid = ref->objectname;
1988 if (get_object(ref, 0, &obj, &oi, err))
1989 return -1;
1992 * If there is no atom that wants to know about tagged
1993 * object, we are done.
1995 if (!need_tagged || (obj->type != OBJ_TAG))
1996 return 0;
1999 * If it is a tag object, see if we use a value that derefs
2000 * the object, and if we do grab the object it refers to.
2002 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2005 * NEEDSWORK: This derefs tag only once, which
2006 * is good to deal with chains of trust, but
2007 * is not consistent with what deref_tag() does
2008 * which peels the onion to the core.
2010 return get_object(ref, 1, &obj, &oi_deref, err);
2014 * Given a ref, return the value for the atom. This lazily gets value
2015 * out of the object by calling populate value.
2017 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2018 struct atom_value **v, struct strbuf *err)
2020 if (!ref->value) {
2021 if (populate_value(ref, err))
2022 return -1;
2023 fill_missing_values(ref->value);
2025 *v = &ref->value[atom];
2026 return 0;
2030 * Return 1 if the refname matches one of the patterns, otherwise 0.
2031 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2032 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2033 * matches "refs/heads/mas*", too).
2035 static int match_pattern(const struct ref_filter *filter, const char *refname)
2037 const char **patterns = filter->name_patterns;
2038 unsigned flags = 0;
2040 if (filter->ignore_case)
2041 flags |= WM_CASEFOLD;
2044 * When no '--format' option is given we need to skip the prefix
2045 * for matching refs of tags and branches.
2047 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2048 skip_prefix(refname, "refs/heads/", &refname) ||
2049 skip_prefix(refname, "refs/remotes/", &refname) ||
2050 skip_prefix(refname, "refs/", &refname));
2052 for (; *patterns; patterns++) {
2053 if (!wildmatch(*patterns, refname, flags))
2054 return 1;
2056 return 0;
2060 * Return 1 if the refname matches one of the patterns, otherwise 0.
2061 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2062 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2063 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2065 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2067 const char **pattern = filter->name_patterns;
2068 int namelen = strlen(refname);
2069 unsigned flags = WM_PATHNAME;
2071 if (filter->ignore_case)
2072 flags |= WM_CASEFOLD;
2074 for (; *pattern; pattern++) {
2075 const char *p = *pattern;
2076 int plen = strlen(p);
2078 if ((plen <= namelen) &&
2079 !strncmp(refname, p, plen) &&
2080 (refname[plen] == '\0' ||
2081 refname[plen] == '/' ||
2082 p[plen-1] == '/'))
2083 return 1;
2084 if (!wildmatch(p, refname, flags))
2085 return 1;
2087 return 0;
2090 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2091 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2093 if (!*filter->name_patterns)
2094 return 1; /* No pattern always matches */
2095 if (filter->match_as_path)
2096 return match_name_as_path(filter, refname);
2097 return match_pattern(filter, refname);
2101 * This is the same as for_each_fullref_in(), but it tries to iterate
2102 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2103 * pattern match, so the callback still has to match each ref individually.
2105 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2106 each_ref_fn cb,
2107 void *cb_data)
2109 if (!filter->match_as_path) {
2111 * in this case, the patterns are applied after
2112 * prefixes like "refs/heads/" etc. are stripped off,
2113 * so we have to look at everything:
2115 return for_each_fullref_in("", cb, cb_data);
2118 if (filter->ignore_case) {
2120 * we can't handle case-insensitive comparisons,
2121 * so just return everything and let the caller
2122 * sort it out.
2124 return for_each_fullref_in("", cb, cb_data);
2127 if (!filter->name_patterns[0]) {
2128 /* no patterns; we have to look at everything */
2129 return for_each_fullref_in("", cb, cb_data);
2132 return for_each_fullref_in_prefixes(NULL, filter->name_patterns,
2133 cb, cb_data);
2137 * Given a ref (oid, refname), check if the ref belongs to the array
2138 * of oids. If the given ref is a tag, check if the given tag points
2139 * at one of the oids in the given oid array.
2140 * NEEDSWORK:
2141 * 1. Only a single level of indirection is obtained, we might want to
2142 * change this to account for multiple levels (e.g. annotated tags
2143 * pointing to annotated tags pointing to a commit.)
2144 * 2. As the refs are cached we might know what refname peels to without
2145 * the need to parse the object via parse_object(). peel_ref() might be a
2146 * more efficient alternative to obtain the pointee.
2148 static const struct object_id *match_points_at(struct oid_array *points_at,
2149 const struct object_id *oid,
2150 const char *refname)
2152 const struct object_id *tagged_oid = NULL;
2153 struct object *obj;
2155 if (oid_array_lookup(points_at, oid) >= 0)
2156 return oid;
2157 obj = parse_object(the_repository, oid);
2158 if (!obj)
2159 die(_("malformed object at '%s'"), refname);
2160 if (obj->type == OBJ_TAG)
2161 tagged_oid = get_tagged_oid((struct tag *)obj);
2162 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2163 return tagged_oid;
2164 return NULL;
2168 * Allocate space for a new ref_array_item and copy the name and oid to it.
2170 * Callers can then fill in other struct members at their leisure.
2172 static struct ref_array_item *new_ref_array_item(const char *refname,
2173 const struct object_id *oid)
2175 struct ref_array_item *ref;
2177 FLEX_ALLOC_STR(ref, refname, refname);
2178 oidcpy(&ref->objectname, oid);
2179 ref->rest = NULL;
2181 return ref;
2184 struct ref_array_item *ref_array_push(struct ref_array *array,
2185 const char *refname,
2186 const struct object_id *oid)
2188 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2190 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2191 array->items[array->nr++] = ref;
2193 return ref;
2196 static int ref_kind_from_refname(const char *refname)
2198 unsigned int i;
2200 static struct {
2201 const char *prefix;
2202 unsigned int kind;
2203 } ref_kind[] = {
2204 { "refs/heads/" , FILTER_REFS_BRANCHES },
2205 { "refs/remotes/" , FILTER_REFS_REMOTES },
2206 { "refs/tags/", FILTER_REFS_TAGS}
2209 if (!strcmp(refname, "HEAD"))
2210 return FILTER_REFS_DETACHED_HEAD;
2212 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2213 if (starts_with(refname, ref_kind[i].prefix))
2214 return ref_kind[i].kind;
2217 return FILTER_REFS_OTHERS;
2220 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2222 if (filter->kind == FILTER_REFS_BRANCHES ||
2223 filter->kind == FILTER_REFS_REMOTES ||
2224 filter->kind == FILTER_REFS_TAGS)
2225 return filter->kind;
2226 return ref_kind_from_refname(refname);
2229 struct ref_filter_cbdata {
2230 struct ref_array *array;
2231 struct ref_filter *filter;
2232 struct contains_cache contains_cache;
2233 struct contains_cache no_contains_cache;
2237 * A call-back given to for_each_ref(). Filter refs and keep them for
2238 * later object processing.
2240 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2242 struct ref_filter_cbdata *ref_cbdata = cb_data;
2243 struct ref_filter *filter = ref_cbdata->filter;
2244 struct ref_array_item *ref;
2245 struct commit *commit = NULL;
2246 unsigned int kind;
2248 if (flag & REF_BAD_NAME) {
2249 warning(_("ignoring ref with broken name %s"), refname);
2250 return 0;
2253 if (flag & REF_ISBROKEN) {
2254 warning(_("ignoring broken ref %s"), refname);
2255 return 0;
2258 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2259 kind = filter_ref_kind(filter, refname);
2260 if (!(kind & filter->kind))
2261 return 0;
2263 if (!filter_pattern_match(filter, refname))
2264 return 0;
2266 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2267 return 0;
2270 * A merge filter is applied on refs pointing to commits. Hence
2271 * obtain the commit using the 'oid' available and discard all
2272 * non-commits early. The actual filtering is done later.
2274 if (filter->reachable_from || filter->unreachable_from ||
2275 filter->with_commit || filter->no_commit || filter->verbose) {
2276 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2277 if (!commit)
2278 return 0;
2279 /* We perform the filtering for the '--contains' option... */
2280 if (filter->with_commit &&
2281 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2282 return 0;
2283 /* ...or for the `--no-contains' option */
2284 if (filter->no_commit &&
2285 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2286 return 0;
2290 * We do not open the object yet; sort may only need refname
2291 * to do its job and the resulting list may yet to be pruned
2292 * by maxcount logic.
2294 ref = ref_array_push(ref_cbdata->array, refname, oid);
2295 ref->commit = commit;
2296 ref->flag = flag;
2297 ref->kind = kind;
2299 return 0;
2302 /* Free memory allocated for a ref_array_item */
2303 static void free_array_item(struct ref_array_item *item)
2305 free((char *)item->symref);
2306 if (item->value) {
2307 int i;
2308 for (i = 0; i < used_atom_cnt; i++)
2309 free((char *)item->value[i].s);
2310 free(item->value);
2312 free(item);
2315 /* Free all memory allocated for ref_array */
2316 void ref_array_clear(struct ref_array *array)
2318 int i;
2320 for (i = 0; i < array->nr; i++)
2321 free_array_item(array->items[i]);
2322 FREE_AND_NULL(array->items);
2323 array->nr = array->alloc = 0;
2325 for (i = 0; i < used_atom_cnt; i++) {
2326 struct used_atom *atom = &used_atom[i];
2327 if (atom->atom_type == ATOM_HEAD)
2328 free(atom->u.head);
2329 free((char *)atom->name);
2331 FREE_AND_NULL(used_atom);
2332 used_atom_cnt = 0;
2334 if (ref_to_worktree_map.worktrees) {
2335 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2336 struct ref_to_worktree_entry, ent);
2337 free_worktrees(ref_to_worktree_map.worktrees);
2338 ref_to_worktree_map.worktrees = NULL;
2342 #define EXCLUDE_REACHED 0
2343 #define INCLUDE_REACHED 1
2344 static void reach_filter(struct ref_array *array,
2345 struct commit_list *check_reachable,
2346 int include_reached)
2348 struct rev_info revs;
2349 int i, old_nr;
2350 struct commit **to_clear;
2351 struct commit_list *cr;
2353 if (!check_reachable)
2354 return;
2356 CALLOC_ARRAY(to_clear, array->nr);
2358 repo_init_revisions(the_repository, &revs, NULL);
2360 for (i = 0; i < array->nr; i++) {
2361 struct ref_array_item *item = array->items[i];
2362 add_pending_object(&revs, &item->commit->object, item->refname);
2363 to_clear[i] = item->commit;
2366 for (cr = check_reachable; cr; cr = cr->next) {
2367 struct commit *merge_commit = cr->item;
2368 merge_commit->object.flags |= UNINTERESTING;
2369 add_pending_object(&revs, &merge_commit->object, "");
2372 revs.limited = 1;
2373 if (prepare_revision_walk(&revs))
2374 die(_("revision walk setup failed"));
2376 old_nr = array->nr;
2377 array->nr = 0;
2379 for (i = 0; i < old_nr; i++) {
2380 struct ref_array_item *item = array->items[i];
2381 struct commit *commit = item->commit;
2383 int is_merged = !!(commit->object.flags & UNINTERESTING);
2385 if (is_merged == include_reached)
2386 array->items[array->nr++] = array->items[i];
2387 else
2388 free_array_item(item);
2391 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2393 while (check_reachable) {
2394 struct commit *merge_commit = pop_commit(&check_reachable);
2395 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2398 release_revisions(&revs);
2399 free(to_clear);
2403 * API for filtering a set of refs. Based on the type of refs the user
2404 * has requested, we iterate through those refs and apply filters
2405 * as per the given ref_filter structure and finally store the
2406 * filtered refs in the ref_array structure.
2408 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2410 struct ref_filter_cbdata ref_cbdata;
2411 int save_commit_buffer_orig;
2412 int ret = 0;
2414 ref_cbdata.array = array;
2415 ref_cbdata.filter = filter;
2417 filter->kind = type & FILTER_REFS_KIND_MASK;
2419 save_commit_buffer_orig = save_commit_buffer;
2420 save_commit_buffer = 0;
2422 init_contains_cache(&ref_cbdata.contains_cache);
2423 init_contains_cache(&ref_cbdata.no_contains_cache);
2425 /* Simple per-ref filtering */
2426 if (!filter->kind)
2427 die("filter_refs: invalid type");
2428 else {
2430 * For common cases where we need only branches or remotes or tags,
2431 * we only iterate through those refs. If a mix of refs is needed,
2432 * we iterate over all refs and filter out required refs with the help
2433 * of filter_ref_kind().
2435 if (filter->kind == FILTER_REFS_BRANCHES)
2436 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2437 else if (filter->kind == FILTER_REFS_REMOTES)
2438 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2439 else if (filter->kind == FILTER_REFS_TAGS)
2440 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2441 else if (filter->kind & FILTER_REFS_ALL)
2442 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2443 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2444 head_ref(ref_filter_handler, &ref_cbdata);
2447 clear_contains_cache(&ref_cbdata.contains_cache);
2448 clear_contains_cache(&ref_cbdata.no_contains_cache);
2450 /* Filters that need revision walking */
2451 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2452 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2454 save_commit_buffer = save_commit_buffer_orig;
2455 return ret;
2458 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2460 if (!(a->kind ^ b->kind))
2461 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2462 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2463 return -1;
2464 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2465 return 1;
2466 BUG("should have died in the xor check above");
2467 return 0;
2470 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2472 const char *s1 = vs1, *s2 = vs2;
2473 const char *end = s1 + n;
2475 for (; s1 < end; s1++, s2++) {
2476 int diff = tolower(*s1) - tolower(*s2);
2477 if (diff)
2478 return diff;
2480 return 0;
2483 struct ref_sorting {
2484 struct ref_sorting *next;
2485 int atom; /* index into used_atom array (internal) */
2486 enum ref_sorting_order sort_flags;
2489 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2491 struct atom_value *va, *vb;
2492 int cmp;
2493 int cmp_detached_head = 0;
2494 cmp_type cmp_type = used_atom[s->atom].type;
2495 struct strbuf err = STRBUF_INIT;
2497 if (get_ref_atom_value(a, s->atom, &va, &err))
2498 die("%s", err.buf);
2499 if (get_ref_atom_value(b, s->atom, &vb, &err))
2500 die("%s", err.buf);
2501 strbuf_release(&err);
2502 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2503 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2504 cmp = compare_detached_head(a, b);
2505 cmp_detached_head = 1;
2506 } else if (s->sort_flags & REF_SORTING_VERSION) {
2507 cmp = versioncmp(va->s, vb->s);
2508 } else if (cmp_type == FIELD_STR) {
2509 if (va->s_size < 0 && vb->s_size < 0) {
2510 int (*cmp_fn)(const char *, const char *);
2511 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2512 ? strcasecmp : strcmp;
2513 cmp = cmp_fn(va->s, vb->s);
2514 } else {
2515 size_t a_size = va->s_size < 0 ?
2516 strlen(va->s) : va->s_size;
2517 size_t b_size = vb->s_size < 0 ?
2518 strlen(vb->s) : vb->s_size;
2519 int (*cmp_fn)(const void *, const void *, size_t);
2520 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2521 ? memcasecmp : memcmp;
2523 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2524 a_size : b_size);
2525 if (!cmp) {
2526 if (a_size > b_size)
2527 cmp = 1;
2528 else if (a_size < b_size)
2529 cmp = -1;
2532 } else {
2533 if (va->value < vb->value)
2534 cmp = -1;
2535 else if (va->value == vb->value)
2536 cmp = 0;
2537 else
2538 cmp = 1;
2541 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2542 ? -cmp : cmp;
2545 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2547 struct ref_array_item *a = *((struct ref_array_item **)a_);
2548 struct ref_array_item *b = *((struct ref_array_item **)b_);
2549 struct ref_sorting *s;
2551 for (s = ref_sorting; s; s = s->next) {
2552 int cmp = cmp_ref_sorting(s, a, b);
2553 if (cmp)
2554 return cmp;
2556 s = ref_sorting;
2557 return s && s->sort_flags & REF_SORTING_ICASE ?
2558 strcasecmp(a->refname, b->refname) :
2559 strcmp(a->refname, b->refname);
2562 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2563 unsigned int mask, int on)
2565 for (; sorting; sorting = sorting->next) {
2566 if (on)
2567 sorting->sort_flags |= mask;
2568 else
2569 sorting->sort_flags &= ~mask;
2573 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2575 QSORT_S(array->items, array->nr, compare_refs, sorting);
2578 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2580 struct strbuf *s = &state->stack->output;
2582 while (*cp && (!ep || cp < ep)) {
2583 if (*cp == '%') {
2584 if (cp[1] == '%')
2585 cp++;
2586 else {
2587 int ch = hex2chr(cp + 1);
2588 if (0 <= ch) {
2589 strbuf_addch(s, ch);
2590 cp += 3;
2591 continue;
2595 strbuf_addch(s, *cp);
2596 cp++;
2600 int format_ref_array_item(struct ref_array_item *info,
2601 struct ref_format *format,
2602 struct strbuf *final_buf,
2603 struct strbuf *error_buf)
2605 const char *cp, *sp, *ep;
2606 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2608 state.quote_style = format->quote_style;
2609 push_stack_element(&state.stack);
2611 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2612 struct atom_value *atomv;
2613 int pos;
2615 ep = strchr(sp, ')');
2616 if (cp < sp)
2617 append_literal(cp, sp, &state);
2618 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2619 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2620 atomv->handler(atomv, &state, error_buf)) {
2621 pop_stack_element(&state.stack);
2622 return -1;
2625 if (*cp) {
2626 sp = cp + strlen(cp);
2627 append_literal(cp, sp, &state);
2629 if (format->need_color_reset_at_eol) {
2630 struct atom_value resetv = ATOM_VALUE_INIT;
2631 resetv.s = GIT_COLOR_RESET;
2632 if (append_atom(&resetv, &state, error_buf)) {
2633 pop_stack_element(&state.stack);
2634 return -1;
2637 if (state.stack->prev) {
2638 pop_stack_element(&state.stack);
2639 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2641 strbuf_addbuf(final_buf, &state.stack->output);
2642 pop_stack_element(&state.stack);
2643 return 0;
2646 void pretty_print_ref(const char *name, const struct object_id *oid,
2647 struct ref_format *format)
2649 struct ref_array_item *ref_item;
2650 struct strbuf output = STRBUF_INIT;
2651 struct strbuf err = STRBUF_INIT;
2653 ref_item = new_ref_array_item(name, oid);
2654 ref_item->kind = ref_kind_from_refname(name);
2655 if (format_ref_array_item(ref_item, format, &output, &err))
2656 die("%s", err.buf);
2657 fwrite(output.buf, 1, output.len, stdout);
2658 putchar('\n');
2660 strbuf_release(&err);
2661 strbuf_release(&output);
2662 free_array_item(ref_item);
2665 static int parse_sorting_atom(const char *atom)
2668 * This parses an atom using a dummy ref_format, since we don't
2669 * actually care about the formatting details.
2671 struct ref_format dummy = REF_FORMAT_INIT;
2672 const char *end = atom + strlen(atom);
2673 struct strbuf err = STRBUF_INIT;
2674 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2675 if (res < 0)
2676 die("%s", err.buf);
2677 strbuf_release(&err);
2678 return res;
2681 /* If no sorting option is given, use refname to sort as default */
2682 static struct ref_sorting *ref_default_sorting(void)
2684 static const char cstr_name[] = "refname";
2686 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2688 sorting->next = NULL;
2689 sorting->atom = parse_sorting_atom(cstr_name);
2690 return sorting;
2693 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2695 struct ref_sorting *s;
2697 CALLOC_ARRAY(s, 1);
2698 s->next = *sorting_tail;
2699 *sorting_tail = s;
2701 if (*arg == '-') {
2702 s->sort_flags |= REF_SORTING_REVERSE;
2703 arg++;
2705 if (skip_prefix(arg, "version:", &arg) ||
2706 skip_prefix(arg, "v:", &arg))
2707 s->sort_flags |= REF_SORTING_VERSION;
2708 s->atom = parse_sorting_atom(arg);
2711 struct ref_sorting *ref_sorting_options(struct string_list *options)
2713 struct string_list_item *item;
2714 struct ref_sorting *sorting = NULL, **tail = &sorting;
2716 if (!options->nr) {
2717 sorting = ref_default_sorting();
2718 } else {
2719 for_each_string_list_item(item, options)
2720 parse_ref_sorting(tail, item->string);
2724 * From here on, the ref_sorting list should be used to talk
2725 * about the sort order used for the output. The caller
2726 * should not touch the string form anymore.
2728 string_list_clear(options, 0);
2729 return sorting;
2732 void ref_sorting_release(struct ref_sorting *sorting)
2734 while (sorting) {
2735 struct ref_sorting *next = sorting->next;
2736 free(sorting);
2737 sorting = next;
2741 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2743 struct ref_filter *rf = opt->value;
2744 struct object_id oid;
2745 struct commit *merge_commit;
2747 BUG_ON_OPT_NEG(unset);
2749 if (get_oid(arg, &oid))
2750 die(_("malformed object name %s"), arg);
2752 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2754 if (!merge_commit)
2755 return error(_("option `%s' must point to a commit"), opt->long_name);
2757 if (starts_with(opt->long_name, "no"))
2758 commit_list_insert(merge_commit, &rf->unreachable_from);
2759 else
2760 commit_list_insert(merge_commit, &rf->reachable_from);
2762 return 0;