t0410: make test description clearer
[git/gitster.git] / ref-filter.c
blob84c603610723eacf15349e0c5809a771de418bfd
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 "repo-settings.h"
17 #include "repository.h"
18 #include "commit.h"
19 #include "mailmap.h"
20 #include "ident.h"
21 #include "remote.h"
22 #include "color.h"
23 #include "tag.h"
24 #include "quote.h"
25 #include "ref-filter.h"
26 #include "revision.h"
27 #include "utf8.h"
28 #include "versioncmp.h"
29 #include "trailer.h"
30 #include "wt-status.h"
31 #include "commit-slab.h"
32 #include "commit-reach.h"
33 #include "worktree.h"
34 #include "hashmap.h"
36 static struct ref_msg {
37 const char *gone;
38 const char *ahead;
39 const char *behind;
40 const char *ahead_behind;
41 } msgs = {
42 /* Untranslated plumbing messages: */
43 "gone",
44 "ahead %d",
45 "behind %d",
46 "ahead %d, behind %d"
49 void setup_ref_filter_porcelain_msg(void)
51 msgs.gone = _("gone");
52 msgs.ahead = _("ahead %d");
53 msgs.behind = _("behind %d");
54 msgs.ahead_behind = _("ahead %d, behind %d");
57 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
58 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
59 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
61 struct align {
62 align_type position;
63 unsigned int width;
66 struct if_then_else {
67 cmp_status cmp_status;
68 const char *str;
69 unsigned int then_atom_seen : 1,
70 else_atom_seen : 1,
71 condition_satisfied : 1;
74 struct refname_atom {
75 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
76 int lstrip, rstrip;
79 struct ref_trailer_buf {
80 struct string_list filter_list;
81 struct strbuf sepbuf;
82 struct strbuf kvsepbuf;
85 static struct expand_data {
86 struct object_id oid;
87 enum object_type type;
88 unsigned long size;
89 off_t disk_size;
90 struct object_id delta_base_oid;
91 void *content;
93 struct object_info info;
94 } oi, oi_deref;
96 struct ref_to_worktree_entry {
97 struct hashmap_entry ent;
98 struct worktree *wt; /* key is wt->head_ref */
101 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
102 const struct hashmap_entry *eptr,
103 const struct hashmap_entry *kptr,
104 const void *keydata_aka_refname)
106 const struct ref_to_worktree_entry *e, *k;
108 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
109 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
111 return strcmp(e->wt->head_ref,
112 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
115 static struct ref_to_worktree_map {
116 struct hashmap map;
117 struct worktree **worktrees;
118 } ref_to_worktree_map;
121 * The enum atom_type is used as the index of valid_atom array.
122 * In the atom parsing stage, it will be passed to used_atom.atom_type
123 * as the identifier of the atom type. We can check the type of used_atom
124 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
126 enum atom_type {
127 ATOM_REFNAME,
128 ATOM_OBJECTTYPE,
129 ATOM_OBJECTSIZE,
130 ATOM_OBJECTNAME,
131 ATOM_DELTABASE,
132 ATOM_TREE,
133 ATOM_PARENT,
134 ATOM_NUMPARENT,
135 ATOM_OBJECT,
136 ATOM_TYPE,
137 ATOM_TAG,
138 ATOM_AUTHOR,
139 ATOM_AUTHORNAME,
140 ATOM_AUTHOREMAIL,
141 ATOM_AUTHORDATE,
142 ATOM_COMMITTER,
143 ATOM_COMMITTERNAME,
144 ATOM_COMMITTEREMAIL,
145 ATOM_COMMITTERDATE,
146 ATOM_TAGGER,
147 ATOM_TAGGERNAME,
148 ATOM_TAGGEREMAIL,
149 ATOM_TAGGERDATE,
150 ATOM_CREATOR,
151 ATOM_CREATORDATE,
152 ATOM_DESCRIBE,
153 ATOM_SUBJECT,
154 ATOM_BODY,
155 ATOM_TRAILERS,
156 ATOM_CONTENTS,
157 ATOM_SIGNATURE,
158 ATOM_RAW,
159 ATOM_UPSTREAM,
160 ATOM_PUSH,
161 ATOM_SYMREF,
162 ATOM_FLAG,
163 ATOM_HEAD,
164 ATOM_COLOR,
165 ATOM_WORKTREEPATH,
166 ATOM_ALIGN,
167 ATOM_END,
168 ATOM_IF,
169 ATOM_THEN,
170 ATOM_ELSE,
171 ATOM_REST,
172 ATOM_AHEADBEHIND,
173 ATOM_ISBASE,
177 * An atom is a valid field atom listed below, possibly prefixed with
178 * a "*" to denote deref_tag().
180 * We parse given format string and sort specifiers, and make a list
181 * of properties that we need to extract out of objects. ref_array_item
182 * structure will hold an array of values extracted that can be
183 * indexed with the "atom number", which is an index into this
184 * array.
186 static struct used_atom {
187 enum atom_type atom_type;
188 const char *name;
189 cmp_type type;
190 info_source source;
191 union {
192 char color[COLOR_MAXLEN];
193 struct align align;
194 struct {
195 enum {
196 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
197 } option;
198 struct refname_atom refname;
199 unsigned int nobracket : 1, push : 1, push_remote : 1;
200 } remote_ref;
201 struct {
202 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
203 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
204 struct process_trailer_options trailer_opts;
205 struct ref_trailer_buf *trailer_buf;
206 unsigned int nlines;
207 } contents;
208 struct {
209 enum { RAW_BARE, RAW_LENGTH } option;
210 } raw_data;
211 struct {
212 cmp_status cmp_status;
213 const char *str;
214 } if_then_else;
215 struct {
216 enum { O_FULL, O_LENGTH, O_SHORT } option;
217 unsigned int length;
218 } oid;
219 struct {
220 enum { O_SIZE, O_SIZE_DISK } option;
221 } objectsize;
222 struct {
223 enum { N_RAW, N_MAILMAP } option;
224 } name_option;
225 struct {
226 enum {
227 EO_RAW = 0,
228 EO_TRIM = 1<<0,
229 EO_LOCALPART = 1<<1,
230 EO_MAILMAP = 1<<2,
231 } option;
232 } email_option;
233 struct {
234 enum { S_BARE, S_GRADE, S_SIGNER, S_KEY,
235 S_FINGERPRINT, S_PRI_KEY_FP, S_TRUST_LEVEL } option;
236 } signature;
237 struct strvec describe_args;
238 struct refname_atom refname;
239 char *head;
240 } u;
241 } *used_atom;
242 static int used_atom_cnt, need_tagged, need_symref;
245 * Expand string, append it to strbuf *sb, then return error code ret.
246 * Allow to save few lines of code.
248 __attribute__((format (printf, 3, 4)))
249 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
251 va_list ap;
252 va_start(ap, fmt);
253 strbuf_vaddf(sb, fmt, ap);
254 va_end(ap);
255 return ret;
258 static int err_no_arg(struct strbuf *sb, const char *name)
260 size_t namelen = strchrnul(name, ':') - name;
261 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
262 (int)namelen, name);
263 return -1;
266 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
268 size_t namelen = strchrnul(name, ':') - name;
269 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
270 (int)namelen, name, arg);
271 return -1;
275 * Parse option of name "candidate" in the option string "to_parse" of
276 * the form
278 * "candidate1[=val1],candidate2[=val2],candidate3[=val3],..."
280 * The remaining part of "to_parse" is stored in "end" (if we are
281 * parsing the last candidate, then this is NULL) and the value of
282 * the candidate is stored in "valuestart" and its length in "valuelen",
283 * that is the portion after "=". Since it is possible for a "candidate"
284 * to not have a value, in such cases, "valuestart" is set to point to
285 * NULL and "valuelen" to 0.
287 * The function returns 1 on success. It returns 0 if we don't find
288 * "candidate" in "to_parse" or we find "candidate" but it is followed
289 * by more chars (for example, "candidatefoo"), that is, we don't find
290 * an exact match.
292 * This function only does the above for one "candidate" at a time. So
293 * it has to be called each time trying to parse a "candidate" in the
294 * option string "to_parse".
296 static int match_atom_arg_value(const char *to_parse, const char *candidate,
297 const char **end, const char **valuestart,
298 size_t *valuelen)
300 const char *atom;
302 if (!skip_prefix(to_parse, candidate, &atom))
303 return 0; /* definitely not "candidate" */
305 if (*atom == '=') {
306 /* we just saw "candidate=" */
307 *valuestart = atom + 1;
308 atom = strchrnul(*valuestart, ',');
309 *valuelen = atom - *valuestart;
310 } else if (*atom != ',' && *atom != '\0') {
311 /* key begins with "candidate" but has more chars */
312 return 0;
313 } else {
314 /* just "candidate" without "=val" */
315 *valuestart = NULL;
316 *valuelen = 0;
319 /* atom points at either the ',' or NUL after this key[=val] */
320 if (*atom == ',')
321 atom++;
322 else if (*atom)
323 BUG("Why is *atom not NULL yet?");
325 *end = atom;
326 return 1;
330 * Parse boolean option of name "candidate" in the option list "to_parse"
331 * of the form
333 * "candidate1[=bool1],candidate2[=bool2],candidate3[=bool3],..."
335 * The remaining part of "to_parse" is stored in "end" (if we are parsing
336 * the last candidate, then this is NULL) and the value (if given) is
337 * parsed and stored in "val", so "val" always points to either 0 or 1.
338 * If the value is not given, then "val" is set to point to 1.
340 * The boolean value is parsed using "git_parse_maybe_bool()", so the
341 * accepted values are
343 * to set true - "1", "yes", "true"
344 * to set false - "0", "no", "false"
346 * This function returns 1 on success. It returns 0 when we don't find
347 * an exact match for "candidate" or when the boolean value given is
348 * not valid.
350 static int match_atom_bool_arg(const char *to_parse, const char *candidate,
351 const char **end, int *val)
353 const char *argval;
354 char *strval;
355 size_t arglen;
356 int v;
358 if (!match_atom_arg_value(to_parse, candidate, end, &argval, &arglen))
359 return 0;
361 if (!argval) {
362 *val = 1;
363 return 1;
366 strval = xstrndup(argval, arglen);
367 v = git_parse_maybe_bool(strval);
368 free(strval);
370 if (v == -1)
371 return 0;
373 *val = v;
375 return 1;
378 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
379 const char *color_value, struct strbuf *err)
381 if (!color_value)
382 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
383 if (color_parse(color_value, atom->u.color) < 0)
384 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
385 color_value);
387 * We check this after we've parsed the color, which lets us complain
388 * about syntactically bogus color names even if they won't be used.
390 if (!want_color(format->use_color))
391 color_parse("", atom->u.color);
392 return 0;
395 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
396 const char *name, struct strbuf *err)
398 if (!arg)
399 atom->option = R_NORMAL;
400 else if (!strcmp(arg, "short"))
401 atom->option = R_SHORT;
402 else if (skip_prefix(arg, "lstrip=", &arg) ||
403 skip_prefix(arg, "strip=", &arg)) {
404 atom->option = R_LSTRIP;
405 if (strtol_i(arg, 10, &atom->lstrip))
406 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
407 } else if (skip_prefix(arg, "rstrip=", &arg)) {
408 atom->option = R_RSTRIP;
409 if (strtol_i(arg, 10, &atom->rstrip))
410 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
411 } else
412 return err_bad_arg(err, name, arg);
413 return 0;
416 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
417 struct used_atom *atom,
418 const char *arg, struct strbuf *err)
420 struct string_list params = STRING_LIST_INIT_DUP;
421 int i;
423 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
424 atom->u.remote_ref.push = 1;
426 if (!arg) {
427 atom->u.remote_ref.option = RR_REF;
428 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
429 arg, atom->name, err);
432 atom->u.remote_ref.nobracket = 0;
433 string_list_split(&params, arg, ',', -1);
435 for (i = 0; i < params.nr; i++) {
436 const char *s = params.items[i].string;
438 if (!strcmp(s, "track"))
439 atom->u.remote_ref.option = RR_TRACK;
440 else if (!strcmp(s, "trackshort"))
441 atom->u.remote_ref.option = RR_TRACKSHORT;
442 else if (!strcmp(s, "nobracket"))
443 atom->u.remote_ref.nobracket = 1;
444 else if (!strcmp(s, "remotename")) {
445 atom->u.remote_ref.option = RR_REMOTE_NAME;
446 atom->u.remote_ref.push_remote = 1;
447 } else if (!strcmp(s, "remoteref")) {
448 atom->u.remote_ref.option = RR_REMOTE_REF;
449 atom->u.remote_ref.push_remote = 1;
450 } else {
451 atom->u.remote_ref.option = RR_REF;
452 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
453 arg, atom->name, err)) {
454 string_list_clear(&params, 0);
455 return -1;
460 string_list_clear(&params, 0);
461 return 0;
464 static int objecttype_atom_parser(struct ref_format *format UNUSED,
465 struct used_atom *atom,
466 const char *arg, struct strbuf *err)
468 if (arg)
469 return err_no_arg(err, "objecttype");
470 if (*atom->name == '*')
471 oi_deref.info.typep = &oi_deref.type;
472 else
473 oi.info.typep = &oi.type;
474 return 0;
477 static int objectsize_atom_parser(struct ref_format *format UNUSED,
478 struct used_atom *atom,
479 const char *arg, struct strbuf *err)
481 if (!arg) {
482 atom->u.objectsize.option = O_SIZE;
483 if (*atom->name == '*')
484 oi_deref.info.sizep = &oi_deref.size;
485 else
486 oi.info.sizep = &oi.size;
487 } else if (!strcmp(arg, "disk")) {
488 atom->u.objectsize.option = O_SIZE_DISK;
489 if (*atom->name == '*')
490 oi_deref.info.disk_sizep = &oi_deref.disk_size;
491 else
492 oi.info.disk_sizep = &oi.disk_size;
493 } else
494 return err_bad_arg(err, "objectsize", arg);
495 return 0;
498 static int deltabase_atom_parser(struct ref_format *format UNUSED,
499 struct used_atom *atom,
500 const char *arg, struct strbuf *err)
502 if (arg)
503 return err_no_arg(err, "deltabase");
504 if (*atom->name == '*')
505 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
506 else
507 oi.info.delta_base_oid = &oi.delta_base_oid;
508 return 0;
511 static int body_atom_parser(struct ref_format *format UNUSED,
512 struct used_atom *atom,
513 const char *arg, struct strbuf *err)
515 if (arg)
516 return err_no_arg(err, "body");
517 atom->u.contents.option = C_BODY_DEP;
518 return 0;
521 static int subject_atom_parser(struct ref_format *format UNUSED,
522 struct used_atom *atom,
523 const char *arg, struct strbuf *err)
525 if (!arg)
526 atom->u.contents.option = C_SUB;
527 else if (!strcmp(arg, "sanitize"))
528 atom->u.contents.option = C_SUB_SANITIZE;
529 else
530 return err_bad_arg(err, "subject", arg);
531 return 0;
534 static int parse_signature_option(const char *arg)
536 if (!arg)
537 return S_BARE;
538 else if (!strcmp(arg, "signer"))
539 return S_SIGNER;
540 else if (!strcmp(arg, "grade"))
541 return S_GRADE;
542 else if (!strcmp(arg, "key"))
543 return S_KEY;
544 else if (!strcmp(arg, "fingerprint"))
545 return S_FINGERPRINT;
546 else if (!strcmp(arg, "primarykeyfingerprint"))
547 return S_PRI_KEY_FP;
548 else if (!strcmp(arg, "trustlevel"))
549 return S_TRUST_LEVEL;
550 return -1;
553 static int signature_atom_parser(struct ref_format *format UNUSED,
554 struct used_atom *atom,
555 const char *arg, struct strbuf *err)
557 int opt = parse_signature_option(arg);
558 if (opt < 0)
559 return err_bad_arg(err, "signature", arg);
560 atom->u.signature.option = opt;
561 return 0;
564 static int trailers_atom_parser(struct ref_format *format UNUSED,
565 struct used_atom *atom,
566 const char *arg, struct strbuf *err)
568 atom->u.contents.trailer_opts.no_divider = 1;
570 if (arg) {
571 char *argbuf = xstrfmt("%s)", arg);
572 const char *arg = argbuf;
573 char *invalid_arg = NULL;
574 struct ref_trailer_buf *tb;
577 * Do not inline these directly into the used_atom struct!
578 * When we parse them in format_set_trailers_options(),
579 * we will make pointer references directly to them,
580 * which will not survive a realloc() of the used_atom list.
581 * They must be allocated in a separate, stable struct.
583 atom->u.contents.trailer_buf = tb = xmalloc(sizeof(*tb));
584 string_list_init_dup(&tb->filter_list);
585 strbuf_init(&tb->sepbuf, 0);
586 strbuf_init(&tb->kvsepbuf, 0);
588 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
589 &tb->filter_list,
590 &tb->sepbuf, &tb->kvsepbuf,
591 &arg, &invalid_arg)) {
592 if (!invalid_arg)
593 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
594 else
595 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
596 free(invalid_arg);
597 free(argbuf);
598 return -1;
600 free(argbuf);
602 atom->u.contents.option = C_TRAILERS;
603 return 0;
606 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
607 const char *arg, struct strbuf *err)
609 if (!arg)
610 atom->u.contents.option = C_BARE;
611 else if (!strcmp(arg, "body"))
612 atom->u.contents.option = C_BODY;
613 else if (!strcmp(arg, "size")) {
614 atom->type = FIELD_ULONG;
615 atom->u.contents.option = C_LENGTH;
616 } else if (!strcmp(arg, "signature"))
617 atom->u.contents.option = C_SIG;
618 else if (!strcmp(arg, "subject"))
619 atom->u.contents.option = C_SUB;
620 else if (!strcmp(arg, "trailers")) {
621 if (trailers_atom_parser(format, atom, NULL, err))
622 return -1;
623 } else if (skip_prefix(arg, "trailers:", &arg)) {
624 if (trailers_atom_parser(format, atom, arg, err))
625 return -1;
626 } else if (skip_prefix(arg, "lines=", &arg)) {
627 atom->u.contents.option = C_LINES;
628 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
629 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
630 } else
631 return err_bad_arg(err, "contents", arg);
632 return 0;
635 static int describe_atom_option_parser(struct strvec *args, const char **arg,
636 struct strbuf *err)
638 const char *argval;
639 size_t arglen = 0;
640 int optval = 0;
642 if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {
643 if (!optval)
644 strvec_push(args, "--no-tags");
645 else
646 strvec_push(args, "--tags");
647 return 1;
650 if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {
651 char *endptr;
653 if (!arglen)
654 return strbuf_addf_ret(err, -1,
655 _("argument expected for %s"),
656 "describe:abbrev");
657 if (strtol(argval, &endptr, 10) < 0)
658 return strbuf_addf_ret(err, -1,
659 _("positive value expected %s=%s"),
660 "describe:abbrev", argval);
661 if (endptr - argval != arglen)
662 return strbuf_addf_ret(err, -1,
663 _("cannot fully parse %s=%s"),
664 "describe:abbrev", argval);
666 strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);
667 return 1;
670 if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {
671 if (!arglen)
672 return strbuf_addf_ret(err, -1,
673 _("value expected %s="),
674 "describe:match");
676 strvec_pushf(args, "--match=%.*s", (int)arglen, argval);
677 return 1;
680 if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {
681 if (!arglen)
682 return strbuf_addf_ret(err, -1,
683 _("value expected %s="),
684 "describe:exclude");
686 strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);
687 return 1;
690 return 0;
693 static int describe_atom_parser(struct ref_format *format UNUSED,
694 struct used_atom *atom,
695 const char *arg, struct strbuf *err)
697 strvec_init(&atom->u.describe_args);
699 for (;;) {
700 int found = 0;
701 const char *bad_arg = arg;
703 if (!arg || !*arg)
704 break;
706 found = describe_atom_option_parser(&atom->u.describe_args, &arg, err);
707 if (found < 0)
708 return found;
709 if (!found)
710 return err_bad_arg(err, "describe", bad_arg);
712 return 0;
715 static int raw_atom_parser(struct ref_format *format UNUSED,
716 struct used_atom *atom,
717 const char *arg, struct strbuf *err)
719 if (!arg)
720 atom->u.raw_data.option = RAW_BARE;
721 else if (!strcmp(arg, "size")) {
722 atom->type = FIELD_ULONG;
723 atom->u.raw_data.option = RAW_LENGTH;
724 } else
725 return err_bad_arg(err, "raw", arg);
726 return 0;
729 static int oid_atom_parser(struct ref_format *format UNUSED,
730 struct used_atom *atom,
731 const char *arg, struct strbuf *err)
733 if (!arg)
734 atom->u.oid.option = O_FULL;
735 else if (!strcmp(arg, "short"))
736 atom->u.oid.option = O_SHORT;
737 else if (skip_prefix(arg, "short=", &arg)) {
738 atom->u.oid.option = O_LENGTH;
739 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
740 atom->u.oid.length == 0)
741 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
742 if (atom->u.oid.length < MINIMUM_ABBREV)
743 atom->u.oid.length = MINIMUM_ABBREV;
744 } else
745 return err_bad_arg(err, atom->name, arg);
746 return 0;
749 static int person_name_atom_parser(struct ref_format *format UNUSED,
750 struct used_atom *atom,
751 const char *arg, struct strbuf *err)
753 if (!arg)
754 atom->u.name_option.option = N_RAW;
755 else if (!strcmp(arg, "mailmap"))
756 atom->u.name_option.option = N_MAILMAP;
757 else
758 return err_bad_arg(err, atom->name, arg);
759 return 0;
762 static int email_atom_option_parser(const char **arg)
764 if (!*arg)
765 return EO_RAW;
766 if (skip_prefix(*arg, "trim", arg))
767 return EO_TRIM;
768 if (skip_prefix(*arg, "localpart", arg))
769 return EO_LOCALPART;
770 if (skip_prefix(*arg, "mailmap", arg))
771 return EO_MAILMAP;
772 return -1;
775 static int person_email_atom_parser(struct ref_format *format UNUSED,
776 struct used_atom *atom,
777 const char *arg, struct strbuf *err)
779 for (;;) {
780 int opt = email_atom_option_parser(&arg);
781 const char *bad_arg = arg;
783 if (opt < 0)
784 return err_bad_arg(err, atom->name, bad_arg);
785 atom->u.email_option.option |= opt;
787 if (!arg || !*arg)
788 break;
789 if (*arg == ',')
790 arg++;
791 else
792 return err_bad_arg(err, atom->name, bad_arg);
794 return 0;
797 static int refname_atom_parser(struct ref_format *format UNUSED,
798 struct used_atom *atom,
799 const char *arg, struct strbuf *err)
801 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
804 static align_type parse_align_position(const char *s)
806 if (!strcmp(s, "right"))
807 return ALIGN_RIGHT;
808 else if (!strcmp(s, "middle"))
809 return ALIGN_MIDDLE;
810 else if (!strcmp(s, "left"))
811 return ALIGN_LEFT;
812 return -1;
815 static int align_atom_parser(struct ref_format *format UNUSED,
816 struct used_atom *atom,
817 const char *arg, struct strbuf *err)
819 struct align *align = &atom->u.align;
820 struct string_list params = STRING_LIST_INIT_DUP;
821 int i;
822 unsigned int width = ~0U;
824 if (!arg)
825 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
827 align->position = ALIGN_LEFT;
829 string_list_split(&params, arg, ',', -1);
830 for (i = 0; i < params.nr; i++) {
831 const char *s = params.items[i].string;
832 int position;
834 if (skip_prefix(s, "position=", &s)) {
835 position = parse_align_position(s);
836 if (position < 0) {
837 strbuf_addf(err, _("unrecognized position:%s"), s);
838 string_list_clear(&params, 0);
839 return -1;
841 align->position = position;
842 } else if (skip_prefix(s, "width=", &s)) {
843 if (strtoul_ui(s, 10, &width)) {
844 strbuf_addf(err, _("unrecognized width:%s"), s);
845 string_list_clear(&params, 0);
846 return -1;
848 } else if (!strtoul_ui(s, 10, &width))
850 else if ((position = parse_align_position(s)) >= 0)
851 align->position = position;
852 else {
853 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
854 string_list_clear(&params, 0);
855 return -1;
859 if (width == ~0U) {
860 string_list_clear(&params, 0);
861 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
863 align->width = width;
864 string_list_clear(&params, 0);
865 return 0;
868 static int if_atom_parser(struct ref_format *format UNUSED,
869 struct used_atom *atom,
870 const char *arg, struct strbuf *err)
872 if (!arg) {
873 atom->u.if_then_else.cmp_status = COMPARE_NONE;
874 return 0;
875 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
876 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
877 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
878 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
879 } else
880 return err_bad_arg(err, "if", arg);
881 return 0;
884 static int rest_atom_parser(struct ref_format *format UNUSED,
885 struct used_atom *atom UNUSED,
886 const char *arg, struct strbuf *err)
888 if (arg)
889 return err_no_arg(err, "rest");
890 return 0;
893 static int ahead_behind_atom_parser(struct ref_format *format,
894 struct used_atom *atom UNUSED,
895 const char *arg, struct strbuf *err)
897 struct string_list_item *item;
899 if (!arg)
900 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
902 item = string_list_append(&format->bases, arg);
903 item->util = lookup_commit_reference_by_name(arg);
904 if (!item->util)
905 die("failed to find '%s'", arg);
907 return 0;
910 static int is_base_atom_parser(struct ref_format *format,
911 struct used_atom *atom UNUSED,
912 const char *arg, struct strbuf *err)
914 struct string_list_item *item;
916 if (!arg)
917 return strbuf_addf_ret(err, -1, _("expected format: %%(is-base:<committish>)"));
919 item = string_list_append(&format->is_base_tips, arg);
920 item->util = lookup_commit_reference_by_name(arg);
921 if (!item->util)
922 die("failed to find '%s'", arg);
924 return 0;
927 static int head_atom_parser(struct ref_format *format UNUSED,
928 struct used_atom *atom,
929 const char *arg, struct strbuf *err)
931 if (arg)
932 return err_no_arg(err, "HEAD");
933 atom->u.head = refs_resolve_refdup(get_main_ref_store(the_repository),
934 "HEAD", RESOLVE_REF_READING, NULL,
935 NULL);
936 return 0;
939 static struct {
940 const char *name;
941 info_source source;
942 cmp_type cmp_type;
943 int (*parser)(struct ref_format *format, struct used_atom *atom,
944 const char *arg, struct strbuf *err);
945 } valid_atom[] = {
946 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
947 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
948 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
949 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
950 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
951 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
952 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
953 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
954 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
955 [ATOM_TYPE] = { "type", SOURCE_OBJ },
956 [ATOM_TAG] = { "tag", SOURCE_OBJ },
957 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
958 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
959 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
960 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
961 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
962 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
963 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
964 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
965 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
966 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
967 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
968 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
969 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
970 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
971 [ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },
972 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
973 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
974 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
975 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
976 [ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },
977 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
978 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
979 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
980 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
981 [ATOM_FLAG] = { "flag", SOURCE_NONE },
982 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
983 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
984 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
985 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
986 [ATOM_END] = { "end", SOURCE_NONE },
987 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
988 [ATOM_THEN] = { "then", SOURCE_NONE },
989 [ATOM_ELSE] = { "else", SOURCE_NONE },
990 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
991 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
992 [ATOM_ISBASE] = { "is-base", SOURCE_OTHER, FIELD_STR, is_base_atom_parser },
994 * Please update $__git_ref_fieldlist in git-completion.bash
995 * when you add new atoms
999 #define REF_FORMATTING_STATE_INIT { 0 }
1001 struct ref_formatting_stack {
1002 struct ref_formatting_stack *prev;
1003 struct strbuf output;
1004 void (*at_end)(struct ref_formatting_stack **stack);
1005 void (*at_end_data_free)(void *data);
1006 void *at_end_data;
1009 struct ref_formatting_state {
1010 int quote_style;
1011 struct ref_formatting_stack *stack;
1014 struct atom_value {
1015 const char *s;
1016 ssize_t s_size;
1017 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
1018 struct strbuf *err);
1019 uintmax_t value; /* used for sorting when not FIELD_STR */
1020 struct used_atom *atom;
1023 #define ATOM_SIZE_UNSPECIFIED (-1)
1025 #define ATOM_VALUE_INIT { \
1026 .s_size = ATOM_SIZE_UNSPECIFIED \
1030 * Used to parse format string and sort specifiers
1032 static int parse_ref_filter_atom(struct ref_format *format,
1033 const char *atom, const char *ep,
1034 struct strbuf *err)
1036 const char *sp;
1037 const char *arg;
1038 int i, at, atom_len;
1040 sp = atom;
1041 if (*sp == '*' && sp < ep)
1042 sp++; /* deref */
1043 if (ep <= sp)
1044 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
1045 (int)(ep-atom), atom);
1048 * If the atom name has a colon, strip it and everything after
1049 * it off - it specifies the format for this entry, and
1050 * shouldn't be used for checking against the valid_atom
1051 * table.
1053 arg = memchr(sp, ':', ep - sp);
1054 atom_len = (arg ? arg : ep) - sp;
1056 /* Do we have the atom already used elsewhere? */
1057 for (i = 0; i < used_atom_cnt; i++) {
1058 int len = strlen(used_atom[i].name);
1059 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
1060 return i;
1063 /* Is the atom a valid one? */
1064 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
1065 int len = strlen(valid_atom[i].name);
1066 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
1067 break;
1070 if (ARRAY_SIZE(valid_atom) <= i)
1071 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
1072 (int)(ep-atom), atom);
1073 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
1074 return strbuf_addf_ret(err, -1,
1075 _("not a git repository, but the field '%.*s' requires access to object data"),
1076 (int)(ep-atom), atom);
1078 /* Add it in, including the deref prefix */
1079 at = used_atom_cnt;
1080 used_atom_cnt++;
1081 REALLOC_ARRAY(used_atom, used_atom_cnt);
1082 used_atom[at].atom_type = i;
1083 used_atom[at].name = xmemdupz(atom, ep - atom);
1084 used_atom[at].type = valid_atom[i].cmp_type;
1085 used_atom[at].source = valid_atom[i].source;
1086 if (used_atom[at].source == SOURCE_OBJ) {
1087 if (*atom == '*')
1088 oi_deref.info.contentp = &oi_deref.content;
1089 else
1090 oi.info.contentp = &oi.content;
1092 if (arg) {
1093 arg = used_atom[at].name + (arg - atom) + 1;
1094 if (!*arg) {
1096 * Treat empty sub-arguments list as NULL (i.e.,
1097 * "%(atom:)" is equivalent to "%(atom)").
1099 arg = NULL;
1102 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
1103 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
1104 return -1;
1105 if (*atom == '*')
1106 need_tagged = 1;
1107 if (i == ATOM_SYMREF)
1108 need_symref = 1;
1109 return at;
1112 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
1114 switch (quote_style) {
1115 case QUOTE_NONE:
1116 if (len < 0)
1117 strbuf_addstr(s, str);
1118 else
1119 strbuf_add(s, str, len);
1120 break;
1121 case QUOTE_SHELL:
1122 sq_quote_buf(s, str);
1123 break;
1124 case QUOTE_PERL:
1125 if (len < 0)
1126 perl_quote_buf(s, str);
1127 else
1128 perl_quote_buf_with_len(s, str, len);
1129 break;
1130 case QUOTE_PYTHON:
1131 python_quote_buf(s, str);
1132 break;
1133 case QUOTE_TCL:
1134 tcl_quote_buf(s, str);
1135 break;
1139 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
1140 struct strbuf *err UNUSED)
1143 * Quote formatting is only done when the stack has a single
1144 * element. Otherwise quote formatting is done on the
1145 * element's entire output strbuf when the %(end) atom is
1146 * encountered.
1148 if (!state->stack->prev)
1149 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
1150 else if (v->s_size < 0)
1151 strbuf_addstr(&state->stack->output, v->s);
1152 else
1153 strbuf_add(&state->stack->output, v->s, v->s_size);
1154 return 0;
1157 static void push_stack_element(struct ref_formatting_stack **stack)
1159 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
1161 strbuf_init(&s->output, 0);
1162 s->prev = *stack;
1163 *stack = s;
1166 static void pop_stack_element(struct ref_formatting_stack **stack)
1168 struct ref_formatting_stack *current = *stack;
1169 struct ref_formatting_stack *prev = current->prev;
1171 if (prev)
1172 strbuf_addbuf(&prev->output, &current->output);
1173 strbuf_release(&current->output);
1174 if (current->at_end_data_free)
1175 current->at_end_data_free(current->at_end_data);
1176 free(current);
1177 *stack = prev;
1180 static void end_align_handler(struct ref_formatting_stack **stack)
1182 struct ref_formatting_stack *cur = *stack;
1183 struct align *align = (struct align *)cur->at_end_data;
1184 struct strbuf s = STRBUF_INIT;
1186 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
1187 strbuf_swap(&cur->output, &s);
1188 strbuf_release(&s);
1191 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1192 struct strbuf *err UNUSED)
1194 struct ref_formatting_stack *new_stack;
1196 push_stack_element(&state->stack);
1197 new_stack = state->stack;
1198 new_stack->at_end = end_align_handler;
1199 new_stack->at_end_data = &atomv->atom->u.align;
1200 return 0;
1203 static void if_then_else_handler(struct ref_formatting_stack **stack)
1205 struct ref_formatting_stack *cur = *stack;
1206 struct ref_formatting_stack *prev = cur->prev;
1207 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
1209 if (!if_then_else->then_atom_seen)
1210 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
1212 if (if_then_else->else_atom_seen) {
1214 * There is an %(else) atom: we need to drop one state from the
1215 * stack, either the %(else) branch if the condition is satisfied, or
1216 * the %(then) branch if it isn't.
1218 if (if_then_else->condition_satisfied) {
1219 strbuf_reset(&cur->output);
1220 pop_stack_element(&cur);
1221 } else {
1222 strbuf_swap(&cur->output, &prev->output);
1223 strbuf_reset(&cur->output);
1224 pop_stack_element(&cur);
1226 } else if (!if_then_else->condition_satisfied) {
1228 * No %(else) atom: just drop the %(then) branch if the
1229 * condition is not satisfied.
1231 strbuf_reset(&cur->output);
1234 *stack = cur;
1237 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1238 struct strbuf *err UNUSED)
1240 struct ref_formatting_stack *new_stack;
1241 struct if_then_else *if_then_else = xcalloc(1, sizeof(*if_then_else));
1243 if_then_else->str = atomv->atom->u.if_then_else.str;
1244 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
1246 push_stack_element(&state->stack);
1247 new_stack = state->stack;
1248 new_stack->at_end = if_then_else_handler;
1249 new_stack->at_end_data = if_then_else;
1250 new_stack->at_end_data_free = free;
1251 return 0;
1254 static int is_empty(struct strbuf *buf)
1256 const char *cur = buf->buf;
1257 const char *end = buf->buf + buf->len;
1259 while (cur != end && (isspace(*cur)))
1260 cur++;
1262 return cur == end;
1265 static int then_atom_handler(struct atom_value *atomv UNUSED,
1266 struct ref_formatting_state *state,
1267 struct strbuf *err)
1269 struct ref_formatting_stack *cur = state->stack;
1270 struct if_then_else *if_then_else = NULL;
1271 size_t str_len = 0;
1273 if (cur->at_end == if_then_else_handler)
1274 if_then_else = (struct if_then_else *)cur->at_end_data;
1275 if (!if_then_else)
1276 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
1277 if (if_then_else->then_atom_seen)
1278 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
1279 if (if_then_else->else_atom_seen)
1280 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
1281 if_then_else->then_atom_seen = 1;
1282 if (if_then_else->str)
1283 str_len = strlen(if_then_else->str);
1285 * If the 'equals' or 'notequals' attribute is used then
1286 * perform the required comparison. If not, only non-empty
1287 * strings satisfy the 'if' condition.
1289 if (if_then_else->cmp_status == COMPARE_EQUAL) {
1290 if (str_len == cur->output.len &&
1291 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1292 if_then_else->condition_satisfied = 1;
1293 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
1294 if (str_len != cur->output.len ||
1295 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1296 if_then_else->condition_satisfied = 1;
1297 } else if (cur->output.len && !is_empty(&cur->output))
1298 if_then_else->condition_satisfied = 1;
1299 strbuf_reset(&cur->output);
1300 return 0;
1303 static int else_atom_handler(struct atom_value *atomv UNUSED,
1304 struct ref_formatting_state *state,
1305 struct strbuf *err)
1307 struct ref_formatting_stack *prev = state->stack;
1308 struct if_then_else *if_then_else = NULL;
1310 if (prev->at_end == if_then_else_handler)
1311 if_then_else = (struct if_then_else *)prev->at_end_data;
1312 if (!if_then_else)
1313 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1314 if (!if_then_else->then_atom_seen)
1315 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1316 if (if_then_else->else_atom_seen)
1317 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1318 if_then_else->else_atom_seen = 1;
1319 push_stack_element(&state->stack);
1320 state->stack->at_end_data = prev->at_end_data;
1321 state->stack->at_end = prev->at_end;
1322 return 0;
1325 static int end_atom_handler(struct atom_value *atomv UNUSED,
1326 struct ref_formatting_state *state,
1327 struct strbuf *err)
1329 struct ref_formatting_stack *current = state->stack;
1330 struct strbuf s = STRBUF_INIT;
1332 if (!current->at_end)
1333 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1334 current->at_end(&state->stack);
1336 /* Stack may have been popped within at_end(), hence reset the current pointer */
1337 current = state->stack;
1340 * Perform quote formatting when the stack element is that of
1341 * a supporting atom. If nested then perform quote formatting
1342 * only on the topmost supporting atom.
1344 if (!current->prev->prev) {
1345 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1346 strbuf_swap(&current->output, &s);
1348 strbuf_release(&s);
1349 pop_stack_element(&state->stack);
1350 return 0;
1354 * In a format string, find the next occurrence of %(atom).
1356 static const char *find_next(const char *cp)
1358 while (*cp) {
1359 if (*cp == '%') {
1361 * %( is the start of an atom;
1362 * %% is a quoted per-cent.
1364 if (cp[1] == '(')
1365 return cp;
1366 else if (cp[1] == '%')
1367 cp++; /* skip over two % */
1368 /* otherwise this is a singleton, literal % */
1370 cp++;
1372 return NULL;
1375 static int reject_atom(enum atom_type atom_type)
1377 return atom_type == ATOM_REST;
1381 * Make sure the format string is well formed, and parse out
1382 * the used atoms.
1384 int verify_ref_format(struct ref_format *format)
1386 const char *cp, *sp;
1388 format->need_color_reset_at_eol = 0;
1389 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1390 struct strbuf err = STRBUF_INIT;
1391 const char *color, *ep = strchr(sp, ')');
1392 int at;
1394 if (!ep)
1395 return error(_("malformed format string %s"), sp);
1396 /* sp points at "%(" and ep points at the closing ")" */
1397 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1398 if (at < 0)
1399 die("%s", err.buf);
1400 if (reject_atom(used_atom[at].atom_type))
1401 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1403 if ((format->quote_style == QUOTE_PYTHON ||
1404 format->quote_style == QUOTE_SHELL ||
1405 format->quote_style == QUOTE_TCL) &&
1406 used_atom[at].atom_type == ATOM_RAW &&
1407 used_atom[at].u.raw_data.option == RAW_BARE)
1408 die(_("--format=%.*s cannot be used with "
1409 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1410 cp = ep + 1;
1412 if (skip_prefix(used_atom[at].name, "color:", &color))
1413 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1414 strbuf_release(&err);
1416 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1417 format->need_color_reset_at_eol = 0;
1418 return 0;
1421 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1422 struct used_atom *atom)
1424 switch (atom->u.oid.option) {
1425 case O_FULL:
1426 return oid_to_hex(oid);
1427 case O_LENGTH:
1428 return repo_find_unique_abbrev(the_repository, oid,
1429 atom->u.oid.length);
1430 case O_SHORT:
1431 return repo_find_unique_abbrev(the_repository, oid,
1432 DEFAULT_ABBREV);
1433 default:
1434 BUG("unknown %%(%s) option", field);
1438 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1439 struct atom_value *v, struct used_atom *atom)
1441 if (starts_with(name, field)) {
1442 v->s = xstrdup(do_grab_oid(field, oid, atom));
1443 return 1;
1445 return 0;
1448 /* See grab_values */
1449 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1451 int i;
1453 for (i = 0; i < used_atom_cnt; i++) {
1454 const char *name = used_atom[i].name;
1455 enum atom_type atom_type = used_atom[i].atom_type;
1456 struct atom_value *v = &val[i];
1457 if (!!deref != (*name == '*'))
1458 continue;
1459 if (deref)
1460 name++;
1461 if (atom_type == ATOM_OBJECTTYPE)
1462 v->s = xstrdup(type_name(oi->type));
1463 else if (atom_type == ATOM_OBJECTSIZE) {
1464 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1465 v->value = oi->disk_size;
1466 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1467 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1468 v->value = oi->size;
1469 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1471 } else if (atom_type == ATOM_DELTABASE)
1472 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1473 else if (atom_type == ATOM_OBJECTNAME && deref)
1474 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1478 /* See grab_values */
1479 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1481 int i;
1482 struct tag *tag = (struct tag *) obj;
1484 for (i = 0; i < used_atom_cnt; i++) {
1485 const char *name = used_atom[i].name;
1486 enum atom_type atom_type = used_atom[i].atom_type;
1487 struct atom_value *v = &val[i];
1488 if (!!deref != (*name == '*'))
1489 continue;
1490 if (deref)
1491 name++;
1492 if (atom_type == ATOM_TAG)
1493 v->s = xstrdup(tag->tag);
1494 else if (atom_type == ATOM_TYPE && tag->tagged)
1495 v->s = xstrdup(type_name(tag->tagged->type));
1496 else if (atom_type == ATOM_OBJECT && tag->tagged)
1497 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1501 /* See grab_values */
1502 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1504 int i;
1505 struct commit *commit = (struct commit *) obj;
1507 for (i = 0; i < used_atom_cnt; i++) {
1508 const char *name = used_atom[i].name;
1509 enum atom_type atom_type = used_atom[i].atom_type;
1510 struct atom_value *v = &val[i];
1511 if (!!deref != (*name == '*'))
1512 continue;
1513 if (deref)
1514 name++;
1515 if (atom_type == ATOM_TREE &&
1516 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1517 continue;
1518 if (atom_type == ATOM_NUMPARENT) {
1519 v->value = commit_list_count(commit->parents);
1520 v->s = xstrfmt("%lu", (unsigned long)v->value);
1522 else if (atom_type == ATOM_PARENT) {
1523 struct commit_list *parents;
1524 struct strbuf s = STRBUF_INIT;
1525 for (parents = commit->parents; parents; parents = parents->next) {
1526 struct object_id *oid = &parents->item->object.oid;
1527 if (parents != commit->parents)
1528 strbuf_addch(&s, ' ');
1529 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1531 v->s = strbuf_detach(&s, NULL);
1536 static const char *find_wholine(const char *who, int wholen, const char *buf)
1538 const char *eol;
1539 while (*buf) {
1540 if (!strncmp(buf, who, wholen) &&
1541 buf[wholen] == ' ')
1542 return buf + wholen + 1;
1543 eol = strchr(buf, '\n');
1544 if (!eol)
1545 return "";
1546 eol++;
1547 if (*eol == '\n')
1548 return ""; /* end of header */
1549 buf = eol;
1551 return "";
1554 static const char *copy_line(const char *buf)
1556 const char *eol = strchrnul(buf, '\n');
1557 return xmemdupz(buf, eol - buf);
1560 static const char *copy_name(const char *buf)
1562 const char *cp;
1563 for (cp = buf; *cp && *cp != '\n'; cp++) {
1564 if (starts_with(cp, " <"))
1565 return xmemdupz(buf, cp - buf);
1567 return xstrdup("");
1570 static const char *find_end_of_email(const char *email, int opt)
1572 const char *eoemail;
1574 if (opt & EO_LOCALPART) {
1575 eoemail = strchr(email, '@');
1576 if (eoemail)
1577 return eoemail;
1578 return strchr(email, '>');
1581 if (opt & EO_TRIM)
1582 return strchr(email, '>');
1585 * The option here is either the raw email option or the raw
1586 * mailmap option (that is EO_RAW or EO_MAILMAP). In such cases,
1587 * we directly grab the whole email including the closing
1588 * angle brackets.
1590 * If EO_MAILMAP was set with any other option (that is either
1591 * EO_TRIM or EO_LOCALPART), we already grab the end of email
1592 * above.
1594 eoemail = strchr(email, '>');
1595 if (eoemail)
1596 eoemail++;
1597 return eoemail;
1600 static const char *copy_email(const char *buf, struct used_atom *atom)
1602 const char *email = strchr(buf, '<');
1603 const char *eoemail;
1604 int opt = atom->u.email_option.option;
1606 if (!email)
1607 return xstrdup("");
1609 if (opt & (EO_LOCALPART | EO_TRIM))
1610 email++;
1612 eoemail = find_end_of_email(email, opt);
1613 if (!eoemail)
1614 return xstrdup("");
1615 return xmemdupz(email, eoemail - email);
1618 static char *copy_subject(const char *buf, unsigned long len)
1620 struct strbuf sb = STRBUF_INIT;
1621 int i;
1623 for (i = 0; i < len; i++) {
1624 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1625 continue; /* ignore CR in CRLF */
1627 if (buf[i] == '\n')
1628 strbuf_addch(&sb, ' ');
1629 else
1630 strbuf_addch(&sb, buf[i]);
1632 return strbuf_detach(&sb, NULL);
1635 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1637 const char *eoemail = strstr(buf, "> ");
1638 char *zone;
1639 timestamp_t timestamp;
1640 long tz;
1641 struct date_mode date_mode = DATE_MODE_INIT;
1642 const char *formatp;
1645 * We got here because atomname ends in "date" or "date<something>";
1646 * it's not possible that <something> is not ":<format>" because
1647 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1648 * ":" means no format is specified, and use the default.
1650 formatp = strchr(atomname, ':');
1651 if (formatp) {
1652 formatp++;
1653 parse_date_format(formatp, &date_mode);
1656 * If this is a sort field and a format was specified, we'll
1657 * want to compare formatted date by string value.
1659 v->atom->type = FIELD_STR;
1662 if (!eoemail)
1663 goto bad;
1664 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1665 if (timestamp == TIME_MAX)
1666 goto bad;
1667 errno = 0;
1668 tz = strtol(zone, NULL, 10);
1669 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1670 goto bad;
1671 v->s = xstrdup(show_date(timestamp, tz, date_mode));
1672 v->value = timestamp;
1673 date_mode_release(&date_mode);
1674 return;
1675 bad:
1676 v->s = xstrdup("");
1677 v->value = 0;
1680 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
1682 /* See grab_values */
1683 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1685 int i;
1686 int wholen = strlen(who);
1687 const char *wholine = NULL;
1688 const char *headers[] = { "author ", "committer ",
1689 "tagger ", NULL };
1691 for (i = 0; i < used_atom_cnt; i++) {
1692 struct used_atom *atom = &used_atom[i];
1693 const char *name = atom->name;
1694 struct atom_value *v = &val[i];
1695 struct strbuf mailmap_buf = STRBUF_INIT;
1697 if (!!deref != (*name == '*'))
1698 continue;
1699 if (deref)
1700 name++;
1701 if (strncmp(who, name, wholen))
1702 continue;
1703 if (name[wholen] != 0 &&
1704 !starts_with(name + wholen, "name") &&
1705 !starts_with(name + wholen, "email") &&
1706 !starts_with(name + wholen, "date"))
1707 continue;
1709 if ((starts_with(name + wholen, "name") &&
1710 (atom->u.name_option.option == N_MAILMAP)) ||
1711 (starts_with(name + wholen, "email") &&
1712 (atom->u.email_option.option & EO_MAILMAP))) {
1713 if (!mailmap.items)
1714 read_mailmap(&mailmap);
1715 strbuf_addstr(&mailmap_buf, buf);
1716 apply_mailmap_to_header(&mailmap_buf, headers, &mailmap);
1717 wholine = find_wholine(who, wholen, mailmap_buf.buf);
1718 } else {
1719 wholine = find_wholine(who, wholen, buf);
1722 if (!wholine)
1723 return; /* no point looking for it */
1724 if (name[wholen] == 0)
1725 v->s = copy_line(wholine);
1726 else if (starts_with(name + wholen, "name"))
1727 v->s = copy_name(wholine);
1728 else if (starts_with(name + wholen, "email"))
1729 v->s = copy_email(wholine, &used_atom[i]);
1730 else if (starts_with(name + wholen, "date"))
1731 grab_date(wholine, v, name);
1733 strbuf_release(&mailmap_buf);
1737 * For a tag or a commit object, if "creator" or "creatordate" is
1738 * requested, do something special.
1740 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1741 return; /* "author" for commit object is not wanted */
1742 if (!wholine)
1743 wholine = find_wholine(who, wholen, buf);
1744 if (!wholine)
1745 return;
1746 for (i = 0; i < used_atom_cnt; i++) {
1747 const char *name = used_atom[i].name;
1748 enum atom_type atom_type = used_atom[i].atom_type;
1749 struct atom_value *v = &val[i];
1750 if (!!deref != (*name == '*'))
1751 continue;
1752 if (deref)
1753 name++;
1755 if (atom_type == ATOM_CREATORDATE)
1756 grab_date(wholine, v, name);
1757 else if (atom_type == ATOM_CREATOR)
1758 v->s = copy_line(wholine);
1762 static void grab_signature(struct atom_value *val, int deref, struct object *obj)
1764 int i;
1765 struct commit *commit = (struct commit *) obj;
1766 struct signature_check sigc = { 0 };
1767 int signature_checked = 0;
1769 for (i = 0; i < used_atom_cnt; i++) {
1770 struct used_atom *atom = &used_atom[i];
1771 const char *name = atom->name;
1772 struct atom_value *v = &val[i];
1773 int opt;
1775 if (!!deref != (*name == '*'))
1776 continue;
1777 if (deref)
1778 name++;
1780 if (!skip_prefix(name, "signature", &name) ||
1781 (*name && *name != ':'))
1782 continue;
1783 if (!*name)
1784 name = NULL;
1785 else
1786 name++;
1788 opt = parse_signature_option(name);
1789 if (opt < 0)
1790 continue;
1792 if (!signature_checked) {
1793 check_commit_signature(commit, &sigc);
1794 signature_checked = 1;
1797 switch (opt) {
1798 case S_BARE:
1799 v->s = xstrdup(sigc.output ? sigc.output: "");
1800 break;
1801 case S_SIGNER:
1802 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1803 break;
1804 case S_GRADE:
1805 switch (sigc.result) {
1806 case 'G':
1807 switch (sigc.trust_level) {
1808 case TRUST_UNDEFINED:
1809 case TRUST_NEVER:
1810 v->s = xstrfmt("%c", (char)'U');
1811 break;
1812 default:
1813 v->s = xstrfmt("%c", (char)'G');
1814 break;
1816 break;
1817 case 'B':
1818 case 'E':
1819 case 'N':
1820 case 'X':
1821 case 'Y':
1822 case 'R':
1823 v->s = xstrfmt("%c", (char)sigc.result);
1824 break;
1826 break;
1827 case S_KEY:
1828 v->s = xstrdup(sigc.key ? sigc.key : "");
1829 break;
1830 case S_FINGERPRINT:
1831 v->s = xstrdup(sigc.fingerprint ?
1832 sigc.fingerprint : "");
1833 break;
1834 case S_PRI_KEY_FP:
1835 v->s = xstrdup(sigc.primary_key_fingerprint ?
1836 sigc.primary_key_fingerprint : "");
1837 break;
1838 case S_TRUST_LEVEL:
1839 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1840 break;
1844 if (signature_checked)
1845 signature_check_clear(&sigc);
1848 static void find_subpos(const char *buf,
1849 const char **sub, size_t *sublen,
1850 const char **body, size_t *bodylen,
1851 size_t *nonsiglen,
1852 const char **sig, size_t *siglen)
1854 const char *eol;
1855 const char *end = buf + strlen(buf);
1856 const char *sigstart;
1858 /* skip past header until we hit empty line */
1859 while (*buf && *buf != '\n') {
1860 eol = strchrnul(buf, '\n');
1861 if (*eol)
1862 eol++;
1863 buf = eol;
1865 /* skip any empty lines */
1866 while (*buf == '\n')
1867 buf++;
1868 /* parse signature first; we might not even have a subject line */
1869 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1870 *sig = sigstart;
1871 *siglen = end - *sig;
1873 /* subject is first non-empty line */
1874 *sub = buf;
1875 /* subject goes to first empty line before signature begins */
1876 if ((eol = strstr(*sub, "\n\n")) ||
1877 (eol = strstr(*sub, "\r\n\r\n"))) {
1878 eol = eol < sigstart ? eol : sigstart;
1879 } else {
1880 /* treat whole message as subject */
1881 eol = sigstart;
1883 buf = eol;
1884 *sublen = buf - *sub;
1885 /* drop trailing newline, if present */
1886 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1887 (*sub)[*sublen - 1] == '\r'))
1888 *sublen -= 1;
1890 /* skip any empty lines */
1891 while (*buf == '\n' || *buf == '\r')
1892 buf++;
1893 *body = buf;
1894 *bodylen = strlen(buf);
1895 *nonsiglen = sigstart - buf;
1899 * If 'lines' is greater than 0, append that many lines from the given
1900 * 'buf' of length 'size' to the given strbuf.
1902 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1904 int i;
1905 const char *sp, *eol;
1906 size_t len;
1908 sp = buf;
1910 for (i = 0; i < lines && sp < buf + size; i++) {
1911 if (i)
1912 strbuf_addstr(out, "\n ");
1913 eol = memchr(sp, '\n', size - (sp - buf));
1914 len = eol ? eol - sp : size - (sp - buf);
1915 strbuf_add(out, sp, len);
1916 if (!eol)
1917 break;
1918 sp = eol + 1;
1922 static void grab_describe_values(struct atom_value *val, int deref,
1923 struct object *obj)
1925 struct commit *commit = (struct commit *)obj;
1926 int i;
1928 for (i = 0; i < used_atom_cnt; i++) {
1929 struct used_atom *atom = &used_atom[i];
1930 enum atom_type type = atom->atom_type;
1931 const char *name = atom->name;
1932 struct atom_value *v = &val[i];
1934 struct child_process cmd = CHILD_PROCESS_INIT;
1935 struct strbuf out = STRBUF_INIT;
1936 struct strbuf err = STRBUF_INIT;
1938 if (type != ATOM_DESCRIBE)
1939 continue;
1941 if (!!deref != (*name == '*'))
1942 continue;
1944 cmd.git_cmd = 1;
1945 strvec_push(&cmd.args, "describe");
1946 strvec_pushv(&cmd.args, atom->u.describe_args.v);
1947 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1948 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
1949 error(_("failed to run 'describe'"));
1950 v->s = xstrdup("");
1951 continue;
1953 strbuf_rtrim(&out);
1954 v->s = strbuf_detach(&out, NULL);
1956 strbuf_release(&err);
1960 /* See grab_values */
1961 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1963 int i;
1964 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1965 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1966 void *buf = data->content;
1968 for (i = 0; i < used_atom_cnt; i++) {
1969 struct used_atom *atom = &used_atom[i];
1970 const char *name = atom->name;
1971 struct atom_value *v = &val[i];
1972 enum atom_type atom_type = atom->atom_type;
1974 if (!!deref != (*name == '*'))
1975 continue;
1976 if (deref)
1977 name++;
1979 if (atom_type == ATOM_RAW) {
1980 unsigned long buf_size = data->size;
1982 if (atom->u.raw_data.option == RAW_BARE) {
1983 v->s = xmemdupz(buf, buf_size);
1984 v->s_size = buf_size;
1985 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1986 v->value = buf_size;
1987 v->s = xstrfmt("%"PRIuMAX, v->value);
1989 continue;
1992 if ((data->type != OBJ_TAG &&
1993 data->type != OBJ_COMMIT) ||
1994 (strcmp(name, "body") &&
1995 !starts_with(name, "subject") &&
1996 !starts_with(name, "trailers") &&
1997 !starts_with(name, "contents")))
1998 continue;
1999 if (!subpos)
2000 find_subpos(buf,
2001 &subpos, &sublen,
2002 &bodypos, &bodylen, &nonsiglen,
2003 &sigpos, &siglen);
2005 if (atom->u.contents.option == C_SUB)
2006 v->s = copy_subject(subpos, sublen);
2007 else if (atom->u.contents.option == C_SUB_SANITIZE) {
2008 struct strbuf sb = STRBUF_INIT;
2009 format_sanitized_subject(&sb, subpos, sublen);
2010 v->s = strbuf_detach(&sb, NULL);
2011 } else if (atom->u.contents.option == C_BODY_DEP)
2012 v->s = xmemdupz(bodypos, bodylen);
2013 else if (atom->u.contents.option == C_LENGTH) {
2014 v->value = strlen(subpos);
2015 v->s = xstrfmt("%"PRIuMAX, v->value);
2016 } else if (atom->u.contents.option == C_BODY)
2017 v->s = xmemdupz(bodypos, nonsiglen);
2018 else if (atom->u.contents.option == C_SIG)
2019 v->s = xmemdupz(sigpos, siglen);
2020 else if (atom->u.contents.option == C_LINES) {
2021 struct strbuf s = STRBUF_INIT;
2022 const char *contents_end = bodypos + nonsiglen;
2024 /* Size is the length of the message after removing the signature */
2025 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
2026 v->s = strbuf_detach(&s, NULL);
2027 } else if (atom->u.contents.option == C_TRAILERS) {
2028 struct strbuf s = STRBUF_INIT;
2029 const char *msg;
2030 char *to_free = NULL;
2032 if (siglen)
2033 msg = to_free = xmemdupz(subpos, sigpos - subpos);
2034 else
2035 msg = subpos;
2037 /* Format the trailer info according to the trailer_opts given */
2038 format_trailers_from_commit(&atom->u.contents.trailer_opts, msg, &s);
2039 free(to_free);
2041 v->s = strbuf_detach(&s, NULL);
2042 } else if (atom->u.contents.option == C_BARE)
2043 v->s = xstrdup(subpos);
2049 * We want to have empty print-string for field requests
2050 * that do not apply (e.g. "authordate" for a tag object)
2052 static void fill_missing_values(struct atom_value *val)
2054 int i;
2055 for (i = 0; i < used_atom_cnt; i++) {
2056 struct atom_value *v = &val[i];
2057 if (!v->s)
2058 v->s = xstrdup("");
2063 * val is a list of atom_value to hold returned values. Extract
2064 * the values for atoms in used_atom array out of (obj, buf, sz).
2065 * when deref is false, (obj, buf, sz) is the object that is
2066 * pointed at by the ref itself; otherwise it is the object the
2067 * ref (which is a tag) refers to.
2069 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
2071 void *buf = data->content;
2073 switch (obj->type) {
2074 case OBJ_TAG:
2075 grab_tag_values(val, deref, obj);
2076 grab_sub_body_contents(val, deref, data);
2077 grab_person("tagger", val, deref, buf);
2078 grab_describe_values(val, deref, obj);
2079 break;
2080 case OBJ_COMMIT:
2081 grab_commit_values(val, deref, obj);
2082 grab_sub_body_contents(val, deref, data);
2083 grab_person("author", val, deref, buf);
2084 grab_person("committer", val, deref, buf);
2085 grab_signature(val, deref, obj);
2086 grab_describe_values(val, deref, obj);
2087 break;
2088 case OBJ_TREE:
2089 /* grab_tree_values(val, deref, obj, buf, sz); */
2090 grab_sub_body_contents(val, deref, data);
2091 break;
2092 case OBJ_BLOB:
2093 /* grab_blob_values(val, deref, obj, buf, sz); */
2094 grab_sub_body_contents(val, deref, data);
2095 break;
2096 default:
2097 die("Eh? Object of type %d?", obj->type);
2101 static inline char *copy_advance(char *dst, const char *src)
2103 while (*src)
2104 *dst++ = *src++;
2105 return dst;
2108 static const char *lstrip_ref_components(const char *refname, int len)
2110 long remaining = len;
2111 const char *start = xstrdup(refname);
2112 const char *to_free = start;
2114 if (len < 0) {
2115 int i;
2116 const char *p = refname;
2118 /* Find total no of '/' separated path-components */
2119 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2122 * The number of components we need to strip is now
2123 * the total minus the components to be left (Plus one
2124 * because we count the number of '/', but the number
2125 * of components is one more than the no of '/').
2127 remaining = i + len + 1;
2130 while (remaining > 0) {
2131 switch (*start++) {
2132 case '\0':
2133 free((char *)to_free);
2134 return xstrdup("");
2135 case '/':
2136 remaining--;
2137 break;
2141 start = xstrdup(start);
2142 free((char *)to_free);
2143 return start;
2146 static const char *rstrip_ref_components(const char *refname, int len)
2148 long remaining = len;
2149 const char *start = xstrdup(refname);
2150 const char *to_free = start;
2152 if (len < 0) {
2153 int i;
2154 const char *p = refname;
2156 /* Find total no of '/' separated path-components */
2157 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2160 * The number of components we need to strip is now
2161 * the total minus the components to be left (Plus one
2162 * because we count the number of '/', but the number
2163 * of components is one more than the no of '/').
2165 remaining = i + len + 1;
2168 while (remaining-- > 0) {
2169 char *p = strrchr(start, '/');
2170 if (!p) {
2171 free((char *)to_free);
2172 return xstrdup("");
2173 } else
2174 p[0] = '\0';
2176 return start;
2179 static const char *show_ref(struct refname_atom *atom, const char *refname)
2181 if (atom->option == R_SHORT)
2182 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2183 refname,
2184 repo_settings_get_warn_ambiguous_refs(the_repository));
2185 else if (atom->option == R_LSTRIP)
2186 return lstrip_ref_components(refname, atom->lstrip);
2187 else if (atom->option == R_RSTRIP)
2188 return rstrip_ref_components(refname, atom->rstrip);
2189 else
2190 return xstrdup(refname);
2193 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2194 struct branch *branch, const char **s)
2196 int num_ours, num_theirs;
2197 if (atom->u.remote_ref.option == RR_REF)
2198 *s = show_ref(&atom->u.remote_ref.refname, refname);
2199 else if (atom->u.remote_ref.option == RR_TRACK) {
2200 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2201 NULL, atom->u.remote_ref.push,
2202 AHEAD_BEHIND_FULL) < 0) {
2203 *s = xstrdup(msgs.gone);
2204 } else if (!num_ours && !num_theirs)
2205 *s = xstrdup("");
2206 else if (!num_ours)
2207 *s = xstrfmt(msgs.behind, num_theirs);
2208 else if (!num_theirs)
2209 *s = xstrfmt(msgs.ahead, num_ours);
2210 else
2211 *s = xstrfmt(msgs.ahead_behind,
2212 num_ours, num_theirs);
2213 if (!atom->u.remote_ref.nobracket && *s[0]) {
2214 const char *to_free = *s;
2215 *s = xstrfmt("[%s]", *s);
2216 free((void *)to_free);
2218 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2219 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2220 NULL, atom->u.remote_ref.push,
2221 AHEAD_BEHIND_FULL) < 0) {
2222 *s = xstrdup("");
2223 return;
2225 if (!num_ours && !num_theirs)
2226 *s = xstrdup("=");
2227 else if (!num_ours)
2228 *s = xstrdup("<");
2229 else if (!num_theirs)
2230 *s = xstrdup(">");
2231 else
2232 *s = xstrdup("<>");
2233 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2234 int explicit;
2235 const char *remote = atom->u.remote_ref.push ?
2236 pushremote_for_branch(branch, &explicit) :
2237 remote_for_branch(branch, &explicit);
2238 *s = xstrdup(explicit ? remote : "");
2239 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2240 const char *merge;
2242 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2243 *s = merge ? merge : xstrdup("");
2244 } else
2245 BUG("unhandled RR_* enum");
2248 char *get_head_description(void)
2250 struct strbuf desc = STRBUF_INIT;
2251 struct wt_status_state state;
2252 memset(&state, 0, sizeof(state));
2253 wt_status_get_state(the_repository, &state, 1);
2254 if (state.rebase_in_progress ||
2255 state.rebase_interactive_in_progress) {
2256 if (state.branch)
2257 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2258 state.branch);
2259 else
2260 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2261 state.detached_from);
2262 } else if (state.bisect_in_progress)
2263 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2264 state.bisecting_from);
2265 else if (state.detached_from) {
2266 if (state.detached_at)
2267 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2268 state.detached_from);
2269 else
2270 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2271 state.detached_from);
2272 } else
2273 strbuf_addstr(&desc, _("(no branch)"));
2275 wt_status_state_free_buffers(&state);
2277 return strbuf_detach(&desc, NULL);
2280 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2282 if (!ref->symref)
2283 return xstrdup("");
2284 else
2285 return show_ref(&atom->u.refname, ref->symref);
2288 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2290 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2291 return get_head_description();
2292 return show_ref(&atom->u.refname, ref->refname);
2295 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
2296 struct expand_data *oi, struct strbuf *err)
2298 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
2299 int eaten = 1;
2300 if (oi->info.contentp) {
2301 /* We need to know that to use parse_object_buffer properly */
2302 oi->info.sizep = &oi->size;
2303 oi->info.typep = &oi->type;
2305 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
2306 OBJECT_INFO_LOOKUP_REPLACE))
2307 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2308 oid_to_hex(&oi->oid), ref->refname);
2309 if (oi->info.disk_sizep && oi->disk_size < 0)
2310 BUG("Object size is less than zero.");
2312 if (oi->info.contentp) {
2313 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
2314 if (!*obj) {
2315 if (!eaten)
2316 free(oi->content);
2317 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
2318 oid_to_hex(&oi->oid), ref->refname);
2320 grab_values(ref->value, deref, *obj, oi);
2323 grab_common_values(ref->value, deref, oi);
2324 if (!eaten)
2325 free(oi->content);
2326 return 0;
2329 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2331 int i;
2333 for (i = 0; worktrees[i]; i++) {
2334 if (worktrees[i]->head_ref) {
2335 struct ref_to_worktree_entry *entry;
2336 entry = xmalloc(sizeof(*entry));
2337 entry->wt = worktrees[i];
2338 hashmap_entry_init(&entry->ent,
2339 strhash(worktrees[i]->head_ref));
2341 hashmap_add(map, &entry->ent);
2346 static void lazy_init_worktree_map(void)
2348 if (ref_to_worktree_map.worktrees)
2349 return;
2351 ref_to_worktree_map.worktrees = get_worktrees();
2352 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2353 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2356 static char *get_worktree_path(const struct ref_array_item *ref)
2358 struct hashmap_entry entry, *e;
2359 struct ref_to_worktree_entry *lookup_result;
2361 lazy_init_worktree_map();
2363 hashmap_entry_init(&entry, strhash(ref->refname));
2364 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2366 if (!e)
2367 return xstrdup("");
2369 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2371 return xstrdup(lookup_result->wt->path);
2375 * Parse the object referred by ref, and grab needed value.
2377 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2379 struct object *obj;
2380 int i;
2381 struct object_info empty = OBJECT_INFO_INIT;
2382 int ahead_behind_atoms = 0;
2383 int is_base_atoms = 0;
2385 CALLOC_ARRAY(ref->value, used_atom_cnt);
2388 * NEEDSWORK: The following code might be unnecessary if all codepaths
2389 * that call populate_value() populates the symref member of ref_array_item
2390 * like in apply_ref_filter(). Currently pretty_print_ref() is the only codepath
2391 * that calls populate_value() without first populating symref.
2393 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2394 ref->symref = refs_resolve_refdup(get_main_ref_store(the_repository),
2395 ref->refname,
2396 RESOLVE_REF_READING,
2397 NULL, NULL);
2398 if (!ref->symref)
2399 ref->symref = xstrdup("");
2402 /* Fill in specials first */
2403 for (i = 0; i < used_atom_cnt; i++) {
2404 struct used_atom *atom = &used_atom[i];
2405 enum atom_type atom_type = atom->atom_type;
2406 const char *name = used_atom[i].name;
2407 struct atom_value *v = &ref->value[i];
2408 int deref = 0;
2409 const char *refname;
2410 struct branch *branch = NULL;
2412 v->s_size = ATOM_SIZE_UNSPECIFIED;
2413 v->handler = append_atom;
2414 v->value = 0;
2415 v->atom = atom;
2417 if (*name == '*') {
2418 deref = 1;
2419 name++;
2422 if (atom_type == ATOM_REFNAME)
2423 refname = get_refname(atom, ref);
2424 else if (atom_type == ATOM_WORKTREEPATH) {
2425 if (ref->kind == FILTER_REFS_BRANCHES)
2426 v->s = get_worktree_path(ref);
2427 else
2428 v->s = xstrdup("");
2429 continue;
2431 else if (atom_type == ATOM_SYMREF)
2432 refname = get_symref(atom, ref);
2433 else if (atom_type == ATOM_UPSTREAM) {
2434 const char *branch_name;
2435 /* only local branches may have an upstream */
2436 if (!skip_prefix(ref->refname, "refs/heads/",
2437 &branch_name)) {
2438 v->s = xstrdup("");
2439 continue;
2441 branch = branch_get(branch_name);
2443 refname = branch_get_upstream(branch, NULL);
2444 if (refname)
2445 fill_remote_ref_details(atom, refname, branch, &v->s);
2446 else
2447 v->s = xstrdup("");
2448 continue;
2449 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2450 const char *branch_name;
2451 v->s = xstrdup("");
2452 if (!skip_prefix(ref->refname, "refs/heads/",
2453 &branch_name))
2454 continue;
2455 branch = branch_get(branch_name);
2457 if (atom->u.remote_ref.push_remote)
2458 refname = NULL;
2459 else {
2460 refname = branch_get_push(branch, NULL);
2461 if (!refname)
2462 continue;
2464 /* We will definitely re-init v->s on the next line. */
2465 free((char *)v->s);
2466 fill_remote_ref_details(atom, refname, branch, &v->s);
2467 continue;
2468 } else if (atom_type == ATOM_COLOR) {
2469 v->s = xstrdup(atom->u.color);
2470 continue;
2471 } else if (atom_type == ATOM_FLAG) {
2472 char buf[256], *cp = buf;
2473 if (ref->flag & REF_ISSYMREF)
2474 cp = copy_advance(cp, ",symref");
2475 if (ref->flag & REF_ISPACKED)
2476 cp = copy_advance(cp, ",packed");
2477 if (cp == buf)
2478 v->s = xstrdup("");
2479 else {
2480 *cp = '\0';
2481 v->s = xstrdup(buf + 1);
2483 continue;
2484 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2485 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2486 continue;
2487 } else if (atom_type == ATOM_HEAD) {
2488 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2489 v->s = xstrdup("*");
2490 else
2491 v->s = xstrdup(" ");
2492 continue;
2493 } else if (atom_type == ATOM_ALIGN) {
2494 v->handler = align_atom_handler;
2495 v->s = xstrdup("");
2496 continue;
2497 } else if (atom_type == ATOM_END) {
2498 v->handler = end_atom_handler;
2499 v->s = xstrdup("");
2500 continue;
2501 } else if (atom_type == ATOM_IF) {
2502 const char *s;
2503 if (skip_prefix(name, "if:", &s))
2504 v->s = xstrdup(s);
2505 else
2506 v->s = xstrdup("");
2507 v->handler = if_atom_handler;
2508 continue;
2509 } else if (atom_type == ATOM_THEN) {
2510 v->handler = then_atom_handler;
2511 v->s = xstrdup("");
2512 continue;
2513 } else if (atom_type == ATOM_ELSE) {
2514 v->handler = else_atom_handler;
2515 v->s = xstrdup("");
2516 continue;
2517 } else if (atom_type == ATOM_REST) {
2518 if (ref->rest)
2519 v->s = xstrdup(ref->rest);
2520 else
2521 v->s = xstrdup("");
2522 continue;
2523 } else if (atom_type == ATOM_AHEADBEHIND) {
2524 if (ref->counts) {
2525 const struct ahead_behind_count *count;
2526 count = ref->counts[ahead_behind_atoms++];
2527 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2528 } else {
2529 /* Not a commit. */
2530 v->s = xstrdup("");
2532 continue;
2533 } else if (atom_type == ATOM_ISBASE) {
2534 if (ref->is_base && ref->is_base[is_base_atoms]) {
2535 v->s = xstrfmt("(%s)", ref->is_base[is_base_atoms]);
2536 free(ref->is_base[is_base_atoms]);
2537 } else {
2538 v->s = xstrdup("");
2540 is_base_atoms++;
2541 continue;
2542 } else
2543 continue;
2545 if (!deref)
2546 v->s = xstrdup(refname);
2547 else
2548 v->s = xstrfmt("%s^{}", refname);
2549 free((char *)refname);
2552 for (i = 0; i < used_atom_cnt; i++) {
2553 struct atom_value *v = &ref->value[i];
2554 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2555 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2556 oid_to_hex(&ref->objectname), ref->refname);
2559 if (need_tagged)
2560 oi.info.contentp = &oi.content;
2561 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2562 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2563 return 0;
2566 oi.oid = ref->objectname;
2567 if (get_object(ref, 0, &obj, &oi, err))
2568 return -1;
2571 * If there is no atom that wants to know about tagged
2572 * object, we are done.
2574 if (!need_tagged || (obj->type != OBJ_TAG))
2575 return 0;
2578 * If it is a tag object, see if we use the peeled value. If we do,
2579 * grab the peeled OID.
2581 if (need_tagged && peel_iterated_oid(the_repository, &obj->oid, &oi_deref.oid))
2582 die("bad tag");
2584 return get_object(ref, 1, &obj, &oi_deref, err);
2588 * Given a ref, return the value for the atom. This lazily gets value
2589 * out of the object by calling populate value.
2591 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2592 struct atom_value **v, struct strbuf *err)
2594 if (!ref->value) {
2595 if (populate_value(ref, err))
2596 return -1;
2597 fill_missing_values(ref->value);
2599 *v = &ref->value[atom];
2600 return 0;
2604 * Return 1 if the refname matches one of the patterns, otherwise 0.
2605 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2606 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2607 * matches "refs/heads/mas*", too).
2609 static int match_pattern(const char **patterns, const char *refname,
2610 int ignore_case)
2612 unsigned flags = 0;
2614 if (ignore_case)
2615 flags |= WM_CASEFOLD;
2618 * When no '--format' option is given we need to skip the prefix
2619 * for matching refs of tags and branches.
2621 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2622 skip_prefix(refname, "refs/heads/", &refname) ||
2623 skip_prefix(refname, "refs/remotes/", &refname) ||
2624 skip_prefix(refname, "refs/", &refname));
2626 for (; *patterns; patterns++) {
2627 if (!wildmatch(*patterns, refname, flags))
2628 return 1;
2630 return 0;
2634 * Return 1 if the refname matches one of the patterns, otherwise 0.
2635 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2636 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2637 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2639 static int match_name_as_path(const char **pattern, const char *refname,
2640 int ignore_case)
2642 int namelen = strlen(refname);
2643 unsigned flags = WM_PATHNAME;
2645 if (ignore_case)
2646 flags |= WM_CASEFOLD;
2648 for (; *pattern; pattern++) {
2649 const char *p = *pattern;
2650 int plen = strlen(p);
2652 if ((plen <= namelen) &&
2653 !strncmp(refname, p, plen) &&
2654 (refname[plen] == '\0' ||
2655 refname[plen] == '/' ||
2656 p[plen-1] == '/'))
2657 return 1;
2658 if (!wildmatch(p, refname, flags))
2659 return 1;
2661 return 0;
2664 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2665 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2667 if (!*filter->name_patterns)
2668 return 1; /* No pattern always matches */
2669 if (filter->match_as_path)
2670 return match_name_as_path(filter->name_patterns, refname,
2671 filter->ignore_case);
2672 return match_pattern(filter->name_patterns, refname,
2673 filter->ignore_case);
2676 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2678 if (!filter->exclude.nr)
2679 return 0;
2680 if (filter->match_as_path)
2681 return match_name_as_path(filter->exclude.v, refname,
2682 filter->ignore_case);
2683 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2687 * This is the same as for_each_fullref_in(), but it tries to iterate
2688 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2689 * pattern match, so the callback still has to match each ref individually.
2691 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2692 each_ref_fn cb,
2693 void *cb_data)
2695 if (filter->kind & FILTER_REFS_ROOT_REFS) {
2696 /* In this case, we want to print all refs including root refs. */
2697 return refs_for_each_include_root_refs(get_main_ref_store(the_repository),
2698 cb, cb_data);
2701 if (!filter->match_as_path) {
2703 * in this case, the patterns are applied after
2704 * prefixes like "refs/heads/" etc. are stripped off,
2705 * so we have to look at everything:
2707 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2708 "", NULL, cb, cb_data);
2711 if (filter->ignore_case) {
2713 * we can't handle case-insensitive comparisons,
2714 * so just return everything and let the caller
2715 * sort it out.
2717 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2718 "", NULL, cb, cb_data);
2721 if (!filter->name_patterns[0]) {
2722 /* no patterns; we have to look at everything */
2723 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2724 "", filter->exclude.v, cb, cb_data);
2727 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2728 NULL, filter->name_patterns,
2729 filter->exclude.v,
2730 cb, cb_data);
2734 * Given a ref (oid, refname), check if the ref belongs to the array
2735 * of oids. If the given ref is a tag, check if the given tag points
2736 * at one of the oids in the given oid array. Returns non-zero if a
2737 * match is found.
2739 * NEEDSWORK:
2740 * As the refs are cached we might know what refname peels to without
2741 * the need to parse the object via parse_object(). peel_ref() might be a
2742 * more efficient alternative to obtain the pointee.
2744 static int match_points_at(struct oid_array *points_at,
2745 const struct object_id *oid,
2746 const char *refname)
2748 struct object *obj;
2750 if (oid_array_lookup(points_at, oid) >= 0)
2751 return 1;
2752 obj = parse_object_with_flags(the_repository, oid,
2753 PARSE_OBJECT_SKIP_HASH_CHECK);
2754 while (obj && obj->type == OBJ_TAG) {
2755 struct tag *tag = (struct tag *)obj;
2757 if (parse_tag(tag) < 0) {
2758 obj = NULL;
2759 break;
2762 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2763 return 1;
2765 obj = tag->tagged;
2767 if (!obj)
2768 die(_("malformed object at '%s'"), refname);
2769 return 0;
2773 * Allocate space for a new ref_array_item and copy the name and oid to it.
2775 * Callers can then fill in other struct members at their leisure.
2777 static struct ref_array_item *new_ref_array_item(const char *refname,
2778 const struct object_id *oid)
2780 struct ref_array_item *ref;
2782 FLEX_ALLOC_STR(ref, refname, refname);
2783 oidcpy(&ref->objectname, oid);
2784 ref->rest = NULL;
2786 return ref;
2789 static void ref_array_append(struct ref_array *array, struct ref_array_item *ref)
2791 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2792 array->items[array->nr++] = ref;
2795 struct ref_array_item *ref_array_push(struct ref_array *array,
2796 const char *refname,
2797 const struct object_id *oid)
2799 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2800 ref_array_append(array, ref);
2801 return ref;
2804 static int ref_kind_from_refname(const char *refname)
2806 unsigned int i;
2808 static struct {
2809 const char *prefix;
2810 unsigned int kind;
2811 } ref_kind[] = {
2812 { "refs/heads/" , FILTER_REFS_BRANCHES },
2813 { "refs/remotes/" , FILTER_REFS_REMOTES },
2814 { "refs/tags/", FILTER_REFS_TAGS}
2817 if (!strcmp(refname, "HEAD"))
2818 return FILTER_REFS_DETACHED_HEAD;
2820 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2821 if (starts_with(refname, ref_kind[i].prefix))
2822 return ref_kind[i].kind;
2825 if (is_pseudo_ref(refname))
2826 return FILTER_REFS_PSEUDOREFS;
2827 if (is_root_ref(refname))
2828 return FILTER_REFS_ROOT_REFS;
2830 return FILTER_REFS_OTHERS;
2833 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2835 if (filter->kind == FILTER_REFS_BRANCHES ||
2836 filter->kind == FILTER_REFS_REMOTES ||
2837 filter->kind == FILTER_REFS_TAGS)
2838 return filter->kind;
2839 return ref_kind_from_refname(refname);
2842 static struct ref_array_item *apply_ref_filter(const char *refname, const char *referent, const struct object_id *oid,
2843 int flag, struct ref_filter *filter)
2845 struct ref_array_item *ref;
2846 struct commit *commit = NULL;
2847 unsigned int kind;
2849 if (flag & REF_BAD_NAME) {
2850 warning(_("ignoring ref with broken name %s"), refname);
2851 return NULL;
2854 if (flag & REF_ISBROKEN) {
2855 warning(_("ignoring broken ref %s"), refname);
2856 return NULL;
2859 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2860 kind = filter_ref_kind(filter, refname);
2863 * Generally HEAD refs are printed with special description denoting a rebase,
2864 * detached state and so forth. This is useful when only printing the HEAD ref
2865 * But when it is being printed along with other root refs, it makes sense to
2866 * keep the formatting consistent. So we mask the type to act like a root ref.
2868 if (filter->kind & FILTER_REFS_ROOT_REFS && kind == FILTER_REFS_DETACHED_HEAD)
2869 kind = FILTER_REFS_ROOT_REFS;
2870 else if (!(kind & filter->kind))
2871 return NULL;
2873 if (!filter_pattern_match(filter, refname))
2874 return NULL;
2876 if (filter_exclude_match(filter, refname))
2877 return NULL;
2879 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2880 return NULL;
2883 * A merge filter is applied on refs pointing to commits. Hence
2884 * obtain the commit using the 'oid' available and discard all
2885 * non-commits early. The actual filtering is done later.
2887 if (filter->reachable_from || filter->unreachable_from ||
2888 filter->with_commit || filter->no_commit || filter->verbose) {
2889 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2890 if (!commit)
2891 return NULL;
2892 /* We perform the filtering for the '--contains' option... */
2893 if (filter->with_commit &&
2894 !commit_contains(filter, commit, filter->with_commit, &filter->internal.contains_cache))
2895 return NULL;
2896 /* ...or for the `--no-contains' option */
2897 if (filter->no_commit &&
2898 commit_contains(filter, commit, filter->no_commit, &filter->internal.no_contains_cache))
2899 return NULL;
2903 * We do not open the object yet; sort may only need refname
2904 * to do its job and the resulting list may yet to be pruned
2905 * by maxcount logic.
2907 ref = new_ref_array_item(refname, oid);
2908 ref->commit = commit;
2909 ref->flag = flag;
2910 ref->kind = kind;
2911 ref->symref = xstrdup_or_null(referent);
2913 return ref;
2916 struct ref_filter_cbdata {
2917 struct ref_array *array;
2918 struct ref_filter *filter;
2922 * A call-back given to for_each_ref(). Filter refs and keep them for
2923 * later object processing.
2925 static int filter_one(const char *refname, const char *referent, const struct object_id *oid, int flag, void *cb_data)
2927 struct ref_filter_cbdata *ref_cbdata = cb_data;
2928 struct ref_array_item *ref;
2930 ref = apply_ref_filter(refname, referent, oid, flag, ref_cbdata->filter);
2931 if (ref)
2932 ref_array_append(ref_cbdata->array, ref);
2934 return 0;
2937 /* Free memory allocated for a ref_array_item */
2938 static void free_array_item(struct ref_array_item *item)
2940 free((char *)item->symref);
2941 if (item->value) {
2942 int i;
2943 for (i = 0; i < used_atom_cnt; i++)
2944 free((char *)item->value[i].s);
2945 free(item->value);
2947 free(item->counts);
2948 free(item->is_base);
2949 free(item);
2952 struct ref_filter_and_format_cbdata {
2953 struct ref_filter *filter;
2954 struct ref_format *format;
2956 struct ref_filter_and_format_internal {
2957 int count;
2958 } internal;
2961 static int filter_and_format_one(const char *refname, const char *referent, const struct object_id *oid, int flag, void *cb_data)
2963 struct ref_filter_and_format_cbdata *ref_cbdata = cb_data;
2964 struct ref_array_item *ref;
2965 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
2967 ref = apply_ref_filter(refname, referent, oid, flag, ref_cbdata->filter);
2968 if (!ref)
2969 return 0;
2971 if (format_ref_array_item(ref, ref_cbdata->format, &output, &err))
2972 die("%s", err.buf);
2974 if (output.len || !ref_cbdata->format->array_opts.omit_empty) {
2975 fwrite(output.buf, 1, output.len, stdout);
2976 putchar('\n');
2979 strbuf_release(&output);
2980 strbuf_release(&err);
2981 free_array_item(ref);
2984 * Increment the running count of refs that match the filter. If
2985 * max_count is set and we've reached the max, stop the ref
2986 * iteration by returning a nonzero value.
2988 if (ref_cbdata->format->array_opts.max_count &&
2989 ++ref_cbdata->internal.count >= ref_cbdata->format->array_opts.max_count)
2990 return 1;
2992 return 0;
2995 /* Free all memory allocated for ref_array */
2996 void ref_array_clear(struct ref_array *array)
2998 int i;
3000 for (i = 0; i < array->nr; i++)
3001 free_array_item(array->items[i]);
3002 FREE_AND_NULL(array->items);
3003 array->nr = array->alloc = 0;
3005 for (i = 0; i < used_atom_cnt; i++) {
3006 struct used_atom *atom = &used_atom[i];
3007 if (atom->atom_type == ATOM_HEAD)
3008 free(atom->u.head);
3009 else if (atom->atom_type == ATOM_DESCRIBE)
3010 strvec_clear(&atom->u.describe_args);
3011 else if (atom->atom_type == ATOM_TRAILERS ||
3012 (atom->atom_type == ATOM_CONTENTS &&
3013 atom->u.contents.option == C_TRAILERS)) {
3014 struct ref_trailer_buf *tb = atom->u.contents.trailer_buf;
3015 if (tb) {
3016 string_list_clear(&tb->filter_list, 0);
3017 strbuf_release(&tb->sepbuf);
3018 strbuf_release(&tb->kvsepbuf);
3019 free(tb);
3022 free((char *)atom->name);
3024 FREE_AND_NULL(used_atom);
3025 used_atom_cnt = 0;
3027 if (ref_to_worktree_map.worktrees) {
3028 hashmap_clear_and_free(&(ref_to_worktree_map.map),
3029 struct ref_to_worktree_entry, ent);
3030 free_worktrees(ref_to_worktree_map.worktrees);
3031 ref_to_worktree_map.worktrees = NULL;
3034 FREE_AND_NULL(array->counts);
3037 #define EXCLUDE_REACHED 0
3038 #define INCLUDE_REACHED 1
3039 static void reach_filter(struct ref_array *array,
3040 struct commit_list **check_reachable,
3041 int include_reached)
3043 int i, old_nr;
3044 struct commit **to_clear;
3046 if (!*check_reachable)
3047 return;
3049 CALLOC_ARRAY(to_clear, array->nr);
3050 for (i = 0; i < array->nr; i++) {
3051 struct ref_array_item *item = array->items[i];
3052 to_clear[i] = item->commit;
3055 tips_reachable_from_bases(the_repository,
3056 *check_reachable,
3057 to_clear, array->nr,
3058 UNINTERESTING);
3060 old_nr = array->nr;
3061 array->nr = 0;
3063 for (i = 0; i < old_nr; i++) {
3064 struct ref_array_item *item = array->items[i];
3065 struct commit *commit = item->commit;
3067 int is_merged = !!(commit->object.flags & UNINTERESTING);
3069 if (is_merged == include_reached)
3070 array->items[array->nr++] = array->items[i];
3071 else
3072 free_array_item(item);
3075 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
3077 while (*check_reachable) {
3078 struct commit *merge_commit = pop_commit(check_reachable);
3079 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
3082 free(to_clear);
3085 void filter_ahead_behind(struct repository *r,
3086 struct ref_format *format,
3087 struct ref_array *array)
3089 struct commit **commits;
3090 size_t commits_nr = format->bases.nr + array->nr;
3092 if (!format->bases.nr || !array->nr)
3093 return;
3095 ALLOC_ARRAY(commits, commits_nr);
3096 for (size_t i = 0; i < format->bases.nr; i++)
3097 commits[i] = format->bases.items[i].util;
3099 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
3101 commits_nr = format->bases.nr;
3102 array->counts_nr = 0;
3103 for (size_t i = 0; i < array->nr; i++) {
3104 const char *name = array->items[i]->refname;
3105 commits[commits_nr] = lookup_commit_reference_by_name(name);
3107 if (!commits[commits_nr])
3108 continue;
3110 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
3111 for (size_t j = 0; j < format->bases.nr; j++) {
3112 struct ahead_behind_count *count;
3113 count = &array->counts[array->counts_nr++];
3114 count->tip_index = commits_nr;
3115 count->base_index = j;
3117 array->items[i]->counts[j] = count;
3119 commits_nr++;
3122 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
3123 free(commits);
3126 void filter_is_base(struct repository *r,
3127 struct ref_format *format,
3128 struct ref_array *array)
3130 struct commit **bases;
3131 size_t bases_nr = 0;
3132 struct ref_array_item **back_index;
3134 if (!format->is_base_tips.nr || !array->nr)
3135 return;
3137 CALLOC_ARRAY(back_index, array->nr);
3138 CALLOC_ARRAY(bases, array->nr);
3140 for (size_t i = 0; i < array->nr; i++) {
3141 const char *name = array->items[i]->refname;
3142 struct commit *c = lookup_commit_reference_by_name_gently(name, 1);
3144 CALLOC_ARRAY(array->items[i]->is_base, format->is_base_tips.nr);
3146 if (!c)
3147 continue;
3149 back_index[bases_nr] = array->items[i];
3150 bases[bases_nr] = c;
3151 bases_nr++;
3154 for (size_t i = 0; i < format->is_base_tips.nr; i++) {
3155 struct commit *tip = format->is_base_tips.items[i].util;
3156 int base_index = get_branch_base_for_tip(r, tip, bases, bases_nr);
3158 if (base_index < 0)
3159 continue;
3161 /* Store the string for use in output later. */
3162 back_index[base_index]->is_base[i] = xstrdup(format->is_base_tips.items[i].string);
3165 free(back_index);
3166 free(bases);
3169 static int do_filter_refs(struct ref_filter *filter, unsigned int type, each_ref_fn fn, void *cb_data)
3171 int ret = 0;
3173 filter->kind = type & FILTER_REFS_KIND_MASK;
3175 init_contains_cache(&filter->internal.contains_cache);
3176 init_contains_cache(&filter->internal.no_contains_cache);
3178 /* Simple per-ref filtering */
3179 if (!filter->kind)
3180 die("filter_refs: invalid type");
3181 else {
3183 * For common cases where we need only branches or remotes or tags,
3184 * we only iterate through those refs. If a mix of refs is needed,
3185 * we iterate over all refs and filter out required refs with the help
3186 * of filter_ref_kind().
3188 if (filter->kind == FILTER_REFS_BRANCHES)
3189 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3190 "refs/heads/", NULL,
3191 fn, cb_data);
3192 else if (filter->kind == FILTER_REFS_REMOTES)
3193 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3194 "refs/remotes/", NULL,
3195 fn, cb_data);
3196 else if (filter->kind == FILTER_REFS_TAGS)
3197 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3198 "refs/tags/", NULL, fn,
3199 cb_data);
3200 else if (filter->kind & FILTER_REFS_REGULAR)
3201 ret = for_each_fullref_in_pattern(filter, fn, cb_data);
3204 * When printing all ref types, HEAD is already included,
3205 * so we don't want to print HEAD again.
3207 if (!ret && !(filter->kind & FILTER_REFS_ROOT_REFS) &&
3208 (filter->kind & FILTER_REFS_DETACHED_HEAD))
3209 refs_head_ref(get_main_ref_store(the_repository), fn,
3210 cb_data);
3213 clear_contains_cache(&filter->internal.contains_cache);
3214 clear_contains_cache(&filter->internal.no_contains_cache);
3216 return ret;
3220 * API for filtering a set of refs. Based on the type of refs the user
3221 * has requested, we iterate through those refs and apply filters
3222 * as per the given ref_filter structure and finally store the
3223 * filtered refs in the ref_array structure.
3225 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
3227 struct ref_filter_cbdata ref_cbdata;
3228 int save_commit_buffer_orig;
3229 int ret = 0;
3231 ref_cbdata.array = array;
3232 ref_cbdata.filter = filter;
3234 save_commit_buffer_orig = save_commit_buffer;
3235 save_commit_buffer = 0;
3237 ret = do_filter_refs(filter, type, filter_one, &ref_cbdata);
3239 /* Filters that need revision walking */
3240 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
3241 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
3243 save_commit_buffer = save_commit_buffer_orig;
3244 return ret;
3247 struct ref_sorting {
3248 struct ref_sorting *next;
3249 int atom; /* index into used_atom array (internal) */
3250 enum ref_sorting_order sort_flags;
3253 static inline int can_do_iterative_format(struct ref_filter *filter,
3254 struct ref_sorting *sorting,
3255 struct ref_format *format)
3258 * Reference backends sort patterns lexicographically by refname, so if
3259 * the sorting options ask for exactly that we are able to do iterative
3260 * formatting.
3262 * Note that we do not have to worry about multiple name patterns,
3263 * either. Those get sorted and deduplicated eventually in
3264 * `refs_for_each_fullref_in_prefixes()`, so we return names in the
3265 * correct ordering here, too.
3267 if (sorting && (sorting->next ||
3268 sorting->sort_flags ||
3269 used_atom[sorting->atom].atom_type != ATOM_REFNAME))
3270 return 0;
3273 * Filtering & formatting results within a single ref iteration
3274 * callback is not compatible with options that require
3275 * post-processing a filtered ref_array. These include:
3276 * - filtering on reachability
3277 * - including ahead-behind information in the formatted output
3279 return !(filter->reachable_from ||
3280 filter->unreachable_from ||
3281 format->bases.nr ||
3282 format->is_base_tips.nr);
3285 void filter_and_format_refs(struct ref_filter *filter, unsigned int type,
3286 struct ref_sorting *sorting,
3287 struct ref_format *format)
3289 if (can_do_iterative_format(filter, sorting, format)) {
3290 int save_commit_buffer_orig;
3291 struct ref_filter_and_format_cbdata ref_cbdata = {
3292 .filter = filter,
3293 .format = format,
3296 save_commit_buffer_orig = save_commit_buffer;
3297 save_commit_buffer = 0;
3299 do_filter_refs(filter, type, filter_and_format_one, &ref_cbdata);
3301 save_commit_buffer = save_commit_buffer_orig;
3302 } else {
3303 struct ref_array array = { 0 };
3304 filter_refs(&array, filter, type);
3305 filter_ahead_behind(the_repository, format, &array);
3306 filter_is_base(the_repository, format, &array);
3307 ref_array_sort(sorting, &array);
3308 print_formatted_ref_array(&array, format);
3309 ref_array_clear(&array);
3313 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
3315 if (!(a->kind ^ b->kind))
3316 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
3317 if (a->kind & FILTER_REFS_DETACHED_HEAD)
3318 return -1;
3319 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
3320 return 1;
3321 BUG("should have died in the xor check above");
3322 return 0;
3325 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
3327 const char *s1 = vs1, *s2 = vs2;
3328 const char *end = s1 + n;
3330 for (; s1 < end; s1++, s2++) {
3331 int diff = tolower(*s1) - tolower(*s2);
3332 if (diff)
3333 return diff;
3335 return 0;
3338 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
3340 struct atom_value *va, *vb;
3341 int cmp;
3342 int cmp_detached_head = 0;
3343 cmp_type cmp_type = used_atom[s->atom].type;
3344 struct strbuf err = STRBUF_INIT;
3346 if (get_ref_atom_value(a, s->atom, &va, &err))
3347 die("%s", err.buf);
3348 if (get_ref_atom_value(b, s->atom, &vb, &err))
3349 die("%s", err.buf);
3350 strbuf_release(&err);
3351 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
3352 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
3353 cmp = compare_detached_head(a, b);
3354 cmp_detached_head = 1;
3355 } else if (s->sort_flags & REF_SORTING_VERSION) {
3356 cmp = versioncmp(va->s, vb->s);
3357 } else if (cmp_type == FIELD_STR) {
3358 if (va->s_size < 0 && vb->s_size < 0) {
3359 int (*cmp_fn)(const char *, const char *);
3360 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3361 ? strcasecmp : strcmp;
3362 cmp = cmp_fn(va->s, vb->s);
3363 } else {
3364 size_t a_size = va->s_size < 0 ?
3365 strlen(va->s) : va->s_size;
3366 size_t b_size = vb->s_size < 0 ?
3367 strlen(vb->s) : vb->s_size;
3368 int (*cmp_fn)(const void *, const void *, size_t);
3369 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3370 ? memcasecmp : memcmp;
3372 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3373 a_size : b_size);
3374 if (!cmp) {
3375 if (a_size > b_size)
3376 cmp = 1;
3377 else if (a_size < b_size)
3378 cmp = -1;
3381 } else {
3382 if (va->value < vb->value)
3383 cmp = -1;
3384 else if (va->value == vb->value)
3385 cmp = 0;
3386 else
3387 cmp = 1;
3390 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3391 ? -cmp : cmp;
3394 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3396 struct ref_array_item *a = *((struct ref_array_item **)a_);
3397 struct ref_array_item *b = *((struct ref_array_item **)b_);
3398 struct ref_sorting *s;
3400 for (s = ref_sorting; s; s = s->next) {
3401 int cmp = cmp_ref_sorting(s, a, b);
3402 if (cmp)
3403 return cmp;
3405 s = ref_sorting;
3406 return s && s->sort_flags & REF_SORTING_ICASE ?
3407 strcasecmp(a->refname, b->refname) :
3408 strcmp(a->refname, b->refname);
3411 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3412 unsigned int mask, int on)
3414 for (; sorting; sorting = sorting->next) {
3415 if (on)
3416 sorting->sort_flags |= mask;
3417 else
3418 sorting->sort_flags &= ~mask;
3422 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3424 if (sorting)
3425 QSORT_S(array->items, array->nr, compare_refs, sorting);
3428 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3430 struct strbuf *s = &state->stack->output;
3432 while (*cp && (!ep || cp < ep)) {
3433 if (*cp == '%') {
3434 if (cp[1] == '%')
3435 cp++;
3436 else {
3437 int ch = hex2chr(cp + 1);
3438 if (0 <= ch) {
3439 strbuf_addch(s, ch);
3440 cp += 3;
3441 continue;
3445 strbuf_addch(s, *cp);
3446 cp++;
3450 int format_ref_array_item(struct ref_array_item *info,
3451 struct ref_format *format,
3452 struct strbuf *final_buf,
3453 struct strbuf *error_buf)
3455 const char *cp, *sp, *ep;
3456 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3458 state.quote_style = format->quote_style;
3459 push_stack_element(&state.stack);
3461 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3462 struct atom_value *atomv;
3463 int pos;
3465 ep = strchr(sp, ')');
3466 if (cp < sp)
3467 append_literal(cp, sp, &state);
3468 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3469 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3470 atomv->handler(atomv, &state, error_buf)) {
3471 pop_stack_element(&state.stack);
3472 return -1;
3475 if (*cp) {
3476 sp = cp + strlen(cp);
3477 append_literal(cp, sp, &state);
3479 if (format->need_color_reset_at_eol) {
3480 struct atom_value resetv = ATOM_VALUE_INIT;
3481 resetv.s = GIT_COLOR_RESET;
3482 if (append_atom(&resetv, &state, error_buf)) {
3483 pop_stack_element(&state.stack);
3484 return -1;
3487 if (state.stack->prev) {
3488 pop_stack_element(&state.stack);
3489 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3491 strbuf_addbuf(final_buf, &state.stack->output);
3492 pop_stack_element(&state.stack);
3493 return 0;
3496 void print_formatted_ref_array(struct ref_array *array, struct ref_format *format)
3498 int total;
3499 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3501 total = format->array_opts.max_count;
3502 if (!total || array->nr < total)
3503 total = array->nr;
3504 for (int i = 0; i < total; i++) {
3505 strbuf_reset(&err);
3506 strbuf_reset(&output);
3507 if (format_ref_array_item(array->items[i], format, &output, &err))
3508 die("%s", err.buf);
3509 if (output.len || !format->array_opts.omit_empty) {
3510 fwrite(output.buf, 1, output.len, stdout);
3511 putchar('\n');
3515 strbuf_release(&err);
3516 strbuf_release(&output);
3519 void pretty_print_ref(const char *name, const struct object_id *oid,
3520 struct ref_format *format)
3522 struct ref_array_item *ref_item;
3523 struct strbuf output = STRBUF_INIT;
3524 struct strbuf err = STRBUF_INIT;
3526 ref_item = new_ref_array_item(name, oid);
3527 ref_item->kind = ref_kind_from_refname(name);
3528 if (format_ref_array_item(ref_item, format, &output, &err))
3529 die("%s", err.buf);
3530 fwrite(output.buf, 1, output.len, stdout);
3531 putchar('\n');
3533 strbuf_release(&err);
3534 strbuf_release(&output);
3535 free_array_item(ref_item);
3538 static int parse_sorting_atom(const char *atom)
3541 * This parses an atom using a dummy ref_format, since we don't
3542 * actually care about the formatting details.
3544 struct ref_format dummy = REF_FORMAT_INIT;
3545 const char *end = atom + strlen(atom);
3546 struct strbuf err = STRBUF_INIT;
3547 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3548 if (res < 0)
3549 die("%s", err.buf);
3550 strbuf_release(&err);
3551 return res;
3554 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3556 struct ref_sorting *s;
3558 CALLOC_ARRAY(s, 1);
3559 s->next = *sorting_tail;
3560 *sorting_tail = s;
3562 if (*arg == '-') {
3563 s->sort_flags |= REF_SORTING_REVERSE;
3564 arg++;
3566 if (skip_prefix(arg, "version:", &arg) ||
3567 skip_prefix(arg, "v:", &arg))
3568 s->sort_flags |= REF_SORTING_VERSION;
3569 s->atom = parse_sorting_atom(arg);
3572 struct ref_sorting *ref_sorting_options(struct string_list *options)
3574 struct string_list_item *item;
3575 struct ref_sorting *sorting = NULL, **tail = &sorting;
3577 if (options->nr) {
3578 for_each_string_list_item(item, options)
3579 parse_ref_sorting(tail, item->string);
3583 * From here on, the ref_sorting list should be used to talk
3584 * about the sort order used for the output. The caller
3585 * should not touch the string form anymore.
3587 string_list_clear(options, 0);
3588 return sorting;
3591 void ref_sorting_release(struct ref_sorting *sorting)
3593 while (sorting) {
3594 struct ref_sorting *next = sorting->next;
3595 free(sorting);
3596 sorting = next;
3600 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3602 struct ref_filter *rf = opt->value;
3603 struct object_id oid;
3604 struct commit *merge_commit;
3606 BUG_ON_OPT_NEG(unset);
3608 if (repo_get_oid(the_repository, arg, &oid))
3609 die(_("malformed object name %s"), arg);
3611 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3613 if (!merge_commit)
3614 return error(_("option `%s' must point to a commit"), opt->long_name);
3616 if (starts_with(opt->long_name, "no"))
3617 commit_list_insert(merge_commit, &rf->unreachable_from);
3618 else
3619 commit_list_insert(merge_commit, &rf->reachable_from);
3621 return 0;
3624 void ref_filter_init(struct ref_filter *filter)
3626 struct ref_filter blank = REF_FILTER_INIT;
3627 memcpy(filter, &blank, sizeof(blank));
3630 void ref_filter_clear(struct ref_filter *filter)
3632 strvec_clear(&filter->exclude);
3633 oid_array_clear(&filter->points_at);
3634 free_commit_list(filter->with_commit);
3635 free_commit_list(filter->no_commit);
3636 free_commit_list(filter->reachable_from);
3637 free_commit_list(filter->unreachable_from);
3638 ref_filter_init(filter);
3641 void ref_format_init(struct ref_format *format)
3643 struct ref_format blank = REF_FORMAT_INIT;
3644 memcpy(format, &blank, sizeof(blank));
3647 void ref_format_clear(struct ref_format *format)
3649 string_list_clear(&format->bases, 0);
3650 string_list_clear(&format->is_base_tips, 0);
3651 ref_format_init(format);