Start preparing for Git 2.46.2
[alt-git.git] / ref-filter.c
blob54880a2497aa90319e2eefaffaa365ee2543f52e
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 errno = 0;
1632 tz = strtol(zone, NULL, 10);
1633 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1634 goto bad;
1635 v->s = xstrdup(show_date(timestamp, tz, date_mode));
1636 v->value = timestamp;
1637 date_mode_release(&date_mode);
1638 return;
1639 bad:
1640 v->s = xstrdup("");
1641 v->value = 0;
1644 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
1646 /* See grab_values */
1647 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1649 int i;
1650 int wholen = strlen(who);
1651 const char *wholine = NULL;
1652 const char *headers[] = { "author ", "committer ",
1653 "tagger ", NULL };
1655 for (i = 0; i < used_atom_cnt; i++) {
1656 struct used_atom *atom = &used_atom[i];
1657 const char *name = atom->name;
1658 struct atom_value *v = &val[i];
1659 struct strbuf mailmap_buf = STRBUF_INIT;
1661 if (!!deref != (*name == '*'))
1662 continue;
1663 if (deref)
1664 name++;
1665 if (strncmp(who, name, wholen))
1666 continue;
1667 if (name[wholen] != 0 &&
1668 !starts_with(name + wholen, "name") &&
1669 !starts_with(name + wholen, "email") &&
1670 !starts_with(name + wholen, "date"))
1671 continue;
1673 if ((starts_with(name + wholen, "name") &&
1674 (atom->u.name_option.option == N_MAILMAP)) ||
1675 (starts_with(name + wholen, "email") &&
1676 (atom->u.email_option.option & EO_MAILMAP))) {
1677 if (!mailmap.items)
1678 read_mailmap(&mailmap);
1679 strbuf_addstr(&mailmap_buf, buf);
1680 apply_mailmap_to_header(&mailmap_buf, headers, &mailmap);
1681 wholine = find_wholine(who, wholen, mailmap_buf.buf);
1682 } else {
1683 wholine = find_wholine(who, wholen, buf);
1686 if (!wholine)
1687 return; /* no point looking for it */
1688 if (name[wholen] == 0)
1689 v->s = copy_line(wholine);
1690 else if (starts_with(name + wholen, "name"))
1691 v->s = copy_name(wholine);
1692 else if (starts_with(name + wholen, "email"))
1693 v->s = copy_email(wholine, &used_atom[i]);
1694 else if (starts_with(name + wholen, "date"))
1695 grab_date(wholine, v, name);
1697 strbuf_release(&mailmap_buf);
1701 * For a tag or a commit object, if "creator" or "creatordate" is
1702 * requested, do something special.
1704 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1705 return; /* "author" for commit object is not wanted */
1706 if (!wholine)
1707 wholine = find_wholine(who, wholen, buf);
1708 if (!wholine)
1709 return;
1710 for (i = 0; i < used_atom_cnt; i++) {
1711 const char *name = used_atom[i].name;
1712 enum atom_type atom_type = used_atom[i].atom_type;
1713 struct atom_value *v = &val[i];
1714 if (!!deref != (*name == '*'))
1715 continue;
1716 if (deref)
1717 name++;
1719 if (atom_type == ATOM_CREATORDATE)
1720 grab_date(wholine, v, name);
1721 else if (atom_type == ATOM_CREATOR)
1722 v->s = copy_line(wholine);
1726 static void grab_signature(struct atom_value *val, int deref, struct object *obj)
1728 int i;
1729 struct commit *commit = (struct commit *) obj;
1730 struct signature_check sigc = { 0 };
1731 int signature_checked = 0;
1733 for (i = 0; i < used_atom_cnt; i++) {
1734 struct used_atom *atom = &used_atom[i];
1735 const char *name = atom->name;
1736 struct atom_value *v = &val[i];
1737 int opt;
1739 if (!!deref != (*name == '*'))
1740 continue;
1741 if (deref)
1742 name++;
1744 if (!skip_prefix(name, "signature", &name) ||
1745 (*name && *name != ':'))
1746 continue;
1747 if (!*name)
1748 name = NULL;
1749 else
1750 name++;
1752 opt = parse_signature_option(name);
1753 if (opt < 0)
1754 continue;
1756 if (!signature_checked) {
1757 check_commit_signature(commit, &sigc);
1758 signature_checked = 1;
1761 switch (opt) {
1762 case S_BARE:
1763 v->s = xstrdup(sigc.output ? sigc.output: "");
1764 break;
1765 case S_SIGNER:
1766 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1767 break;
1768 case S_GRADE:
1769 switch (sigc.result) {
1770 case 'G':
1771 switch (sigc.trust_level) {
1772 case TRUST_UNDEFINED:
1773 case TRUST_NEVER:
1774 v->s = xstrfmt("%c", (char)'U');
1775 break;
1776 default:
1777 v->s = xstrfmt("%c", (char)'G');
1778 break;
1780 break;
1781 case 'B':
1782 case 'E':
1783 case 'N':
1784 case 'X':
1785 case 'Y':
1786 case 'R':
1787 v->s = xstrfmt("%c", (char)sigc.result);
1788 break;
1790 break;
1791 case S_KEY:
1792 v->s = xstrdup(sigc.key ? sigc.key : "");
1793 break;
1794 case S_FINGERPRINT:
1795 v->s = xstrdup(sigc.fingerprint ?
1796 sigc.fingerprint : "");
1797 break;
1798 case S_PRI_KEY_FP:
1799 v->s = xstrdup(sigc.primary_key_fingerprint ?
1800 sigc.primary_key_fingerprint : "");
1801 break;
1802 case S_TRUST_LEVEL:
1803 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1804 break;
1808 if (signature_checked)
1809 signature_check_clear(&sigc);
1812 static void find_subpos(const char *buf,
1813 const char **sub, size_t *sublen,
1814 const char **body, size_t *bodylen,
1815 size_t *nonsiglen,
1816 const char **sig, size_t *siglen)
1818 struct strbuf payload = STRBUF_INIT;
1819 struct strbuf signature = STRBUF_INIT;
1820 const char *eol;
1821 const char *end = buf + strlen(buf);
1822 const char *sigstart;
1824 /* parse signature first; we might not even have a subject line */
1825 parse_signature(buf, end - buf, &payload, &signature);
1826 strbuf_release(&payload);
1828 /* skip past header until we hit empty line */
1829 while (*buf && *buf != '\n') {
1830 eol = strchrnul(buf, '\n');
1831 if (*eol)
1832 eol++;
1833 buf = eol;
1835 /* skip any empty lines */
1836 while (*buf == '\n')
1837 buf++;
1838 *sig = strbuf_detach(&signature, siglen);
1839 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1841 /* subject is first non-empty line */
1842 *sub = buf;
1843 /* subject goes to first empty line before signature begins */
1844 if ((eol = strstr(*sub, "\n\n")) ||
1845 (eol = strstr(*sub, "\r\n\r\n"))) {
1846 eol = eol < sigstart ? eol : sigstart;
1847 } else {
1848 /* treat whole message as subject */
1849 eol = sigstart;
1851 buf = eol;
1852 *sublen = buf - *sub;
1853 /* drop trailing newline, if present */
1854 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1855 (*sub)[*sublen - 1] == '\r'))
1856 *sublen -= 1;
1858 /* skip any empty lines */
1859 while (*buf == '\n' || *buf == '\r')
1860 buf++;
1861 *body = buf;
1862 *bodylen = strlen(buf);
1863 *nonsiglen = sigstart - buf;
1867 * If 'lines' is greater than 0, append that many lines from the given
1868 * 'buf' of length 'size' to the given strbuf.
1870 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1872 int i;
1873 const char *sp, *eol;
1874 size_t len;
1876 sp = buf;
1878 for (i = 0; i < lines && sp < buf + size; i++) {
1879 if (i)
1880 strbuf_addstr(out, "\n ");
1881 eol = memchr(sp, '\n', size - (sp - buf));
1882 len = eol ? eol - sp : size - (sp - buf);
1883 strbuf_add(out, sp, len);
1884 if (!eol)
1885 break;
1886 sp = eol + 1;
1890 static void grab_describe_values(struct atom_value *val, int deref,
1891 struct object *obj)
1893 struct commit *commit = (struct commit *)obj;
1894 int i;
1896 for (i = 0; i < used_atom_cnt; i++) {
1897 struct used_atom *atom = &used_atom[i];
1898 enum atom_type type = atom->atom_type;
1899 const char *name = atom->name;
1900 struct atom_value *v = &val[i];
1902 struct child_process cmd = CHILD_PROCESS_INIT;
1903 struct strbuf out = STRBUF_INIT;
1904 struct strbuf err = STRBUF_INIT;
1906 if (type != ATOM_DESCRIBE)
1907 continue;
1909 if (!!deref != (*name == '*'))
1910 continue;
1912 cmd.git_cmd = 1;
1913 strvec_push(&cmd.args, "describe");
1914 strvec_pushv(&cmd.args, atom->u.describe_args);
1915 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1916 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
1917 error(_("failed to run 'describe'"));
1918 v->s = xstrdup("");
1919 continue;
1921 strbuf_rtrim(&out);
1922 v->s = strbuf_detach(&out, NULL);
1924 strbuf_release(&err);
1928 /* See grab_values */
1929 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1931 int i;
1932 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1933 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1934 void *buf = data->content;
1936 for (i = 0; i < used_atom_cnt; i++) {
1937 struct used_atom *atom = &used_atom[i];
1938 const char *name = atom->name;
1939 struct atom_value *v = &val[i];
1940 enum atom_type atom_type = atom->atom_type;
1942 if (!!deref != (*name == '*'))
1943 continue;
1944 if (deref)
1945 name++;
1947 if (atom_type == ATOM_RAW) {
1948 unsigned long buf_size = data->size;
1950 if (atom->u.raw_data.option == RAW_BARE) {
1951 v->s = xmemdupz(buf, buf_size);
1952 v->s_size = buf_size;
1953 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1954 v->value = buf_size;
1955 v->s = xstrfmt("%"PRIuMAX, v->value);
1957 continue;
1960 if ((data->type != OBJ_TAG &&
1961 data->type != OBJ_COMMIT) ||
1962 (strcmp(name, "body") &&
1963 !starts_with(name, "subject") &&
1964 !starts_with(name, "trailers") &&
1965 !starts_with(name, "contents")))
1966 continue;
1967 if (!subpos)
1968 find_subpos(buf,
1969 &subpos, &sublen,
1970 &bodypos, &bodylen, &nonsiglen,
1971 &sigpos, &siglen);
1973 if (atom->u.contents.option == C_SUB)
1974 v->s = copy_subject(subpos, sublen);
1975 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1976 struct strbuf sb = STRBUF_INIT;
1977 format_sanitized_subject(&sb, subpos, sublen);
1978 v->s = strbuf_detach(&sb, NULL);
1979 } else if (atom->u.contents.option == C_BODY_DEP)
1980 v->s = xmemdupz(bodypos, bodylen);
1981 else if (atom->u.contents.option == C_LENGTH) {
1982 v->value = strlen(subpos);
1983 v->s = xstrfmt("%"PRIuMAX, v->value);
1984 } else if (atom->u.contents.option == C_BODY)
1985 v->s = xmemdupz(bodypos, nonsiglen);
1986 else if (atom->u.contents.option == C_SIG)
1987 v->s = xmemdupz(sigpos, siglen);
1988 else if (atom->u.contents.option == C_LINES) {
1989 struct strbuf s = STRBUF_INIT;
1990 const char *contents_end = bodypos + nonsiglen;
1992 /* Size is the length of the message after removing the signature */
1993 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1994 v->s = strbuf_detach(&s, NULL);
1995 } else if (atom->u.contents.option == C_TRAILERS) {
1996 struct strbuf s = STRBUF_INIT;
1998 /* Format the trailer info according to the trailer_opts given */
1999 format_trailers_from_commit(&atom->u.contents.trailer_opts, subpos, &s);
2001 v->s = strbuf_detach(&s, NULL);
2002 } else if (atom->u.contents.option == C_BARE)
2003 v->s = xstrdup(subpos);
2006 free((void *)sigpos);
2010 * We want to have empty print-string for field requests
2011 * that do not apply (e.g. "authordate" for a tag object)
2013 static void fill_missing_values(struct atom_value *val)
2015 int i;
2016 for (i = 0; i < used_atom_cnt; i++) {
2017 struct atom_value *v = &val[i];
2018 if (!v->s)
2019 v->s = xstrdup("");
2024 * val is a list of atom_value to hold returned values. Extract
2025 * the values for atoms in used_atom array out of (obj, buf, sz).
2026 * when deref is false, (obj, buf, sz) is the object that is
2027 * pointed at by the ref itself; otherwise it is the object the
2028 * ref (which is a tag) refers to.
2030 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
2032 void *buf = data->content;
2034 switch (obj->type) {
2035 case OBJ_TAG:
2036 grab_tag_values(val, deref, obj);
2037 grab_sub_body_contents(val, deref, data);
2038 grab_person("tagger", val, deref, buf);
2039 grab_describe_values(val, deref, obj);
2040 break;
2041 case OBJ_COMMIT:
2042 grab_commit_values(val, deref, obj);
2043 grab_sub_body_contents(val, deref, data);
2044 grab_person("author", val, deref, buf);
2045 grab_person("committer", val, deref, buf);
2046 grab_signature(val, deref, obj);
2047 grab_describe_values(val, deref, obj);
2048 break;
2049 case OBJ_TREE:
2050 /* grab_tree_values(val, deref, obj, buf, sz); */
2051 grab_sub_body_contents(val, deref, data);
2052 break;
2053 case OBJ_BLOB:
2054 /* grab_blob_values(val, deref, obj, buf, sz); */
2055 grab_sub_body_contents(val, deref, data);
2056 break;
2057 default:
2058 die("Eh? Object of type %d?", obj->type);
2062 static inline char *copy_advance(char *dst, const char *src)
2064 while (*src)
2065 *dst++ = *src++;
2066 return dst;
2069 static const char *lstrip_ref_components(const char *refname, int len)
2071 long remaining = len;
2072 const char *start = xstrdup(refname);
2073 const char *to_free = start;
2075 if (len < 0) {
2076 int i;
2077 const char *p = refname;
2079 /* Find total no of '/' separated path-components */
2080 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2083 * The number of components we need to strip is now
2084 * the total minus the components to be left (Plus one
2085 * because we count the number of '/', but the number
2086 * of components is one more than the no of '/').
2088 remaining = i + len + 1;
2091 while (remaining > 0) {
2092 switch (*start++) {
2093 case '\0':
2094 free((char *)to_free);
2095 return xstrdup("");
2096 case '/':
2097 remaining--;
2098 break;
2102 start = xstrdup(start);
2103 free((char *)to_free);
2104 return start;
2107 static const char *rstrip_ref_components(const char *refname, int len)
2109 long remaining = len;
2110 const char *start = xstrdup(refname);
2111 const char *to_free = start;
2113 if (len < 0) {
2114 int i;
2115 const char *p = refname;
2117 /* Find total no of '/' separated path-components */
2118 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2121 * The number of components we need to strip is now
2122 * the total minus the components to be left (Plus one
2123 * because we count the number of '/', but the number
2124 * of components is one more than the no of '/').
2126 remaining = i + len + 1;
2129 while (remaining-- > 0) {
2130 char *p = strrchr(start, '/');
2131 if (!p) {
2132 free((char *)to_free);
2133 return xstrdup("");
2134 } else
2135 p[0] = '\0';
2137 return start;
2140 static const char *show_ref(struct refname_atom *atom, const char *refname)
2142 if (atom->option == R_SHORT)
2143 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2144 refname,
2145 warn_ambiguous_refs);
2146 else if (atom->option == R_LSTRIP)
2147 return lstrip_ref_components(refname, atom->lstrip);
2148 else if (atom->option == R_RSTRIP)
2149 return rstrip_ref_components(refname, atom->rstrip);
2150 else
2151 return xstrdup(refname);
2154 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2155 struct branch *branch, const char **s)
2157 int num_ours, num_theirs;
2158 if (atom->u.remote_ref.option == RR_REF)
2159 *s = show_ref(&atom->u.remote_ref.refname, refname);
2160 else if (atom->u.remote_ref.option == RR_TRACK) {
2161 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2162 NULL, atom->u.remote_ref.push,
2163 AHEAD_BEHIND_FULL) < 0) {
2164 *s = xstrdup(msgs.gone);
2165 } else if (!num_ours && !num_theirs)
2166 *s = xstrdup("");
2167 else if (!num_ours)
2168 *s = xstrfmt(msgs.behind, num_theirs);
2169 else if (!num_theirs)
2170 *s = xstrfmt(msgs.ahead, num_ours);
2171 else
2172 *s = xstrfmt(msgs.ahead_behind,
2173 num_ours, num_theirs);
2174 if (!atom->u.remote_ref.nobracket && *s[0]) {
2175 const char *to_free = *s;
2176 *s = xstrfmt("[%s]", *s);
2177 free((void *)to_free);
2179 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2180 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2181 NULL, atom->u.remote_ref.push,
2182 AHEAD_BEHIND_FULL) < 0) {
2183 *s = xstrdup("");
2184 return;
2186 if (!num_ours && !num_theirs)
2187 *s = xstrdup("=");
2188 else if (!num_ours)
2189 *s = xstrdup("<");
2190 else if (!num_theirs)
2191 *s = xstrdup(">");
2192 else
2193 *s = xstrdup("<>");
2194 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2195 int explicit;
2196 const char *remote = atom->u.remote_ref.push ?
2197 pushremote_for_branch(branch, &explicit) :
2198 remote_for_branch(branch, &explicit);
2199 *s = xstrdup(explicit ? remote : "");
2200 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2201 const char *merge;
2203 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2204 *s = xstrdup(merge ? merge : "");
2205 } else
2206 BUG("unhandled RR_* enum");
2209 char *get_head_description(void)
2211 struct strbuf desc = STRBUF_INIT;
2212 struct wt_status_state state;
2213 memset(&state, 0, sizeof(state));
2214 wt_status_get_state(the_repository, &state, 1);
2215 if (state.rebase_in_progress ||
2216 state.rebase_interactive_in_progress) {
2217 if (state.branch)
2218 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2219 state.branch);
2220 else
2221 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2222 state.detached_from);
2223 } else if (state.bisect_in_progress)
2224 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2225 state.bisecting_from);
2226 else if (state.detached_from) {
2227 if (state.detached_at)
2228 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2229 state.detached_from);
2230 else
2231 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2232 state.detached_from);
2233 } else
2234 strbuf_addstr(&desc, _("(no branch)"));
2236 wt_status_state_free_buffers(&state);
2238 return strbuf_detach(&desc, NULL);
2241 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2243 if (!ref->symref)
2244 return xstrdup("");
2245 else
2246 return show_ref(&atom->u.refname, ref->symref);
2249 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2251 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2252 return get_head_description();
2253 return show_ref(&atom->u.refname, ref->refname);
2256 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
2257 struct expand_data *oi, struct strbuf *err)
2259 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
2260 int eaten = 1;
2261 if (oi->info.contentp) {
2262 /* We need to know that to use parse_object_buffer properly */
2263 oi->info.sizep = &oi->size;
2264 oi->info.typep = &oi->type;
2266 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
2267 OBJECT_INFO_LOOKUP_REPLACE))
2268 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2269 oid_to_hex(&oi->oid), ref->refname);
2270 if (oi->info.disk_sizep && oi->disk_size < 0)
2271 BUG("Object size is less than zero.");
2273 if (oi->info.contentp) {
2274 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
2275 if (!*obj) {
2276 if (!eaten)
2277 free(oi->content);
2278 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
2279 oid_to_hex(&oi->oid), ref->refname);
2281 grab_values(ref->value, deref, *obj, oi);
2284 grab_common_values(ref->value, deref, oi);
2285 if (!eaten)
2286 free(oi->content);
2287 return 0;
2290 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2292 int i;
2294 for (i = 0; worktrees[i]; i++) {
2295 if (worktrees[i]->head_ref) {
2296 struct ref_to_worktree_entry *entry;
2297 entry = xmalloc(sizeof(*entry));
2298 entry->wt = worktrees[i];
2299 hashmap_entry_init(&entry->ent,
2300 strhash(worktrees[i]->head_ref));
2302 hashmap_add(map, &entry->ent);
2307 static void lazy_init_worktree_map(void)
2309 if (ref_to_worktree_map.worktrees)
2310 return;
2312 ref_to_worktree_map.worktrees = get_worktrees();
2313 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2314 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2317 static char *get_worktree_path(const struct ref_array_item *ref)
2319 struct hashmap_entry entry, *e;
2320 struct ref_to_worktree_entry *lookup_result;
2322 lazy_init_worktree_map();
2324 hashmap_entry_init(&entry, strhash(ref->refname));
2325 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2327 if (!e)
2328 return xstrdup("");
2330 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2332 return xstrdup(lookup_result->wt->path);
2336 * Parse the object referred by ref, and grab needed value.
2338 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2340 struct object *obj;
2341 int i;
2342 struct object_info empty = OBJECT_INFO_INIT;
2343 int ahead_behind_atoms = 0;
2345 CALLOC_ARRAY(ref->value, used_atom_cnt);
2347 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2348 ref->symref = refs_resolve_refdup(get_main_ref_store(the_repository),
2349 ref->refname,
2350 RESOLVE_REF_READING,
2351 NULL, NULL);
2352 if (!ref->symref)
2353 ref->symref = xstrdup("");
2356 /* Fill in specials first */
2357 for (i = 0; i < used_atom_cnt; i++) {
2358 struct used_atom *atom = &used_atom[i];
2359 enum atom_type atom_type = atom->atom_type;
2360 const char *name = used_atom[i].name;
2361 struct atom_value *v = &ref->value[i];
2362 int deref = 0;
2363 const char *refname;
2364 struct branch *branch = NULL;
2366 v->s_size = ATOM_SIZE_UNSPECIFIED;
2367 v->handler = append_atom;
2368 v->value = 0;
2369 v->atom = atom;
2371 if (*name == '*') {
2372 deref = 1;
2373 name++;
2376 if (atom_type == ATOM_REFNAME)
2377 refname = get_refname(atom, ref);
2378 else if (atom_type == ATOM_WORKTREEPATH) {
2379 if (ref->kind == FILTER_REFS_BRANCHES)
2380 v->s = get_worktree_path(ref);
2381 else
2382 v->s = xstrdup("");
2383 continue;
2385 else if (atom_type == ATOM_SYMREF)
2386 refname = get_symref(atom, ref);
2387 else if (atom_type == ATOM_UPSTREAM) {
2388 const char *branch_name;
2389 /* only local branches may have an upstream */
2390 if (!skip_prefix(ref->refname, "refs/heads/",
2391 &branch_name)) {
2392 v->s = xstrdup("");
2393 continue;
2395 branch = branch_get(branch_name);
2397 refname = branch_get_upstream(branch, NULL);
2398 if (refname)
2399 fill_remote_ref_details(atom, refname, branch, &v->s);
2400 else
2401 v->s = xstrdup("");
2402 continue;
2403 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2404 const char *branch_name;
2405 v->s = xstrdup("");
2406 if (!skip_prefix(ref->refname, "refs/heads/",
2407 &branch_name))
2408 continue;
2409 branch = branch_get(branch_name);
2411 if (atom->u.remote_ref.push_remote)
2412 refname = NULL;
2413 else {
2414 refname = branch_get_push(branch, NULL);
2415 if (!refname)
2416 continue;
2418 /* We will definitely re-init v->s on the next line. */
2419 free((char *)v->s);
2420 fill_remote_ref_details(atom, refname, branch, &v->s);
2421 continue;
2422 } else if (atom_type == ATOM_COLOR) {
2423 v->s = xstrdup(atom->u.color);
2424 continue;
2425 } else if (atom_type == ATOM_FLAG) {
2426 char buf[256], *cp = buf;
2427 if (ref->flag & REF_ISSYMREF)
2428 cp = copy_advance(cp, ",symref");
2429 if (ref->flag & REF_ISPACKED)
2430 cp = copy_advance(cp, ",packed");
2431 if (cp == buf)
2432 v->s = xstrdup("");
2433 else {
2434 *cp = '\0';
2435 v->s = xstrdup(buf + 1);
2437 continue;
2438 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2439 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2440 continue;
2441 } else if (atom_type == ATOM_HEAD) {
2442 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2443 v->s = xstrdup("*");
2444 else
2445 v->s = xstrdup(" ");
2446 continue;
2447 } else if (atom_type == ATOM_ALIGN) {
2448 v->handler = align_atom_handler;
2449 v->s = xstrdup("");
2450 continue;
2451 } else if (atom_type == ATOM_END) {
2452 v->handler = end_atom_handler;
2453 v->s = xstrdup("");
2454 continue;
2455 } else if (atom_type == ATOM_IF) {
2456 const char *s;
2457 if (skip_prefix(name, "if:", &s))
2458 v->s = xstrdup(s);
2459 else
2460 v->s = xstrdup("");
2461 v->handler = if_atom_handler;
2462 continue;
2463 } else if (atom_type == ATOM_THEN) {
2464 v->handler = then_atom_handler;
2465 v->s = xstrdup("");
2466 continue;
2467 } else if (atom_type == ATOM_ELSE) {
2468 v->handler = else_atom_handler;
2469 v->s = xstrdup("");
2470 continue;
2471 } else if (atom_type == ATOM_REST) {
2472 if (ref->rest)
2473 v->s = xstrdup(ref->rest);
2474 else
2475 v->s = xstrdup("");
2476 continue;
2477 } else if (atom_type == ATOM_AHEADBEHIND) {
2478 if (ref->counts) {
2479 const struct ahead_behind_count *count;
2480 count = ref->counts[ahead_behind_atoms++];
2481 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2482 } else {
2483 /* Not a commit. */
2484 v->s = xstrdup("");
2486 continue;
2487 } else
2488 continue;
2490 if (!deref)
2491 v->s = xstrdup(refname);
2492 else
2493 v->s = xstrfmt("%s^{}", refname);
2494 free((char *)refname);
2497 for (i = 0; i < used_atom_cnt; i++) {
2498 struct atom_value *v = &ref->value[i];
2499 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2500 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2501 oid_to_hex(&ref->objectname), ref->refname);
2504 if (need_tagged)
2505 oi.info.contentp = &oi.content;
2506 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2507 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2508 return 0;
2511 oi.oid = ref->objectname;
2512 if (get_object(ref, 0, &obj, &oi, err))
2513 return -1;
2516 * If there is no atom that wants to know about tagged
2517 * object, we are done.
2519 if (!need_tagged || (obj->type != OBJ_TAG))
2520 return 0;
2523 * If it is a tag object, see if we use the peeled value. If we do,
2524 * grab the peeled OID.
2526 if (need_tagged && peel_iterated_oid(the_repository, &obj->oid, &oi_deref.oid))
2527 die("bad tag");
2529 return get_object(ref, 1, &obj, &oi_deref, err);
2533 * Given a ref, return the value for the atom. This lazily gets value
2534 * out of the object by calling populate value.
2536 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2537 struct atom_value **v, struct strbuf *err)
2539 if (!ref->value) {
2540 if (populate_value(ref, err))
2541 return -1;
2542 fill_missing_values(ref->value);
2544 *v = &ref->value[atom];
2545 return 0;
2549 * Return 1 if the refname matches one of the patterns, otherwise 0.
2550 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2551 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2552 * matches "refs/heads/mas*", too).
2554 static int match_pattern(const char **patterns, const char *refname,
2555 int ignore_case)
2557 unsigned flags = 0;
2559 if (ignore_case)
2560 flags |= WM_CASEFOLD;
2563 * When no '--format' option is given we need to skip the prefix
2564 * for matching refs of tags and branches.
2566 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2567 skip_prefix(refname, "refs/heads/", &refname) ||
2568 skip_prefix(refname, "refs/remotes/", &refname) ||
2569 skip_prefix(refname, "refs/", &refname));
2571 for (; *patterns; patterns++) {
2572 if (!wildmatch(*patterns, refname, flags))
2573 return 1;
2575 return 0;
2579 * Return 1 if the refname matches one of the patterns, otherwise 0.
2580 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2581 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2582 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2584 static int match_name_as_path(const char **pattern, const char *refname,
2585 int ignore_case)
2587 int namelen = strlen(refname);
2588 unsigned flags = WM_PATHNAME;
2590 if (ignore_case)
2591 flags |= WM_CASEFOLD;
2593 for (; *pattern; pattern++) {
2594 const char *p = *pattern;
2595 int plen = strlen(p);
2597 if ((plen <= namelen) &&
2598 !strncmp(refname, p, plen) &&
2599 (refname[plen] == '\0' ||
2600 refname[plen] == '/' ||
2601 p[plen-1] == '/'))
2602 return 1;
2603 if (!wildmatch(p, refname, flags))
2604 return 1;
2606 return 0;
2609 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2610 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2612 if (!*filter->name_patterns)
2613 return 1; /* No pattern always matches */
2614 if (filter->match_as_path)
2615 return match_name_as_path(filter->name_patterns, refname,
2616 filter->ignore_case);
2617 return match_pattern(filter->name_patterns, refname,
2618 filter->ignore_case);
2621 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2623 if (!filter->exclude.nr)
2624 return 0;
2625 if (filter->match_as_path)
2626 return match_name_as_path(filter->exclude.v, refname,
2627 filter->ignore_case);
2628 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2632 * This is the same as for_each_fullref_in(), but it tries to iterate
2633 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2634 * pattern match, so the callback still has to match each ref individually.
2636 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2637 each_ref_fn cb,
2638 void *cb_data)
2640 if (filter->kind & FILTER_REFS_ROOT_REFS) {
2641 /* In this case, we want to print all refs including root refs. */
2642 return refs_for_each_include_root_refs(get_main_ref_store(the_repository),
2643 cb, cb_data);
2646 if (!filter->match_as_path) {
2648 * in this case, the patterns are applied after
2649 * prefixes like "refs/heads/" etc. are stripped off,
2650 * so we have to look at everything:
2652 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2653 "", NULL, cb, cb_data);
2656 if (filter->ignore_case) {
2658 * we can't handle case-insensitive comparisons,
2659 * so just return everything and let the caller
2660 * sort it out.
2662 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2663 "", NULL, cb, cb_data);
2666 if (!filter->name_patterns[0]) {
2667 /* no patterns; we have to look at everything */
2668 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2669 "", filter->exclude.v, cb, cb_data);
2672 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2673 NULL, filter->name_patterns,
2674 filter->exclude.v,
2675 cb, cb_data);
2679 * Given a ref (oid, refname), check if the ref belongs to the array
2680 * of oids. If the given ref is a tag, check if the given tag points
2681 * at one of the oids in the given oid array. Returns non-zero if a
2682 * match is found.
2684 * NEEDSWORK:
2685 * As the refs are cached we might know what refname peels to without
2686 * the need to parse the object via parse_object(). peel_ref() might be a
2687 * more efficient alternative to obtain the pointee.
2689 static int match_points_at(struct oid_array *points_at,
2690 const struct object_id *oid,
2691 const char *refname)
2693 struct object *obj;
2695 if (oid_array_lookup(points_at, oid) >= 0)
2696 return 1;
2697 obj = parse_object_with_flags(the_repository, oid,
2698 PARSE_OBJECT_SKIP_HASH_CHECK);
2699 while (obj && obj->type == OBJ_TAG) {
2700 struct tag *tag = (struct tag *)obj;
2702 if (parse_tag(tag) < 0) {
2703 obj = NULL;
2704 break;
2707 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2708 return 1;
2710 obj = tag->tagged;
2712 if (!obj)
2713 die(_("malformed object at '%s'"), refname);
2714 return 0;
2718 * Allocate space for a new ref_array_item and copy the name and oid to it.
2720 * Callers can then fill in other struct members at their leisure.
2722 static struct ref_array_item *new_ref_array_item(const char *refname,
2723 const struct object_id *oid)
2725 struct ref_array_item *ref;
2727 FLEX_ALLOC_STR(ref, refname, refname);
2728 oidcpy(&ref->objectname, oid);
2729 ref->rest = NULL;
2731 return ref;
2734 static void ref_array_append(struct ref_array *array, struct ref_array_item *ref)
2736 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2737 array->items[array->nr++] = ref;
2740 struct ref_array_item *ref_array_push(struct ref_array *array,
2741 const char *refname,
2742 const struct object_id *oid)
2744 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2745 ref_array_append(array, ref);
2746 return ref;
2749 static int ref_kind_from_refname(const char *refname)
2751 unsigned int i;
2753 static struct {
2754 const char *prefix;
2755 unsigned int kind;
2756 } ref_kind[] = {
2757 { "refs/heads/" , FILTER_REFS_BRANCHES },
2758 { "refs/remotes/" , FILTER_REFS_REMOTES },
2759 { "refs/tags/", FILTER_REFS_TAGS}
2762 if (!strcmp(refname, "HEAD"))
2763 return FILTER_REFS_DETACHED_HEAD;
2765 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2766 if (starts_with(refname, ref_kind[i].prefix))
2767 return ref_kind[i].kind;
2770 if (is_pseudo_ref(refname))
2771 return FILTER_REFS_PSEUDOREFS;
2772 if (is_root_ref(refname))
2773 return FILTER_REFS_ROOT_REFS;
2775 return FILTER_REFS_OTHERS;
2778 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2780 if (filter->kind == FILTER_REFS_BRANCHES ||
2781 filter->kind == FILTER_REFS_REMOTES ||
2782 filter->kind == FILTER_REFS_TAGS)
2783 return filter->kind;
2784 return ref_kind_from_refname(refname);
2787 static struct ref_array_item *apply_ref_filter(const char *refname, const struct object_id *oid,
2788 int flag, struct ref_filter *filter)
2790 struct ref_array_item *ref;
2791 struct commit *commit = NULL;
2792 unsigned int kind;
2794 if (flag & REF_BAD_NAME) {
2795 warning(_("ignoring ref with broken name %s"), refname);
2796 return NULL;
2799 if (flag & REF_ISBROKEN) {
2800 warning(_("ignoring broken ref %s"), refname);
2801 return NULL;
2804 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2805 kind = filter_ref_kind(filter, refname);
2808 * Generally HEAD refs are printed with special description denoting a rebase,
2809 * detached state and so forth. This is useful when only printing the HEAD ref
2810 * But when it is being printed along with other root refs, it makes sense to
2811 * keep the formatting consistent. So we mask the type to act like a root ref.
2813 if (filter->kind & FILTER_REFS_ROOT_REFS && kind == FILTER_REFS_DETACHED_HEAD)
2814 kind = FILTER_REFS_ROOT_REFS;
2815 else if (!(kind & filter->kind))
2816 return NULL;
2818 if (!filter_pattern_match(filter, refname))
2819 return NULL;
2821 if (filter_exclude_match(filter, refname))
2822 return NULL;
2824 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2825 return NULL;
2828 * A merge filter is applied on refs pointing to commits. Hence
2829 * obtain the commit using the 'oid' available and discard all
2830 * non-commits early. The actual filtering is done later.
2832 if (filter->reachable_from || filter->unreachable_from ||
2833 filter->with_commit || filter->no_commit || filter->verbose) {
2834 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2835 if (!commit)
2836 return NULL;
2837 /* We perform the filtering for the '--contains' option... */
2838 if (filter->with_commit &&
2839 !commit_contains(filter, commit, filter->with_commit, &filter->internal.contains_cache))
2840 return NULL;
2841 /* ...or for the `--no-contains' option */
2842 if (filter->no_commit &&
2843 commit_contains(filter, commit, filter->no_commit, &filter->internal.no_contains_cache))
2844 return NULL;
2848 * We do not open the object yet; sort may only need refname
2849 * to do its job and the resulting list may yet to be pruned
2850 * by maxcount logic.
2852 ref = new_ref_array_item(refname, oid);
2853 ref->commit = commit;
2854 ref->flag = flag;
2855 ref->kind = kind;
2857 return ref;
2860 struct ref_filter_cbdata {
2861 struct ref_array *array;
2862 struct ref_filter *filter;
2866 * A call-back given to for_each_ref(). Filter refs and keep them for
2867 * later object processing.
2869 static int filter_one(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2871 struct ref_filter_cbdata *ref_cbdata = cb_data;
2872 struct ref_array_item *ref;
2874 ref = apply_ref_filter(refname, oid, flag, ref_cbdata->filter);
2875 if (ref)
2876 ref_array_append(ref_cbdata->array, ref);
2878 return 0;
2881 /* Free memory allocated for a ref_array_item */
2882 static void free_array_item(struct ref_array_item *item)
2884 free((char *)item->symref);
2885 if (item->value) {
2886 int i;
2887 for (i = 0; i < used_atom_cnt; i++)
2888 free((char *)item->value[i].s);
2889 free(item->value);
2891 free(item->counts);
2892 free(item);
2895 struct ref_filter_and_format_cbdata {
2896 struct ref_filter *filter;
2897 struct ref_format *format;
2899 struct ref_filter_and_format_internal {
2900 int count;
2901 } internal;
2904 static int filter_and_format_one(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2906 struct ref_filter_and_format_cbdata *ref_cbdata = cb_data;
2907 struct ref_array_item *ref;
2908 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
2910 ref = apply_ref_filter(refname, oid, flag, ref_cbdata->filter);
2911 if (!ref)
2912 return 0;
2914 if (format_ref_array_item(ref, ref_cbdata->format, &output, &err))
2915 die("%s", err.buf);
2917 if (output.len || !ref_cbdata->format->array_opts.omit_empty) {
2918 fwrite(output.buf, 1, output.len, stdout);
2919 putchar('\n');
2922 strbuf_release(&output);
2923 strbuf_release(&err);
2924 free_array_item(ref);
2927 * Increment the running count of refs that match the filter. If
2928 * max_count is set and we've reached the max, stop the ref
2929 * iteration by returning a nonzero value.
2931 if (ref_cbdata->format->array_opts.max_count &&
2932 ++ref_cbdata->internal.count >= ref_cbdata->format->array_opts.max_count)
2933 return 1;
2935 return 0;
2938 /* Free all memory allocated for ref_array */
2939 void ref_array_clear(struct ref_array *array)
2941 int i;
2943 for (i = 0; i < array->nr; i++)
2944 free_array_item(array->items[i]);
2945 FREE_AND_NULL(array->items);
2946 array->nr = array->alloc = 0;
2948 for (i = 0; i < used_atom_cnt; i++) {
2949 struct used_atom *atom = &used_atom[i];
2950 if (atom->atom_type == ATOM_HEAD)
2951 free(atom->u.head);
2952 free((char *)atom->name);
2954 FREE_AND_NULL(used_atom);
2955 used_atom_cnt = 0;
2957 if (ref_to_worktree_map.worktrees) {
2958 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2959 struct ref_to_worktree_entry, ent);
2960 free_worktrees(ref_to_worktree_map.worktrees);
2961 ref_to_worktree_map.worktrees = NULL;
2964 FREE_AND_NULL(array->counts);
2967 #define EXCLUDE_REACHED 0
2968 #define INCLUDE_REACHED 1
2969 static void reach_filter(struct ref_array *array,
2970 struct commit_list **check_reachable,
2971 int include_reached)
2973 int i, old_nr;
2974 struct commit **to_clear;
2976 if (!*check_reachable)
2977 return;
2979 CALLOC_ARRAY(to_clear, array->nr);
2980 for (i = 0; i < array->nr; i++) {
2981 struct ref_array_item *item = array->items[i];
2982 to_clear[i] = item->commit;
2985 tips_reachable_from_bases(the_repository,
2986 *check_reachable,
2987 to_clear, array->nr,
2988 UNINTERESTING);
2990 old_nr = array->nr;
2991 array->nr = 0;
2993 for (i = 0; i < old_nr; i++) {
2994 struct ref_array_item *item = array->items[i];
2995 struct commit *commit = item->commit;
2997 int is_merged = !!(commit->object.flags & UNINTERESTING);
2999 if (is_merged == include_reached)
3000 array->items[array->nr++] = array->items[i];
3001 else
3002 free_array_item(item);
3005 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
3007 while (*check_reachable) {
3008 struct commit *merge_commit = pop_commit(check_reachable);
3009 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
3012 free(to_clear);
3015 void filter_ahead_behind(struct repository *r,
3016 struct ref_format *format,
3017 struct ref_array *array)
3019 struct commit **commits;
3020 size_t commits_nr = format->bases.nr + array->nr;
3022 if (!format->bases.nr || !array->nr)
3023 return;
3025 ALLOC_ARRAY(commits, commits_nr);
3026 for (size_t i = 0; i < format->bases.nr; i++)
3027 commits[i] = format->bases.items[i].util;
3029 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
3031 commits_nr = format->bases.nr;
3032 array->counts_nr = 0;
3033 for (size_t i = 0; i < array->nr; i++) {
3034 const char *name = array->items[i]->refname;
3035 commits[commits_nr] = lookup_commit_reference_by_name(name);
3037 if (!commits[commits_nr])
3038 continue;
3040 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
3041 for (size_t j = 0; j < format->bases.nr; j++) {
3042 struct ahead_behind_count *count;
3043 count = &array->counts[array->counts_nr++];
3044 count->tip_index = commits_nr;
3045 count->base_index = j;
3047 array->items[i]->counts[j] = count;
3049 commits_nr++;
3052 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
3053 free(commits);
3056 static int do_filter_refs(struct ref_filter *filter, unsigned int type, each_ref_fn fn, void *cb_data)
3058 int ret = 0;
3060 filter->kind = type & FILTER_REFS_KIND_MASK;
3062 init_contains_cache(&filter->internal.contains_cache);
3063 init_contains_cache(&filter->internal.no_contains_cache);
3065 /* Simple per-ref filtering */
3066 if (!filter->kind)
3067 die("filter_refs: invalid type");
3068 else {
3070 * For common cases where we need only branches or remotes or tags,
3071 * we only iterate through those refs. If a mix of refs is needed,
3072 * we iterate over all refs and filter out required refs with the help
3073 * of filter_ref_kind().
3075 if (filter->kind == FILTER_REFS_BRANCHES)
3076 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3077 "refs/heads/", NULL,
3078 fn, cb_data);
3079 else if (filter->kind == FILTER_REFS_REMOTES)
3080 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3081 "refs/remotes/", NULL,
3082 fn, cb_data);
3083 else if (filter->kind == FILTER_REFS_TAGS)
3084 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3085 "refs/tags/", NULL, fn,
3086 cb_data);
3087 else if (filter->kind & FILTER_REFS_REGULAR)
3088 ret = for_each_fullref_in_pattern(filter, fn, cb_data);
3091 * When printing all ref types, HEAD is already included,
3092 * so we don't want to print HEAD again.
3094 if (!ret && !(filter->kind & FILTER_REFS_ROOT_REFS) &&
3095 (filter->kind & FILTER_REFS_DETACHED_HEAD))
3096 refs_head_ref(get_main_ref_store(the_repository), fn,
3097 cb_data);
3100 clear_contains_cache(&filter->internal.contains_cache);
3101 clear_contains_cache(&filter->internal.no_contains_cache);
3103 return ret;
3107 * API for filtering a set of refs. Based on the type of refs the user
3108 * has requested, we iterate through those refs and apply filters
3109 * as per the given ref_filter structure and finally store the
3110 * filtered refs in the ref_array structure.
3112 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
3114 struct ref_filter_cbdata ref_cbdata;
3115 int save_commit_buffer_orig;
3116 int ret = 0;
3118 ref_cbdata.array = array;
3119 ref_cbdata.filter = filter;
3121 save_commit_buffer_orig = save_commit_buffer;
3122 save_commit_buffer = 0;
3124 ret = do_filter_refs(filter, type, filter_one, &ref_cbdata);
3126 /* Filters that need revision walking */
3127 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
3128 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
3130 save_commit_buffer = save_commit_buffer_orig;
3131 return ret;
3134 static inline int can_do_iterative_format(struct ref_filter *filter,
3135 struct ref_sorting *sorting,
3136 struct ref_format *format)
3139 * Filtering & formatting results within a single ref iteration
3140 * callback is not compatible with options that require
3141 * post-processing a filtered ref_array. These include:
3142 * - filtering on reachability
3143 * - sorting the filtered results
3144 * - including ahead-behind information in the formatted output
3146 return !(filter->reachable_from ||
3147 filter->unreachable_from ||
3148 sorting ||
3149 format->bases.nr);
3152 void filter_and_format_refs(struct ref_filter *filter, unsigned int type,
3153 struct ref_sorting *sorting,
3154 struct ref_format *format)
3156 if (can_do_iterative_format(filter, sorting, format)) {
3157 int save_commit_buffer_orig;
3158 struct ref_filter_and_format_cbdata ref_cbdata = {
3159 .filter = filter,
3160 .format = format,
3163 save_commit_buffer_orig = save_commit_buffer;
3164 save_commit_buffer = 0;
3166 do_filter_refs(filter, type, filter_and_format_one, &ref_cbdata);
3168 save_commit_buffer = save_commit_buffer_orig;
3169 } else {
3170 struct ref_array array = { 0 };
3171 filter_refs(&array, filter, type);
3172 filter_ahead_behind(the_repository, format, &array);
3173 ref_array_sort(sorting, &array);
3174 print_formatted_ref_array(&array, format);
3175 ref_array_clear(&array);
3179 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
3181 if (!(a->kind ^ b->kind))
3182 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
3183 if (a->kind & FILTER_REFS_DETACHED_HEAD)
3184 return -1;
3185 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
3186 return 1;
3187 BUG("should have died in the xor check above");
3188 return 0;
3191 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
3193 const char *s1 = vs1, *s2 = vs2;
3194 const char *end = s1 + n;
3196 for (; s1 < end; s1++, s2++) {
3197 int diff = tolower(*s1) - tolower(*s2);
3198 if (diff)
3199 return diff;
3201 return 0;
3204 struct ref_sorting {
3205 struct ref_sorting *next;
3206 int atom; /* index into used_atom array (internal) */
3207 enum ref_sorting_order sort_flags;
3210 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
3212 struct atom_value *va, *vb;
3213 int cmp;
3214 int cmp_detached_head = 0;
3215 cmp_type cmp_type = used_atom[s->atom].type;
3216 struct strbuf err = STRBUF_INIT;
3218 if (get_ref_atom_value(a, s->atom, &va, &err))
3219 die("%s", err.buf);
3220 if (get_ref_atom_value(b, s->atom, &vb, &err))
3221 die("%s", err.buf);
3222 strbuf_release(&err);
3223 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
3224 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
3225 cmp = compare_detached_head(a, b);
3226 cmp_detached_head = 1;
3227 } else if (s->sort_flags & REF_SORTING_VERSION) {
3228 cmp = versioncmp(va->s, vb->s);
3229 } else if (cmp_type == FIELD_STR) {
3230 if (va->s_size < 0 && vb->s_size < 0) {
3231 int (*cmp_fn)(const char *, const char *);
3232 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3233 ? strcasecmp : strcmp;
3234 cmp = cmp_fn(va->s, vb->s);
3235 } else {
3236 size_t a_size = va->s_size < 0 ?
3237 strlen(va->s) : va->s_size;
3238 size_t b_size = vb->s_size < 0 ?
3239 strlen(vb->s) : vb->s_size;
3240 int (*cmp_fn)(const void *, const void *, size_t);
3241 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3242 ? memcasecmp : memcmp;
3244 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3245 a_size : b_size);
3246 if (!cmp) {
3247 if (a_size > b_size)
3248 cmp = 1;
3249 else if (a_size < b_size)
3250 cmp = -1;
3253 } else {
3254 if (va->value < vb->value)
3255 cmp = -1;
3256 else if (va->value == vb->value)
3257 cmp = 0;
3258 else
3259 cmp = 1;
3262 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3263 ? -cmp : cmp;
3266 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3268 struct ref_array_item *a = *((struct ref_array_item **)a_);
3269 struct ref_array_item *b = *((struct ref_array_item **)b_);
3270 struct ref_sorting *s;
3272 for (s = ref_sorting; s; s = s->next) {
3273 int cmp = cmp_ref_sorting(s, a, b);
3274 if (cmp)
3275 return cmp;
3277 s = ref_sorting;
3278 return s && s->sort_flags & REF_SORTING_ICASE ?
3279 strcasecmp(a->refname, b->refname) :
3280 strcmp(a->refname, b->refname);
3283 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3284 unsigned int mask, int on)
3286 for (; sorting; sorting = sorting->next) {
3287 if (on)
3288 sorting->sort_flags |= mask;
3289 else
3290 sorting->sort_flags &= ~mask;
3294 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3296 if (sorting)
3297 QSORT_S(array->items, array->nr, compare_refs, sorting);
3300 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3302 struct strbuf *s = &state->stack->output;
3304 while (*cp && (!ep || cp < ep)) {
3305 if (*cp == '%') {
3306 if (cp[1] == '%')
3307 cp++;
3308 else {
3309 int ch = hex2chr(cp + 1);
3310 if (0 <= ch) {
3311 strbuf_addch(s, ch);
3312 cp += 3;
3313 continue;
3317 strbuf_addch(s, *cp);
3318 cp++;
3322 int format_ref_array_item(struct ref_array_item *info,
3323 struct ref_format *format,
3324 struct strbuf *final_buf,
3325 struct strbuf *error_buf)
3327 const char *cp, *sp, *ep;
3328 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3330 state.quote_style = format->quote_style;
3331 push_stack_element(&state.stack);
3333 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3334 struct atom_value *atomv;
3335 int pos;
3337 ep = strchr(sp, ')');
3338 if (cp < sp)
3339 append_literal(cp, sp, &state);
3340 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3341 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3342 atomv->handler(atomv, &state, error_buf)) {
3343 pop_stack_element(&state.stack);
3344 return -1;
3347 if (*cp) {
3348 sp = cp + strlen(cp);
3349 append_literal(cp, sp, &state);
3351 if (format->need_color_reset_at_eol) {
3352 struct atom_value resetv = ATOM_VALUE_INIT;
3353 resetv.s = GIT_COLOR_RESET;
3354 if (append_atom(&resetv, &state, error_buf)) {
3355 pop_stack_element(&state.stack);
3356 return -1;
3359 if (state.stack->prev) {
3360 pop_stack_element(&state.stack);
3361 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3363 strbuf_addbuf(final_buf, &state.stack->output);
3364 pop_stack_element(&state.stack);
3365 return 0;
3368 void print_formatted_ref_array(struct ref_array *array, struct ref_format *format)
3370 int total;
3371 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3373 total = format->array_opts.max_count;
3374 if (!total || array->nr < total)
3375 total = array->nr;
3376 for (int i = 0; i < total; i++) {
3377 strbuf_reset(&err);
3378 strbuf_reset(&output);
3379 if (format_ref_array_item(array->items[i], format, &output, &err))
3380 die("%s", err.buf);
3381 if (output.len || !format->array_opts.omit_empty) {
3382 fwrite(output.buf, 1, output.len, stdout);
3383 putchar('\n');
3387 strbuf_release(&err);
3388 strbuf_release(&output);
3391 void pretty_print_ref(const char *name, const struct object_id *oid,
3392 struct ref_format *format)
3394 struct ref_array_item *ref_item;
3395 struct strbuf output = STRBUF_INIT;
3396 struct strbuf err = STRBUF_INIT;
3398 ref_item = new_ref_array_item(name, oid);
3399 ref_item->kind = ref_kind_from_refname(name);
3400 if (format_ref_array_item(ref_item, format, &output, &err))
3401 die("%s", err.buf);
3402 fwrite(output.buf, 1, output.len, stdout);
3403 putchar('\n');
3405 strbuf_release(&err);
3406 strbuf_release(&output);
3407 free_array_item(ref_item);
3410 static int parse_sorting_atom(const char *atom)
3413 * This parses an atom using a dummy ref_format, since we don't
3414 * actually care about the formatting details.
3416 struct ref_format dummy = REF_FORMAT_INIT;
3417 const char *end = atom + strlen(atom);
3418 struct strbuf err = STRBUF_INIT;
3419 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3420 if (res < 0)
3421 die("%s", err.buf);
3422 strbuf_release(&err);
3423 return res;
3426 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3428 struct ref_sorting *s;
3430 CALLOC_ARRAY(s, 1);
3431 s->next = *sorting_tail;
3432 *sorting_tail = s;
3434 if (*arg == '-') {
3435 s->sort_flags |= REF_SORTING_REVERSE;
3436 arg++;
3438 if (skip_prefix(arg, "version:", &arg) ||
3439 skip_prefix(arg, "v:", &arg))
3440 s->sort_flags |= REF_SORTING_VERSION;
3441 s->atom = parse_sorting_atom(arg);
3444 struct ref_sorting *ref_sorting_options(struct string_list *options)
3446 struct string_list_item *item;
3447 struct ref_sorting *sorting = NULL, **tail = &sorting;
3449 if (options->nr) {
3450 for_each_string_list_item(item, options)
3451 parse_ref_sorting(tail, item->string);
3455 * From here on, the ref_sorting list should be used to talk
3456 * about the sort order used for the output. The caller
3457 * should not touch the string form anymore.
3459 string_list_clear(options, 0);
3460 return sorting;
3463 void ref_sorting_release(struct ref_sorting *sorting)
3465 while (sorting) {
3466 struct ref_sorting *next = sorting->next;
3467 free(sorting);
3468 sorting = next;
3472 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3474 struct ref_filter *rf = opt->value;
3475 struct object_id oid;
3476 struct commit *merge_commit;
3478 BUG_ON_OPT_NEG(unset);
3480 if (repo_get_oid(the_repository, arg, &oid))
3481 die(_("malformed object name %s"), arg);
3483 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3485 if (!merge_commit)
3486 return error(_("option `%s' must point to a commit"), opt->long_name);
3488 if (starts_with(opt->long_name, "no"))
3489 commit_list_insert(merge_commit, &rf->unreachable_from);
3490 else
3491 commit_list_insert(merge_commit, &rf->reachable_from);
3493 return 0;
3496 void ref_filter_init(struct ref_filter *filter)
3498 struct ref_filter blank = REF_FILTER_INIT;
3499 memcpy(filter, &blank, sizeof(blank));
3502 void ref_filter_clear(struct ref_filter *filter)
3504 strvec_clear(&filter->exclude);
3505 oid_array_clear(&filter->points_at);
3506 free_commit_list(filter->with_commit);
3507 free_commit_list(filter->no_commit);
3508 free_commit_list(filter->reachable_from);
3509 free_commit_list(filter->unreachable_from);
3510 ref_filter_init(filter);