Merge branch 'ps/reftable-drop-generic'
[git/gitster.git] / ref-filter.c
blobb6c6c101276b63f7f144984888aada0524a3af94
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "config.h"
7 #include "gpg-interface.h"
8 #include "hex.h"
9 #include "parse-options.h"
10 #include "run-command.h"
11 #include "refs.h"
12 #include "wildmatch.h"
13 #include "object-name.h"
14 #include "object-store-ll.h"
15 #include "oid-array.h"
16 #include "repository.h"
17 #include "commit.h"
18 #include "mailmap.h"
19 #include "ident.h"
20 #include "remote.h"
21 #include "color.h"
22 #include "tag.h"
23 #include "quote.h"
24 #include "ref-filter.h"
25 #include "revision.h"
26 #include "utf8.h"
27 #include "versioncmp.h"
28 #include "trailer.h"
29 #include "wt-status.h"
30 #include "commit-slab.h"
31 #include "commit-reach.h"
32 #include "worktree.h"
33 #include "hashmap.h"
35 static struct ref_msg {
36 const char *gone;
37 const char *ahead;
38 const char *behind;
39 const char *ahead_behind;
40 } msgs = {
41 /* Untranslated plumbing messages: */
42 "gone",
43 "ahead %d",
44 "behind %d",
45 "ahead %d, behind %d"
48 void setup_ref_filter_porcelain_msg(void)
50 msgs.gone = _("gone");
51 msgs.ahead = _("ahead %d");
52 msgs.behind = _("behind %d");
53 msgs.ahead_behind = _("ahead %d, behind %d");
56 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
57 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
58 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
60 struct align {
61 align_type position;
62 unsigned int width;
65 struct if_then_else {
66 cmp_status cmp_status;
67 const char *str;
68 unsigned int then_atom_seen : 1,
69 else_atom_seen : 1,
70 condition_satisfied : 1;
73 struct refname_atom {
74 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
75 int lstrip, rstrip;
78 static struct ref_trailer_buf {
79 struct string_list filter_list;
80 struct strbuf sepbuf;
81 struct strbuf kvsepbuf;
82 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
84 static struct expand_data {
85 struct object_id oid;
86 enum object_type type;
87 unsigned long size;
88 off_t disk_size;
89 struct object_id delta_base_oid;
90 void *content;
92 struct object_info info;
93 } oi, oi_deref;
95 struct ref_to_worktree_entry {
96 struct hashmap_entry ent;
97 struct worktree *wt; /* key is wt->head_ref */
100 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
101 const struct hashmap_entry *eptr,
102 const struct hashmap_entry *kptr,
103 const void *keydata_aka_refname)
105 const struct ref_to_worktree_entry *e, *k;
107 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
108 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
110 return strcmp(e->wt->head_ref,
111 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
114 static struct ref_to_worktree_map {
115 struct hashmap map;
116 struct worktree **worktrees;
117 } ref_to_worktree_map;
120 * The enum atom_type is used as the index of valid_atom array.
121 * In the atom parsing stage, it will be passed to used_atom.atom_type
122 * as the identifier of the atom type. We can check the type of used_atom
123 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
125 enum atom_type {
126 ATOM_REFNAME,
127 ATOM_OBJECTTYPE,
128 ATOM_OBJECTSIZE,
129 ATOM_OBJECTNAME,
130 ATOM_DELTABASE,
131 ATOM_TREE,
132 ATOM_PARENT,
133 ATOM_NUMPARENT,
134 ATOM_OBJECT,
135 ATOM_TYPE,
136 ATOM_TAG,
137 ATOM_AUTHOR,
138 ATOM_AUTHORNAME,
139 ATOM_AUTHOREMAIL,
140 ATOM_AUTHORDATE,
141 ATOM_COMMITTER,
142 ATOM_COMMITTERNAME,
143 ATOM_COMMITTEREMAIL,
144 ATOM_COMMITTERDATE,
145 ATOM_TAGGER,
146 ATOM_TAGGERNAME,
147 ATOM_TAGGEREMAIL,
148 ATOM_TAGGERDATE,
149 ATOM_CREATOR,
150 ATOM_CREATORDATE,
151 ATOM_DESCRIBE,
152 ATOM_SUBJECT,
153 ATOM_BODY,
154 ATOM_TRAILERS,
155 ATOM_CONTENTS,
156 ATOM_SIGNATURE,
157 ATOM_RAW,
158 ATOM_UPSTREAM,
159 ATOM_PUSH,
160 ATOM_SYMREF,
161 ATOM_FLAG,
162 ATOM_HEAD,
163 ATOM_COLOR,
164 ATOM_WORKTREEPATH,
165 ATOM_ALIGN,
166 ATOM_END,
167 ATOM_IF,
168 ATOM_THEN,
169 ATOM_ELSE,
170 ATOM_REST,
171 ATOM_AHEADBEHIND,
172 ATOM_ISBASE,
176 * An atom is a valid field atom listed below, possibly prefixed with
177 * a "*" to denote deref_tag().
179 * We parse given format string and sort specifiers, and make a list
180 * of properties that we need to extract out of objects. ref_array_item
181 * structure will hold an array of values extracted that can be
182 * indexed with the "atom number", which is an index into this
183 * array.
185 static struct used_atom {
186 enum atom_type atom_type;
187 const char *name;
188 cmp_type type;
189 info_source source;
190 union {
191 char color[COLOR_MAXLEN];
192 struct align align;
193 struct {
194 enum {
195 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
196 } option;
197 struct refname_atom refname;
198 unsigned int nobracket : 1, push : 1, push_remote : 1;
199 } remote_ref;
200 struct {
201 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
202 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
203 struct process_trailer_options trailer_opts;
204 unsigned int nlines;
205 } contents;
206 struct {
207 enum { RAW_BARE, RAW_LENGTH } option;
208 } raw_data;
209 struct {
210 cmp_status cmp_status;
211 const char *str;
212 } if_then_else;
213 struct {
214 enum { O_FULL, O_LENGTH, O_SHORT } option;
215 unsigned int length;
216 } oid;
217 struct {
218 enum { O_SIZE, O_SIZE_DISK } option;
219 } objectsize;
220 struct {
221 enum { N_RAW, N_MAILMAP } option;
222 } name_option;
223 struct {
224 enum {
225 EO_RAW = 0,
226 EO_TRIM = 1<<0,
227 EO_LOCALPART = 1<<1,
228 EO_MAILMAP = 1<<2,
229 } option;
230 } email_option;
231 struct {
232 enum { S_BARE, S_GRADE, S_SIGNER, S_KEY,
233 S_FINGERPRINT, S_PRI_KEY_FP, S_TRUST_LEVEL } option;
234 } signature;
235 const char **describe_args;
236 struct refname_atom refname;
237 char *head;
238 } u;
239 } *used_atom;
240 static int used_atom_cnt, need_tagged, need_symref;
243 * Expand string, append it to strbuf *sb, then return error code ret.
244 * Allow to save few lines of code.
246 __attribute__((format (printf, 3, 4)))
247 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
249 va_list ap;
250 va_start(ap, fmt);
251 strbuf_vaddf(sb, fmt, ap);
252 va_end(ap);
253 return ret;
256 static int err_no_arg(struct strbuf *sb, const char *name)
258 size_t namelen = strchrnul(name, ':') - name;
259 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
260 (int)namelen, name);
261 return -1;
264 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
266 size_t namelen = strchrnul(name, ':') - name;
267 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
268 (int)namelen, name, arg);
269 return -1;
273 * Parse option of name "candidate" in the option string "to_parse" of
274 * the form
276 * "candidate1[=val1],candidate2[=val2],candidate3[=val3],..."
278 * The remaining part of "to_parse" is stored in "end" (if we are
279 * parsing the last candidate, then this is NULL) and the value of
280 * the candidate is stored in "valuestart" and its length in "valuelen",
281 * that is the portion after "=". Since it is possible for a "candidate"
282 * to not have a value, in such cases, "valuestart" is set to point to
283 * NULL and "valuelen" to 0.
285 * The function returns 1 on success. It returns 0 if we don't find
286 * "candidate" in "to_parse" or we find "candidate" but it is followed
287 * by more chars (for example, "candidatefoo"), that is, we don't find
288 * an exact match.
290 * This function only does the above for one "candidate" at a time. So
291 * it has to be called each time trying to parse a "candidate" in the
292 * option string "to_parse".
294 static int match_atom_arg_value(const char *to_parse, const char *candidate,
295 const char **end, const char **valuestart,
296 size_t *valuelen)
298 const char *atom;
300 if (!skip_prefix(to_parse, candidate, &atom))
301 return 0; /* definitely not "candidate" */
303 if (*atom == '=') {
304 /* we just saw "candidate=" */
305 *valuestart = atom + 1;
306 atom = strchrnul(*valuestart, ',');
307 *valuelen = atom - *valuestart;
308 } else if (*atom != ',' && *atom != '\0') {
309 /* key begins with "candidate" but has more chars */
310 return 0;
311 } else {
312 /* just "candidate" without "=val" */
313 *valuestart = NULL;
314 *valuelen = 0;
317 /* atom points at either the ',' or NUL after this key[=val] */
318 if (*atom == ',')
319 atom++;
320 else if (*atom)
321 BUG("Why is *atom not NULL yet?");
323 *end = atom;
324 return 1;
328 * Parse boolean option of name "candidate" in the option list "to_parse"
329 * of the form
331 * "candidate1[=bool1],candidate2[=bool2],candidate3[=bool3],..."
333 * The remaining part of "to_parse" is stored in "end" (if we are parsing
334 * the last candidate, then this is NULL) and the value (if given) is
335 * parsed and stored in "val", so "val" always points to either 0 or 1.
336 * If the value is not given, then "val" is set to point to 1.
338 * The boolean value is parsed using "git_parse_maybe_bool()", so the
339 * accepted values are
341 * to set true - "1", "yes", "true"
342 * to set false - "0", "no", "false"
344 * This function returns 1 on success. It returns 0 when we don't find
345 * an exact match for "candidate" or when the boolean value given is
346 * not valid.
348 static int match_atom_bool_arg(const char *to_parse, const char *candidate,
349 const char **end, int *val)
351 const char *argval;
352 char *strval;
353 size_t arglen;
354 int v;
356 if (!match_atom_arg_value(to_parse, candidate, end, &argval, &arglen))
357 return 0;
359 if (!argval) {
360 *val = 1;
361 return 1;
364 strval = xstrndup(argval, arglen);
365 v = git_parse_maybe_bool(strval);
366 free(strval);
368 if (v == -1)
369 return 0;
371 *val = v;
373 return 1;
376 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
377 const char *color_value, struct strbuf *err)
379 if (!color_value)
380 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
381 if (color_parse(color_value, atom->u.color) < 0)
382 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
383 color_value);
385 * We check this after we've parsed the color, which lets us complain
386 * about syntactically bogus color names even if they won't be used.
388 if (!want_color(format->use_color))
389 color_parse("", atom->u.color);
390 return 0;
393 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
394 const char *name, struct strbuf *err)
396 if (!arg)
397 atom->option = R_NORMAL;
398 else if (!strcmp(arg, "short"))
399 atom->option = R_SHORT;
400 else if (skip_prefix(arg, "lstrip=", &arg) ||
401 skip_prefix(arg, "strip=", &arg)) {
402 atom->option = R_LSTRIP;
403 if (strtol_i(arg, 10, &atom->lstrip))
404 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
405 } else if (skip_prefix(arg, "rstrip=", &arg)) {
406 atom->option = R_RSTRIP;
407 if (strtol_i(arg, 10, &atom->rstrip))
408 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
409 } else
410 return err_bad_arg(err, name, arg);
411 return 0;
414 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
415 struct used_atom *atom,
416 const char *arg, struct strbuf *err)
418 struct string_list params = STRING_LIST_INIT_DUP;
419 int i;
421 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
422 atom->u.remote_ref.push = 1;
424 if (!arg) {
425 atom->u.remote_ref.option = RR_REF;
426 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
427 arg, atom->name, err);
430 atom->u.remote_ref.nobracket = 0;
431 string_list_split(&params, arg, ',', -1);
433 for (i = 0; i < params.nr; i++) {
434 const char *s = params.items[i].string;
436 if (!strcmp(s, "track"))
437 atom->u.remote_ref.option = RR_TRACK;
438 else if (!strcmp(s, "trackshort"))
439 atom->u.remote_ref.option = RR_TRACKSHORT;
440 else if (!strcmp(s, "nobracket"))
441 atom->u.remote_ref.nobracket = 1;
442 else if (!strcmp(s, "remotename")) {
443 atom->u.remote_ref.option = RR_REMOTE_NAME;
444 atom->u.remote_ref.push_remote = 1;
445 } else if (!strcmp(s, "remoteref")) {
446 atom->u.remote_ref.option = RR_REMOTE_REF;
447 atom->u.remote_ref.push_remote = 1;
448 } else {
449 atom->u.remote_ref.option = RR_REF;
450 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
451 arg, atom->name, err)) {
452 string_list_clear(&params, 0);
453 return -1;
458 string_list_clear(&params, 0);
459 return 0;
462 static int objecttype_atom_parser(struct ref_format *format UNUSED,
463 struct used_atom *atom,
464 const char *arg, struct strbuf *err)
466 if (arg)
467 return err_no_arg(err, "objecttype");
468 if (*atom->name == '*')
469 oi_deref.info.typep = &oi_deref.type;
470 else
471 oi.info.typep = &oi.type;
472 return 0;
475 static int objectsize_atom_parser(struct ref_format *format UNUSED,
476 struct used_atom *atom,
477 const char *arg, struct strbuf *err)
479 if (!arg) {
480 atom->u.objectsize.option = O_SIZE;
481 if (*atom->name == '*')
482 oi_deref.info.sizep = &oi_deref.size;
483 else
484 oi.info.sizep = &oi.size;
485 } else if (!strcmp(arg, "disk")) {
486 atom->u.objectsize.option = O_SIZE_DISK;
487 if (*atom->name == '*')
488 oi_deref.info.disk_sizep = &oi_deref.disk_size;
489 else
490 oi.info.disk_sizep = &oi.disk_size;
491 } else
492 return err_bad_arg(err, "objectsize", arg);
493 return 0;
496 static int deltabase_atom_parser(struct ref_format *format UNUSED,
497 struct used_atom *atom,
498 const char *arg, struct strbuf *err)
500 if (arg)
501 return err_no_arg(err, "deltabase");
502 if (*atom->name == '*')
503 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
504 else
505 oi.info.delta_base_oid = &oi.delta_base_oid;
506 return 0;
509 static int body_atom_parser(struct ref_format *format UNUSED,
510 struct used_atom *atom,
511 const char *arg, struct strbuf *err)
513 if (arg)
514 return err_no_arg(err, "body");
515 atom->u.contents.option = C_BODY_DEP;
516 return 0;
519 static int subject_atom_parser(struct ref_format *format UNUSED,
520 struct used_atom *atom,
521 const char *arg, struct strbuf *err)
523 if (!arg)
524 atom->u.contents.option = C_SUB;
525 else if (!strcmp(arg, "sanitize"))
526 atom->u.contents.option = C_SUB_SANITIZE;
527 else
528 return err_bad_arg(err, "subject", arg);
529 return 0;
532 static int parse_signature_option(const char *arg)
534 if (!arg)
535 return S_BARE;
536 else if (!strcmp(arg, "signer"))
537 return S_SIGNER;
538 else if (!strcmp(arg, "grade"))
539 return S_GRADE;
540 else if (!strcmp(arg, "key"))
541 return S_KEY;
542 else if (!strcmp(arg, "fingerprint"))
543 return S_FINGERPRINT;
544 else if (!strcmp(arg, "primarykeyfingerprint"))
545 return S_PRI_KEY_FP;
546 else if (!strcmp(arg, "trustlevel"))
547 return S_TRUST_LEVEL;
548 return -1;
551 static int signature_atom_parser(struct ref_format *format UNUSED,
552 struct used_atom *atom,
553 const char *arg, struct strbuf *err)
555 int opt = parse_signature_option(arg);
556 if (opt < 0)
557 return err_bad_arg(err, "signature", arg);
558 atom->u.signature.option = opt;
559 return 0;
562 static int trailers_atom_parser(struct ref_format *format UNUSED,
563 struct used_atom *atom,
564 const char *arg, struct strbuf *err)
566 atom->u.contents.trailer_opts.no_divider = 1;
568 if (arg) {
569 const char *argbuf = xstrfmt("%s)", arg);
570 char *invalid_arg = NULL;
572 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
573 &ref_trailer_buf.filter_list,
574 &ref_trailer_buf.sepbuf,
575 &ref_trailer_buf.kvsepbuf,
576 &argbuf, &invalid_arg)) {
577 if (!invalid_arg)
578 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
579 else
580 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
581 free((char *)invalid_arg);
582 return -1;
585 atom->u.contents.option = C_TRAILERS;
586 return 0;
589 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
590 const char *arg, struct strbuf *err)
592 if (!arg)
593 atom->u.contents.option = C_BARE;
594 else if (!strcmp(arg, "body"))
595 atom->u.contents.option = C_BODY;
596 else if (!strcmp(arg, "size")) {
597 atom->type = FIELD_ULONG;
598 atom->u.contents.option = C_LENGTH;
599 } else if (!strcmp(arg, "signature"))
600 atom->u.contents.option = C_SIG;
601 else if (!strcmp(arg, "subject"))
602 atom->u.contents.option = C_SUB;
603 else if (!strcmp(arg, "trailers")) {
604 if (trailers_atom_parser(format, atom, NULL, err))
605 return -1;
606 } else if (skip_prefix(arg, "trailers:", &arg)) {
607 if (trailers_atom_parser(format, atom, arg, err))
608 return -1;
609 } else if (skip_prefix(arg, "lines=", &arg)) {
610 atom->u.contents.option = C_LINES;
611 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
612 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
613 } else
614 return err_bad_arg(err, "contents", arg);
615 return 0;
618 static int describe_atom_option_parser(struct strvec *args, const char **arg,
619 struct strbuf *err)
621 const char *argval;
622 size_t arglen = 0;
623 int optval = 0;
625 if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {
626 if (!optval)
627 strvec_push(args, "--no-tags");
628 else
629 strvec_push(args, "--tags");
630 return 1;
633 if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {
634 char *endptr;
636 if (!arglen)
637 return strbuf_addf_ret(err, -1,
638 _("argument expected for %s"),
639 "describe:abbrev");
640 if (strtol(argval, &endptr, 10) < 0)
641 return strbuf_addf_ret(err, -1,
642 _("positive value expected %s=%s"),
643 "describe:abbrev", argval);
644 if (endptr - argval != arglen)
645 return strbuf_addf_ret(err, -1,
646 _("cannot fully parse %s=%s"),
647 "describe:abbrev", argval);
649 strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);
650 return 1;
653 if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {
654 if (!arglen)
655 return strbuf_addf_ret(err, -1,
656 _("value expected %s="),
657 "describe:match");
659 strvec_pushf(args, "--match=%.*s", (int)arglen, argval);
660 return 1;
663 if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {
664 if (!arglen)
665 return strbuf_addf_ret(err, -1,
666 _("value expected %s="),
667 "describe:exclude");
669 strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);
670 return 1;
673 return 0;
676 static int describe_atom_parser(struct ref_format *format UNUSED,
677 struct used_atom *atom,
678 const char *arg, struct strbuf *err)
680 struct strvec args = STRVEC_INIT;
682 for (;;) {
683 int found = 0;
684 const char *bad_arg = arg;
686 if (!arg || !*arg)
687 break;
689 found = describe_atom_option_parser(&args, &arg, err);
690 if (found < 0)
691 return found;
692 if (!found)
693 return err_bad_arg(err, "describe", bad_arg);
695 atom->u.describe_args = strvec_detach(&args);
696 return 0;
699 static int raw_atom_parser(struct ref_format *format UNUSED,
700 struct used_atom *atom,
701 const char *arg, struct strbuf *err)
703 if (!arg)
704 atom->u.raw_data.option = RAW_BARE;
705 else if (!strcmp(arg, "size")) {
706 atom->type = FIELD_ULONG;
707 atom->u.raw_data.option = RAW_LENGTH;
708 } else
709 return err_bad_arg(err, "raw", arg);
710 return 0;
713 static int oid_atom_parser(struct ref_format *format UNUSED,
714 struct used_atom *atom,
715 const char *arg, struct strbuf *err)
717 if (!arg)
718 atom->u.oid.option = O_FULL;
719 else if (!strcmp(arg, "short"))
720 atom->u.oid.option = O_SHORT;
721 else if (skip_prefix(arg, "short=", &arg)) {
722 atom->u.oid.option = O_LENGTH;
723 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
724 atom->u.oid.length == 0)
725 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
726 if (atom->u.oid.length < MINIMUM_ABBREV)
727 atom->u.oid.length = MINIMUM_ABBREV;
728 } else
729 return err_bad_arg(err, atom->name, arg);
730 return 0;
733 static int person_name_atom_parser(struct ref_format *format UNUSED,
734 struct used_atom *atom,
735 const char *arg, struct strbuf *err)
737 if (!arg)
738 atom->u.name_option.option = N_RAW;
739 else if (!strcmp(arg, "mailmap"))
740 atom->u.name_option.option = N_MAILMAP;
741 else
742 return err_bad_arg(err, atom->name, arg);
743 return 0;
746 static int email_atom_option_parser(const char **arg)
748 if (!*arg)
749 return EO_RAW;
750 if (skip_prefix(*arg, "trim", arg))
751 return EO_TRIM;
752 if (skip_prefix(*arg, "localpart", arg))
753 return EO_LOCALPART;
754 if (skip_prefix(*arg, "mailmap", arg))
755 return EO_MAILMAP;
756 return -1;
759 static int person_email_atom_parser(struct ref_format *format UNUSED,
760 struct used_atom *atom,
761 const char *arg, struct strbuf *err)
763 for (;;) {
764 int opt = email_atom_option_parser(&arg);
765 const char *bad_arg = arg;
767 if (opt < 0)
768 return err_bad_arg(err, atom->name, bad_arg);
769 atom->u.email_option.option |= opt;
771 if (!arg || !*arg)
772 break;
773 if (*arg == ',')
774 arg++;
775 else
776 return err_bad_arg(err, atom->name, bad_arg);
778 return 0;
781 static int refname_atom_parser(struct ref_format *format UNUSED,
782 struct used_atom *atom,
783 const char *arg, struct strbuf *err)
785 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
788 static align_type parse_align_position(const char *s)
790 if (!strcmp(s, "right"))
791 return ALIGN_RIGHT;
792 else if (!strcmp(s, "middle"))
793 return ALIGN_MIDDLE;
794 else if (!strcmp(s, "left"))
795 return ALIGN_LEFT;
796 return -1;
799 static int align_atom_parser(struct ref_format *format UNUSED,
800 struct used_atom *atom,
801 const char *arg, struct strbuf *err)
803 struct align *align = &atom->u.align;
804 struct string_list params = STRING_LIST_INIT_DUP;
805 int i;
806 unsigned int width = ~0U;
808 if (!arg)
809 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
811 align->position = ALIGN_LEFT;
813 string_list_split(&params, arg, ',', -1);
814 for (i = 0; i < params.nr; i++) {
815 const char *s = params.items[i].string;
816 int position;
818 if (skip_prefix(s, "position=", &s)) {
819 position = parse_align_position(s);
820 if (position < 0) {
821 strbuf_addf(err, _("unrecognized position:%s"), s);
822 string_list_clear(&params, 0);
823 return -1;
825 align->position = position;
826 } else if (skip_prefix(s, "width=", &s)) {
827 if (strtoul_ui(s, 10, &width)) {
828 strbuf_addf(err, _("unrecognized width:%s"), s);
829 string_list_clear(&params, 0);
830 return -1;
832 } else if (!strtoul_ui(s, 10, &width))
834 else if ((position = parse_align_position(s)) >= 0)
835 align->position = position;
836 else {
837 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
838 string_list_clear(&params, 0);
839 return -1;
843 if (width == ~0U) {
844 string_list_clear(&params, 0);
845 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
847 align->width = width;
848 string_list_clear(&params, 0);
849 return 0;
852 static int if_atom_parser(struct ref_format *format UNUSED,
853 struct used_atom *atom,
854 const char *arg, struct strbuf *err)
856 if (!arg) {
857 atom->u.if_then_else.cmp_status = COMPARE_NONE;
858 return 0;
859 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
860 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
861 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
862 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
863 } else
864 return err_bad_arg(err, "if", arg);
865 return 0;
868 static int rest_atom_parser(struct ref_format *format UNUSED,
869 struct used_atom *atom UNUSED,
870 const char *arg, struct strbuf *err)
872 if (arg)
873 return err_no_arg(err, "rest");
874 return 0;
877 static int ahead_behind_atom_parser(struct ref_format *format,
878 struct used_atom *atom UNUSED,
879 const char *arg, struct strbuf *err)
881 struct string_list_item *item;
883 if (!arg)
884 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
886 item = string_list_append(&format->bases, arg);
887 item->util = lookup_commit_reference_by_name(arg);
888 if (!item->util)
889 die("failed to find '%s'", arg);
891 return 0;
894 static int is_base_atom_parser(struct ref_format *format,
895 struct used_atom *atom UNUSED,
896 const char *arg, struct strbuf *err)
898 struct string_list_item *item;
900 if (!arg)
901 return strbuf_addf_ret(err, -1, _("expected format: %%(is-base:<committish>)"));
903 item = string_list_append(&format->is_base_tips, arg);
904 item->util = lookup_commit_reference_by_name(arg);
905 if (!item->util)
906 die("failed to find '%s'", arg);
908 return 0;
911 static int head_atom_parser(struct ref_format *format UNUSED,
912 struct used_atom *atom,
913 const char *arg, struct strbuf *err)
915 if (arg)
916 return err_no_arg(err, "HEAD");
917 atom->u.head = refs_resolve_refdup(get_main_ref_store(the_repository),
918 "HEAD", RESOLVE_REF_READING, NULL,
919 NULL);
920 return 0;
923 static struct {
924 const char *name;
925 info_source source;
926 cmp_type cmp_type;
927 int (*parser)(struct ref_format *format, struct used_atom *atom,
928 const char *arg, struct strbuf *err);
929 } valid_atom[] = {
930 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
931 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
932 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
933 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
934 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
935 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
936 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
937 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
938 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
939 [ATOM_TYPE] = { "type", SOURCE_OBJ },
940 [ATOM_TAG] = { "tag", SOURCE_OBJ },
941 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
942 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
943 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
944 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
945 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
946 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
947 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
948 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
949 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
950 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
951 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
952 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
953 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
954 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
955 [ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },
956 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
957 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
958 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
959 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
960 [ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },
961 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
962 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
963 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
964 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
965 [ATOM_FLAG] = { "flag", SOURCE_NONE },
966 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
967 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
968 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
969 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
970 [ATOM_END] = { "end", SOURCE_NONE },
971 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
972 [ATOM_THEN] = { "then", SOURCE_NONE },
973 [ATOM_ELSE] = { "else", SOURCE_NONE },
974 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
975 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
976 [ATOM_ISBASE] = { "is-base", SOURCE_OTHER, FIELD_STR, is_base_atom_parser },
978 * Please update $__git_ref_fieldlist in git-completion.bash
979 * when you add new atoms
983 #define REF_FORMATTING_STATE_INIT { 0 }
985 struct ref_formatting_stack {
986 struct ref_formatting_stack *prev;
987 struct strbuf output;
988 void (*at_end)(struct ref_formatting_stack **stack);
989 void *at_end_data;
992 struct ref_formatting_state {
993 int quote_style;
994 struct ref_formatting_stack *stack;
997 struct atom_value {
998 const char *s;
999 ssize_t s_size;
1000 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
1001 struct strbuf *err);
1002 uintmax_t value; /* used for sorting when not FIELD_STR */
1003 struct used_atom *atom;
1006 #define ATOM_SIZE_UNSPECIFIED (-1)
1008 #define ATOM_VALUE_INIT { \
1009 .s_size = ATOM_SIZE_UNSPECIFIED \
1013 * Used to parse format string and sort specifiers
1015 static int parse_ref_filter_atom(struct ref_format *format,
1016 const char *atom, const char *ep,
1017 struct strbuf *err)
1019 const char *sp;
1020 const char *arg;
1021 int i, at, atom_len;
1023 sp = atom;
1024 if (*sp == '*' && sp < ep)
1025 sp++; /* deref */
1026 if (ep <= sp)
1027 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
1028 (int)(ep-atom), atom);
1031 * If the atom name has a colon, strip it and everything after
1032 * it off - it specifies the format for this entry, and
1033 * shouldn't be used for checking against the valid_atom
1034 * table.
1036 arg = memchr(sp, ':', ep - sp);
1037 atom_len = (arg ? arg : ep) - sp;
1039 /* Do we have the atom already used elsewhere? */
1040 for (i = 0; i < used_atom_cnt; i++) {
1041 int len = strlen(used_atom[i].name);
1042 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
1043 return i;
1046 /* Is the atom a valid one? */
1047 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
1048 int len = strlen(valid_atom[i].name);
1049 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
1050 break;
1053 if (ARRAY_SIZE(valid_atom) <= i)
1054 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
1055 (int)(ep-atom), atom);
1056 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
1057 return strbuf_addf_ret(err, -1,
1058 _("not a git repository, but the field '%.*s' requires access to object data"),
1059 (int)(ep-atom), atom);
1061 /* Add it in, including the deref prefix */
1062 at = used_atom_cnt;
1063 used_atom_cnt++;
1064 REALLOC_ARRAY(used_atom, used_atom_cnt);
1065 used_atom[at].atom_type = i;
1066 used_atom[at].name = xmemdupz(atom, ep - atom);
1067 used_atom[at].type = valid_atom[i].cmp_type;
1068 used_atom[at].source = valid_atom[i].source;
1069 if (used_atom[at].source == SOURCE_OBJ) {
1070 if (*atom == '*')
1071 oi_deref.info.contentp = &oi_deref.content;
1072 else
1073 oi.info.contentp = &oi.content;
1075 if (arg) {
1076 arg = used_atom[at].name + (arg - atom) + 1;
1077 if (!*arg) {
1079 * Treat empty sub-arguments list as NULL (i.e.,
1080 * "%(atom:)" is equivalent to "%(atom)").
1082 arg = NULL;
1085 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
1086 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
1087 return -1;
1088 if (*atom == '*')
1089 need_tagged = 1;
1090 if (i == ATOM_SYMREF)
1091 need_symref = 1;
1092 return at;
1095 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
1097 switch (quote_style) {
1098 case QUOTE_NONE:
1099 if (len < 0)
1100 strbuf_addstr(s, str);
1101 else
1102 strbuf_add(s, str, len);
1103 break;
1104 case QUOTE_SHELL:
1105 sq_quote_buf(s, str);
1106 break;
1107 case QUOTE_PERL:
1108 if (len < 0)
1109 perl_quote_buf(s, str);
1110 else
1111 perl_quote_buf_with_len(s, str, len);
1112 break;
1113 case QUOTE_PYTHON:
1114 python_quote_buf(s, str);
1115 break;
1116 case QUOTE_TCL:
1117 tcl_quote_buf(s, str);
1118 break;
1122 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
1123 struct strbuf *err UNUSED)
1126 * Quote formatting is only done when the stack has a single
1127 * element. Otherwise quote formatting is done on the
1128 * element's entire output strbuf when the %(end) atom is
1129 * encountered.
1131 if (!state->stack->prev)
1132 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
1133 else if (v->s_size < 0)
1134 strbuf_addstr(&state->stack->output, v->s);
1135 else
1136 strbuf_add(&state->stack->output, v->s, v->s_size);
1137 return 0;
1140 static void push_stack_element(struct ref_formatting_stack **stack)
1142 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
1144 strbuf_init(&s->output, 0);
1145 s->prev = *stack;
1146 *stack = s;
1149 static void pop_stack_element(struct ref_formatting_stack **stack)
1151 struct ref_formatting_stack *current = *stack;
1152 struct ref_formatting_stack *prev = current->prev;
1154 if (prev)
1155 strbuf_addbuf(&prev->output, &current->output);
1156 strbuf_release(&current->output);
1157 free(current);
1158 *stack = prev;
1161 static void end_align_handler(struct ref_formatting_stack **stack)
1163 struct ref_formatting_stack *cur = *stack;
1164 struct align *align = (struct align *)cur->at_end_data;
1165 struct strbuf s = STRBUF_INIT;
1167 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
1168 strbuf_swap(&cur->output, &s);
1169 strbuf_release(&s);
1172 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1173 struct strbuf *err UNUSED)
1175 struct ref_formatting_stack *new_stack;
1177 push_stack_element(&state->stack);
1178 new_stack = state->stack;
1179 new_stack->at_end = end_align_handler;
1180 new_stack->at_end_data = &atomv->atom->u.align;
1181 return 0;
1184 static void if_then_else_handler(struct ref_formatting_stack **stack)
1186 struct ref_formatting_stack *cur = *stack;
1187 struct ref_formatting_stack *prev = cur->prev;
1188 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
1190 if (!if_then_else->then_atom_seen)
1191 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
1193 if (if_then_else->else_atom_seen) {
1195 * There is an %(else) atom: we need to drop one state from the
1196 * stack, either the %(else) branch if the condition is satisfied, or
1197 * the %(then) branch if it isn't.
1199 if (if_then_else->condition_satisfied) {
1200 strbuf_reset(&cur->output);
1201 pop_stack_element(&cur);
1202 } else {
1203 strbuf_swap(&cur->output, &prev->output);
1204 strbuf_reset(&cur->output);
1205 pop_stack_element(&cur);
1207 } else if (!if_then_else->condition_satisfied) {
1209 * No %(else) atom: just drop the %(then) branch if the
1210 * condition is not satisfied.
1212 strbuf_reset(&cur->output);
1215 *stack = cur;
1216 free(if_then_else);
1219 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1220 struct strbuf *err UNUSED)
1222 struct ref_formatting_stack *new_stack;
1223 struct if_then_else *if_then_else = xcalloc(1,
1224 sizeof(struct if_then_else));
1226 if_then_else->str = atomv->atom->u.if_then_else.str;
1227 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
1229 push_stack_element(&state->stack);
1230 new_stack = state->stack;
1231 new_stack->at_end = if_then_else_handler;
1232 new_stack->at_end_data = if_then_else;
1233 return 0;
1236 static int is_empty(struct strbuf *buf)
1238 const char *cur = buf->buf;
1239 const char *end = buf->buf + buf->len;
1241 while (cur != end && (isspace(*cur)))
1242 cur++;
1244 return cur == end;
1247 static int then_atom_handler(struct atom_value *atomv UNUSED,
1248 struct ref_formatting_state *state,
1249 struct strbuf *err)
1251 struct ref_formatting_stack *cur = state->stack;
1252 struct if_then_else *if_then_else = NULL;
1253 size_t str_len = 0;
1255 if (cur->at_end == if_then_else_handler)
1256 if_then_else = (struct if_then_else *)cur->at_end_data;
1257 if (!if_then_else)
1258 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
1259 if (if_then_else->then_atom_seen)
1260 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
1261 if (if_then_else->else_atom_seen)
1262 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
1263 if_then_else->then_atom_seen = 1;
1264 if (if_then_else->str)
1265 str_len = strlen(if_then_else->str);
1267 * If the 'equals' or 'notequals' attribute is used then
1268 * perform the required comparison. If not, only non-empty
1269 * strings satisfy the 'if' condition.
1271 if (if_then_else->cmp_status == COMPARE_EQUAL) {
1272 if (str_len == cur->output.len &&
1273 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1274 if_then_else->condition_satisfied = 1;
1275 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
1276 if (str_len != cur->output.len ||
1277 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1278 if_then_else->condition_satisfied = 1;
1279 } else if (cur->output.len && !is_empty(&cur->output))
1280 if_then_else->condition_satisfied = 1;
1281 strbuf_reset(&cur->output);
1282 return 0;
1285 static int else_atom_handler(struct atom_value *atomv UNUSED,
1286 struct ref_formatting_state *state,
1287 struct strbuf *err)
1289 struct ref_formatting_stack *prev = state->stack;
1290 struct if_then_else *if_then_else = NULL;
1292 if (prev->at_end == if_then_else_handler)
1293 if_then_else = (struct if_then_else *)prev->at_end_data;
1294 if (!if_then_else)
1295 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1296 if (!if_then_else->then_atom_seen)
1297 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1298 if (if_then_else->else_atom_seen)
1299 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1300 if_then_else->else_atom_seen = 1;
1301 push_stack_element(&state->stack);
1302 state->stack->at_end_data = prev->at_end_data;
1303 state->stack->at_end = prev->at_end;
1304 return 0;
1307 static int end_atom_handler(struct atom_value *atomv UNUSED,
1308 struct ref_formatting_state *state,
1309 struct strbuf *err)
1311 struct ref_formatting_stack *current = state->stack;
1312 struct strbuf s = STRBUF_INIT;
1314 if (!current->at_end)
1315 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1316 current->at_end(&state->stack);
1318 /* Stack may have been popped within at_end(), hence reset the current pointer */
1319 current = state->stack;
1322 * Perform quote formatting when the stack element is that of
1323 * a supporting atom. If nested then perform quote formatting
1324 * only on the topmost supporting atom.
1326 if (!current->prev->prev) {
1327 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1328 strbuf_swap(&current->output, &s);
1330 strbuf_release(&s);
1331 pop_stack_element(&state->stack);
1332 return 0;
1336 * In a format string, find the next occurrence of %(atom).
1338 static const char *find_next(const char *cp)
1340 while (*cp) {
1341 if (*cp == '%') {
1343 * %( is the start of an atom;
1344 * %% is a quoted per-cent.
1346 if (cp[1] == '(')
1347 return cp;
1348 else if (cp[1] == '%')
1349 cp++; /* skip over two % */
1350 /* otherwise this is a singleton, literal % */
1352 cp++;
1354 return NULL;
1357 static int reject_atom(enum atom_type atom_type)
1359 return atom_type == ATOM_REST;
1363 * Make sure the format string is well formed, and parse out
1364 * the used atoms.
1366 int verify_ref_format(struct ref_format *format)
1368 const char *cp, *sp;
1370 format->need_color_reset_at_eol = 0;
1371 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1372 struct strbuf err = STRBUF_INIT;
1373 const char *color, *ep = strchr(sp, ')');
1374 int at;
1376 if (!ep)
1377 return error(_("malformed format string %s"), sp);
1378 /* sp points at "%(" and ep points at the closing ")" */
1379 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1380 if (at < 0)
1381 die("%s", err.buf);
1382 if (reject_atom(used_atom[at].atom_type))
1383 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1385 if ((format->quote_style == QUOTE_PYTHON ||
1386 format->quote_style == QUOTE_SHELL ||
1387 format->quote_style == QUOTE_TCL) &&
1388 used_atom[at].atom_type == ATOM_RAW &&
1389 used_atom[at].u.raw_data.option == RAW_BARE)
1390 die(_("--format=%.*s cannot be used with "
1391 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1392 cp = ep + 1;
1394 if (skip_prefix(used_atom[at].name, "color:", &color))
1395 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1396 strbuf_release(&err);
1398 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1399 format->need_color_reset_at_eol = 0;
1400 return 0;
1403 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1404 struct used_atom *atom)
1406 switch (atom->u.oid.option) {
1407 case O_FULL:
1408 return oid_to_hex(oid);
1409 case O_LENGTH:
1410 return repo_find_unique_abbrev(the_repository, oid,
1411 atom->u.oid.length);
1412 case O_SHORT:
1413 return repo_find_unique_abbrev(the_repository, oid,
1414 DEFAULT_ABBREV);
1415 default:
1416 BUG("unknown %%(%s) option", field);
1420 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1421 struct atom_value *v, struct used_atom *atom)
1423 if (starts_with(name, field)) {
1424 v->s = xstrdup(do_grab_oid(field, oid, atom));
1425 return 1;
1427 return 0;
1430 /* See grab_values */
1431 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1433 int i;
1435 for (i = 0; i < used_atom_cnt; i++) {
1436 const char *name = used_atom[i].name;
1437 enum atom_type atom_type = used_atom[i].atom_type;
1438 struct atom_value *v = &val[i];
1439 if (!!deref != (*name == '*'))
1440 continue;
1441 if (deref)
1442 name++;
1443 if (atom_type == ATOM_OBJECTTYPE)
1444 v->s = xstrdup(type_name(oi->type));
1445 else if (atom_type == ATOM_OBJECTSIZE) {
1446 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1447 v->value = oi->disk_size;
1448 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1449 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1450 v->value = oi->size;
1451 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1453 } else if (atom_type == ATOM_DELTABASE)
1454 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1455 else if (atom_type == ATOM_OBJECTNAME && deref)
1456 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1460 /* See grab_values */
1461 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1463 int i;
1464 struct tag *tag = (struct tag *) obj;
1466 for (i = 0; i < used_atom_cnt; i++) {
1467 const char *name = used_atom[i].name;
1468 enum atom_type atom_type = used_atom[i].atom_type;
1469 struct atom_value *v = &val[i];
1470 if (!!deref != (*name == '*'))
1471 continue;
1472 if (deref)
1473 name++;
1474 if (atom_type == ATOM_TAG)
1475 v->s = xstrdup(tag->tag);
1476 else if (atom_type == ATOM_TYPE && tag->tagged)
1477 v->s = xstrdup(type_name(tag->tagged->type));
1478 else if (atom_type == ATOM_OBJECT && tag->tagged)
1479 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1483 /* See grab_values */
1484 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1486 int i;
1487 struct commit *commit = (struct commit *) obj;
1489 for (i = 0; i < used_atom_cnt; i++) {
1490 const char *name = used_atom[i].name;
1491 enum atom_type atom_type = used_atom[i].atom_type;
1492 struct atom_value *v = &val[i];
1493 if (!!deref != (*name == '*'))
1494 continue;
1495 if (deref)
1496 name++;
1497 if (atom_type == ATOM_TREE &&
1498 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1499 continue;
1500 if (atom_type == ATOM_NUMPARENT) {
1501 v->value = commit_list_count(commit->parents);
1502 v->s = xstrfmt("%lu", (unsigned long)v->value);
1504 else if (atom_type == ATOM_PARENT) {
1505 struct commit_list *parents;
1506 struct strbuf s = STRBUF_INIT;
1507 for (parents = commit->parents; parents; parents = parents->next) {
1508 struct object_id *oid = &parents->item->object.oid;
1509 if (parents != commit->parents)
1510 strbuf_addch(&s, ' ');
1511 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1513 v->s = strbuf_detach(&s, NULL);
1518 static const char *find_wholine(const char *who, int wholen, const char *buf)
1520 const char *eol;
1521 while (*buf) {
1522 if (!strncmp(buf, who, wholen) &&
1523 buf[wholen] == ' ')
1524 return buf + wholen + 1;
1525 eol = strchr(buf, '\n');
1526 if (!eol)
1527 return "";
1528 eol++;
1529 if (*eol == '\n')
1530 return ""; /* end of header */
1531 buf = eol;
1533 return "";
1536 static const char *copy_line(const char *buf)
1538 const char *eol = strchrnul(buf, '\n');
1539 return xmemdupz(buf, eol - buf);
1542 static const char *copy_name(const char *buf)
1544 const char *cp;
1545 for (cp = buf; *cp && *cp != '\n'; cp++) {
1546 if (starts_with(cp, " <"))
1547 return xmemdupz(buf, cp - buf);
1549 return xstrdup("");
1552 static const char *find_end_of_email(const char *email, int opt)
1554 const char *eoemail;
1556 if (opt & EO_LOCALPART) {
1557 eoemail = strchr(email, '@');
1558 if (eoemail)
1559 return eoemail;
1560 return strchr(email, '>');
1563 if (opt & EO_TRIM)
1564 return strchr(email, '>');
1567 * The option here is either the raw email option or the raw
1568 * mailmap option (that is EO_RAW or EO_MAILMAP). In such cases,
1569 * we directly grab the whole email including the closing
1570 * angle brackets.
1572 * If EO_MAILMAP was set with any other option (that is either
1573 * EO_TRIM or EO_LOCALPART), we already grab the end of email
1574 * above.
1576 eoemail = strchr(email, '>');
1577 if (eoemail)
1578 eoemail++;
1579 return eoemail;
1582 static const char *copy_email(const char *buf, struct used_atom *atom)
1584 const char *email = strchr(buf, '<');
1585 const char *eoemail;
1586 int opt = atom->u.email_option.option;
1588 if (!email)
1589 return xstrdup("");
1591 if (opt & (EO_LOCALPART | EO_TRIM))
1592 email++;
1594 eoemail = find_end_of_email(email, opt);
1595 if (!eoemail)
1596 return xstrdup("");
1597 return xmemdupz(email, eoemail - email);
1600 static char *copy_subject(const char *buf, unsigned long len)
1602 struct strbuf sb = STRBUF_INIT;
1603 int i;
1605 for (i = 0; i < len; i++) {
1606 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1607 continue; /* ignore CR in CRLF */
1609 if (buf[i] == '\n')
1610 strbuf_addch(&sb, ' ');
1611 else
1612 strbuf_addch(&sb, buf[i]);
1614 return strbuf_detach(&sb, NULL);
1617 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1619 const char *eoemail = strstr(buf, "> ");
1620 char *zone;
1621 timestamp_t timestamp;
1622 long tz;
1623 struct date_mode date_mode = DATE_MODE_INIT;
1624 const char *formatp;
1627 * We got here because atomname ends in "date" or "date<something>";
1628 * it's not possible that <something> is not ":<format>" because
1629 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1630 * ":" means no format is specified, and use the default.
1632 formatp = strchr(atomname, ':');
1633 if (formatp) {
1634 formatp++;
1635 parse_date_format(formatp, &date_mode);
1638 * If this is a sort field and a format was specified, we'll
1639 * want to compare formatted date by string value.
1641 v->atom->type = FIELD_STR;
1644 if (!eoemail)
1645 goto bad;
1646 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1647 if (timestamp == TIME_MAX)
1648 goto bad;
1649 errno = 0;
1650 tz = strtol(zone, NULL, 10);
1651 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1652 goto bad;
1653 v->s = xstrdup(show_date(timestamp, tz, date_mode));
1654 v->value = timestamp;
1655 date_mode_release(&date_mode);
1656 return;
1657 bad:
1658 v->s = xstrdup("");
1659 v->value = 0;
1662 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
1664 /* See grab_values */
1665 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1667 int i;
1668 int wholen = strlen(who);
1669 const char *wholine = NULL;
1670 const char *headers[] = { "author ", "committer ",
1671 "tagger ", NULL };
1673 for (i = 0; i < used_atom_cnt; i++) {
1674 struct used_atom *atom = &used_atom[i];
1675 const char *name = atom->name;
1676 struct atom_value *v = &val[i];
1677 struct strbuf mailmap_buf = STRBUF_INIT;
1679 if (!!deref != (*name == '*'))
1680 continue;
1681 if (deref)
1682 name++;
1683 if (strncmp(who, name, wholen))
1684 continue;
1685 if (name[wholen] != 0 &&
1686 !starts_with(name + wholen, "name") &&
1687 !starts_with(name + wholen, "email") &&
1688 !starts_with(name + wholen, "date"))
1689 continue;
1691 if ((starts_with(name + wholen, "name") &&
1692 (atom->u.name_option.option == N_MAILMAP)) ||
1693 (starts_with(name + wholen, "email") &&
1694 (atom->u.email_option.option & EO_MAILMAP))) {
1695 if (!mailmap.items)
1696 read_mailmap(&mailmap);
1697 strbuf_addstr(&mailmap_buf, buf);
1698 apply_mailmap_to_header(&mailmap_buf, headers, &mailmap);
1699 wholine = find_wholine(who, wholen, mailmap_buf.buf);
1700 } else {
1701 wholine = find_wholine(who, wholen, buf);
1704 if (!wholine)
1705 return; /* no point looking for it */
1706 if (name[wholen] == 0)
1707 v->s = copy_line(wholine);
1708 else if (starts_with(name + wholen, "name"))
1709 v->s = copy_name(wholine);
1710 else if (starts_with(name + wholen, "email"))
1711 v->s = copy_email(wholine, &used_atom[i]);
1712 else if (starts_with(name + wholen, "date"))
1713 grab_date(wholine, v, name);
1715 strbuf_release(&mailmap_buf);
1719 * For a tag or a commit object, if "creator" or "creatordate" is
1720 * requested, do something special.
1722 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1723 return; /* "author" for commit object is not wanted */
1724 if (!wholine)
1725 wholine = find_wholine(who, wholen, buf);
1726 if (!wholine)
1727 return;
1728 for (i = 0; i < used_atom_cnt; i++) {
1729 const char *name = used_atom[i].name;
1730 enum atom_type atom_type = used_atom[i].atom_type;
1731 struct atom_value *v = &val[i];
1732 if (!!deref != (*name == '*'))
1733 continue;
1734 if (deref)
1735 name++;
1737 if (atom_type == ATOM_CREATORDATE)
1738 grab_date(wholine, v, name);
1739 else if (atom_type == ATOM_CREATOR)
1740 v->s = copy_line(wholine);
1744 static void grab_signature(struct atom_value *val, int deref, struct object *obj)
1746 int i;
1747 struct commit *commit = (struct commit *) obj;
1748 struct signature_check sigc = { 0 };
1749 int signature_checked = 0;
1751 for (i = 0; i < used_atom_cnt; i++) {
1752 struct used_atom *atom = &used_atom[i];
1753 const char *name = atom->name;
1754 struct atom_value *v = &val[i];
1755 int opt;
1757 if (!!deref != (*name == '*'))
1758 continue;
1759 if (deref)
1760 name++;
1762 if (!skip_prefix(name, "signature", &name) ||
1763 (*name && *name != ':'))
1764 continue;
1765 if (!*name)
1766 name = NULL;
1767 else
1768 name++;
1770 opt = parse_signature_option(name);
1771 if (opt < 0)
1772 continue;
1774 if (!signature_checked) {
1775 check_commit_signature(commit, &sigc);
1776 signature_checked = 1;
1779 switch (opt) {
1780 case S_BARE:
1781 v->s = xstrdup(sigc.output ? sigc.output: "");
1782 break;
1783 case S_SIGNER:
1784 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1785 break;
1786 case S_GRADE:
1787 switch (sigc.result) {
1788 case 'G':
1789 switch (sigc.trust_level) {
1790 case TRUST_UNDEFINED:
1791 case TRUST_NEVER:
1792 v->s = xstrfmt("%c", (char)'U');
1793 break;
1794 default:
1795 v->s = xstrfmt("%c", (char)'G');
1796 break;
1798 break;
1799 case 'B':
1800 case 'E':
1801 case 'N':
1802 case 'X':
1803 case 'Y':
1804 case 'R':
1805 v->s = xstrfmt("%c", (char)sigc.result);
1806 break;
1808 break;
1809 case S_KEY:
1810 v->s = xstrdup(sigc.key ? sigc.key : "");
1811 break;
1812 case S_FINGERPRINT:
1813 v->s = xstrdup(sigc.fingerprint ?
1814 sigc.fingerprint : "");
1815 break;
1816 case S_PRI_KEY_FP:
1817 v->s = xstrdup(sigc.primary_key_fingerprint ?
1818 sigc.primary_key_fingerprint : "");
1819 break;
1820 case S_TRUST_LEVEL:
1821 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1822 break;
1826 if (signature_checked)
1827 signature_check_clear(&sigc);
1830 static void find_subpos(const char *buf,
1831 const char **sub, size_t *sublen,
1832 const char **body, size_t *bodylen,
1833 size_t *nonsiglen,
1834 const char **sig, size_t *siglen)
1836 struct strbuf payload = STRBUF_INIT;
1837 struct strbuf signature = STRBUF_INIT;
1838 const char *eol;
1839 const char *end = buf + strlen(buf);
1840 const char *sigstart;
1842 /* parse signature first; we might not even have a subject line */
1843 parse_signature(buf, end - buf, &payload, &signature);
1844 strbuf_release(&payload);
1846 /* skip past header until we hit empty line */
1847 while (*buf && *buf != '\n') {
1848 eol = strchrnul(buf, '\n');
1849 if (*eol)
1850 eol++;
1851 buf = eol;
1853 /* skip any empty lines */
1854 while (*buf == '\n')
1855 buf++;
1856 *sig = strbuf_detach(&signature, siglen);
1857 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1859 /* subject is first non-empty line */
1860 *sub = buf;
1861 /* subject goes to first empty line before signature begins */
1862 if ((eol = strstr(*sub, "\n\n")) ||
1863 (eol = strstr(*sub, "\r\n\r\n"))) {
1864 eol = eol < sigstart ? eol : sigstart;
1865 } else {
1866 /* treat whole message as subject */
1867 eol = sigstart;
1869 buf = eol;
1870 *sublen = buf - *sub;
1871 /* drop trailing newline, if present */
1872 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1873 (*sub)[*sublen - 1] == '\r'))
1874 *sublen -= 1;
1876 /* skip any empty lines */
1877 while (*buf == '\n' || *buf == '\r')
1878 buf++;
1879 *body = buf;
1880 *bodylen = strlen(buf);
1881 *nonsiglen = sigstart - buf;
1885 * If 'lines' is greater than 0, append that many lines from the given
1886 * 'buf' of length 'size' to the given strbuf.
1888 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1890 int i;
1891 const char *sp, *eol;
1892 size_t len;
1894 sp = buf;
1896 for (i = 0; i < lines && sp < buf + size; i++) {
1897 if (i)
1898 strbuf_addstr(out, "\n ");
1899 eol = memchr(sp, '\n', size - (sp - buf));
1900 len = eol ? eol - sp : size - (sp - buf);
1901 strbuf_add(out, sp, len);
1902 if (!eol)
1903 break;
1904 sp = eol + 1;
1908 static void grab_describe_values(struct atom_value *val, int deref,
1909 struct object *obj)
1911 struct commit *commit = (struct commit *)obj;
1912 int i;
1914 for (i = 0; i < used_atom_cnt; i++) {
1915 struct used_atom *atom = &used_atom[i];
1916 enum atom_type type = atom->atom_type;
1917 const char *name = atom->name;
1918 struct atom_value *v = &val[i];
1920 struct child_process cmd = CHILD_PROCESS_INIT;
1921 struct strbuf out = STRBUF_INIT;
1922 struct strbuf err = STRBUF_INIT;
1924 if (type != ATOM_DESCRIBE)
1925 continue;
1927 if (!!deref != (*name == '*'))
1928 continue;
1930 cmd.git_cmd = 1;
1931 strvec_push(&cmd.args, "describe");
1932 strvec_pushv(&cmd.args, atom->u.describe_args);
1933 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1934 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
1935 error(_("failed to run 'describe'"));
1936 v->s = xstrdup("");
1937 continue;
1939 strbuf_rtrim(&out);
1940 v->s = strbuf_detach(&out, NULL);
1942 strbuf_release(&err);
1946 /* See grab_values */
1947 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1949 int i;
1950 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1951 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1952 void *buf = data->content;
1954 for (i = 0; i < used_atom_cnt; i++) {
1955 struct used_atom *atom = &used_atom[i];
1956 const char *name = atom->name;
1957 struct atom_value *v = &val[i];
1958 enum atom_type atom_type = atom->atom_type;
1960 if (!!deref != (*name == '*'))
1961 continue;
1962 if (deref)
1963 name++;
1965 if (atom_type == ATOM_RAW) {
1966 unsigned long buf_size = data->size;
1968 if (atom->u.raw_data.option == RAW_BARE) {
1969 v->s = xmemdupz(buf, buf_size);
1970 v->s_size = buf_size;
1971 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1972 v->value = buf_size;
1973 v->s = xstrfmt("%"PRIuMAX, v->value);
1975 continue;
1978 if ((data->type != OBJ_TAG &&
1979 data->type != OBJ_COMMIT) ||
1980 (strcmp(name, "body") &&
1981 !starts_with(name, "subject") &&
1982 !starts_with(name, "trailers") &&
1983 !starts_with(name, "contents")))
1984 continue;
1985 if (!subpos)
1986 find_subpos(buf,
1987 &subpos, &sublen,
1988 &bodypos, &bodylen, &nonsiglen,
1989 &sigpos, &siglen);
1991 if (atom->u.contents.option == C_SUB)
1992 v->s = copy_subject(subpos, sublen);
1993 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1994 struct strbuf sb = STRBUF_INIT;
1995 format_sanitized_subject(&sb, subpos, sublen);
1996 v->s = strbuf_detach(&sb, NULL);
1997 } else if (atom->u.contents.option == C_BODY_DEP)
1998 v->s = xmemdupz(bodypos, bodylen);
1999 else if (atom->u.contents.option == C_LENGTH) {
2000 v->value = strlen(subpos);
2001 v->s = xstrfmt("%"PRIuMAX, v->value);
2002 } else if (atom->u.contents.option == C_BODY)
2003 v->s = xmemdupz(bodypos, nonsiglen);
2004 else if (atom->u.contents.option == C_SIG)
2005 v->s = xmemdupz(sigpos, siglen);
2006 else if (atom->u.contents.option == C_LINES) {
2007 struct strbuf s = STRBUF_INIT;
2008 const char *contents_end = bodypos + nonsiglen;
2010 /* Size is the length of the message after removing the signature */
2011 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
2012 v->s = strbuf_detach(&s, NULL);
2013 } else if (atom->u.contents.option == C_TRAILERS) {
2014 struct strbuf s = STRBUF_INIT;
2016 /* Format the trailer info according to the trailer_opts given */
2017 format_trailers_from_commit(&atom->u.contents.trailer_opts, subpos, &s);
2019 v->s = strbuf_detach(&s, NULL);
2020 } else if (atom->u.contents.option == C_BARE)
2021 v->s = xstrdup(subpos);
2024 free((void *)sigpos);
2028 * We want to have empty print-string for field requests
2029 * that do not apply (e.g. "authordate" for a tag object)
2031 static void fill_missing_values(struct atom_value *val)
2033 int i;
2034 for (i = 0; i < used_atom_cnt; i++) {
2035 struct atom_value *v = &val[i];
2036 if (!v->s)
2037 v->s = xstrdup("");
2042 * val is a list of atom_value to hold returned values. Extract
2043 * the values for atoms in used_atom array out of (obj, buf, sz).
2044 * when deref is false, (obj, buf, sz) is the object that is
2045 * pointed at by the ref itself; otherwise it is the object the
2046 * ref (which is a tag) refers to.
2048 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
2050 void *buf = data->content;
2052 switch (obj->type) {
2053 case OBJ_TAG:
2054 grab_tag_values(val, deref, obj);
2055 grab_sub_body_contents(val, deref, data);
2056 grab_person("tagger", val, deref, buf);
2057 grab_describe_values(val, deref, obj);
2058 break;
2059 case OBJ_COMMIT:
2060 grab_commit_values(val, deref, obj);
2061 grab_sub_body_contents(val, deref, data);
2062 grab_person("author", val, deref, buf);
2063 grab_person("committer", val, deref, buf);
2064 grab_signature(val, deref, obj);
2065 grab_describe_values(val, deref, obj);
2066 break;
2067 case OBJ_TREE:
2068 /* grab_tree_values(val, deref, obj, buf, sz); */
2069 grab_sub_body_contents(val, deref, data);
2070 break;
2071 case OBJ_BLOB:
2072 /* grab_blob_values(val, deref, obj, buf, sz); */
2073 grab_sub_body_contents(val, deref, data);
2074 break;
2075 default:
2076 die("Eh? Object of type %d?", obj->type);
2080 static inline char *copy_advance(char *dst, const char *src)
2082 while (*src)
2083 *dst++ = *src++;
2084 return dst;
2087 static const char *lstrip_ref_components(const char *refname, int len)
2089 long remaining = len;
2090 const char *start = xstrdup(refname);
2091 const char *to_free = start;
2093 if (len < 0) {
2094 int i;
2095 const char *p = refname;
2097 /* Find total no of '/' separated path-components */
2098 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2101 * The number of components we need to strip is now
2102 * the total minus the components to be left (Plus one
2103 * because we count the number of '/', but the number
2104 * of components is one more than the no of '/').
2106 remaining = i + len + 1;
2109 while (remaining > 0) {
2110 switch (*start++) {
2111 case '\0':
2112 free((char *)to_free);
2113 return xstrdup("");
2114 case '/':
2115 remaining--;
2116 break;
2120 start = xstrdup(start);
2121 free((char *)to_free);
2122 return start;
2125 static const char *rstrip_ref_components(const char *refname, int len)
2127 long remaining = len;
2128 const char *start = xstrdup(refname);
2129 const char *to_free = start;
2131 if (len < 0) {
2132 int i;
2133 const char *p = refname;
2135 /* Find total no of '/' separated path-components */
2136 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2139 * The number of components we need to strip is now
2140 * the total minus the components to be left (Plus one
2141 * because we count the number of '/', but the number
2142 * of components is one more than the no of '/').
2144 remaining = i + len + 1;
2147 while (remaining-- > 0) {
2148 char *p = strrchr(start, '/');
2149 if (!p) {
2150 free((char *)to_free);
2151 return xstrdup("");
2152 } else
2153 p[0] = '\0';
2155 return start;
2158 static const char *show_ref(struct refname_atom *atom, const char *refname)
2160 if (atom->option == R_SHORT)
2161 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2162 refname,
2163 warn_ambiguous_refs);
2164 else if (atom->option == R_LSTRIP)
2165 return lstrip_ref_components(refname, atom->lstrip);
2166 else if (atom->option == R_RSTRIP)
2167 return rstrip_ref_components(refname, atom->rstrip);
2168 else
2169 return xstrdup(refname);
2172 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2173 struct branch *branch, const char **s)
2175 int num_ours, num_theirs;
2176 if (atom->u.remote_ref.option == RR_REF)
2177 *s = show_ref(&atom->u.remote_ref.refname, refname);
2178 else if (atom->u.remote_ref.option == RR_TRACK) {
2179 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2180 NULL, atom->u.remote_ref.push,
2181 AHEAD_BEHIND_FULL) < 0) {
2182 *s = xstrdup(msgs.gone);
2183 } else if (!num_ours && !num_theirs)
2184 *s = xstrdup("");
2185 else if (!num_ours)
2186 *s = xstrfmt(msgs.behind, num_theirs);
2187 else if (!num_theirs)
2188 *s = xstrfmt(msgs.ahead, num_ours);
2189 else
2190 *s = xstrfmt(msgs.ahead_behind,
2191 num_ours, num_theirs);
2192 if (!atom->u.remote_ref.nobracket && *s[0]) {
2193 const char *to_free = *s;
2194 *s = xstrfmt("[%s]", *s);
2195 free((void *)to_free);
2197 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2198 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2199 NULL, atom->u.remote_ref.push,
2200 AHEAD_BEHIND_FULL) < 0) {
2201 *s = xstrdup("");
2202 return;
2204 if (!num_ours && !num_theirs)
2205 *s = xstrdup("=");
2206 else if (!num_ours)
2207 *s = xstrdup("<");
2208 else if (!num_theirs)
2209 *s = xstrdup(">");
2210 else
2211 *s = xstrdup("<>");
2212 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2213 int explicit;
2214 const char *remote = atom->u.remote_ref.push ?
2215 pushremote_for_branch(branch, &explicit) :
2216 remote_for_branch(branch, &explicit);
2217 *s = xstrdup(explicit ? remote : "");
2218 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2219 const char *merge;
2221 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2222 *s = xstrdup(merge ? merge : "");
2223 } else
2224 BUG("unhandled RR_* enum");
2227 char *get_head_description(void)
2229 struct strbuf desc = STRBUF_INIT;
2230 struct wt_status_state state;
2231 memset(&state, 0, sizeof(state));
2232 wt_status_get_state(the_repository, &state, 1);
2233 if (state.rebase_in_progress ||
2234 state.rebase_interactive_in_progress) {
2235 if (state.branch)
2236 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2237 state.branch);
2238 else
2239 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2240 state.detached_from);
2241 } else if (state.bisect_in_progress)
2242 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2243 state.bisecting_from);
2244 else if (state.detached_from) {
2245 if (state.detached_at)
2246 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2247 state.detached_from);
2248 else
2249 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2250 state.detached_from);
2251 } else
2252 strbuf_addstr(&desc, _("(no branch)"));
2254 wt_status_state_free_buffers(&state);
2256 return strbuf_detach(&desc, NULL);
2259 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2261 if (!ref->symref)
2262 return xstrdup("");
2263 else
2264 return show_ref(&atom->u.refname, ref->symref);
2267 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2269 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2270 return get_head_description();
2271 return show_ref(&atom->u.refname, ref->refname);
2274 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
2275 struct expand_data *oi, struct strbuf *err)
2277 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
2278 int eaten = 1;
2279 if (oi->info.contentp) {
2280 /* We need to know that to use parse_object_buffer properly */
2281 oi->info.sizep = &oi->size;
2282 oi->info.typep = &oi->type;
2284 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
2285 OBJECT_INFO_LOOKUP_REPLACE))
2286 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2287 oid_to_hex(&oi->oid), ref->refname);
2288 if (oi->info.disk_sizep && oi->disk_size < 0)
2289 BUG("Object size is less than zero.");
2291 if (oi->info.contentp) {
2292 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
2293 if (!*obj) {
2294 if (!eaten)
2295 free(oi->content);
2296 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
2297 oid_to_hex(&oi->oid), ref->refname);
2299 grab_values(ref->value, deref, *obj, oi);
2302 grab_common_values(ref->value, deref, oi);
2303 if (!eaten)
2304 free(oi->content);
2305 return 0;
2308 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2310 int i;
2312 for (i = 0; worktrees[i]; i++) {
2313 if (worktrees[i]->head_ref) {
2314 struct ref_to_worktree_entry *entry;
2315 entry = xmalloc(sizeof(*entry));
2316 entry->wt = worktrees[i];
2317 hashmap_entry_init(&entry->ent,
2318 strhash(worktrees[i]->head_ref));
2320 hashmap_add(map, &entry->ent);
2325 static void lazy_init_worktree_map(void)
2327 if (ref_to_worktree_map.worktrees)
2328 return;
2330 ref_to_worktree_map.worktrees = get_worktrees();
2331 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2332 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2335 static char *get_worktree_path(const struct ref_array_item *ref)
2337 struct hashmap_entry entry, *e;
2338 struct ref_to_worktree_entry *lookup_result;
2340 lazy_init_worktree_map();
2342 hashmap_entry_init(&entry, strhash(ref->refname));
2343 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2345 if (!e)
2346 return xstrdup("");
2348 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2350 return xstrdup(lookup_result->wt->path);
2354 * Parse the object referred by ref, and grab needed value.
2356 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2358 struct object *obj;
2359 int i;
2360 struct object_info empty = OBJECT_INFO_INIT;
2361 int ahead_behind_atoms = 0;
2362 int is_base_atoms = 0;
2364 CALLOC_ARRAY(ref->value, used_atom_cnt);
2367 * NEEDSWORK: The following code might be unncessary if all codepaths
2368 * that call populate_value() populates the symref member of ref_array_item
2369 * like in apply_ref_filter(). Currently pretty_print_ref() is the only codepath
2370 * that calls populate_value() without first populating symref.
2372 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2373 ref->symref = refs_resolve_refdup(get_main_ref_store(the_repository),
2374 ref->refname,
2375 RESOLVE_REF_READING,
2376 NULL, NULL);
2377 if (!ref->symref)
2378 ref->symref = xstrdup("");
2381 /* Fill in specials first */
2382 for (i = 0; i < used_atom_cnt; i++) {
2383 struct used_atom *atom = &used_atom[i];
2384 enum atom_type atom_type = atom->atom_type;
2385 const char *name = used_atom[i].name;
2386 struct atom_value *v = &ref->value[i];
2387 int deref = 0;
2388 const char *refname;
2389 struct branch *branch = NULL;
2391 v->s_size = ATOM_SIZE_UNSPECIFIED;
2392 v->handler = append_atom;
2393 v->value = 0;
2394 v->atom = atom;
2396 if (*name == '*') {
2397 deref = 1;
2398 name++;
2401 if (atom_type == ATOM_REFNAME)
2402 refname = get_refname(atom, ref);
2403 else if (atom_type == ATOM_WORKTREEPATH) {
2404 if (ref->kind == FILTER_REFS_BRANCHES)
2405 v->s = get_worktree_path(ref);
2406 else
2407 v->s = xstrdup("");
2408 continue;
2410 else if (atom_type == ATOM_SYMREF)
2411 refname = get_symref(atom, ref);
2412 else if (atom_type == ATOM_UPSTREAM) {
2413 const char *branch_name;
2414 /* only local branches may have an upstream */
2415 if (!skip_prefix(ref->refname, "refs/heads/",
2416 &branch_name)) {
2417 v->s = xstrdup("");
2418 continue;
2420 branch = branch_get(branch_name);
2422 refname = branch_get_upstream(branch, NULL);
2423 if (refname)
2424 fill_remote_ref_details(atom, refname, branch, &v->s);
2425 else
2426 v->s = xstrdup("");
2427 continue;
2428 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2429 const char *branch_name;
2430 v->s = xstrdup("");
2431 if (!skip_prefix(ref->refname, "refs/heads/",
2432 &branch_name))
2433 continue;
2434 branch = branch_get(branch_name);
2436 if (atom->u.remote_ref.push_remote)
2437 refname = NULL;
2438 else {
2439 refname = branch_get_push(branch, NULL);
2440 if (!refname)
2441 continue;
2443 /* We will definitely re-init v->s on the next line. */
2444 free((char *)v->s);
2445 fill_remote_ref_details(atom, refname, branch, &v->s);
2446 continue;
2447 } else if (atom_type == ATOM_COLOR) {
2448 v->s = xstrdup(atom->u.color);
2449 continue;
2450 } else if (atom_type == ATOM_FLAG) {
2451 char buf[256], *cp = buf;
2452 if (ref->flag & REF_ISSYMREF)
2453 cp = copy_advance(cp, ",symref");
2454 if (ref->flag & REF_ISPACKED)
2455 cp = copy_advance(cp, ",packed");
2456 if (cp == buf)
2457 v->s = xstrdup("");
2458 else {
2459 *cp = '\0';
2460 v->s = xstrdup(buf + 1);
2462 continue;
2463 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2464 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2465 continue;
2466 } else if (atom_type == ATOM_HEAD) {
2467 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2468 v->s = xstrdup("*");
2469 else
2470 v->s = xstrdup(" ");
2471 continue;
2472 } else if (atom_type == ATOM_ALIGN) {
2473 v->handler = align_atom_handler;
2474 v->s = xstrdup("");
2475 continue;
2476 } else if (atom_type == ATOM_END) {
2477 v->handler = end_atom_handler;
2478 v->s = xstrdup("");
2479 continue;
2480 } else if (atom_type == ATOM_IF) {
2481 const char *s;
2482 if (skip_prefix(name, "if:", &s))
2483 v->s = xstrdup(s);
2484 else
2485 v->s = xstrdup("");
2486 v->handler = if_atom_handler;
2487 continue;
2488 } else if (atom_type == ATOM_THEN) {
2489 v->handler = then_atom_handler;
2490 v->s = xstrdup("");
2491 continue;
2492 } else if (atom_type == ATOM_ELSE) {
2493 v->handler = else_atom_handler;
2494 v->s = xstrdup("");
2495 continue;
2496 } else if (atom_type == ATOM_REST) {
2497 if (ref->rest)
2498 v->s = xstrdup(ref->rest);
2499 else
2500 v->s = xstrdup("");
2501 continue;
2502 } else if (atom_type == ATOM_AHEADBEHIND) {
2503 if (ref->counts) {
2504 const struct ahead_behind_count *count;
2505 count = ref->counts[ahead_behind_atoms++];
2506 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2507 } else {
2508 /* Not a commit. */
2509 v->s = xstrdup("");
2511 continue;
2512 } else if (atom_type == ATOM_ISBASE) {
2513 if (ref->is_base && ref->is_base[is_base_atoms]) {
2514 v->s = xstrfmt("(%s)", ref->is_base[is_base_atoms]);
2515 free(ref->is_base[is_base_atoms]);
2516 } else {
2517 v->s = xstrdup("");
2519 is_base_atoms++;
2520 continue;
2521 } else
2522 continue;
2524 if (!deref)
2525 v->s = xstrdup(refname);
2526 else
2527 v->s = xstrfmt("%s^{}", refname);
2528 free((char *)refname);
2531 for (i = 0; i < used_atom_cnt; i++) {
2532 struct atom_value *v = &ref->value[i];
2533 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2534 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2535 oid_to_hex(&ref->objectname), ref->refname);
2538 if (need_tagged)
2539 oi.info.contentp = &oi.content;
2540 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2541 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2542 return 0;
2545 oi.oid = ref->objectname;
2546 if (get_object(ref, 0, &obj, &oi, err))
2547 return -1;
2550 * If there is no atom that wants to know about tagged
2551 * object, we are done.
2553 if (!need_tagged || (obj->type != OBJ_TAG))
2554 return 0;
2557 * If it is a tag object, see if we use the peeled value. If we do,
2558 * grab the peeled OID.
2560 if (need_tagged && peel_iterated_oid(the_repository, &obj->oid, &oi_deref.oid))
2561 die("bad tag");
2563 return get_object(ref, 1, &obj, &oi_deref, err);
2567 * Given a ref, return the value for the atom. This lazily gets value
2568 * out of the object by calling populate value.
2570 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2571 struct atom_value **v, struct strbuf *err)
2573 if (!ref->value) {
2574 if (populate_value(ref, err))
2575 return -1;
2576 fill_missing_values(ref->value);
2578 *v = &ref->value[atom];
2579 return 0;
2583 * Return 1 if the refname matches one of the patterns, otherwise 0.
2584 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2585 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2586 * matches "refs/heads/mas*", too).
2588 static int match_pattern(const char **patterns, const char *refname,
2589 int ignore_case)
2591 unsigned flags = 0;
2593 if (ignore_case)
2594 flags |= WM_CASEFOLD;
2597 * When no '--format' option is given we need to skip the prefix
2598 * for matching refs of tags and branches.
2600 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2601 skip_prefix(refname, "refs/heads/", &refname) ||
2602 skip_prefix(refname, "refs/remotes/", &refname) ||
2603 skip_prefix(refname, "refs/", &refname));
2605 for (; *patterns; patterns++) {
2606 if (!wildmatch(*patterns, refname, flags))
2607 return 1;
2609 return 0;
2613 * Return 1 if the refname matches one of the patterns, otherwise 0.
2614 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2615 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2616 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2618 static int match_name_as_path(const char **pattern, const char *refname,
2619 int ignore_case)
2621 int namelen = strlen(refname);
2622 unsigned flags = WM_PATHNAME;
2624 if (ignore_case)
2625 flags |= WM_CASEFOLD;
2627 for (; *pattern; pattern++) {
2628 const char *p = *pattern;
2629 int plen = strlen(p);
2631 if ((plen <= namelen) &&
2632 !strncmp(refname, p, plen) &&
2633 (refname[plen] == '\0' ||
2634 refname[plen] == '/' ||
2635 p[plen-1] == '/'))
2636 return 1;
2637 if (!wildmatch(p, refname, flags))
2638 return 1;
2640 return 0;
2643 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2644 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2646 if (!*filter->name_patterns)
2647 return 1; /* No pattern always matches */
2648 if (filter->match_as_path)
2649 return match_name_as_path(filter->name_patterns, refname,
2650 filter->ignore_case);
2651 return match_pattern(filter->name_patterns, refname,
2652 filter->ignore_case);
2655 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2657 if (!filter->exclude.nr)
2658 return 0;
2659 if (filter->match_as_path)
2660 return match_name_as_path(filter->exclude.v, refname,
2661 filter->ignore_case);
2662 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2666 * This is the same as for_each_fullref_in(), but it tries to iterate
2667 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2668 * pattern match, so the callback still has to match each ref individually.
2670 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2671 each_ref_fn cb,
2672 void *cb_data)
2674 if (filter->kind & FILTER_REFS_ROOT_REFS) {
2675 /* In this case, we want to print all refs including root refs. */
2676 return refs_for_each_include_root_refs(get_main_ref_store(the_repository),
2677 cb, cb_data);
2680 if (!filter->match_as_path) {
2682 * in this case, the patterns are applied after
2683 * prefixes like "refs/heads/" etc. are stripped off,
2684 * so we have to look at everything:
2686 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2687 "", NULL, cb, cb_data);
2690 if (filter->ignore_case) {
2692 * we can't handle case-insensitive comparisons,
2693 * so just return everything and let the caller
2694 * sort it out.
2696 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2697 "", NULL, cb, cb_data);
2700 if (!filter->name_patterns[0]) {
2701 /* no patterns; we have to look at everything */
2702 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2703 "", filter->exclude.v, cb, cb_data);
2706 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2707 NULL, filter->name_patterns,
2708 filter->exclude.v,
2709 cb, cb_data);
2713 * Given a ref (oid, refname), check if the ref belongs to the array
2714 * of oids. If the given ref is a tag, check if the given tag points
2715 * at one of the oids in the given oid array. Returns non-zero if a
2716 * match is found.
2718 * NEEDSWORK:
2719 * As the refs are cached we might know what refname peels to without
2720 * the need to parse the object via parse_object(). peel_ref() might be a
2721 * more efficient alternative to obtain the pointee.
2723 static int match_points_at(struct oid_array *points_at,
2724 const struct object_id *oid,
2725 const char *refname)
2727 struct object *obj;
2729 if (oid_array_lookup(points_at, oid) >= 0)
2730 return 1;
2731 obj = parse_object_with_flags(the_repository, oid,
2732 PARSE_OBJECT_SKIP_HASH_CHECK);
2733 while (obj && obj->type == OBJ_TAG) {
2734 struct tag *tag = (struct tag *)obj;
2736 if (parse_tag(tag) < 0) {
2737 obj = NULL;
2738 break;
2741 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2742 return 1;
2744 obj = tag->tagged;
2746 if (!obj)
2747 die(_("malformed object at '%s'"), refname);
2748 return 0;
2752 * Allocate space for a new ref_array_item and copy the name and oid to it.
2754 * Callers can then fill in other struct members at their leisure.
2756 static struct ref_array_item *new_ref_array_item(const char *refname,
2757 const struct object_id *oid)
2759 struct ref_array_item *ref;
2761 FLEX_ALLOC_STR(ref, refname, refname);
2762 oidcpy(&ref->objectname, oid);
2763 ref->rest = NULL;
2765 return ref;
2768 static void ref_array_append(struct ref_array *array, struct ref_array_item *ref)
2770 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2771 array->items[array->nr++] = ref;
2774 struct ref_array_item *ref_array_push(struct ref_array *array,
2775 const char *refname,
2776 const struct object_id *oid)
2778 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2779 ref_array_append(array, ref);
2780 return ref;
2783 static int ref_kind_from_refname(const char *refname)
2785 unsigned int i;
2787 static struct {
2788 const char *prefix;
2789 unsigned int kind;
2790 } ref_kind[] = {
2791 { "refs/heads/" , FILTER_REFS_BRANCHES },
2792 { "refs/remotes/" , FILTER_REFS_REMOTES },
2793 { "refs/tags/", FILTER_REFS_TAGS}
2796 if (!strcmp(refname, "HEAD"))
2797 return FILTER_REFS_DETACHED_HEAD;
2799 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2800 if (starts_with(refname, ref_kind[i].prefix))
2801 return ref_kind[i].kind;
2804 if (is_pseudo_ref(refname))
2805 return FILTER_REFS_PSEUDOREFS;
2806 if (is_root_ref(refname))
2807 return FILTER_REFS_ROOT_REFS;
2809 return FILTER_REFS_OTHERS;
2812 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2814 if (filter->kind == FILTER_REFS_BRANCHES ||
2815 filter->kind == FILTER_REFS_REMOTES ||
2816 filter->kind == FILTER_REFS_TAGS)
2817 return filter->kind;
2818 return ref_kind_from_refname(refname);
2821 static struct ref_array_item *apply_ref_filter(const char *refname, const char *referent, const struct object_id *oid,
2822 int flag, struct ref_filter *filter)
2824 struct ref_array_item *ref;
2825 struct commit *commit = NULL;
2826 unsigned int kind;
2828 if (flag & REF_BAD_NAME) {
2829 warning(_("ignoring ref with broken name %s"), refname);
2830 return NULL;
2833 if (flag & REF_ISBROKEN) {
2834 warning(_("ignoring broken ref %s"), refname);
2835 return NULL;
2838 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2839 kind = filter_ref_kind(filter, refname);
2842 * Generally HEAD refs are printed with special description denoting a rebase,
2843 * detached state and so forth. This is useful when only printing the HEAD ref
2844 * But when it is being printed along with other root refs, it makes sense to
2845 * keep the formatting consistent. So we mask the type to act like a root ref.
2847 if (filter->kind & FILTER_REFS_ROOT_REFS && kind == FILTER_REFS_DETACHED_HEAD)
2848 kind = FILTER_REFS_ROOT_REFS;
2849 else if (!(kind & filter->kind))
2850 return NULL;
2852 if (!filter_pattern_match(filter, refname))
2853 return NULL;
2855 if (filter_exclude_match(filter, refname))
2856 return NULL;
2858 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2859 return NULL;
2862 * A merge filter is applied on refs pointing to commits. Hence
2863 * obtain the commit using the 'oid' available and discard all
2864 * non-commits early. The actual filtering is done later.
2866 if (filter->reachable_from || filter->unreachable_from ||
2867 filter->with_commit || filter->no_commit || filter->verbose) {
2868 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2869 if (!commit)
2870 return NULL;
2871 /* We perform the filtering for the '--contains' option... */
2872 if (filter->with_commit &&
2873 !commit_contains(filter, commit, filter->with_commit, &filter->internal.contains_cache))
2874 return NULL;
2875 /* ...or for the `--no-contains' option */
2876 if (filter->no_commit &&
2877 commit_contains(filter, commit, filter->no_commit, &filter->internal.no_contains_cache))
2878 return NULL;
2882 * We do not open the object yet; sort may only need refname
2883 * to do its job and the resulting list may yet to be pruned
2884 * by maxcount logic.
2886 ref = new_ref_array_item(refname, oid);
2887 ref->commit = commit;
2888 ref->flag = flag;
2889 ref->kind = kind;
2890 ref->symref = xstrdup_or_null(referent);
2892 return ref;
2895 struct ref_filter_cbdata {
2896 struct ref_array *array;
2897 struct ref_filter *filter;
2901 * A call-back given to for_each_ref(). Filter refs and keep them for
2902 * later object processing.
2904 static int filter_one(const char *refname, const char *referent, const struct object_id *oid, int flag, void *cb_data)
2906 struct ref_filter_cbdata *ref_cbdata = cb_data;
2907 struct ref_array_item *ref;
2909 ref = apply_ref_filter(refname, referent, oid, flag, ref_cbdata->filter);
2910 if (ref)
2911 ref_array_append(ref_cbdata->array, ref);
2913 return 0;
2916 /* Free memory allocated for a ref_array_item */
2917 static void free_array_item(struct ref_array_item *item)
2919 free((char *)item->symref);
2920 if (item->value) {
2921 int i;
2922 for (i = 0; i < used_atom_cnt; i++)
2923 free((char *)item->value[i].s);
2924 free(item->value);
2926 free(item->counts);
2927 free(item->is_base);
2928 free(item);
2931 struct ref_filter_and_format_cbdata {
2932 struct ref_filter *filter;
2933 struct ref_format *format;
2935 struct ref_filter_and_format_internal {
2936 int count;
2937 } internal;
2940 static int filter_and_format_one(const char *refname, const char *referent, const struct object_id *oid, int flag, void *cb_data)
2942 struct ref_filter_and_format_cbdata *ref_cbdata = cb_data;
2943 struct ref_array_item *ref;
2944 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
2946 ref = apply_ref_filter(refname, referent, oid, flag, ref_cbdata->filter);
2947 if (!ref)
2948 return 0;
2950 if (format_ref_array_item(ref, ref_cbdata->format, &output, &err))
2951 die("%s", err.buf);
2953 if (output.len || !ref_cbdata->format->array_opts.omit_empty) {
2954 fwrite(output.buf, 1, output.len, stdout);
2955 putchar('\n');
2958 strbuf_release(&output);
2959 strbuf_release(&err);
2960 free_array_item(ref);
2963 * Increment the running count of refs that match the filter. If
2964 * max_count is set and we've reached the max, stop the ref
2965 * iteration by returning a nonzero value.
2967 if (ref_cbdata->format->array_opts.max_count &&
2968 ++ref_cbdata->internal.count >= ref_cbdata->format->array_opts.max_count)
2969 return 1;
2971 return 0;
2974 /* Free all memory allocated for ref_array */
2975 void ref_array_clear(struct ref_array *array)
2977 int i;
2979 for (i = 0; i < array->nr; i++)
2980 free_array_item(array->items[i]);
2981 FREE_AND_NULL(array->items);
2982 array->nr = array->alloc = 0;
2984 for (i = 0; i < used_atom_cnt; i++) {
2985 struct used_atom *atom = &used_atom[i];
2986 if (atom->atom_type == ATOM_HEAD)
2987 free(atom->u.head);
2988 free((char *)atom->name);
2990 FREE_AND_NULL(used_atom);
2991 used_atom_cnt = 0;
2993 if (ref_to_worktree_map.worktrees) {
2994 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2995 struct ref_to_worktree_entry, ent);
2996 free_worktrees(ref_to_worktree_map.worktrees);
2997 ref_to_worktree_map.worktrees = NULL;
3000 FREE_AND_NULL(array->counts);
3003 #define EXCLUDE_REACHED 0
3004 #define INCLUDE_REACHED 1
3005 static void reach_filter(struct ref_array *array,
3006 struct commit_list **check_reachable,
3007 int include_reached)
3009 int i, old_nr;
3010 struct commit **to_clear;
3012 if (!*check_reachable)
3013 return;
3015 CALLOC_ARRAY(to_clear, array->nr);
3016 for (i = 0; i < array->nr; i++) {
3017 struct ref_array_item *item = array->items[i];
3018 to_clear[i] = item->commit;
3021 tips_reachable_from_bases(the_repository,
3022 *check_reachable,
3023 to_clear, array->nr,
3024 UNINTERESTING);
3026 old_nr = array->nr;
3027 array->nr = 0;
3029 for (i = 0; i < old_nr; i++) {
3030 struct ref_array_item *item = array->items[i];
3031 struct commit *commit = item->commit;
3033 int is_merged = !!(commit->object.flags & UNINTERESTING);
3035 if (is_merged == include_reached)
3036 array->items[array->nr++] = array->items[i];
3037 else
3038 free_array_item(item);
3041 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
3043 while (*check_reachable) {
3044 struct commit *merge_commit = pop_commit(check_reachable);
3045 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
3048 free(to_clear);
3051 void filter_ahead_behind(struct repository *r,
3052 struct ref_format *format,
3053 struct ref_array *array)
3055 struct commit **commits;
3056 size_t commits_nr = format->bases.nr + array->nr;
3058 if (!format->bases.nr || !array->nr)
3059 return;
3061 ALLOC_ARRAY(commits, commits_nr);
3062 for (size_t i = 0; i < format->bases.nr; i++)
3063 commits[i] = format->bases.items[i].util;
3065 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
3067 commits_nr = format->bases.nr;
3068 array->counts_nr = 0;
3069 for (size_t i = 0; i < array->nr; i++) {
3070 const char *name = array->items[i]->refname;
3071 commits[commits_nr] = lookup_commit_reference_by_name(name);
3073 if (!commits[commits_nr])
3074 continue;
3076 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
3077 for (size_t j = 0; j < format->bases.nr; j++) {
3078 struct ahead_behind_count *count;
3079 count = &array->counts[array->counts_nr++];
3080 count->tip_index = commits_nr;
3081 count->base_index = j;
3083 array->items[i]->counts[j] = count;
3085 commits_nr++;
3088 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
3089 free(commits);
3092 void filter_is_base(struct repository *r,
3093 struct ref_format *format,
3094 struct ref_array *array)
3096 struct commit **bases;
3097 size_t bases_nr = 0;
3098 struct ref_array_item **back_index;
3100 if (!format->is_base_tips.nr || !array->nr)
3101 return;
3103 CALLOC_ARRAY(back_index, array->nr);
3104 CALLOC_ARRAY(bases, array->nr);
3106 for (size_t i = 0; i < array->nr; i++) {
3107 const char *name = array->items[i]->refname;
3108 struct commit *c = lookup_commit_reference_by_name_gently(name, 1);
3110 CALLOC_ARRAY(array->items[i]->is_base, format->is_base_tips.nr);
3112 if (!c)
3113 continue;
3115 back_index[bases_nr] = array->items[i];
3116 bases[bases_nr] = c;
3117 bases_nr++;
3120 for (size_t i = 0; i < format->is_base_tips.nr; i++) {
3121 struct commit *tip = format->is_base_tips.items[i].util;
3122 int base_index = get_branch_base_for_tip(r, tip, bases, bases_nr);
3124 if (base_index < 0)
3125 continue;
3127 /* Store the string for use in output later. */
3128 back_index[base_index]->is_base[i] = xstrdup(format->is_base_tips.items[i].string);
3131 free(back_index);
3132 free(bases);
3135 static int do_filter_refs(struct ref_filter *filter, unsigned int type, each_ref_fn fn, void *cb_data)
3137 int ret = 0;
3139 filter->kind = type & FILTER_REFS_KIND_MASK;
3141 init_contains_cache(&filter->internal.contains_cache);
3142 init_contains_cache(&filter->internal.no_contains_cache);
3144 /* Simple per-ref filtering */
3145 if (!filter->kind)
3146 die("filter_refs: invalid type");
3147 else {
3149 * For common cases where we need only branches or remotes or tags,
3150 * we only iterate through those refs. If a mix of refs is needed,
3151 * we iterate over all refs and filter out required refs with the help
3152 * of filter_ref_kind().
3154 if (filter->kind == FILTER_REFS_BRANCHES)
3155 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3156 "refs/heads/", NULL,
3157 fn, cb_data);
3158 else if (filter->kind == FILTER_REFS_REMOTES)
3159 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3160 "refs/remotes/", NULL,
3161 fn, cb_data);
3162 else if (filter->kind == FILTER_REFS_TAGS)
3163 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3164 "refs/tags/", NULL, fn,
3165 cb_data);
3166 else if (filter->kind & FILTER_REFS_REGULAR)
3167 ret = for_each_fullref_in_pattern(filter, fn, cb_data);
3170 * When printing all ref types, HEAD is already included,
3171 * so we don't want to print HEAD again.
3173 if (!ret && !(filter->kind & FILTER_REFS_ROOT_REFS) &&
3174 (filter->kind & FILTER_REFS_DETACHED_HEAD))
3175 refs_head_ref(get_main_ref_store(the_repository), fn,
3176 cb_data);
3179 clear_contains_cache(&filter->internal.contains_cache);
3180 clear_contains_cache(&filter->internal.no_contains_cache);
3182 return ret;
3186 * API for filtering a set of refs. Based on the type of refs the user
3187 * has requested, we iterate through those refs and apply filters
3188 * as per the given ref_filter structure and finally store the
3189 * filtered refs in the ref_array structure.
3191 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
3193 struct ref_filter_cbdata ref_cbdata;
3194 int save_commit_buffer_orig;
3195 int ret = 0;
3197 ref_cbdata.array = array;
3198 ref_cbdata.filter = filter;
3200 save_commit_buffer_orig = save_commit_buffer;
3201 save_commit_buffer = 0;
3203 ret = do_filter_refs(filter, type, filter_one, &ref_cbdata);
3205 /* Filters that need revision walking */
3206 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
3207 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
3209 save_commit_buffer = save_commit_buffer_orig;
3210 return ret;
3213 static inline int can_do_iterative_format(struct ref_filter *filter,
3214 struct ref_sorting *sorting,
3215 struct ref_format *format)
3218 * Filtering & formatting results within a single ref iteration
3219 * callback is not compatible with options that require
3220 * post-processing a filtered ref_array. These include:
3221 * - filtering on reachability
3222 * - sorting the filtered results
3223 * - including ahead-behind information in the formatted output
3225 return !(filter->reachable_from ||
3226 filter->unreachable_from ||
3227 sorting ||
3228 format->bases.nr ||
3229 format->is_base_tips.nr);
3232 void filter_and_format_refs(struct ref_filter *filter, unsigned int type,
3233 struct ref_sorting *sorting,
3234 struct ref_format *format)
3236 if (can_do_iterative_format(filter, sorting, format)) {
3237 int save_commit_buffer_orig;
3238 struct ref_filter_and_format_cbdata ref_cbdata = {
3239 .filter = filter,
3240 .format = format,
3243 save_commit_buffer_orig = save_commit_buffer;
3244 save_commit_buffer = 0;
3246 do_filter_refs(filter, type, filter_and_format_one, &ref_cbdata);
3248 save_commit_buffer = save_commit_buffer_orig;
3249 } else {
3250 struct ref_array array = { 0 };
3251 filter_refs(&array, filter, type);
3252 filter_ahead_behind(the_repository, format, &array);
3253 filter_is_base(the_repository, format, &array);
3254 ref_array_sort(sorting, &array);
3255 print_formatted_ref_array(&array, format);
3256 ref_array_clear(&array);
3260 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
3262 if (!(a->kind ^ b->kind))
3263 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
3264 if (a->kind & FILTER_REFS_DETACHED_HEAD)
3265 return -1;
3266 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
3267 return 1;
3268 BUG("should have died in the xor check above");
3269 return 0;
3272 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
3274 const char *s1 = vs1, *s2 = vs2;
3275 const char *end = s1 + n;
3277 for (; s1 < end; s1++, s2++) {
3278 int diff = tolower(*s1) - tolower(*s2);
3279 if (diff)
3280 return diff;
3282 return 0;
3285 struct ref_sorting {
3286 struct ref_sorting *next;
3287 int atom; /* index into used_atom array (internal) */
3288 enum ref_sorting_order sort_flags;
3291 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
3293 struct atom_value *va, *vb;
3294 int cmp;
3295 int cmp_detached_head = 0;
3296 cmp_type cmp_type = used_atom[s->atom].type;
3297 struct strbuf err = STRBUF_INIT;
3299 if (get_ref_atom_value(a, s->atom, &va, &err))
3300 die("%s", err.buf);
3301 if (get_ref_atom_value(b, s->atom, &vb, &err))
3302 die("%s", err.buf);
3303 strbuf_release(&err);
3304 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
3305 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
3306 cmp = compare_detached_head(a, b);
3307 cmp_detached_head = 1;
3308 } else if (s->sort_flags & REF_SORTING_VERSION) {
3309 cmp = versioncmp(va->s, vb->s);
3310 } else if (cmp_type == FIELD_STR) {
3311 if (va->s_size < 0 && vb->s_size < 0) {
3312 int (*cmp_fn)(const char *, const char *);
3313 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3314 ? strcasecmp : strcmp;
3315 cmp = cmp_fn(va->s, vb->s);
3316 } else {
3317 size_t a_size = va->s_size < 0 ?
3318 strlen(va->s) : va->s_size;
3319 size_t b_size = vb->s_size < 0 ?
3320 strlen(vb->s) : vb->s_size;
3321 int (*cmp_fn)(const void *, const void *, size_t);
3322 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3323 ? memcasecmp : memcmp;
3325 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3326 a_size : b_size);
3327 if (!cmp) {
3328 if (a_size > b_size)
3329 cmp = 1;
3330 else if (a_size < b_size)
3331 cmp = -1;
3334 } else {
3335 if (va->value < vb->value)
3336 cmp = -1;
3337 else if (va->value == vb->value)
3338 cmp = 0;
3339 else
3340 cmp = 1;
3343 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3344 ? -cmp : cmp;
3347 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3349 struct ref_array_item *a = *((struct ref_array_item **)a_);
3350 struct ref_array_item *b = *((struct ref_array_item **)b_);
3351 struct ref_sorting *s;
3353 for (s = ref_sorting; s; s = s->next) {
3354 int cmp = cmp_ref_sorting(s, a, b);
3355 if (cmp)
3356 return cmp;
3358 s = ref_sorting;
3359 return s && s->sort_flags & REF_SORTING_ICASE ?
3360 strcasecmp(a->refname, b->refname) :
3361 strcmp(a->refname, b->refname);
3364 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3365 unsigned int mask, int on)
3367 for (; sorting; sorting = sorting->next) {
3368 if (on)
3369 sorting->sort_flags |= mask;
3370 else
3371 sorting->sort_flags &= ~mask;
3375 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3377 if (sorting)
3378 QSORT_S(array->items, array->nr, compare_refs, sorting);
3381 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3383 struct strbuf *s = &state->stack->output;
3385 while (*cp && (!ep || cp < ep)) {
3386 if (*cp == '%') {
3387 if (cp[1] == '%')
3388 cp++;
3389 else {
3390 int ch = hex2chr(cp + 1);
3391 if (0 <= ch) {
3392 strbuf_addch(s, ch);
3393 cp += 3;
3394 continue;
3398 strbuf_addch(s, *cp);
3399 cp++;
3403 int format_ref_array_item(struct ref_array_item *info,
3404 struct ref_format *format,
3405 struct strbuf *final_buf,
3406 struct strbuf *error_buf)
3408 const char *cp, *sp, *ep;
3409 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3411 state.quote_style = format->quote_style;
3412 push_stack_element(&state.stack);
3414 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3415 struct atom_value *atomv;
3416 int pos;
3418 ep = strchr(sp, ')');
3419 if (cp < sp)
3420 append_literal(cp, sp, &state);
3421 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3422 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3423 atomv->handler(atomv, &state, error_buf)) {
3424 pop_stack_element(&state.stack);
3425 return -1;
3428 if (*cp) {
3429 sp = cp + strlen(cp);
3430 append_literal(cp, sp, &state);
3432 if (format->need_color_reset_at_eol) {
3433 struct atom_value resetv = ATOM_VALUE_INIT;
3434 resetv.s = GIT_COLOR_RESET;
3435 if (append_atom(&resetv, &state, error_buf)) {
3436 pop_stack_element(&state.stack);
3437 return -1;
3440 if (state.stack->prev) {
3441 pop_stack_element(&state.stack);
3442 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3444 strbuf_addbuf(final_buf, &state.stack->output);
3445 pop_stack_element(&state.stack);
3446 return 0;
3449 void print_formatted_ref_array(struct ref_array *array, struct ref_format *format)
3451 int total;
3452 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3454 total = format->array_opts.max_count;
3455 if (!total || array->nr < total)
3456 total = array->nr;
3457 for (int i = 0; i < total; i++) {
3458 strbuf_reset(&err);
3459 strbuf_reset(&output);
3460 if (format_ref_array_item(array->items[i], format, &output, &err))
3461 die("%s", err.buf);
3462 if (output.len || !format->array_opts.omit_empty) {
3463 fwrite(output.buf, 1, output.len, stdout);
3464 putchar('\n');
3468 strbuf_release(&err);
3469 strbuf_release(&output);
3472 void pretty_print_ref(const char *name, const struct object_id *oid,
3473 struct ref_format *format)
3475 struct ref_array_item *ref_item;
3476 struct strbuf output = STRBUF_INIT;
3477 struct strbuf err = STRBUF_INIT;
3479 ref_item = new_ref_array_item(name, oid);
3480 ref_item->kind = ref_kind_from_refname(name);
3481 if (format_ref_array_item(ref_item, format, &output, &err))
3482 die("%s", err.buf);
3483 fwrite(output.buf, 1, output.len, stdout);
3484 putchar('\n');
3486 strbuf_release(&err);
3487 strbuf_release(&output);
3488 free_array_item(ref_item);
3491 static int parse_sorting_atom(const char *atom)
3494 * This parses an atom using a dummy ref_format, since we don't
3495 * actually care about the formatting details.
3497 struct ref_format dummy = REF_FORMAT_INIT;
3498 const char *end = atom + strlen(atom);
3499 struct strbuf err = STRBUF_INIT;
3500 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3501 if (res < 0)
3502 die("%s", err.buf);
3503 strbuf_release(&err);
3504 return res;
3507 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3509 struct ref_sorting *s;
3511 CALLOC_ARRAY(s, 1);
3512 s->next = *sorting_tail;
3513 *sorting_tail = s;
3515 if (*arg == '-') {
3516 s->sort_flags |= REF_SORTING_REVERSE;
3517 arg++;
3519 if (skip_prefix(arg, "version:", &arg) ||
3520 skip_prefix(arg, "v:", &arg))
3521 s->sort_flags |= REF_SORTING_VERSION;
3522 s->atom = parse_sorting_atom(arg);
3525 struct ref_sorting *ref_sorting_options(struct string_list *options)
3527 struct string_list_item *item;
3528 struct ref_sorting *sorting = NULL, **tail = &sorting;
3530 if (options->nr) {
3531 for_each_string_list_item(item, options)
3532 parse_ref_sorting(tail, item->string);
3536 * From here on, the ref_sorting list should be used to talk
3537 * about the sort order used for the output. The caller
3538 * should not touch the string form anymore.
3540 string_list_clear(options, 0);
3541 return sorting;
3544 void ref_sorting_release(struct ref_sorting *sorting)
3546 while (sorting) {
3547 struct ref_sorting *next = sorting->next;
3548 free(sorting);
3549 sorting = next;
3553 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3555 struct ref_filter *rf = opt->value;
3556 struct object_id oid;
3557 struct commit *merge_commit;
3559 BUG_ON_OPT_NEG(unset);
3561 if (repo_get_oid(the_repository, arg, &oid))
3562 die(_("malformed object name %s"), arg);
3564 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3566 if (!merge_commit)
3567 return error(_("option `%s' must point to a commit"), opt->long_name);
3569 if (starts_with(opt->long_name, "no"))
3570 commit_list_insert(merge_commit, &rf->unreachable_from);
3571 else
3572 commit_list_insert(merge_commit, &rf->reachable_from);
3574 return 0;
3577 void ref_filter_init(struct ref_filter *filter)
3579 struct ref_filter blank = REF_FILTER_INIT;
3580 memcpy(filter, &blank, sizeof(blank));
3583 void ref_filter_clear(struct ref_filter *filter)
3585 strvec_clear(&filter->exclude);
3586 oid_array_clear(&filter->points_at);
3587 free_commit_list(filter->with_commit);
3588 free_commit_list(filter->no_commit);
3589 free_commit_list(filter->reachable_from);
3590 free_commit_list(filter->unreachable_from);
3591 ref_filter_init(filter);