Merge branch 'db/date-underflow-fix'
[git.git] / ref-filter.c
blob8c5e673fc0a521425c1035ce3f31575c185c34ef
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "config.h"
7 #include "gpg-interface.h"
8 #include "hex.h"
9 #include "parse-options.h"
10 #include "run-command.h"
11 #include "refs.h"
12 #include "wildmatch.h"
13 #include "object-name.h"
14 #include "object-store-ll.h"
15 #include "oid-array.h"
16 #include "repository.h"
17 #include "commit.h"
18 #include "mailmap.h"
19 #include "ident.h"
20 #include "remote.h"
21 #include "color.h"
22 #include "tag.h"
23 #include "quote.h"
24 #include "ref-filter.h"
25 #include "revision.h"
26 #include "utf8.h"
27 #include "versioncmp.h"
28 #include "trailer.h"
29 #include "wt-status.h"
30 #include "commit-slab.h"
31 #include "commit-reach.h"
32 #include "worktree.h"
33 #include "hashmap.h"
35 static struct ref_msg {
36 const char *gone;
37 const char *ahead;
38 const char *behind;
39 const char *ahead_behind;
40 } msgs = {
41 /* Untranslated plumbing messages: */
42 "gone",
43 "ahead %d",
44 "behind %d",
45 "ahead %d, behind %d"
48 void setup_ref_filter_porcelain_msg(void)
50 msgs.gone = _("gone");
51 msgs.ahead = _("ahead %d");
52 msgs.behind = _("behind %d");
53 msgs.ahead_behind = _("ahead %d, behind %d");
56 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
57 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
58 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
60 struct align {
61 align_type position;
62 unsigned int width;
65 struct if_then_else {
66 cmp_status cmp_status;
67 const char *str;
68 unsigned int then_atom_seen : 1,
69 else_atom_seen : 1,
70 condition_satisfied : 1;
73 struct refname_atom {
74 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
75 int lstrip, rstrip;
78 static struct ref_trailer_buf {
79 struct string_list filter_list;
80 struct strbuf sepbuf;
81 struct strbuf kvsepbuf;
82 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
84 static struct expand_data {
85 struct object_id oid;
86 enum object_type type;
87 unsigned long size;
88 off_t disk_size;
89 struct object_id delta_base_oid;
90 void *content;
92 struct object_info info;
93 } oi, oi_deref;
95 struct ref_to_worktree_entry {
96 struct hashmap_entry ent;
97 struct worktree *wt; /* key is wt->head_ref */
100 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
101 const struct hashmap_entry *eptr,
102 const struct hashmap_entry *kptr,
103 const void *keydata_aka_refname)
105 const struct ref_to_worktree_entry *e, *k;
107 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
108 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
110 return strcmp(e->wt->head_ref,
111 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
114 static struct ref_to_worktree_map {
115 struct hashmap map;
116 struct worktree **worktrees;
117 } ref_to_worktree_map;
120 * The enum atom_type is used as the index of valid_atom array.
121 * In the atom parsing stage, it will be passed to used_atom.atom_type
122 * as the identifier of the atom type. We can check the type of used_atom
123 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
125 enum atom_type {
126 ATOM_REFNAME,
127 ATOM_OBJECTTYPE,
128 ATOM_OBJECTSIZE,
129 ATOM_OBJECTNAME,
130 ATOM_DELTABASE,
131 ATOM_TREE,
132 ATOM_PARENT,
133 ATOM_NUMPARENT,
134 ATOM_OBJECT,
135 ATOM_TYPE,
136 ATOM_TAG,
137 ATOM_AUTHOR,
138 ATOM_AUTHORNAME,
139 ATOM_AUTHOREMAIL,
140 ATOM_AUTHORDATE,
141 ATOM_COMMITTER,
142 ATOM_COMMITTERNAME,
143 ATOM_COMMITTEREMAIL,
144 ATOM_COMMITTERDATE,
145 ATOM_TAGGER,
146 ATOM_TAGGERNAME,
147 ATOM_TAGGEREMAIL,
148 ATOM_TAGGERDATE,
149 ATOM_CREATOR,
150 ATOM_CREATORDATE,
151 ATOM_DESCRIBE,
152 ATOM_SUBJECT,
153 ATOM_BODY,
154 ATOM_TRAILERS,
155 ATOM_CONTENTS,
156 ATOM_SIGNATURE,
157 ATOM_RAW,
158 ATOM_UPSTREAM,
159 ATOM_PUSH,
160 ATOM_SYMREF,
161 ATOM_FLAG,
162 ATOM_HEAD,
163 ATOM_COLOR,
164 ATOM_WORKTREEPATH,
165 ATOM_ALIGN,
166 ATOM_END,
167 ATOM_IF,
168 ATOM_THEN,
169 ATOM_ELSE,
170 ATOM_REST,
171 ATOM_AHEADBEHIND,
175 * An atom is a valid field atom listed below, possibly prefixed with
176 * a "*" to denote deref_tag().
178 * We parse given format string and sort specifiers, and make a list
179 * of properties that we need to extract out of objects. ref_array_item
180 * structure will hold an array of values extracted that can be
181 * indexed with the "atom number", which is an index into this
182 * array.
184 static struct used_atom {
185 enum atom_type atom_type;
186 const char *name;
187 cmp_type type;
188 info_source source;
189 union {
190 char color[COLOR_MAXLEN];
191 struct align align;
192 struct {
193 enum {
194 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
195 } option;
196 struct refname_atom refname;
197 unsigned int nobracket : 1, push : 1, push_remote : 1;
198 } remote_ref;
199 struct {
200 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
201 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
202 struct process_trailer_options trailer_opts;
203 unsigned int nlines;
204 } contents;
205 struct {
206 enum { RAW_BARE, RAW_LENGTH } option;
207 } raw_data;
208 struct {
209 cmp_status cmp_status;
210 const char *str;
211 } if_then_else;
212 struct {
213 enum { O_FULL, O_LENGTH, O_SHORT } option;
214 unsigned int length;
215 } oid;
216 struct {
217 enum { O_SIZE, O_SIZE_DISK } option;
218 } objectsize;
219 struct {
220 enum { N_RAW, N_MAILMAP } option;
221 } name_option;
222 struct {
223 enum {
224 EO_RAW = 0,
225 EO_TRIM = 1<<0,
226 EO_LOCALPART = 1<<1,
227 EO_MAILMAP = 1<<2,
228 } option;
229 } email_option;
230 struct {
231 enum { S_BARE, S_GRADE, S_SIGNER, S_KEY,
232 S_FINGERPRINT, S_PRI_KEY_FP, S_TRUST_LEVEL } option;
233 } signature;
234 const char **describe_args;
235 struct refname_atom refname;
236 char *head;
237 } u;
238 } *used_atom;
239 static int used_atom_cnt, need_tagged, need_symref;
242 * Expand string, append it to strbuf *sb, then return error code ret.
243 * Allow to save few lines of code.
245 __attribute__((format (printf, 3, 4)))
246 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
248 va_list ap;
249 va_start(ap, fmt);
250 strbuf_vaddf(sb, fmt, ap);
251 va_end(ap);
252 return ret;
255 static int err_no_arg(struct strbuf *sb, const char *name)
257 size_t namelen = strchrnul(name, ':') - name;
258 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
259 (int)namelen, name);
260 return -1;
263 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
265 size_t namelen = strchrnul(name, ':') - name;
266 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
267 (int)namelen, name, arg);
268 return -1;
272 * Parse option of name "candidate" in the option string "to_parse" of
273 * the form
275 * "candidate1[=val1],candidate2[=val2],candidate3[=val3],..."
277 * The remaining part of "to_parse" is stored in "end" (if we are
278 * parsing the last candidate, then this is NULL) and the value of
279 * the candidate is stored in "valuestart" and its length in "valuelen",
280 * that is the portion after "=". Since it is possible for a "candidate"
281 * to not have a value, in such cases, "valuestart" is set to point to
282 * NULL and "valuelen" to 0.
284 * The function returns 1 on success. It returns 0 if we don't find
285 * "candidate" in "to_parse" or we find "candidate" but it is followed
286 * by more chars (for example, "candidatefoo"), that is, we don't find
287 * an exact match.
289 * This function only does the above for one "candidate" at a time. So
290 * it has to be called each time trying to parse a "candidate" in the
291 * option string "to_parse".
293 static int match_atom_arg_value(const char *to_parse, const char *candidate,
294 const char **end, const char **valuestart,
295 size_t *valuelen)
297 const char *atom;
299 if (!skip_prefix(to_parse, candidate, &atom))
300 return 0; /* definitely not "candidate" */
302 if (*atom == '=') {
303 /* we just saw "candidate=" */
304 *valuestart = atom + 1;
305 atom = strchrnul(*valuestart, ',');
306 *valuelen = atom - *valuestart;
307 } else if (*atom != ',' && *atom != '\0') {
308 /* key begins with "candidate" but has more chars */
309 return 0;
310 } else {
311 /* just "candidate" without "=val" */
312 *valuestart = NULL;
313 *valuelen = 0;
316 /* atom points at either the ',' or NUL after this key[=val] */
317 if (*atom == ',')
318 atom++;
319 else if (*atom)
320 BUG("Why is *atom not NULL yet?");
322 *end = atom;
323 return 1;
327 * Parse boolean option of name "candidate" in the option list "to_parse"
328 * of the form
330 * "candidate1[=bool1],candidate2[=bool2],candidate3[=bool3],..."
332 * The remaining part of "to_parse" is stored in "end" (if we are parsing
333 * the last candidate, then this is NULL) and the value (if given) is
334 * parsed and stored in "val", so "val" always points to either 0 or 1.
335 * If the value is not given, then "val" is set to point to 1.
337 * The boolean value is parsed using "git_parse_maybe_bool()", so the
338 * accepted values are
340 * to set true - "1", "yes", "true"
341 * to set false - "0", "no", "false"
343 * This function returns 1 on success. It returns 0 when we don't find
344 * an exact match for "candidate" or when the boolean value given is
345 * not valid.
347 static int match_atom_bool_arg(const char *to_parse, const char *candidate,
348 const char **end, int *val)
350 const char *argval;
351 char *strval;
352 size_t arglen;
353 int v;
355 if (!match_atom_arg_value(to_parse, candidate, end, &argval, &arglen))
356 return 0;
358 if (!argval) {
359 *val = 1;
360 return 1;
363 strval = xstrndup(argval, arglen);
364 v = git_parse_maybe_bool(strval);
365 free(strval);
367 if (v == -1)
368 return 0;
370 *val = v;
372 return 1;
375 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
376 const char *color_value, struct strbuf *err)
378 if (!color_value)
379 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
380 if (color_parse(color_value, atom->u.color) < 0)
381 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
382 color_value);
384 * We check this after we've parsed the color, which lets us complain
385 * about syntactically bogus color names even if they won't be used.
387 if (!want_color(format->use_color))
388 color_parse("", atom->u.color);
389 return 0;
392 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
393 const char *name, struct strbuf *err)
395 if (!arg)
396 atom->option = R_NORMAL;
397 else if (!strcmp(arg, "short"))
398 atom->option = R_SHORT;
399 else if (skip_prefix(arg, "lstrip=", &arg) ||
400 skip_prefix(arg, "strip=", &arg)) {
401 atom->option = R_LSTRIP;
402 if (strtol_i(arg, 10, &atom->lstrip))
403 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
404 } else if (skip_prefix(arg, "rstrip=", &arg)) {
405 atom->option = R_RSTRIP;
406 if (strtol_i(arg, 10, &atom->rstrip))
407 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
408 } else
409 return err_bad_arg(err, name, arg);
410 return 0;
413 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
414 struct used_atom *atom,
415 const char *arg, struct strbuf *err)
417 struct string_list params = STRING_LIST_INIT_DUP;
418 int i;
420 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
421 atom->u.remote_ref.push = 1;
423 if (!arg) {
424 atom->u.remote_ref.option = RR_REF;
425 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
426 arg, atom->name, err);
429 atom->u.remote_ref.nobracket = 0;
430 string_list_split(&params, arg, ',', -1);
432 for (i = 0; i < params.nr; i++) {
433 const char *s = params.items[i].string;
435 if (!strcmp(s, "track"))
436 atom->u.remote_ref.option = RR_TRACK;
437 else if (!strcmp(s, "trackshort"))
438 atom->u.remote_ref.option = RR_TRACKSHORT;
439 else if (!strcmp(s, "nobracket"))
440 atom->u.remote_ref.nobracket = 1;
441 else if (!strcmp(s, "remotename")) {
442 atom->u.remote_ref.option = RR_REMOTE_NAME;
443 atom->u.remote_ref.push_remote = 1;
444 } else if (!strcmp(s, "remoteref")) {
445 atom->u.remote_ref.option = RR_REMOTE_REF;
446 atom->u.remote_ref.push_remote = 1;
447 } else {
448 atom->u.remote_ref.option = RR_REF;
449 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
450 arg, atom->name, err)) {
451 string_list_clear(&params, 0);
452 return -1;
457 string_list_clear(&params, 0);
458 return 0;
461 static int objecttype_atom_parser(struct ref_format *format UNUSED,
462 struct used_atom *atom,
463 const char *arg, struct strbuf *err)
465 if (arg)
466 return err_no_arg(err, "objecttype");
467 if (*atom->name == '*')
468 oi_deref.info.typep = &oi_deref.type;
469 else
470 oi.info.typep = &oi.type;
471 return 0;
474 static int objectsize_atom_parser(struct ref_format *format UNUSED,
475 struct used_atom *atom,
476 const char *arg, struct strbuf *err)
478 if (!arg) {
479 atom->u.objectsize.option = O_SIZE;
480 if (*atom->name == '*')
481 oi_deref.info.sizep = &oi_deref.size;
482 else
483 oi.info.sizep = &oi.size;
484 } else if (!strcmp(arg, "disk")) {
485 atom->u.objectsize.option = O_SIZE_DISK;
486 if (*atom->name == '*')
487 oi_deref.info.disk_sizep = &oi_deref.disk_size;
488 else
489 oi.info.disk_sizep = &oi.disk_size;
490 } else
491 return err_bad_arg(err, "objectsize", arg);
492 return 0;
495 static int deltabase_atom_parser(struct ref_format *format UNUSED,
496 struct used_atom *atom,
497 const char *arg, struct strbuf *err)
499 if (arg)
500 return err_no_arg(err, "deltabase");
501 if (*atom->name == '*')
502 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
503 else
504 oi.info.delta_base_oid = &oi.delta_base_oid;
505 return 0;
508 static int body_atom_parser(struct ref_format *format UNUSED,
509 struct used_atom *atom,
510 const char *arg, struct strbuf *err)
512 if (arg)
513 return err_no_arg(err, "body");
514 atom->u.contents.option = C_BODY_DEP;
515 return 0;
518 static int subject_atom_parser(struct ref_format *format UNUSED,
519 struct used_atom *atom,
520 const char *arg, struct strbuf *err)
522 if (!arg)
523 atom->u.contents.option = C_SUB;
524 else if (!strcmp(arg, "sanitize"))
525 atom->u.contents.option = C_SUB_SANITIZE;
526 else
527 return err_bad_arg(err, "subject", arg);
528 return 0;
531 static int parse_signature_option(const char *arg)
533 if (!arg)
534 return S_BARE;
535 else if (!strcmp(arg, "signer"))
536 return S_SIGNER;
537 else if (!strcmp(arg, "grade"))
538 return S_GRADE;
539 else if (!strcmp(arg, "key"))
540 return S_KEY;
541 else if (!strcmp(arg, "fingerprint"))
542 return S_FINGERPRINT;
543 else if (!strcmp(arg, "primarykeyfingerprint"))
544 return S_PRI_KEY_FP;
545 else if (!strcmp(arg, "trustlevel"))
546 return S_TRUST_LEVEL;
547 return -1;
550 static int signature_atom_parser(struct ref_format *format UNUSED,
551 struct used_atom *atom,
552 const char *arg, struct strbuf *err)
554 int opt = parse_signature_option(arg);
555 if (opt < 0)
556 return err_bad_arg(err, "signature", arg);
557 atom->u.signature.option = opt;
558 return 0;
561 static int trailers_atom_parser(struct ref_format *format UNUSED,
562 struct used_atom *atom,
563 const char *arg, struct strbuf *err)
565 atom->u.contents.trailer_opts.no_divider = 1;
567 if (arg) {
568 const char *argbuf = xstrfmt("%s)", arg);
569 char *invalid_arg = NULL;
571 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
572 &ref_trailer_buf.filter_list,
573 &ref_trailer_buf.sepbuf,
574 &ref_trailer_buf.kvsepbuf,
575 &argbuf, &invalid_arg)) {
576 if (!invalid_arg)
577 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
578 else
579 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
580 free((char *)invalid_arg);
581 return -1;
584 atom->u.contents.option = C_TRAILERS;
585 return 0;
588 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
589 const char *arg, struct strbuf *err)
591 if (!arg)
592 atom->u.contents.option = C_BARE;
593 else if (!strcmp(arg, "body"))
594 atom->u.contents.option = C_BODY;
595 else if (!strcmp(arg, "size")) {
596 atom->type = FIELD_ULONG;
597 atom->u.contents.option = C_LENGTH;
598 } else if (!strcmp(arg, "signature"))
599 atom->u.contents.option = C_SIG;
600 else if (!strcmp(arg, "subject"))
601 atom->u.contents.option = C_SUB;
602 else if (!strcmp(arg, "trailers")) {
603 if (trailers_atom_parser(format, atom, NULL, err))
604 return -1;
605 } else if (skip_prefix(arg, "trailers:", &arg)) {
606 if (trailers_atom_parser(format, atom, arg, err))
607 return -1;
608 } else if (skip_prefix(arg, "lines=", &arg)) {
609 atom->u.contents.option = C_LINES;
610 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
611 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
612 } else
613 return err_bad_arg(err, "contents", arg);
614 return 0;
617 static int describe_atom_option_parser(struct strvec *args, const char **arg,
618 struct strbuf *err)
620 const char *argval;
621 size_t arglen = 0;
622 int optval = 0;
624 if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {
625 if (!optval)
626 strvec_push(args, "--no-tags");
627 else
628 strvec_push(args, "--tags");
629 return 1;
632 if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {
633 char *endptr;
635 if (!arglen)
636 return strbuf_addf_ret(err, -1,
637 _("argument expected for %s"),
638 "describe:abbrev");
639 if (strtol(argval, &endptr, 10) < 0)
640 return strbuf_addf_ret(err, -1,
641 _("positive value expected %s=%s"),
642 "describe:abbrev", argval);
643 if (endptr - argval != arglen)
644 return strbuf_addf_ret(err, -1,
645 _("cannot fully parse %s=%s"),
646 "describe:abbrev", argval);
648 strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);
649 return 1;
652 if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {
653 if (!arglen)
654 return strbuf_addf_ret(err, -1,
655 _("value expected %s="),
656 "describe:match");
658 strvec_pushf(args, "--match=%.*s", (int)arglen, argval);
659 return 1;
662 if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {
663 if (!arglen)
664 return strbuf_addf_ret(err, -1,
665 _("value expected %s="),
666 "describe:exclude");
668 strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);
669 return 1;
672 return 0;
675 static int describe_atom_parser(struct ref_format *format UNUSED,
676 struct used_atom *atom,
677 const char *arg, struct strbuf *err)
679 struct strvec args = STRVEC_INIT;
681 for (;;) {
682 int found = 0;
683 const char *bad_arg = arg;
685 if (!arg || !*arg)
686 break;
688 found = describe_atom_option_parser(&args, &arg, err);
689 if (found < 0)
690 return found;
691 if (!found)
692 return err_bad_arg(err, "describe", bad_arg);
694 atom->u.describe_args = strvec_detach(&args);
695 return 0;
698 static int raw_atom_parser(struct ref_format *format UNUSED,
699 struct used_atom *atom,
700 const char *arg, struct strbuf *err)
702 if (!arg)
703 atom->u.raw_data.option = RAW_BARE;
704 else if (!strcmp(arg, "size")) {
705 atom->type = FIELD_ULONG;
706 atom->u.raw_data.option = RAW_LENGTH;
707 } else
708 return err_bad_arg(err, "raw", arg);
709 return 0;
712 static int oid_atom_parser(struct ref_format *format UNUSED,
713 struct used_atom *atom,
714 const char *arg, struct strbuf *err)
716 if (!arg)
717 atom->u.oid.option = O_FULL;
718 else if (!strcmp(arg, "short"))
719 atom->u.oid.option = O_SHORT;
720 else if (skip_prefix(arg, "short=", &arg)) {
721 atom->u.oid.option = O_LENGTH;
722 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
723 atom->u.oid.length == 0)
724 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
725 if (atom->u.oid.length < MINIMUM_ABBREV)
726 atom->u.oid.length = MINIMUM_ABBREV;
727 } else
728 return err_bad_arg(err, atom->name, arg);
729 return 0;
732 static int person_name_atom_parser(struct ref_format *format UNUSED,
733 struct used_atom *atom,
734 const char *arg, struct strbuf *err)
736 if (!arg)
737 atom->u.name_option.option = N_RAW;
738 else if (!strcmp(arg, "mailmap"))
739 atom->u.name_option.option = N_MAILMAP;
740 else
741 return err_bad_arg(err, atom->name, arg);
742 return 0;
745 static int email_atom_option_parser(struct used_atom *atom,
746 const char **arg, struct strbuf *err)
748 if (!*arg)
749 return EO_RAW;
750 if (skip_prefix(*arg, "trim", arg))
751 return EO_TRIM;
752 if (skip_prefix(*arg, "localpart", arg))
753 return EO_LOCALPART;
754 if (skip_prefix(*arg, "mailmap", arg))
755 return EO_MAILMAP;
756 return -1;
759 static int person_email_atom_parser(struct ref_format *format UNUSED,
760 struct used_atom *atom,
761 const char *arg, struct strbuf *err)
763 for (;;) {
764 int opt = email_atom_option_parser(atom, &arg, err);
765 const char *bad_arg = arg;
767 if (opt < 0)
768 return err_bad_arg(err, atom->name, bad_arg);
769 atom->u.email_option.option |= opt;
771 if (!arg || !*arg)
772 break;
773 if (*arg == ',')
774 arg++;
775 else
776 return err_bad_arg(err, atom->name, bad_arg);
778 return 0;
781 static int refname_atom_parser(struct ref_format *format UNUSED,
782 struct used_atom *atom,
783 const char *arg, struct strbuf *err)
785 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
788 static align_type parse_align_position(const char *s)
790 if (!strcmp(s, "right"))
791 return ALIGN_RIGHT;
792 else if (!strcmp(s, "middle"))
793 return ALIGN_MIDDLE;
794 else if (!strcmp(s, "left"))
795 return ALIGN_LEFT;
796 return -1;
799 static int align_atom_parser(struct ref_format *format UNUSED,
800 struct used_atom *atom,
801 const char *arg, struct strbuf *err)
803 struct align *align = &atom->u.align;
804 struct string_list params = STRING_LIST_INIT_DUP;
805 int i;
806 unsigned int width = ~0U;
808 if (!arg)
809 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
811 align->position = ALIGN_LEFT;
813 string_list_split(&params, arg, ',', -1);
814 for (i = 0; i < params.nr; i++) {
815 const char *s = params.items[i].string;
816 int position;
818 if (skip_prefix(s, "position=", &s)) {
819 position = parse_align_position(s);
820 if (position < 0) {
821 strbuf_addf(err, _("unrecognized position:%s"), s);
822 string_list_clear(&params, 0);
823 return -1;
825 align->position = position;
826 } else if (skip_prefix(s, "width=", &s)) {
827 if (strtoul_ui(s, 10, &width)) {
828 strbuf_addf(err, _("unrecognized width:%s"), s);
829 string_list_clear(&params, 0);
830 return -1;
832 } else if (!strtoul_ui(s, 10, &width))
834 else if ((position = parse_align_position(s)) >= 0)
835 align->position = position;
836 else {
837 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
838 string_list_clear(&params, 0);
839 return -1;
843 if (width == ~0U) {
844 string_list_clear(&params, 0);
845 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
847 align->width = width;
848 string_list_clear(&params, 0);
849 return 0;
852 static int if_atom_parser(struct ref_format *format UNUSED,
853 struct used_atom *atom,
854 const char *arg, struct strbuf *err)
856 if (!arg) {
857 atom->u.if_then_else.cmp_status = COMPARE_NONE;
858 return 0;
859 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
860 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
861 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
862 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
863 } else
864 return err_bad_arg(err, "if", arg);
865 return 0;
868 static int rest_atom_parser(struct ref_format *format UNUSED,
869 struct used_atom *atom UNUSED,
870 const char *arg, struct strbuf *err)
872 if (arg)
873 return err_no_arg(err, "rest");
874 return 0;
877 static int ahead_behind_atom_parser(struct ref_format *format,
878 struct used_atom *atom UNUSED,
879 const char *arg, struct strbuf *err)
881 struct string_list_item *item;
883 if (!arg)
884 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
886 item = string_list_append(&format->bases, arg);
887 item->util = lookup_commit_reference_by_name(arg);
888 if (!item->util)
889 die("failed to find '%s'", arg);
891 return 0;
894 static int head_atom_parser(struct ref_format *format UNUSED,
895 struct used_atom *atom,
896 const char *arg, struct strbuf *err)
898 if (arg)
899 return err_no_arg(err, "HEAD");
900 atom->u.head = refs_resolve_refdup(get_main_ref_store(the_repository),
901 "HEAD", RESOLVE_REF_READING, NULL,
902 NULL);
903 return 0;
906 static struct {
907 const char *name;
908 info_source source;
909 cmp_type cmp_type;
910 int (*parser)(struct ref_format *format, struct used_atom *atom,
911 const char *arg, struct strbuf *err);
912 } valid_atom[] = {
913 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
914 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
915 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
916 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
917 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
918 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
919 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
920 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
921 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
922 [ATOM_TYPE] = { "type", SOURCE_OBJ },
923 [ATOM_TAG] = { "tag", SOURCE_OBJ },
924 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
925 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
926 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
927 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
928 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
929 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
930 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
931 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
932 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
933 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
934 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
935 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
936 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
937 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
938 [ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },
939 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
940 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
941 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
942 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
943 [ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },
944 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
945 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
946 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
947 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
948 [ATOM_FLAG] = { "flag", SOURCE_NONE },
949 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
950 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
951 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
952 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
953 [ATOM_END] = { "end", SOURCE_NONE },
954 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
955 [ATOM_THEN] = { "then", SOURCE_NONE },
956 [ATOM_ELSE] = { "else", SOURCE_NONE },
957 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
958 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
960 * Please update $__git_ref_fieldlist in git-completion.bash
961 * when you add new atoms
965 #define REF_FORMATTING_STATE_INIT { 0 }
967 struct ref_formatting_stack {
968 struct ref_formatting_stack *prev;
969 struct strbuf output;
970 void (*at_end)(struct ref_formatting_stack **stack);
971 void *at_end_data;
974 struct ref_formatting_state {
975 int quote_style;
976 struct ref_formatting_stack *stack;
979 struct atom_value {
980 const char *s;
981 ssize_t s_size;
982 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
983 struct strbuf *err);
984 uintmax_t value; /* used for sorting when not FIELD_STR */
985 struct used_atom *atom;
988 #define ATOM_SIZE_UNSPECIFIED (-1)
990 #define ATOM_VALUE_INIT { \
991 .s_size = ATOM_SIZE_UNSPECIFIED \
995 * Used to parse format string and sort specifiers
997 static int parse_ref_filter_atom(struct ref_format *format,
998 const char *atom, const char *ep,
999 struct strbuf *err)
1001 const char *sp;
1002 const char *arg;
1003 int i, at, atom_len;
1005 sp = atom;
1006 if (*sp == '*' && sp < ep)
1007 sp++; /* deref */
1008 if (ep <= sp)
1009 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
1010 (int)(ep-atom), atom);
1013 * If the atom name has a colon, strip it and everything after
1014 * it off - it specifies the format for this entry, and
1015 * shouldn't be used for checking against the valid_atom
1016 * table.
1018 arg = memchr(sp, ':', ep - sp);
1019 atom_len = (arg ? arg : ep) - sp;
1021 /* Do we have the atom already used elsewhere? */
1022 for (i = 0; i < used_atom_cnt; i++) {
1023 int len = strlen(used_atom[i].name);
1024 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
1025 return i;
1028 /* Is the atom a valid one? */
1029 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
1030 int len = strlen(valid_atom[i].name);
1031 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
1032 break;
1035 if (ARRAY_SIZE(valid_atom) <= i)
1036 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
1037 (int)(ep-atom), atom);
1038 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
1039 return strbuf_addf_ret(err, -1,
1040 _("not a git repository, but the field '%.*s' requires access to object data"),
1041 (int)(ep-atom), atom);
1043 /* Add it in, including the deref prefix */
1044 at = used_atom_cnt;
1045 used_atom_cnt++;
1046 REALLOC_ARRAY(used_atom, used_atom_cnt);
1047 used_atom[at].atom_type = i;
1048 used_atom[at].name = xmemdupz(atom, ep - atom);
1049 used_atom[at].type = valid_atom[i].cmp_type;
1050 used_atom[at].source = valid_atom[i].source;
1051 if (used_atom[at].source == SOURCE_OBJ) {
1052 if (*atom == '*')
1053 oi_deref.info.contentp = &oi_deref.content;
1054 else
1055 oi.info.contentp = &oi.content;
1057 if (arg) {
1058 arg = used_atom[at].name + (arg - atom) + 1;
1059 if (!*arg) {
1061 * Treat empty sub-arguments list as NULL (i.e.,
1062 * "%(atom:)" is equivalent to "%(atom)").
1064 arg = NULL;
1067 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
1068 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
1069 return -1;
1070 if (*atom == '*')
1071 need_tagged = 1;
1072 if (i == ATOM_SYMREF)
1073 need_symref = 1;
1074 return at;
1077 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
1079 switch (quote_style) {
1080 case QUOTE_NONE:
1081 if (len < 0)
1082 strbuf_addstr(s, str);
1083 else
1084 strbuf_add(s, str, len);
1085 break;
1086 case QUOTE_SHELL:
1087 sq_quote_buf(s, str);
1088 break;
1089 case QUOTE_PERL:
1090 if (len < 0)
1091 perl_quote_buf(s, str);
1092 else
1093 perl_quote_buf_with_len(s, str, len);
1094 break;
1095 case QUOTE_PYTHON:
1096 python_quote_buf(s, str);
1097 break;
1098 case QUOTE_TCL:
1099 tcl_quote_buf(s, str);
1100 break;
1104 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
1105 struct strbuf *err UNUSED)
1108 * Quote formatting is only done when the stack has a single
1109 * element. Otherwise quote formatting is done on the
1110 * element's entire output strbuf when the %(end) atom is
1111 * encountered.
1113 if (!state->stack->prev)
1114 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
1115 else if (v->s_size < 0)
1116 strbuf_addstr(&state->stack->output, v->s);
1117 else
1118 strbuf_add(&state->stack->output, v->s, v->s_size);
1119 return 0;
1122 static void push_stack_element(struct ref_formatting_stack **stack)
1124 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
1126 strbuf_init(&s->output, 0);
1127 s->prev = *stack;
1128 *stack = s;
1131 static void pop_stack_element(struct ref_formatting_stack **stack)
1133 struct ref_formatting_stack *current = *stack;
1134 struct ref_formatting_stack *prev = current->prev;
1136 if (prev)
1137 strbuf_addbuf(&prev->output, &current->output);
1138 strbuf_release(&current->output);
1139 free(current);
1140 *stack = prev;
1143 static void end_align_handler(struct ref_formatting_stack **stack)
1145 struct ref_formatting_stack *cur = *stack;
1146 struct align *align = (struct align *)cur->at_end_data;
1147 struct strbuf s = STRBUF_INIT;
1149 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
1150 strbuf_swap(&cur->output, &s);
1151 strbuf_release(&s);
1154 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1155 struct strbuf *err UNUSED)
1157 struct ref_formatting_stack *new_stack;
1159 push_stack_element(&state->stack);
1160 new_stack = state->stack;
1161 new_stack->at_end = end_align_handler;
1162 new_stack->at_end_data = &atomv->atom->u.align;
1163 return 0;
1166 static void if_then_else_handler(struct ref_formatting_stack **stack)
1168 struct ref_formatting_stack *cur = *stack;
1169 struct ref_formatting_stack *prev = cur->prev;
1170 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
1172 if (!if_then_else->then_atom_seen)
1173 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
1175 if (if_then_else->else_atom_seen) {
1177 * There is an %(else) atom: we need to drop one state from the
1178 * stack, either the %(else) branch if the condition is satisfied, or
1179 * the %(then) branch if it isn't.
1181 if (if_then_else->condition_satisfied) {
1182 strbuf_reset(&cur->output);
1183 pop_stack_element(&cur);
1184 } else {
1185 strbuf_swap(&cur->output, &prev->output);
1186 strbuf_reset(&cur->output);
1187 pop_stack_element(&cur);
1189 } else if (!if_then_else->condition_satisfied) {
1191 * No %(else) atom: just drop the %(then) branch if the
1192 * condition is not satisfied.
1194 strbuf_reset(&cur->output);
1197 *stack = cur;
1198 free(if_then_else);
1201 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1202 struct strbuf *err UNUSED)
1204 struct ref_formatting_stack *new_stack;
1205 struct if_then_else *if_then_else = xcalloc(1,
1206 sizeof(struct if_then_else));
1208 if_then_else->str = atomv->atom->u.if_then_else.str;
1209 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
1211 push_stack_element(&state->stack);
1212 new_stack = state->stack;
1213 new_stack->at_end = if_then_else_handler;
1214 new_stack->at_end_data = if_then_else;
1215 return 0;
1218 static int is_empty(struct strbuf *buf)
1220 const char *cur = buf->buf;
1221 const char *end = buf->buf + buf->len;
1223 while (cur != end && (isspace(*cur)))
1224 cur++;
1226 return cur == end;
1229 static int then_atom_handler(struct atom_value *atomv UNUSED,
1230 struct ref_formatting_state *state,
1231 struct strbuf *err)
1233 struct ref_formatting_stack *cur = state->stack;
1234 struct if_then_else *if_then_else = NULL;
1235 size_t str_len = 0;
1237 if (cur->at_end == if_then_else_handler)
1238 if_then_else = (struct if_then_else *)cur->at_end_data;
1239 if (!if_then_else)
1240 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
1241 if (if_then_else->then_atom_seen)
1242 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
1243 if (if_then_else->else_atom_seen)
1244 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
1245 if_then_else->then_atom_seen = 1;
1246 if (if_then_else->str)
1247 str_len = strlen(if_then_else->str);
1249 * If the 'equals' or 'notequals' attribute is used then
1250 * perform the required comparison. If not, only non-empty
1251 * strings satisfy the 'if' condition.
1253 if (if_then_else->cmp_status == COMPARE_EQUAL) {
1254 if (str_len == cur->output.len &&
1255 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1256 if_then_else->condition_satisfied = 1;
1257 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
1258 if (str_len != cur->output.len ||
1259 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1260 if_then_else->condition_satisfied = 1;
1261 } else if (cur->output.len && !is_empty(&cur->output))
1262 if_then_else->condition_satisfied = 1;
1263 strbuf_reset(&cur->output);
1264 return 0;
1267 static int else_atom_handler(struct atom_value *atomv UNUSED,
1268 struct ref_formatting_state *state,
1269 struct strbuf *err)
1271 struct ref_formatting_stack *prev = state->stack;
1272 struct if_then_else *if_then_else = NULL;
1274 if (prev->at_end == if_then_else_handler)
1275 if_then_else = (struct if_then_else *)prev->at_end_data;
1276 if (!if_then_else)
1277 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1278 if (!if_then_else->then_atom_seen)
1279 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1280 if (if_then_else->else_atom_seen)
1281 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1282 if_then_else->else_atom_seen = 1;
1283 push_stack_element(&state->stack);
1284 state->stack->at_end_data = prev->at_end_data;
1285 state->stack->at_end = prev->at_end;
1286 return 0;
1289 static int end_atom_handler(struct atom_value *atomv UNUSED,
1290 struct ref_formatting_state *state,
1291 struct strbuf *err)
1293 struct ref_formatting_stack *current = state->stack;
1294 struct strbuf s = STRBUF_INIT;
1296 if (!current->at_end)
1297 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1298 current->at_end(&state->stack);
1300 /* Stack may have been popped within at_end(), hence reset the current pointer */
1301 current = state->stack;
1304 * Perform quote formatting when the stack element is that of
1305 * a supporting atom. If nested then perform quote formatting
1306 * only on the topmost supporting atom.
1308 if (!current->prev->prev) {
1309 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1310 strbuf_swap(&current->output, &s);
1312 strbuf_release(&s);
1313 pop_stack_element(&state->stack);
1314 return 0;
1318 * In a format string, find the next occurrence of %(atom).
1320 static const char *find_next(const char *cp)
1322 while (*cp) {
1323 if (*cp == '%') {
1325 * %( is the start of an atom;
1326 * %% is a quoted per-cent.
1328 if (cp[1] == '(')
1329 return cp;
1330 else if (cp[1] == '%')
1331 cp++; /* skip over two % */
1332 /* otherwise this is a singleton, literal % */
1334 cp++;
1336 return NULL;
1339 static int reject_atom(enum atom_type atom_type)
1341 return atom_type == ATOM_REST;
1345 * Make sure the format string is well formed, and parse out
1346 * the used atoms.
1348 int verify_ref_format(struct ref_format *format)
1350 const char *cp, *sp;
1352 format->need_color_reset_at_eol = 0;
1353 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1354 struct strbuf err = STRBUF_INIT;
1355 const char *color, *ep = strchr(sp, ')');
1356 int at;
1358 if (!ep)
1359 return error(_("malformed format string %s"), sp);
1360 /* sp points at "%(" and ep points at the closing ")" */
1361 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1362 if (at < 0)
1363 die("%s", err.buf);
1364 if (reject_atom(used_atom[at].atom_type))
1365 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1367 if ((format->quote_style == QUOTE_PYTHON ||
1368 format->quote_style == QUOTE_SHELL ||
1369 format->quote_style == QUOTE_TCL) &&
1370 used_atom[at].atom_type == ATOM_RAW &&
1371 used_atom[at].u.raw_data.option == RAW_BARE)
1372 die(_("--format=%.*s cannot be used with "
1373 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1374 cp = ep + 1;
1376 if (skip_prefix(used_atom[at].name, "color:", &color))
1377 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1378 strbuf_release(&err);
1380 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1381 format->need_color_reset_at_eol = 0;
1382 return 0;
1385 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1386 struct used_atom *atom)
1388 switch (atom->u.oid.option) {
1389 case O_FULL:
1390 return oid_to_hex(oid);
1391 case O_LENGTH:
1392 return repo_find_unique_abbrev(the_repository, oid,
1393 atom->u.oid.length);
1394 case O_SHORT:
1395 return repo_find_unique_abbrev(the_repository, oid,
1396 DEFAULT_ABBREV);
1397 default:
1398 BUG("unknown %%(%s) option", field);
1402 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1403 struct atom_value *v, struct used_atom *atom)
1405 if (starts_with(name, field)) {
1406 v->s = xstrdup(do_grab_oid(field, oid, atom));
1407 return 1;
1409 return 0;
1412 /* See grab_values */
1413 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1415 int i;
1417 for (i = 0; i < used_atom_cnt; i++) {
1418 const char *name = used_atom[i].name;
1419 enum atom_type atom_type = used_atom[i].atom_type;
1420 struct atom_value *v = &val[i];
1421 if (!!deref != (*name == '*'))
1422 continue;
1423 if (deref)
1424 name++;
1425 if (atom_type == ATOM_OBJECTTYPE)
1426 v->s = xstrdup(type_name(oi->type));
1427 else if (atom_type == ATOM_OBJECTSIZE) {
1428 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1429 v->value = oi->disk_size;
1430 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1431 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1432 v->value = oi->size;
1433 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1435 } else if (atom_type == ATOM_DELTABASE)
1436 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1437 else if (atom_type == ATOM_OBJECTNAME && deref)
1438 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1442 /* See grab_values */
1443 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1445 int i;
1446 struct tag *tag = (struct tag *) obj;
1448 for (i = 0; i < used_atom_cnt; i++) {
1449 const char *name = used_atom[i].name;
1450 enum atom_type atom_type = used_atom[i].atom_type;
1451 struct atom_value *v = &val[i];
1452 if (!!deref != (*name == '*'))
1453 continue;
1454 if (deref)
1455 name++;
1456 if (atom_type == ATOM_TAG)
1457 v->s = xstrdup(tag->tag);
1458 else if (atom_type == ATOM_TYPE && tag->tagged)
1459 v->s = xstrdup(type_name(tag->tagged->type));
1460 else if (atom_type == ATOM_OBJECT && tag->tagged)
1461 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1465 /* See grab_values */
1466 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1468 int i;
1469 struct commit *commit = (struct commit *) obj;
1471 for (i = 0; i < used_atom_cnt; i++) {
1472 const char *name = used_atom[i].name;
1473 enum atom_type atom_type = used_atom[i].atom_type;
1474 struct atom_value *v = &val[i];
1475 if (!!deref != (*name == '*'))
1476 continue;
1477 if (deref)
1478 name++;
1479 if (atom_type == ATOM_TREE &&
1480 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1481 continue;
1482 if (atom_type == ATOM_NUMPARENT) {
1483 v->value = commit_list_count(commit->parents);
1484 v->s = xstrfmt("%lu", (unsigned long)v->value);
1486 else if (atom_type == ATOM_PARENT) {
1487 struct commit_list *parents;
1488 struct strbuf s = STRBUF_INIT;
1489 for (parents = commit->parents; parents; parents = parents->next) {
1490 struct object_id *oid = &parents->item->object.oid;
1491 if (parents != commit->parents)
1492 strbuf_addch(&s, ' ');
1493 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1495 v->s = strbuf_detach(&s, NULL);
1500 static const char *find_wholine(const char *who, int wholen, const char *buf)
1502 const char *eol;
1503 while (*buf) {
1504 if (!strncmp(buf, who, wholen) &&
1505 buf[wholen] == ' ')
1506 return buf + wholen + 1;
1507 eol = strchr(buf, '\n');
1508 if (!eol)
1509 return "";
1510 eol++;
1511 if (*eol == '\n')
1512 return ""; /* end of header */
1513 buf = eol;
1515 return "";
1518 static const char *copy_line(const char *buf)
1520 const char *eol = strchrnul(buf, '\n');
1521 return xmemdupz(buf, eol - buf);
1524 static const char *copy_name(const char *buf)
1526 const char *cp;
1527 for (cp = buf; *cp && *cp != '\n'; cp++) {
1528 if (starts_with(cp, " <"))
1529 return xmemdupz(buf, cp - buf);
1531 return xstrdup("");
1534 static const char *find_end_of_email(const char *email, int opt)
1536 const char *eoemail;
1538 if (opt & EO_LOCALPART) {
1539 eoemail = strchr(email, '@');
1540 if (eoemail)
1541 return eoemail;
1542 return strchr(email, '>');
1545 if (opt & EO_TRIM)
1546 return strchr(email, '>');
1549 * The option here is either the raw email option or the raw
1550 * mailmap option (that is EO_RAW or EO_MAILMAP). In such cases,
1551 * we directly grab the whole email including the closing
1552 * angle brackets.
1554 * If EO_MAILMAP was set with any other option (that is either
1555 * EO_TRIM or EO_LOCALPART), we already grab the end of email
1556 * above.
1558 eoemail = strchr(email, '>');
1559 if (eoemail)
1560 eoemail++;
1561 return eoemail;
1564 static const char *copy_email(const char *buf, struct used_atom *atom)
1566 const char *email = strchr(buf, '<');
1567 const char *eoemail;
1568 int opt = atom->u.email_option.option;
1570 if (!email)
1571 return xstrdup("");
1573 if (opt & (EO_LOCALPART | EO_TRIM))
1574 email++;
1576 eoemail = find_end_of_email(email, opt);
1577 if (!eoemail)
1578 return xstrdup("");
1579 return xmemdupz(email, eoemail - email);
1582 static char *copy_subject(const char *buf, unsigned long len)
1584 struct strbuf sb = STRBUF_INIT;
1585 int i;
1587 for (i = 0; i < len; i++) {
1588 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1589 continue; /* ignore CR in CRLF */
1591 if (buf[i] == '\n')
1592 strbuf_addch(&sb, ' ');
1593 else
1594 strbuf_addch(&sb, buf[i]);
1596 return strbuf_detach(&sb, NULL);
1599 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1601 const char *eoemail = strstr(buf, "> ");
1602 char *zone;
1603 timestamp_t timestamp;
1604 long tz;
1605 struct date_mode date_mode = DATE_MODE_INIT;
1606 const char *formatp;
1609 * We got here because atomname ends in "date" or "date<something>";
1610 * it's not possible that <something> is not ":<format>" because
1611 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1612 * ":" means no format is specified, and use the default.
1614 formatp = strchr(atomname, ':');
1615 if (formatp) {
1616 formatp++;
1617 parse_date_format(formatp, &date_mode);
1620 * If this is a sort field and a format was specified, we'll
1621 * want to compare formatted date by string value.
1623 v->atom->type = FIELD_STR;
1626 if (!eoemail)
1627 goto bad;
1628 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1629 if (timestamp == TIME_MAX)
1630 goto bad;
1631 tz = strtol(zone, NULL, 10);
1632 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1633 goto bad;
1634 v->s = xstrdup(show_date(timestamp, tz, date_mode));
1635 v->value = timestamp;
1636 date_mode_release(&date_mode);
1637 return;
1638 bad:
1639 v->s = xstrdup("");
1640 v->value = 0;
1643 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
1645 /* See grab_values */
1646 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1648 int i;
1649 int wholen = strlen(who);
1650 const char *wholine = NULL;
1651 const char *headers[] = { "author ", "committer ",
1652 "tagger ", NULL };
1654 for (i = 0; i < used_atom_cnt; i++) {
1655 struct used_atom *atom = &used_atom[i];
1656 const char *name = atom->name;
1657 struct atom_value *v = &val[i];
1658 struct strbuf mailmap_buf = STRBUF_INIT;
1660 if (!!deref != (*name == '*'))
1661 continue;
1662 if (deref)
1663 name++;
1664 if (strncmp(who, name, wholen))
1665 continue;
1666 if (name[wholen] != 0 &&
1667 !starts_with(name + wholen, "name") &&
1668 !starts_with(name + wholen, "email") &&
1669 !starts_with(name + wholen, "date"))
1670 continue;
1672 if ((starts_with(name + wholen, "name") &&
1673 (atom->u.name_option.option == N_MAILMAP)) ||
1674 (starts_with(name + wholen, "email") &&
1675 (atom->u.email_option.option & EO_MAILMAP))) {
1676 if (!mailmap.items)
1677 read_mailmap(&mailmap);
1678 strbuf_addstr(&mailmap_buf, buf);
1679 apply_mailmap_to_header(&mailmap_buf, headers, &mailmap);
1680 wholine = find_wholine(who, wholen, mailmap_buf.buf);
1681 } else {
1682 wholine = find_wholine(who, wholen, buf);
1685 if (!wholine)
1686 return; /* no point looking for it */
1687 if (name[wholen] == 0)
1688 v->s = copy_line(wholine);
1689 else if (starts_with(name + wholen, "name"))
1690 v->s = copy_name(wholine);
1691 else if (starts_with(name + wholen, "email"))
1692 v->s = copy_email(wholine, &used_atom[i]);
1693 else if (starts_with(name + wholen, "date"))
1694 grab_date(wholine, v, name);
1696 strbuf_release(&mailmap_buf);
1700 * For a tag or a commit object, if "creator" or "creatordate" is
1701 * requested, do something special.
1703 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1704 return; /* "author" for commit object is not wanted */
1705 if (!wholine)
1706 wholine = find_wholine(who, wholen, buf);
1707 if (!wholine)
1708 return;
1709 for (i = 0; i < used_atom_cnt; i++) {
1710 const char *name = used_atom[i].name;
1711 enum atom_type atom_type = used_atom[i].atom_type;
1712 struct atom_value *v = &val[i];
1713 if (!!deref != (*name == '*'))
1714 continue;
1715 if (deref)
1716 name++;
1718 if (atom_type == ATOM_CREATORDATE)
1719 grab_date(wholine, v, name);
1720 else if (atom_type == ATOM_CREATOR)
1721 v->s = copy_line(wholine);
1725 static void grab_signature(struct atom_value *val, int deref, struct object *obj)
1727 int i;
1728 struct commit *commit = (struct commit *) obj;
1729 struct signature_check sigc = { 0 };
1730 int signature_checked = 0;
1732 for (i = 0; i < used_atom_cnt; i++) {
1733 struct used_atom *atom = &used_atom[i];
1734 const char *name = atom->name;
1735 struct atom_value *v = &val[i];
1736 int opt;
1738 if (!!deref != (*name == '*'))
1739 continue;
1740 if (deref)
1741 name++;
1743 if (!skip_prefix(name, "signature", &name) ||
1744 (*name && *name != ':'))
1745 continue;
1746 if (!*name)
1747 name = NULL;
1748 else
1749 name++;
1751 opt = parse_signature_option(name);
1752 if (opt < 0)
1753 continue;
1755 if (!signature_checked) {
1756 check_commit_signature(commit, &sigc);
1757 signature_checked = 1;
1760 switch (opt) {
1761 case S_BARE:
1762 v->s = xstrdup(sigc.output ? sigc.output: "");
1763 break;
1764 case S_SIGNER:
1765 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1766 break;
1767 case S_GRADE:
1768 switch (sigc.result) {
1769 case 'G':
1770 switch (sigc.trust_level) {
1771 case TRUST_UNDEFINED:
1772 case TRUST_NEVER:
1773 v->s = xstrfmt("%c", (char)'U');
1774 break;
1775 default:
1776 v->s = xstrfmt("%c", (char)'G');
1777 break;
1779 break;
1780 case 'B':
1781 case 'E':
1782 case 'N':
1783 case 'X':
1784 case 'Y':
1785 case 'R':
1786 v->s = xstrfmt("%c", (char)sigc.result);
1787 break;
1789 break;
1790 case S_KEY:
1791 v->s = xstrdup(sigc.key ? sigc.key : "");
1792 break;
1793 case S_FINGERPRINT:
1794 v->s = xstrdup(sigc.fingerprint ?
1795 sigc.fingerprint : "");
1796 break;
1797 case S_PRI_KEY_FP:
1798 v->s = xstrdup(sigc.primary_key_fingerprint ?
1799 sigc.primary_key_fingerprint : "");
1800 break;
1801 case S_TRUST_LEVEL:
1802 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1803 break;
1807 if (signature_checked)
1808 signature_check_clear(&sigc);
1811 static void find_subpos(const char *buf,
1812 const char **sub, size_t *sublen,
1813 const char **body, size_t *bodylen,
1814 size_t *nonsiglen,
1815 const char **sig, size_t *siglen)
1817 struct strbuf payload = STRBUF_INIT;
1818 struct strbuf signature = STRBUF_INIT;
1819 const char *eol;
1820 const char *end = buf + strlen(buf);
1821 const char *sigstart;
1823 /* parse signature first; we might not even have a subject line */
1824 parse_signature(buf, end - buf, &payload, &signature);
1825 strbuf_release(&payload);
1827 /* skip past header until we hit empty line */
1828 while (*buf && *buf != '\n') {
1829 eol = strchrnul(buf, '\n');
1830 if (*eol)
1831 eol++;
1832 buf = eol;
1834 /* skip any empty lines */
1835 while (*buf == '\n')
1836 buf++;
1837 *sig = strbuf_detach(&signature, siglen);
1838 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1840 /* subject is first non-empty line */
1841 *sub = buf;
1842 /* subject goes to first empty line before signature begins */
1843 if ((eol = strstr(*sub, "\n\n")) ||
1844 (eol = strstr(*sub, "\r\n\r\n"))) {
1845 eol = eol < sigstart ? eol : sigstart;
1846 } else {
1847 /* treat whole message as subject */
1848 eol = sigstart;
1850 buf = eol;
1851 *sublen = buf - *sub;
1852 /* drop trailing newline, if present */
1853 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1854 (*sub)[*sublen - 1] == '\r'))
1855 *sublen -= 1;
1857 /* skip any empty lines */
1858 while (*buf == '\n' || *buf == '\r')
1859 buf++;
1860 *body = buf;
1861 *bodylen = strlen(buf);
1862 *nonsiglen = sigstart - buf;
1866 * If 'lines' is greater than 0, append that many lines from the given
1867 * 'buf' of length 'size' to the given strbuf.
1869 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1871 int i;
1872 const char *sp, *eol;
1873 size_t len;
1875 sp = buf;
1877 for (i = 0; i < lines && sp < buf + size; i++) {
1878 if (i)
1879 strbuf_addstr(out, "\n ");
1880 eol = memchr(sp, '\n', size - (sp - buf));
1881 len = eol ? eol - sp : size - (sp - buf);
1882 strbuf_add(out, sp, len);
1883 if (!eol)
1884 break;
1885 sp = eol + 1;
1889 static void grab_describe_values(struct atom_value *val, int deref,
1890 struct object *obj)
1892 struct commit *commit = (struct commit *)obj;
1893 int i;
1895 for (i = 0; i < used_atom_cnt; i++) {
1896 struct used_atom *atom = &used_atom[i];
1897 enum atom_type type = atom->atom_type;
1898 const char *name = atom->name;
1899 struct atom_value *v = &val[i];
1901 struct child_process cmd = CHILD_PROCESS_INIT;
1902 struct strbuf out = STRBUF_INIT;
1903 struct strbuf err = STRBUF_INIT;
1905 if (type != ATOM_DESCRIBE)
1906 continue;
1908 if (!!deref != (*name == '*'))
1909 continue;
1911 cmd.git_cmd = 1;
1912 strvec_push(&cmd.args, "describe");
1913 strvec_pushv(&cmd.args, atom->u.describe_args);
1914 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1915 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
1916 error(_("failed to run 'describe'"));
1917 v->s = xstrdup("");
1918 continue;
1920 strbuf_rtrim(&out);
1921 v->s = strbuf_detach(&out, NULL);
1923 strbuf_release(&err);
1927 /* See grab_values */
1928 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1930 int i;
1931 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1932 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1933 void *buf = data->content;
1935 for (i = 0; i < used_atom_cnt; i++) {
1936 struct used_atom *atom = &used_atom[i];
1937 const char *name = atom->name;
1938 struct atom_value *v = &val[i];
1939 enum atom_type atom_type = atom->atom_type;
1941 if (!!deref != (*name == '*'))
1942 continue;
1943 if (deref)
1944 name++;
1946 if (atom_type == ATOM_RAW) {
1947 unsigned long buf_size = data->size;
1949 if (atom->u.raw_data.option == RAW_BARE) {
1950 v->s = xmemdupz(buf, buf_size);
1951 v->s_size = buf_size;
1952 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1953 v->value = buf_size;
1954 v->s = xstrfmt("%"PRIuMAX, v->value);
1956 continue;
1959 if ((data->type != OBJ_TAG &&
1960 data->type != OBJ_COMMIT) ||
1961 (strcmp(name, "body") &&
1962 !starts_with(name, "subject") &&
1963 !starts_with(name, "trailers") &&
1964 !starts_with(name, "contents")))
1965 continue;
1966 if (!subpos)
1967 find_subpos(buf,
1968 &subpos, &sublen,
1969 &bodypos, &bodylen, &nonsiglen,
1970 &sigpos, &siglen);
1972 if (atom->u.contents.option == C_SUB)
1973 v->s = copy_subject(subpos, sublen);
1974 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1975 struct strbuf sb = STRBUF_INIT;
1976 format_sanitized_subject(&sb, subpos, sublen);
1977 v->s = strbuf_detach(&sb, NULL);
1978 } else if (atom->u.contents.option == C_BODY_DEP)
1979 v->s = xmemdupz(bodypos, bodylen);
1980 else if (atom->u.contents.option == C_LENGTH) {
1981 v->value = strlen(subpos);
1982 v->s = xstrfmt("%"PRIuMAX, v->value);
1983 } else if (atom->u.contents.option == C_BODY)
1984 v->s = xmemdupz(bodypos, nonsiglen);
1985 else if (atom->u.contents.option == C_SIG)
1986 v->s = xmemdupz(sigpos, siglen);
1987 else if (atom->u.contents.option == C_LINES) {
1988 struct strbuf s = STRBUF_INIT;
1989 const char *contents_end = bodypos + nonsiglen;
1991 /* Size is the length of the message after removing the signature */
1992 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1993 v->s = strbuf_detach(&s, NULL);
1994 } else if (atom->u.contents.option == C_TRAILERS) {
1995 struct strbuf s = STRBUF_INIT;
1997 /* Format the trailer info according to the trailer_opts given */
1998 format_trailers_from_commit(&atom->u.contents.trailer_opts, subpos, &s);
2000 v->s = strbuf_detach(&s, NULL);
2001 } else if (atom->u.contents.option == C_BARE)
2002 v->s = xstrdup(subpos);
2005 free((void *)sigpos);
2009 * We want to have empty print-string for field requests
2010 * that do not apply (e.g. "authordate" for a tag object)
2012 static void fill_missing_values(struct atom_value *val)
2014 int i;
2015 for (i = 0; i < used_atom_cnt; i++) {
2016 struct atom_value *v = &val[i];
2017 if (!v->s)
2018 v->s = xstrdup("");
2023 * val is a list of atom_value to hold returned values. Extract
2024 * the values for atoms in used_atom array out of (obj, buf, sz).
2025 * when deref is false, (obj, buf, sz) is the object that is
2026 * pointed at by the ref itself; otherwise it is the object the
2027 * ref (which is a tag) refers to.
2029 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
2031 void *buf = data->content;
2033 switch (obj->type) {
2034 case OBJ_TAG:
2035 grab_tag_values(val, deref, obj);
2036 grab_sub_body_contents(val, deref, data);
2037 grab_person("tagger", val, deref, buf);
2038 grab_describe_values(val, deref, obj);
2039 break;
2040 case OBJ_COMMIT:
2041 grab_commit_values(val, deref, obj);
2042 grab_sub_body_contents(val, deref, data);
2043 grab_person("author", val, deref, buf);
2044 grab_person("committer", val, deref, buf);
2045 grab_signature(val, deref, obj);
2046 grab_describe_values(val, deref, obj);
2047 break;
2048 case OBJ_TREE:
2049 /* grab_tree_values(val, deref, obj, buf, sz); */
2050 grab_sub_body_contents(val, deref, data);
2051 break;
2052 case OBJ_BLOB:
2053 /* grab_blob_values(val, deref, obj, buf, sz); */
2054 grab_sub_body_contents(val, deref, data);
2055 break;
2056 default:
2057 die("Eh? Object of type %d?", obj->type);
2061 static inline char *copy_advance(char *dst, const char *src)
2063 while (*src)
2064 *dst++ = *src++;
2065 return dst;
2068 static const char *lstrip_ref_components(const char *refname, int len)
2070 long remaining = len;
2071 const char *start = xstrdup(refname);
2072 const char *to_free = start;
2074 if (len < 0) {
2075 int i;
2076 const char *p = refname;
2078 /* Find total no of '/' separated path-components */
2079 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2082 * The number of components we need to strip is now
2083 * the total minus the components to be left (Plus one
2084 * because we count the number of '/', but the number
2085 * of components is one more than the no of '/').
2087 remaining = i + len + 1;
2090 while (remaining > 0) {
2091 switch (*start++) {
2092 case '\0':
2093 free((char *)to_free);
2094 return xstrdup("");
2095 case '/':
2096 remaining--;
2097 break;
2101 start = xstrdup(start);
2102 free((char *)to_free);
2103 return start;
2106 static const char *rstrip_ref_components(const char *refname, int len)
2108 long remaining = len;
2109 const char *start = xstrdup(refname);
2110 const char *to_free = start;
2112 if (len < 0) {
2113 int i;
2114 const char *p = refname;
2116 /* Find total no of '/' separated path-components */
2117 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2120 * The number of components we need to strip is now
2121 * the total minus the components to be left (Plus one
2122 * because we count the number of '/', but the number
2123 * of components is one more than the no of '/').
2125 remaining = i + len + 1;
2128 while (remaining-- > 0) {
2129 char *p = strrchr(start, '/');
2130 if (!p) {
2131 free((char *)to_free);
2132 return xstrdup("");
2133 } else
2134 p[0] = '\0';
2136 return start;
2139 static const char *show_ref(struct refname_atom *atom, const char *refname)
2141 if (atom->option == R_SHORT)
2142 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2143 refname,
2144 warn_ambiguous_refs);
2145 else if (atom->option == R_LSTRIP)
2146 return lstrip_ref_components(refname, atom->lstrip);
2147 else if (atom->option == R_RSTRIP)
2148 return rstrip_ref_components(refname, atom->rstrip);
2149 else
2150 return xstrdup(refname);
2153 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2154 struct branch *branch, const char **s)
2156 int num_ours, num_theirs;
2157 if (atom->u.remote_ref.option == RR_REF)
2158 *s = show_ref(&atom->u.remote_ref.refname, refname);
2159 else if (atom->u.remote_ref.option == RR_TRACK) {
2160 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2161 NULL, atom->u.remote_ref.push,
2162 AHEAD_BEHIND_FULL) < 0) {
2163 *s = xstrdup(msgs.gone);
2164 } else if (!num_ours && !num_theirs)
2165 *s = xstrdup("");
2166 else if (!num_ours)
2167 *s = xstrfmt(msgs.behind, num_theirs);
2168 else if (!num_theirs)
2169 *s = xstrfmt(msgs.ahead, num_ours);
2170 else
2171 *s = xstrfmt(msgs.ahead_behind,
2172 num_ours, num_theirs);
2173 if (!atom->u.remote_ref.nobracket && *s[0]) {
2174 const char *to_free = *s;
2175 *s = xstrfmt("[%s]", *s);
2176 free((void *)to_free);
2178 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2179 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2180 NULL, atom->u.remote_ref.push,
2181 AHEAD_BEHIND_FULL) < 0) {
2182 *s = xstrdup("");
2183 return;
2185 if (!num_ours && !num_theirs)
2186 *s = xstrdup("=");
2187 else if (!num_ours)
2188 *s = xstrdup("<");
2189 else if (!num_theirs)
2190 *s = xstrdup(">");
2191 else
2192 *s = xstrdup("<>");
2193 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2194 int explicit;
2195 const char *remote = atom->u.remote_ref.push ?
2196 pushremote_for_branch(branch, &explicit) :
2197 remote_for_branch(branch, &explicit);
2198 *s = xstrdup(explicit ? remote : "");
2199 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2200 const char *merge;
2202 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2203 *s = xstrdup(merge ? merge : "");
2204 } else
2205 BUG("unhandled RR_* enum");
2208 char *get_head_description(void)
2210 struct strbuf desc = STRBUF_INIT;
2211 struct wt_status_state state;
2212 memset(&state, 0, sizeof(state));
2213 wt_status_get_state(the_repository, &state, 1);
2214 if (state.rebase_in_progress ||
2215 state.rebase_interactive_in_progress) {
2216 if (state.branch)
2217 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2218 state.branch);
2219 else
2220 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2221 state.detached_from);
2222 } else if (state.bisect_in_progress)
2223 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2224 state.bisecting_from);
2225 else if (state.detached_from) {
2226 if (state.detached_at)
2227 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2228 state.detached_from);
2229 else
2230 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2231 state.detached_from);
2232 } else
2233 strbuf_addstr(&desc, _("(no branch)"));
2235 wt_status_state_free_buffers(&state);
2237 return strbuf_detach(&desc, NULL);
2240 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2242 if (!ref->symref)
2243 return xstrdup("");
2244 else
2245 return show_ref(&atom->u.refname, ref->symref);
2248 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2250 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2251 return get_head_description();
2252 return show_ref(&atom->u.refname, ref->refname);
2255 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
2256 struct expand_data *oi, struct strbuf *err)
2258 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
2259 int eaten = 1;
2260 if (oi->info.contentp) {
2261 /* We need to know that to use parse_object_buffer properly */
2262 oi->info.sizep = &oi->size;
2263 oi->info.typep = &oi->type;
2265 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
2266 OBJECT_INFO_LOOKUP_REPLACE))
2267 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2268 oid_to_hex(&oi->oid), ref->refname);
2269 if (oi->info.disk_sizep && oi->disk_size < 0)
2270 BUG("Object size is less than zero.");
2272 if (oi->info.contentp) {
2273 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
2274 if (!*obj) {
2275 if (!eaten)
2276 free(oi->content);
2277 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
2278 oid_to_hex(&oi->oid), ref->refname);
2280 grab_values(ref->value, deref, *obj, oi);
2283 grab_common_values(ref->value, deref, oi);
2284 if (!eaten)
2285 free(oi->content);
2286 return 0;
2289 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2291 int i;
2293 for (i = 0; worktrees[i]; i++) {
2294 if (worktrees[i]->head_ref) {
2295 struct ref_to_worktree_entry *entry;
2296 entry = xmalloc(sizeof(*entry));
2297 entry->wt = worktrees[i];
2298 hashmap_entry_init(&entry->ent,
2299 strhash(worktrees[i]->head_ref));
2301 hashmap_add(map, &entry->ent);
2306 static void lazy_init_worktree_map(void)
2308 if (ref_to_worktree_map.worktrees)
2309 return;
2311 ref_to_worktree_map.worktrees = get_worktrees();
2312 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2313 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2316 static char *get_worktree_path(const struct ref_array_item *ref)
2318 struct hashmap_entry entry, *e;
2319 struct ref_to_worktree_entry *lookup_result;
2321 lazy_init_worktree_map();
2323 hashmap_entry_init(&entry, strhash(ref->refname));
2324 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2326 if (!e)
2327 return xstrdup("");
2329 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2331 return xstrdup(lookup_result->wt->path);
2335 * Parse the object referred by ref, and grab needed value.
2337 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2339 struct object *obj;
2340 int i;
2341 struct object_info empty = OBJECT_INFO_INIT;
2342 int ahead_behind_atoms = 0;
2344 CALLOC_ARRAY(ref->value, used_atom_cnt);
2346 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2347 ref->symref = refs_resolve_refdup(get_main_ref_store(the_repository),
2348 ref->refname,
2349 RESOLVE_REF_READING,
2350 NULL, NULL);
2351 if (!ref->symref)
2352 ref->symref = xstrdup("");
2355 /* Fill in specials first */
2356 for (i = 0; i < used_atom_cnt; i++) {
2357 struct used_atom *atom = &used_atom[i];
2358 enum atom_type atom_type = atom->atom_type;
2359 const char *name = used_atom[i].name;
2360 struct atom_value *v = &ref->value[i];
2361 int deref = 0;
2362 const char *refname;
2363 struct branch *branch = NULL;
2365 v->s_size = ATOM_SIZE_UNSPECIFIED;
2366 v->handler = append_atom;
2367 v->value = 0;
2368 v->atom = atom;
2370 if (*name == '*') {
2371 deref = 1;
2372 name++;
2375 if (atom_type == ATOM_REFNAME)
2376 refname = get_refname(atom, ref);
2377 else if (atom_type == ATOM_WORKTREEPATH) {
2378 if (ref->kind == FILTER_REFS_BRANCHES)
2379 v->s = get_worktree_path(ref);
2380 else
2381 v->s = xstrdup("");
2382 continue;
2384 else if (atom_type == ATOM_SYMREF)
2385 refname = get_symref(atom, ref);
2386 else if (atom_type == ATOM_UPSTREAM) {
2387 const char *branch_name;
2388 /* only local branches may have an upstream */
2389 if (!skip_prefix(ref->refname, "refs/heads/",
2390 &branch_name)) {
2391 v->s = xstrdup("");
2392 continue;
2394 branch = branch_get(branch_name);
2396 refname = branch_get_upstream(branch, NULL);
2397 if (refname)
2398 fill_remote_ref_details(atom, refname, branch, &v->s);
2399 else
2400 v->s = xstrdup("");
2401 continue;
2402 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2403 const char *branch_name;
2404 v->s = xstrdup("");
2405 if (!skip_prefix(ref->refname, "refs/heads/",
2406 &branch_name))
2407 continue;
2408 branch = branch_get(branch_name);
2410 if (atom->u.remote_ref.push_remote)
2411 refname = NULL;
2412 else {
2413 refname = branch_get_push(branch, NULL);
2414 if (!refname)
2415 continue;
2417 /* We will definitely re-init v->s on the next line. */
2418 free((char *)v->s);
2419 fill_remote_ref_details(atom, refname, branch, &v->s);
2420 continue;
2421 } else if (atom_type == ATOM_COLOR) {
2422 v->s = xstrdup(atom->u.color);
2423 continue;
2424 } else if (atom_type == ATOM_FLAG) {
2425 char buf[256], *cp = buf;
2426 if (ref->flag & REF_ISSYMREF)
2427 cp = copy_advance(cp, ",symref");
2428 if (ref->flag & REF_ISPACKED)
2429 cp = copy_advance(cp, ",packed");
2430 if (cp == buf)
2431 v->s = xstrdup("");
2432 else {
2433 *cp = '\0';
2434 v->s = xstrdup(buf + 1);
2436 continue;
2437 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2438 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2439 continue;
2440 } else if (atom_type == ATOM_HEAD) {
2441 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2442 v->s = xstrdup("*");
2443 else
2444 v->s = xstrdup(" ");
2445 continue;
2446 } else if (atom_type == ATOM_ALIGN) {
2447 v->handler = align_atom_handler;
2448 v->s = xstrdup("");
2449 continue;
2450 } else if (atom_type == ATOM_END) {
2451 v->handler = end_atom_handler;
2452 v->s = xstrdup("");
2453 continue;
2454 } else if (atom_type == ATOM_IF) {
2455 const char *s;
2456 if (skip_prefix(name, "if:", &s))
2457 v->s = xstrdup(s);
2458 else
2459 v->s = xstrdup("");
2460 v->handler = if_atom_handler;
2461 continue;
2462 } else if (atom_type == ATOM_THEN) {
2463 v->handler = then_atom_handler;
2464 v->s = xstrdup("");
2465 continue;
2466 } else if (atom_type == ATOM_ELSE) {
2467 v->handler = else_atom_handler;
2468 v->s = xstrdup("");
2469 continue;
2470 } else if (atom_type == ATOM_REST) {
2471 if (ref->rest)
2472 v->s = xstrdup(ref->rest);
2473 else
2474 v->s = xstrdup("");
2475 continue;
2476 } else if (atom_type == ATOM_AHEADBEHIND) {
2477 if (ref->counts) {
2478 const struct ahead_behind_count *count;
2479 count = ref->counts[ahead_behind_atoms++];
2480 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2481 } else {
2482 /* Not a commit. */
2483 v->s = xstrdup("");
2485 continue;
2486 } else
2487 continue;
2489 if (!deref)
2490 v->s = xstrdup(refname);
2491 else
2492 v->s = xstrfmt("%s^{}", refname);
2493 free((char *)refname);
2496 for (i = 0; i < used_atom_cnt; i++) {
2497 struct atom_value *v = &ref->value[i];
2498 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2499 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2500 oid_to_hex(&ref->objectname), ref->refname);
2503 if (need_tagged)
2504 oi.info.contentp = &oi.content;
2505 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2506 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2507 return 0;
2510 oi.oid = ref->objectname;
2511 if (get_object(ref, 0, &obj, &oi, err))
2512 return -1;
2515 * If there is no atom that wants to know about tagged
2516 * object, we are done.
2518 if (!need_tagged || (obj->type != OBJ_TAG))
2519 return 0;
2522 * If it is a tag object, see if we use the peeled value. If we do,
2523 * grab the peeled OID.
2525 if (need_tagged && peel_iterated_oid(the_repository, &obj->oid, &oi_deref.oid))
2526 die("bad tag");
2528 return get_object(ref, 1, &obj, &oi_deref, err);
2532 * Given a ref, return the value for the atom. This lazily gets value
2533 * out of the object by calling populate value.
2535 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2536 struct atom_value **v, struct strbuf *err)
2538 if (!ref->value) {
2539 if (populate_value(ref, err))
2540 return -1;
2541 fill_missing_values(ref->value);
2543 *v = &ref->value[atom];
2544 return 0;
2548 * Return 1 if the refname matches one of the patterns, otherwise 0.
2549 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2550 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2551 * matches "refs/heads/mas*", too).
2553 static int match_pattern(const char **patterns, const char *refname,
2554 int ignore_case)
2556 unsigned flags = 0;
2558 if (ignore_case)
2559 flags |= WM_CASEFOLD;
2562 * When no '--format' option is given we need to skip the prefix
2563 * for matching refs of tags and branches.
2565 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2566 skip_prefix(refname, "refs/heads/", &refname) ||
2567 skip_prefix(refname, "refs/remotes/", &refname) ||
2568 skip_prefix(refname, "refs/", &refname));
2570 for (; *patterns; patterns++) {
2571 if (!wildmatch(*patterns, refname, flags))
2572 return 1;
2574 return 0;
2578 * Return 1 if the refname matches one of the patterns, otherwise 0.
2579 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2580 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2581 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2583 static int match_name_as_path(const char **pattern, const char *refname,
2584 int ignore_case)
2586 int namelen = strlen(refname);
2587 unsigned flags = WM_PATHNAME;
2589 if (ignore_case)
2590 flags |= WM_CASEFOLD;
2592 for (; *pattern; pattern++) {
2593 const char *p = *pattern;
2594 int plen = strlen(p);
2596 if ((plen <= namelen) &&
2597 !strncmp(refname, p, plen) &&
2598 (refname[plen] == '\0' ||
2599 refname[plen] == '/' ||
2600 p[plen-1] == '/'))
2601 return 1;
2602 if (!wildmatch(p, refname, flags))
2603 return 1;
2605 return 0;
2608 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2609 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2611 if (!*filter->name_patterns)
2612 return 1; /* No pattern always matches */
2613 if (filter->match_as_path)
2614 return match_name_as_path(filter->name_patterns, refname,
2615 filter->ignore_case);
2616 return match_pattern(filter->name_patterns, refname,
2617 filter->ignore_case);
2620 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2622 if (!filter->exclude.nr)
2623 return 0;
2624 if (filter->match_as_path)
2625 return match_name_as_path(filter->exclude.v, refname,
2626 filter->ignore_case);
2627 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2631 * This is the same as for_each_fullref_in(), but it tries to iterate
2632 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2633 * pattern match, so the callback still has to match each ref individually.
2635 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2636 each_ref_fn cb,
2637 void *cb_data)
2639 if (filter->kind & FILTER_REFS_ROOT_REFS) {
2640 /* In this case, we want to print all refs including root refs. */
2641 return refs_for_each_include_root_refs(get_main_ref_store(the_repository),
2642 cb, cb_data);
2645 if (!filter->match_as_path) {
2647 * in this case, the patterns are applied after
2648 * prefixes like "refs/heads/" etc. are stripped off,
2649 * so we have to look at everything:
2651 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2652 "", NULL, cb, cb_data);
2655 if (filter->ignore_case) {
2657 * we can't handle case-insensitive comparisons,
2658 * so just return everything and let the caller
2659 * sort it out.
2661 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2662 "", NULL, cb, cb_data);
2665 if (!filter->name_patterns[0]) {
2666 /* no patterns; we have to look at everything */
2667 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2668 "", filter->exclude.v, cb, cb_data);
2671 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2672 NULL, filter->name_patterns,
2673 filter->exclude.v,
2674 cb, cb_data);
2678 * Given a ref (oid, refname), check if the ref belongs to the array
2679 * of oids. If the given ref is a tag, check if the given tag points
2680 * at one of the oids in the given oid array. Returns non-zero if a
2681 * match is found.
2683 * NEEDSWORK:
2684 * As the refs are cached we might know what refname peels to without
2685 * the need to parse the object via parse_object(). peel_ref() might be a
2686 * more efficient alternative to obtain the pointee.
2688 static int match_points_at(struct oid_array *points_at,
2689 const struct object_id *oid,
2690 const char *refname)
2692 struct object *obj;
2694 if (oid_array_lookup(points_at, oid) >= 0)
2695 return 1;
2696 obj = parse_object_with_flags(the_repository, oid,
2697 PARSE_OBJECT_SKIP_HASH_CHECK);
2698 while (obj && obj->type == OBJ_TAG) {
2699 struct tag *tag = (struct tag *)obj;
2701 if (parse_tag(tag) < 0) {
2702 obj = NULL;
2703 break;
2706 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2707 return 1;
2709 obj = tag->tagged;
2711 if (!obj)
2712 die(_("malformed object at '%s'"), refname);
2713 return 0;
2717 * Allocate space for a new ref_array_item and copy the name and oid to it.
2719 * Callers can then fill in other struct members at their leisure.
2721 static struct ref_array_item *new_ref_array_item(const char *refname,
2722 const struct object_id *oid)
2724 struct ref_array_item *ref;
2726 FLEX_ALLOC_STR(ref, refname, refname);
2727 oidcpy(&ref->objectname, oid);
2728 ref->rest = NULL;
2730 return ref;
2733 static void ref_array_append(struct ref_array *array, struct ref_array_item *ref)
2735 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2736 array->items[array->nr++] = ref;
2739 struct ref_array_item *ref_array_push(struct ref_array *array,
2740 const char *refname,
2741 const struct object_id *oid)
2743 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2744 ref_array_append(array, ref);
2745 return ref;
2748 static int ref_kind_from_refname(const char *refname)
2750 unsigned int i;
2752 static struct {
2753 const char *prefix;
2754 unsigned int kind;
2755 } ref_kind[] = {
2756 { "refs/heads/" , FILTER_REFS_BRANCHES },
2757 { "refs/remotes/" , FILTER_REFS_REMOTES },
2758 { "refs/tags/", FILTER_REFS_TAGS}
2761 if (!strcmp(refname, "HEAD"))
2762 return FILTER_REFS_DETACHED_HEAD;
2764 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2765 if (starts_with(refname, ref_kind[i].prefix))
2766 return ref_kind[i].kind;
2769 if (is_pseudo_ref(refname))
2770 return FILTER_REFS_PSEUDOREFS;
2771 if (is_root_ref(refname))
2772 return FILTER_REFS_ROOT_REFS;
2774 return FILTER_REFS_OTHERS;
2777 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2779 if (filter->kind == FILTER_REFS_BRANCHES ||
2780 filter->kind == FILTER_REFS_REMOTES ||
2781 filter->kind == FILTER_REFS_TAGS)
2782 return filter->kind;
2783 return ref_kind_from_refname(refname);
2786 static struct ref_array_item *apply_ref_filter(const char *refname, const struct object_id *oid,
2787 int flag, struct ref_filter *filter)
2789 struct ref_array_item *ref;
2790 struct commit *commit = NULL;
2791 unsigned int kind;
2793 if (flag & REF_BAD_NAME) {
2794 warning(_("ignoring ref with broken name %s"), refname);
2795 return NULL;
2798 if (flag & REF_ISBROKEN) {
2799 warning(_("ignoring broken ref %s"), refname);
2800 return NULL;
2803 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2804 kind = filter_ref_kind(filter, refname);
2807 * Generally HEAD refs are printed with special description denoting a rebase,
2808 * detached state and so forth. This is useful when only printing the HEAD ref
2809 * But when it is being printed along with other root refs, it makes sense to
2810 * keep the formatting consistent. So we mask the type to act like a root ref.
2812 if (filter->kind & FILTER_REFS_ROOT_REFS && kind == FILTER_REFS_DETACHED_HEAD)
2813 kind = FILTER_REFS_ROOT_REFS;
2814 else if (!(kind & filter->kind))
2815 return NULL;
2817 if (!filter_pattern_match(filter, refname))
2818 return NULL;
2820 if (filter_exclude_match(filter, refname))
2821 return NULL;
2823 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2824 return NULL;
2827 * A merge filter is applied on refs pointing to commits. Hence
2828 * obtain the commit using the 'oid' available and discard all
2829 * non-commits early. The actual filtering is done later.
2831 if (filter->reachable_from || filter->unreachable_from ||
2832 filter->with_commit || filter->no_commit || filter->verbose) {
2833 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2834 if (!commit)
2835 return NULL;
2836 /* We perform the filtering for the '--contains' option... */
2837 if (filter->with_commit &&
2838 !commit_contains(filter, commit, filter->with_commit, &filter->internal.contains_cache))
2839 return NULL;
2840 /* ...or for the `--no-contains' option */
2841 if (filter->no_commit &&
2842 commit_contains(filter, commit, filter->no_commit, &filter->internal.no_contains_cache))
2843 return NULL;
2847 * We do not open the object yet; sort may only need refname
2848 * to do its job and the resulting list may yet to be pruned
2849 * by maxcount logic.
2851 ref = new_ref_array_item(refname, oid);
2852 ref->commit = commit;
2853 ref->flag = flag;
2854 ref->kind = kind;
2856 return ref;
2859 struct ref_filter_cbdata {
2860 struct ref_array *array;
2861 struct ref_filter *filter;
2865 * A call-back given to for_each_ref(). Filter refs and keep them for
2866 * later object processing.
2868 static int filter_one(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2870 struct ref_filter_cbdata *ref_cbdata = cb_data;
2871 struct ref_array_item *ref;
2873 ref = apply_ref_filter(refname, oid, flag, ref_cbdata->filter);
2874 if (ref)
2875 ref_array_append(ref_cbdata->array, ref);
2877 return 0;
2880 /* Free memory allocated for a ref_array_item */
2881 static void free_array_item(struct ref_array_item *item)
2883 free((char *)item->symref);
2884 if (item->value) {
2885 int i;
2886 for (i = 0; i < used_atom_cnt; i++)
2887 free((char *)item->value[i].s);
2888 free(item->value);
2890 free(item->counts);
2891 free(item);
2894 struct ref_filter_and_format_cbdata {
2895 struct ref_filter *filter;
2896 struct ref_format *format;
2898 struct ref_filter_and_format_internal {
2899 int count;
2900 } internal;
2903 static int filter_and_format_one(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2905 struct ref_filter_and_format_cbdata *ref_cbdata = cb_data;
2906 struct ref_array_item *ref;
2907 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
2909 ref = apply_ref_filter(refname, oid, flag, ref_cbdata->filter);
2910 if (!ref)
2911 return 0;
2913 if (format_ref_array_item(ref, ref_cbdata->format, &output, &err))
2914 die("%s", err.buf);
2916 if (output.len || !ref_cbdata->format->array_opts.omit_empty) {
2917 fwrite(output.buf, 1, output.len, stdout);
2918 putchar('\n');
2921 strbuf_release(&output);
2922 strbuf_release(&err);
2923 free_array_item(ref);
2926 * Increment the running count of refs that match the filter. If
2927 * max_count is set and we've reached the max, stop the ref
2928 * iteration by returning a nonzero value.
2930 if (ref_cbdata->format->array_opts.max_count &&
2931 ++ref_cbdata->internal.count >= ref_cbdata->format->array_opts.max_count)
2932 return 1;
2934 return 0;
2937 /* Free all memory allocated for ref_array */
2938 void ref_array_clear(struct ref_array *array)
2940 int i;
2942 for (i = 0; i < array->nr; i++)
2943 free_array_item(array->items[i]);
2944 FREE_AND_NULL(array->items);
2945 array->nr = array->alloc = 0;
2947 for (i = 0; i < used_atom_cnt; i++) {
2948 struct used_atom *atom = &used_atom[i];
2949 if (atom->atom_type == ATOM_HEAD)
2950 free(atom->u.head);
2951 free((char *)atom->name);
2953 FREE_AND_NULL(used_atom);
2954 used_atom_cnt = 0;
2956 if (ref_to_worktree_map.worktrees) {
2957 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2958 struct ref_to_worktree_entry, ent);
2959 free_worktrees(ref_to_worktree_map.worktrees);
2960 ref_to_worktree_map.worktrees = NULL;
2963 FREE_AND_NULL(array->counts);
2966 #define EXCLUDE_REACHED 0
2967 #define INCLUDE_REACHED 1
2968 static void reach_filter(struct ref_array *array,
2969 struct commit_list **check_reachable,
2970 int include_reached)
2972 int i, old_nr;
2973 struct commit **to_clear;
2975 if (!*check_reachable)
2976 return;
2978 CALLOC_ARRAY(to_clear, array->nr);
2979 for (i = 0; i < array->nr; i++) {
2980 struct ref_array_item *item = array->items[i];
2981 to_clear[i] = item->commit;
2984 tips_reachable_from_bases(the_repository,
2985 *check_reachable,
2986 to_clear, array->nr,
2987 UNINTERESTING);
2989 old_nr = array->nr;
2990 array->nr = 0;
2992 for (i = 0; i < old_nr; i++) {
2993 struct ref_array_item *item = array->items[i];
2994 struct commit *commit = item->commit;
2996 int is_merged = !!(commit->object.flags & UNINTERESTING);
2998 if (is_merged == include_reached)
2999 array->items[array->nr++] = array->items[i];
3000 else
3001 free_array_item(item);
3004 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
3006 while (*check_reachable) {
3007 struct commit *merge_commit = pop_commit(check_reachable);
3008 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
3011 free(to_clear);
3014 void filter_ahead_behind(struct repository *r,
3015 struct ref_format *format,
3016 struct ref_array *array)
3018 struct commit **commits;
3019 size_t commits_nr = format->bases.nr + array->nr;
3021 if (!format->bases.nr || !array->nr)
3022 return;
3024 ALLOC_ARRAY(commits, commits_nr);
3025 for (size_t i = 0; i < format->bases.nr; i++)
3026 commits[i] = format->bases.items[i].util;
3028 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
3030 commits_nr = format->bases.nr;
3031 array->counts_nr = 0;
3032 for (size_t i = 0; i < array->nr; i++) {
3033 const char *name = array->items[i]->refname;
3034 commits[commits_nr] = lookup_commit_reference_by_name(name);
3036 if (!commits[commits_nr])
3037 continue;
3039 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
3040 for (size_t j = 0; j < format->bases.nr; j++) {
3041 struct ahead_behind_count *count;
3042 count = &array->counts[array->counts_nr++];
3043 count->tip_index = commits_nr;
3044 count->base_index = j;
3046 array->items[i]->counts[j] = count;
3048 commits_nr++;
3051 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
3052 free(commits);
3055 static int do_filter_refs(struct ref_filter *filter, unsigned int type, each_ref_fn fn, void *cb_data)
3057 int ret = 0;
3059 filter->kind = type & FILTER_REFS_KIND_MASK;
3061 init_contains_cache(&filter->internal.contains_cache);
3062 init_contains_cache(&filter->internal.no_contains_cache);
3064 /* Simple per-ref filtering */
3065 if (!filter->kind)
3066 die("filter_refs: invalid type");
3067 else {
3069 * For common cases where we need only branches or remotes or tags,
3070 * we only iterate through those refs. If a mix of refs is needed,
3071 * we iterate over all refs and filter out required refs with the help
3072 * of filter_ref_kind().
3074 if (filter->kind == FILTER_REFS_BRANCHES)
3075 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3076 "refs/heads/", NULL,
3077 fn, cb_data);
3078 else if (filter->kind == FILTER_REFS_REMOTES)
3079 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3080 "refs/remotes/", NULL,
3081 fn, cb_data);
3082 else if (filter->kind == FILTER_REFS_TAGS)
3083 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3084 "refs/tags/", NULL, fn,
3085 cb_data);
3086 else if (filter->kind & FILTER_REFS_REGULAR)
3087 ret = for_each_fullref_in_pattern(filter, fn, cb_data);
3090 * When printing all ref types, HEAD is already included,
3091 * so we don't want to print HEAD again.
3093 if (!ret && !(filter->kind & FILTER_REFS_ROOT_REFS) &&
3094 (filter->kind & FILTER_REFS_DETACHED_HEAD))
3095 refs_head_ref(get_main_ref_store(the_repository), fn,
3096 cb_data);
3099 clear_contains_cache(&filter->internal.contains_cache);
3100 clear_contains_cache(&filter->internal.no_contains_cache);
3102 return ret;
3106 * API for filtering a set of refs. Based on the type of refs the user
3107 * has requested, we iterate through those refs and apply filters
3108 * as per the given ref_filter structure and finally store the
3109 * filtered refs in the ref_array structure.
3111 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
3113 struct ref_filter_cbdata ref_cbdata;
3114 int save_commit_buffer_orig;
3115 int ret = 0;
3117 ref_cbdata.array = array;
3118 ref_cbdata.filter = filter;
3120 save_commit_buffer_orig = save_commit_buffer;
3121 save_commit_buffer = 0;
3123 ret = do_filter_refs(filter, type, filter_one, &ref_cbdata);
3125 /* Filters that need revision walking */
3126 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
3127 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
3129 save_commit_buffer = save_commit_buffer_orig;
3130 return ret;
3133 static inline int can_do_iterative_format(struct ref_filter *filter,
3134 struct ref_sorting *sorting,
3135 struct ref_format *format)
3138 * Filtering & formatting results within a single ref iteration
3139 * callback is not compatible with options that require
3140 * post-processing a filtered ref_array. These include:
3141 * - filtering on reachability
3142 * - sorting the filtered results
3143 * - including ahead-behind information in the formatted output
3145 return !(filter->reachable_from ||
3146 filter->unreachable_from ||
3147 sorting ||
3148 format->bases.nr);
3151 void filter_and_format_refs(struct ref_filter *filter, unsigned int type,
3152 struct ref_sorting *sorting,
3153 struct ref_format *format)
3155 if (can_do_iterative_format(filter, sorting, format)) {
3156 int save_commit_buffer_orig;
3157 struct ref_filter_and_format_cbdata ref_cbdata = {
3158 .filter = filter,
3159 .format = format,
3162 save_commit_buffer_orig = save_commit_buffer;
3163 save_commit_buffer = 0;
3165 do_filter_refs(filter, type, filter_and_format_one, &ref_cbdata);
3167 save_commit_buffer = save_commit_buffer_orig;
3168 } else {
3169 struct ref_array array = { 0 };
3170 filter_refs(&array, filter, type);
3171 filter_ahead_behind(the_repository, format, &array);
3172 ref_array_sort(sorting, &array);
3173 print_formatted_ref_array(&array, format);
3174 ref_array_clear(&array);
3178 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
3180 if (!(a->kind ^ b->kind))
3181 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
3182 if (a->kind & FILTER_REFS_DETACHED_HEAD)
3183 return -1;
3184 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
3185 return 1;
3186 BUG("should have died in the xor check above");
3187 return 0;
3190 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
3192 const char *s1 = vs1, *s2 = vs2;
3193 const char *end = s1 + n;
3195 for (; s1 < end; s1++, s2++) {
3196 int diff = tolower(*s1) - tolower(*s2);
3197 if (diff)
3198 return diff;
3200 return 0;
3203 struct ref_sorting {
3204 struct ref_sorting *next;
3205 int atom; /* index into used_atom array (internal) */
3206 enum ref_sorting_order sort_flags;
3209 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
3211 struct atom_value *va, *vb;
3212 int cmp;
3213 int cmp_detached_head = 0;
3214 cmp_type cmp_type = used_atom[s->atom].type;
3215 struct strbuf err = STRBUF_INIT;
3217 if (get_ref_atom_value(a, s->atom, &va, &err))
3218 die("%s", err.buf);
3219 if (get_ref_atom_value(b, s->atom, &vb, &err))
3220 die("%s", err.buf);
3221 strbuf_release(&err);
3222 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
3223 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
3224 cmp = compare_detached_head(a, b);
3225 cmp_detached_head = 1;
3226 } else if (s->sort_flags & REF_SORTING_VERSION) {
3227 cmp = versioncmp(va->s, vb->s);
3228 } else if (cmp_type == FIELD_STR) {
3229 if (va->s_size < 0 && vb->s_size < 0) {
3230 int (*cmp_fn)(const char *, const char *);
3231 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3232 ? strcasecmp : strcmp;
3233 cmp = cmp_fn(va->s, vb->s);
3234 } else {
3235 size_t a_size = va->s_size < 0 ?
3236 strlen(va->s) : va->s_size;
3237 size_t b_size = vb->s_size < 0 ?
3238 strlen(vb->s) : vb->s_size;
3239 int (*cmp_fn)(const void *, const void *, size_t);
3240 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3241 ? memcasecmp : memcmp;
3243 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3244 a_size : b_size);
3245 if (!cmp) {
3246 if (a_size > b_size)
3247 cmp = 1;
3248 else if (a_size < b_size)
3249 cmp = -1;
3252 } else {
3253 if (va->value < vb->value)
3254 cmp = -1;
3255 else if (va->value == vb->value)
3256 cmp = 0;
3257 else
3258 cmp = 1;
3261 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3262 ? -cmp : cmp;
3265 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3267 struct ref_array_item *a = *((struct ref_array_item **)a_);
3268 struct ref_array_item *b = *((struct ref_array_item **)b_);
3269 struct ref_sorting *s;
3271 for (s = ref_sorting; s; s = s->next) {
3272 int cmp = cmp_ref_sorting(s, a, b);
3273 if (cmp)
3274 return cmp;
3276 s = ref_sorting;
3277 return s && s->sort_flags & REF_SORTING_ICASE ?
3278 strcasecmp(a->refname, b->refname) :
3279 strcmp(a->refname, b->refname);
3282 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3283 unsigned int mask, int on)
3285 for (; sorting; sorting = sorting->next) {
3286 if (on)
3287 sorting->sort_flags |= mask;
3288 else
3289 sorting->sort_flags &= ~mask;
3293 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3295 if (sorting)
3296 QSORT_S(array->items, array->nr, compare_refs, sorting);
3299 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3301 struct strbuf *s = &state->stack->output;
3303 while (*cp && (!ep || cp < ep)) {
3304 if (*cp == '%') {
3305 if (cp[1] == '%')
3306 cp++;
3307 else {
3308 int ch = hex2chr(cp + 1);
3309 if (0 <= ch) {
3310 strbuf_addch(s, ch);
3311 cp += 3;
3312 continue;
3316 strbuf_addch(s, *cp);
3317 cp++;
3321 int format_ref_array_item(struct ref_array_item *info,
3322 struct ref_format *format,
3323 struct strbuf *final_buf,
3324 struct strbuf *error_buf)
3326 const char *cp, *sp, *ep;
3327 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3329 state.quote_style = format->quote_style;
3330 push_stack_element(&state.stack);
3332 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3333 struct atom_value *atomv;
3334 int pos;
3336 ep = strchr(sp, ')');
3337 if (cp < sp)
3338 append_literal(cp, sp, &state);
3339 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3340 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3341 atomv->handler(atomv, &state, error_buf)) {
3342 pop_stack_element(&state.stack);
3343 return -1;
3346 if (*cp) {
3347 sp = cp + strlen(cp);
3348 append_literal(cp, sp, &state);
3350 if (format->need_color_reset_at_eol) {
3351 struct atom_value resetv = ATOM_VALUE_INIT;
3352 resetv.s = GIT_COLOR_RESET;
3353 if (append_atom(&resetv, &state, error_buf)) {
3354 pop_stack_element(&state.stack);
3355 return -1;
3358 if (state.stack->prev) {
3359 pop_stack_element(&state.stack);
3360 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3362 strbuf_addbuf(final_buf, &state.stack->output);
3363 pop_stack_element(&state.stack);
3364 return 0;
3367 void print_formatted_ref_array(struct ref_array *array, struct ref_format *format)
3369 int total;
3370 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3372 total = format->array_opts.max_count;
3373 if (!total || array->nr < total)
3374 total = array->nr;
3375 for (int i = 0; i < total; i++) {
3376 strbuf_reset(&err);
3377 strbuf_reset(&output);
3378 if (format_ref_array_item(array->items[i], format, &output, &err))
3379 die("%s", err.buf);
3380 if (output.len || !format->array_opts.omit_empty) {
3381 fwrite(output.buf, 1, output.len, stdout);
3382 putchar('\n');
3386 strbuf_release(&err);
3387 strbuf_release(&output);
3390 void pretty_print_ref(const char *name, const struct object_id *oid,
3391 struct ref_format *format)
3393 struct ref_array_item *ref_item;
3394 struct strbuf output = STRBUF_INIT;
3395 struct strbuf err = STRBUF_INIT;
3397 ref_item = new_ref_array_item(name, oid);
3398 ref_item->kind = ref_kind_from_refname(name);
3399 if (format_ref_array_item(ref_item, format, &output, &err))
3400 die("%s", err.buf);
3401 fwrite(output.buf, 1, output.len, stdout);
3402 putchar('\n');
3404 strbuf_release(&err);
3405 strbuf_release(&output);
3406 free_array_item(ref_item);
3409 static int parse_sorting_atom(const char *atom)
3412 * This parses an atom using a dummy ref_format, since we don't
3413 * actually care about the formatting details.
3415 struct ref_format dummy = REF_FORMAT_INIT;
3416 const char *end = atom + strlen(atom);
3417 struct strbuf err = STRBUF_INIT;
3418 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3419 if (res < 0)
3420 die("%s", err.buf);
3421 strbuf_release(&err);
3422 return res;
3425 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3427 struct ref_sorting *s;
3429 CALLOC_ARRAY(s, 1);
3430 s->next = *sorting_tail;
3431 *sorting_tail = s;
3433 if (*arg == '-') {
3434 s->sort_flags |= REF_SORTING_REVERSE;
3435 arg++;
3437 if (skip_prefix(arg, "version:", &arg) ||
3438 skip_prefix(arg, "v:", &arg))
3439 s->sort_flags |= REF_SORTING_VERSION;
3440 s->atom = parse_sorting_atom(arg);
3443 struct ref_sorting *ref_sorting_options(struct string_list *options)
3445 struct string_list_item *item;
3446 struct ref_sorting *sorting = NULL, **tail = &sorting;
3448 if (options->nr) {
3449 for_each_string_list_item(item, options)
3450 parse_ref_sorting(tail, item->string);
3454 * From here on, the ref_sorting list should be used to talk
3455 * about the sort order used for the output. The caller
3456 * should not touch the string form anymore.
3458 string_list_clear(options, 0);
3459 return sorting;
3462 void ref_sorting_release(struct ref_sorting *sorting)
3464 while (sorting) {
3465 struct ref_sorting *next = sorting->next;
3466 free(sorting);
3467 sorting = next;
3471 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3473 struct ref_filter *rf = opt->value;
3474 struct object_id oid;
3475 struct commit *merge_commit;
3477 BUG_ON_OPT_NEG(unset);
3479 if (repo_get_oid(the_repository, arg, &oid))
3480 die(_("malformed object name %s"), arg);
3482 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3484 if (!merge_commit)
3485 return error(_("option `%s' must point to a commit"), opt->long_name);
3487 if (starts_with(opt->long_name, "no"))
3488 commit_list_insert(merge_commit, &rf->unreachable_from);
3489 else
3490 commit_list_insert(merge_commit, &rf->reachable_from);
3492 return 0;
3495 void ref_filter_init(struct ref_filter *filter)
3497 struct ref_filter blank = REF_FILTER_INIT;
3498 memcpy(filter, &blank, sizeof(blank));
3501 void ref_filter_clear(struct ref_filter *filter)
3503 strvec_clear(&filter->exclude);
3504 oid_array_clear(&filter->points_at);
3505 free_commit_list(filter->with_commit);
3506 free_commit_list(filter->no_commit);
3507 free_commit_list(filter->reachable_from);
3508 free_commit_list(filter->unreachable_from);
3509 ref_filter_init(filter);