post-cocci: adjust comments for recent repo_* migration
[git/debian.git] / ref-filter.c
blobc6cd131e70bb1aff61541585757b89898e46814b
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "refs.h"
5 #include "wildmatch.h"
6 #include "object-store.h"
7 #include "repository.h"
8 #include "commit.h"
9 #include "remote.h"
10 #include "color.h"
11 #include "tag.h"
12 #include "quote.h"
13 #include "ref-filter.h"
14 #include "revision.h"
15 #include "utf8.h"
16 #include "git-compat-util.h"
17 #include "version.h"
18 #include "trailer.h"
19 #include "wt-status.h"
20 #include "commit-slab.h"
21 #include "commit-graph.h"
22 #include "commit-reach.h"
23 #include "worktree.h"
24 #include "hashmap.h"
25 #include "strvec.h"
27 static struct ref_msg {
28 const char *gone;
29 const char *ahead;
30 const char *behind;
31 const char *ahead_behind;
32 } msgs = {
33 /* Untranslated plumbing messages: */
34 "gone",
35 "ahead %d",
36 "behind %d",
37 "ahead %d, behind %d"
40 void setup_ref_filter_porcelain_msg(void)
42 msgs.gone = _("gone");
43 msgs.ahead = _("ahead %d");
44 msgs.behind = _("behind %d");
45 msgs.ahead_behind = _("ahead %d, behind %d");
48 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
49 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
50 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
52 struct align {
53 align_type position;
54 unsigned int width;
57 struct if_then_else {
58 cmp_status cmp_status;
59 const char *str;
60 unsigned int then_atom_seen : 1,
61 else_atom_seen : 1,
62 condition_satisfied : 1;
65 struct refname_atom {
66 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
67 int lstrip, rstrip;
70 static struct ref_trailer_buf {
71 struct string_list filter_list;
72 struct strbuf sepbuf;
73 struct strbuf kvsepbuf;
74 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
76 static struct expand_data {
77 struct object_id oid;
78 enum object_type type;
79 unsigned long size;
80 off_t disk_size;
81 struct object_id delta_base_oid;
82 void *content;
84 struct object_info info;
85 } oi, oi_deref;
87 struct ref_to_worktree_entry {
88 struct hashmap_entry ent;
89 struct worktree *wt; /* key is wt->head_ref */
92 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
93 const struct hashmap_entry *eptr,
94 const struct hashmap_entry *kptr,
95 const void *keydata_aka_refname)
97 const struct ref_to_worktree_entry *e, *k;
99 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
100 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
102 return strcmp(e->wt->head_ref,
103 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
106 static struct ref_to_worktree_map {
107 struct hashmap map;
108 struct worktree **worktrees;
109 } ref_to_worktree_map;
112 * The enum atom_type is used as the index of valid_atom array.
113 * In the atom parsing stage, it will be passed to used_atom.atom_type
114 * as the identifier of the atom type. We can check the type of used_atom
115 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
117 enum atom_type {
118 ATOM_REFNAME,
119 ATOM_OBJECTTYPE,
120 ATOM_OBJECTSIZE,
121 ATOM_OBJECTNAME,
122 ATOM_DELTABASE,
123 ATOM_TREE,
124 ATOM_PARENT,
125 ATOM_NUMPARENT,
126 ATOM_OBJECT,
127 ATOM_TYPE,
128 ATOM_TAG,
129 ATOM_AUTHOR,
130 ATOM_AUTHORNAME,
131 ATOM_AUTHOREMAIL,
132 ATOM_AUTHORDATE,
133 ATOM_COMMITTER,
134 ATOM_COMMITTERNAME,
135 ATOM_COMMITTEREMAIL,
136 ATOM_COMMITTERDATE,
137 ATOM_TAGGER,
138 ATOM_TAGGERNAME,
139 ATOM_TAGGEREMAIL,
140 ATOM_TAGGERDATE,
141 ATOM_CREATOR,
142 ATOM_CREATORDATE,
143 ATOM_SUBJECT,
144 ATOM_BODY,
145 ATOM_TRAILERS,
146 ATOM_CONTENTS,
147 ATOM_RAW,
148 ATOM_UPSTREAM,
149 ATOM_PUSH,
150 ATOM_SYMREF,
151 ATOM_FLAG,
152 ATOM_HEAD,
153 ATOM_COLOR,
154 ATOM_WORKTREEPATH,
155 ATOM_ALIGN,
156 ATOM_END,
157 ATOM_IF,
158 ATOM_THEN,
159 ATOM_ELSE,
160 ATOM_REST,
164 * An atom is a valid field atom listed below, possibly prefixed with
165 * a "*" to denote deref_tag().
167 * We parse given format string and sort specifiers, and make a list
168 * of properties that we need to extract out of objects. ref_array_item
169 * structure will hold an array of values extracted that can be
170 * indexed with the "atom number", which is an index into this
171 * array.
173 static struct used_atom {
174 enum atom_type atom_type;
175 const char *name;
176 cmp_type type;
177 info_source source;
178 union {
179 char color[COLOR_MAXLEN];
180 struct align align;
181 struct {
182 enum {
183 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
184 } option;
185 struct refname_atom refname;
186 unsigned int nobracket : 1, push : 1, push_remote : 1;
187 } remote_ref;
188 struct {
189 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
190 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
191 struct process_trailer_options trailer_opts;
192 unsigned int nlines;
193 } contents;
194 struct {
195 enum { RAW_BARE, RAW_LENGTH } option;
196 } raw_data;
197 struct {
198 cmp_status cmp_status;
199 const char *str;
200 } if_then_else;
201 struct {
202 enum { O_FULL, O_LENGTH, O_SHORT } option;
203 unsigned int length;
204 } oid;
205 struct {
206 enum { O_SIZE, O_SIZE_DISK } option;
207 } objectsize;
208 struct email_option {
209 enum { EO_RAW, EO_TRIM, EO_LOCALPART } option;
210 } email_option;
211 struct refname_atom refname;
212 char *head;
213 } u;
214 } *used_atom;
215 static int used_atom_cnt, need_tagged, need_symref;
218 * Expand string, append it to strbuf *sb, then return error code ret.
219 * Allow to save few lines of code.
221 __attribute__((format (printf, 3, 4)))
222 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
224 va_list ap;
225 va_start(ap, fmt);
226 strbuf_vaddf(sb, fmt, ap);
227 va_end(ap);
228 return ret;
231 static int err_no_arg(struct strbuf *sb, const char *name)
233 size_t namelen = strchrnul(name, ':') - name;
234 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
235 (int)namelen, name);
236 return -1;
239 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
241 size_t namelen = strchrnul(name, ':') - name;
242 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
243 (int)namelen, name, arg);
244 return -1;
247 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
248 const char *color_value, struct strbuf *err)
250 if (!color_value)
251 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
252 if (color_parse(color_value, atom->u.color) < 0)
253 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
254 color_value);
256 * We check this after we've parsed the color, which lets us complain
257 * about syntactically bogus color names even if they won't be used.
259 if (!want_color(format->use_color))
260 color_parse("", atom->u.color);
261 return 0;
264 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
265 const char *name, struct strbuf *err)
267 if (!arg)
268 atom->option = R_NORMAL;
269 else if (!strcmp(arg, "short"))
270 atom->option = R_SHORT;
271 else if (skip_prefix(arg, "lstrip=", &arg) ||
272 skip_prefix(arg, "strip=", &arg)) {
273 atom->option = R_LSTRIP;
274 if (strtol_i(arg, 10, &atom->lstrip))
275 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
276 } else if (skip_prefix(arg, "rstrip=", &arg)) {
277 atom->option = R_RSTRIP;
278 if (strtol_i(arg, 10, &atom->rstrip))
279 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
280 } else
281 return err_bad_arg(err, name, arg);
282 return 0;
285 static int remote_ref_atom_parser(struct ref_format *format, struct used_atom *atom,
286 const char *arg, struct strbuf *err)
288 struct string_list params = STRING_LIST_INIT_DUP;
289 int i;
291 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
292 atom->u.remote_ref.push = 1;
294 if (!arg) {
295 atom->u.remote_ref.option = RR_REF;
296 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
297 arg, atom->name, err);
300 atom->u.remote_ref.nobracket = 0;
301 string_list_split(&params, arg, ',', -1);
303 for (i = 0; i < params.nr; i++) {
304 const char *s = params.items[i].string;
306 if (!strcmp(s, "track"))
307 atom->u.remote_ref.option = RR_TRACK;
308 else if (!strcmp(s, "trackshort"))
309 atom->u.remote_ref.option = RR_TRACKSHORT;
310 else if (!strcmp(s, "nobracket"))
311 atom->u.remote_ref.nobracket = 1;
312 else if (!strcmp(s, "remotename")) {
313 atom->u.remote_ref.option = RR_REMOTE_NAME;
314 atom->u.remote_ref.push_remote = 1;
315 } else if (!strcmp(s, "remoteref")) {
316 atom->u.remote_ref.option = RR_REMOTE_REF;
317 atom->u.remote_ref.push_remote = 1;
318 } else {
319 atom->u.remote_ref.option = RR_REF;
320 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
321 arg, atom->name, err)) {
322 string_list_clear(&params, 0);
323 return -1;
328 string_list_clear(&params, 0);
329 return 0;
332 static int objecttype_atom_parser(struct ref_format *format, struct used_atom *atom,
333 const char *arg, struct strbuf *err)
335 if (arg)
336 return err_no_arg(err, "objecttype");
337 if (*atom->name == '*')
338 oi_deref.info.typep = &oi_deref.type;
339 else
340 oi.info.typep = &oi.type;
341 return 0;
344 static int objectsize_atom_parser(struct ref_format *format, struct used_atom *atom,
345 const char *arg, struct strbuf *err)
347 if (!arg) {
348 atom->u.objectsize.option = O_SIZE;
349 if (*atom->name == '*')
350 oi_deref.info.sizep = &oi_deref.size;
351 else
352 oi.info.sizep = &oi.size;
353 } else if (!strcmp(arg, "disk")) {
354 atom->u.objectsize.option = O_SIZE_DISK;
355 if (*atom->name == '*')
356 oi_deref.info.disk_sizep = &oi_deref.disk_size;
357 else
358 oi.info.disk_sizep = &oi.disk_size;
359 } else
360 return err_bad_arg(err, "objectsize", arg);
361 return 0;
364 static int deltabase_atom_parser(struct ref_format *format, struct used_atom *atom,
365 const char *arg, struct strbuf *err)
367 if (arg)
368 return err_no_arg(err, "deltabase");
369 if (*atom->name == '*')
370 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
371 else
372 oi.info.delta_base_oid = &oi.delta_base_oid;
373 return 0;
376 static int body_atom_parser(struct ref_format *format, struct used_atom *atom,
377 const char *arg, struct strbuf *err)
379 if (arg)
380 return err_no_arg(err, "body");
381 atom->u.contents.option = C_BODY_DEP;
382 return 0;
385 static int subject_atom_parser(struct ref_format *format, struct used_atom *atom,
386 const char *arg, struct strbuf *err)
388 if (!arg)
389 atom->u.contents.option = C_SUB;
390 else if (!strcmp(arg, "sanitize"))
391 atom->u.contents.option = C_SUB_SANITIZE;
392 else
393 return err_bad_arg(err, "subject", arg);
394 return 0;
397 static int trailers_atom_parser(struct ref_format *format, struct used_atom *atom,
398 const char *arg, struct strbuf *err)
400 atom->u.contents.trailer_opts.no_divider = 1;
402 if (arg) {
403 const char *argbuf = xstrfmt("%s)", arg);
404 char *invalid_arg = NULL;
406 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
407 &ref_trailer_buf.filter_list,
408 &ref_trailer_buf.sepbuf,
409 &ref_trailer_buf.kvsepbuf,
410 &argbuf, &invalid_arg)) {
411 if (!invalid_arg)
412 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
413 else
414 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
415 free((char *)invalid_arg);
416 return -1;
419 atom->u.contents.option = C_TRAILERS;
420 return 0;
423 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
424 const char *arg, struct strbuf *err)
426 if (!arg)
427 atom->u.contents.option = C_BARE;
428 else if (!strcmp(arg, "body"))
429 atom->u.contents.option = C_BODY;
430 else if (!strcmp(arg, "size"))
431 atom->u.contents.option = C_LENGTH;
432 else if (!strcmp(arg, "signature"))
433 atom->u.contents.option = C_SIG;
434 else if (!strcmp(arg, "subject"))
435 atom->u.contents.option = C_SUB;
436 else if (!strcmp(arg, "trailers")) {
437 if (trailers_atom_parser(format, atom, NULL, err))
438 return -1;
439 } else if (skip_prefix(arg, "trailers:", &arg)) {
440 if (trailers_atom_parser(format, atom, arg, err))
441 return -1;
442 } else if (skip_prefix(arg, "lines=", &arg)) {
443 atom->u.contents.option = C_LINES;
444 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
445 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
446 } else
447 return err_bad_arg(err, "contents", arg);
448 return 0;
451 static int raw_atom_parser(struct ref_format *format, struct used_atom *atom,
452 const char *arg, struct strbuf *err)
454 if (!arg)
455 atom->u.raw_data.option = RAW_BARE;
456 else if (!strcmp(arg, "size"))
457 atom->u.raw_data.option = RAW_LENGTH;
458 else
459 return err_bad_arg(err, "raw", arg);
460 return 0;
463 static int oid_atom_parser(struct ref_format *format, struct used_atom *atom,
464 const char *arg, struct strbuf *err)
466 if (!arg)
467 atom->u.oid.option = O_FULL;
468 else if (!strcmp(arg, "short"))
469 atom->u.oid.option = O_SHORT;
470 else if (skip_prefix(arg, "short=", &arg)) {
471 atom->u.oid.option = O_LENGTH;
472 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
473 atom->u.oid.length == 0)
474 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
475 if (atom->u.oid.length < MINIMUM_ABBREV)
476 atom->u.oid.length = MINIMUM_ABBREV;
477 } else
478 return err_bad_arg(err, atom->name, arg);
479 return 0;
482 static int person_email_atom_parser(struct ref_format *format, struct used_atom *atom,
483 const char *arg, struct strbuf *err)
485 if (!arg)
486 atom->u.email_option.option = EO_RAW;
487 else if (!strcmp(arg, "trim"))
488 atom->u.email_option.option = EO_TRIM;
489 else if (!strcmp(arg, "localpart"))
490 atom->u.email_option.option = EO_LOCALPART;
491 else
492 return err_bad_arg(err, atom->name, arg);
493 return 0;
496 static int refname_atom_parser(struct ref_format *format, struct used_atom *atom,
497 const char *arg, struct strbuf *err)
499 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
502 static align_type parse_align_position(const char *s)
504 if (!strcmp(s, "right"))
505 return ALIGN_RIGHT;
506 else if (!strcmp(s, "middle"))
507 return ALIGN_MIDDLE;
508 else if (!strcmp(s, "left"))
509 return ALIGN_LEFT;
510 return -1;
513 static int align_atom_parser(struct ref_format *format, struct used_atom *atom,
514 const char *arg, struct strbuf *err)
516 struct align *align = &atom->u.align;
517 struct string_list params = STRING_LIST_INIT_DUP;
518 int i;
519 unsigned int width = ~0U;
521 if (!arg)
522 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
524 align->position = ALIGN_LEFT;
526 string_list_split(&params, arg, ',', -1);
527 for (i = 0; i < params.nr; i++) {
528 const char *s = params.items[i].string;
529 int position;
531 if (skip_prefix(s, "position=", &s)) {
532 position = parse_align_position(s);
533 if (position < 0) {
534 strbuf_addf(err, _("unrecognized position:%s"), s);
535 string_list_clear(&params, 0);
536 return -1;
538 align->position = position;
539 } else if (skip_prefix(s, "width=", &s)) {
540 if (strtoul_ui(s, 10, &width)) {
541 strbuf_addf(err, _("unrecognized width:%s"), s);
542 string_list_clear(&params, 0);
543 return -1;
545 } else if (!strtoul_ui(s, 10, &width))
547 else if ((position = parse_align_position(s)) >= 0)
548 align->position = position;
549 else {
550 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
551 string_list_clear(&params, 0);
552 return -1;
556 if (width == ~0U) {
557 string_list_clear(&params, 0);
558 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
560 align->width = width;
561 string_list_clear(&params, 0);
562 return 0;
565 static int if_atom_parser(struct ref_format *format, struct used_atom *atom,
566 const char *arg, struct strbuf *err)
568 if (!arg) {
569 atom->u.if_then_else.cmp_status = COMPARE_NONE;
570 return 0;
571 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
572 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
573 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
574 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
575 } else
576 return err_bad_arg(err, "if", arg);
577 return 0;
580 static int rest_atom_parser(struct ref_format *format, struct used_atom *atom,
581 const char *arg, struct strbuf *err)
583 if (arg)
584 return err_no_arg(err, "rest");
585 format->use_rest = 1;
586 return 0;
589 static int head_atom_parser(struct ref_format *format, struct used_atom *atom,
590 const char *arg, struct strbuf *err)
592 if (arg)
593 return err_no_arg(err, "HEAD");
594 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
595 return 0;
598 static struct {
599 const char *name;
600 info_source source;
601 cmp_type cmp_type;
602 int (*parser)(struct ref_format *format, struct used_atom *atom,
603 const char *arg, struct strbuf *err);
604 } valid_atom[] = {
605 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
606 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
607 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
608 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
609 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
610 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
611 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
612 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
613 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
614 [ATOM_TYPE] = { "type", SOURCE_OBJ },
615 [ATOM_TAG] = { "tag", SOURCE_OBJ },
616 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
617 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
618 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
619 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
620 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
621 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
622 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
623 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
624 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
625 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
626 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
627 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
628 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
629 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
630 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
631 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
632 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
633 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
634 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
635 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
636 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
637 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
638 [ATOM_FLAG] = { "flag", SOURCE_NONE },
639 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
640 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
641 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
642 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
643 [ATOM_END] = { "end", SOURCE_NONE },
644 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
645 [ATOM_THEN] = { "then", SOURCE_NONE },
646 [ATOM_ELSE] = { "else", SOURCE_NONE },
647 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
649 * Please update $__git_ref_fieldlist in git-completion.bash
650 * when you add new atoms
654 #define REF_FORMATTING_STATE_INIT { 0 }
656 struct ref_formatting_stack {
657 struct ref_formatting_stack *prev;
658 struct strbuf output;
659 void (*at_end)(struct ref_formatting_stack **stack);
660 void *at_end_data;
663 struct ref_formatting_state {
664 int quote_style;
665 struct ref_formatting_stack *stack;
668 struct atom_value {
669 const char *s;
670 ssize_t s_size;
671 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
672 struct strbuf *err);
673 uintmax_t value; /* used for sorting when not FIELD_STR */
674 struct used_atom *atom;
677 #define ATOM_SIZE_UNSPECIFIED (-1)
679 #define ATOM_VALUE_INIT { \
680 .s_size = ATOM_SIZE_UNSPECIFIED \
684 * Used to parse format string and sort specifiers
686 static int parse_ref_filter_atom(struct ref_format *format,
687 const char *atom, const char *ep,
688 struct strbuf *err)
690 const char *sp;
691 const char *arg;
692 int i, at, atom_len;
694 sp = atom;
695 if (*sp == '*' && sp < ep)
696 sp++; /* deref */
697 if (ep <= sp)
698 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
699 (int)(ep-atom), atom);
702 * If the atom name has a colon, strip it and everything after
703 * it off - it specifies the format for this entry, and
704 * shouldn't be used for checking against the valid_atom
705 * table.
707 arg = memchr(sp, ':', ep - sp);
708 atom_len = (arg ? arg : ep) - sp;
710 /* Do we have the atom already used elsewhere? */
711 for (i = 0; i < used_atom_cnt; i++) {
712 int len = strlen(used_atom[i].name);
713 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
714 return i;
717 /* Is the atom a valid one? */
718 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
719 int len = strlen(valid_atom[i].name);
720 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
721 break;
724 if (ARRAY_SIZE(valid_atom) <= i)
725 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
726 (int)(ep-atom), atom);
727 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
728 return strbuf_addf_ret(err, -1,
729 _("not a git repository, but the field '%.*s' requires access to object data"),
730 (int)(ep-atom), atom);
732 /* Add it in, including the deref prefix */
733 at = used_atom_cnt;
734 used_atom_cnt++;
735 REALLOC_ARRAY(used_atom, used_atom_cnt);
736 used_atom[at].atom_type = i;
737 used_atom[at].name = xmemdupz(atom, ep - atom);
738 used_atom[at].type = valid_atom[i].cmp_type;
739 used_atom[at].source = valid_atom[i].source;
740 if (used_atom[at].source == SOURCE_OBJ) {
741 if (*atom == '*')
742 oi_deref.info.contentp = &oi_deref.content;
743 else
744 oi.info.contentp = &oi.content;
746 if (arg) {
747 arg = used_atom[at].name + (arg - atom) + 1;
748 if (!*arg) {
750 * Treat empty sub-arguments list as NULL (i.e.,
751 * "%(atom:)" is equivalent to "%(atom)").
753 arg = NULL;
756 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
757 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
758 return -1;
759 if (*atom == '*')
760 need_tagged = 1;
761 if (i == ATOM_SYMREF)
762 need_symref = 1;
763 return at;
766 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
768 switch (quote_style) {
769 case QUOTE_NONE:
770 if (len < 0)
771 strbuf_addstr(s, str);
772 else
773 strbuf_add(s, str, len);
774 break;
775 case QUOTE_SHELL:
776 sq_quote_buf(s, str);
777 break;
778 case QUOTE_PERL:
779 if (len < 0)
780 perl_quote_buf(s, str);
781 else
782 perl_quote_buf_with_len(s, str, len);
783 break;
784 case QUOTE_PYTHON:
785 python_quote_buf(s, str);
786 break;
787 case QUOTE_TCL:
788 tcl_quote_buf(s, str);
789 break;
793 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
794 struct strbuf *unused_err)
797 * Quote formatting is only done when the stack has a single
798 * element. Otherwise quote formatting is done on the
799 * element's entire output strbuf when the %(end) atom is
800 * encountered.
802 if (!state->stack->prev)
803 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
804 else if (v->s_size < 0)
805 strbuf_addstr(&state->stack->output, v->s);
806 else
807 strbuf_add(&state->stack->output, v->s, v->s_size);
808 return 0;
811 static void push_stack_element(struct ref_formatting_stack **stack)
813 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
815 strbuf_init(&s->output, 0);
816 s->prev = *stack;
817 *stack = s;
820 static void pop_stack_element(struct ref_formatting_stack **stack)
822 struct ref_formatting_stack *current = *stack;
823 struct ref_formatting_stack *prev = current->prev;
825 if (prev)
826 strbuf_addbuf(&prev->output, &current->output);
827 strbuf_release(&current->output);
828 free(current);
829 *stack = prev;
832 static void end_align_handler(struct ref_formatting_stack **stack)
834 struct ref_formatting_stack *cur = *stack;
835 struct align *align = (struct align *)cur->at_end_data;
836 struct strbuf s = STRBUF_INIT;
838 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
839 strbuf_swap(&cur->output, &s);
840 strbuf_release(&s);
843 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
844 struct strbuf *unused_err)
846 struct ref_formatting_stack *new_stack;
848 push_stack_element(&state->stack);
849 new_stack = state->stack;
850 new_stack->at_end = end_align_handler;
851 new_stack->at_end_data = &atomv->atom->u.align;
852 return 0;
855 static void if_then_else_handler(struct ref_formatting_stack **stack)
857 struct ref_formatting_stack *cur = *stack;
858 struct ref_formatting_stack *prev = cur->prev;
859 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
861 if (!if_then_else->then_atom_seen)
862 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
864 if (if_then_else->else_atom_seen) {
866 * There is an %(else) atom: we need to drop one state from the
867 * stack, either the %(else) branch if the condition is satisfied, or
868 * the %(then) branch if it isn't.
870 if (if_then_else->condition_satisfied) {
871 strbuf_reset(&cur->output);
872 pop_stack_element(&cur);
873 } else {
874 strbuf_swap(&cur->output, &prev->output);
875 strbuf_reset(&cur->output);
876 pop_stack_element(&cur);
878 } else if (!if_then_else->condition_satisfied) {
880 * No %(else) atom: just drop the %(then) branch if the
881 * condition is not satisfied.
883 strbuf_reset(&cur->output);
886 *stack = cur;
887 free(if_then_else);
890 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
891 struct strbuf *unused_err)
893 struct ref_formatting_stack *new_stack;
894 struct if_then_else *if_then_else = xcalloc(1,
895 sizeof(struct if_then_else));
897 if_then_else->str = atomv->atom->u.if_then_else.str;
898 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
900 push_stack_element(&state->stack);
901 new_stack = state->stack;
902 new_stack->at_end = if_then_else_handler;
903 new_stack->at_end_data = if_then_else;
904 return 0;
907 static int is_empty(struct strbuf *buf)
909 const char *cur = buf->buf;
910 const char *end = buf->buf + buf->len;
912 while (cur != end && (isspace(*cur)))
913 cur++;
915 return cur == end;
918 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
919 struct strbuf *err)
921 struct ref_formatting_stack *cur = state->stack;
922 struct if_then_else *if_then_else = NULL;
923 size_t str_len = 0;
925 if (cur->at_end == if_then_else_handler)
926 if_then_else = (struct if_then_else *)cur->at_end_data;
927 if (!if_then_else)
928 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
929 if (if_then_else->then_atom_seen)
930 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
931 if (if_then_else->else_atom_seen)
932 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
933 if_then_else->then_atom_seen = 1;
934 if (if_then_else->str)
935 str_len = strlen(if_then_else->str);
937 * If the 'equals' or 'notequals' attribute is used then
938 * perform the required comparison. If not, only non-empty
939 * strings satisfy the 'if' condition.
941 if (if_then_else->cmp_status == COMPARE_EQUAL) {
942 if (str_len == cur->output.len &&
943 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
944 if_then_else->condition_satisfied = 1;
945 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
946 if (str_len != cur->output.len ||
947 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
948 if_then_else->condition_satisfied = 1;
949 } else if (cur->output.len && !is_empty(&cur->output))
950 if_then_else->condition_satisfied = 1;
951 strbuf_reset(&cur->output);
952 return 0;
955 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
956 struct strbuf *err)
958 struct ref_formatting_stack *prev = state->stack;
959 struct if_then_else *if_then_else = NULL;
961 if (prev->at_end == if_then_else_handler)
962 if_then_else = (struct if_then_else *)prev->at_end_data;
963 if (!if_then_else)
964 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
965 if (!if_then_else->then_atom_seen)
966 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
967 if (if_then_else->else_atom_seen)
968 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
969 if_then_else->else_atom_seen = 1;
970 push_stack_element(&state->stack);
971 state->stack->at_end_data = prev->at_end_data;
972 state->stack->at_end = prev->at_end;
973 return 0;
976 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
977 struct strbuf *err)
979 struct ref_formatting_stack *current = state->stack;
980 struct strbuf s = STRBUF_INIT;
982 if (!current->at_end)
983 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
984 current->at_end(&state->stack);
986 /* Stack may have been popped within at_end(), hence reset the current pointer */
987 current = state->stack;
990 * Perform quote formatting when the stack element is that of
991 * a supporting atom. If nested then perform quote formatting
992 * only on the topmost supporting atom.
994 if (!current->prev->prev) {
995 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
996 strbuf_swap(&current->output, &s);
998 strbuf_release(&s);
999 pop_stack_element(&state->stack);
1000 return 0;
1004 * In a format string, find the next occurrence of %(atom).
1006 static const char *find_next(const char *cp)
1008 while (*cp) {
1009 if (*cp == '%') {
1011 * %( is the start of an atom;
1012 * %% is a quoted per-cent.
1014 if (cp[1] == '(')
1015 return cp;
1016 else if (cp[1] == '%')
1017 cp++; /* skip over two % */
1018 /* otherwise this is a singleton, literal % */
1020 cp++;
1022 return NULL;
1025 static int reject_atom(enum atom_type atom_type)
1027 return atom_type == ATOM_REST;
1031 * Make sure the format string is well formed, and parse out
1032 * the used atoms.
1034 int verify_ref_format(struct ref_format *format)
1036 const char *cp, *sp;
1038 format->need_color_reset_at_eol = 0;
1039 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1040 struct strbuf err = STRBUF_INIT;
1041 const char *color, *ep = strchr(sp, ')');
1042 int at;
1044 if (!ep)
1045 return error(_("malformed format string %s"), sp);
1046 /* sp points at "%(" and ep points at the closing ")" */
1047 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1048 if (at < 0)
1049 die("%s", err.buf);
1050 if (reject_atom(used_atom[at].atom_type))
1051 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1053 if ((format->quote_style == QUOTE_PYTHON ||
1054 format->quote_style == QUOTE_SHELL ||
1055 format->quote_style == QUOTE_TCL) &&
1056 used_atom[at].atom_type == ATOM_RAW &&
1057 used_atom[at].u.raw_data.option == RAW_BARE)
1058 die(_("--format=%.*s cannot be used with "
1059 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1060 cp = ep + 1;
1062 if (skip_prefix(used_atom[at].name, "color:", &color))
1063 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1064 strbuf_release(&err);
1066 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1067 format->need_color_reset_at_eol = 0;
1068 return 0;
1071 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1072 struct used_atom *atom)
1074 switch (atom->u.oid.option) {
1075 case O_FULL:
1076 return oid_to_hex(oid);
1077 case O_LENGTH:
1078 return repo_find_unique_abbrev(the_repository, oid,
1079 atom->u.oid.length);
1080 case O_SHORT:
1081 return repo_find_unique_abbrev(the_repository, oid,
1082 DEFAULT_ABBREV);
1083 default:
1084 BUG("unknown %%(%s) option", field);
1088 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1089 struct atom_value *v, struct used_atom *atom)
1091 if (starts_with(name, field)) {
1092 v->s = xstrdup(do_grab_oid(field, oid, atom));
1093 return 1;
1095 return 0;
1098 /* See grab_values */
1099 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1101 int i;
1103 for (i = 0; i < used_atom_cnt; i++) {
1104 const char *name = used_atom[i].name;
1105 enum atom_type atom_type = used_atom[i].atom_type;
1106 struct atom_value *v = &val[i];
1107 if (!!deref != (*name == '*'))
1108 continue;
1109 if (deref)
1110 name++;
1111 if (atom_type == ATOM_OBJECTTYPE)
1112 v->s = xstrdup(type_name(oi->type));
1113 else if (atom_type == ATOM_OBJECTSIZE) {
1114 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1115 v->value = oi->disk_size;
1116 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1117 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1118 v->value = oi->size;
1119 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1121 } else if (atom_type == ATOM_DELTABASE)
1122 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1123 else if (atom_type == ATOM_OBJECTNAME && deref)
1124 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1128 /* See grab_values */
1129 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1131 int i;
1132 struct tag *tag = (struct tag *) obj;
1134 for (i = 0; i < used_atom_cnt; i++) {
1135 const char *name = used_atom[i].name;
1136 enum atom_type atom_type = used_atom[i].atom_type;
1137 struct atom_value *v = &val[i];
1138 if (!!deref != (*name == '*'))
1139 continue;
1140 if (deref)
1141 name++;
1142 if (atom_type == ATOM_TAG)
1143 v->s = xstrdup(tag->tag);
1144 else if (atom_type == ATOM_TYPE && tag->tagged)
1145 v->s = xstrdup(type_name(tag->tagged->type));
1146 else if (atom_type == ATOM_OBJECT && tag->tagged)
1147 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1151 /* See grab_values */
1152 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1154 int i;
1155 struct commit *commit = (struct commit *) obj;
1157 for (i = 0; i < used_atom_cnt; i++) {
1158 const char *name = used_atom[i].name;
1159 enum atom_type atom_type = used_atom[i].atom_type;
1160 struct atom_value *v = &val[i];
1161 if (!!deref != (*name == '*'))
1162 continue;
1163 if (deref)
1164 name++;
1165 if (atom_type == ATOM_TREE &&
1166 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1167 continue;
1168 if (atom_type == ATOM_NUMPARENT) {
1169 v->value = commit_list_count(commit->parents);
1170 v->s = xstrfmt("%lu", (unsigned long)v->value);
1172 else if (atom_type == ATOM_PARENT) {
1173 struct commit_list *parents;
1174 struct strbuf s = STRBUF_INIT;
1175 for (parents = commit->parents; parents; parents = parents->next) {
1176 struct object_id *oid = &parents->item->object.oid;
1177 if (parents != commit->parents)
1178 strbuf_addch(&s, ' ');
1179 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1181 v->s = strbuf_detach(&s, NULL);
1186 static const char *find_wholine(const char *who, int wholen, const char *buf)
1188 const char *eol;
1189 while (*buf) {
1190 if (!strncmp(buf, who, wholen) &&
1191 buf[wholen] == ' ')
1192 return buf + wholen + 1;
1193 eol = strchr(buf, '\n');
1194 if (!eol)
1195 return "";
1196 eol++;
1197 if (*eol == '\n')
1198 return ""; /* end of header */
1199 buf = eol;
1201 return "";
1204 static const char *copy_line(const char *buf)
1206 const char *eol = strchrnul(buf, '\n');
1207 return xmemdupz(buf, eol - buf);
1210 static const char *copy_name(const char *buf)
1212 const char *cp;
1213 for (cp = buf; *cp && *cp != '\n'; cp++) {
1214 if (starts_with(cp, " <"))
1215 return xmemdupz(buf, cp - buf);
1217 return xstrdup("");
1220 static const char *copy_email(const char *buf, struct used_atom *atom)
1222 const char *email = strchr(buf, '<');
1223 const char *eoemail;
1224 if (!email)
1225 return xstrdup("");
1226 switch (atom->u.email_option.option) {
1227 case EO_RAW:
1228 eoemail = strchr(email, '>');
1229 if (eoemail)
1230 eoemail++;
1231 break;
1232 case EO_TRIM:
1233 email++;
1234 eoemail = strchr(email, '>');
1235 break;
1236 case EO_LOCALPART:
1237 email++;
1238 eoemail = strchr(email, '@');
1239 if (!eoemail)
1240 eoemail = strchr(email, '>');
1241 break;
1242 default:
1243 BUG("unknown email option");
1246 if (!eoemail)
1247 return xstrdup("");
1248 return xmemdupz(email, eoemail - email);
1251 static char *copy_subject(const char *buf, unsigned long len)
1253 struct strbuf sb = STRBUF_INIT;
1254 int i;
1256 for (i = 0; i < len; i++) {
1257 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1258 continue; /* ignore CR in CRLF */
1260 if (buf[i] == '\n')
1261 strbuf_addch(&sb, ' ');
1262 else
1263 strbuf_addch(&sb, buf[i]);
1265 return strbuf_detach(&sb, NULL);
1268 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1270 const char *eoemail = strstr(buf, "> ");
1271 char *zone;
1272 timestamp_t timestamp;
1273 long tz;
1274 struct date_mode date_mode = DATE_MODE_INIT;
1275 const char *formatp;
1278 * We got here because atomname ends in "date" or "date<something>";
1279 * it's not possible that <something> is not ":<format>" because
1280 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1281 * ":" means no format is specified, and use the default.
1283 formatp = strchr(atomname, ':');
1284 if (formatp) {
1285 formatp++;
1286 parse_date_format(formatp, &date_mode);
1289 if (!eoemail)
1290 goto bad;
1291 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1292 if (timestamp == TIME_MAX)
1293 goto bad;
1294 tz = strtol(zone, NULL, 10);
1295 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1296 goto bad;
1297 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1298 v->value = timestamp;
1299 date_mode_release(&date_mode);
1300 return;
1301 bad:
1302 v->s = xstrdup("");
1303 v->value = 0;
1306 /* See grab_values */
1307 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1309 int i;
1310 int wholen = strlen(who);
1311 const char *wholine = NULL;
1313 for (i = 0; i < used_atom_cnt; i++) {
1314 const char *name = used_atom[i].name;
1315 struct atom_value *v = &val[i];
1316 if (!!deref != (*name == '*'))
1317 continue;
1318 if (deref)
1319 name++;
1320 if (strncmp(who, name, wholen))
1321 continue;
1322 if (name[wholen] != 0 &&
1323 strcmp(name + wholen, "name") &&
1324 !starts_with(name + wholen, "email") &&
1325 !starts_with(name + wholen, "date"))
1326 continue;
1327 if (!wholine)
1328 wholine = find_wholine(who, wholen, buf);
1329 if (!wholine)
1330 return; /* no point looking for it */
1331 if (name[wholen] == 0)
1332 v->s = copy_line(wholine);
1333 else if (!strcmp(name + wholen, "name"))
1334 v->s = copy_name(wholine);
1335 else if (starts_with(name + wholen, "email"))
1336 v->s = copy_email(wholine, &used_atom[i]);
1337 else if (starts_with(name + wholen, "date"))
1338 grab_date(wholine, v, name);
1342 * For a tag or a commit object, if "creator" or "creatordate" is
1343 * requested, do something special.
1345 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1346 return; /* "author" for commit object is not wanted */
1347 if (!wholine)
1348 wholine = find_wholine(who, wholen, buf);
1349 if (!wholine)
1350 return;
1351 for (i = 0; i < used_atom_cnt; i++) {
1352 const char *name = used_atom[i].name;
1353 enum atom_type atom_type = used_atom[i].atom_type;
1354 struct atom_value *v = &val[i];
1355 if (!!deref != (*name == '*'))
1356 continue;
1357 if (deref)
1358 name++;
1360 if (atom_type == ATOM_CREATORDATE)
1361 grab_date(wholine, v, name);
1362 else if (atom_type == ATOM_CREATOR)
1363 v->s = copy_line(wholine);
1367 static void find_subpos(const char *buf,
1368 const char **sub, size_t *sublen,
1369 const char **body, size_t *bodylen,
1370 size_t *nonsiglen,
1371 const char **sig, size_t *siglen)
1373 struct strbuf payload = STRBUF_INIT;
1374 struct strbuf signature = STRBUF_INIT;
1375 const char *eol;
1376 const char *end = buf + strlen(buf);
1377 const char *sigstart;
1379 /* parse signature first; we might not even have a subject line */
1380 parse_signature(buf, end - buf, &payload, &signature);
1381 strbuf_release(&payload);
1383 /* skip past header until we hit empty line */
1384 while (*buf && *buf != '\n') {
1385 eol = strchrnul(buf, '\n');
1386 if (*eol)
1387 eol++;
1388 buf = eol;
1390 /* skip any empty lines */
1391 while (*buf == '\n')
1392 buf++;
1393 *sig = strbuf_detach(&signature, siglen);
1394 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1396 /* subject is first non-empty line */
1397 *sub = buf;
1398 /* subject goes to first empty line before signature begins */
1399 if ((eol = strstr(*sub, "\n\n")) ||
1400 (eol = strstr(*sub, "\r\n\r\n"))) {
1401 eol = eol < sigstart ? eol : sigstart;
1402 } else {
1403 /* treat whole message as subject */
1404 eol = sigstart;
1406 buf = eol;
1407 *sublen = buf - *sub;
1408 /* drop trailing newline, if present */
1409 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1410 (*sub)[*sublen - 1] == '\r'))
1411 *sublen -= 1;
1413 /* skip any empty lines */
1414 while (*buf == '\n' || *buf == '\r')
1415 buf++;
1416 *body = buf;
1417 *bodylen = strlen(buf);
1418 *nonsiglen = sigstart - buf;
1422 * If 'lines' is greater than 0, append that many lines from the given
1423 * 'buf' of length 'size' to the given strbuf.
1425 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1427 int i;
1428 const char *sp, *eol;
1429 size_t len;
1431 sp = buf;
1433 for (i = 0; i < lines && sp < buf + size; i++) {
1434 if (i)
1435 strbuf_addstr(out, "\n ");
1436 eol = memchr(sp, '\n', size - (sp - buf));
1437 len = eol ? eol - sp : size - (sp - buf);
1438 strbuf_add(out, sp, len);
1439 if (!eol)
1440 break;
1441 sp = eol + 1;
1445 /* See grab_values */
1446 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1448 int i;
1449 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1450 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1451 void *buf = data->content;
1453 for (i = 0; i < used_atom_cnt; i++) {
1454 struct used_atom *atom = &used_atom[i];
1455 const char *name = atom->name;
1456 struct atom_value *v = &val[i];
1457 enum atom_type atom_type = atom->atom_type;
1459 if (!!deref != (*name == '*'))
1460 continue;
1461 if (deref)
1462 name++;
1464 if (atom_type == ATOM_RAW) {
1465 unsigned long buf_size = data->size;
1467 if (atom->u.raw_data.option == RAW_BARE) {
1468 v->s = xmemdupz(buf, buf_size);
1469 v->s_size = buf_size;
1470 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1471 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1473 continue;
1476 if ((data->type != OBJ_TAG &&
1477 data->type != OBJ_COMMIT) ||
1478 (strcmp(name, "body") &&
1479 !starts_with(name, "subject") &&
1480 !starts_with(name, "trailers") &&
1481 !starts_with(name, "contents")))
1482 continue;
1483 if (!subpos)
1484 find_subpos(buf,
1485 &subpos, &sublen,
1486 &bodypos, &bodylen, &nonsiglen,
1487 &sigpos, &siglen);
1489 if (atom->u.contents.option == C_SUB)
1490 v->s = copy_subject(subpos, sublen);
1491 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1492 struct strbuf sb = STRBUF_INIT;
1493 format_sanitized_subject(&sb, subpos, sublen);
1494 v->s = strbuf_detach(&sb, NULL);
1495 } else if (atom->u.contents.option == C_BODY_DEP)
1496 v->s = xmemdupz(bodypos, bodylen);
1497 else if (atom->u.contents.option == C_LENGTH)
1498 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1499 else if (atom->u.contents.option == C_BODY)
1500 v->s = xmemdupz(bodypos, nonsiglen);
1501 else if (atom->u.contents.option == C_SIG)
1502 v->s = xmemdupz(sigpos, siglen);
1503 else if (atom->u.contents.option == C_LINES) {
1504 struct strbuf s = STRBUF_INIT;
1505 const char *contents_end = bodypos + nonsiglen;
1507 /* Size is the length of the message after removing the signature */
1508 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1509 v->s = strbuf_detach(&s, NULL);
1510 } else if (atom->u.contents.option == C_TRAILERS) {
1511 struct strbuf s = STRBUF_INIT;
1513 /* Format the trailer info according to the trailer_opts given */
1514 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1516 v->s = strbuf_detach(&s, NULL);
1517 } else if (atom->u.contents.option == C_BARE)
1518 v->s = xstrdup(subpos);
1521 free((void *)sigpos);
1525 * We want to have empty print-string for field requests
1526 * that do not apply (e.g. "authordate" for a tag object)
1528 static void fill_missing_values(struct atom_value *val)
1530 int i;
1531 for (i = 0; i < used_atom_cnt; i++) {
1532 struct atom_value *v = &val[i];
1533 if (!v->s)
1534 v->s = xstrdup("");
1539 * val is a list of atom_value to hold returned values. Extract
1540 * the values for atoms in used_atom array out of (obj, buf, sz).
1541 * when deref is false, (obj, buf, sz) is the object that is
1542 * pointed at by the ref itself; otherwise it is the object the
1543 * ref (which is a tag) refers to.
1545 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1547 void *buf = data->content;
1549 switch (obj->type) {
1550 case OBJ_TAG:
1551 grab_tag_values(val, deref, obj);
1552 grab_sub_body_contents(val, deref, data);
1553 grab_person("tagger", val, deref, buf);
1554 break;
1555 case OBJ_COMMIT:
1556 grab_commit_values(val, deref, obj);
1557 grab_sub_body_contents(val, deref, data);
1558 grab_person("author", val, deref, buf);
1559 grab_person("committer", val, deref, buf);
1560 break;
1561 case OBJ_TREE:
1562 /* grab_tree_values(val, deref, obj, buf, sz); */
1563 grab_sub_body_contents(val, deref, data);
1564 break;
1565 case OBJ_BLOB:
1566 /* grab_blob_values(val, deref, obj, buf, sz); */
1567 grab_sub_body_contents(val, deref, data);
1568 break;
1569 default:
1570 die("Eh? Object of type %d?", obj->type);
1574 static inline char *copy_advance(char *dst, const char *src)
1576 while (*src)
1577 *dst++ = *src++;
1578 return dst;
1581 static const char *lstrip_ref_components(const char *refname, int len)
1583 long remaining = len;
1584 const char *start = xstrdup(refname);
1585 const char *to_free = start;
1587 if (len < 0) {
1588 int i;
1589 const char *p = refname;
1591 /* Find total no of '/' separated path-components */
1592 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1595 * The number of components we need to strip is now
1596 * the total minus the components to be left (Plus one
1597 * because we count the number of '/', but the number
1598 * of components is one more than the no of '/').
1600 remaining = i + len + 1;
1603 while (remaining > 0) {
1604 switch (*start++) {
1605 case '\0':
1606 free((char *)to_free);
1607 return xstrdup("");
1608 case '/':
1609 remaining--;
1610 break;
1614 start = xstrdup(start);
1615 free((char *)to_free);
1616 return start;
1619 static const char *rstrip_ref_components(const char *refname, int len)
1621 long remaining = len;
1622 const char *start = xstrdup(refname);
1623 const char *to_free = start;
1625 if (len < 0) {
1626 int i;
1627 const char *p = refname;
1629 /* Find total no of '/' separated path-components */
1630 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1633 * The number of components we need to strip is now
1634 * the total minus the components to be left (Plus one
1635 * because we count the number of '/', but the number
1636 * of components is one more than the no of '/').
1638 remaining = i + len + 1;
1641 while (remaining-- > 0) {
1642 char *p = strrchr(start, '/');
1643 if (!p) {
1644 free((char *)to_free);
1645 return xstrdup("");
1646 } else
1647 p[0] = '\0';
1649 return start;
1652 static const char *show_ref(struct refname_atom *atom, const char *refname)
1654 if (atom->option == R_SHORT)
1655 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1656 else if (atom->option == R_LSTRIP)
1657 return lstrip_ref_components(refname, atom->lstrip);
1658 else if (atom->option == R_RSTRIP)
1659 return rstrip_ref_components(refname, atom->rstrip);
1660 else
1661 return xstrdup(refname);
1664 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1665 struct branch *branch, const char **s)
1667 int num_ours, num_theirs;
1668 if (atom->u.remote_ref.option == RR_REF)
1669 *s = show_ref(&atom->u.remote_ref.refname, refname);
1670 else if (atom->u.remote_ref.option == RR_TRACK) {
1671 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1672 NULL, atom->u.remote_ref.push,
1673 AHEAD_BEHIND_FULL) < 0) {
1674 *s = xstrdup(msgs.gone);
1675 } else if (!num_ours && !num_theirs)
1676 *s = xstrdup("");
1677 else if (!num_ours)
1678 *s = xstrfmt(msgs.behind, num_theirs);
1679 else if (!num_theirs)
1680 *s = xstrfmt(msgs.ahead, num_ours);
1681 else
1682 *s = xstrfmt(msgs.ahead_behind,
1683 num_ours, num_theirs);
1684 if (!atom->u.remote_ref.nobracket && *s[0]) {
1685 const char *to_free = *s;
1686 *s = xstrfmt("[%s]", *s);
1687 free((void *)to_free);
1689 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1690 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1691 NULL, atom->u.remote_ref.push,
1692 AHEAD_BEHIND_FULL) < 0) {
1693 *s = xstrdup("");
1694 return;
1696 if (!num_ours && !num_theirs)
1697 *s = xstrdup("=");
1698 else if (!num_ours)
1699 *s = xstrdup("<");
1700 else if (!num_theirs)
1701 *s = xstrdup(">");
1702 else
1703 *s = xstrdup("<>");
1704 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1705 int explicit;
1706 const char *remote = atom->u.remote_ref.push ?
1707 pushremote_for_branch(branch, &explicit) :
1708 remote_for_branch(branch, &explicit);
1709 *s = xstrdup(explicit ? remote : "");
1710 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1711 const char *merge;
1713 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1714 *s = xstrdup(merge ? merge : "");
1715 } else
1716 BUG("unhandled RR_* enum");
1719 char *get_head_description(void)
1721 struct strbuf desc = STRBUF_INIT;
1722 struct wt_status_state state;
1723 memset(&state, 0, sizeof(state));
1724 wt_status_get_state(the_repository, &state, 1);
1725 if (state.rebase_in_progress ||
1726 state.rebase_interactive_in_progress) {
1727 if (state.branch)
1728 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1729 state.branch);
1730 else
1731 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1732 state.detached_from);
1733 } else if (state.bisect_in_progress)
1734 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1735 state.branch);
1736 else if (state.detached_from) {
1737 if (state.detached_at)
1738 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1739 state.detached_from);
1740 else
1741 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1742 state.detached_from);
1743 } else
1744 strbuf_addstr(&desc, _("(no branch)"));
1746 wt_status_state_free_buffers(&state);
1748 return strbuf_detach(&desc, NULL);
1751 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1753 if (!ref->symref)
1754 return xstrdup("");
1755 else
1756 return show_ref(&atom->u.refname, ref->symref);
1759 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1761 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1762 return get_head_description();
1763 return show_ref(&atom->u.refname, ref->refname);
1766 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1767 struct expand_data *oi, struct strbuf *err)
1769 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1770 int eaten = 1;
1771 if (oi->info.contentp) {
1772 /* We need to know that to use parse_object_buffer properly */
1773 oi->info.sizep = &oi->size;
1774 oi->info.typep = &oi->type;
1776 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1777 OBJECT_INFO_LOOKUP_REPLACE))
1778 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1779 oid_to_hex(&oi->oid), ref->refname);
1780 if (oi->info.disk_sizep && oi->disk_size < 0)
1781 BUG("Object size is less than zero.");
1783 if (oi->info.contentp) {
1784 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1785 if (!*obj) {
1786 if (!eaten)
1787 free(oi->content);
1788 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1789 oid_to_hex(&oi->oid), ref->refname);
1791 grab_values(ref->value, deref, *obj, oi);
1794 grab_common_values(ref->value, deref, oi);
1795 if (!eaten)
1796 free(oi->content);
1797 return 0;
1800 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1802 int i;
1804 for (i = 0; worktrees[i]; i++) {
1805 if (worktrees[i]->head_ref) {
1806 struct ref_to_worktree_entry *entry;
1807 entry = xmalloc(sizeof(*entry));
1808 entry->wt = worktrees[i];
1809 hashmap_entry_init(&entry->ent,
1810 strhash(worktrees[i]->head_ref));
1812 hashmap_add(map, &entry->ent);
1817 static void lazy_init_worktree_map(void)
1819 if (ref_to_worktree_map.worktrees)
1820 return;
1822 ref_to_worktree_map.worktrees = get_worktrees();
1823 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1824 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1827 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1829 struct hashmap_entry entry, *e;
1830 struct ref_to_worktree_entry *lookup_result;
1832 lazy_init_worktree_map();
1834 hashmap_entry_init(&entry, strhash(ref->refname));
1835 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1837 if (!e)
1838 return xstrdup("");
1840 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1842 return xstrdup(lookup_result->wt->path);
1846 * Parse the object referred by ref, and grab needed value.
1848 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1850 struct object *obj;
1851 int i;
1852 struct object_info empty = OBJECT_INFO_INIT;
1854 CALLOC_ARRAY(ref->value, used_atom_cnt);
1856 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1857 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1858 NULL, NULL);
1859 if (!ref->symref)
1860 ref->symref = xstrdup("");
1863 /* Fill in specials first */
1864 for (i = 0; i < used_atom_cnt; i++) {
1865 struct used_atom *atom = &used_atom[i];
1866 enum atom_type atom_type = atom->atom_type;
1867 const char *name = used_atom[i].name;
1868 struct atom_value *v = &ref->value[i];
1869 int deref = 0;
1870 const char *refname;
1871 struct branch *branch = NULL;
1873 v->s_size = ATOM_SIZE_UNSPECIFIED;
1874 v->handler = append_atom;
1875 v->atom = atom;
1877 if (*name == '*') {
1878 deref = 1;
1879 name++;
1882 if (atom_type == ATOM_REFNAME)
1883 refname = get_refname(atom, ref);
1884 else if (atom_type == ATOM_WORKTREEPATH) {
1885 if (ref->kind == FILTER_REFS_BRANCHES)
1886 v->s = get_worktree_path(atom, ref);
1887 else
1888 v->s = xstrdup("");
1889 continue;
1891 else if (atom_type == ATOM_SYMREF)
1892 refname = get_symref(atom, ref);
1893 else if (atom_type == ATOM_UPSTREAM) {
1894 const char *branch_name;
1895 /* only local branches may have an upstream */
1896 if (!skip_prefix(ref->refname, "refs/heads/",
1897 &branch_name)) {
1898 v->s = xstrdup("");
1899 continue;
1901 branch = branch_get(branch_name);
1903 refname = branch_get_upstream(branch, NULL);
1904 if (refname)
1905 fill_remote_ref_details(atom, refname, branch, &v->s);
1906 else
1907 v->s = xstrdup("");
1908 continue;
1909 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1910 const char *branch_name;
1911 v->s = xstrdup("");
1912 if (!skip_prefix(ref->refname, "refs/heads/",
1913 &branch_name))
1914 continue;
1915 branch = branch_get(branch_name);
1917 if (atom->u.remote_ref.push_remote)
1918 refname = NULL;
1919 else {
1920 refname = branch_get_push(branch, NULL);
1921 if (!refname)
1922 continue;
1924 /* We will definitely re-init v->s on the next line. */
1925 free((char *)v->s);
1926 fill_remote_ref_details(atom, refname, branch, &v->s);
1927 continue;
1928 } else if (atom_type == ATOM_COLOR) {
1929 v->s = xstrdup(atom->u.color);
1930 continue;
1931 } else if (atom_type == ATOM_FLAG) {
1932 char buf[256], *cp = buf;
1933 if (ref->flag & REF_ISSYMREF)
1934 cp = copy_advance(cp, ",symref");
1935 if (ref->flag & REF_ISPACKED)
1936 cp = copy_advance(cp, ",packed");
1937 if (cp == buf)
1938 v->s = xstrdup("");
1939 else {
1940 *cp = '\0';
1941 v->s = xstrdup(buf + 1);
1943 continue;
1944 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1945 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1946 continue;
1947 } else if (atom_type == ATOM_HEAD) {
1948 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1949 v->s = xstrdup("*");
1950 else
1951 v->s = xstrdup(" ");
1952 continue;
1953 } else if (atom_type == ATOM_ALIGN) {
1954 v->handler = align_atom_handler;
1955 v->s = xstrdup("");
1956 continue;
1957 } else if (atom_type == ATOM_END) {
1958 v->handler = end_atom_handler;
1959 v->s = xstrdup("");
1960 continue;
1961 } else if (atom_type == ATOM_IF) {
1962 const char *s;
1963 if (skip_prefix(name, "if:", &s))
1964 v->s = xstrdup(s);
1965 else
1966 v->s = xstrdup("");
1967 v->handler = if_atom_handler;
1968 continue;
1969 } else if (atom_type == ATOM_THEN) {
1970 v->handler = then_atom_handler;
1971 v->s = xstrdup("");
1972 continue;
1973 } else if (atom_type == ATOM_ELSE) {
1974 v->handler = else_atom_handler;
1975 v->s = xstrdup("");
1976 continue;
1977 } else if (atom_type == ATOM_REST) {
1978 if (ref->rest)
1979 v->s = xstrdup(ref->rest);
1980 else
1981 v->s = xstrdup("");
1982 continue;
1983 } else
1984 continue;
1986 if (!deref)
1987 v->s = xstrdup(refname);
1988 else
1989 v->s = xstrfmt("%s^{}", refname);
1990 free((char *)refname);
1993 for (i = 0; i < used_atom_cnt; i++) {
1994 struct atom_value *v = &ref->value[i];
1995 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1996 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1997 oid_to_hex(&ref->objectname), ref->refname);
2000 if (need_tagged)
2001 oi.info.contentp = &oi.content;
2002 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2003 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2004 return 0;
2007 oi.oid = ref->objectname;
2008 if (get_object(ref, 0, &obj, &oi, err))
2009 return -1;
2012 * If there is no atom that wants to know about tagged
2013 * object, we are done.
2015 if (!need_tagged || (obj->type != OBJ_TAG))
2016 return 0;
2019 * If it is a tag object, see if we use a value that derefs
2020 * the object, and if we do grab the object it refers to.
2022 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2025 * NEEDSWORK: This derefs tag only once, which
2026 * is good to deal with chains of trust, but
2027 * is not consistent with what deref_tag() does
2028 * which peels the onion to the core.
2030 return get_object(ref, 1, &obj, &oi_deref, err);
2034 * Given a ref, return the value for the atom. This lazily gets value
2035 * out of the object by calling populate value.
2037 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2038 struct atom_value **v, struct strbuf *err)
2040 if (!ref->value) {
2041 if (populate_value(ref, err))
2042 return -1;
2043 fill_missing_values(ref->value);
2045 *v = &ref->value[atom];
2046 return 0;
2050 * Return 1 if the refname matches one of the patterns, otherwise 0.
2051 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2052 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2053 * matches "refs/heads/mas*", too).
2055 static int match_pattern(const struct ref_filter *filter, const char *refname)
2057 const char **patterns = filter->name_patterns;
2058 unsigned flags = 0;
2060 if (filter->ignore_case)
2061 flags |= WM_CASEFOLD;
2064 * When no '--format' option is given we need to skip the prefix
2065 * for matching refs of tags and branches.
2067 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2068 skip_prefix(refname, "refs/heads/", &refname) ||
2069 skip_prefix(refname, "refs/remotes/", &refname) ||
2070 skip_prefix(refname, "refs/", &refname));
2072 for (; *patterns; patterns++) {
2073 if (!wildmatch(*patterns, refname, flags))
2074 return 1;
2076 return 0;
2080 * Return 1 if the refname matches one of the patterns, otherwise 0.
2081 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2082 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2083 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2085 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2087 const char **pattern = filter->name_patterns;
2088 int namelen = strlen(refname);
2089 unsigned flags = WM_PATHNAME;
2091 if (filter->ignore_case)
2092 flags |= WM_CASEFOLD;
2094 for (; *pattern; pattern++) {
2095 const char *p = *pattern;
2096 int plen = strlen(p);
2098 if ((plen <= namelen) &&
2099 !strncmp(refname, p, plen) &&
2100 (refname[plen] == '\0' ||
2101 refname[plen] == '/' ||
2102 p[plen-1] == '/'))
2103 return 1;
2104 if (!wildmatch(p, refname, flags))
2105 return 1;
2107 return 0;
2110 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2111 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2113 if (!*filter->name_patterns)
2114 return 1; /* No pattern always matches */
2115 if (filter->match_as_path)
2116 return match_name_as_path(filter, refname);
2117 return match_pattern(filter, refname);
2121 * This is the same as for_each_fullref_in(), but it tries to iterate
2122 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2123 * pattern match, so the callback still has to match each ref individually.
2125 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2126 each_ref_fn cb,
2127 void *cb_data)
2129 if (!filter->match_as_path) {
2131 * in this case, the patterns are applied after
2132 * prefixes like "refs/heads/" etc. are stripped off,
2133 * so we have to look at everything:
2135 return for_each_fullref_in("", cb, cb_data);
2138 if (filter->ignore_case) {
2140 * we can't handle case-insensitive comparisons,
2141 * so just return everything and let the caller
2142 * sort it out.
2144 return for_each_fullref_in("", cb, cb_data);
2147 if (!filter->name_patterns[0]) {
2148 /* no patterns; we have to look at everything */
2149 return for_each_fullref_in("", cb, cb_data);
2152 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2153 NULL, filter->name_patterns,
2154 cb, cb_data);
2158 * Given a ref (oid, refname), check if the ref belongs to the array
2159 * of oids. If the given ref is a tag, check if the given tag points
2160 * at one of the oids in the given oid array.
2161 * NEEDSWORK:
2162 * 1. Only a single level of indirection is obtained, we might want to
2163 * change this to account for multiple levels (e.g. annotated tags
2164 * pointing to annotated tags pointing to a commit.)
2165 * 2. As the refs are cached we might know what refname peels to without
2166 * the need to parse the object via parse_object(). peel_ref() might be a
2167 * more efficient alternative to obtain the pointee.
2169 static const struct object_id *match_points_at(struct oid_array *points_at,
2170 const struct object_id *oid,
2171 const char *refname)
2173 const struct object_id *tagged_oid = NULL;
2174 struct object *obj;
2176 if (oid_array_lookup(points_at, oid) >= 0)
2177 return oid;
2178 obj = parse_object(the_repository, oid);
2179 if (!obj)
2180 die(_("malformed object at '%s'"), refname);
2181 if (obj->type == OBJ_TAG)
2182 tagged_oid = get_tagged_oid((struct tag *)obj);
2183 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2184 return tagged_oid;
2185 return NULL;
2189 * Allocate space for a new ref_array_item and copy the name and oid to it.
2191 * Callers can then fill in other struct members at their leisure.
2193 static struct ref_array_item *new_ref_array_item(const char *refname,
2194 const struct object_id *oid)
2196 struct ref_array_item *ref;
2198 FLEX_ALLOC_STR(ref, refname, refname);
2199 oidcpy(&ref->objectname, oid);
2200 ref->rest = NULL;
2202 return ref;
2205 struct ref_array_item *ref_array_push(struct ref_array *array,
2206 const char *refname,
2207 const struct object_id *oid)
2209 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2211 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2212 array->items[array->nr++] = ref;
2214 return ref;
2217 static int ref_kind_from_refname(const char *refname)
2219 unsigned int i;
2221 static struct {
2222 const char *prefix;
2223 unsigned int kind;
2224 } ref_kind[] = {
2225 { "refs/heads/" , FILTER_REFS_BRANCHES },
2226 { "refs/remotes/" , FILTER_REFS_REMOTES },
2227 { "refs/tags/", FILTER_REFS_TAGS}
2230 if (!strcmp(refname, "HEAD"))
2231 return FILTER_REFS_DETACHED_HEAD;
2233 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2234 if (starts_with(refname, ref_kind[i].prefix))
2235 return ref_kind[i].kind;
2238 return FILTER_REFS_OTHERS;
2241 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2243 if (filter->kind == FILTER_REFS_BRANCHES ||
2244 filter->kind == FILTER_REFS_REMOTES ||
2245 filter->kind == FILTER_REFS_TAGS)
2246 return filter->kind;
2247 return ref_kind_from_refname(refname);
2250 struct ref_filter_cbdata {
2251 struct ref_array *array;
2252 struct ref_filter *filter;
2253 struct contains_cache contains_cache;
2254 struct contains_cache no_contains_cache;
2258 * A call-back given to for_each_ref(). Filter refs and keep them for
2259 * later object processing.
2261 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2263 struct ref_filter_cbdata *ref_cbdata = cb_data;
2264 struct ref_filter *filter = ref_cbdata->filter;
2265 struct ref_array_item *ref;
2266 struct commit *commit = NULL;
2267 unsigned int kind;
2269 if (flag & REF_BAD_NAME) {
2270 warning(_("ignoring ref with broken name %s"), refname);
2271 return 0;
2274 if (flag & REF_ISBROKEN) {
2275 warning(_("ignoring broken ref %s"), refname);
2276 return 0;
2279 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2280 kind = filter_ref_kind(filter, refname);
2281 if (!(kind & filter->kind))
2282 return 0;
2284 if (!filter_pattern_match(filter, refname))
2285 return 0;
2287 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2288 return 0;
2291 * A merge filter is applied on refs pointing to commits. Hence
2292 * obtain the commit using the 'oid' available and discard all
2293 * non-commits early. The actual filtering is done later.
2295 if (filter->reachable_from || filter->unreachable_from ||
2296 filter->with_commit || filter->no_commit || filter->verbose) {
2297 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2298 if (!commit)
2299 return 0;
2300 /* We perform the filtering for the '--contains' option... */
2301 if (filter->with_commit &&
2302 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2303 return 0;
2304 /* ...or for the `--no-contains' option */
2305 if (filter->no_commit &&
2306 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2307 return 0;
2311 * We do not open the object yet; sort may only need refname
2312 * to do its job and the resulting list may yet to be pruned
2313 * by maxcount logic.
2315 ref = ref_array_push(ref_cbdata->array, refname, oid);
2316 ref->commit = commit;
2317 ref->flag = flag;
2318 ref->kind = kind;
2320 return 0;
2323 /* Free memory allocated for a ref_array_item */
2324 static void free_array_item(struct ref_array_item *item)
2326 free((char *)item->symref);
2327 if (item->value) {
2328 int i;
2329 for (i = 0; i < used_atom_cnt; i++)
2330 free((char *)item->value[i].s);
2331 free(item->value);
2333 free(item);
2336 /* Free all memory allocated for ref_array */
2337 void ref_array_clear(struct ref_array *array)
2339 int i;
2341 for (i = 0; i < array->nr; i++)
2342 free_array_item(array->items[i]);
2343 FREE_AND_NULL(array->items);
2344 array->nr = array->alloc = 0;
2346 for (i = 0; i < used_atom_cnt; i++) {
2347 struct used_atom *atom = &used_atom[i];
2348 if (atom->atom_type == ATOM_HEAD)
2349 free(atom->u.head);
2350 free((char *)atom->name);
2352 FREE_AND_NULL(used_atom);
2353 used_atom_cnt = 0;
2355 if (ref_to_worktree_map.worktrees) {
2356 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2357 struct ref_to_worktree_entry, ent);
2358 free_worktrees(ref_to_worktree_map.worktrees);
2359 ref_to_worktree_map.worktrees = NULL;
2363 #define EXCLUDE_REACHED 0
2364 #define INCLUDE_REACHED 1
2365 static void reach_filter(struct ref_array *array,
2366 struct commit_list *check_reachable,
2367 int include_reached)
2369 struct rev_info revs;
2370 int i, old_nr;
2371 struct commit **to_clear;
2372 struct commit_list *cr;
2374 if (!check_reachable)
2375 return;
2377 CALLOC_ARRAY(to_clear, array->nr);
2379 repo_init_revisions(the_repository, &revs, NULL);
2381 for (i = 0; i < array->nr; i++) {
2382 struct ref_array_item *item = array->items[i];
2383 add_pending_object(&revs, &item->commit->object, item->refname);
2384 to_clear[i] = item->commit;
2387 for (cr = check_reachable; cr; cr = cr->next) {
2388 struct commit *merge_commit = cr->item;
2389 merge_commit->object.flags |= UNINTERESTING;
2390 add_pending_object(&revs, &merge_commit->object, "");
2393 revs.limited = 1;
2394 if (prepare_revision_walk(&revs))
2395 die(_("revision walk setup failed"));
2397 old_nr = array->nr;
2398 array->nr = 0;
2400 for (i = 0; i < old_nr; i++) {
2401 struct ref_array_item *item = array->items[i];
2402 struct commit *commit = item->commit;
2404 int is_merged = !!(commit->object.flags & UNINTERESTING);
2406 if (is_merged == include_reached)
2407 array->items[array->nr++] = array->items[i];
2408 else
2409 free_array_item(item);
2412 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2414 while (check_reachable) {
2415 struct commit *merge_commit = pop_commit(&check_reachable);
2416 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2419 release_revisions(&revs);
2420 free(to_clear);
2424 * API for filtering a set of refs. Based on the type of refs the user
2425 * has requested, we iterate through those refs and apply filters
2426 * as per the given ref_filter structure and finally store the
2427 * filtered refs in the ref_array structure.
2429 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2431 struct ref_filter_cbdata ref_cbdata;
2432 int save_commit_buffer_orig;
2433 int ret = 0;
2435 ref_cbdata.array = array;
2436 ref_cbdata.filter = filter;
2438 filter->kind = type & FILTER_REFS_KIND_MASK;
2440 save_commit_buffer_orig = save_commit_buffer;
2441 save_commit_buffer = 0;
2443 init_contains_cache(&ref_cbdata.contains_cache);
2444 init_contains_cache(&ref_cbdata.no_contains_cache);
2446 /* Simple per-ref filtering */
2447 if (!filter->kind)
2448 die("filter_refs: invalid type");
2449 else {
2451 * For common cases where we need only branches or remotes or tags,
2452 * we only iterate through those refs. If a mix of refs is needed,
2453 * we iterate over all refs and filter out required refs with the help
2454 * of filter_ref_kind().
2456 if (filter->kind == FILTER_REFS_BRANCHES)
2457 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2458 else if (filter->kind == FILTER_REFS_REMOTES)
2459 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2460 else if (filter->kind == FILTER_REFS_TAGS)
2461 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2462 else if (filter->kind & FILTER_REFS_ALL)
2463 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2464 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2465 head_ref(ref_filter_handler, &ref_cbdata);
2468 clear_contains_cache(&ref_cbdata.contains_cache);
2469 clear_contains_cache(&ref_cbdata.no_contains_cache);
2471 /* Filters that need revision walking */
2472 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2473 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2475 save_commit_buffer = save_commit_buffer_orig;
2476 return ret;
2479 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2481 if (!(a->kind ^ b->kind))
2482 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2483 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2484 return -1;
2485 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2486 return 1;
2487 BUG("should have died in the xor check above");
2488 return 0;
2491 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2493 const char *s1 = vs1, *s2 = vs2;
2494 const char *end = s1 + n;
2496 for (; s1 < end; s1++, s2++) {
2497 int diff = tolower(*s1) - tolower(*s2);
2498 if (diff)
2499 return diff;
2501 return 0;
2504 struct ref_sorting {
2505 struct ref_sorting *next;
2506 int atom; /* index into used_atom array (internal) */
2507 enum ref_sorting_order sort_flags;
2510 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2512 struct atom_value *va, *vb;
2513 int cmp;
2514 int cmp_detached_head = 0;
2515 cmp_type cmp_type = used_atom[s->atom].type;
2516 struct strbuf err = STRBUF_INIT;
2518 if (get_ref_atom_value(a, s->atom, &va, &err))
2519 die("%s", err.buf);
2520 if (get_ref_atom_value(b, s->atom, &vb, &err))
2521 die("%s", err.buf);
2522 strbuf_release(&err);
2523 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2524 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2525 cmp = compare_detached_head(a, b);
2526 cmp_detached_head = 1;
2527 } else if (s->sort_flags & REF_SORTING_VERSION) {
2528 cmp = versioncmp(va->s, vb->s);
2529 } else if (cmp_type == FIELD_STR) {
2530 if (va->s_size < 0 && vb->s_size < 0) {
2531 int (*cmp_fn)(const char *, const char *);
2532 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2533 ? strcasecmp : strcmp;
2534 cmp = cmp_fn(va->s, vb->s);
2535 } else {
2536 size_t a_size = va->s_size < 0 ?
2537 strlen(va->s) : va->s_size;
2538 size_t b_size = vb->s_size < 0 ?
2539 strlen(vb->s) : vb->s_size;
2540 int (*cmp_fn)(const void *, const void *, size_t);
2541 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2542 ? memcasecmp : memcmp;
2544 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2545 a_size : b_size);
2546 if (!cmp) {
2547 if (a_size > b_size)
2548 cmp = 1;
2549 else if (a_size < b_size)
2550 cmp = -1;
2553 } else {
2554 if (va->value < vb->value)
2555 cmp = -1;
2556 else if (va->value == vb->value)
2557 cmp = 0;
2558 else
2559 cmp = 1;
2562 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2563 ? -cmp : cmp;
2566 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2568 struct ref_array_item *a = *((struct ref_array_item **)a_);
2569 struct ref_array_item *b = *((struct ref_array_item **)b_);
2570 struct ref_sorting *s;
2572 for (s = ref_sorting; s; s = s->next) {
2573 int cmp = cmp_ref_sorting(s, a, b);
2574 if (cmp)
2575 return cmp;
2577 s = ref_sorting;
2578 return s && s->sort_flags & REF_SORTING_ICASE ?
2579 strcasecmp(a->refname, b->refname) :
2580 strcmp(a->refname, b->refname);
2583 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2584 unsigned int mask, int on)
2586 for (; sorting; sorting = sorting->next) {
2587 if (on)
2588 sorting->sort_flags |= mask;
2589 else
2590 sorting->sort_flags &= ~mask;
2594 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2596 QSORT_S(array->items, array->nr, compare_refs, sorting);
2599 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2601 struct strbuf *s = &state->stack->output;
2603 while (*cp && (!ep || cp < ep)) {
2604 if (*cp == '%') {
2605 if (cp[1] == '%')
2606 cp++;
2607 else {
2608 int ch = hex2chr(cp + 1);
2609 if (0 <= ch) {
2610 strbuf_addch(s, ch);
2611 cp += 3;
2612 continue;
2616 strbuf_addch(s, *cp);
2617 cp++;
2621 int format_ref_array_item(struct ref_array_item *info,
2622 struct ref_format *format,
2623 struct strbuf *final_buf,
2624 struct strbuf *error_buf)
2626 const char *cp, *sp, *ep;
2627 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2629 state.quote_style = format->quote_style;
2630 push_stack_element(&state.stack);
2632 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2633 struct atom_value *atomv;
2634 int pos;
2636 ep = strchr(sp, ')');
2637 if (cp < sp)
2638 append_literal(cp, sp, &state);
2639 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2640 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2641 atomv->handler(atomv, &state, error_buf)) {
2642 pop_stack_element(&state.stack);
2643 return -1;
2646 if (*cp) {
2647 sp = cp + strlen(cp);
2648 append_literal(cp, sp, &state);
2650 if (format->need_color_reset_at_eol) {
2651 struct atom_value resetv = ATOM_VALUE_INIT;
2652 resetv.s = GIT_COLOR_RESET;
2653 if (append_atom(&resetv, &state, error_buf)) {
2654 pop_stack_element(&state.stack);
2655 return -1;
2658 if (state.stack->prev) {
2659 pop_stack_element(&state.stack);
2660 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2662 strbuf_addbuf(final_buf, &state.stack->output);
2663 pop_stack_element(&state.stack);
2664 return 0;
2667 void pretty_print_ref(const char *name, const struct object_id *oid,
2668 struct ref_format *format)
2670 struct ref_array_item *ref_item;
2671 struct strbuf output = STRBUF_INIT;
2672 struct strbuf err = STRBUF_INIT;
2674 ref_item = new_ref_array_item(name, oid);
2675 ref_item->kind = ref_kind_from_refname(name);
2676 if (format_ref_array_item(ref_item, format, &output, &err))
2677 die("%s", err.buf);
2678 fwrite(output.buf, 1, output.len, stdout);
2679 putchar('\n');
2681 strbuf_release(&err);
2682 strbuf_release(&output);
2683 free_array_item(ref_item);
2686 static int parse_sorting_atom(const char *atom)
2689 * This parses an atom using a dummy ref_format, since we don't
2690 * actually care about the formatting details.
2692 struct ref_format dummy = REF_FORMAT_INIT;
2693 const char *end = atom + strlen(atom);
2694 struct strbuf err = STRBUF_INIT;
2695 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2696 if (res < 0)
2697 die("%s", err.buf);
2698 strbuf_release(&err);
2699 return res;
2702 /* If no sorting option is given, use refname to sort as default */
2703 static struct ref_sorting *ref_default_sorting(void)
2705 static const char cstr_name[] = "refname";
2707 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2709 sorting->next = NULL;
2710 sorting->atom = parse_sorting_atom(cstr_name);
2711 return sorting;
2714 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2716 struct ref_sorting *s;
2718 CALLOC_ARRAY(s, 1);
2719 s->next = *sorting_tail;
2720 *sorting_tail = s;
2722 if (*arg == '-') {
2723 s->sort_flags |= REF_SORTING_REVERSE;
2724 arg++;
2726 if (skip_prefix(arg, "version:", &arg) ||
2727 skip_prefix(arg, "v:", &arg))
2728 s->sort_flags |= REF_SORTING_VERSION;
2729 s->atom = parse_sorting_atom(arg);
2732 struct ref_sorting *ref_sorting_options(struct string_list *options)
2734 struct string_list_item *item;
2735 struct ref_sorting *sorting = NULL, **tail = &sorting;
2737 if (!options->nr) {
2738 sorting = ref_default_sorting();
2739 } else {
2740 for_each_string_list_item(item, options)
2741 parse_ref_sorting(tail, item->string);
2745 * From here on, the ref_sorting list should be used to talk
2746 * about the sort order used for the output. The caller
2747 * should not touch the string form anymore.
2749 string_list_clear(options, 0);
2750 return sorting;
2753 void ref_sorting_release(struct ref_sorting *sorting)
2755 while (sorting) {
2756 struct ref_sorting *next = sorting->next;
2757 free(sorting);
2758 sorting = next;
2762 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2764 struct ref_filter *rf = opt->value;
2765 struct object_id oid;
2766 struct commit *merge_commit;
2768 BUG_ON_OPT_NEG(unset);
2770 if (repo_get_oid(the_repository, arg, &oid))
2771 die(_("malformed object name %s"), arg);
2773 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2775 if (!merge_commit)
2776 return error(_("option `%s' must point to a commit"), opt->long_name);
2778 if (starts_with(opt->long_name, "no"))
2779 commit_list_insert(merge_commit, &rf->unreachable_from);
2780 else
2781 commit_list_insert(merge_commit, &rf->reachable_from);
2783 return 0;