ws.h: move declarations for ws.c functions from cache.h
[alt-git.git] / ref-filter.c
blob57a5884aec787bdf12402b46c2b7bc77349d92a8
1 #include "cache.h"
2 #include "alloc.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "hex.h"
6 #include "parse-options.h"
7 #include "refs.h"
8 #include "wildmatch.h"
9 #include "object-name.h"
10 #include "object-store.h"
11 #include "oid-array.h"
12 #include "repository.h"
13 #include "commit.h"
14 #include "remote.h"
15 #include "color.h"
16 #include "tag.h"
17 #include "quote.h"
18 #include "ref-filter.h"
19 #include "revision.h"
20 #include "utf8.h"
21 #include "version.h"
22 #include "trailer.h"
23 #include "wt-status.h"
24 #include "commit-slab.h"
25 #include "commit-graph.h"
26 #include "commit-reach.h"
27 #include "worktree.h"
28 #include "hashmap.h"
29 #include "strvec.h"
31 static struct ref_msg {
32 const char *gone;
33 const char *ahead;
34 const char *behind;
35 const char *ahead_behind;
36 } msgs = {
37 /* Untranslated plumbing messages: */
38 "gone",
39 "ahead %d",
40 "behind %d",
41 "ahead %d, behind %d"
44 void setup_ref_filter_porcelain_msg(void)
46 msgs.gone = _("gone");
47 msgs.ahead = _("ahead %d");
48 msgs.behind = _("behind %d");
49 msgs.ahead_behind = _("ahead %d, behind %d");
52 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
53 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
54 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
56 struct align {
57 align_type position;
58 unsigned int width;
61 struct if_then_else {
62 cmp_status cmp_status;
63 const char *str;
64 unsigned int then_atom_seen : 1,
65 else_atom_seen : 1,
66 condition_satisfied : 1;
69 struct refname_atom {
70 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
71 int lstrip, rstrip;
74 static struct ref_trailer_buf {
75 struct string_list filter_list;
76 struct strbuf sepbuf;
77 struct strbuf kvsepbuf;
78 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
80 static struct expand_data {
81 struct object_id oid;
82 enum object_type type;
83 unsigned long size;
84 off_t disk_size;
85 struct object_id delta_base_oid;
86 void *content;
88 struct object_info info;
89 } oi, oi_deref;
91 struct ref_to_worktree_entry {
92 struct hashmap_entry ent;
93 struct worktree *wt; /* key is wt->head_ref */
96 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
97 const struct hashmap_entry *eptr,
98 const struct hashmap_entry *kptr,
99 const void *keydata_aka_refname)
101 const struct ref_to_worktree_entry *e, *k;
103 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
104 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
106 return strcmp(e->wt->head_ref,
107 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
110 static struct ref_to_worktree_map {
111 struct hashmap map;
112 struct worktree **worktrees;
113 } ref_to_worktree_map;
116 * The enum atom_type is used as the index of valid_atom array.
117 * In the atom parsing stage, it will be passed to used_atom.atom_type
118 * as the identifier of the atom type. We can check the type of used_atom
119 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
121 enum atom_type {
122 ATOM_REFNAME,
123 ATOM_OBJECTTYPE,
124 ATOM_OBJECTSIZE,
125 ATOM_OBJECTNAME,
126 ATOM_DELTABASE,
127 ATOM_TREE,
128 ATOM_PARENT,
129 ATOM_NUMPARENT,
130 ATOM_OBJECT,
131 ATOM_TYPE,
132 ATOM_TAG,
133 ATOM_AUTHOR,
134 ATOM_AUTHORNAME,
135 ATOM_AUTHOREMAIL,
136 ATOM_AUTHORDATE,
137 ATOM_COMMITTER,
138 ATOM_COMMITTERNAME,
139 ATOM_COMMITTEREMAIL,
140 ATOM_COMMITTERDATE,
141 ATOM_TAGGER,
142 ATOM_TAGGERNAME,
143 ATOM_TAGGEREMAIL,
144 ATOM_TAGGERDATE,
145 ATOM_CREATOR,
146 ATOM_CREATORDATE,
147 ATOM_SUBJECT,
148 ATOM_BODY,
149 ATOM_TRAILERS,
150 ATOM_CONTENTS,
151 ATOM_RAW,
152 ATOM_UPSTREAM,
153 ATOM_PUSH,
154 ATOM_SYMREF,
155 ATOM_FLAG,
156 ATOM_HEAD,
157 ATOM_COLOR,
158 ATOM_WORKTREEPATH,
159 ATOM_ALIGN,
160 ATOM_END,
161 ATOM_IF,
162 ATOM_THEN,
163 ATOM_ELSE,
164 ATOM_REST,
168 * An atom is a valid field atom listed below, possibly prefixed with
169 * a "*" to denote deref_tag().
171 * We parse given format string and sort specifiers, and make a list
172 * of properties that we need to extract out of objects. ref_array_item
173 * structure will hold an array of values extracted that can be
174 * indexed with the "atom number", which is an index into this
175 * array.
177 static struct used_atom {
178 enum atom_type atom_type;
179 const char *name;
180 cmp_type type;
181 info_source source;
182 union {
183 char color[COLOR_MAXLEN];
184 struct align align;
185 struct {
186 enum {
187 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
188 } option;
189 struct refname_atom refname;
190 unsigned int nobracket : 1, push : 1, push_remote : 1;
191 } remote_ref;
192 struct {
193 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
194 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
195 struct process_trailer_options trailer_opts;
196 unsigned int nlines;
197 } contents;
198 struct {
199 enum { RAW_BARE, RAW_LENGTH } option;
200 } raw_data;
201 struct {
202 cmp_status cmp_status;
203 const char *str;
204 } if_then_else;
205 struct {
206 enum { O_FULL, O_LENGTH, O_SHORT } option;
207 unsigned int length;
208 } oid;
209 struct {
210 enum { O_SIZE, O_SIZE_DISK } option;
211 } objectsize;
212 struct email_option {
213 enum { EO_RAW, EO_TRIM, EO_LOCALPART } option;
214 } email_option;
215 struct refname_atom refname;
216 char *head;
217 } u;
218 } *used_atom;
219 static int used_atom_cnt, need_tagged, need_symref;
222 * Expand string, append it to strbuf *sb, then return error code ret.
223 * Allow to save few lines of code.
225 __attribute__((format (printf, 3, 4)))
226 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
228 va_list ap;
229 va_start(ap, fmt);
230 strbuf_vaddf(sb, fmt, ap);
231 va_end(ap);
232 return ret;
235 static int err_no_arg(struct strbuf *sb, const char *name)
237 size_t namelen = strchrnul(name, ':') - name;
238 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
239 (int)namelen, name);
240 return -1;
243 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
245 size_t namelen = strchrnul(name, ':') - name;
246 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
247 (int)namelen, name, arg);
248 return -1;
251 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
252 const char *color_value, struct strbuf *err)
254 if (!color_value)
255 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
256 if (color_parse(color_value, atom->u.color) < 0)
257 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
258 color_value);
260 * We check this after we've parsed the color, which lets us complain
261 * about syntactically bogus color names even if they won't be used.
263 if (!want_color(format->use_color))
264 color_parse("", atom->u.color);
265 return 0;
268 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
269 const char *name, struct strbuf *err)
271 if (!arg)
272 atom->option = R_NORMAL;
273 else if (!strcmp(arg, "short"))
274 atom->option = R_SHORT;
275 else if (skip_prefix(arg, "lstrip=", &arg) ||
276 skip_prefix(arg, "strip=", &arg)) {
277 atom->option = R_LSTRIP;
278 if (strtol_i(arg, 10, &atom->lstrip))
279 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
280 } else if (skip_prefix(arg, "rstrip=", &arg)) {
281 atom->option = R_RSTRIP;
282 if (strtol_i(arg, 10, &atom->rstrip))
283 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
284 } else
285 return err_bad_arg(err, name, arg);
286 return 0;
289 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
290 struct used_atom *atom,
291 const char *arg, struct strbuf *err)
293 struct string_list params = STRING_LIST_INIT_DUP;
294 int i;
296 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
297 atom->u.remote_ref.push = 1;
299 if (!arg) {
300 atom->u.remote_ref.option = RR_REF;
301 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
302 arg, atom->name, err);
305 atom->u.remote_ref.nobracket = 0;
306 string_list_split(&params, arg, ',', -1);
308 for (i = 0; i < params.nr; i++) {
309 const char *s = params.items[i].string;
311 if (!strcmp(s, "track"))
312 atom->u.remote_ref.option = RR_TRACK;
313 else if (!strcmp(s, "trackshort"))
314 atom->u.remote_ref.option = RR_TRACKSHORT;
315 else if (!strcmp(s, "nobracket"))
316 atom->u.remote_ref.nobracket = 1;
317 else if (!strcmp(s, "remotename")) {
318 atom->u.remote_ref.option = RR_REMOTE_NAME;
319 atom->u.remote_ref.push_remote = 1;
320 } else if (!strcmp(s, "remoteref")) {
321 atom->u.remote_ref.option = RR_REMOTE_REF;
322 atom->u.remote_ref.push_remote = 1;
323 } else {
324 atom->u.remote_ref.option = RR_REF;
325 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
326 arg, atom->name, err)) {
327 string_list_clear(&params, 0);
328 return -1;
333 string_list_clear(&params, 0);
334 return 0;
337 static int objecttype_atom_parser(struct ref_format *format UNUSED,
338 struct used_atom *atom,
339 const char *arg, struct strbuf *err)
341 if (arg)
342 return err_no_arg(err, "objecttype");
343 if (*atom->name == '*')
344 oi_deref.info.typep = &oi_deref.type;
345 else
346 oi.info.typep = &oi.type;
347 return 0;
350 static int objectsize_atom_parser(struct ref_format *format UNUSED,
351 struct used_atom *atom,
352 const char *arg, struct strbuf *err)
354 if (!arg) {
355 atom->u.objectsize.option = O_SIZE;
356 if (*atom->name == '*')
357 oi_deref.info.sizep = &oi_deref.size;
358 else
359 oi.info.sizep = &oi.size;
360 } else if (!strcmp(arg, "disk")) {
361 atom->u.objectsize.option = O_SIZE_DISK;
362 if (*atom->name == '*')
363 oi_deref.info.disk_sizep = &oi_deref.disk_size;
364 else
365 oi.info.disk_sizep = &oi.disk_size;
366 } else
367 return err_bad_arg(err, "objectsize", arg);
368 return 0;
371 static int deltabase_atom_parser(struct ref_format *format UNUSED,
372 struct used_atom *atom,
373 const char *arg, struct strbuf *err)
375 if (arg)
376 return err_no_arg(err, "deltabase");
377 if (*atom->name == '*')
378 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
379 else
380 oi.info.delta_base_oid = &oi.delta_base_oid;
381 return 0;
384 static int body_atom_parser(struct ref_format *format UNUSED,
385 struct used_atom *atom,
386 const char *arg, struct strbuf *err)
388 if (arg)
389 return err_no_arg(err, "body");
390 atom->u.contents.option = C_BODY_DEP;
391 return 0;
394 static int subject_atom_parser(struct ref_format *format UNUSED,
395 struct used_atom *atom,
396 const char *arg, struct strbuf *err)
398 if (!arg)
399 atom->u.contents.option = C_SUB;
400 else if (!strcmp(arg, "sanitize"))
401 atom->u.contents.option = C_SUB_SANITIZE;
402 else
403 return err_bad_arg(err, "subject", arg);
404 return 0;
407 static int trailers_atom_parser(struct ref_format *format UNUSED,
408 struct used_atom *atom,
409 const char *arg, struct strbuf *err)
411 atom->u.contents.trailer_opts.no_divider = 1;
413 if (arg) {
414 const char *argbuf = xstrfmt("%s)", arg);
415 char *invalid_arg = NULL;
417 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
418 &ref_trailer_buf.filter_list,
419 &ref_trailer_buf.sepbuf,
420 &ref_trailer_buf.kvsepbuf,
421 &argbuf, &invalid_arg)) {
422 if (!invalid_arg)
423 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
424 else
425 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
426 free((char *)invalid_arg);
427 return -1;
430 atom->u.contents.option = C_TRAILERS;
431 return 0;
434 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
435 const char *arg, struct strbuf *err)
437 if (!arg)
438 atom->u.contents.option = C_BARE;
439 else if (!strcmp(arg, "body"))
440 atom->u.contents.option = C_BODY;
441 else if (!strcmp(arg, "size"))
442 atom->u.contents.option = C_LENGTH;
443 else if (!strcmp(arg, "signature"))
444 atom->u.contents.option = C_SIG;
445 else if (!strcmp(arg, "subject"))
446 atom->u.contents.option = C_SUB;
447 else if (!strcmp(arg, "trailers")) {
448 if (trailers_atom_parser(format, atom, NULL, err))
449 return -1;
450 } else if (skip_prefix(arg, "trailers:", &arg)) {
451 if (trailers_atom_parser(format, atom, arg, err))
452 return -1;
453 } else if (skip_prefix(arg, "lines=", &arg)) {
454 atom->u.contents.option = C_LINES;
455 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
456 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
457 } else
458 return err_bad_arg(err, "contents", arg);
459 return 0;
462 static int raw_atom_parser(struct ref_format *format UNUSED,
463 struct used_atom *atom,
464 const char *arg, struct strbuf *err)
466 if (!arg)
467 atom->u.raw_data.option = RAW_BARE;
468 else if (!strcmp(arg, "size"))
469 atom->u.raw_data.option = RAW_LENGTH;
470 else
471 return err_bad_arg(err, "raw", arg);
472 return 0;
475 static int oid_atom_parser(struct ref_format *format UNUSED,
476 struct used_atom *atom,
477 const char *arg, struct strbuf *err)
479 if (!arg)
480 atom->u.oid.option = O_FULL;
481 else if (!strcmp(arg, "short"))
482 atom->u.oid.option = O_SHORT;
483 else if (skip_prefix(arg, "short=", &arg)) {
484 atom->u.oid.option = O_LENGTH;
485 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
486 atom->u.oid.length == 0)
487 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
488 if (atom->u.oid.length < MINIMUM_ABBREV)
489 atom->u.oid.length = MINIMUM_ABBREV;
490 } else
491 return err_bad_arg(err, atom->name, arg);
492 return 0;
495 static int person_email_atom_parser(struct ref_format *format UNUSED,
496 struct used_atom *atom,
497 const char *arg, struct strbuf *err)
499 if (!arg)
500 atom->u.email_option.option = EO_RAW;
501 else if (!strcmp(arg, "trim"))
502 atom->u.email_option.option = EO_TRIM;
503 else if (!strcmp(arg, "localpart"))
504 atom->u.email_option.option = EO_LOCALPART;
505 else
506 return err_bad_arg(err, atom->name, arg);
507 return 0;
510 static int refname_atom_parser(struct ref_format *format UNUSED,
511 struct used_atom *atom,
512 const char *arg, struct strbuf *err)
514 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
517 static align_type parse_align_position(const char *s)
519 if (!strcmp(s, "right"))
520 return ALIGN_RIGHT;
521 else if (!strcmp(s, "middle"))
522 return ALIGN_MIDDLE;
523 else if (!strcmp(s, "left"))
524 return ALIGN_LEFT;
525 return -1;
528 static int align_atom_parser(struct ref_format *format UNUSED,
529 struct used_atom *atom,
530 const char *arg, struct strbuf *err)
532 struct align *align = &atom->u.align;
533 struct string_list params = STRING_LIST_INIT_DUP;
534 int i;
535 unsigned int width = ~0U;
537 if (!arg)
538 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
540 align->position = ALIGN_LEFT;
542 string_list_split(&params, arg, ',', -1);
543 for (i = 0; i < params.nr; i++) {
544 const char *s = params.items[i].string;
545 int position;
547 if (skip_prefix(s, "position=", &s)) {
548 position = parse_align_position(s);
549 if (position < 0) {
550 strbuf_addf(err, _("unrecognized position:%s"), s);
551 string_list_clear(&params, 0);
552 return -1;
554 align->position = position;
555 } else if (skip_prefix(s, "width=", &s)) {
556 if (strtoul_ui(s, 10, &width)) {
557 strbuf_addf(err, _("unrecognized width:%s"), s);
558 string_list_clear(&params, 0);
559 return -1;
561 } else if (!strtoul_ui(s, 10, &width))
563 else if ((position = parse_align_position(s)) >= 0)
564 align->position = position;
565 else {
566 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
567 string_list_clear(&params, 0);
568 return -1;
572 if (width == ~0U) {
573 string_list_clear(&params, 0);
574 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
576 align->width = width;
577 string_list_clear(&params, 0);
578 return 0;
581 static int if_atom_parser(struct ref_format *format UNUSED,
582 struct used_atom *atom,
583 const char *arg, struct strbuf *err)
585 if (!arg) {
586 atom->u.if_then_else.cmp_status = COMPARE_NONE;
587 return 0;
588 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
589 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
590 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
591 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
592 } else
593 return err_bad_arg(err, "if", arg);
594 return 0;
597 static int rest_atom_parser(struct ref_format *format,
598 struct used_atom *atom UNUSED,
599 const char *arg, struct strbuf *err)
601 if (arg)
602 return err_no_arg(err, "rest");
603 format->use_rest = 1;
604 return 0;
607 static int head_atom_parser(struct ref_format *format UNUSED,
608 struct used_atom *atom,
609 const char *arg, struct strbuf *err)
611 if (arg)
612 return err_no_arg(err, "HEAD");
613 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
614 return 0;
617 static struct {
618 const char *name;
619 info_source source;
620 cmp_type cmp_type;
621 int (*parser)(struct ref_format *format, struct used_atom *atom,
622 const char *arg, struct strbuf *err);
623 } valid_atom[] = {
624 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
625 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
626 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
627 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
628 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
629 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
630 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
631 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
632 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
633 [ATOM_TYPE] = { "type", SOURCE_OBJ },
634 [ATOM_TAG] = { "tag", SOURCE_OBJ },
635 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
636 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
637 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
638 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
639 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
640 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
641 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
642 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
643 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
644 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
645 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
646 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
647 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
648 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
649 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
650 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
651 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
652 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
653 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
654 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
655 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
656 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
657 [ATOM_FLAG] = { "flag", SOURCE_NONE },
658 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
659 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
660 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
661 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
662 [ATOM_END] = { "end", SOURCE_NONE },
663 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
664 [ATOM_THEN] = { "then", SOURCE_NONE },
665 [ATOM_ELSE] = { "else", SOURCE_NONE },
666 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
668 * Please update $__git_ref_fieldlist in git-completion.bash
669 * when you add new atoms
673 #define REF_FORMATTING_STATE_INIT { 0 }
675 struct ref_formatting_stack {
676 struct ref_formatting_stack *prev;
677 struct strbuf output;
678 void (*at_end)(struct ref_formatting_stack **stack);
679 void *at_end_data;
682 struct ref_formatting_state {
683 int quote_style;
684 struct ref_formatting_stack *stack;
687 struct atom_value {
688 const char *s;
689 ssize_t s_size;
690 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
691 struct strbuf *err);
692 uintmax_t value; /* used for sorting when not FIELD_STR */
693 struct used_atom *atom;
696 #define ATOM_SIZE_UNSPECIFIED (-1)
698 #define ATOM_VALUE_INIT { \
699 .s_size = ATOM_SIZE_UNSPECIFIED \
703 * Used to parse format string and sort specifiers
705 static int parse_ref_filter_atom(struct ref_format *format,
706 const char *atom, const char *ep,
707 struct strbuf *err)
709 const char *sp;
710 const char *arg;
711 int i, at, atom_len;
713 sp = atom;
714 if (*sp == '*' && sp < ep)
715 sp++; /* deref */
716 if (ep <= sp)
717 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
718 (int)(ep-atom), atom);
721 * If the atom name has a colon, strip it and everything after
722 * it off - it specifies the format for this entry, and
723 * shouldn't be used for checking against the valid_atom
724 * table.
726 arg = memchr(sp, ':', ep - sp);
727 atom_len = (arg ? arg : ep) - sp;
729 /* Do we have the atom already used elsewhere? */
730 for (i = 0; i < used_atom_cnt; i++) {
731 int len = strlen(used_atom[i].name);
732 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
733 return i;
736 /* Is the atom a valid one? */
737 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
738 int len = strlen(valid_atom[i].name);
739 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
740 break;
743 if (ARRAY_SIZE(valid_atom) <= i)
744 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
745 (int)(ep-atom), atom);
746 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
747 return strbuf_addf_ret(err, -1,
748 _("not a git repository, but the field '%.*s' requires access to object data"),
749 (int)(ep-atom), atom);
751 /* Add it in, including the deref prefix */
752 at = used_atom_cnt;
753 used_atom_cnt++;
754 REALLOC_ARRAY(used_atom, used_atom_cnt);
755 used_atom[at].atom_type = i;
756 used_atom[at].name = xmemdupz(atom, ep - atom);
757 used_atom[at].type = valid_atom[i].cmp_type;
758 used_atom[at].source = valid_atom[i].source;
759 if (used_atom[at].source == SOURCE_OBJ) {
760 if (*atom == '*')
761 oi_deref.info.contentp = &oi_deref.content;
762 else
763 oi.info.contentp = &oi.content;
765 if (arg) {
766 arg = used_atom[at].name + (arg - atom) + 1;
767 if (!*arg) {
769 * Treat empty sub-arguments list as NULL (i.e.,
770 * "%(atom:)" is equivalent to "%(atom)").
772 arg = NULL;
775 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
776 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
777 return -1;
778 if (*atom == '*')
779 need_tagged = 1;
780 if (i == ATOM_SYMREF)
781 need_symref = 1;
782 return at;
785 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
787 switch (quote_style) {
788 case QUOTE_NONE:
789 if (len < 0)
790 strbuf_addstr(s, str);
791 else
792 strbuf_add(s, str, len);
793 break;
794 case QUOTE_SHELL:
795 sq_quote_buf(s, str);
796 break;
797 case QUOTE_PERL:
798 if (len < 0)
799 perl_quote_buf(s, str);
800 else
801 perl_quote_buf_with_len(s, str, len);
802 break;
803 case QUOTE_PYTHON:
804 python_quote_buf(s, str);
805 break;
806 case QUOTE_TCL:
807 tcl_quote_buf(s, str);
808 break;
812 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
813 struct strbuf *err UNUSED)
816 * Quote formatting is only done when the stack has a single
817 * element. Otherwise quote formatting is done on the
818 * element's entire output strbuf when the %(end) atom is
819 * encountered.
821 if (!state->stack->prev)
822 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
823 else if (v->s_size < 0)
824 strbuf_addstr(&state->stack->output, v->s);
825 else
826 strbuf_add(&state->stack->output, v->s, v->s_size);
827 return 0;
830 static void push_stack_element(struct ref_formatting_stack **stack)
832 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
834 strbuf_init(&s->output, 0);
835 s->prev = *stack;
836 *stack = s;
839 static void pop_stack_element(struct ref_formatting_stack **stack)
841 struct ref_formatting_stack *current = *stack;
842 struct ref_formatting_stack *prev = current->prev;
844 if (prev)
845 strbuf_addbuf(&prev->output, &current->output);
846 strbuf_release(&current->output);
847 free(current);
848 *stack = prev;
851 static void end_align_handler(struct ref_formatting_stack **stack)
853 struct ref_formatting_stack *cur = *stack;
854 struct align *align = (struct align *)cur->at_end_data;
855 struct strbuf s = STRBUF_INIT;
857 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
858 strbuf_swap(&cur->output, &s);
859 strbuf_release(&s);
862 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
863 struct strbuf *err UNUSED)
865 struct ref_formatting_stack *new_stack;
867 push_stack_element(&state->stack);
868 new_stack = state->stack;
869 new_stack->at_end = end_align_handler;
870 new_stack->at_end_data = &atomv->atom->u.align;
871 return 0;
874 static void if_then_else_handler(struct ref_formatting_stack **stack)
876 struct ref_formatting_stack *cur = *stack;
877 struct ref_formatting_stack *prev = cur->prev;
878 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
880 if (!if_then_else->then_atom_seen)
881 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
883 if (if_then_else->else_atom_seen) {
885 * There is an %(else) atom: we need to drop one state from the
886 * stack, either the %(else) branch if the condition is satisfied, or
887 * the %(then) branch if it isn't.
889 if (if_then_else->condition_satisfied) {
890 strbuf_reset(&cur->output);
891 pop_stack_element(&cur);
892 } else {
893 strbuf_swap(&cur->output, &prev->output);
894 strbuf_reset(&cur->output);
895 pop_stack_element(&cur);
897 } else if (!if_then_else->condition_satisfied) {
899 * No %(else) atom: just drop the %(then) branch if the
900 * condition is not satisfied.
902 strbuf_reset(&cur->output);
905 *stack = cur;
906 free(if_then_else);
909 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
910 struct strbuf *err UNUSED)
912 struct ref_formatting_stack *new_stack;
913 struct if_then_else *if_then_else = xcalloc(1,
914 sizeof(struct if_then_else));
916 if_then_else->str = atomv->atom->u.if_then_else.str;
917 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
919 push_stack_element(&state->stack);
920 new_stack = state->stack;
921 new_stack->at_end = if_then_else_handler;
922 new_stack->at_end_data = if_then_else;
923 return 0;
926 static int is_empty(struct strbuf *buf)
928 const char *cur = buf->buf;
929 const char *end = buf->buf + buf->len;
931 while (cur != end && (isspace(*cur)))
932 cur++;
934 return cur == end;
937 static int then_atom_handler(struct atom_value *atomv UNUSED,
938 struct ref_formatting_state *state,
939 struct strbuf *err)
941 struct ref_formatting_stack *cur = state->stack;
942 struct if_then_else *if_then_else = NULL;
943 size_t str_len = 0;
945 if (cur->at_end == if_then_else_handler)
946 if_then_else = (struct if_then_else *)cur->at_end_data;
947 if (!if_then_else)
948 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
949 if (if_then_else->then_atom_seen)
950 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
951 if (if_then_else->else_atom_seen)
952 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
953 if_then_else->then_atom_seen = 1;
954 if (if_then_else->str)
955 str_len = strlen(if_then_else->str);
957 * If the 'equals' or 'notequals' attribute is used then
958 * perform the required comparison. If not, only non-empty
959 * strings satisfy the 'if' condition.
961 if (if_then_else->cmp_status == COMPARE_EQUAL) {
962 if (str_len == cur->output.len &&
963 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
964 if_then_else->condition_satisfied = 1;
965 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
966 if (str_len != cur->output.len ||
967 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
968 if_then_else->condition_satisfied = 1;
969 } else if (cur->output.len && !is_empty(&cur->output))
970 if_then_else->condition_satisfied = 1;
971 strbuf_reset(&cur->output);
972 return 0;
975 static int else_atom_handler(struct atom_value *atomv UNUSED,
976 struct ref_formatting_state *state,
977 struct strbuf *err)
979 struct ref_formatting_stack *prev = state->stack;
980 struct if_then_else *if_then_else = NULL;
982 if (prev->at_end == if_then_else_handler)
983 if_then_else = (struct if_then_else *)prev->at_end_data;
984 if (!if_then_else)
985 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
986 if (!if_then_else->then_atom_seen)
987 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
988 if (if_then_else->else_atom_seen)
989 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
990 if_then_else->else_atom_seen = 1;
991 push_stack_element(&state->stack);
992 state->stack->at_end_data = prev->at_end_data;
993 state->stack->at_end = prev->at_end;
994 return 0;
997 static int end_atom_handler(struct atom_value *atomv UNUSED,
998 struct ref_formatting_state *state,
999 struct strbuf *err)
1001 struct ref_formatting_stack *current = state->stack;
1002 struct strbuf s = STRBUF_INIT;
1004 if (!current->at_end)
1005 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1006 current->at_end(&state->stack);
1008 /* Stack may have been popped within at_end(), hence reset the current pointer */
1009 current = state->stack;
1012 * Perform quote formatting when the stack element is that of
1013 * a supporting atom. If nested then perform quote formatting
1014 * only on the topmost supporting atom.
1016 if (!current->prev->prev) {
1017 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1018 strbuf_swap(&current->output, &s);
1020 strbuf_release(&s);
1021 pop_stack_element(&state->stack);
1022 return 0;
1026 * In a format string, find the next occurrence of %(atom).
1028 static const char *find_next(const char *cp)
1030 while (*cp) {
1031 if (*cp == '%') {
1033 * %( is the start of an atom;
1034 * %% is a quoted per-cent.
1036 if (cp[1] == '(')
1037 return cp;
1038 else if (cp[1] == '%')
1039 cp++; /* skip over two % */
1040 /* otherwise this is a singleton, literal % */
1042 cp++;
1044 return NULL;
1047 static int reject_atom(enum atom_type atom_type)
1049 return atom_type == ATOM_REST;
1053 * Make sure the format string is well formed, and parse out
1054 * the used atoms.
1056 int verify_ref_format(struct ref_format *format)
1058 const char *cp, *sp;
1060 format->need_color_reset_at_eol = 0;
1061 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1062 struct strbuf err = STRBUF_INIT;
1063 const char *color, *ep = strchr(sp, ')');
1064 int at;
1066 if (!ep)
1067 return error(_("malformed format string %s"), sp);
1068 /* sp points at "%(" and ep points at the closing ")" */
1069 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1070 if (at < 0)
1071 die("%s", err.buf);
1072 if (reject_atom(used_atom[at].atom_type))
1073 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1075 if ((format->quote_style == QUOTE_PYTHON ||
1076 format->quote_style == QUOTE_SHELL ||
1077 format->quote_style == QUOTE_TCL) &&
1078 used_atom[at].atom_type == ATOM_RAW &&
1079 used_atom[at].u.raw_data.option == RAW_BARE)
1080 die(_("--format=%.*s cannot be used with "
1081 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1082 cp = ep + 1;
1084 if (skip_prefix(used_atom[at].name, "color:", &color))
1085 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1086 strbuf_release(&err);
1088 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1089 format->need_color_reset_at_eol = 0;
1090 return 0;
1093 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1094 struct used_atom *atom)
1096 switch (atom->u.oid.option) {
1097 case O_FULL:
1098 return oid_to_hex(oid);
1099 case O_LENGTH:
1100 return repo_find_unique_abbrev(the_repository, oid,
1101 atom->u.oid.length);
1102 case O_SHORT:
1103 return repo_find_unique_abbrev(the_repository, oid,
1104 DEFAULT_ABBREV);
1105 default:
1106 BUG("unknown %%(%s) option", field);
1110 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1111 struct atom_value *v, struct used_atom *atom)
1113 if (starts_with(name, field)) {
1114 v->s = xstrdup(do_grab_oid(field, oid, atom));
1115 return 1;
1117 return 0;
1120 /* See grab_values */
1121 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1123 int i;
1125 for (i = 0; i < used_atom_cnt; i++) {
1126 const char *name = used_atom[i].name;
1127 enum atom_type atom_type = used_atom[i].atom_type;
1128 struct atom_value *v = &val[i];
1129 if (!!deref != (*name == '*'))
1130 continue;
1131 if (deref)
1132 name++;
1133 if (atom_type == ATOM_OBJECTTYPE)
1134 v->s = xstrdup(type_name(oi->type));
1135 else if (atom_type == ATOM_OBJECTSIZE) {
1136 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1137 v->value = oi->disk_size;
1138 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1139 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1140 v->value = oi->size;
1141 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1143 } else if (atom_type == ATOM_DELTABASE)
1144 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1145 else if (atom_type == ATOM_OBJECTNAME && deref)
1146 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1150 /* See grab_values */
1151 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1153 int i;
1154 struct tag *tag = (struct tag *) obj;
1156 for (i = 0; i < used_atom_cnt; i++) {
1157 const char *name = used_atom[i].name;
1158 enum atom_type atom_type = used_atom[i].atom_type;
1159 struct atom_value *v = &val[i];
1160 if (!!deref != (*name == '*'))
1161 continue;
1162 if (deref)
1163 name++;
1164 if (atom_type == ATOM_TAG)
1165 v->s = xstrdup(tag->tag);
1166 else if (atom_type == ATOM_TYPE && tag->tagged)
1167 v->s = xstrdup(type_name(tag->tagged->type));
1168 else if (atom_type == ATOM_OBJECT && tag->tagged)
1169 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1173 /* See grab_values */
1174 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1176 int i;
1177 struct commit *commit = (struct commit *) obj;
1179 for (i = 0; i < used_atom_cnt; i++) {
1180 const char *name = used_atom[i].name;
1181 enum atom_type atom_type = used_atom[i].atom_type;
1182 struct atom_value *v = &val[i];
1183 if (!!deref != (*name == '*'))
1184 continue;
1185 if (deref)
1186 name++;
1187 if (atom_type == ATOM_TREE &&
1188 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1189 continue;
1190 if (atom_type == ATOM_NUMPARENT) {
1191 v->value = commit_list_count(commit->parents);
1192 v->s = xstrfmt("%lu", (unsigned long)v->value);
1194 else if (atom_type == ATOM_PARENT) {
1195 struct commit_list *parents;
1196 struct strbuf s = STRBUF_INIT;
1197 for (parents = commit->parents; parents; parents = parents->next) {
1198 struct object_id *oid = &parents->item->object.oid;
1199 if (parents != commit->parents)
1200 strbuf_addch(&s, ' ');
1201 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1203 v->s = strbuf_detach(&s, NULL);
1208 static const char *find_wholine(const char *who, int wholen, const char *buf)
1210 const char *eol;
1211 while (*buf) {
1212 if (!strncmp(buf, who, wholen) &&
1213 buf[wholen] == ' ')
1214 return buf + wholen + 1;
1215 eol = strchr(buf, '\n');
1216 if (!eol)
1217 return "";
1218 eol++;
1219 if (*eol == '\n')
1220 return ""; /* end of header */
1221 buf = eol;
1223 return "";
1226 static const char *copy_line(const char *buf)
1228 const char *eol = strchrnul(buf, '\n');
1229 return xmemdupz(buf, eol - buf);
1232 static const char *copy_name(const char *buf)
1234 const char *cp;
1235 for (cp = buf; *cp && *cp != '\n'; cp++) {
1236 if (starts_with(cp, " <"))
1237 return xmemdupz(buf, cp - buf);
1239 return xstrdup("");
1242 static const char *copy_email(const char *buf, struct used_atom *atom)
1244 const char *email = strchr(buf, '<');
1245 const char *eoemail;
1246 if (!email)
1247 return xstrdup("");
1248 switch (atom->u.email_option.option) {
1249 case EO_RAW:
1250 eoemail = strchr(email, '>');
1251 if (eoemail)
1252 eoemail++;
1253 break;
1254 case EO_TRIM:
1255 email++;
1256 eoemail = strchr(email, '>');
1257 break;
1258 case EO_LOCALPART:
1259 email++;
1260 eoemail = strchr(email, '@');
1261 if (!eoemail)
1262 eoemail = strchr(email, '>');
1263 break;
1264 default:
1265 BUG("unknown email option");
1268 if (!eoemail)
1269 return xstrdup("");
1270 return xmemdupz(email, eoemail - email);
1273 static char *copy_subject(const char *buf, unsigned long len)
1275 struct strbuf sb = STRBUF_INIT;
1276 int i;
1278 for (i = 0; i < len; i++) {
1279 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1280 continue; /* ignore CR in CRLF */
1282 if (buf[i] == '\n')
1283 strbuf_addch(&sb, ' ');
1284 else
1285 strbuf_addch(&sb, buf[i]);
1287 return strbuf_detach(&sb, NULL);
1290 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1292 const char *eoemail = strstr(buf, "> ");
1293 char *zone;
1294 timestamp_t timestamp;
1295 long tz;
1296 struct date_mode date_mode = DATE_MODE_INIT;
1297 const char *formatp;
1300 * We got here because atomname ends in "date" or "date<something>";
1301 * it's not possible that <something> is not ":<format>" because
1302 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1303 * ":" means no format is specified, and use the default.
1305 formatp = strchr(atomname, ':');
1306 if (formatp) {
1307 formatp++;
1308 parse_date_format(formatp, &date_mode);
1311 if (!eoemail)
1312 goto bad;
1313 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1314 if (timestamp == TIME_MAX)
1315 goto bad;
1316 tz = strtol(zone, NULL, 10);
1317 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1318 goto bad;
1319 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1320 v->value = timestamp;
1321 date_mode_release(&date_mode);
1322 return;
1323 bad:
1324 v->s = xstrdup("");
1325 v->value = 0;
1328 /* See grab_values */
1329 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1331 int i;
1332 int wholen = strlen(who);
1333 const char *wholine = NULL;
1335 for (i = 0; i < used_atom_cnt; i++) {
1336 const char *name = used_atom[i].name;
1337 struct atom_value *v = &val[i];
1338 if (!!deref != (*name == '*'))
1339 continue;
1340 if (deref)
1341 name++;
1342 if (strncmp(who, name, wholen))
1343 continue;
1344 if (name[wholen] != 0 &&
1345 strcmp(name + wholen, "name") &&
1346 !starts_with(name + wholen, "email") &&
1347 !starts_with(name + wholen, "date"))
1348 continue;
1349 if (!wholine)
1350 wholine = find_wholine(who, wholen, buf);
1351 if (!wholine)
1352 return; /* no point looking for it */
1353 if (name[wholen] == 0)
1354 v->s = copy_line(wholine);
1355 else if (!strcmp(name + wholen, "name"))
1356 v->s = copy_name(wholine);
1357 else if (starts_with(name + wholen, "email"))
1358 v->s = copy_email(wholine, &used_atom[i]);
1359 else if (starts_with(name + wholen, "date"))
1360 grab_date(wholine, v, name);
1364 * For a tag or a commit object, if "creator" or "creatordate" is
1365 * requested, do something special.
1367 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1368 return; /* "author" for commit object is not wanted */
1369 if (!wholine)
1370 wholine = find_wholine(who, wholen, buf);
1371 if (!wholine)
1372 return;
1373 for (i = 0; i < used_atom_cnt; i++) {
1374 const char *name = used_atom[i].name;
1375 enum atom_type atom_type = used_atom[i].atom_type;
1376 struct atom_value *v = &val[i];
1377 if (!!deref != (*name == '*'))
1378 continue;
1379 if (deref)
1380 name++;
1382 if (atom_type == ATOM_CREATORDATE)
1383 grab_date(wholine, v, name);
1384 else if (atom_type == ATOM_CREATOR)
1385 v->s = copy_line(wholine);
1389 static void find_subpos(const char *buf,
1390 const char **sub, size_t *sublen,
1391 const char **body, size_t *bodylen,
1392 size_t *nonsiglen,
1393 const char **sig, size_t *siglen)
1395 struct strbuf payload = STRBUF_INIT;
1396 struct strbuf signature = STRBUF_INIT;
1397 const char *eol;
1398 const char *end = buf + strlen(buf);
1399 const char *sigstart;
1401 /* parse signature first; we might not even have a subject line */
1402 parse_signature(buf, end - buf, &payload, &signature);
1403 strbuf_release(&payload);
1405 /* skip past header until we hit empty line */
1406 while (*buf && *buf != '\n') {
1407 eol = strchrnul(buf, '\n');
1408 if (*eol)
1409 eol++;
1410 buf = eol;
1412 /* skip any empty lines */
1413 while (*buf == '\n')
1414 buf++;
1415 *sig = strbuf_detach(&signature, siglen);
1416 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1418 /* subject is first non-empty line */
1419 *sub = buf;
1420 /* subject goes to first empty line before signature begins */
1421 if ((eol = strstr(*sub, "\n\n")) ||
1422 (eol = strstr(*sub, "\r\n\r\n"))) {
1423 eol = eol < sigstart ? eol : sigstart;
1424 } else {
1425 /* treat whole message as subject */
1426 eol = sigstart;
1428 buf = eol;
1429 *sublen = buf - *sub;
1430 /* drop trailing newline, if present */
1431 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1432 (*sub)[*sublen - 1] == '\r'))
1433 *sublen -= 1;
1435 /* skip any empty lines */
1436 while (*buf == '\n' || *buf == '\r')
1437 buf++;
1438 *body = buf;
1439 *bodylen = strlen(buf);
1440 *nonsiglen = sigstart - buf;
1444 * If 'lines' is greater than 0, append that many lines from the given
1445 * 'buf' of length 'size' to the given strbuf.
1447 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1449 int i;
1450 const char *sp, *eol;
1451 size_t len;
1453 sp = buf;
1455 for (i = 0; i < lines && sp < buf + size; i++) {
1456 if (i)
1457 strbuf_addstr(out, "\n ");
1458 eol = memchr(sp, '\n', size - (sp - buf));
1459 len = eol ? eol - sp : size - (sp - buf);
1460 strbuf_add(out, sp, len);
1461 if (!eol)
1462 break;
1463 sp = eol + 1;
1467 /* See grab_values */
1468 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1470 int i;
1471 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1472 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1473 void *buf = data->content;
1475 for (i = 0; i < used_atom_cnt; i++) {
1476 struct used_atom *atom = &used_atom[i];
1477 const char *name = atom->name;
1478 struct atom_value *v = &val[i];
1479 enum atom_type atom_type = atom->atom_type;
1481 if (!!deref != (*name == '*'))
1482 continue;
1483 if (deref)
1484 name++;
1486 if (atom_type == ATOM_RAW) {
1487 unsigned long buf_size = data->size;
1489 if (atom->u.raw_data.option == RAW_BARE) {
1490 v->s = xmemdupz(buf, buf_size);
1491 v->s_size = buf_size;
1492 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1493 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1495 continue;
1498 if ((data->type != OBJ_TAG &&
1499 data->type != OBJ_COMMIT) ||
1500 (strcmp(name, "body") &&
1501 !starts_with(name, "subject") &&
1502 !starts_with(name, "trailers") &&
1503 !starts_with(name, "contents")))
1504 continue;
1505 if (!subpos)
1506 find_subpos(buf,
1507 &subpos, &sublen,
1508 &bodypos, &bodylen, &nonsiglen,
1509 &sigpos, &siglen);
1511 if (atom->u.contents.option == C_SUB)
1512 v->s = copy_subject(subpos, sublen);
1513 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1514 struct strbuf sb = STRBUF_INIT;
1515 format_sanitized_subject(&sb, subpos, sublen);
1516 v->s = strbuf_detach(&sb, NULL);
1517 } else if (atom->u.contents.option == C_BODY_DEP)
1518 v->s = xmemdupz(bodypos, bodylen);
1519 else if (atom->u.contents.option == C_LENGTH)
1520 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1521 else if (atom->u.contents.option == C_BODY)
1522 v->s = xmemdupz(bodypos, nonsiglen);
1523 else if (atom->u.contents.option == C_SIG)
1524 v->s = xmemdupz(sigpos, siglen);
1525 else if (atom->u.contents.option == C_LINES) {
1526 struct strbuf s = STRBUF_INIT;
1527 const char *contents_end = bodypos + nonsiglen;
1529 /* Size is the length of the message after removing the signature */
1530 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1531 v->s = strbuf_detach(&s, NULL);
1532 } else if (atom->u.contents.option == C_TRAILERS) {
1533 struct strbuf s = STRBUF_INIT;
1535 /* Format the trailer info according to the trailer_opts given */
1536 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1538 v->s = strbuf_detach(&s, NULL);
1539 } else if (atom->u.contents.option == C_BARE)
1540 v->s = xstrdup(subpos);
1543 free((void *)sigpos);
1547 * We want to have empty print-string for field requests
1548 * that do not apply (e.g. "authordate" for a tag object)
1550 static void fill_missing_values(struct atom_value *val)
1552 int i;
1553 for (i = 0; i < used_atom_cnt; i++) {
1554 struct atom_value *v = &val[i];
1555 if (!v->s)
1556 v->s = xstrdup("");
1561 * val is a list of atom_value to hold returned values. Extract
1562 * the values for atoms in used_atom array out of (obj, buf, sz).
1563 * when deref is false, (obj, buf, sz) is the object that is
1564 * pointed at by the ref itself; otherwise it is the object the
1565 * ref (which is a tag) refers to.
1567 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1569 void *buf = data->content;
1571 switch (obj->type) {
1572 case OBJ_TAG:
1573 grab_tag_values(val, deref, obj);
1574 grab_sub_body_contents(val, deref, data);
1575 grab_person("tagger", val, deref, buf);
1576 break;
1577 case OBJ_COMMIT:
1578 grab_commit_values(val, deref, obj);
1579 grab_sub_body_contents(val, deref, data);
1580 grab_person("author", val, deref, buf);
1581 grab_person("committer", val, deref, buf);
1582 break;
1583 case OBJ_TREE:
1584 /* grab_tree_values(val, deref, obj, buf, sz); */
1585 grab_sub_body_contents(val, deref, data);
1586 break;
1587 case OBJ_BLOB:
1588 /* grab_blob_values(val, deref, obj, buf, sz); */
1589 grab_sub_body_contents(val, deref, data);
1590 break;
1591 default:
1592 die("Eh? Object of type %d?", obj->type);
1596 static inline char *copy_advance(char *dst, const char *src)
1598 while (*src)
1599 *dst++ = *src++;
1600 return dst;
1603 static const char *lstrip_ref_components(const char *refname, int len)
1605 long remaining = len;
1606 const char *start = xstrdup(refname);
1607 const char *to_free = start;
1609 if (len < 0) {
1610 int i;
1611 const char *p = refname;
1613 /* Find total no of '/' separated path-components */
1614 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1617 * The number of components we need to strip is now
1618 * the total minus the components to be left (Plus one
1619 * because we count the number of '/', but the number
1620 * of components is one more than the no of '/').
1622 remaining = i + len + 1;
1625 while (remaining > 0) {
1626 switch (*start++) {
1627 case '\0':
1628 free((char *)to_free);
1629 return xstrdup("");
1630 case '/':
1631 remaining--;
1632 break;
1636 start = xstrdup(start);
1637 free((char *)to_free);
1638 return start;
1641 static const char *rstrip_ref_components(const char *refname, int len)
1643 long remaining = len;
1644 const char *start = xstrdup(refname);
1645 const char *to_free = start;
1647 if (len < 0) {
1648 int i;
1649 const char *p = refname;
1651 /* Find total no of '/' separated path-components */
1652 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1655 * The number of components we need to strip is now
1656 * the total minus the components to be left (Plus one
1657 * because we count the number of '/', but the number
1658 * of components is one more than the no of '/').
1660 remaining = i + len + 1;
1663 while (remaining-- > 0) {
1664 char *p = strrchr(start, '/');
1665 if (!p) {
1666 free((char *)to_free);
1667 return xstrdup("");
1668 } else
1669 p[0] = '\0';
1671 return start;
1674 static const char *show_ref(struct refname_atom *atom, const char *refname)
1676 if (atom->option == R_SHORT)
1677 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1678 else if (atom->option == R_LSTRIP)
1679 return lstrip_ref_components(refname, atom->lstrip);
1680 else if (atom->option == R_RSTRIP)
1681 return rstrip_ref_components(refname, atom->rstrip);
1682 else
1683 return xstrdup(refname);
1686 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1687 struct branch *branch, const char **s)
1689 int num_ours, num_theirs;
1690 if (atom->u.remote_ref.option == RR_REF)
1691 *s = show_ref(&atom->u.remote_ref.refname, refname);
1692 else if (atom->u.remote_ref.option == RR_TRACK) {
1693 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1694 NULL, atom->u.remote_ref.push,
1695 AHEAD_BEHIND_FULL) < 0) {
1696 *s = xstrdup(msgs.gone);
1697 } else if (!num_ours && !num_theirs)
1698 *s = xstrdup("");
1699 else if (!num_ours)
1700 *s = xstrfmt(msgs.behind, num_theirs);
1701 else if (!num_theirs)
1702 *s = xstrfmt(msgs.ahead, num_ours);
1703 else
1704 *s = xstrfmt(msgs.ahead_behind,
1705 num_ours, num_theirs);
1706 if (!atom->u.remote_ref.nobracket && *s[0]) {
1707 const char *to_free = *s;
1708 *s = xstrfmt("[%s]", *s);
1709 free((void *)to_free);
1711 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1712 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1713 NULL, atom->u.remote_ref.push,
1714 AHEAD_BEHIND_FULL) < 0) {
1715 *s = xstrdup("");
1716 return;
1718 if (!num_ours && !num_theirs)
1719 *s = xstrdup("=");
1720 else if (!num_ours)
1721 *s = xstrdup("<");
1722 else if (!num_theirs)
1723 *s = xstrdup(">");
1724 else
1725 *s = xstrdup("<>");
1726 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1727 int explicit;
1728 const char *remote = atom->u.remote_ref.push ?
1729 pushremote_for_branch(branch, &explicit) :
1730 remote_for_branch(branch, &explicit);
1731 *s = xstrdup(explicit ? remote : "");
1732 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1733 const char *merge;
1735 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1736 *s = xstrdup(merge ? merge : "");
1737 } else
1738 BUG("unhandled RR_* enum");
1741 char *get_head_description(void)
1743 struct strbuf desc = STRBUF_INIT;
1744 struct wt_status_state state;
1745 memset(&state, 0, sizeof(state));
1746 wt_status_get_state(the_repository, &state, 1);
1747 if (state.rebase_in_progress ||
1748 state.rebase_interactive_in_progress) {
1749 if (state.branch)
1750 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1751 state.branch);
1752 else
1753 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1754 state.detached_from);
1755 } else if (state.bisect_in_progress)
1756 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1757 state.branch);
1758 else if (state.detached_from) {
1759 if (state.detached_at)
1760 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1761 state.detached_from);
1762 else
1763 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1764 state.detached_from);
1765 } else
1766 strbuf_addstr(&desc, _("(no branch)"));
1768 wt_status_state_free_buffers(&state);
1770 return strbuf_detach(&desc, NULL);
1773 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1775 if (!ref->symref)
1776 return xstrdup("");
1777 else
1778 return show_ref(&atom->u.refname, ref->symref);
1781 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1783 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1784 return get_head_description();
1785 return show_ref(&atom->u.refname, ref->refname);
1788 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1789 struct expand_data *oi, struct strbuf *err)
1791 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1792 int eaten = 1;
1793 if (oi->info.contentp) {
1794 /* We need to know that to use parse_object_buffer properly */
1795 oi->info.sizep = &oi->size;
1796 oi->info.typep = &oi->type;
1798 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1799 OBJECT_INFO_LOOKUP_REPLACE))
1800 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1801 oid_to_hex(&oi->oid), ref->refname);
1802 if (oi->info.disk_sizep && oi->disk_size < 0)
1803 BUG("Object size is less than zero.");
1805 if (oi->info.contentp) {
1806 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1807 if (!*obj) {
1808 if (!eaten)
1809 free(oi->content);
1810 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1811 oid_to_hex(&oi->oid), ref->refname);
1813 grab_values(ref->value, deref, *obj, oi);
1816 grab_common_values(ref->value, deref, oi);
1817 if (!eaten)
1818 free(oi->content);
1819 return 0;
1822 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1824 int i;
1826 for (i = 0; worktrees[i]; i++) {
1827 if (worktrees[i]->head_ref) {
1828 struct ref_to_worktree_entry *entry;
1829 entry = xmalloc(sizeof(*entry));
1830 entry->wt = worktrees[i];
1831 hashmap_entry_init(&entry->ent,
1832 strhash(worktrees[i]->head_ref));
1834 hashmap_add(map, &entry->ent);
1839 static void lazy_init_worktree_map(void)
1841 if (ref_to_worktree_map.worktrees)
1842 return;
1844 ref_to_worktree_map.worktrees = get_worktrees();
1845 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1846 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1849 static char *get_worktree_path(const struct ref_array_item *ref)
1851 struct hashmap_entry entry, *e;
1852 struct ref_to_worktree_entry *lookup_result;
1854 lazy_init_worktree_map();
1856 hashmap_entry_init(&entry, strhash(ref->refname));
1857 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1859 if (!e)
1860 return xstrdup("");
1862 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1864 return xstrdup(lookup_result->wt->path);
1868 * Parse the object referred by ref, and grab needed value.
1870 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1872 struct object *obj;
1873 int i;
1874 struct object_info empty = OBJECT_INFO_INIT;
1876 CALLOC_ARRAY(ref->value, used_atom_cnt);
1878 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1879 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1880 NULL, NULL);
1881 if (!ref->symref)
1882 ref->symref = xstrdup("");
1885 /* Fill in specials first */
1886 for (i = 0; i < used_atom_cnt; i++) {
1887 struct used_atom *atom = &used_atom[i];
1888 enum atom_type atom_type = atom->atom_type;
1889 const char *name = used_atom[i].name;
1890 struct atom_value *v = &ref->value[i];
1891 int deref = 0;
1892 const char *refname;
1893 struct branch *branch = NULL;
1895 v->s_size = ATOM_SIZE_UNSPECIFIED;
1896 v->handler = append_atom;
1897 v->atom = atom;
1899 if (*name == '*') {
1900 deref = 1;
1901 name++;
1904 if (atom_type == ATOM_REFNAME)
1905 refname = get_refname(atom, ref);
1906 else if (atom_type == ATOM_WORKTREEPATH) {
1907 if (ref->kind == FILTER_REFS_BRANCHES)
1908 v->s = get_worktree_path(ref);
1909 else
1910 v->s = xstrdup("");
1911 continue;
1913 else if (atom_type == ATOM_SYMREF)
1914 refname = get_symref(atom, ref);
1915 else if (atom_type == ATOM_UPSTREAM) {
1916 const char *branch_name;
1917 /* only local branches may have an upstream */
1918 if (!skip_prefix(ref->refname, "refs/heads/",
1919 &branch_name)) {
1920 v->s = xstrdup("");
1921 continue;
1923 branch = branch_get(branch_name);
1925 refname = branch_get_upstream(branch, NULL);
1926 if (refname)
1927 fill_remote_ref_details(atom, refname, branch, &v->s);
1928 else
1929 v->s = xstrdup("");
1930 continue;
1931 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1932 const char *branch_name;
1933 v->s = xstrdup("");
1934 if (!skip_prefix(ref->refname, "refs/heads/",
1935 &branch_name))
1936 continue;
1937 branch = branch_get(branch_name);
1939 if (atom->u.remote_ref.push_remote)
1940 refname = NULL;
1941 else {
1942 refname = branch_get_push(branch, NULL);
1943 if (!refname)
1944 continue;
1946 /* We will definitely re-init v->s on the next line. */
1947 free((char *)v->s);
1948 fill_remote_ref_details(atom, refname, branch, &v->s);
1949 continue;
1950 } else if (atom_type == ATOM_COLOR) {
1951 v->s = xstrdup(atom->u.color);
1952 continue;
1953 } else if (atom_type == ATOM_FLAG) {
1954 char buf[256], *cp = buf;
1955 if (ref->flag & REF_ISSYMREF)
1956 cp = copy_advance(cp, ",symref");
1957 if (ref->flag & REF_ISPACKED)
1958 cp = copy_advance(cp, ",packed");
1959 if (cp == buf)
1960 v->s = xstrdup("");
1961 else {
1962 *cp = '\0';
1963 v->s = xstrdup(buf + 1);
1965 continue;
1966 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1967 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1968 continue;
1969 } else if (atom_type == ATOM_HEAD) {
1970 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1971 v->s = xstrdup("*");
1972 else
1973 v->s = xstrdup(" ");
1974 continue;
1975 } else if (atom_type == ATOM_ALIGN) {
1976 v->handler = align_atom_handler;
1977 v->s = xstrdup("");
1978 continue;
1979 } else if (atom_type == ATOM_END) {
1980 v->handler = end_atom_handler;
1981 v->s = xstrdup("");
1982 continue;
1983 } else if (atom_type == ATOM_IF) {
1984 const char *s;
1985 if (skip_prefix(name, "if:", &s))
1986 v->s = xstrdup(s);
1987 else
1988 v->s = xstrdup("");
1989 v->handler = if_atom_handler;
1990 continue;
1991 } else if (atom_type == ATOM_THEN) {
1992 v->handler = then_atom_handler;
1993 v->s = xstrdup("");
1994 continue;
1995 } else if (atom_type == ATOM_ELSE) {
1996 v->handler = else_atom_handler;
1997 v->s = xstrdup("");
1998 continue;
1999 } else if (atom_type == ATOM_REST) {
2000 if (ref->rest)
2001 v->s = xstrdup(ref->rest);
2002 else
2003 v->s = xstrdup("");
2004 continue;
2005 } else
2006 continue;
2008 if (!deref)
2009 v->s = xstrdup(refname);
2010 else
2011 v->s = xstrfmt("%s^{}", refname);
2012 free((char *)refname);
2015 for (i = 0; i < used_atom_cnt; i++) {
2016 struct atom_value *v = &ref->value[i];
2017 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2018 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2019 oid_to_hex(&ref->objectname), ref->refname);
2022 if (need_tagged)
2023 oi.info.contentp = &oi.content;
2024 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2025 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2026 return 0;
2029 oi.oid = ref->objectname;
2030 if (get_object(ref, 0, &obj, &oi, err))
2031 return -1;
2034 * If there is no atom that wants to know about tagged
2035 * object, we are done.
2037 if (!need_tagged || (obj->type != OBJ_TAG))
2038 return 0;
2041 * If it is a tag object, see if we use a value that derefs
2042 * the object, and if we do grab the object it refers to.
2044 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2047 * NEEDSWORK: This derefs tag only once, which
2048 * is good to deal with chains of trust, but
2049 * is not consistent with what deref_tag() does
2050 * which peels the onion to the core.
2052 return get_object(ref, 1, &obj, &oi_deref, err);
2056 * Given a ref, return the value for the atom. This lazily gets value
2057 * out of the object by calling populate value.
2059 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2060 struct atom_value **v, struct strbuf *err)
2062 if (!ref->value) {
2063 if (populate_value(ref, err))
2064 return -1;
2065 fill_missing_values(ref->value);
2067 *v = &ref->value[atom];
2068 return 0;
2072 * Return 1 if the refname matches one of the patterns, otherwise 0.
2073 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2074 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2075 * matches "refs/heads/mas*", too).
2077 static int match_pattern(const struct ref_filter *filter, const char *refname)
2079 const char **patterns = filter->name_patterns;
2080 unsigned flags = 0;
2082 if (filter->ignore_case)
2083 flags |= WM_CASEFOLD;
2086 * When no '--format' option is given we need to skip the prefix
2087 * for matching refs of tags and branches.
2089 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2090 skip_prefix(refname, "refs/heads/", &refname) ||
2091 skip_prefix(refname, "refs/remotes/", &refname) ||
2092 skip_prefix(refname, "refs/", &refname));
2094 for (; *patterns; patterns++) {
2095 if (!wildmatch(*patterns, refname, flags))
2096 return 1;
2098 return 0;
2102 * Return 1 if the refname matches one of the patterns, otherwise 0.
2103 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2104 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2105 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2107 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2109 const char **pattern = filter->name_patterns;
2110 int namelen = strlen(refname);
2111 unsigned flags = WM_PATHNAME;
2113 if (filter->ignore_case)
2114 flags |= WM_CASEFOLD;
2116 for (; *pattern; pattern++) {
2117 const char *p = *pattern;
2118 int plen = strlen(p);
2120 if ((plen <= namelen) &&
2121 !strncmp(refname, p, plen) &&
2122 (refname[plen] == '\0' ||
2123 refname[plen] == '/' ||
2124 p[plen-1] == '/'))
2125 return 1;
2126 if (!wildmatch(p, refname, flags))
2127 return 1;
2129 return 0;
2132 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2133 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2135 if (!*filter->name_patterns)
2136 return 1; /* No pattern always matches */
2137 if (filter->match_as_path)
2138 return match_name_as_path(filter, refname);
2139 return match_pattern(filter, refname);
2143 * This is the same as for_each_fullref_in(), but it tries to iterate
2144 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2145 * pattern match, so the callback still has to match each ref individually.
2147 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2148 each_ref_fn cb,
2149 void *cb_data)
2151 if (!filter->match_as_path) {
2153 * in this case, the patterns are applied after
2154 * prefixes like "refs/heads/" etc. are stripped off,
2155 * so we have to look at everything:
2157 return for_each_fullref_in("", cb, cb_data);
2160 if (filter->ignore_case) {
2162 * we can't handle case-insensitive comparisons,
2163 * so just return everything and let the caller
2164 * sort it out.
2166 return for_each_fullref_in("", cb, cb_data);
2169 if (!filter->name_patterns[0]) {
2170 /* no patterns; we have to look at everything */
2171 return for_each_fullref_in("", cb, cb_data);
2174 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2175 NULL, filter->name_patterns,
2176 cb, cb_data);
2180 * Given a ref (oid, refname), check if the ref belongs to the array
2181 * of oids. If the given ref is a tag, check if the given tag points
2182 * at one of the oids in the given oid array.
2183 * NEEDSWORK:
2184 * 1. Only a single level of indirection is obtained, we might want to
2185 * change this to account for multiple levels (e.g. annotated tags
2186 * pointing to annotated tags pointing to a commit.)
2187 * 2. As the refs are cached we might know what refname peels to without
2188 * the need to parse the object via parse_object(). peel_ref() might be a
2189 * more efficient alternative to obtain the pointee.
2191 static const struct object_id *match_points_at(struct oid_array *points_at,
2192 const struct object_id *oid,
2193 const char *refname)
2195 const struct object_id *tagged_oid = NULL;
2196 struct object *obj;
2198 if (oid_array_lookup(points_at, oid) >= 0)
2199 return oid;
2200 obj = parse_object(the_repository, oid);
2201 if (!obj)
2202 die(_("malformed object at '%s'"), refname);
2203 if (obj->type == OBJ_TAG)
2204 tagged_oid = get_tagged_oid((struct tag *)obj);
2205 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2206 return tagged_oid;
2207 return NULL;
2211 * Allocate space for a new ref_array_item and copy the name and oid to it.
2213 * Callers can then fill in other struct members at their leisure.
2215 static struct ref_array_item *new_ref_array_item(const char *refname,
2216 const struct object_id *oid)
2218 struct ref_array_item *ref;
2220 FLEX_ALLOC_STR(ref, refname, refname);
2221 oidcpy(&ref->objectname, oid);
2222 ref->rest = NULL;
2224 return ref;
2227 struct ref_array_item *ref_array_push(struct ref_array *array,
2228 const char *refname,
2229 const struct object_id *oid)
2231 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2233 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2234 array->items[array->nr++] = ref;
2236 return ref;
2239 static int ref_kind_from_refname(const char *refname)
2241 unsigned int i;
2243 static struct {
2244 const char *prefix;
2245 unsigned int kind;
2246 } ref_kind[] = {
2247 { "refs/heads/" , FILTER_REFS_BRANCHES },
2248 { "refs/remotes/" , FILTER_REFS_REMOTES },
2249 { "refs/tags/", FILTER_REFS_TAGS}
2252 if (!strcmp(refname, "HEAD"))
2253 return FILTER_REFS_DETACHED_HEAD;
2255 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2256 if (starts_with(refname, ref_kind[i].prefix))
2257 return ref_kind[i].kind;
2260 return FILTER_REFS_OTHERS;
2263 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2265 if (filter->kind == FILTER_REFS_BRANCHES ||
2266 filter->kind == FILTER_REFS_REMOTES ||
2267 filter->kind == FILTER_REFS_TAGS)
2268 return filter->kind;
2269 return ref_kind_from_refname(refname);
2272 struct ref_filter_cbdata {
2273 struct ref_array *array;
2274 struct ref_filter *filter;
2275 struct contains_cache contains_cache;
2276 struct contains_cache no_contains_cache;
2280 * A call-back given to for_each_ref(). Filter refs and keep them for
2281 * later object processing.
2283 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2285 struct ref_filter_cbdata *ref_cbdata = cb_data;
2286 struct ref_filter *filter = ref_cbdata->filter;
2287 struct ref_array_item *ref;
2288 struct commit *commit = NULL;
2289 unsigned int kind;
2291 if (flag & REF_BAD_NAME) {
2292 warning(_("ignoring ref with broken name %s"), refname);
2293 return 0;
2296 if (flag & REF_ISBROKEN) {
2297 warning(_("ignoring broken ref %s"), refname);
2298 return 0;
2301 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2302 kind = filter_ref_kind(filter, refname);
2303 if (!(kind & filter->kind))
2304 return 0;
2306 if (!filter_pattern_match(filter, refname))
2307 return 0;
2309 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2310 return 0;
2313 * A merge filter is applied on refs pointing to commits. Hence
2314 * obtain the commit using the 'oid' available and discard all
2315 * non-commits early. The actual filtering is done later.
2317 if (filter->reachable_from || filter->unreachable_from ||
2318 filter->with_commit || filter->no_commit || filter->verbose) {
2319 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2320 if (!commit)
2321 return 0;
2322 /* We perform the filtering for the '--contains' option... */
2323 if (filter->with_commit &&
2324 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2325 return 0;
2326 /* ...or for the `--no-contains' option */
2327 if (filter->no_commit &&
2328 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2329 return 0;
2333 * We do not open the object yet; sort may only need refname
2334 * to do its job and the resulting list may yet to be pruned
2335 * by maxcount logic.
2337 ref = ref_array_push(ref_cbdata->array, refname, oid);
2338 ref->commit = commit;
2339 ref->flag = flag;
2340 ref->kind = kind;
2342 return 0;
2345 /* Free memory allocated for a ref_array_item */
2346 static void free_array_item(struct ref_array_item *item)
2348 free((char *)item->symref);
2349 if (item->value) {
2350 int i;
2351 for (i = 0; i < used_atom_cnt; i++)
2352 free((char *)item->value[i].s);
2353 free(item->value);
2355 free(item);
2358 /* Free all memory allocated for ref_array */
2359 void ref_array_clear(struct ref_array *array)
2361 int i;
2363 for (i = 0; i < array->nr; i++)
2364 free_array_item(array->items[i]);
2365 FREE_AND_NULL(array->items);
2366 array->nr = array->alloc = 0;
2368 for (i = 0; i < used_atom_cnt; i++) {
2369 struct used_atom *atom = &used_atom[i];
2370 if (atom->atom_type == ATOM_HEAD)
2371 free(atom->u.head);
2372 free((char *)atom->name);
2374 FREE_AND_NULL(used_atom);
2375 used_atom_cnt = 0;
2377 if (ref_to_worktree_map.worktrees) {
2378 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2379 struct ref_to_worktree_entry, ent);
2380 free_worktrees(ref_to_worktree_map.worktrees);
2381 ref_to_worktree_map.worktrees = NULL;
2385 #define EXCLUDE_REACHED 0
2386 #define INCLUDE_REACHED 1
2387 static void reach_filter(struct ref_array *array,
2388 struct commit_list *check_reachable,
2389 int include_reached)
2391 struct rev_info revs;
2392 int i, old_nr;
2393 struct commit **to_clear;
2394 struct commit_list *cr;
2396 if (!check_reachable)
2397 return;
2399 CALLOC_ARRAY(to_clear, array->nr);
2401 repo_init_revisions(the_repository, &revs, NULL);
2403 for (i = 0; i < array->nr; i++) {
2404 struct ref_array_item *item = array->items[i];
2405 add_pending_object(&revs, &item->commit->object, item->refname);
2406 to_clear[i] = item->commit;
2409 for (cr = check_reachable; cr; cr = cr->next) {
2410 struct commit *merge_commit = cr->item;
2411 merge_commit->object.flags |= UNINTERESTING;
2412 add_pending_object(&revs, &merge_commit->object, "");
2415 revs.limited = 1;
2416 if (prepare_revision_walk(&revs))
2417 die(_("revision walk setup failed"));
2419 old_nr = array->nr;
2420 array->nr = 0;
2422 for (i = 0; i < old_nr; i++) {
2423 struct ref_array_item *item = array->items[i];
2424 struct commit *commit = item->commit;
2426 int is_merged = !!(commit->object.flags & UNINTERESTING);
2428 if (is_merged == include_reached)
2429 array->items[array->nr++] = array->items[i];
2430 else
2431 free_array_item(item);
2434 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2436 while (check_reachable) {
2437 struct commit *merge_commit = pop_commit(&check_reachable);
2438 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2441 release_revisions(&revs);
2442 free(to_clear);
2446 * API for filtering a set of refs. Based on the type of refs the user
2447 * has requested, we iterate through those refs and apply filters
2448 * as per the given ref_filter structure and finally store the
2449 * filtered refs in the ref_array structure.
2451 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2453 struct ref_filter_cbdata ref_cbdata;
2454 int save_commit_buffer_orig;
2455 int ret = 0;
2457 ref_cbdata.array = array;
2458 ref_cbdata.filter = filter;
2460 filter->kind = type & FILTER_REFS_KIND_MASK;
2462 save_commit_buffer_orig = save_commit_buffer;
2463 save_commit_buffer = 0;
2465 init_contains_cache(&ref_cbdata.contains_cache);
2466 init_contains_cache(&ref_cbdata.no_contains_cache);
2468 /* Simple per-ref filtering */
2469 if (!filter->kind)
2470 die("filter_refs: invalid type");
2471 else {
2473 * For common cases where we need only branches or remotes or tags,
2474 * we only iterate through those refs. If a mix of refs is needed,
2475 * we iterate over all refs and filter out required refs with the help
2476 * of filter_ref_kind().
2478 if (filter->kind == FILTER_REFS_BRANCHES)
2479 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2480 else if (filter->kind == FILTER_REFS_REMOTES)
2481 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2482 else if (filter->kind == FILTER_REFS_TAGS)
2483 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2484 else if (filter->kind & FILTER_REFS_ALL)
2485 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2486 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2487 head_ref(ref_filter_handler, &ref_cbdata);
2490 clear_contains_cache(&ref_cbdata.contains_cache);
2491 clear_contains_cache(&ref_cbdata.no_contains_cache);
2493 /* Filters that need revision walking */
2494 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2495 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2497 save_commit_buffer = save_commit_buffer_orig;
2498 return ret;
2501 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2503 if (!(a->kind ^ b->kind))
2504 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2505 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2506 return -1;
2507 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2508 return 1;
2509 BUG("should have died in the xor check above");
2510 return 0;
2513 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2515 const char *s1 = vs1, *s2 = vs2;
2516 const char *end = s1 + n;
2518 for (; s1 < end; s1++, s2++) {
2519 int diff = tolower(*s1) - tolower(*s2);
2520 if (diff)
2521 return diff;
2523 return 0;
2526 struct ref_sorting {
2527 struct ref_sorting *next;
2528 int atom; /* index into used_atom array (internal) */
2529 enum ref_sorting_order sort_flags;
2532 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2534 struct atom_value *va, *vb;
2535 int cmp;
2536 int cmp_detached_head = 0;
2537 cmp_type cmp_type = used_atom[s->atom].type;
2538 struct strbuf err = STRBUF_INIT;
2540 if (get_ref_atom_value(a, s->atom, &va, &err))
2541 die("%s", err.buf);
2542 if (get_ref_atom_value(b, s->atom, &vb, &err))
2543 die("%s", err.buf);
2544 strbuf_release(&err);
2545 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2546 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2547 cmp = compare_detached_head(a, b);
2548 cmp_detached_head = 1;
2549 } else if (s->sort_flags & REF_SORTING_VERSION) {
2550 cmp = versioncmp(va->s, vb->s);
2551 } else if (cmp_type == FIELD_STR) {
2552 if (va->s_size < 0 && vb->s_size < 0) {
2553 int (*cmp_fn)(const char *, const char *);
2554 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2555 ? strcasecmp : strcmp;
2556 cmp = cmp_fn(va->s, vb->s);
2557 } else {
2558 size_t a_size = va->s_size < 0 ?
2559 strlen(va->s) : va->s_size;
2560 size_t b_size = vb->s_size < 0 ?
2561 strlen(vb->s) : vb->s_size;
2562 int (*cmp_fn)(const void *, const void *, size_t);
2563 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2564 ? memcasecmp : memcmp;
2566 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2567 a_size : b_size);
2568 if (!cmp) {
2569 if (a_size > b_size)
2570 cmp = 1;
2571 else if (a_size < b_size)
2572 cmp = -1;
2575 } else {
2576 if (va->value < vb->value)
2577 cmp = -1;
2578 else if (va->value == vb->value)
2579 cmp = 0;
2580 else
2581 cmp = 1;
2584 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2585 ? -cmp : cmp;
2588 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2590 struct ref_array_item *a = *((struct ref_array_item **)a_);
2591 struct ref_array_item *b = *((struct ref_array_item **)b_);
2592 struct ref_sorting *s;
2594 for (s = ref_sorting; s; s = s->next) {
2595 int cmp = cmp_ref_sorting(s, a, b);
2596 if (cmp)
2597 return cmp;
2599 s = ref_sorting;
2600 return s && s->sort_flags & REF_SORTING_ICASE ?
2601 strcasecmp(a->refname, b->refname) :
2602 strcmp(a->refname, b->refname);
2605 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2606 unsigned int mask, int on)
2608 for (; sorting; sorting = sorting->next) {
2609 if (on)
2610 sorting->sort_flags |= mask;
2611 else
2612 sorting->sort_flags &= ~mask;
2616 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2618 QSORT_S(array->items, array->nr, compare_refs, sorting);
2621 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2623 struct strbuf *s = &state->stack->output;
2625 while (*cp && (!ep || cp < ep)) {
2626 if (*cp == '%') {
2627 if (cp[1] == '%')
2628 cp++;
2629 else {
2630 int ch = hex2chr(cp + 1);
2631 if (0 <= ch) {
2632 strbuf_addch(s, ch);
2633 cp += 3;
2634 continue;
2638 strbuf_addch(s, *cp);
2639 cp++;
2643 int format_ref_array_item(struct ref_array_item *info,
2644 struct ref_format *format,
2645 struct strbuf *final_buf,
2646 struct strbuf *error_buf)
2648 const char *cp, *sp, *ep;
2649 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2651 state.quote_style = format->quote_style;
2652 push_stack_element(&state.stack);
2654 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2655 struct atom_value *atomv;
2656 int pos;
2658 ep = strchr(sp, ')');
2659 if (cp < sp)
2660 append_literal(cp, sp, &state);
2661 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2662 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2663 atomv->handler(atomv, &state, error_buf)) {
2664 pop_stack_element(&state.stack);
2665 return -1;
2668 if (*cp) {
2669 sp = cp + strlen(cp);
2670 append_literal(cp, sp, &state);
2672 if (format->need_color_reset_at_eol) {
2673 struct atom_value resetv = ATOM_VALUE_INIT;
2674 resetv.s = GIT_COLOR_RESET;
2675 if (append_atom(&resetv, &state, error_buf)) {
2676 pop_stack_element(&state.stack);
2677 return -1;
2680 if (state.stack->prev) {
2681 pop_stack_element(&state.stack);
2682 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2684 strbuf_addbuf(final_buf, &state.stack->output);
2685 pop_stack_element(&state.stack);
2686 return 0;
2689 void pretty_print_ref(const char *name, const struct object_id *oid,
2690 struct ref_format *format)
2692 struct ref_array_item *ref_item;
2693 struct strbuf output = STRBUF_INIT;
2694 struct strbuf err = STRBUF_INIT;
2696 ref_item = new_ref_array_item(name, oid);
2697 ref_item->kind = ref_kind_from_refname(name);
2698 if (format_ref_array_item(ref_item, format, &output, &err))
2699 die("%s", err.buf);
2700 fwrite(output.buf, 1, output.len, stdout);
2701 putchar('\n');
2703 strbuf_release(&err);
2704 strbuf_release(&output);
2705 free_array_item(ref_item);
2708 static int parse_sorting_atom(const char *atom)
2711 * This parses an atom using a dummy ref_format, since we don't
2712 * actually care about the formatting details.
2714 struct ref_format dummy = REF_FORMAT_INIT;
2715 const char *end = atom + strlen(atom);
2716 struct strbuf err = STRBUF_INIT;
2717 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2718 if (res < 0)
2719 die("%s", err.buf);
2720 strbuf_release(&err);
2721 return res;
2724 /* If no sorting option is given, use refname to sort as default */
2725 static struct ref_sorting *ref_default_sorting(void)
2727 static const char cstr_name[] = "refname";
2729 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2731 sorting->next = NULL;
2732 sorting->atom = parse_sorting_atom(cstr_name);
2733 return sorting;
2736 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2738 struct ref_sorting *s;
2740 CALLOC_ARRAY(s, 1);
2741 s->next = *sorting_tail;
2742 *sorting_tail = s;
2744 if (*arg == '-') {
2745 s->sort_flags |= REF_SORTING_REVERSE;
2746 arg++;
2748 if (skip_prefix(arg, "version:", &arg) ||
2749 skip_prefix(arg, "v:", &arg))
2750 s->sort_flags |= REF_SORTING_VERSION;
2751 s->atom = parse_sorting_atom(arg);
2754 struct ref_sorting *ref_sorting_options(struct string_list *options)
2756 struct string_list_item *item;
2757 struct ref_sorting *sorting = NULL, **tail = &sorting;
2759 if (!options->nr) {
2760 sorting = ref_default_sorting();
2761 } else {
2762 for_each_string_list_item(item, options)
2763 parse_ref_sorting(tail, item->string);
2767 * From here on, the ref_sorting list should be used to talk
2768 * about the sort order used for the output. The caller
2769 * should not touch the string form anymore.
2771 string_list_clear(options, 0);
2772 return sorting;
2775 void ref_sorting_release(struct ref_sorting *sorting)
2777 while (sorting) {
2778 struct ref_sorting *next = sorting->next;
2779 free(sorting);
2780 sorting = next;
2784 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2786 struct ref_filter *rf = opt->value;
2787 struct object_id oid;
2788 struct commit *merge_commit;
2790 BUG_ON_OPT_NEG(unset);
2792 if (repo_get_oid(the_repository, arg, &oid))
2793 die(_("malformed object name %s"), arg);
2795 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2797 if (!merge_commit)
2798 return error(_("option `%s' must point to a commit"), opt->long_name);
2800 if (starts_with(opt->long_name, "no"))
2801 commit_list_insert(merge_commit, &rf->unreachable_from);
2802 else
2803 commit_list_insert(merge_commit, &rf->reachable_from);
2805 return 0;