The eighteenth batch
[git.git] / ref-filter.c
blobb06e18a569ae068f346fcccb81ed590c435e75a2
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 struct ref_trailer_buf {
79 struct string_list filter_list;
80 struct strbuf sepbuf;
81 struct strbuf kvsepbuf;
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 struct ref_trailer_buf *trailer_buf;
205 unsigned int nlines;
206 } contents;
207 struct {
208 enum { RAW_BARE, RAW_LENGTH } option;
209 } raw_data;
210 struct {
211 cmp_status cmp_status;
212 const char *str;
213 } if_then_else;
214 struct {
215 enum { O_FULL, O_LENGTH, O_SHORT } option;
216 unsigned int length;
217 } oid;
218 struct {
219 enum { O_SIZE, O_SIZE_DISK } option;
220 } objectsize;
221 struct {
222 enum { N_RAW, N_MAILMAP } option;
223 } name_option;
224 struct {
225 enum {
226 EO_RAW = 0,
227 EO_TRIM = 1<<0,
228 EO_LOCALPART = 1<<1,
229 EO_MAILMAP = 1<<2,
230 } option;
231 } email_option;
232 struct {
233 enum { S_BARE, S_GRADE, S_SIGNER, S_KEY,
234 S_FINGERPRINT, S_PRI_KEY_FP, S_TRUST_LEVEL } option;
235 } signature;
236 struct strvec describe_args;
237 struct refname_atom refname;
238 char *head;
239 } u;
240 } *used_atom;
241 static int used_atom_cnt, need_tagged, need_symref;
244 * Expand string, append it to strbuf *sb, then return error code ret.
245 * Allow to save few lines of code.
247 __attribute__((format (printf, 3, 4)))
248 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
250 va_list ap;
251 va_start(ap, fmt);
252 strbuf_vaddf(sb, fmt, ap);
253 va_end(ap);
254 return ret;
257 static int err_no_arg(struct strbuf *sb, const char *name)
259 size_t namelen = strchrnul(name, ':') - name;
260 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
261 (int)namelen, name);
262 return -1;
265 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
267 size_t namelen = strchrnul(name, ':') - name;
268 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
269 (int)namelen, name, arg);
270 return -1;
274 * Parse option of name "candidate" in the option string "to_parse" of
275 * the form
277 * "candidate1[=val1],candidate2[=val2],candidate3[=val3],..."
279 * The remaining part of "to_parse" is stored in "end" (if we are
280 * parsing the last candidate, then this is NULL) and the value of
281 * the candidate is stored in "valuestart" and its length in "valuelen",
282 * that is the portion after "=". Since it is possible for a "candidate"
283 * to not have a value, in such cases, "valuestart" is set to point to
284 * NULL and "valuelen" to 0.
286 * The function returns 1 on success. It returns 0 if we don't find
287 * "candidate" in "to_parse" or we find "candidate" but it is followed
288 * by more chars (for example, "candidatefoo"), that is, we don't find
289 * an exact match.
291 * This function only does the above for one "candidate" at a time. So
292 * it has to be called each time trying to parse a "candidate" in the
293 * option string "to_parse".
295 static int match_atom_arg_value(const char *to_parse, const char *candidate,
296 const char **end, const char **valuestart,
297 size_t *valuelen)
299 const char *atom;
301 if (!skip_prefix(to_parse, candidate, &atom))
302 return 0; /* definitely not "candidate" */
304 if (*atom == '=') {
305 /* we just saw "candidate=" */
306 *valuestart = atom + 1;
307 atom = strchrnul(*valuestart, ',');
308 *valuelen = atom - *valuestart;
309 } else if (*atom != ',' && *atom != '\0') {
310 /* key begins with "candidate" but has more chars */
311 return 0;
312 } else {
313 /* just "candidate" without "=val" */
314 *valuestart = NULL;
315 *valuelen = 0;
318 /* atom points at either the ',' or NUL after this key[=val] */
319 if (*atom == ',')
320 atom++;
321 else if (*atom)
322 BUG("Why is *atom not NULL yet?");
324 *end = atom;
325 return 1;
329 * Parse boolean option of name "candidate" in the option list "to_parse"
330 * of the form
332 * "candidate1[=bool1],candidate2[=bool2],candidate3[=bool3],..."
334 * The remaining part of "to_parse" is stored in "end" (if we are parsing
335 * the last candidate, then this is NULL) and the value (if given) is
336 * parsed and stored in "val", so "val" always points to either 0 or 1.
337 * If the value is not given, then "val" is set to point to 1.
339 * The boolean value is parsed using "git_parse_maybe_bool()", so the
340 * accepted values are
342 * to set true - "1", "yes", "true"
343 * to set false - "0", "no", "false"
345 * This function returns 1 on success. It returns 0 when we don't find
346 * an exact match for "candidate" or when the boolean value given is
347 * not valid.
349 static int match_atom_bool_arg(const char *to_parse, const char *candidate,
350 const char **end, int *val)
352 const char *argval;
353 char *strval;
354 size_t arglen;
355 int v;
357 if (!match_atom_arg_value(to_parse, candidate, end, &argval, &arglen))
358 return 0;
360 if (!argval) {
361 *val = 1;
362 return 1;
365 strval = xstrndup(argval, arglen);
366 v = git_parse_maybe_bool(strval);
367 free(strval);
369 if (v == -1)
370 return 0;
372 *val = v;
374 return 1;
377 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
378 const char *color_value, struct strbuf *err)
380 if (!color_value)
381 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
382 if (color_parse(color_value, atom->u.color) < 0)
383 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
384 color_value);
386 * We check this after we've parsed the color, which lets us complain
387 * about syntactically bogus color names even if they won't be used.
389 if (!want_color(format->use_color))
390 color_parse("", atom->u.color);
391 return 0;
394 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
395 const char *name, struct strbuf *err)
397 if (!arg)
398 atom->option = R_NORMAL;
399 else if (!strcmp(arg, "short"))
400 atom->option = R_SHORT;
401 else if (skip_prefix(arg, "lstrip=", &arg) ||
402 skip_prefix(arg, "strip=", &arg)) {
403 atom->option = R_LSTRIP;
404 if (strtol_i(arg, 10, &atom->lstrip))
405 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
406 } else if (skip_prefix(arg, "rstrip=", &arg)) {
407 atom->option = R_RSTRIP;
408 if (strtol_i(arg, 10, &atom->rstrip))
409 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
410 } else
411 return err_bad_arg(err, name, arg);
412 return 0;
415 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
416 struct used_atom *atom,
417 const char *arg, struct strbuf *err)
419 struct string_list params = STRING_LIST_INIT_DUP;
420 int i;
422 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
423 atom->u.remote_ref.push = 1;
425 if (!arg) {
426 atom->u.remote_ref.option = RR_REF;
427 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
428 arg, atom->name, err);
431 atom->u.remote_ref.nobracket = 0;
432 string_list_split(&params, arg, ',', -1);
434 for (i = 0; i < params.nr; i++) {
435 const char *s = params.items[i].string;
437 if (!strcmp(s, "track"))
438 atom->u.remote_ref.option = RR_TRACK;
439 else if (!strcmp(s, "trackshort"))
440 atom->u.remote_ref.option = RR_TRACKSHORT;
441 else if (!strcmp(s, "nobracket"))
442 atom->u.remote_ref.nobracket = 1;
443 else if (!strcmp(s, "remotename")) {
444 atom->u.remote_ref.option = RR_REMOTE_NAME;
445 atom->u.remote_ref.push_remote = 1;
446 } else if (!strcmp(s, "remoteref")) {
447 atom->u.remote_ref.option = RR_REMOTE_REF;
448 atom->u.remote_ref.push_remote = 1;
449 } else {
450 atom->u.remote_ref.option = RR_REF;
451 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
452 arg, atom->name, err)) {
453 string_list_clear(&params, 0);
454 return -1;
459 string_list_clear(&params, 0);
460 return 0;
463 static int objecttype_atom_parser(struct ref_format *format UNUSED,
464 struct used_atom *atom,
465 const char *arg, struct strbuf *err)
467 if (arg)
468 return err_no_arg(err, "objecttype");
469 if (*atom->name == '*')
470 oi_deref.info.typep = &oi_deref.type;
471 else
472 oi.info.typep = &oi.type;
473 return 0;
476 static int objectsize_atom_parser(struct ref_format *format UNUSED,
477 struct used_atom *atom,
478 const char *arg, struct strbuf *err)
480 if (!arg) {
481 atom->u.objectsize.option = O_SIZE;
482 if (*atom->name == '*')
483 oi_deref.info.sizep = &oi_deref.size;
484 else
485 oi.info.sizep = &oi.size;
486 } else if (!strcmp(arg, "disk")) {
487 atom->u.objectsize.option = O_SIZE_DISK;
488 if (*atom->name == '*')
489 oi_deref.info.disk_sizep = &oi_deref.disk_size;
490 else
491 oi.info.disk_sizep = &oi.disk_size;
492 } else
493 return err_bad_arg(err, "objectsize", arg);
494 return 0;
497 static int deltabase_atom_parser(struct ref_format *format UNUSED,
498 struct used_atom *atom,
499 const char *arg, struct strbuf *err)
501 if (arg)
502 return err_no_arg(err, "deltabase");
503 if (*atom->name == '*')
504 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
505 else
506 oi.info.delta_base_oid = &oi.delta_base_oid;
507 return 0;
510 static int body_atom_parser(struct ref_format *format UNUSED,
511 struct used_atom *atom,
512 const char *arg, struct strbuf *err)
514 if (arg)
515 return err_no_arg(err, "body");
516 atom->u.contents.option = C_BODY_DEP;
517 return 0;
520 static int subject_atom_parser(struct ref_format *format UNUSED,
521 struct used_atom *atom,
522 const char *arg, struct strbuf *err)
524 if (!arg)
525 atom->u.contents.option = C_SUB;
526 else if (!strcmp(arg, "sanitize"))
527 atom->u.contents.option = C_SUB_SANITIZE;
528 else
529 return err_bad_arg(err, "subject", arg);
530 return 0;
533 static int parse_signature_option(const char *arg)
535 if (!arg)
536 return S_BARE;
537 else if (!strcmp(arg, "signer"))
538 return S_SIGNER;
539 else if (!strcmp(arg, "grade"))
540 return S_GRADE;
541 else if (!strcmp(arg, "key"))
542 return S_KEY;
543 else if (!strcmp(arg, "fingerprint"))
544 return S_FINGERPRINT;
545 else if (!strcmp(arg, "primarykeyfingerprint"))
546 return S_PRI_KEY_FP;
547 else if (!strcmp(arg, "trustlevel"))
548 return S_TRUST_LEVEL;
549 return -1;
552 static int signature_atom_parser(struct ref_format *format UNUSED,
553 struct used_atom *atom,
554 const char *arg, struct strbuf *err)
556 int opt = parse_signature_option(arg);
557 if (opt < 0)
558 return err_bad_arg(err, "signature", arg);
559 atom->u.signature.option = opt;
560 return 0;
563 static int trailers_atom_parser(struct ref_format *format UNUSED,
564 struct used_atom *atom,
565 const char *arg, struct strbuf *err)
567 atom->u.contents.trailer_opts.no_divider = 1;
569 if (arg) {
570 char *argbuf = xstrfmt("%s)", arg);
571 const char *arg = argbuf;
572 char *invalid_arg = NULL;
573 struct ref_trailer_buf *tb;
576 * Do not inline these directly into the used_atom struct!
577 * When we parse them in format_set_trailers_options(),
578 * we will make pointer references directly to them,
579 * which will not survive a realloc() of the used_atom list.
580 * They must be allocated in a separate, stable struct.
582 atom->u.contents.trailer_buf = tb = xmalloc(sizeof(*tb));
583 string_list_init_dup(&tb->filter_list);
584 strbuf_init(&tb->sepbuf, 0);
585 strbuf_init(&tb->kvsepbuf, 0);
587 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
588 &tb->filter_list,
589 &tb->sepbuf, &tb->kvsepbuf,
590 &arg, &invalid_arg)) {
591 if (!invalid_arg)
592 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
593 else
594 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
595 free(invalid_arg);
596 free(argbuf);
597 return -1;
599 free(argbuf);
601 atom->u.contents.option = C_TRAILERS;
602 return 0;
605 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
606 const char *arg, struct strbuf *err)
608 if (!arg)
609 atom->u.contents.option = C_BARE;
610 else if (!strcmp(arg, "body"))
611 atom->u.contents.option = C_BODY;
612 else if (!strcmp(arg, "size")) {
613 atom->type = FIELD_ULONG;
614 atom->u.contents.option = C_LENGTH;
615 } else if (!strcmp(arg, "signature"))
616 atom->u.contents.option = C_SIG;
617 else if (!strcmp(arg, "subject"))
618 atom->u.contents.option = C_SUB;
619 else if (!strcmp(arg, "trailers")) {
620 if (trailers_atom_parser(format, atom, NULL, err))
621 return -1;
622 } else if (skip_prefix(arg, "trailers:", &arg)) {
623 if (trailers_atom_parser(format, atom, arg, err))
624 return -1;
625 } else if (skip_prefix(arg, "lines=", &arg)) {
626 atom->u.contents.option = C_LINES;
627 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
628 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
629 } else
630 return err_bad_arg(err, "contents", arg);
631 return 0;
634 static int describe_atom_option_parser(struct strvec *args, const char **arg,
635 struct strbuf *err)
637 const char *argval;
638 size_t arglen = 0;
639 int optval = 0;
641 if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {
642 if (!optval)
643 strvec_push(args, "--no-tags");
644 else
645 strvec_push(args, "--tags");
646 return 1;
649 if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {
650 char *endptr;
652 if (!arglen)
653 return strbuf_addf_ret(err, -1,
654 _("argument expected for %s"),
655 "describe:abbrev");
656 if (strtol(argval, &endptr, 10) < 0)
657 return strbuf_addf_ret(err, -1,
658 _("positive value expected %s=%s"),
659 "describe:abbrev", argval);
660 if (endptr - argval != arglen)
661 return strbuf_addf_ret(err, -1,
662 _("cannot fully parse %s=%s"),
663 "describe:abbrev", argval);
665 strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);
666 return 1;
669 if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {
670 if (!arglen)
671 return strbuf_addf_ret(err, -1,
672 _("value expected %s="),
673 "describe:match");
675 strvec_pushf(args, "--match=%.*s", (int)arglen, argval);
676 return 1;
679 if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {
680 if (!arglen)
681 return strbuf_addf_ret(err, -1,
682 _("value expected %s="),
683 "describe:exclude");
685 strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);
686 return 1;
689 return 0;
692 static int describe_atom_parser(struct ref_format *format UNUSED,
693 struct used_atom *atom,
694 const char *arg, struct strbuf *err)
696 strvec_init(&atom->u.describe_args);
698 for (;;) {
699 int found = 0;
700 const char *bad_arg = arg;
702 if (!arg || !*arg)
703 break;
705 found = describe_atom_option_parser(&atom->u.describe_args, &arg, err);
706 if (found < 0)
707 return found;
708 if (!found)
709 return err_bad_arg(err, "describe", bad_arg);
711 return 0;
714 static int raw_atom_parser(struct ref_format *format UNUSED,
715 struct used_atom *atom,
716 const char *arg, struct strbuf *err)
718 if (!arg)
719 atom->u.raw_data.option = RAW_BARE;
720 else if (!strcmp(arg, "size")) {
721 atom->type = FIELD_ULONG;
722 atom->u.raw_data.option = RAW_LENGTH;
723 } else
724 return err_bad_arg(err, "raw", arg);
725 return 0;
728 static int oid_atom_parser(struct ref_format *format UNUSED,
729 struct used_atom *atom,
730 const char *arg, struct strbuf *err)
732 if (!arg)
733 atom->u.oid.option = O_FULL;
734 else if (!strcmp(arg, "short"))
735 atom->u.oid.option = O_SHORT;
736 else if (skip_prefix(arg, "short=", &arg)) {
737 atom->u.oid.option = O_LENGTH;
738 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
739 atom->u.oid.length == 0)
740 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
741 if (atom->u.oid.length < MINIMUM_ABBREV)
742 atom->u.oid.length = MINIMUM_ABBREV;
743 } else
744 return err_bad_arg(err, atom->name, arg);
745 return 0;
748 static int person_name_atom_parser(struct ref_format *format UNUSED,
749 struct used_atom *atom,
750 const char *arg, struct strbuf *err)
752 if (!arg)
753 atom->u.name_option.option = N_RAW;
754 else if (!strcmp(arg, "mailmap"))
755 atom->u.name_option.option = N_MAILMAP;
756 else
757 return err_bad_arg(err, atom->name, arg);
758 return 0;
761 static int email_atom_option_parser(const char **arg)
763 if (!*arg)
764 return EO_RAW;
765 if (skip_prefix(*arg, "trim", arg))
766 return EO_TRIM;
767 if (skip_prefix(*arg, "localpart", arg))
768 return EO_LOCALPART;
769 if (skip_prefix(*arg, "mailmap", arg))
770 return EO_MAILMAP;
771 return -1;
774 static int person_email_atom_parser(struct ref_format *format UNUSED,
775 struct used_atom *atom,
776 const char *arg, struct strbuf *err)
778 for (;;) {
779 int opt = email_atom_option_parser(&arg);
780 const char *bad_arg = arg;
782 if (opt < 0)
783 return err_bad_arg(err, atom->name, bad_arg);
784 atom->u.email_option.option |= opt;
786 if (!arg || !*arg)
787 break;
788 if (*arg == ',')
789 arg++;
790 else
791 return err_bad_arg(err, atom->name, bad_arg);
793 return 0;
796 static int refname_atom_parser(struct ref_format *format UNUSED,
797 struct used_atom *atom,
798 const char *arg, struct strbuf *err)
800 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
803 static align_type parse_align_position(const char *s)
805 if (!strcmp(s, "right"))
806 return ALIGN_RIGHT;
807 else if (!strcmp(s, "middle"))
808 return ALIGN_MIDDLE;
809 else if (!strcmp(s, "left"))
810 return ALIGN_LEFT;
811 return -1;
814 static int align_atom_parser(struct ref_format *format UNUSED,
815 struct used_atom *atom,
816 const char *arg, struct strbuf *err)
818 struct align *align = &atom->u.align;
819 struct string_list params = STRING_LIST_INIT_DUP;
820 int i;
821 unsigned int width = ~0U;
823 if (!arg)
824 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
826 align->position = ALIGN_LEFT;
828 string_list_split(&params, arg, ',', -1);
829 for (i = 0; i < params.nr; i++) {
830 const char *s = params.items[i].string;
831 int position;
833 if (skip_prefix(s, "position=", &s)) {
834 position = parse_align_position(s);
835 if (position < 0) {
836 strbuf_addf(err, _("unrecognized position:%s"), s);
837 string_list_clear(&params, 0);
838 return -1;
840 align->position = position;
841 } else if (skip_prefix(s, "width=", &s)) {
842 if (strtoul_ui(s, 10, &width)) {
843 strbuf_addf(err, _("unrecognized width:%s"), s);
844 string_list_clear(&params, 0);
845 return -1;
847 } else if (!strtoul_ui(s, 10, &width))
849 else if ((position = parse_align_position(s)) >= 0)
850 align->position = position;
851 else {
852 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
853 string_list_clear(&params, 0);
854 return -1;
858 if (width == ~0U) {
859 string_list_clear(&params, 0);
860 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
862 align->width = width;
863 string_list_clear(&params, 0);
864 return 0;
867 static int if_atom_parser(struct ref_format *format UNUSED,
868 struct used_atom *atom,
869 const char *arg, struct strbuf *err)
871 if (!arg) {
872 atom->u.if_then_else.cmp_status = COMPARE_NONE;
873 return 0;
874 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
875 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
876 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
877 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
878 } else
879 return err_bad_arg(err, "if", arg);
880 return 0;
883 static int rest_atom_parser(struct ref_format *format UNUSED,
884 struct used_atom *atom UNUSED,
885 const char *arg, struct strbuf *err)
887 if (arg)
888 return err_no_arg(err, "rest");
889 return 0;
892 static int ahead_behind_atom_parser(struct ref_format *format,
893 struct used_atom *atom UNUSED,
894 const char *arg, struct strbuf *err)
896 struct string_list_item *item;
898 if (!arg)
899 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
901 item = string_list_append(&format->bases, arg);
902 item->util = lookup_commit_reference_by_name(arg);
903 if (!item->util)
904 die("failed to find '%s'", arg);
906 return 0;
909 static int is_base_atom_parser(struct ref_format *format,
910 struct used_atom *atom UNUSED,
911 const char *arg, struct strbuf *err)
913 struct string_list_item *item;
915 if (!arg)
916 return strbuf_addf_ret(err, -1, _("expected format: %%(is-base:<committish>)"));
918 item = string_list_append(&format->is_base_tips, arg);
919 item->util = lookup_commit_reference_by_name(arg);
920 if (!item->util)
921 die("failed to find '%s'", arg);
923 return 0;
926 static int head_atom_parser(struct ref_format *format UNUSED,
927 struct used_atom *atom,
928 const char *arg, struct strbuf *err)
930 if (arg)
931 return err_no_arg(err, "HEAD");
932 atom->u.head = refs_resolve_refdup(get_main_ref_store(the_repository),
933 "HEAD", RESOLVE_REF_READING, NULL,
934 NULL);
935 return 0;
938 static struct {
939 const char *name;
940 info_source source;
941 cmp_type cmp_type;
942 int (*parser)(struct ref_format *format, struct used_atom *atom,
943 const char *arg, struct strbuf *err);
944 } valid_atom[] = {
945 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
946 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
947 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
948 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
949 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
950 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
951 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
952 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
953 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
954 [ATOM_TYPE] = { "type", SOURCE_OBJ },
955 [ATOM_TAG] = { "tag", SOURCE_OBJ },
956 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
957 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
958 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
959 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
960 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
961 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
962 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
963 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
964 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
965 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
966 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
967 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
968 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
969 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
970 [ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },
971 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
972 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
973 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
974 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
975 [ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },
976 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
977 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
978 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
979 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
980 [ATOM_FLAG] = { "flag", SOURCE_NONE },
981 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
982 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
983 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
984 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
985 [ATOM_END] = { "end", SOURCE_NONE },
986 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
987 [ATOM_THEN] = { "then", SOURCE_NONE },
988 [ATOM_ELSE] = { "else", SOURCE_NONE },
989 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
990 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
991 [ATOM_ISBASE] = { "is-base", SOURCE_OTHER, FIELD_STR, is_base_atom_parser },
993 * Please update $__git_ref_fieldlist in git-completion.bash
994 * when you add new atoms
998 #define REF_FORMATTING_STATE_INIT { 0 }
1000 struct ref_formatting_stack {
1001 struct ref_formatting_stack *prev;
1002 struct strbuf output;
1003 void (*at_end)(struct ref_formatting_stack **stack);
1004 void (*at_end_data_free)(void *data);
1005 void *at_end_data;
1008 struct ref_formatting_state {
1009 int quote_style;
1010 struct ref_formatting_stack *stack;
1013 struct atom_value {
1014 const char *s;
1015 ssize_t s_size;
1016 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
1017 struct strbuf *err);
1018 uintmax_t value; /* used for sorting when not FIELD_STR */
1019 struct used_atom *atom;
1022 #define ATOM_SIZE_UNSPECIFIED (-1)
1024 #define ATOM_VALUE_INIT { \
1025 .s_size = ATOM_SIZE_UNSPECIFIED \
1029 * Used to parse format string and sort specifiers
1031 static int parse_ref_filter_atom(struct ref_format *format,
1032 const char *atom, const char *ep,
1033 struct strbuf *err)
1035 const char *sp;
1036 const char *arg;
1037 int i, at, atom_len;
1039 sp = atom;
1040 if (*sp == '*' && sp < ep)
1041 sp++; /* deref */
1042 if (ep <= sp)
1043 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
1044 (int)(ep-atom), atom);
1047 * If the atom name has a colon, strip it and everything after
1048 * it off - it specifies the format for this entry, and
1049 * shouldn't be used for checking against the valid_atom
1050 * table.
1052 arg = memchr(sp, ':', ep - sp);
1053 atom_len = (arg ? arg : ep) - sp;
1055 /* Do we have the atom already used elsewhere? */
1056 for (i = 0; i < used_atom_cnt; i++) {
1057 int len = strlen(used_atom[i].name);
1058 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
1059 return i;
1062 /* Is the atom a valid one? */
1063 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
1064 int len = strlen(valid_atom[i].name);
1065 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
1066 break;
1069 if (ARRAY_SIZE(valid_atom) <= i)
1070 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
1071 (int)(ep-atom), atom);
1072 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
1073 return strbuf_addf_ret(err, -1,
1074 _("not a git repository, but the field '%.*s' requires access to object data"),
1075 (int)(ep-atom), atom);
1077 /* Add it in, including the deref prefix */
1078 at = used_atom_cnt;
1079 used_atom_cnt++;
1080 REALLOC_ARRAY(used_atom, used_atom_cnt);
1081 used_atom[at].atom_type = i;
1082 used_atom[at].name = xmemdupz(atom, ep - atom);
1083 used_atom[at].type = valid_atom[i].cmp_type;
1084 used_atom[at].source = valid_atom[i].source;
1085 if (used_atom[at].source == SOURCE_OBJ) {
1086 if (*atom == '*')
1087 oi_deref.info.contentp = &oi_deref.content;
1088 else
1089 oi.info.contentp = &oi.content;
1091 if (arg) {
1092 arg = used_atom[at].name + (arg - atom) + 1;
1093 if (!*arg) {
1095 * Treat empty sub-arguments list as NULL (i.e.,
1096 * "%(atom:)" is equivalent to "%(atom)").
1098 arg = NULL;
1101 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
1102 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
1103 return -1;
1104 if (*atom == '*')
1105 need_tagged = 1;
1106 if (i == ATOM_SYMREF)
1107 need_symref = 1;
1108 return at;
1111 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
1113 switch (quote_style) {
1114 case QUOTE_NONE:
1115 if (len < 0)
1116 strbuf_addstr(s, str);
1117 else
1118 strbuf_add(s, str, len);
1119 break;
1120 case QUOTE_SHELL:
1121 sq_quote_buf(s, str);
1122 break;
1123 case QUOTE_PERL:
1124 if (len < 0)
1125 perl_quote_buf(s, str);
1126 else
1127 perl_quote_buf_with_len(s, str, len);
1128 break;
1129 case QUOTE_PYTHON:
1130 python_quote_buf(s, str);
1131 break;
1132 case QUOTE_TCL:
1133 tcl_quote_buf(s, str);
1134 break;
1138 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
1139 struct strbuf *err UNUSED)
1142 * Quote formatting is only done when the stack has a single
1143 * element. Otherwise quote formatting is done on the
1144 * element's entire output strbuf when the %(end) atom is
1145 * encountered.
1147 if (!state->stack->prev)
1148 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
1149 else if (v->s_size < 0)
1150 strbuf_addstr(&state->stack->output, v->s);
1151 else
1152 strbuf_add(&state->stack->output, v->s, v->s_size);
1153 return 0;
1156 static void push_stack_element(struct ref_formatting_stack **stack)
1158 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
1160 strbuf_init(&s->output, 0);
1161 s->prev = *stack;
1162 *stack = s;
1165 static void pop_stack_element(struct ref_formatting_stack **stack)
1167 struct ref_formatting_stack *current = *stack;
1168 struct ref_formatting_stack *prev = current->prev;
1170 if (prev)
1171 strbuf_addbuf(&prev->output, &current->output);
1172 strbuf_release(&current->output);
1173 if (current->at_end_data_free)
1174 current->at_end_data_free(current->at_end_data);
1175 free(current);
1176 *stack = prev;
1179 static void end_align_handler(struct ref_formatting_stack **stack)
1181 struct ref_formatting_stack *cur = *stack;
1182 struct align *align = (struct align *)cur->at_end_data;
1183 struct strbuf s = STRBUF_INIT;
1185 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
1186 strbuf_swap(&cur->output, &s);
1187 strbuf_release(&s);
1190 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1191 struct strbuf *err UNUSED)
1193 struct ref_formatting_stack *new_stack;
1195 push_stack_element(&state->stack);
1196 new_stack = state->stack;
1197 new_stack->at_end = end_align_handler;
1198 new_stack->at_end_data = &atomv->atom->u.align;
1199 return 0;
1202 static void if_then_else_handler(struct ref_formatting_stack **stack)
1204 struct ref_formatting_stack *cur = *stack;
1205 struct ref_formatting_stack *prev = cur->prev;
1206 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
1208 if (!if_then_else->then_atom_seen)
1209 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
1211 if (if_then_else->else_atom_seen) {
1213 * There is an %(else) atom: we need to drop one state from the
1214 * stack, either the %(else) branch if the condition is satisfied, or
1215 * the %(then) branch if it isn't.
1217 if (if_then_else->condition_satisfied) {
1218 strbuf_reset(&cur->output);
1219 pop_stack_element(&cur);
1220 } else {
1221 strbuf_swap(&cur->output, &prev->output);
1222 strbuf_reset(&cur->output);
1223 pop_stack_element(&cur);
1225 } else if (!if_then_else->condition_satisfied) {
1227 * No %(else) atom: just drop the %(then) branch if the
1228 * condition is not satisfied.
1230 strbuf_reset(&cur->output);
1233 *stack = cur;
1236 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1237 struct strbuf *err UNUSED)
1239 struct ref_formatting_stack *new_stack;
1240 struct if_then_else *if_then_else = xcalloc(1, sizeof(*if_then_else));
1242 if_then_else->str = atomv->atom->u.if_then_else.str;
1243 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
1245 push_stack_element(&state->stack);
1246 new_stack = state->stack;
1247 new_stack->at_end = if_then_else_handler;
1248 new_stack->at_end_data = if_then_else;
1249 new_stack->at_end_data_free = free;
1250 return 0;
1253 static int is_empty(struct strbuf *buf)
1255 const char *cur = buf->buf;
1256 const char *end = buf->buf + buf->len;
1258 while (cur != end && (isspace(*cur)))
1259 cur++;
1261 return cur == end;
1264 static int then_atom_handler(struct atom_value *atomv UNUSED,
1265 struct ref_formatting_state *state,
1266 struct strbuf *err)
1268 struct ref_formatting_stack *cur = state->stack;
1269 struct if_then_else *if_then_else = NULL;
1270 size_t str_len = 0;
1272 if (cur->at_end == if_then_else_handler)
1273 if_then_else = (struct if_then_else *)cur->at_end_data;
1274 if (!if_then_else)
1275 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
1276 if (if_then_else->then_atom_seen)
1277 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
1278 if (if_then_else->else_atom_seen)
1279 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
1280 if_then_else->then_atom_seen = 1;
1281 if (if_then_else->str)
1282 str_len = strlen(if_then_else->str);
1284 * If the 'equals' or 'notequals' attribute is used then
1285 * perform the required comparison. If not, only non-empty
1286 * strings satisfy the 'if' condition.
1288 if (if_then_else->cmp_status == COMPARE_EQUAL) {
1289 if (str_len == cur->output.len &&
1290 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1291 if_then_else->condition_satisfied = 1;
1292 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
1293 if (str_len != cur->output.len ||
1294 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1295 if_then_else->condition_satisfied = 1;
1296 } else if (cur->output.len && !is_empty(&cur->output))
1297 if_then_else->condition_satisfied = 1;
1298 strbuf_reset(&cur->output);
1299 return 0;
1302 static int else_atom_handler(struct atom_value *atomv UNUSED,
1303 struct ref_formatting_state *state,
1304 struct strbuf *err)
1306 struct ref_formatting_stack *prev = state->stack;
1307 struct if_then_else *if_then_else = NULL;
1309 if (prev->at_end == if_then_else_handler)
1310 if_then_else = (struct if_then_else *)prev->at_end_data;
1311 if (!if_then_else)
1312 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1313 if (!if_then_else->then_atom_seen)
1314 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1315 if (if_then_else->else_atom_seen)
1316 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1317 if_then_else->else_atom_seen = 1;
1318 push_stack_element(&state->stack);
1319 state->stack->at_end_data = prev->at_end_data;
1320 state->stack->at_end = prev->at_end;
1321 return 0;
1324 static int end_atom_handler(struct atom_value *atomv UNUSED,
1325 struct ref_formatting_state *state,
1326 struct strbuf *err)
1328 struct ref_formatting_stack *current = state->stack;
1329 struct strbuf s = STRBUF_INIT;
1331 if (!current->at_end)
1332 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1333 current->at_end(&state->stack);
1335 /* Stack may have been popped within at_end(), hence reset the current pointer */
1336 current = state->stack;
1339 * Perform quote formatting when the stack element is that of
1340 * a supporting atom. If nested then perform quote formatting
1341 * only on the topmost supporting atom.
1343 if (!current->prev->prev) {
1344 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1345 strbuf_swap(&current->output, &s);
1347 strbuf_release(&s);
1348 pop_stack_element(&state->stack);
1349 return 0;
1353 * In a format string, find the next occurrence of %(atom).
1355 static const char *find_next(const char *cp)
1357 while (*cp) {
1358 if (*cp == '%') {
1360 * %( is the start of an atom;
1361 * %% is a quoted per-cent.
1363 if (cp[1] == '(')
1364 return cp;
1365 else if (cp[1] == '%')
1366 cp++; /* skip over two % */
1367 /* otherwise this is a singleton, literal % */
1369 cp++;
1371 return NULL;
1374 static int reject_atom(enum atom_type atom_type)
1376 return atom_type == ATOM_REST;
1380 * Make sure the format string is well formed, and parse out
1381 * the used atoms.
1383 int verify_ref_format(struct ref_format *format)
1385 const char *cp, *sp;
1387 format->need_color_reset_at_eol = 0;
1388 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1389 struct strbuf err = STRBUF_INIT;
1390 const char *color, *ep = strchr(sp, ')');
1391 int at;
1393 if (!ep)
1394 return error(_("malformed format string %s"), sp);
1395 /* sp points at "%(" and ep points at the closing ")" */
1396 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1397 if (at < 0)
1398 die("%s", err.buf);
1399 if (reject_atom(used_atom[at].atom_type))
1400 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1402 if ((format->quote_style == QUOTE_PYTHON ||
1403 format->quote_style == QUOTE_SHELL ||
1404 format->quote_style == QUOTE_TCL) &&
1405 used_atom[at].atom_type == ATOM_RAW &&
1406 used_atom[at].u.raw_data.option == RAW_BARE)
1407 die(_("--format=%.*s cannot be used with "
1408 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1409 cp = ep + 1;
1411 if (skip_prefix(used_atom[at].name, "color:", &color))
1412 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1413 strbuf_release(&err);
1415 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1416 format->need_color_reset_at_eol = 0;
1417 return 0;
1420 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1421 struct used_atom *atom)
1423 switch (atom->u.oid.option) {
1424 case O_FULL:
1425 return oid_to_hex(oid);
1426 case O_LENGTH:
1427 return repo_find_unique_abbrev(the_repository, oid,
1428 atom->u.oid.length);
1429 case O_SHORT:
1430 return repo_find_unique_abbrev(the_repository, oid,
1431 DEFAULT_ABBREV);
1432 default:
1433 BUG("unknown %%(%s) option", field);
1437 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1438 struct atom_value *v, struct used_atom *atom)
1440 if (starts_with(name, field)) {
1441 v->s = xstrdup(do_grab_oid(field, oid, atom));
1442 return 1;
1444 return 0;
1447 /* See grab_values */
1448 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1450 int i;
1452 for (i = 0; i < used_atom_cnt; i++) {
1453 const char *name = used_atom[i].name;
1454 enum atom_type atom_type = used_atom[i].atom_type;
1455 struct atom_value *v = &val[i];
1456 if (!!deref != (*name == '*'))
1457 continue;
1458 if (deref)
1459 name++;
1460 if (atom_type == ATOM_OBJECTTYPE)
1461 v->s = xstrdup(type_name(oi->type));
1462 else if (atom_type == ATOM_OBJECTSIZE) {
1463 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1464 v->value = oi->disk_size;
1465 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1466 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1467 v->value = oi->size;
1468 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1470 } else if (atom_type == ATOM_DELTABASE)
1471 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1472 else if (atom_type == ATOM_OBJECTNAME && deref)
1473 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1477 /* See grab_values */
1478 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1480 int i;
1481 struct tag *tag = (struct tag *) obj;
1483 for (i = 0; i < used_atom_cnt; i++) {
1484 const char *name = used_atom[i].name;
1485 enum atom_type atom_type = used_atom[i].atom_type;
1486 struct atom_value *v = &val[i];
1487 if (!!deref != (*name == '*'))
1488 continue;
1489 if (deref)
1490 name++;
1491 if (atom_type == ATOM_TAG)
1492 v->s = xstrdup(tag->tag);
1493 else if (atom_type == ATOM_TYPE && tag->tagged)
1494 v->s = xstrdup(type_name(tag->tagged->type));
1495 else if (atom_type == ATOM_OBJECT && tag->tagged)
1496 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1500 /* See grab_values */
1501 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1503 int i;
1504 struct commit *commit = (struct commit *) obj;
1506 for (i = 0; i < used_atom_cnt; i++) {
1507 const char *name = used_atom[i].name;
1508 enum atom_type atom_type = used_atom[i].atom_type;
1509 struct atom_value *v = &val[i];
1510 if (!!deref != (*name == '*'))
1511 continue;
1512 if (deref)
1513 name++;
1514 if (atom_type == ATOM_TREE &&
1515 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1516 continue;
1517 if (atom_type == ATOM_NUMPARENT) {
1518 v->value = commit_list_count(commit->parents);
1519 v->s = xstrfmt("%lu", (unsigned long)v->value);
1521 else if (atom_type == ATOM_PARENT) {
1522 struct commit_list *parents;
1523 struct strbuf s = STRBUF_INIT;
1524 for (parents = commit->parents; parents; parents = parents->next) {
1525 struct object_id *oid = &parents->item->object.oid;
1526 if (parents != commit->parents)
1527 strbuf_addch(&s, ' ');
1528 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1530 v->s = strbuf_detach(&s, NULL);
1535 static const char *find_wholine(const char *who, int wholen, const char *buf)
1537 const char *eol;
1538 while (*buf) {
1539 if (!strncmp(buf, who, wholen) &&
1540 buf[wholen] == ' ')
1541 return buf + wholen + 1;
1542 eol = strchr(buf, '\n');
1543 if (!eol)
1544 return "";
1545 eol++;
1546 if (*eol == '\n')
1547 return ""; /* end of header */
1548 buf = eol;
1550 return "";
1553 static const char *copy_line(const char *buf)
1555 const char *eol = strchrnul(buf, '\n');
1556 return xmemdupz(buf, eol - buf);
1559 static const char *copy_name(const char *buf)
1561 const char *cp;
1562 for (cp = buf; *cp && *cp != '\n'; cp++) {
1563 if (starts_with(cp, " <"))
1564 return xmemdupz(buf, cp - buf);
1566 return xstrdup("");
1569 static const char *find_end_of_email(const char *email, int opt)
1571 const char *eoemail;
1573 if (opt & EO_LOCALPART) {
1574 eoemail = strchr(email, '@');
1575 if (eoemail)
1576 return eoemail;
1577 return strchr(email, '>');
1580 if (opt & EO_TRIM)
1581 return strchr(email, '>');
1584 * The option here is either the raw email option or the raw
1585 * mailmap option (that is EO_RAW or EO_MAILMAP). In such cases,
1586 * we directly grab the whole email including the closing
1587 * angle brackets.
1589 * If EO_MAILMAP was set with any other option (that is either
1590 * EO_TRIM or EO_LOCALPART), we already grab the end of email
1591 * above.
1593 eoemail = strchr(email, '>');
1594 if (eoemail)
1595 eoemail++;
1596 return eoemail;
1599 static const char *copy_email(const char *buf, struct used_atom *atom)
1601 const char *email = strchr(buf, '<');
1602 const char *eoemail;
1603 int opt = atom->u.email_option.option;
1605 if (!email)
1606 return xstrdup("");
1608 if (opt & (EO_LOCALPART | EO_TRIM))
1609 email++;
1611 eoemail = find_end_of_email(email, opt);
1612 if (!eoemail)
1613 return xstrdup("");
1614 return xmemdupz(email, eoemail - email);
1617 static char *copy_subject(const char *buf, unsigned long len)
1619 struct strbuf sb = STRBUF_INIT;
1620 int i;
1622 for (i = 0; i < len; i++) {
1623 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1624 continue; /* ignore CR in CRLF */
1626 if (buf[i] == '\n')
1627 strbuf_addch(&sb, ' ');
1628 else
1629 strbuf_addch(&sb, buf[i]);
1631 return strbuf_detach(&sb, NULL);
1634 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1636 const char *eoemail = strstr(buf, "> ");
1637 char *zone;
1638 timestamp_t timestamp;
1639 long tz;
1640 struct date_mode date_mode = DATE_MODE_INIT;
1641 const char *formatp;
1644 * We got here because atomname ends in "date" or "date<something>";
1645 * it's not possible that <something> is not ":<format>" because
1646 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1647 * ":" means no format is specified, and use the default.
1649 formatp = strchr(atomname, ':');
1650 if (formatp) {
1651 formatp++;
1652 parse_date_format(formatp, &date_mode);
1655 * If this is a sort field and a format was specified, we'll
1656 * want to compare formatted date by string value.
1658 v->atom->type = FIELD_STR;
1661 if (!eoemail)
1662 goto bad;
1663 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1664 if (timestamp == TIME_MAX)
1665 goto bad;
1666 errno = 0;
1667 tz = strtol(zone, NULL, 10);
1668 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1669 goto bad;
1670 v->s = xstrdup(show_date(timestamp, tz, date_mode));
1671 v->value = timestamp;
1672 date_mode_release(&date_mode);
1673 return;
1674 bad:
1675 v->s = xstrdup("");
1676 v->value = 0;
1679 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
1681 /* See grab_values */
1682 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1684 int i;
1685 int wholen = strlen(who);
1686 const char *wholine = NULL;
1687 const char *headers[] = { "author ", "committer ",
1688 "tagger ", NULL };
1690 for (i = 0; i < used_atom_cnt; i++) {
1691 struct used_atom *atom = &used_atom[i];
1692 const char *name = atom->name;
1693 struct atom_value *v = &val[i];
1694 struct strbuf mailmap_buf = STRBUF_INIT;
1696 if (!!deref != (*name == '*'))
1697 continue;
1698 if (deref)
1699 name++;
1700 if (strncmp(who, name, wholen))
1701 continue;
1702 if (name[wholen] != 0 &&
1703 !starts_with(name + wholen, "name") &&
1704 !starts_with(name + wholen, "email") &&
1705 !starts_with(name + wholen, "date"))
1706 continue;
1708 if ((starts_with(name + wholen, "name") &&
1709 (atom->u.name_option.option == N_MAILMAP)) ||
1710 (starts_with(name + wholen, "email") &&
1711 (atom->u.email_option.option & EO_MAILMAP))) {
1712 if (!mailmap.items)
1713 read_mailmap(&mailmap);
1714 strbuf_addstr(&mailmap_buf, buf);
1715 apply_mailmap_to_header(&mailmap_buf, headers, &mailmap);
1716 wholine = find_wholine(who, wholen, mailmap_buf.buf);
1717 } else {
1718 wholine = find_wholine(who, wholen, buf);
1721 if (!wholine)
1722 return; /* no point looking for it */
1723 if (name[wholen] == 0)
1724 v->s = copy_line(wholine);
1725 else if (starts_with(name + wholen, "name"))
1726 v->s = copy_name(wholine);
1727 else if (starts_with(name + wholen, "email"))
1728 v->s = copy_email(wholine, &used_atom[i]);
1729 else if (starts_with(name + wholen, "date"))
1730 grab_date(wholine, v, name);
1732 strbuf_release(&mailmap_buf);
1736 * For a tag or a commit object, if "creator" or "creatordate" is
1737 * requested, do something special.
1739 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1740 return; /* "author" for commit object is not wanted */
1741 if (!wholine)
1742 wholine = find_wholine(who, wholen, buf);
1743 if (!wholine)
1744 return;
1745 for (i = 0; i < used_atom_cnt; i++) {
1746 const char *name = used_atom[i].name;
1747 enum atom_type atom_type = used_atom[i].atom_type;
1748 struct atom_value *v = &val[i];
1749 if (!!deref != (*name == '*'))
1750 continue;
1751 if (deref)
1752 name++;
1754 if (atom_type == ATOM_CREATORDATE)
1755 grab_date(wholine, v, name);
1756 else if (atom_type == ATOM_CREATOR)
1757 v->s = copy_line(wholine);
1761 static void grab_signature(struct atom_value *val, int deref, struct object *obj)
1763 int i;
1764 struct commit *commit = (struct commit *) obj;
1765 struct signature_check sigc = { 0 };
1766 int signature_checked = 0;
1768 for (i = 0; i < used_atom_cnt; i++) {
1769 struct used_atom *atom = &used_atom[i];
1770 const char *name = atom->name;
1771 struct atom_value *v = &val[i];
1772 int opt;
1774 if (!!deref != (*name == '*'))
1775 continue;
1776 if (deref)
1777 name++;
1779 if (!skip_prefix(name, "signature", &name) ||
1780 (*name && *name != ':'))
1781 continue;
1782 if (!*name)
1783 name = NULL;
1784 else
1785 name++;
1787 opt = parse_signature_option(name);
1788 if (opt < 0)
1789 continue;
1791 if (!signature_checked) {
1792 check_commit_signature(commit, &sigc);
1793 signature_checked = 1;
1796 switch (opt) {
1797 case S_BARE:
1798 v->s = xstrdup(sigc.output ? sigc.output: "");
1799 break;
1800 case S_SIGNER:
1801 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1802 break;
1803 case S_GRADE:
1804 switch (sigc.result) {
1805 case 'G':
1806 switch (sigc.trust_level) {
1807 case TRUST_UNDEFINED:
1808 case TRUST_NEVER:
1809 v->s = xstrfmt("%c", (char)'U');
1810 break;
1811 default:
1812 v->s = xstrfmt("%c", (char)'G');
1813 break;
1815 break;
1816 case 'B':
1817 case 'E':
1818 case 'N':
1819 case 'X':
1820 case 'Y':
1821 case 'R':
1822 v->s = xstrfmt("%c", (char)sigc.result);
1823 break;
1825 break;
1826 case S_KEY:
1827 v->s = xstrdup(sigc.key ? sigc.key : "");
1828 break;
1829 case S_FINGERPRINT:
1830 v->s = xstrdup(sigc.fingerprint ?
1831 sigc.fingerprint : "");
1832 break;
1833 case S_PRI_KEY_FP:
1834 v->s = xstrdup(sigc.primary_key_fingerprint ?
1835 sigc.primary_key_fingerprint : "");
1836 break;
1837 case S_TRUST_LEVEL:
1838 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1839 break;
1843 if (signature_checked)
1844 signature_check_clear(&sigc);
1847 static void find_subpos(const char *buf,
1848 const char **sub, size_t *sublen,
1849 const char **body, size_t *bodylen,
1850 size_t *nonsiglen,
1851 const char **sig, size_t *siglen)
1853 const char *eol;
1854 const char *end = buf + strlen(buf);
1855 const char *sigstart;
1857 /* skip past header until we hit empty line */
1858 while (*buf && *buf != '\n') {
1859 eol = strchrnul(buf, '\n');
1860 if (*eol)
1861 eol++;
1862 buf = eol;
1864 /* skip any empty lines */
1865 while (*buf == '\n')
1866 buf++;
1867 /* parse signature first; we might not even have a subject line */
1868 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1869 *sig = sigstart;
1870 *siglen = end - *sig;
1872 /* subject is first non-empty line */
1873 *sub = buf;
1874 /* subject goes to first empty line before signature begins */
1875 if ((eol = strstr(*sub, "\n\n")) ||
1876 (eol = strstr(*sub, "\r\n\r\n"))) {
1877 eol = eol < sigstart ? eol : sigstart;
1878 } else {
1879 /* treat whole message as subject */
1880 eol = sigstart;
1882 buf = eol;
1883 *sublen = buf - *sub;
1884 /* drop trailing newline, if present */
1885 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1886 (*sub)[*sublen - 1] == '\r'))
1887 *sublen -= 1;
1889 /* skip any empty lines */
1890 while (*buf == '\n' || *buf == '\r')
1891 buf++;
1892 *body = buf;
1893 *bodylen = strlen(buf);
1894 *nonsiglen = sigstart - buf;
1898 * If 'lines' is greater than 0, append that many lines from the given
1899 * 'buf' of length 'size' to the given strbuf.
1901 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1903 int i;
1904 const char *sp, *eol;
1905 size_t len;
1907 sp = buf;
1909 for (i = 0; i < lines && sp < buf + size; i++) {
1910 if (i)
1911 strbuf_addstr(out, "\n ");
1912 eol = memchr(sp, '\n', size - (sp - buf));
1913 len = eol ? eol - sp : size - (sp - buf);
1914 strbuf_add(out, sp, len);
1915 if (!eol)
1916 break;
1917 sp = eol + 1;
1921 static void grab_describe_values(struct atom_value *val, int deref,
1922 struct object *obj)
1924 struct commit *commit = (struct commit *)obj;
1925 int i;
1927 for (i = 0; i < used_atom_cnt; i++) {
1928 struct used_atom *atom = &used_atom[i];
1929 enum atom_type type = atom->atom_type;
1930 const char *name = atom->name;
1931 struct atom_value *v = &val[i];
1933 struct child_process cmd = CHILD_PROCESS_INIT;
1934 struct strbuf out = STRBUF_INIT;
1935 struct strbuf err = STRBUF_INIT;
1937 if (type != ATOM_DESCRIBE)
1938 continue;
1940 if (!!deref != (*name == '*'))
1941 continue;
1943 cmd.git_cmd = 1;
1944 strvec_push(&cmd.args, "describe");
1945 strvec_pushv(&cmd.args, atom->u.describe_args.v);
1946 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1947 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
1948 error(_("failed to run 'describe'"));
1949 v->s = xstrdup("");
1950 continue;
1952 strbuf_rtrim(&out);
1953 v->s = strbuf_detach(&out, NULL);
1955 strbuf_release(&err);
1959 /* See grab_values */
1960 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1962 int i;
1963 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1964 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1965 void *buf = data->content;
1967 for (i = 0; i < used_atom_cnt; i++) {
1968 struct used_atom *atom = &used_atom[i];
1969 const char *name = atom->name;
1970 struct atom_value *v = &val[i];
1971 enum atom_type atom_type = atom->atom_type;
1973 if (!!deref != (*name == '*'))
1974 continue;
1975 if (deref)
1976 name++;
1978 if (atom_type == ATOM_RAW) {
1979 unsigned long buf_size = data->size;
1981 if (atom->u.raw_data.option == RAW_BARE) {
1982 v->s = xmemdupz(buf, buf_size);
1983 v->s_size = buf_size;
1984 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1985 v->value = buf_size;
1986 v->s = xstrfmt("%"PRIuMAX, v->value);
1988 continue;
1991 if ((data->type != OBJ_TAG &&
1992 data->type != OBJ_COMMIT) ||
1993 (strcmp(name, "body") &&
1994 !starts_with(name, "subject") &&
1995 !starts_with(name, "trailers") &&
1996 !starts_with(name, "contents")))
1997 continue;
1998 if (!subpos)
1999 find_subpos(buf,
2000 &subpos, &sublen,
2001 &bodypos, &bodylen, &nonsiglen,
2002 &sigpos, &siglen);
2004 if (atom->u.contents.option == C_SUB)
2005 v->s = copy_subject(subpos, sublen);
2006 else if (atom->u.contents.option == C_SUB_SANITIZE) {
2007 struct strbuf sb = STRBUF_INIT;
2008 format_sanitized_subject(&sb, subpos, sublen);
2009 v->s = strbuf_detach(&sb, NULL);
2010 } else if (atom->u.contents.option == C_BODY_DEP)
2011 v->s = xmemdupz(bodypos, bodylen);
2012 else if (atom->u.contents.option == C_LENGTH) {
2013 v->value = strlen(subpos);
2014 v->s = xstrfmt("%"PRIuMAX, v->value);
2015 } else if (atom->u.contents.option == C_BODY)
2016 v->s = xmemdupz(bodypos, nonsiglen);
2017 else if (atom->u.contents.option == C_SIG)
2018 v->s = xmemdupz(sigpos, siglen);
2019 else if (atom->u.contents.option == C_LINES) {
2020 struct strbuf s = STRBUF_INIT;
2021 const char *contents_end = bodypos + nonsiglen;
2023 /* Size is the length of the message after removing the signature */
2024 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
2025 v->s = strbuf_detach(&s, NULL);
2026 } else if (atom->u.contents.option == C_TRAILERS) {
2027 struct strbuf s = STRBUF_INIT;
2028 const char *msg;
2029 char *to_free = NULL;
2031 if (siglen)
2032 msg = to_free = xmemdupz(subpos, sigpos - subpos);
2033 else
2034 msg = subpos;
2036 /* Format the trailer info according to the trailer_opts given */
2037 format_trailers_from_commit(&atom->u.contents.trailer_opts, msg, &s);
2038 free(to_free);
2040 v->s = strbuf_detach(&s, NULL);
2041 } else if (atom->u.contents.option == C_BARE)
2042 v->s = xstrdup(subpos);
2048 * We want to have empty print-string for field requests
2049 * that do not apply (e.g. "authordate" for a tag object)
2051 static void fill_missing_values(struct atom_value *val)
2053 int i;
2054 for (i = 0; i < used_atom_cnt; i++) {
2055 struct atom_value *v = &val[i];
2056 if (!v->s)
2057 v->s = xstrdup("");
2062 * val is a list of atom_value to hold returned values. Extract
2063 * the values for atoms in used_atom array out of (obj, buf, sz).
2064 * when deref is false, (obj, buf, sz) is the object that is
2065 * pointed at by the ref itself; otherwise it is the object the
2066 * ref (which is a tag) refers to.
2068 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
2070 void *buf = data->content;
2072 switch (obj->type) {
2073 case OBJ_TAG:
2074 grab_tag_values(val, deref, obj);
2075 grab_sub_body_contents(val, deref, data);
2076 grab_person("tagger", val, deref, buf);
2077 grab_describe_values(val, deref, obj);
2078 break;
2079 case OBJ_COMMIT:
2080 grab_commit_values(val, deref, obj);
2081 grab_sub_body_contents(val, deref, data);
2082 grab_person("author", val, deref, buf);
2083 grab_person("committer", val, deref, buf);
2084 grab_signature(val, deref, obj);
2085 grab_describe_values(val, deref, obj);
2086 break;
2087 case OBJ_TREE:
2088 /* grab_tree_values(val, deref, obj, buf, sz); */
2089 grab_sub_body_contents(val, deref, data);
2090 break;
2091 case OBJ_BLOB:
2092 /* grab_blob_values(val, deref, obj, buf, sz); */
2093 grab_sub_body_contents(val, deref, data);
2094 break;
2095 default:
2096 die("Eh? Object of type %d?", obj->type);
2100 static inline char *copy_advance(char *dst, const char *src)
2102 while (*src)
2103 *dst++ = *src++;
2104 return dst;
2107 static const char *lstrip_ref_components(const char *refname, int len)
2109 long remaining = len;
2110 const char *start = xstrdup(refname);
2111 const char *to_free = start;
2113 if (len < 0) {
2114 int i;
2115 const char *p = refname;
2117 /* Find total no of '/' separated path-components */
2118 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2121 * The number of components we need to strip is now
2122 * the total minus the components to be left (Plus one
2123 * because we count the number of '/', but the number
2124 * of components is one more than the no of '/').
2126 remaining = i + len + 1;
2129 while (remaining > 0) {
2130 switch (*start++) {
2131 case '\0':
2132 free((char *)to_free);
2133 return xstrdup("");
2134 case '/':
2135 remaining--;
2136 break;
2140 start = xstrdup(start);
2141 free((char *)to_free);
2142 return start;
2145 static const char *rstrip_ref_components(const char *refname, int len)
2147 long remaining = len;
2148 const char *start = xstrdup(refname);
2149 const char *to_free = start;
2151 if (len < 0) {
2152 int i;
2153 const char *p = refname;
2155 /* Find total no of '/' separated path-components */
2156 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2159 * The number of components we need to strip is now
2160 * the total minus the components to be left (Plus one
2161 * because we count the number of '/', but the number
2162 * of components is one more than the no of '/').
2164 remaining = i + len + 1;
2167 while (remaining-- > 0) {
2168 char *p = strrchr(start, '/');
2169 if (!p) {
2170 free((char *)to_free);
2171 return xstrdup("");
2172 } else
2173 p[0] = '\0';
2175 return start;
2178 static const char *show_ref(struct refname_atom *atom, const char *refname)
2180 if (atom->option == R_SHORT)
2181 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2182 refname,
2183 warn_ambiguous_refs);
2184 else if (atom->option == R_LSTRIP)
2185 return lstrip_ref_components(refname, atom->lstrip);
2186 else if (atom->option == R_RSTRIP)
2187 return rstrip_ref_components(refname, atom->rstrip);
2188 else
2189 return xstrdup(refname);
2192 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2193 struct branch *branch, const char **s)
2195 int num_ours, num_theirs;
2196 if (atom->u.remote_ref.option == RR_REF)
2197 *s = show_ref(&atom->u.remote_ref.refname, refname);
2198 else if (atom->u.remote_ref.option == RR_TRACK) {
2199 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2200 NULL, atom->u.remote_ref.push,
2201 AHEAD_BEHIND_FULL) < 0) {
2202 *s = xstrdup(msgs.gone);
2203 } else if (!num_ours && !num_theirs)
2204 *s = xstrdup("");
2205 else if (!num_ours)
2206 *s = xstrfmt(msgs.behind, num_theirs);
2207 else if (!num_theirs)
2208 *s = xstrfmt(msgs.ahead, num_ours);
2209 else
2210 *s = xstrfmt(msgs.ahead_behind,
2211 num_ours, num_theirs);
2212 if (!atom->u.remote_ref.nobracket && *s[0]) {
2213 const char *to_free = *s;
2214 *s = xstrfmt("[%s]", *s);
2215 free((void *)to_free);
2217 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2218 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2219 NULL, atom->u.remote_ref.push,
2220 AHEAD_BEHIND_FULL) < 0) {
2221 *s = xstrdup("");
2222 return;
2224 if (!num_ours && !num_theirs)
2225 *s = xstrdup("=");
2226 else if (!num_ours)
2227 *s = xstrdup("<");
2228 else if (!num_theirs)
2229 *s = xstrdup(">");
2230 else
2231 *s = xstrdup("<>");
2232 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2233 int explicit;
2234 const char *remote = atom->u.remote_ref.push ?
2235 pushremote_for_branch(branch, &explicit) :
2236 remote_for_branch(branch, &explicit);
2237 *s = xstrdup(explicit ? remote : "");
2238 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2239 const char *merge;
2241 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2242 *s = merge ? merge : xstrdup("");
2243 } else
2244 BUG("unhandled RR_* enum");
2247 char *get_head_description(void)
2249 struct strbuf desc = STRBUF_INIT;
2250 struct wt_status_state state;
2251 memset(&state, 0, sizeof(state));
2252 wt_status_get_state(the_repository, &state, 1);
2253 if (state.rebase_in_progress ||
2254 state.rebase_interactive_in_progress) {
2255 if (state.branch)
2256 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2257 state.branch);
2258 else
2259 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2260 state.detached_from);
2261 } else if (state.bisect_in_progress)
2262 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2263 state.bisecting_from);
2264 else if (state.detached_from) {
2265 if (state.detached_at)
2266 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2267 state.detached_from);
2268 else
2269 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2270 state.detached_from);
2271 } else
2272 strbuf_addstr(&desc, _("(no branch)"));
2274 wt_status_state_free_buffers(&state);
2276 return strbuf_detach(&desc, NULL);
2279 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2281 if (!ref->symref)
2282 return xstrdup("");
2283 else
2284 return show_ref(&atom->u.refname, ref->symref);
2287 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2289 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2290 return get_head_description();
2291 return show_ref(&atom->u.refname, ref->refname);
2294 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
2295 struct expand_data *oi, struct strbuf *err)
2297 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
2298 int eaten = 1;
2299 if (oi->info.contentp) {
2300 /* We need to know that to use parse_object_buffer properly */
2301 oi->info.sizep = &oi->size;
2302 oi->info.typep = &oi->type;
2304 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
2305 OBJECT_INFO_LOOKUP_REPLACE))
2306 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2307 oid_to_hex(&oi->oid), ref->refname);
2308 if (oi->info.disk_sizep && oi->disk_size < 0)
2309 BUG("Object size is less than zero.");
2311 if (oi->info.contentp) {
2312 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
2313 if (!*obj) {
2314 if (!eaten)
2315 free(oi->content);
2316 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
2317 oid_to_hex(&oi->oid), ref->refname);
2319 grab_values(ref->value, deref, *obj, oi);
2322 grab_common_values(ref->value, deref, oi);
2323 if (!eaten)
2324 free(oi->content);
2325 return 0;
2328 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2330 int i;
2332 for (i = 0; worktrees[i]; i++) {
2333 if (worktrees[i]->head_ref) {
2334 struct ref_to_worktree_entry *entry;
2335 entry = xmalloc(sizeof(*entry));
2336 entry->wt = worktrees[i];
2337 hashmap_entry_init(&entry->ent,
2338 strhash(worktrees[i]->head_ref));
2340 hashmap_add(map, &entry->ent);
2345 static void lazy_init_worktree_map(void)
2347 if (ref_to_worktree_map.worktrees)
2348 return;
2350 ref_to_worktree_map.worktrees = get_worktrees();
2351 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2352 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2355 static char *get_worktree_path(const struct ref_array_item *ref)
2357 struct hashmap_entry entry, *e;
2358 struct ref_to_worktree_entry *lookup_result;
2360 lazy_init_worktree_map();
2362 hashmap_entry_init(&entry, strhash(ref->refname));
2363 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2365 if (!e)
2366 return xstrdup("");
2368 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2370 return xstrdup(lookup_result->wt->path);
2374 * Parse the object referred by ref, and grab needed value.
2376 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2378 struct object *obj;
2379 int i;
2380 struct object_info empty = OBJECT_INFO_INIT;
2381 int ahead_behind_atoms = 0;
2382 int is_base_atoms = 0;
2384 CALLOC_ARRAY(ref->value, used_atom_cnt);
2387 * NEEDSWORK: The following code might be unncessary if all codepaths
2388 * that call populate_value() populates the symref member of ref_array_item
2389 * like in apply_ref_filter(). Currently pretty_print_ref() is the only codepath
2390 * that calls populate_value() without first populating symref.
2392 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2393 ref->symref = refs_resolve_refdup(get_main_ref_store(the_repository),
2394 ref->refname,
2395 RESOLVE_REF_READING,
2396 NULL, NULL);
2397 if (!ref->symref)
2398 ref->symref = xstrdup("");
2401 /* Fill in specials first */
2402 for (i = 0; i < used_atom_cnt; i++) {
2403 struct used_atom *atom = &used_atom[i];
2404 enum atom_type atom_type = atom->atom_type;
2405 const char *name = used_atom[i].name;
2406 struct atom_value *v = &ref->value[i];
2407 int deref = 0;
2408 const char *refname;
2409 struct branch *branch = NULL;
2411 v->s_size = ATOM_SIZE_UNSPECIFIED;
2412 v->handler = append_atom;
2413 v->value = 0;
2414 v->atom = atom;
2416 if (*name == '*') {
2417 deref = 1;
2418 name++;
2421 if (atom_type == ATOM_REFNAME)
2422 refname = get_refname(atom, ref);
2423 else if (atom_type == ATOM_WORKTREEPATH) {
2424 if (ref->kind == FILTER_REFS_BRANCHES)
2425 v->s = get_worktree_path(ref);
2426 else
2427 v->s = xstrdup("");
2428 continue;
2430 else if (atom_type == ATOM_SYMREF)
2431 refname = get_symref(atom, ref);
2432 else if (atom_type == ATOM_UPSTREAM) {
2433 const char *branch_name;
2434 /* only local branches may have an upstream */
2435 if (!skip_prefix(ref->refname, "refs/heads/",
2436 &branch_name)) {
2437 v->s = xstrdup("");
2438 continue;
2440 branch = branch_get(branch_name);
2442 refname = branch_get_upstream(branch, NULL);
2443 if (refname)
2444 fill_remote_ref_details(atom, refname, branch, &v->s);
2445 else
2446 v->s = xstrdup("");
2447 continue;
2448 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2449 const char *branch_name;
2450 v->s = xstrdup("");
2451 if (!skip_prefix(ref->refname, "refs/heads/",
2452 &branch_name))
2453 continue;
2454 branch = branch_get(branch_name);
2456 if (atom->u.remote_ref.push_remote)
2457 refname = NULL;
2458 else {
2459 refname = branch_get_push(branch, NULL);
2460 if (!refname)
2461 continue;
2463 /* We will definitely re-init v->s on the next line. */
2464 free((char *)v->s);
2465 fill_remote_ref_details(atom, refname, branch, &v->s);
2466 continue;
2467 } else if (atom_type == ATOM_COLOR) {
2468 v->s = xstrdup(atom->u.color);
2469 continue;
2470 } else if (atom_type == ATOM_FLAG) {
2471 char buf[256], *cp = buf;
2472 if (ref->flag & REF_ISSYMREF)
2473 cp = copy_advance(cp, ",symref");
2474 if (ref->flag & REF_ISPACKED)
2475 cp = copy_advance(cp, ",packed");
2476 if (cp == buf)
2477 v->s = xstrdup("");
2478 else {
2479 *cp = '\0';
2480 v->s = xstrdup(buf + 1);
2482 continue;
2483 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2484 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2485 continue;
2486 } else if (atom_type == ATOM_HEAD) {
2487 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2488 v->s = xstrdup("*");
2489 else
2490 v->s = xstrdup(" ");
2491 continue;
2492 } else if (atom_type == ATOM_ALIGN) {
2493 v->handler = align_atom_handler;
2494 v->s = xstrdup("");
2495 continue;
2496 } else if (atom_type == ATOM_END) {
2497 v->handler = end_atom_handler;
2498 v->s = xstrdup("");
2499 continue;
2500 } else if (atom_type == ATOM_IF) {
2501 const char *s;
2502 if (skip_prefix(name, "if:", &s))
2503 v->s = xstrdup(s);
2504 else
2505 v->s = xstrdup("");
2506 v->handler = if_atom_handler;
2507 continue;
2508 } else if (atom_type == ATOM_THEN) {
2509 v->handler = then_atom_handler;
2510 v->s = xstrdup("");
2511 continue;
2512 } else if (atom_type == ATOM_ELSE) {
2513 v->handler = else_atom_handler;
2514 v->s = xstrdup("");
2515 continue;
2516 } else if (atom_type == ATOM_REST) {
2517 if (ref->rest)
2518 v->s = xstrdup(ref->rest);
2519 else
2520 v->s = xstrdup("");
2521 continue;
2522 } else if (atom_type == ATOM_AHEADBEHIND) {
2523 if (ref->counts) {
2524 const struct ahead_behind_count *count;
2525 count = ref->counts[ahead_behind_atoms++];
2526 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2527 } else {
2528 /* Not a commit. */
2529 v->s = xstrdup("");
2531 continue;
2532 } else if (atom_type == ATOM_ISBASE) {
2533 if (ref->is_base && ref->is_base[is_base_atoms]) {
2534 v->s = xstrfmt("(%s)", ref->is_base[is_base_atoms]);
2535 free(ref->is_base[is_base_atoms]);
2536 } else {
2537 v->s = xstrdup("");
2539 is_base_atoms++;
2540 continue;
2541 } else
2542 continue;
2544 if (!deref)
2545 v->s = xstrdup(refname);
2546 else
2547 v->s = xstrfmt("%s^{}", refname);
2548 free((char *)refname);
2551 for (i = 0; i < used_atom_cnt; i++) {
2552 struct atom_value *v = &ref->value[i];
2553 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2554 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2555 oid_to_hex(&ref->objectname), ref->refname);
2558 if (need_tagged)
2559 oi.info.contentp = &oi.content;
2560 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2561 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2562 return 0;
2565 oi.oid = ref->objectname;
2566 if (get_object(ref, 0, &obj, &oi, err))
2567 return -1;
2570 * If there is no atom that wants to know about tagged
2571 * object, we are done.
2573 if (!need_tagged || (obj->type != OBJ_TAG))
2574 return 0;
2577 * If it is a tag object, see if we use the peeled value. If we do,
2578 * grab the peeled OID.
2580 if (need_tagged && peel_iterated_oid(the_repository, &obj->oid, &oi_deref.oid))
2581 die("bad tag");
2583 return get_object(ref, 1, &obj, &oi_deref, err);
2587 * Given a ref, return the value for the atom. This lazily gets value
2588 * out of the object by calling populate value.
2590 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2591 struct atom_value **v, struct strbuf *err)
2593 if (!ref->value) {
2594 if (populate_value(ref, err))
2595 return -1;
2596 fill_missing_values(ref->value);
2598 *v = &ref->value[atom];
2599 return 0;
2603 * Return 1 if the refname matches one of the patterns, otherwise 0.
2604 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2605 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2606 * matches "refs/heads/mas*", too).
2608 static int match_pattern(const char **patterns, const char *refname,
2609 int ignore_case)
2611 unsigned flags = 0;
2613 if (ignore_case)
2614 flags |= WM_CASEFOLD;
2617 * When no '--format' option is given we need to skip the prefix
2618 * for matching refs of tags and branches.
2620 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2621 skip_prefix(refname, "refs/heads/", &refname) ||
2622 skip_prefix(refname, "refs/remotes/", &refname) ||
2623 skip_prefix(refname, "refs/", &refname));
2625 for (; *patterns; patterns++) {
2626 if (!wildmatch(*patterns, refname, flags))
2627 return 1;
2629 return 0;
2633 * Return 1 if the refname matches one of the patterns, otherwise 0.
2634 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2635 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2636 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2638 static int match_name_as_path(const char **pattern, const char *refname,
2639 int ignore_case)
2641 int namelen = strlen(refname);
2642 unsigned flags = WM_PATHNAME;
2644 if (ignore_case)
2645 flags |= WM_CASEFOLD;
2647 for (; *pattern; pattern++) {
2648 const char *p = *pattern;
2649 int plen = strlen(p);
2651 if ((plen <= namelen) &&
2652 !strncmp(refname, p, plen) &&
2653 (refname[plen] == '\0' ||
2654 refname[plen] == '/' ||
2655 p[plen-1] == '/'))
2656 return 1;
2657 if (!wildmatch(p, refname, flags))
2658 return 1;
2660 return 0;
2663 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2664 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2666 if (!*filter->name_patterns)
2667 return 1; /* No pattern always matches */
2668 if (filter->match_as_path)
2669 return match_name_as_path(filter->name_patterns, refname,
2670 filter->ignore_case);
2671 return match_pattern(filter->name_patterns, refname,
2672 filter->ignore_case);
2675 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2677 if (!filter->exclude.nr)
2678 return 0;
2679 if (filter->match_as_path)
2680 return match_name_as_path(filter->exclude.v, refname,
2681 filter->ignore_case);
2682 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2686 * This is the same as for_each_fullref_in(), but it tries to iterate
2687 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2688 * pattern match, so the callback still has to match each ref individually.
2690 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2691 each_ref_fn cb,
2692 void *cb_data)
2694 if (filter->kind & FILTER_REFS_ROOT_REFS) {
2695 /* In this case, we want to print all refs including root refs. */
2696 return refs_for_each_include_root_refs(get_main_ref_store(the_repository),
2697 cb, cb_data);
2700 if (!filter->match_as_path) {
2702 * in this case, the patterns are applied after
2703 * prefixes like "refs/heads/" etc. are stripped off,
2704 * so we have to look at everything:
2706 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2707 "", NULL, cb, cb_data);
2710 if (filter->ignore_case) {
2712 * we can't handle case-insensitive comparisons,
2713 * so just return everything and let the caller
2714 * sort it out.
2716 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2717 "", NULL, cb, cb_data);
2720 if (!filter->name_patterns[0]) {
2721 /* no patterns; we have to look at everything */
2722 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2723 "", filter->exclude.v, cb, cb_data);
2726 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2727 NULL, filter->name_patterns,
2728 filter->exclude.v,
2729 cb, cb_data);
2733 * Given a ref (oid, refname), check if the ref belongs to the array
2734 * of oids. If the given ref is a tag, check if the given tag points
2735 * at one of the oids in the given oid array. Returns non-zero if a
2736 * match is found.
2738 * NEEDSWORK:
2739 * As the refs are cached we might know what refname peels to without
2740 * the need to parse the object via parse_object(). peel_ref() might be a
2741 * more efficient alternative to obtain the pointee.
2743 static int match_points_at(struct oid_array *points_at,
2744 const struct object_id *oid,
2745 const char *refname)
2747 struct object *obj;
2749 if (oid_array_lookup(points_at, oid) >= 0)
2750 return 1;
2751 obj = parse_object_with_flags(the_repository, oid,
2752 PARSE_OBJECT_SKIP_HASH_CHECK);
2753 while (obj && obj->type == OBJ_TAG) {
2754 struct tag *tag = (struct tag *)obj;
2756 if (parse_tag(tag) < 0) {
2757 obj = NULL;
2758 break;
2761 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2762 return 1;
2764 obj = tag->tagged;
2766 if (!obj)
2767 die(_("malformed object at '%s'"), refname);
2768 return 0;
2772 * Allocate space for a new ref_array_item and copy the name and oid to it.
2774 * Callers can then fill in other struct members at their leisure.
2776 static struct ref_array_item *new_ref_array_item(const char *refname,
2777 const struct object_id *oid)
2779 struct ref_array_item *ref;
2781 FLEX_ALLOC_STR(ref, refname, refname);
2782 oidcpy(&ref->objectname, oid);
2783 ref->rest = NULL;
2785 return ref;
2788 static void ref_array_append(struct ref_array *array, struct ref_array_item *ref)
2790 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2791 array->items[array->nr++] = ref;
2794 struct ref_array_item *ref_array_push(struct ref_array *array,
2795 const char *refname,
2796 const struct object_id *oid)
2798 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2799 ref_array_append(array, ref);
2800 return ref;
2803 static int ref_kind_from_refname(const char *refname)
2805 unsigned int i;
2807 static struct {
2808 const char *prefix;
2809 unsigned int kind;
2810 } ref_kind[] = {
2811 { "refs/heads/" , FILTER_REFS_BRANCHES },
2812 { "refs/remotes/" , FILTER_REFS_REMOTES },
2813 { "refs/tags/", FILTER_REFS_TAGS}
2816 if (!strcmp(refname, "HEAD"))
2817 return FILTER_REFS_DETACHED_HEAD;
2819 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2820 if (starts_with(refname, ref_kind[i].prefix))
2821 return ref_kind[i].kind;
2824 if (is_pseudo_ref(refname))
2825 return FILTER_REFS_PSEUDOREFS;
2826 if (is_root_ref(refname))
2827 return FILTER_REFS_ROOT_REFS;
2829 return FILTER_REFS_OTHERS;
2832 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2834 if (filter->kind == FILTER_REFS_BRANCHES ||
2835 filter->kind == FILTER_REFS_REMOTES ||
2836 filter->kind == FILTER_REFS_TAGS)
2837 return filter->kind;
2838 return ref_kind_from_refname(refname);
2841 static struct ref_array_item *apply_ref_filter(const char *refname, const char *referent, const struct object_id *oid,
2842 int flag, struct ref_filter *filter)
2844 struct ref_array_item *ref;
2845 struct commit *commit = NULL;
2846 unsigned int kind;
2848 if (flag & REF_BAD_NAME) {
2849 warning(_("ignoring ref with broken name %s"), refname);
2850 return NULL;
2853 if (flag & REF_ISBROKEN) {
2854 warning(_("ignoring broken ref %s"), refname);
2855 return NULL;
2858 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2859 kind = filter_ref_kind(filter, refname);
2862 * Generally HEAD refs are printed with special description denoting a rebase,
2863 * detached state and so forth. This is useful when only printing the HEAD ref
2864 * But when it is being printed along with other root refs, it makes sense to
2865 * keep the formatting consistent. So we mask the type to act like a root ref.
2867 if (filter->kind & FILTER_REFS_ROOT_REFS && kind == FILTER_REFS_DETACHED_HEAD)
2868 kind = FILTER_REFS_ROOT_REFS;
2869 else if (!(kind & filter->kind))
2870 return NULL;
2872 if (!filter_pattern_match(filter, refname))
2873 return NULL;
2875 if (filter_exclude_match(filter, refname))
2876 return NULL;
2878 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2879 return NULL;
2882 * A merge filter is applied on refs pointing to commits. Hence
2883 * obtain the commit using the 'oid' available and discard all
2884 * non-commits early. The actual filtering is done later.
2886 if (filter->reachable_from || filter->unreachable_from ||
2887 filter->with_commit || filter->no_commit || filter->verbose) {
2888 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2889 if (!commit)
2890 return NULL;
2891 /* We perform the filtering for the '--contains' option... */
2892 if (filter->with_commit &&
2893 !commit_contains(filter, commit, filter->with_commit, &filter->internal.contains_cache))
2894 return NULL;
2895 /* ...or for the `--no-contains' option */
2896 if (filter->no_commit &&
2897 commit_contains(filter, commit, filter->no_commit, &filter->internal.no_contains_cache))
2898 return NULL;
2902 * We do not open the object yet; sort may only need refname
2903 * to do its job and the resulting list may yet to be pruned
2904 * by maxcount logic.
2906 ref = new_ref_array_item(refname, oid);
2907 ref->commit = commit;
2908 ref->flag = flag;
2909 ref->kind = kind;
2910 ref->symref = xstrdup_or_null(referent);
2912 return ref;
2915 struct ref_filter_cbdata {
2916 struct ref_array *array;
2917 struct ref_filter *filter;
2921 * A call-back given to for_each_ref(). Filter refs and keep them for
2922 * later object processing.
2924 static int filter_one(const char *refname, const char *referent, const struct object_id *oid, int flag, void *cb_data)
2926 struct ref_filter_cbdata *ref_cbdata = cb_data;
2927 struct ref_array_item *ref;
2929 ref = apply_ref_filter(refname, referent, oid, flag, ref_cbdata->filter);
2930 if (ref)
2931 ref_array_append(ref_cbdata->array, ref);
2933 return 0;
2936 /* Free memory allocated for a ref_array_item */
2937 static void free_array_item(struct ref_array_item *item)
2939 free((char *)item->symref);
2940 if (item->value) {
2941 int i;
2942 for (i = 0; i < used_atom_cnt; i++)
2943 free((char *)item->value[i].s);
2944 free(item->value);
2946 free(item->counts);
2947 free(item->is_base);
2948 free(item);
2951 struct ref_filter_and_format_cbdata {
2952 struct ref_filter *filter;
2953 struct ref_format *format;
2955 struct ref_filter_and_format_internal {
2956 int count;
2957 } internal;
2960 static int filter_and_format_one(const char *refname, const char *referent, const struct object_id *oid, int flag, void *cb_data)
2962 struct ref_filter_and_format_cbdata *ref_cbdata = cb_data;
2963 struct ref_array_item *ref;
2964 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
2966 ref = apply_ref_filter(refname, referent, oid, flag, ref_cbdata->filter);
2967 if (!ref)
2968 return 0;
2970 if (format_ref_array_item(ref, ref_cbdata->format, &output, &err))
2971 die("%s", err.buf);
2973 if (output.len || !ref_cbdata->format->array_opts.omit_empty) {
2974 fwrite(output.buf, 1, output.len, stdout);
2975 putchar('\n');
2978 strbuf_release(&output);
2979 strbuf_release(&err);
2980 free_array_item(ref);
2983 * Increment the running count of refs that match the filter. If
2984 * max_count is set and we've reached the max, stop the ref
2985 * iteration by returning a nonzero value.
2987 if (ref_cbdata->format->array_opts.max_count &&
2988 ++ref_cbdata->internal.count >= ref_cbdata->format->array_opts.max_count)
2989 return 1;
2991 return 0;
2994 /* Free all memory allocated for ref_array */
2995 void ref_array_clear(struct ref_array *array)
2997 int i;
2999 for (i = 0; i < array->nr; i++)
3000 free_array_item(array->items[i]);
3001 FREE_AND_NULL(array->items);
3002 array->nr = array->alloc = 0;
3004 for (i = 0; i < used_atom_cnt; i++) {
3005 struct used_atom *atom = &used_atom[i];
3006 if (atom->atom_type == ATOM_HEAD)
3007 free(atom->u.head);
3008 else if (atom->atom_type == ATOM_DESCRIBE)
3009 strvec_clear(&atom->u.describe_args);
3010 else if (atom->atom_type == ATOM_TRAILERS ||
3011 (atom->atom_type == ATOM_CONTENTS &&
3012 atom->u.contents.option == C_TRAILERS)) {
3013 struct ref_trailer_buf *tb = atom->u.contents.trailer_buf;
3014 if (tb) {
3015 string_list_clear(&tb->filter_list, 0);
3016 strbuf_release(&tb->sepbuf);
3017 strbuf_release(&tb->kvsepbuf);
3018 free(tb);
3021 free((char *)atom->name);
3023 FREE_AND_NULL(used_atom);
3024 used_atom_cnt = 0;
3026 if (ref_to_worktree_map.worktrees) {
3027 hashmap_clear_and_free(&(ref_to_worktree_map.map),
3028 struct ref_to_worktree_entry, ent);
3029 free_worktrees(ref_to_worktree_map.worktrees);
3030 ref_to_worktree_map.worktrees = NULL;
3033 FREE_AND_NULL(array->counts);
3036 #define EXCLUDE_REACHED 0
3037 #define INCLUDE_REACHED 1
3038 static void reach_filter(struct ref_array *array,
3039 struct commit_list **check_reachable,
3040 int include_reached)
3042 int i, old_nr;
3043 struct commit **to_clear;
3045 if (!*check_reachable)
3046 return;
3048 CALLOC_ARRAY(to_clear, array->nr);
3049 for (i = 0; i < array->nr; i++) {
3050 struct ref_array_item *item = array->items[i];
3051 to_clear[i] = item->commit;
3054 tips_reachable_from_bases(the_repository,
3055 *check_reachable,
3056 to_clear, array->nr,
3057 UNINTERESTING);
3059 old_nr = array->nr;
3060 array->nr = 0;
3062 for (i = 0; i < old_nr; i++) {
3063 struct ref_array_item *item = array->items[i];
3064 struct commit *commit = item->commit;
3066 int is_merged = !!(commit->object.flags & UNINTERESTING);
3068 if (is_merged == include_reached)
3069 array->items[array->nr++] = array->items[i];
3070 else
3071 free_array_item(item);
3074 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
3076 while (*check_reachable) {
3077 struct commit *merge_commit = pop_commit(check_reachable);
3078 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
3081 free(to_clear);
3084 void filter_ahead_behind(struct repository *r,
3085 struct ref_format *format,
3086 struct ref_array *array)
3088 struct commit **commits;
3089 size_t commits_nr = format->bases.nr + array->nr;
3091 if (!format->bases.nr || !array->nr)
3092 return;
3094 ALLOC_ARRAY(commits, commits_nr);
3095 for (size_t i = 0; i < format->bases.nr; i++)
3096 commits[i] = format->bases.items[i].util;
3098 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
3100 commits_nr = format->bases.nr;
3101 array->counts_nr = 0;
3102 for (size_t i = 0; i < array->nr; i++) {
3103 const char *name = array->items[i]->refname;
3104 commits[commits_nr] = lookup_commit_reference_by_name(name);
3106 if (!commits[commits_nr])
3107 continue;
3109 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
3110 for (size_t j = 0; j < format->bases.nr; j++) {
3111 struct ahead_behind_count *count;
3112 count = &array->counts[array->counts_nr++];
3113 count->tip_index = commits_nr;
3114 count->base_index = j;
3116 array->items[i]->counts[j] = count;
3118 commits_nr++;
3121 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
3122 free(commits);
3125 void filter_is_base(struct repository *r,
3126 struct ref_format *format,
3127 struct ref_array *array)
3129 struct commit **bases;
3130 size_t bases_nr = 0;
3131 struct ref_array_item **back_index;
3133 if (!format->is_base_tips.nr || !array->nr)
3134 return;
3136 CALLOC_ARRAY(back_index, array->nr);
3137 CALLOC_ARRAY(bases, array->nr);
3139 for (size_t i = 0; i < array->nr; i++) {
3140 const char *name = array->items[i]->refname;
3141 struct commit *c = lookup_commit_reference_by_name_gently(name, 1);
3143 CALLOC_ARRAY(array->items[i]->is_base, format->is_base_tips.nr);
3145 if (!c)
3146 continue;
3148 back_index[bases_nr] = array->items[i];
3149 bases[bases_nr] = c;
3150 bases_nr++;
3153 for (size_t i = 0; i < format->is_base_tips.nr; i++) {
3154 struct commit *tip = format->is_base_tips.items[i].util;
3155 int base_index = get_branch_base_for_tip(r, tip, bases, bases_nr);
3157 if (base_index < 0)
3158 continue;
3160 /* Store the string for use in output later. */
3161 back_index[base_index]->is_base[i] = xstrdup(format->is_base_tips.items[i].string);
3164 free(back_index);
3165 free(bases);
3168 static int do_filter_refs(struct ref_filter *filter, unsigned int type, each_ref_fn fn, void *cb_data)
3170 int ret = 0;
3172 filter->kind = type & FILTER_REFS_KIND_MASK;
3174 init_contains_cache(&filter->internal.contains_cache);
3175 init_contains_cache(&filter->internal.no_contains_cache);
3177 /* Simple per-ref filtering */
3178 if (!filter->kind)
3179 die("filter_refs: invalid type");
3180 else {
3182 * For common cases where we need only branches or remotes or tags,
3183 * we only iterate through those refs. If a mix of refs is needed,
3184 * we iterate over all refs and filter out required refs with the help
3185 * of filter_ref_kind().
3187 if (filter->kind == FILTER_REFS_BRANCHES)
3188 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3189 "refs/heads/", NULL,
3190 fn, cb_data);
3191 else if (filter->kind == FILTER_REFS_REMOTES)
3192 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3193 "refs/remotes/", NULL,
3194 fn, cb_data);
3195 else if (filter->kind == FILTER_REFS_TAGS)
3196 ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),
3197 "refs/tags/", NULL, fn,
3198 cb_data);
3199 else if (filter->kind & FILTER_REFS_REGULAR)
3200 ret = for_each_fullref_in_pattern(filter, fn, cb_data);
3203 * When printing all ref types, HEAD is already included,
3204 * so we don't want to print HEAD again.
3206 if (!ret && !(filter->kind & FILTER_REFS_ROOT_REFS) &&
3207 (filter->kind & FILTER_REFS_DETACHED_HEAD))
3208 refs_head_ref(get_main_ref_store(the_repository), fn,
3209 cb_data);
3212 clear_contains_cache(&filter->internal.contains_cache);
3213 clear_contains_cache(&filter->internal.no_contains_cache);
3215 return ret;
3219 * API for filtering a set of refs. Based on the type of refs the user
3220 * has requested, we iterate through those refs and apply filters
3221 * as per the given ref_filter structure and finally store the
3222 * filtered refs in the ref_array structure.
3224 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
3226 struct ref_filter_cbdata ref_cbdata;
3227 int save_commit_buffer_orig;
3228 int ret = 0;
3230 ref_cbdata.array = array;
3231 ref_cbdata.filter = filter;
3233 save_commit_buffer_orig = save_commit_buffer;
3234 save_commit_buffer = 0;
3236 ret = do_filter_refs(filter, type, filter_one, &ref_cbdata);
3238 /* Filters that need revision walking */
3239 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
3240 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
3242 save_commit_buffer = save_commit_buffer_orig;
3243 return ret;
3246 static inline int can_do_iterative_format(struct ref_filter *filter,
3247 struct ref_sorting *sorting,
3248 struct ref_format *format)
3251 * Filtering & formatting results within a single ref iteration
3252 * callback is not compatible with options that require
3253 * post-processing a filtered ref_array. These include:
3254 * - filtering on reachability
3255 * - sorting the filtered results
3256 * - including ahead-behind information in the formatted output
3258 return !(filter->reachable_from ||
3259 filter->unreachable_from ||
3260 sorting ||
3261 format->bases.nr ||
3262 format->is_base_tips.nr);
3265 void filter_and_format_refs(struct ref_filter *filter, unsigned int type,
3266 struct ref_sorting *sorting,
3267 struct ref_format *format)
3269 if (can_do_iterative_format(filter, sorting, format)) {
3270 int save_commit_buffer_orig;
3271 struct ref_filter_and_format_cbdata ref_cbdata = {
3272 .filter = filter,
3273 .format = format,
3276 save_commit_buffer_orig = save_commit_buffer;
3277 save_commit_buffer = 0;
3279 do_filter_refs(filter, type, filter_and_format_one, &ref_cbdata);
3281 save_commit_buffer = save_commit_buffer_orig;
3282 } else {
3283 struct ref_array array = { 0 };
3284 filter_refs(&array, filter, type);
3285 filter_ahead_behind(the_repository, format, &array);
3286 filter_is_base(the_repository, format, &array);
3287 ref_array_sort(sorting, &array);
3288 print_formatted_ref_array(&array, format);
3289 ref_array_clear(&array);
3293 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
3295 if (!(a->kind ^ b->kind))
3296 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
3297 if (a->kind & FILTER_REFS_DETACHED_HEAD)
3298 return -1;
3299 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
3300 return 1;
3301 BUG("should have died in the xor check above");
3302 return 0;
3305 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
3307 const char *s1 = vs1, *s2 = vs2;
3308 const char *end = s1 + n;
3310 for (; s1 < end; s1++, s2++) {
3311 int diff = tolower(*s1) - tolower(*s2);
3312 if (diff)
3313 return diff;
3315 return 0;
3318 struct ref_sorting {
3319 struct ref_sorting *next;
3320 int atom; /* index into used_atom array (internal) */
3321 enum ref_sorting_order sort_flags;
3324 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
3326 struct atom_value *va, *vb;
3327 int cmp;
3328 int cmp_detached_head = 0;
3329 cmp_type cmp_type = used_atom[s->atom].type;
3330 struct strbuf err = STRBUF_INIT;
3332 if (get_ref_atom_value(a, s->atom, &va, &err))
3333 die("%s", err.buf);
3334 if (get_ref_atom_value(b, s->atom, &vb, &err))
3335 die("%s", err.buf);
3336 strbuf_release(&err);
3337 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
3338 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
3339 cmp = compare_detached_head(a, b);
3340 cmp_detached_head = 1;
3341 } else if (s->sort_flags & REF_SORTING_VERSION) {
3342 cmp = versioncmp(va->s, vb->s);
3343 } else if (cmp_type == FIELD_STR) {
3344 if (va->s_size < 0 && vb->s_size < 0) {
3345 int (*cmp_fn)(const char *, const char *);
3346 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3347 ? strcasecmp : strcmp;
3348 cmp = cmp_fn(va->s, vb->s);
3349 } else {
3350 size_t a_size = va->s_size < 0 ?
3351 strlen(va->s) : va->s_size;
3352 size_t b_size = vb->s_size < 0 ?
3353 strlen(vb->s) : vb->s_size;
3354 int (*cmp_fn)(const void *, const void *, size_t);
3355 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3356 ? memcasecmp : memcmp;
3358 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3359 a_size : b_size);
3360 if (!cmp) {
3361 if (a_size > b_size)
3362 cmp = 1;
3363 else if (a_size < b_size)
3364 cmp = -1;
3367 } else {
3368 if (va->value < vb->value)
3369 cmp = -1;
3370 else if (va->value == vb->value)
3371 cmp = 0;
3372 else
3373 cmp = 1;
3376 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3377 ? -cmp : cmp;
3380 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3382 struct ref_array_item *a = *((struct ref_array_item **)a_);
3383 struct ref_array_item *b = *((struct ref_array_item **)b_);
3384 struct ref_sorting *s;
3386 for (s = ref_sorting; s; s = s->next) {
3387 int cmp = cmp_ref_sorting(s, a, b);
3388 if (cmp)
3389 return cmp;
3391 s = ref_sorting;
3392 return s && s->sort_flags & REF_SORTING_ICASE ?
3393 strcasecmp(a->refname, b->refname) :
3394 strcmp(a->refname, b->refname);
3397 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3398 unsigned int mask, int on)
3400 for (; sorting; sorting = sorting->next) {
3401 if (on)
3402 sorting->sort_flags |= mask;
3403 else
3404 sorting->sort_flags &= ~mask;
3408 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3410 if (sorting)
3411 QSORT_S(array->items, array->nr, compare_refs, sorting);
3414 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3416 struct strbuf *s = &state->stack->output;
3418 while (*cp && (!ep || cp < ep)) {
3419 if (*cp == '%') {
3420 if (cp[1] == '%')
3421 cp++;
3422 else {
3423 int ch = hex2chr(cp + 1);
3424 if (0 <= ch) {
3425 strbuf_addch(s, ch);
3426 cp += 3;
3427 continue;
3431 strbuf_addch(s, *cp);
3432 cp++;
3436 int format_ref_array_item(struct ref_array_item *info,
3437 struct ref_format *format,
3438 struct strbuf *final_buf,
3439 struct strbuf *error_buf)
3441 const char *cp, *sp, *ep;
3442 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3444 state.quote_style = format->quote_style;
3445 push_stack_element(&state.stack);
3447 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3448 struct atom_value *atomv;
3449 int pos;
3451 ep = strchr(sp, ')');
3452 if (cp < sp)
3453 append_literal(cp, sp, &state);
3454 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3455 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3456 atomv->handler(atomv, &state, error_buf)) {
3457 pop_stack_element(&state.stack);
3458 return -1;
3461 if (*cp) {
3462 sp = cp + strlen(cp);
3463 append_literal(cp, sp, &state);
3465 if (format->need_color_reset_at_eol) {
3466 struct atom_value resetv = ATOM_VALUE_INIT;
3467 resetv.s = GIT_COLOR_RESET;
3468 if (append_atom(&resetv, &state, error_buf)) {
3469 pop_stack_element(&state.stack);
3470 return -1;
3473 if (state.stack->prev) {
3474 pop_stack_element(&state.stack);
3475 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3477 strbuf_addbuf(final_buf, &state.stack->output);
3478 pop_stack_element(&state.stack);
3479 return 0;
3482 void print_formatted_ref_array(struct ref_array *array, struct ref_format *format)
3484 int total;
3485 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3487 total = format->array_opts.max_count;
3488 if (!total || array->nr < total)
3489 total = array->nr;
3490 for (int i = 0; i < total; i++) {
3491 strbuf_reset(&err);
3492 strbuf_reset(&output);
3493 if (format_ref_array_item(array->items[i], format, &output, &err))
3494 die("%s", err.buf);
3495 if (output.len || !format->array_opts.omit_empty) {
3496 fwrite(output.buf, 1, output.len, stdout);
3497 putchar('\n');
3501 strbuf_release(&err);
3502 strbuf_release(&output);
3505 void pretty_print_ref(const char *name, const struct object_id *oid,
3506 struct ref_format *format)
3508 struct ref_array_item *ref_item;
3509 struct strbuf output = STRBUF_INIT;
3510 struct strbuf err = STRBUF_INIT;
3512 ref_item = new_ref_array_item(name, oid);
3513 ref_item->kind = ref_kind_from_refname(name);
3514 if (format_ref_array_item(ref_item, format, &output, &err))
3515 die("%s", err.buf);
3516 fwrite(output.buf, 1, output.len, stdout);
3517 putchar('\n');
3519 strbuf_release(&err);
3520 strbuf_release(&output);
3521 free_array_item(ref_item);
3524 static int parse_sorting_atom(const char *atom)
3527 * This parses an atom using a dummy ref_format, since we don't
3528 * actually care about the formatting details.
3530 struct ref_format dummy = REF_FORMAT_INIT;
3531 const char *end = atom + strlen(atom);
3532 struct strbuf err = STRBUF_INIT;
3533 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3534 if (res < 0)
3535 die("%s", err.buf);
3536 strbuf_release(&err);
3537 return res;
3540 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3542 struct ref_sorting *s;
3544 CALLOC_ARRAY(s, 1);
3545 s->next = *sorting_tail;
3546 *sorting_tail = s;
3548 if (*arg == '-') {
3549 s->sort_flags |= REF_SORTING_REVERSE;
3550 arg++;
3552 if (skip_prefix(arg, "version:", &arg) ||
3553 skip_prefix(arg, "v:", &arg))
3554 s->sort_flags |= REF_SORTING_VERSION;
3555 s->atom = parse_sorting_atom(arg);
3558 struct ref_sorting *ref_sorting_options(struct string_list *options)
3560 struct string_list_item *item;
3561 struct ref_sorting *sorting = NULL, **tail = &sorting;
3563 if (options->nr) {
3564 for_each_string_list_item(item, options)
3565 parse_ref_sorting(tail, item->string);
3569 * From here on, the ref_sorting list should be used to talk
3570 * about the sort order used for the output. The caller
3571 * should not touch the string form anymore.
3573 string_list_clear(options, 0);
3574 return sorting;
3577 void ref_sorting_release(struct ref_sorting *sorting)
3579 while (sorting) {
3580 struct ref_sorting *next = sorting->next;
3581 free(sorting);
3582 sorting = next;
3586 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3588 struct ref_filter *rf = opt->value;
3589 struct object_id oid;
3590 struct commit *merge_commit;
3592 BUG_ON_OPT_NEG(unset);
3594 if (repo_get_oid(the_repository, arg, &oid))
3595 die(_("malformed object name %s"), arg);
3597 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3599 if (!merge_commit)
3600 return error(_("option `%s' must point to a commit"), opt->long_name);
3602 if (starts_with(opt->long_name, "no"))
3603 commit_list_insert(merge_commit, &rf->unreachable_from);
3604 else
3605 commit_list_insert(merge_commit, &rf->reachable_from);
3607 return 0;
3610 void ref_filter_init(struct ref_filter *filter)
3612 struct ref_filter blank = REF_FILTER_INIT;
3613 memcpy(filter, &blank, sizeof(blank));
3616 void ref_filter_clear(struct ref_filter *filter)
3618 strvec_clear(&filter->exclude);
3619 oid_array_clear(&filter->points_at);
3620 free_commit_list(filter->with_commit);
3621 free_commit_list(filter->no_commit);
3622 free_commit_list(filter->reachable_from);
3623 free_commit_list(filter->unreachable_from);
3624 ref_filter_init(filter);
3627 void ref_format_init(struct ref_format *format)
3629 struct ref_format blank = REF_FORMAT_INIT;
3630 memcpy(format, &blank, sizeof(blank));
3633 void ref_format_clear(struct ref_format *format)
3635 string_list_clear(&format->bases, 0);
3636 string_list_clear(&format->is_base_tips, 0);
3637 ref_format_init(format);