debian: new upstream release
[git/debian.git] / ref-filter.c
blobe4d3510e28e15a7ff967737f08a8c1acadb588e1
1 #include "git-compat-util.h"
2 #include "environment.h"
3 #include "gettext.h"
4 #include "config.h"
5 #include "gpg-interface.h"
6 #include "hex.h"
7 #include "parse-options.h"
8 #include "run-command.h"
9 #include "refs.h"
10 #include "wildmatch.h"
11 #include "object-name.h"
12 #include "object-store-ll.h"
13 #include "oid-array.h"
14 #include "repository.h"
15 #include "commit.h"
16 #include "mailmap.h"
17 #include "ident.h"
18 #include "remote.h"
19 #include "color.h"
20 #include "tag.h"
21 #include "quote.h"
22 #include "ref-filter.h"
23 #include "revision.h"
24 #include "utf8.h"
25 #include "version.h"
26 #include "versioncmp.h"
27 #include "trailer.h"
28 #include "wt-status.h"
29 #include "commit-slab.h"
30 #include "commit-graph.h"
31 #include "commit-reach.h"
32 #include "worktree.h"
33 #include "hashmap.h"
34 #include "strvec.h"
36 static struct ref_msg {
37 const char *gone;
38 const char *ahead;
39 const char *behind;
40 const char *ahead_behind;
41 } msgs = {
42 /* Untranslated plumbing messages: */
43 "gone",
44 "ahead %d",
45 "behind %d",
46 "ahead %d, behind %d"
49 void setup_ref_filter_porcelain_msg(void)
51 msgs.gone = _("gone");
52 msgs.ahead = _("ahead %d");
53 msgs.behind = _("behind %d");
54 msgs.ahead_behind = _("ahead %d, behind %d");
57 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
58 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
59 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
61 struct align {
62 align_type position;
63 unsigned int width;
66 struct if_then_else {
67 cmp_status cmp_status;
68 const char *str;
69 unsigned int then_atom_seen : 1,
70 else_atom_seen : 1,
71 condition_satisfied : 1;
74 struct refname_atom {
75 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
76 int lstrip, rstrip;
79 static struct ref_trailer_buf {
80 struct string_list filter_list;
81 struct strbuf sepbuf;
82 struct strbuf kvsepbuf;
83 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
85 static struct expand_data {
86 struct object_id oid;
87 enum object_type type;
88 unsigned long size;
89 off_t disk_size;
90 struct object_id delta_base_oid;
91 void *content;
93 struct object_info info;
94 } oi, oi_deref;
96 struct ref_to_worktree_entry {
97 struct hashmap_entry ent;
98 struct worktree *wt; /* key is wt->head_ref */
101 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
102 const struct hashmap_entry *eptr,
103 const struct hashmap_entry *kptr,
104 const void *keydata_aka_refname)
106 const struct ref_to_worktree_entry *e, *k;
108 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
109 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
111 return strcmp(e->wt->head_ref,
112 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
115 static struct ref_to_worktree_map {
116 struct hashmap map;
117 struct worktree **worktrees;
118 } ref_to_worktree_map;
121 * The enum atom_type is used as the index of valid_atom array.
122 * In the atom parsing stage, it will be passed to used_atom.atom_type
123 * as the identifier of the atom type. We can check the type of used_atom
124 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
126 enum atom_type {
127 ATOM_REFNAME,
128 ATOM_OBJECTTYPE,
129 ATOM_OBJECTSIZE,
130 ATOM_OBJECTNAME,
131 ATOM_DELTABASE,
132 ATOM_TREE,
133 ATOM_PARENT,
134 ATOM_NUMPARENT,
135 ATOM_OBJECT,
136 ATOM_TYPE,
137 ATOM_TAG,
138 ATOM_AUTHOR,
139 ATOM_AUTHORNAME,
140 ATOM_AUTHOREMAIL,
141 ATOM_AUTHORDATE,
142 ATOM_COMMITTER,
143 ATOM_COMMITTERNAME,
144 ATOM_COMMITTEREMAIL,
145 ATOM_COMMITTERDATE,
146 ATOM_TAGGER,
147 ATOM_TAGGERNAME,
148 ATOM_TAGGEREMAIL,
149 ATOM_TAGGERDATE,
150 ATOM_CREATOR,
151 ATOM_CREATORDATE,
152 ATOM_DESCRIBE,
153 ATOM_SUBJECT,
154 ATOM_BODY,
155 ATOM_TRAILERS,
156 ATOM_CONTENTS,
157 ATOM_SIGNATURE,
158 ATOM_RAW,
159 ATOM_UPSTREAM,
160 ATOM_PUSH,
161 ATOM_SYMREF,
162 ATOM_FLAG,
163 ATOM_HEAD,
164 ATOM_COLOR,
165 ATOM_WORKTREEPATH,
166 ATOM_ALIGN,
167 ATOM_END,
168 ATOM_IF,
169 ATOM_THEN,
170 ATOM_ELSE,
171 ATOM_REST,
172 ATOM_AHEADBEHIND,
176 * An atom is a valid field atom listed below, possibly prefixed with
177 * a "*" to denote deref_tag().
179 * We parse given format string and sort specifiers, and make a list
180 * of properties that we need to extract out of objects. ref_array_item
181 * structure will hold an array of values extracted that can be
182 * indexed with the "atom number", which is an index into this
183 * array.
185 static struct used_atom {
186 enum atom_type atom_type;
187 const char *name;
188 cmp_type type;
189 info_source source;
190 union {
191 char color[COLOR_MAXLEN];
192 struct align align;
193 struct {
194 enum {
195 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
196 } option;
197 struct refname_atom refname;
198 unsigned int nobracket : 1, push : 1, push_remote : 1;
199 } remote_ref;
200 struct {
201 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
202 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
203 struct process_trailer_options trailer_opts;
204 unsigned int nlines;
205 } contents;
206 struct {
207 enum { RAW_BARE, RAW_LENGTH } option;
208 } raw_data;
209 struct {
210 cmp_status cmp_status;
211 const char *str;
212 } if_then_else;
213 struct {
214 enum { O_FULL, O_LENGTH, O_SHORT } option;
215 unsigned int length;
216 } oid;
217 struct {
218 enum { O_SIZE, O_SIZE_DISK } option;
219 } objectsize;
220 struct {
221 enum { N_RAW, N_MAILMAP } option;
222 } name_option;
223 struct {
224 enum {
225 EO_RAW = 0,
226 EO_TRIM = 1<<0,
227 EO_LOCALPART = 1<<1,
228 EO_MAILMAP = 1<<2,
229 } option;
230 } email_option;
231 struct {
232 enum { S_BARE, S_GRADE, S_SIGNER, S_KEY,
233 S_FINGERPRINT, S_PRI_KEY_FP, S_TRUST_LEVEL } option;
234 } signature;
235 const char **describe_args;
236 struct refname_atom refname;
237 char *head;
238 } u;
239 } *used_atom;
240 static int used_atom_cnt, need_tagged, need_symref;
243 * Expand string, append it to strbuf *sb, then return error code ret.
244 * Allow to save few lines of code.
246 __attribute__((format (printf, 3, 4)))
247 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
249 va_list ap;
250 va_start(ap, fmt);
251 strbuf_vaddf(sb, fmt, ap);
252 va_end(ap);
253 return ret;
256 static int err_no_arg(struct strbuf *sb, const char *name)
258 size_t namelen = strchrnul(name, ':') - name;
259 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
260 (int)namelen, name);
261 return -1;
264 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
266 size_t namelen = strchrnul(name, ':') - name;
267 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
268 (int)namelen, name, arg);
269 return -1;
273 * Parse option of name "candidate" in the option string "to_parse" of
274 * the form
276 * "candidate1[=val1],candidate2[=val2],candidate3[=val3],..."
278 * The remaining part of "to_parse" is stored in "end" (if we are
279 * parsing the last candidate, then this is NULL) and the value of
280 * the candidate is stored in "valuestart" and its length in "valuelen",
281 * that is the portion after "=". Since it is possible for a "candidate"
282 * to not have a value, in such cases, "valuestart" is set to point to
283 * NULL and "valuelen" to 0.
285 * The function returns 1 on success. It returns 0 if we don't find
286 * "candidate" in "to_parse" or we find "candidate" but it is followed
287 * by more chars (for example, "candidatefoo"), that is, we don't find
288 * an exact match.
290 * This function only does the above for one "candidate" at a time. So
291 * it has to be called each time trying to parse a "candidate" in the
292 * option string "to_parse".
294 static int match_atom_arg_value(const char *to_parse, const char *candidate,
295 const char **end, const char **valuestart,
296 size_t *valuelen)
298 const char *atom;
300 if (!skip_prefix(to_parse, candidate, &atom))
301 return 0; /* definitely not "candidate" */
303 if (*atom == '=') {
304 /* we just saw "candidate=" */
305 *valuestart = atom + 1;
306 atom = strchrnul(*valuestart, ',');
307 *valuelen = atom - *valuestart;
308 } else if (*atom != ',' && *atom != '\0') {
309 /* key begins with "candidate" but has more chars */
310 return 0;
311 } else {
312 /* just "candidate" without "=val" */
313 *valuestart = NULL;
314 *valuelen = 0;
317 /* atom points at either the ',' or NUL after this key[=val] */
318 if (*atom == ',')
319 atom++;
320 else if (*atom)
321 BUG("Why is *atom not NULL yet?");
323 *end = atom;
324 return 1;
328 * Parse boolean option of name "candidate" in the option list "to_parse"
329 * of the form
331 * "candidate1[=bool1],candidate2[=bool2],candidate3[=bool3],..."
333 * The remaining part of "to_parse" is stored in "end" (if we are parsing
334 * the last candidate, then this is NULL) and the value (if given) is
335 * parsed and stored in "val", so "val" always points to either 0 or 1.
336 * If the value is not given, then "val" is set to point to 1.
338 * The boolean value is parsed using "git_parse_maybe_bool()", so the
339 * accepted values are
341 * to set true - "1", "yes", "true"
342 * to set false - "0", "no", "false"
344 * This function returns 1 on success. It returns 0 when we don't find
345 * an exact match for "candidate" or when the boolean value given is
346 * not valid.
348 static int match_atom_bool_arg(const char *to_parse, const char *candidate,
349 const char **end, int *val)
351 const char *argval;
352 char *strval;
353 size_t arglen;
354 int v;
356 if (!match_atom_arg_value(to_parse, candidate, end, &argval, &arglen))
357 return 0;
359 if (!argval) {
360 *val = 1;
361 return 1;
364 strval = xstrndup(argval, arglen);
365 v = git_parse_maybe_bool(strval);
366 free(strval);
368 if (v == -1)
369 return 0;
371 *val = v;
373 return 1;
376 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
377 const char *color_value, struct strbuf *err)
379 if (!color_value)
380 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
381 if (color_parse(color_value, atom->u.color) < 0)
382 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
383 color_value);
385 * We check this after we've parsed the color, which lets us complain
386 * about syntactically bogus color names even if they won't be used.
388 if (!want_color(format->use_color))
389 color_parse("", atom->u.color);
390 return 0;
393 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
394 const char *name, struct strbuf *err)
396 if (!arg)
397 atom->option = R_NORMAL;
398 else if (!strcmp(arg, "short"))
399 atom->option = R_SHORT;
400 else if (skip_prefix(arg, "lstrip=", &arg) ||
401 skip_prefix(arg, "strip=", &arg)) {
402 atom->option = R_LSTRIP;
403 if (strtol_i(arg, 10, &atom->lstrip))
404 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
405 } else if (skip_prefix(arg, "rstrip=", &arg)) {
406 atom->option = R_RSTRIP;
407 if (strtol_i(arg, 10, &atom->rstrip))
408 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
409 } else
410 return err_bad_arg(err, name, arg);
411 return 0;
414 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
415 struct used_atom *atom,
416 const char *arg, struct strbuf *err)
418 struct string_list params = STRING_LIST_INIT_DUP;
419 int i;
421 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
422 atom->u.remote_ref.push = 1;
424 if (!arg) {
425 atom->u.remote_ref.option = RR_REF;
426 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
427 arg, atom->name, err);
430 atom->u.remote_ref.nobracket = 0;
431 string_list_split(&params, arg, ',', -1);
433 for (i = 0; i < params.nr; i++) {
434 const char *s = params.items[i].string;
436 if (!strcmp(s, "track"))
437 atom->u.remote_ref.option = RR_TRACK;
438 else if (!strcmp(s, "trackshort"))
439 atom->u.remote_ref.option = RR_TRACKSHORT;
440 else if (!strcmp(s, "nobracket"))
441 atom->u.remote_ref.nobracket = 1;
442 else if (!strcmp(s, "remotename")) {
443 atom->u.remote_ref.option = RR_REMOTE_NAME;
444 atom->u.remote_ref.push_remote = 1;
445 } else if (!strcmp(s, "remoteref")) {
446 atom->u.remote_ref.option = RR_REMOTE_REF;
447 atom->u.remote_ref.push_remote = 1;
448 } else {
449 atom->u.remote_ref.option = RR_REF;
450 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
451 arg, atom->name, err)) {
452 string_list_clear(&params, 0);
453 return -1;
458 string_list_clear(&params, 0);
459 return 0;
462 static int objecttype_atom_parser(struct ref_format *format UNUSED,
463 struct used_atom *atom,
464 const char *arg, struct strbuf *err)
466 if (arg)
467 return err_no_arg(err, "objecttype");
468 if (*atom->name == '*')
469 oi_deref.info.typep = &oi_deref.type;
470 else
471 oi.info.typep = &oi.type;
472 return 0;
475 static int objectsize_atom_parser(struct ref_format *format UNUSED,
476 struct used_atom *atom,
477 const char *arg, struct strbuf *err)
479 if (!arg) {
480 atom->u.objectsize.option = O_SIZE;
481 if (*atom->name == '*')
482 oi_deref.info.sizep = &oi_deref.size;
483 else
484 oi.info.sizep = &oi.size;
485 } else if (!strcmp(arg, "disk")) {
486 atom->u.objectsize.option = O_SIZE_DISK;
487 if (*atom->name == '*')
488 oi_deref.info.disk_sizep = &oi_deref.disk_size;
489 else
490 oi.info.disk_sizep = &oi.disk_size;
491 } else
492 return err_bad_arg(err, "objectsize", arg);
493 return 0;
496 static int deltabase_atom_parser(struct ref_format *format UNUSED,
497 struct used_atom *atom,
498 const char *arg, struct strbuf *err)
500 if (arg)
501 return err_no_arg(err, "deltabase");
502 if (*atom->name == '*')
503 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
504 else
505 oi.info.delta_base_oid = &oi.delta_base_oid;
506 return 0;
509 static int body_atom_parser(struct ref_format *format UNUSED,
510 struct used_atom *atom,
511 const char *arg, struct strbuf *err)
513 if (arg)
514 return err_no_arg(err, "body");
515 atom->u.contents.option = C_BODY_DEP;
516 return 0;
519 static int subject_atom_parser(struct ref_format *format UNUSED,
520 struct used_atom *atom,
521 const char *arg, struct strbuf *err)
523 if (!arg)
524 atom->u.contents.option = C_SUB;
525 else if (!strcmp(arg, "sanitize"))
526 atom->u.contents.option = C_SUB_SANITIZE;
527 else
528 return err_bad_arg(err, "subject", arg);
529 return 0;
532 static int parse_signature_option(const char *arg)
534 if (!arg)
535 return S_BARE;
536 else if (!strcmp(arg, "signer"))
537 return S_SIGNER;
538 else if (!strcmp(arg, "grade"))
539 return S_GRADE;
540 else if (!strcmp(arg, "key"))
541 return S_KEY;
542 else if (!strcmp(arg, "fingerprint"))
543 return S_FINGERPRINT;
544 else if (!strcmp(arg, "primarykeyfingerprint"))
545 return S_PRI_KEY_FP;
546 else if (!strcmp(arg, "trustlevel"))
547 return S_TRUST_LEVEL;
548 return -1;
551 static int signature_atom_parser(struct ref_format *format UNUSED,
552 struct used_atom *atom,
553 const char *arg, struct strbuf *err)
555 int opt = parse_signature_option(arg);
556 if (opt < 0)
557 return err_bad_arg(err, "signature", arg);
558 atom->u.signature.option = opt;
559 return 0;
562 static int trailers_atom_parser(struct ref_format *format UNUSED,
563 struct used_atom *atom,
564 const char *arg, struct strbuf *err)
566 atom->u.contents.trailer_opts.no_divider = 1;
568 if (arg) {
569 const char *argbuf = xstrfmt("%s)", arg);
570 char *invalid_arg = NULL;
572 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
573 &ref_trailer_buf.filter_list,
574 &ref_trailer_buf.sepbuf,
575 &ref_trailer_buf.kvsepbuf,
576 &argbuf, &invalid_arg)) {
577 if (!invalid_arg)
578 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
579 else
580 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
581 free((char *)invalid_arg);
582 return -1;
585 atom->u.contents.option = C_TRAILERS;
586 return 0;
589 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
590 const char *arg, struct strbuf *err)
592 if (!arg)
593 atom->u.contents.option = C_BARE;
594 else if (!strcmp(arg, "body"))
595 atom->u.contents.option = C_BODY;
596 else if (!strcmp(arg, "size")) {
597 atom->type = FIELD_ULONG;
598 atom->u.contents.option = C_LENGTH;
599 } else if (!strcmp(arg, "signature"))
600 atom->u.contents.option = C_SIG;
601 else if (!strcmp(arg, "subject"))
602 atom->u.contents.option = C_SUB;
603 else if (!strcmp(arg, "trailers")) {
604 if (trailers_atom_parser(format, atom, NULL, err))
605 return -1;
606 } else if (skip_prefix(arg, "trailers:", &arg)) {
607 if (trailers_atom_parser(format, atom, arg, err))
608 return -1;
609 } else if (skip_prefix(arg, "lines=", &arg)) {
610 atom->u.contents.option = C_LINES;
611 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
612 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
613 } else
614 return err_bad_arg(err, "contents", arg);
615 return 0;
618 static int describe_atom_option_parser(struct strvec *args, const char **arg,
619 struct strbuf *err)
621 const char *argval;
622 size_t arglen = 0;
623 int optval = 0;
625 if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {
626 if (!optval)
627 strvec_push(args, "--no-tags");
628 else
629 strvec_push(args, "--tags");
630 return 1;
633 if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {
634 char *endptr;
636 if (!arglen)
637 return strbuf_addf_ret(err, -1,
638 _("argument expected for %s"),
639 "describe:abbrev");
640 if (strtol(argval, &endptr, 10) < 0)
641 return strbuf_addf_ret(err, -1,
642 _("positive value expected %s=%s"),
643 "describe:abbrev", argval);
644 if (endptr - argval != arglen)
645 return strbuf_addf_ret(err, -1,
646 _("cannot fully parse %s=%s"),
647 "describe:abbrev", argval);
649 strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);
650 return 1;
653 if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {
654 if (!arglen)
655 return strbuf_addf_ret(err, -1,
656 _("value expected %s="),
657 "describe:match");
659 strvec_pushf(args, "--match=%.*s", (int)arglen, argval);
660 return 1;
663 if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {
664 if (!arglen)
665 return strbuf_addf_ret(err, -1,
666 _("value expected %s="),
667 "describe:exclude");
669 strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);
670 return 1;
673 return 0;
676 static int describe_atom_parser(struct ref_format *format UNUSED,
677 struct used_atom *atom,
678 const char *arg, struct strbuf *err)
680 struct strvec args = STRVEC_INIT;
682 for (;;) {
683 int found = 0;
684 const char *bad_arg = arg;
686 if (!arg || !*arg)
687 break;
689 found = describe_atom_option_parser(&args, &arg, err);
690 if (found < 0)
691 return found;
692 if (!found)
693 return err_bad_arg(err, "describe", bad_arg);
695 atom->u.describe_args = strvec_detach(&args);
696 return 0;
699 static int raw_atom_parser(struct ref_format *format UNUSED,
700 struct used_atom *atom,
701 const char *arg, struct strbuf *err)
703 if (!arg)
704 atom->u.raw_data.option = RAW_BARE;
705 else if (!strcmp(arg, "size")) {
706 atom->type = FIELD_ULONG;
707 atom->u.raw_data.option = RAW_LENGTH;
708 } else
709 return err_bad_arg(err, "raw", arg);
710 return 0;
713 static int oid_atom_parser(struct ref_format *format UNUSED,
714 struct used_atom *atom,
715 const char *arg, struct strbuf *err)
717 if (!arg)
718 atom->u.oid.option = O_FULL;
719 else if (!strcmp(arg, "short"))
720 atom->u.oid.option = O_SHORT;
721 else if (skip_prefix(arg, "short=", &arg)) {
722 atom->u.oid.option = O_LENGTH;
723 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
724 atom->u.oid.length == 0)
725 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
726 if (atom->u.oid.length < MINIMUM_ABBREV)
727 atom->u.oid.length = MINIMUM_ABBREV;
728 } else
729 return err_bad_arg(err, atom->name, arg);
730 return 0;
733 static int person_name_atom_parser(struct ref_format *format UNUSED,
734 struct used_atom *atom,
735 const char *arg, struct strbuf *err)
737 if (!arg)
738 atom->u.name_option.option = N_RAW;
739 else if (!strcmp(arg, "mailmap"))
740 atom->u.name_option.option = N_MAILMAP;
741 else
742 return err_bad_arg(err, atom->name, arg);
743 return 0;
746 static int email_atom_option_parser(struct used_atom *atom,
747 const char **arg, struct strbuf *err)
749 if (!*arg)
750 return EO_RAW;
751 if (skip_prefix(*arg, "trim", arg))
752 return EO_TRIM;
753 if (skip_prefix(*arg, "localpart", arg))
754 return EO_LOCALPART;
755 if (skip_prefix(*arg, "mailmap", arg))
756 return EO_MAILMAP;
757 return -1;
760 static int person_email_atom_parser(struct ref_format *format UNUSED,
761 struct used_atom *atom,
762 const char *arg, struct strbuf *err)
764 for (;;) {
765 int opt = email_atom_option_parser(atom, &arg, err);
766 const char *bad_arg = arg;
768 if (opt < 0)
769 return err_bad_arg(err, atom->name, bad_arg);
770 atom->u.email_option.option |= opt;
772 if (!arg || !*arg)
773 break;
774 if (*arg == ',')
775 arg++;
776 else
777 return err_bad_arg(err, atom->name, bad_arg);
779 return 0;
782 static int refname_atom_parser(struct ref_format *format UNUSED,
783 struct used_atom *atom,
784 const char *arg, struct strbuf *err)
786 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
789 static align_type parse_align_position(const char *s)
791 if (!strcmp(s, "right"))
792 return ALIGN_RIGHT;
793 else if (!strcmp(s, "middle"))
794 return ALIGN_MIDDLE;
795 else if (!strcmp(s, "left"))
796 return ALIGN_LEFT;
797 return -1;
800 static int align_atom_parser(struct ref_format *format UNUSED,
801 struct used_atom *atom,
802 const char *arg, struct strbuf *err)
804 struct align *align = &atom->u.align;
805 struct string_list params = STRING_LIST_INIT_DUP;
806 int i;
807 unsigned int width = ~0U;
809 if (!arg)
810 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
812 align->position = ALIGN_LEFT;
814 string_list_split(&params, arg, ',', -1);
815 for (i = 0; i < params.nr; i++) {
816 const char *s = params.items[i].string;
817 int position;
819 if (skip_prefix(s, "position=", &s)) {
820 position = parse_align_position(s);
821 if (position < 0) {
822 strbuf_addf(err, _("unrecognized position:%s"), s);
823 string_list_clear(&params, 0);
824 return -1;
826 align->position = position;
827 } else if (skip_prefix(s, "width=", &s)) {
828 if (strtoul_ui(s, 10, &width)) {
829 strbuf_addf(err, _("unrecognized width:%s"), s);
830 string_list_clear(&params, 0);
831 return -1;
833 } else if (!strtoul_ui(s, 10, &width))
835 else if ((position = parse_align_position(s)) >= 0)
836 align->position = position;
837 else {
838 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
839 string_list_clear(&params, 0);
840 return -1;
844 if (width == ~0U) {
845 string_list_clear(&params, 0);
846 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
848 align->width = width;
849 string_list_clear(&params, 0);
850 return 0;
853 static int if_atom_parser(struct ref_format *format UNUSED,
854 struct used_atom *atom,
855 const char *arg, struct strbuf *err)
857 if (!arg) {
858 atom->u.if_then_else.cmp_status = COMPARE_NONE;
859 return 0;
860 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
861 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
862 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
863 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
864 } else
865 return err_bad_arg(err, "if", arg);
866 return 0;
869 static int rest_atom_parser(struct ref_format *format UNUSED,
870 struct used_atom *atom UNUSED,
871 const char *arg, struct strbuf *err)
873 if (arg)
874 return err_no_arg(err, "rest");
875 return 0;
878 static int ahead_behind_atom_parser(struct ref_format *format,
879 struct used_atom *atom UNUSED,
880 const char *arg, struct strbuf *err)
882 struct string_list_item *item;
884 if (!arg)
885 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
887 item = string_list_append(&format->bases, arg);
888 item->util = lookup_commit_reference_by_name(arg);
889 if (!item->util)
890 die("failed to find '%s'", arg);
892 return 0;
895 static int head_atom_parser(struct ref_format *format UNUSED,
896 struct used_atom *atom,
897 const char *arg, struct strbuf *err)
899 if (arg)
900 return err_no_arg(err, "HEAD");
901 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
902 return 0;
905 static struct {
906 const char *name;
907 info_source source;
908 cmp_type cmp_type;
909 int (*parser)(struct ref_format *format, struct used_atom *atom,
910 const char *arg, struct strbuf *err);
911 } valid_atom[] = {
912 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
913 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
914 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
915 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
916 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
917 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
918 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
919 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
920 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
921 [ATOM_TYPE] = { "type", SOURCE_OBJ },
922 [ATOM_TAG] = { "tag", SOURCE_OBJ },
923 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
924 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
925 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
926 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
927 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
928 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
929 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
930 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
931 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
932 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
933 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
934 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
935 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
936 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
937 [ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },
938 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
939 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
940 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
941 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
942 [ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },
943 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
944 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
945 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
946 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
947 [ATOM_FLAG] = { "flag", SOURCE_NONE },
948 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
949 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
950 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
951 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
952 [ATOM_END] = { "end", SOURCE_NONE },
953 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
954 [ATOM_THEN] = { "then", SOURCE_NONE },
955 [ATOM_ELSE] = { "else", SOURCE_NONE },
956 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
957 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
959 * Please update $__git_ref_fieldlist in git-completion.bash
960 * when you add new atoms
964 #define REF_FORMATTING_STATE_INIT { 0 }
966 struct ref_formatting_stack {
967 struct ref_formatting_stack *prev;
968 struct strbuf output;
969 void (*at_end)(struct ref_formatting_stack **stack);
970 void *at_end_data;
973 struct ref_formatting_state {
974 int quote_style;
975 struct ref_formatting_stack *stack;
978 struct atom_value {
979 const char *s;
980 ssize_t s_size;
981 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
982 struct strbuf *err);
983 uintmax_t value; /* used for sorting when not FIELD_STR */
984 struct used_atom *atom;
987 #define ATOM_SIZE_UNSPECIFIED (-1)
989 #define ATOM_VALUE_INIT { \
990 .s_size = ATOM_SIZE_UNSPECIFIED \
994 * Used to parse format string and sort specifiers
996 static int parse_ref_filter_atom(struct ref_format *format,
997 const char *atom, const char *ep,
998 struct strbuf *err)
1000 const char *sp;
1001 const char *arg;
1002 int i, at, atom_len;
1004 sp = atom;
1005 if (*sp == '*' && sp < ep)
1006 sp++; /* deref */
1007 if (ep <= sp)
1008 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
1009 (int)(ep-atom), atom);
1012 * If the atom name has a colon, strip it and everything after
1013 * it off - it specifies the format for this entry, and
1014 * shouldn't be used for checking against the valid_atom
1015 * table.
1017 arg = memchr(sp, ':', ep - sp);
1018 atom_len = (arg ? arg : ep) - sp;
1020 /* Do we have the atom already used elsewhere? */
1021 for (i = 0; i < used_atom_cnt; i++) {
1022 int len = strlen(used_atom[i].name);
1023 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
1024 return i;
1027 /* Is the atom a valid one? */
1028 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
1029 int len = strlen(valid_atom[i].name);
1030 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
1031 break;
1034 if (ARRAY_SIZE(valid_atom) <= i)
1035 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
1036 (int)(ep-atom), atom);
1037 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
1038 return strbuf_addf_ret(err, -1,
1039 _("not a git repository, but the field '%.*s' requires access to object data"),
1040 (int)(ep-atom), atom);
1042 /* Add it in, including the deref prefix */
1043 at = used_atom_cnt;
1044 used_atom_cnt++;
1045 REALLOC_ARRAY(used_atom, used_atom_cnt);
1046 used_atom[at].atom_type = i;
1047 used_atom[at].name = xmemdupz(atom, ep - atom);
1048 used_atom[at].type = valid_atom[i].cmp_type;
1049 used_atom[at].source = valid_atom[i].source;
1050 if (used_atom[at].source == SOURCE_OBJ) {
1051 if (*atom == '*')
1052 oi_deref.info.contentp = &oi_deref.content;
1053 else
1054 oi.info.contentp = &oi.content;
1056 if (arg) {
1057 arg = used_atom[at].name + (arg - atom) + 1;
1058 if (!*arg) {
1060 * Treat empty sub-arguments list as NULL (i.e.,
1061 * "%(atom:)" is equivalent to "%(atom)").
1063 arg = NULL;
1066 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
1067 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
1068 return -1;
1069 if (*atom == '*')
1070 need_tagged = 1;
1071 if (i == ATOM_SYMREF)
1072 need_symref = 1;
1073 return at;
1076 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
1078 switch (quote_style) {
1079 case QUOTE_NONE:
1080 if (len < 0)
1081 strbuf_addstr(s, str);
1082 else
1083 strbuf_add(s, str, len);
1084 break;
1085 case QUOTE_SHELL:
1086 sq_quote_buf(s, str);
1087 break;
1088 case QUOTE_PERL:
1089 if (len < 0)
1090 perl_quote_buf(s, str);
1091 else
1092 perl_quote_buf_with_len(s, str, len);
1093 break;
1094 case QUOTE_PYTHON:
1095 python_quote_buf(s, str);
1096 break;
1097 case QUOTE_TCL:
1098 tcl_quote_buf(s, str);
1099 break;
1103 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
1104 struct strbuf *err UNUSED)
1107 * Quote formatting is only done when the stack has a single
1108 * element. Otherwise quote formatting is done on the
1109 * element's entire output strbuf when the %(end) atom is
1110 * encountered.
1112 if (!state->stack->prev)
1113 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
1114 else if (v->s_size < 0)
1115 strbuf_addstr(&state->stack->output, v->s);
1116 else
1117 strbuf_add(&state->stack->output, v->s, v->s_size);
1118 return 0;
1121 static void push_stack_element(struct ref_formatting_stack **stack)
1123 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
1125 strbuf_init(&s->output, 0);
1126 s->prev = *stack;
1127 *stack = s;
1130 static void pop_stack_element(struct ref_formatting_stack **stack)
1132 struct ref_formatting_stack *current = *stack;
1133 struct ref_formatting_stack *prev = current->prev;
1135 if (prev)
1136 strbuf_addbuf(&prev->output, &current->output);
1137 strbuf_release(&current->output);
1138 free(current);
1139 *stack = prev;
1142 static void end_align_handler(struct ref_formatting_stack **stack)
1144 struct ref_formatting_stack *cur = *stack;
1145 struct align *align = (struct align *)cur->at_end_data;
1146 struct strbuf s = STRBUF_INIT;
1148 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
1149 strbuf_swap(&cur->output, &s);
1150 strbuf_release(&s);
1153 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1154 struct strbuf *err UNUSED)
1156 struct ref_formatting_stack *new_stack;
1158 push_stack_element(&state->stack);
1159 new_stack = state->stack;
1160 new_stack->at_end = end_align_handler;
1161 new_stack->at_end_data = &atomv->atom->u.align;
1162 return 0;
1165 static void if_then_else_handler(struct ref_formatting_stack **stack)
1167 struct ref_formatting_stack *cur = *stack;
1168 struct ref_formatting_stack *prev = cur->prev;
1169 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
1171 if (!if_then_else->then_atom_seen)
1172 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
1174 if (if_then_else->else_atom_seen) {
1176 * There is an %(else) atom: we need to drop one state from the
1177 * stack, either the %(else) branch if the condition is satisfied, or
1178 * the %(then) branch if it isn't.
1180 if (if_then_else->condition_satisfied) {
1181 strbuf_reset(&cur->output);
1182 pop_stack_element(&cur);
1183 } else {
1184 strbuf_swap(&cur->output, &prev->output);
1185 strbuf_reset(&cur->output);
1186 pop_stack_element(&cur);
1188 } else if (!if_then_else->condition_satisfied) {
1190 * No %(else) atom: just drop the %(then) branch if the
1191 * condition is not satisfied.
1193 strbuf_reset(&cur->output);
1196 *stack = cur;
1197 free(if_then_else);
1200 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1201 struct strbuf *err UNUSED)
1203 struct ref_formatting_stack *new_stack;
1204 struct if_then_else *if_then_else = xcalloc(1,
1205 sizeof(struct if_then_else));
1207 if_then_else->str = atomv->atom->u.if_then_else.str;
1208 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
1210 push_stack_element(&state->stack);
1211 new_stack = state->stack;
1212 new_stack->at_end = if_then_else_handler;
1213 new_stack->at_end_data = if_then_else;
1214 return 0;
1217 static int is_empty(struct strbuf *buf)
1219 const char *cur = buf->buf;
1220 const char *end = buf->buf + buf->len;
1222 while (cur != end && (isspace(*cur)))
1223 cur++;
1225 return cur == end;
1228 static int then_atom_handler(struct atom_value *atomv UNUSED,
1229 struct ref_formatting_state *state,
1230 struct strbuf *err)
1232 struct ref_formatting_stack *cur = state->stack;
1233 struct if_then_else *if_then_else = NULL;
1234 size_t str_len = 0;
1236 if (cur->at_end == if_then_else_handler)
1237 if_then_else = (struct if_then_else *)cur->at_end_data;
1238 if (!if_then_else)
1239 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
1240 if (if_then_else->then_atom_seen)
1241 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
1242 if (if_then_else->else_atom_seen)
1243 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
1244 if_then_else->then_atom_seen = 1;
1245 if (if_then_else->str)
1246 str_len = strlen(if_then_else->str);
1248 * If the 'equals' or 'notequals' attribute is used then
1249 * perform the required comparison. If not, only non-empty
1250 * strings satisfy the 'if' condition.
1252 if (if_then_else->cmp_status == COMPARE_EQUAL) {
1253 if (str_len == cur->output.len &&
1254 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1255 if_then_else->condition_satisfied = 1;
1256 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
1257 if (str_len != cur->output.len ||
1258 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1259 if_then_else->condition_satisfied = 1;
1260 } else if (cur->output.len && !is_empty(&cur->output))
1261 if_then_else->condition_satisfied = 1;
1262 strbuf_reset(&cur->output);
1263 return 0;
1266 static int else_atom_handler(struct atom_value *atomv UNUSED,
1267 struct ref_formatting_state *state,
1268 struct strbuf *err)
1270 struct ref_formatting_stack *prev = state->stack;
1271 struct if_then_else *if_then_else = NULL;
1273 if (prev->at_end == if_then_else_handler)
1274 if_then_else = (struct if_then_else *)prev->at_end_data;
1275 if (!if_then_else)
1276 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1277 if (!if_then_else->then_atom_seen)
1278 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1279 if (if_then_else->else_atom_seen)
1280 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1281 if_then_else->else_atom_seen = 1;
1282 push_stack_element(&state->stack);
1283 state->stack->at_end_data = prev->at_end_data;
1284 state->stack->at_end = prev->at_end;
1285 return 0;
1288 static int end_atom_handler(struct atom_value *atomv UNUSED,
1289 struct ref_formatting_state *state,
1290 struct strbuf *err)
1292 struct ref_formatting_stack *current = state->stack;
1293 struct strbuf s = STRBUF_INIT;
1295 if (!current->at_end)
1296 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1297 current->at_end(&state->stack);
1299 /* Stack may have been popped within at_end(), hence reset the current pointer */
1300 current = state->stack;
1303 * Perform quote formatting when the stack element is that of
1304 * a supporting atom. If nested then perform quote formatting
1305 * only on the topmost supporting atom.
1307 if (!current->prev->prev) {
1308 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1309 strbuf_swap(&current->output, &s);
1311 strbuf_release(&s);
1312 pop_stack_element(&state->stack);
1313 return 0;
1317 * In a format string, find the next occurrence of %(atom).
1319 static const char *find_next(const char *cp)
1321 while (*cp) {
1322 if (*cp == '%') {
1324 * %( is the start of an atom;
1325 * %% is a quoted per-cent.
1327 if (cp[1] == '(')
1328 return cp;
1329 else if (cp[1] == '%')
1330 cp++; /* skip over two % */
1331 /* otherwise this is a singleton, literal % */
1333 cp++;
1335 return NULL;
1338 static int reject_atom(enum atom_type atom_type)
1340 return atom_type == ATOM_REST;
1344 * Make sure the format string is well formed, and parse out
1345 * the used atoms.
1347 int verify_ref_format(struct ref_format *format)
1349 const char *cp, *sp;
1351 format->need_color_reset_at_eol = 0;
1352 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1353 struct strbuf err = STRBUF_INIT;
1354 const char *color, *ep = strchr(sp, ')');
1355 int at;
1357 if (!ep)
1358 return error(_("malformed format string %s"), sp);
1359 /* sp points at "%(" and ep points at the closing ")" */
1360 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1361 if (at < 0)
1362 die("%s", err.buf);
1363 if (reject_atom(used_atom[at].atom_type))
1364 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1366 if ((format->quote_style == QUOTE_PYTHON ||
1367 format->quote_style == QUOTE_SHELL ||
1368 format->quote_style == QUOTE_TCL) &&
1369 used_atom[at].atom_type == ATOM_RAW &&
1370 used_atom[at].u.raw_data.option == RAW_BARE)
1371 die(_("--format=%.*s cannot be used with "
1372 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1373 cp = ep + 1;
1375 if (skip_prefix(used_atom[at].name, "color:", &color))
1376 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1377 strbuf_release(&err);
1379 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1380 format->need_color_reset_at_eol = 0;
1381 return 0;
1384 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1385 struct used_atom *atom)
1387 switch (atom->u.oid.option) {
1388 case O_FULL:
1389 return oid_to_hex(oid);
1390 case O_LENGTH:
1391 return repo_find_unique_abbrev(the_repository, oid,
1392 atom->u.oid.length);
1393 case O_SHORT:
1394 return repo_find_unique_abbrev(the_repository, oid,
1395 DEFAULT_ABBREV);
1396 default:
1397 BUG("unknown %%(%s) option", field);
1401 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1402 struct atom_value *v, struct used_atom *atom)
1404 if (starts_with(name, field)) {
1405 v->s = xstrdup(do_grab_oid(field, oid, atom));
1406 return 1;
1408 return 0;
1411 /* See grab_values */
1412 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1414 int i;
1416 for (i = 0; i < used_atom_cnt; i++) {
1417 const char *name = used_atom[i].name;
1418 enum atom_type atom_type = used_atom[i].atom_type;
1419 struct atom_value *v = &val[i];
1420 if (!!deref != (*name == '*'))
1421 continue;
1422 if (deref)
1423 name++;
1424 if (atom_type == ATOM_OBJECTTYPE)
1425 v->s = xstrdup(type_name(oi->type));
1426 else if (atom_type == ATOM_OBJECTSIZE) {
1427 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1428 v->value = oi->disk_size;
1429 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1430 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1431 v->value = oi->size;
1432 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1434 } else if (atom_type == ATOM_DELTABASE)
1435 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1436 else if (atom_type == ATOM_OBJECTNAME && deref)
1437 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1441 /* See grab_values */
1442 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1444 int i;
1445 struct tag *tag = (struct tag *) obj;
1447 for (i = 0; i < used_atom_cnt; i++) {
1448 const char *name = used_atom[i].name;
1449 enum atom_type atom_type = used_atom[i].atom_type;
1450 struct atom_value *v = &val[i];
1451 if (!!deref != (*name == '*'))
1452 continue;
1453 if (deref)
1454 name++;
1455 if (atom_type == ATOM_TAG)
1456 v->s = xstrdup(tag->tag);
1457 else if (atom_type == ATOM_TYPE && tag->tagged)
1458 v->s = xstrdup(type_name(tag->tagged->type));
1459 else if (atom_type == ATOM_OBJECT && tag->tagged)
1460 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1464 /* See grab_values */
1465 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1467 int i;
1468 struct commit *commit = (struct commit *) obj;
1470 for (i = 0; i < used_atom_cnt; i++) {
1471 const char *name = used_atom[i].name;
1472 enum atom_type atom_type = used_atom[i].atom_type;
1473 struct atom_value *v = &val[i];
1474 if (!!deref != (*name == '*'))
1475 continue;
1476 if (deref)
1477 name++;
1478 if (atom_type == ATOM_TREE &&
1479 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1480 continue;
1481 if (atom_type == ATOM_NUMPARENT) {
1482 v->value = commit_list_count(commit->parents);
1483 v->s = xstrfmt("%lu", (unsigned long)v->value);
1485 else if (atom_type == ATOM_PARENT) {
1486 struct commit_list *parents;
1487 struct strbuf s = STRBUF_INIT;
1488 for (parents = commit->parents; parents; parents = parents->next) {
1489 struct object_id *oid = &parents->item->object.oid;
1490 if (parents != commit->parents)
1491 strbuf_addch(&s, ' ');
1492 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1494 v->s = strbuf_detach(&s, NULL);
1499 static const char *find_wholine(const char *who, int wholen, const char *buf)
1501 const char *eol;
1502 while (*buf) {
1503 if (!strncmp(buf, who, wholen) &&
1504 buf[wholen] == ' ')
1505 return buf + wholen + 1;
1506 eol = strchr(buf, '\n');
1507 if (!eol)
1508 return "";
1509 eol++;
1510 if (*eol == '\n')
1511 return ""; /* end of header */
1512 buf = eol;
1514 return "";
1517 static const char *copy_line(const char *buf)
1519 const char *eol = strchrnul(buf, '\n');
1520 return xmemdupz(buf, eol - buf);
1523 static const char *copy_name(const char *buf)
1525 const char *cp;
1526 for (cp = buf; *cp && *cp != '\n'; cp++) {
1527 if (starts_with(cp, " <"))
1528 return xmemdupz(buf, cp - buf);
1530 return xstrdup("");
1533 static const char *find_end_of_email(const char *email, int opt)
1535 const char *eoemail;
1537 if (opt & EO_LOCALPART) {
1538 eoemail = strchr(email, '@');
1539 if (eoemail)
1540 return eoemail;
1541 return strchr(email, '>');
1544 if (opt & EO_TRIM)
1545 return strchr(email, '>');
1548 * The option here is either the raw email option or the raw
1549 * mailmap option (that is EO_RAW or EO_MAILMAP). In such cases,
1550 * we directly grab the whole email including the closing
1551 * angle brackets.
1553 * If EO_MAILMAP was set with any other option (that is either
1554 * EO_TRIM or EO_LOCALPART), we already grab the end of email
1555 * above.
1557 eoemail = strchr(email, '>');
1558 if (eoemail)
1559 eoemail++;
1560 return eoemail;
1563 static const char *copy_email(const char *buf, struct used_atom *atom)
1565 const char *email = strchr(buf, '<');
1566 const char *eoemail;
1567 int opt = atom->u.email_option.option;
1569 if (!email)
1570 return xstrdup("");
1572 if (opt & (EO_LOCALPART | EO_TRIM))
1573 email++;
1575 eoemail = find_end_of_email(email, opt);
1576 if (!eoemail)
1577 return xstrdup("");
1578 return xmemdupz(email, eoemail - email);
1581 static char *copy_subject(const char *buf, unsigned long len)
1583 struct strbuf sb = STRBUF_INIT;
1584 int i;
1586 for (i = 0; i < len; i++) {
1587 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1588 continue; /* ignore CR in CRLF */
1590 if (buf[i] == '\n')
1591 strbuf_addch(&sb, ' ');
1592 else
1593 strbuf_addch(&sb, buf[i]);
1595 return strbuf_detach(&sb, NULL);
1598 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1600 const char *eoemail = strstr(buf, "> ");
1601 char *zone;
1602 timestamp_t timestamp;
1603 long tz;
1604 struct date_mode date_mode = DATE_MODE_INIT;
1605 const char *formatp;
1608 * We got here because atomname ends in "date" or "date<something>";
1609 * it's not possible that <something> is not ":<format>" because
1610 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1611 * ":" means no format is specified, and use the default.
1613 formatp = strchr(atomname, ':');
1614 if (formatp) {
1615 formatp++;
1616 parse_date_format(formatp, &date_mode);
1619 if (!eoemail)
1620 goto bad;
1621 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1622 if (timestamp == TIME_MAX)
1623 goto bad;
1624 tz = strtol(zone, NULL, 10);
1625 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1626 goto bad;
1627 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1628 v->value = timestamp;
1629 date_mode_release(&date_mode);
1630 return;
1631 bad:
1632 v->s = xstrdup("");
1633 v->value = 0;
1636 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
1638 /* See grab_values */
1639 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1641 int i;
1642 int wholen = strlen(who);
1643 const char *wholine = NULL;
1644 const char *headers[] = { "author ", "committer ",
1645 "tagger ", NULL };
1647 for (i = 0; i < used_atom_cnt; i++) {
1648 struct used_atom *atom = &used_atom[i];
1649 const char *name = atom->name;
1650 struct atom_value *v = &val[i];
1651 struct strbuf mailmap_buf = STRBUF_INIT;
1653 if (!!deref != (*name == '*'))
1654 continue;
1655 if (deref)
1656 name++;
1657 if (strncmp(who, name, wholen))
1658 continue;
1659 if (name[wholen] != 0 &&
1660 !starts_with(name + wholen, "name") &&
1661 !starts_with(name + wholen, "email") &&
1662 !starts_with(name + wholen, "date"))
1663 continue;
1665 if ((starts_with(name + wholen, "name") &&
1666 (atom->u.name_option.option == N_MAILMAP)) ||
1667 (starts_with(name + wholen, "email") &&
1668 (atom->u.email_option.option & EO_MAILMAP))) {
1669 if (!mailmap.items)
1670 read_mailmap(&mailmap);
1671 strbuf_addstr(&mailmap_buf, buf);
1672 apply_mailmap_to_header(&mailmap_buf, headers, &mailmap);
1673 wholine = find_wholine(who, wholen, mailmap_buf.buf);
1674 } else {
1675 wholine = find_wholine(who, wholen, buf);
1678 if (!wholine)
1679 return; /* no point looking for it */
1680 if (name[wholen] == 0)
1681 v->s = copy_line(wholine);
1682 else if (starts_with(name + wholen, "name"))
1683 v->s = copy_name(wholine);
1684 else if (starts_with(name + wholen, "email"))
1685 v->s = copy_email(wholine, &used_atom[i]);
1686 else if (starts_with(name + wholen, "date"))
1687 grab_date(wholine, v, name);
1689 strbuf_release(&mailmap_buf);
1693 * For a tag or a commit object, if "creator" or "creatordate" is
1694 * requested, do something special.
1696 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1697 return; /* "author" for commit object is not wanted */
1698 if (!wholine)
1699 wholine = find_wholine(who, wholen, buf);
1700 if (!wholine)
1701 return;
1702 for (i = 0; i < used_atom_cnt; i++) {
1703 const char *name = used_atom[i].name;
1704 enum atom_type atom_type = used_atom[i].atom_type;
1705 struct atom_value *v = &val[i];
1706 if (!!deref != (*name == '*'))
1707 continue;
1708 if (deref)
1709 name++;
1711 if (atom_type == ATOM_CREATORDATE)
1712 grab_date(wholine, v, name);
1713 else if (atom_type == ATOM_CREATOR)
1714 v->s = copy_line(wholine);
1718 static void grab_signature(struct atom_value *val, int deref, struct object *obj)
1720 int i;
1721 struct commit *commit = (struct commit *) obj;
1722 struct signature_check sigc = { 0 };
1723 int signature_checked = 0;
1725 for (i = 0; i < used_atom_cnt; i++) {
1726 struct used_atom *atom = &used_atom[i];
1727 const char *name = atom->name;
1728 struct atom_value *v = &val[i];
1729 int opt;
1731 if (!!deref != (*name == '*'))
1732 continue;
1733 if (deref)
1734 name++;
1736 if (!skip_prefix(name, "signature", &name) ||
1737 (*name && *name != ':'))
1738 continue;
1739 if (!*name)
1740 name = NULL;
1741 else
1742 name++;
1744 opt = parse_signature_option(name);
1745 if (opt < 0)
1746 continue;
1748 if (!signature_checked) {
1749 check_commit_signature(commit, &sigc);
1750 signature_checked = 1;
1753 switch (opt) {
1754 case S_BARE:
1755 v->s = xstrdup(sigc.output ? sigc.output: "");
1756 break;
1757 case S_SIGNER:
1758 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1759 break;
1760 case S_GRADE:
1761 switch (sigc.result) {
1762 case 'G':
1763 switch (sigc.trust_level) {
1764 case TRUST_UNDEFINED:
1765 case TRUST_NEVER:
1766 v->s = xstrfmt("%c", (char)'U');
1767 break;
1768 default:
1769 v->s = xstrfmt("%c", (char)'G');
1770 break;
1772 break;
1773 case 'B':
1774 case 'E':
1775 case 'N':
1776 case 'X':
1777 case 'Y':
1778 case 'R':
1779 v->s = xstrfmt("%c", (char)sigc.result);
1780 break;
1782 break;
1783 case S_KEY:
1784 v->s = xstrdup(sigc.key ? sigc.key : "");
1785 break;
1786 case S_FINGERPRINT:
1787 v->s = xstrdup(sigc.fingerprint ?
1788 sigc.fingerprint : "");
1789 break;
1790 case S_PRI_KEY_FP:
1791 v->s = xstrdup(sigc.primary_key_fingerprint ?
1792 sigc.primary_key_fingerprint : "");
1793 break;
1794 case S_TRUST_LEVEL:
1795 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1796 break;
1800 if (signature_checked)
1801 signature_check_clear(&sigc);
1804 static void find_subpos(const char *buf,
1805 const char **sub, size_t *sublen,
1806 const char **body, size_t *bodylen,
1807 size_t *nonsiglen,
1808 const char **sig, size_t *siglen)
1810 struct strbuf payload = STRBUF_INIT;
1811 struct strbuf signature = STRBUF_INIT;
1812 const char *eol;
1813 const char *end = buf + strlen(buf);
1814 const char *sigstart;
1816 /* parse signature first; we might not even have a subject line */
1817 parse_signature(buf, end - buf, &payload, &signature);
1818 strbuf_release(&payload);
1820 /* skip past header until we hit empty line */
1821 while (*buf && *buf != '\n') {
1822 eol = strchrnul(buf, '\n');
1823 if (*eol)
1824 eol++;
1825 buf = eol;
1827 /* skip any empty lines */
1828 while (*buf == '\n')
1829 buf++;
1830 *sig = strbuf_detach(&signature, siglen);
1831 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1833 /* subject is first non-empty line */
1834 *sub = buf;
1835 /* subject goes to first empty line before signature begins */
1836 if ((eol = strstr(*sub, "\n\n")) ||
1837 (eol = strstr(*sub, "\r\n\r\n"))) {
1838 eol = eol < sigstart ? eol : sigstart;
1839 } else {
1840 /* treat whole message as subject */
1841 eol = sigstart;
1843 buf = eol;
1844 *sublen = buf - *sub;
1845 /* drop trailing newline, if present */
1846 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1847 (*sub)[*sublen - 1] == '\r'))
1848 *sublen -= 1;
1850 /* skip any empty lines */
1851 while (*buf == '\n' || *buf == '\r')
1852 buf++;
1853 *body = buf;
1854 *bodylen = strlen(buf);
1855 *nonsiglen = sigstart - buf;
1859 * If 'lines' is greater than 0, append that many lines from the given
1860 * 'buf' of length 'size' to the given strbuf.
1862 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1864 int i;
1865 const char *sp, *eol;
1866 size_t len;
1868 sp = buf;
1870 for (i = 0; i < lines && sp < buf + size; i++) {
1871 if (i)
1872 strbuf_addstr(out, "\n ");
1873 eol = memchr(sp, '\n', size - (sp - buf));
1874 len = eol ? eol - sp : size - (sp - buf);
1875 strbuf_add(out, sp, len);
1876 if (!eol)
1877 break;
1878 sp = eol + 1;
1882 static void grab_describe_values(struct atom_value *val, int deref,
1883 struct object *obj)
1885 struct commit *commit = (struct commit *)obj;
1886 int i;
1888 for (i = 0; i < used_atom_cnt; i++) {
1889 struct used_atom *atom = &used_atom[i];
1890 enum atom_type type = atom->atom_type;
1891 const char *name = atom->name;
1892 struct atom_value *v = &val[i];
1894 struct child_process cmd = CHILD_PROCESS_INIT;
1895 struct strbuf out = STRBUF_INIT;
1896 struct strbuf err = STRBUF_INIT;
1898 if (type != ATOM_DESCRIBE)
1899 continue;
1901 if (!!deref != (*name == '*'))
1902 continue;
1904 cmd.git_cmd = 1;
1905 strvec_push(&cmd.args, "describe");
1906 strvec_pushv(&cmd.args, atom->u.describe_args);
1907 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1908 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
1909 error(_("failed to run 'describe'"));
1910 v->s = xstrdup("");
1911 continue;
1913 strbuf_rtrim(&out);
1914 v->s = strbuf_detach(&out, NULL);
1916 strbuf_release(&err);
1920 /* See grab_values */
1921 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1923 int i;
1924 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1925 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1926 void *buf = data->content;
1928 for (i = 0; i < used_atom_cnt; i++) {
1929 struct used_atom *atom = &used_atom[i];
1930 const char *name = atom->name;
1931 struct atom_value *v = &val[i];
1932 enum atom_type atom_type = atom->atom_type;
1934 if (!!deref != (*name == '*'))
1935 continue;
1936 if (deref)
1937 name++;
1939 if (atom_type == ATOM_RAW) {
1940 unsigned long buf_size = data->size;
1942 if (atom->u.raw_data.option == RAW_BARE) {
1943 v->s = xmemdupz(buf, buf_size);
1944 v->s_size = buf_size;
1945 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1946 v->value = buf_size;
1947 v->s = xstrfmt("%"PRIuMAX, v->value);
1949 continue;
1952 if ((data->type != OBJ_TAG &&
1953 data->type != OBJ_COMMIT) ||
1954 (strcmp(name, "body") &&
1955 !starts_with(name, "subject") &&
1956 !starts_with(name, "trailers") &&
1957 !starts_with(name, "contents")))
1958 continue;
1959 if (!subpos)
1960 find_subpos(buf,
1961 &subpos, &sublen,
1962 &bodypos, &bodylen, &nonsiglen,
1963 &sigpos, &siglen);
1965 if (atom->u.contents.option == C_SUB)
1966 v->s = copy_subject(subpos, sublen);
1967 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1968 struct strbuf sb = STRBUF_INIT;
1969 format_sanitized_subject(&sb, subpos, sublen);
1970 v->s = strbuf_detach(&sb, NULL);
1971 } else if (atom->u.contents.option == C_BODY_DEP)
1972 v->s = xmemdupz(bodypos, bodylen);
1973 else if (atom->u.contents.option == C_LENGTH) {
1974 v->value = strlen(subpos);
1975 v->s = xstrfmt("%"PRIuMAX, v->value);
1976 } else if (atom->u.contents.option == C_BODY)
1977 v->s = xmemdupz(bodypos, nonsiglen);
1978 else if (atom->u.contents.option == C_SIG)
1979 v->s = xmemdupz(sigpos, siglen);
1980 else if (atom->u.contents.option == C_LINES) {
1981 struct strbuf s = STRBUF_INIT;
1982 const char *contents_end = bodypos + nonsiglen;
1984 /* Size is the length of the message after removing the signature */
1985 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1986 v->s = strbuf_detach(&s, NULL);
1987 } else if (atom->u.contents.option == C_TRAILERS) {
1988 struct strbuf s = STRBUF_INIT;
1990 /* Format the trailer info according to the trailer_opts given */
1991 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1993 v->s = strbuf_detach(&s, NULL);
1994 } else if (atom->u.contents.option == C_BARE)
1995 v->s = xstrdup(subpos);
1998 free((void *)sigpos);
2002 * We want to have empty print-string for field requests
2003 * that do not apply (e.g. "authordate" for a tag object)
2005 static void fill_missing_values(struct atom_value *val)
2007 int i;
2008 for (i = 0; i < used_atom_cnt; i++) {
2009 struct atom_value *v = &val[i];
2010 if (!v->s)
2011 v->s = xstrdup("");
2016 * val is a list of atom_value to hold returned values. Extract
2017 * the values for atoms in used_atom array out of (obj, buf, sz).
2018 * when deref is false, (obj, buf, sz) is the object that is
2019 * pointed at by the ref itself; otherwise it is the object the
2020 * ref (which is a tag) refers to.
2022 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
2024 void *buf = data->content;
2026 switch (obj->type) {
2027 case OBJ_TAG:
2028 grab_tag_values(val, deref, obj);
2029 grab_sub_body_contents(val, deref, data);
2030 grab_person("tagger", val, deref, buf);
2031 grab_describe_values(val, deref, obj);
2032 break;
2033 case OBJ_COMMIT:
2034 grab_commit_values(val, deref, obj);
2035 grab_sub_body_contents(val, deref, data);
2036 grab_person("author", val, deref, buf);
2037 grab_person("committer", val, deref, buf);
2038 grab_signature(val, deref, obj);
2039 grab_describe_values(val, deref, obj);
2040 break;
2041 case OBJ_TREE:
2042 /* grab_tree_values(val, deref, obj, buf, sz); */
2043 grab_sub_body_contents(val, deref, data);
2044 break;
2045 case OBJ_BLOB:
2046 /* grab_blob_values(val, deref, obj, buf, sz); */
2047 grab_sub_body_contents(val, deref, data);
2048 break;
2049 default:
2050 die("Eh? Object of type %d?", obj->type);
2054 static inline char *copy_advance(char *dst, const char *src)
2056 while (*src)
2057 *dst++ = *src++;
2058 return dst;
2061 static const char *lstrip_ref_components(const char *refname, int len)
2063 long remaining = len;
2064 const char *start = xstrdup(refname);
2065 const char *to_free = start;
2067 if (len < 0) {
2068 int i;
2069 const char *p = refname;
2071 /* Find total no of '/' separated path-components */
2072 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2075 * The number of components we need to strip is now
2076 * the total minus the components to be left (Plus one
2077 * because we count the number of '/', but the number
2078 * of components is one more than the no of '/').
2080 remaining = i + len + 1;
2083 while (remaining > 0) {
2084 switch (*start++) {
2085 case '\0':
2086 free((char *)to_free);
2087 return xstrdup("");
2088 case '/':
2089 remaining--;
2090 break;
2094 start = xstrdup(start);
2095 free((char *)to_free);
2096 return start;
2099 static const char *rstrip_ref_components(const char *refname, int len)
2101 long remaining = len;
2102 const char *start = xstrdup(refname);
2103 const char *to_free = start;
2105 if (len < 0) {
2106 int i;
2107 const char *p = refname;
2109 /* Find total no of '/' separated path-components */
2110 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2113 * The number of components we need to strip is now
2114 * the total minus the components to be left (Plus one
2115 * because we count the number of '/', but the number
2116 * of components is one more than the no of '/').
2118 remaining = i + len + 1;
2121 while (remaining-- > 0) {
2122 char *p = strrchr(start, '/');
2123 if (!p) {
2124 free((char *)to_free);
2125 return xstrdup("");
2126 } else
2127 p[0] = '\0';
2129 return start;
2132 static const char *show_ref(struct refname_atom *atom, const char *refname)
2134 if (atom->option == R_SHORT)
2135 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
2136 else if (atom->option == R_LSTRIP)
2137 return lstrip_ref_components(refname, atom->lstrip);
2138 else if (atom->option == R_RSTRIP)
2139 return rstrip_ref_components(refname, atom->rstrip);
2140 else
2141 return xstrdup(refname);
2144 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2145 struct branch *branch, const char **s)
2147 int num_ours, num_theirs;
2148 if (atom->u.remote_ref.option == RR_REF)
2149 *s = show_ref(&atom->u.remote_ref.refname, refname);
2150 else if (atom->u.remote_ref.option == RR_TRACK) {
2151 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2152 NULL, atom->u.remote_ref.push,
2153 AHEAD_BEHIND_FULL) < 0) {
2154 *s = xstrdup(msgs.gone);
2155 } else if (!num_ours && !num_theirs)
2156 *s = xstrdup("");
2157 else if (!num_ours)
2158 *s = xstrfmt(msgs.behind, num_theirs);
2159 else if (!num_theirs)
2160 *s = xstrfmt(msgs.ahead, num_ours);
2161 else
2162 *s = xstrfmt(msgs.ahead_behind,
2163 num_ours, num_theirs);
2164 if (!atom->u.remote_ref.nobracket && *s[0]) {
2165 const char *to_free = *s;
2166 *s = xstrfmt("[%s]", *s);
2167 free((void *)to_free);
2169 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2170 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2171 NULL, atom->u.remote_ref.push,
2172 AHEAD_BEHIND_FULL) < 0) {
2173 *s = xstrdup("");
2174 return;
2176 if (!num_ours && !num_theirs)
2177 *s = xstrdup("=");
2178 else if (!num_ours)
2179 *s = xstrdup("<");
2180 else if (!num_theirs)
2181 *s = xstrdup(">");
2182 else
2183 *s = xstrdup("<>");
2184 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2185 int explicit;
2186 const char *remote = atom->u.remote_ref.push ?
2187 pushremote_for_branch(branch, &explicit) :
2188 remote_for_branch(branch, &explicit);
2189 *s = xstrdup(explicit ? remote : "");
2190 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2191 const char *merge;
2193 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2194 *s = xstrdup(merge ? merge : "");
2195 } else
2196 BUG("unhandled RR_* enum");
2199 char *get_head_description(void)
2201 struct strbuf desc = STRBUF_INIT;
2202 struct wt_status_state state;
2203 memset(&state, 0, sizeof(state));
2204 wt_status_get_state(the_repository, &state, 1);
2205 if (state.rebase_in_progress ||
2206 state.rebase_interactive_in_progress) {
2207 if (state.branch)
2208 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2209 state.branch);
2210 else
2211 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2212 state.detached_from);
2213 } else if (state.bisect_in_progress)
2214 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2215 state.branch);
2216 else if (state.detached_from) {
2217 if (state.detached_at)
2218 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2219 state.detached_from);
2220 else
2221 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2222 state.detached_from);
2223 } else
2224 strbuf_addstr(&desc, _("(no branch)"));
2226 wt_status_state_free_buffers(&state);
2228 return strbuf_detach(&desc, NULL);
2231 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2233 if (!ref->symref)
2234 return xstrdup("");
2235 else
2236 return show_ref(&atom->u.refname, ref->symref);
2239 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2241 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2242 return get_head_description();
2243 return show_ref(&atom->u.refname, ref->refname);
2246 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
2247 struct expand_data *oi, struct strbuf *err)
2249 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
2250 int eaten = 1;
2251 if (oi->info.contentp) {
2252 /* We need to know that to use parse_object_buffer properly */
2253 oi->info.sizep = &oi->size;
2254 oi->info.typep = &oi->type;
2256 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
2257 OBJECT_INFO_LOOKUP_REPLACE))
2258 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2259 oid_to_hex(&oi->oid), ref->refname);
2260 if (oi->info.disk_sizep && oi->disk_size < 0)
2261 BUG("Object size is less than zero.");
2263 if (oi->info.contentp) {
2264 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
2265 if (!*obj) {
2266 if (!eaten)
2267 free(oi->content);
2268 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
2269 oid_to_hex(&oi->oid), ref->refname);
2271 grab_values(ref->value, deref, *obj, oi);
2274 grab_common_values(ref->value, deref, oi);
2275 if (!eaten)
2276 free(oi->content);
2277 return 0;
2280 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2282 int i;
2284 for (i = 0; worktrees[i]; i++) {
2285 if (worktrees[i]->head_ref) {
2286 struct ref_to_worktree_entry *entry;
2287 entry = xmalloc(sizeof(*entry));
2288 entry->wt = worktrees[i];
2289 hashmap_entry_init(&entry->ent,
2290 strhash(worktrees[i]->head_ref));
2292 hashmap_add(map, &entry->ent);
2297 static void lazy_init_worktree_map(void)
2299 if (ref_to_worktree_map.worktrees)
2300 return;
2302 ref_to_worktree_map.worktrees = get_worktrees();
2303 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2304 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2307 static char *get_worktree_path(const struct ref_array_item *ref)
2309 struct hashmap_entry entry, *e;
2310 struct ref_to_worktree_entry *lookup_result;
2312 lazy_init_worktree_map();
2314 hashmap_entry_init(&entry, strhash(ref->refname));
2315 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2317 if (!e)
2318 return xstrdup("");
2320 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2322 return xstrdup(lookup_result->wt->path);
2326 * Parse the object referred by ref, and grab needed value.
2328 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2330 struct object *obj;
2331 int i;
2332 struct object_info empty = OBJECT_INFO_INIT;
2333 int ahead_behind_atoms = 0;
2335 CALLOC_ARRAY(ref->value, used_atom_cnt);
2337 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2338 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
2339 NULL, NULL);
2340 if (!ref->symref)
2341 ref->symref = xstrdup("");
2344 /* Fill in specials first */
2345 for (i = 0; i < used_atom_cnt; i++) {
2346 struct used_atom *atom = &used_atom[i];
2347 enum atom_type atom_type = atom->atom_type;
2348 const char *name = used_atom[i].name;
2349 struct atom_value *v = &ref->value[i];
2350 int deref = 0;
2351 const char *refname;
2352 struct branch *branch = NULL;
2354 v->s_size = ATOM_SIZE_UNSPECIFIED;
2355 v->handler = append_atom;
2356 v->value = 0;
2357 v->atom = atom;
2359 if (*name == '*') {
2360 deref = 1;
2361 name++;
2364 if (atom_type == ATOM_REFNAME)
2365 refname = get_refname(atom, ref);
2366 else if (atom_type == ATOM_WORKTREEPATH) {
2367 if (ref->kind == FILTER_REFS_BRANCHES)
2368 v->s = get_worktree_path(ref);
2369 else
2370 v->s = xstrdup("");
2371 continue;
2373 else if (atom_type == ATOM_SYMREF)
2374 refname = get_symref(atom, ref);
2375 else if (atom_type == ATOM_UPSTREAM) {
2376 const char *branch_name;
2377 /* only local branches may have an upstream */
2378 if (!skip_prefix(ref->refname, "refs/heads/",
2379 &branch_name)) {
2380 v->s = xstrdup("");
2381 continue;
2383 branch = branch_get(branch_name);
2385 refname = branch_get_upstream(branch, NULL);
2386 if (refname)
2387 fill_remote_ref_details(atom, refname, branch, &v->s);
2388 else
2389 v->s = xstrdup("");
2390 continue;
2391 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2392 const char *branch_name;
2393 v->s = xstrdup("");
2394 if (!skip_prefix(ref->refname, "refs/heads/",
2395 &branch_name))
2396 continue;
2397 branch = branch_get(branch_name);
2399 if (atom->u.remote_ref.push_remote)
2400 refname = NULL;
2401 else {
2402 refname = branch_get_push(branch, NULL);
2403 if (!refname)
2404 continue;
2406 /* We will definitely re-init v->s on the next line. */
2407 free((char *)v->s);
2408 fill_remote_ref_details(atom, refname, branch, &v->s);
2409 continue;
2410 } else if (atom_type == ATOM_COLOR) {
2411 v->s = xstrdup(atom->u.color);
2412 continue;
2413 } else if (atom_type == ATOM_FLAG) {
2414 char buf[256], *cp = buf;
2415 if (ref->flag & REF_ISSYMREF)
2416 cp = copy_advance(cp, ",symref");
2417 if (ref->flag & REF_ISPACKED)
2418 cp = copy_advance(cp, ",packed");
2419 if (cp == buf)
2420 v->s = xstrdup("");
2421 else {
2422 *cp = '\0';
2423 v->s = xstrdup(buf + 1);
2425 continue;
2426 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2427 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2428 continue;
2429 } else if (atom_type == ATOM_HEAD) {
2430 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2431 v->s = xstrdup("*");
2432 else
2433 v->s = xstrdup(" ");
2434 continue;
2435 } else if (atom_type == ATOM_ALIGN) {
2436 v->handler = align_atom_handler;
2437 v->s = xstrdup("");
2438 continue;
2439 } else if (atom_type == ATOM_END) {
2440 v->handler = end_atom_handler;
2441 v->s = xstrdup("");
2442 continue;
2443 } else if (atom_type == ATOM_IF) {
2444 const char *s;
2445 if (skip_prefix(name, "if:", &s))
2446 v->s = xstrdup(s);
2447 else
2448 v->s = xstrdup("");
2449 v->handler = if_atom_handler;
2450 continue;
2451 } else if (atom_type == ATOM_THEN) {
2452 v->handler = then_atom_handler;
2453 v->s = xstrdup("");
2454 continue;
2455 } else if (atom_type == ATOM_ELSE) {
2456 v->handler = else_atom_handler;
2457 v->s = xstrdup("");
2458 continue;
2459 } else if (atom_type == ATOM_REST) {
2460 if (ref->rest)
2461 v->s = xstrdup(ref->rest);
2462 else
2463 v->s = xstrdup("");
2464 continue;
2465 } else if (atom_type == ATOM_AHEADBEHIND) {
2466 if (ref->counts) {
2467 const struct ahead_behind_count *count;
2468 count = ref->counts[ahead_behind_atoms++];
2469 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2470 } else {
2471 /* Not a commit. */
2472 v->s = xstrdup("");
2474 continue;
2475 } else
2476 continue;
2478 if (!deref)
2479 v->s = xstrdup(refname);
2480 else
2481 v->s = xstrfmt("%s^{}", refname);
2482 free((char *)refname);
2485 for (i = 0; i < used_atom_cnt; i++) {
2486 struct atom_value *v = &ref->value[i];
2487 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2488 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2489 oid_to_hex(&ref->objectname), ref->refname);
2492 if (need_tagged)
2493 oi.info.contentp = &oi.content;
2494 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2495 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2496 return 0;
2499 oi.oid = ref->objectname;
2500 if (get_object(ref, 0, &obj, &oi, err))
2501 return -1;
2504 * If there is no atom that wants to know about tagged
2505 * object, we are done.
2507 if (!need_tagged || (obj->type != OBJ_TAG))
2508 return 0;
2511 * If it is a tag object, see if we use a value that derefs
2512 * the object, and if we do grab the object it refers to.
2514 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2517 * NEEDSWORK: This derefs tag only once, which
2518 * is good to deal with chains of trust, but
2519 * is not consistent with what deref_tag() does
2520 * which peels the onion to the core.
2522 return get_object(ref, 1, &obj, &oi_deref, err);
2526 * Given a ref, return the value for the atom. This lazily gets value
2527 * out of the object by calling populate value.
2529 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2530 struct atom_value **v, struct strbuf *err)
2532 if (!ref->value) {
2533 if (populate_value(ref, err))
2534 return -1;
2535 fill_missing_values(ref->value);
2537 *v = &ref->value[atom];
2538 return 0;
2542 * Return 1 if the refname matches one of the patterns, otherwise 0.
2543 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2544 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2545 * matches "refs/heads/mas*", too).
2547 static int match_pattern(const char **patterns, const char *refname,
2548 int ignore_case)
2550 unsigned flags = 0;
2552 if (ignore_case)
2553 flags |= WM_CASEFOLD;
2556 * When no '--format' option is given we need to skip the prefix
2557 * for matching refs of tags and branches.
2559 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2560 skip_prefix(refname, "refs/heads/", &refname) ||
2561 skip_prefix(refname, "refs/remotes/", &refname) ||
2562 skip_prefix(refname, "refs/", &refname));
2564 for (; *patterns; patterns++) {
2565 if (!wildmatch(*patterns, refname, flags))
2566 return 1;
2568 return 0;
2572 * Return 1 if the refname matches one of the patterns, otherwise 0.
2573 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2574 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2575 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2577 static int match_name_as_path(const char **pattern, const char *refname,
2578 int ignore_case)
2580 int namelen = strlen(refname);
2581 unsigned flags = WM_PATHNAME;
2583 if (ignore_case)
2584 flags |= WM_CASEFOLD;
2586 for (; *pattern; pattern++) {
2587 const char *p = *pattern;
2588 int plen = strlen(p);
2590 if ((plen <= namelen) &&
2591 !strncmp(refname, p, plen) &&
2592 (refname[plen] == '\0' ||
2593 refname[plen] == '/' ||
2594 p[plen-1] == '/'))
2595 return 1;
2596 if (!wildmatch(p, refname, flags))
2597 return 1;
2599 return 0;
2602 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2603 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2605 if (!*filter->name_patterns)
2606 return 1; /* No pattern always matches */
2607 if (filter->match_as_path)
2608 return match_name_as_path(filter->name_patterns, refname,
2609 filter->ignore_case);
2610 return match_pattern(filter->name_patterns, refname,
2611 filter->ignore_case);
2614 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2616 if (!filter->exclude.nr)
2617 return 0;
2618 if (filter->match_as_path)
2619 return match_name_as_path(filter->exclude.v, refname,
2620 filter->ignore_case);
2621 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2625 * This is the same as for_each_fullref_in(), but it tries to iterate
2626 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2627 * pattern match, so the callback still has to match each ref individually.
2629 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2630 each_ref_fn cb,
2631 void *cb_data)
2633 if (!filter->match_as_path) {
2635 * in this case, the patterns are applied after
2636 * prefixes like "refs/heads/" etc. are stripped off,
2637 * so we have to look at everything:
2639 return for_each_fullref_in("", cb, cb_data);
2642 if (filter->ignore_case) {
2644 * we can't handle case-insensitive comparisons,
2645 * so just return everything and let the caller
2646 * sort it out.
2648 return for_each_fullref_in("", cb, cb_data);
2651 if (!filter->name_patterns[0]) {
2652 /* no patterns; we have to look at everything */
2653 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2654 "", filter->exclude.v, cb, cb_data);
2657 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2658 NULL, filter->name_patterns,
2659 filter->exclude.v,
2660 cb, cb_data);
2664 * Given a ref (oid, refname), check if the ref belongs to the array
2665 * of oids. If the given ref is a tag, check if the given tag points
2666 * at one of the oids in the given oid array. Returns non-zero if a
2667 * match is found.
2669 * NEEDSWORK:
2670 * As the refs are cached we might know what refname peels to without
2671 * the need to parse the object via parse_object(). peel_ref() might be a
2672 * more efficient alternative to obtain the pointee.
2674 static int match_points_at(struct oid_array *points_at,
2675 const struct object_id *oid,
2676 const char *refname)
2678 struct object *obj;
2680 if (oid_array_lookup(points_at, oid) >= 0)
2681 return 1;
2682 obj = parse_object_with_flags(the_repository, oid,
2683 PARSE_OBJECT_SKIP_HASH_CHECK);
2684 while (obj && obj->type == OBJ_TAG) {
2685 struct tag *tag = (struct tag *)obj;
2687 if (parse_tag(tag) < 0) {
2688 obj = NULL;
2689 break;
2692 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2693 return 1;
2695 obj = tag->tagged;
2697 if (!obj)
2698 die(_("malformed object at '%s'"), refname);
2699 return 0;
2703 * Allocate space for a new ref_array_item and copy the name and oid to it.
2705 * Callers can then fill in other struct members at their leisure.
2707 static struct ref_array_item *new_ref_array_item(const char *refname,
2708 const struct object_id *oid)
2710 struct ref_array_item *ref;
2712 FLEX_ALLOC_STR(ref, refname, refname);
2713 oidcpy(&ref->objectname, oid);
2714 ref->rest = NULL;
2716 return ref;
2719 struct ref_array_item *ref_array_push(struct ref_array *array,
2720 const char *refname,
2721 const struct object_id *oid)
2723 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2725 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2726 array->items[array->nr++] = ref;
2728 return ref;
2731 static int ref_kind_from_refname(const char *refname)
2733 unsigned int i;
2735 static struct {
2736 const char *prefix;
2737 unsigned int kind;
2738 } ref_kind[] = {
2739 { "refs/heads/" , FILTER_REFS_BRANCHES },
2740 { "refs/remotes/" , FILTER_REFS_REMOTES },
2741 { "refs/tags/", FILTER_REFS_TAGS}
2744 if (!strcmp(refname, "HEAD"))
2745 return FILTER_REFS_DETACHED_HEAD;
2747 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2748 if (starts_with(refname, ref_kind[i].prefix))
2749 return ref_kind[i].kind;
2752 return FILTER_REFS_OTHERS;
2755 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2757 if (filter->kind == FILTER_REFS_BRANCHES ||
2758 filter->kind == FILTER_REFS_REMOTES ||
2759 filter->kind == FILTER_REFS_TAGS)
2760 return filter->kind;
2761 return ref_kind_from_refname(refname);
2764 struct ref_filter_cbdata {
2765 struct ref_array *array;
2766 struct ref_filter *filter;
2767 struct contains_cache contains_cache;
2768 struct contains_cache no_contains_cache;
2772 * A call-back given to for_each_ref(). Filter refs and keep them for
2773 * later object processing.
2775 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2777 struct ref_filter_cbdata *ref_cbdata = cb_data;
2778 struct ref_filter *filter = ref_cbdata->filter;
2779 struct ref_array_item *ref;
2780 struct commit *commit = NULL;
2781 unsigned int kind;
2783 if (flag & REF_BAD_NAME) {
2784 warning(_("ignoring ref with broken name %s"), refname);
2785 return 0;
2788 if (flag & REF_ISBROKEN) {
2789 warning(_("ignoring broken ref %s"), refname);
2790 return 0;
2793 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2794 kind = filter_ref_kind(filter, refname);
2795 if (!(kind & filter->kind))
2796 return 0;
2798 if (!filter_pattern_match(filter, refname))
2799 return 0;
2801 if (filter_exclude_match(filter, refname))
2802 return 0;
2804 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2805 return 0;
2808 * A merge filter is applied on refs pointing to commits. Hence
2809 * obtain the commit using the 'oid' available and discard all
2810 * non-commits early. The actual filtering is done later.
2812 if (filter->reachable_from || filter->unreachable_from ||
2813 filter->with_commit || filter->no_commit || filter->verbose) {
2814 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2815 if (!commit)
2816 return 0;
2817 /* We perform the filtering for the '--contains' option... */
2818 if (filter->with_commit &&
2819 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2820 return 0;
2821 /* ...or for the `--no-contains' option */
2822 if (filter->no_commit &&
2823 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2824 return 0;
2828 * We do not open the object yet; sort may only need refname
2829 * to do its job and the resulting list may yet to be pruned
2830 * by maxcount logic.
2832 ref = ref_array_push(ref_cbdata->array, refname, oid);
2833 ref->commit = commit;
2834 ref->flag = flag;
2835 ref->kind = kind;
2837 return 0;
2840 /* Free memory allocated for a ref_array_item */
2841 static void free_array_item(struct ref_array_item *item)
2843 free((char *)item->symref);
2844 if (item->value) {
2845 int i;
2846 for (i = 0; i < used_atom_cnt; i++)
2847 free((char *)item->value[i].s);
2848 free(item->value);
2850 free(item->counts);
2851 free(item);
2854 /* Free all memory allocated for ref_array */
2855 void ref_array_clear(struct ref_array *array)
2857 int i;
2859 for (i = 0; i < array->nr; i++)
2860 free_array_item(array->items[i]);
2861 FREE_AND_NULL(array->items);
2862 array->nr = array->alloc = 0;
2864 for (i = 0; i < used_atom_cnt; i++) {
2865 struct used_atom *atom = &used_atom[i];
2866 if (atom->atom_type == ATOM_HEAD)
2867 free(atom->u.head);
2868 free((char *)atom->name);
2870 FREE_AND_NULL(used_atom);
2871 used_atom_cnt = 0;
2873 if (ref_to_worktree_map.worktrees) {
2874 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2875 struct ref_to_worktree_entry, ent);
2876 free_worktrees(ref_to_worktree_map.worktrees);
2877 ref_to_worktree_map.worktrees = NULL;
2880 FREE_AND_NULL(array->counts);
2883 #define EXCLUDE_REACHED 0
2884 #define INCLUDE_REACHED 1
2885 static void reach_filter(struct ref_array *array,
2886 struct commit_list **check_reachable,
2887 int include_reached)
2889 int i, old_nr;
2890 struct commit **to_clear;
2892 if (!*check_reachable)
2893 return;
2895 CALLOC_ARRAY(to_clear, array->nr);
2896 for (i = 0; i < array->nr; i++) {
2897 struct ref_array_item *item = array->items[i];
2898 to_clear[i] = item->commit;
2901 tips_reachable_from_bases(the_repository,
2902 *check_reachable,
2903 to_clear, array->nr,
2904 UNINTERESTING);
2906 old_nr = array->nr;
2907 array->nr = 0;
2909 for (i = 0; i < old_nr; i++) {
2910 struct ref_array_item *item = array->items[i];
2911 struct commit *commit = item->commit;
2913 int is_merged = !!(commit->object.flags & UNINTERESTING);
2915 if (is_merged == include_reached)
2916 array->items[array->nr++] = array->items[i];
2917 else
2918 free_array_item(item);
2921 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2923 while (*check_reachable) {
2924 struct commit *merge_commit = pop_commit(check_reachable);
2925 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2928 free(to_clear);
2931 void filter_ahead_behind(struct repository *r,
2932 struct ref_format *format,
2933 struct ref_array *array)
2935 struct commit **commits;
2936 size_t commits_nr = format->bases.nr + array->nr;
2938 if (!format->bases.nr || !array->nr)
2939 return;
2941 ALLOC_ARRAY(commits, commits_nr);
2942 for (size_t i = 0; i < format->bases.nr; i++)
2943 commits[i] = format->bases.items[i].util;
2945 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
2947 commits_nr = format->bases.nr;
2948 array->counts_nr = 0;
2949 for (size_t i = 0; i < array->nr; i++) {
2950 const char *name = array->items[i]->refname;
2951 commits[commits_nr] = lookup_commit_reference_by_name(name);
2953 if (!commits[commits_nr])
2954 continue;
2956 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
2957 for (size_t j = 0; j < format->bases.nr; j++) {
2958 struct ahead_behind_count *count;
2959 count = &array->counts[array->counts_nr++];
2960 count->tip_index = commits_nr;
2961 count->base_index = j;
2963 array->items[i]->counts[j] = count;
2965 commits_nr++;
2968 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
2969 free(commits);
2973 * API for filtering a set of refs. Based on the type of refs the user
2974 * has requested, we iterate through those refs and apply filters
2975 * as per the given ref_filter structure and finally store the
2976 * filtered refs in the ref_array structure.
2978 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2980 struct ref_filter_cbdata ref_cbdata;
2981 int save_commit_buffer_orig;
2982 int ret = 0;
2984 ref_cbdata.array = array;
2985 ref_cbdata.filter = filter;
2987 filter->kind = type & FILTER_REFS_KIND_MASK;
2989 save_commit_buffer_orig = save_commit_buffer;
2990 save_commit_buffer = 0;
2992 init_contains_cache(&ref_cbdata.contains_cache);
2993 init_contains_cache(&ref_cbdata.no_contains_cache);
2995 /* Simple per-ref filtering */
2996 if (!filter->kind)
2997 die("filter_refs: invalid type");
2998 else {
3000 * For common cases where we need only branches or remotes or tags,
3001 * we only iterate through those refs. If a mix of refs is needed,
3002 * we iterate over all refs and filter out required refs with the help
3003 * of filter_ref_kind().
3005 if (filter->kind == FILTER_REFS_BRANCHES)
3006 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
3007 else if (filter->kind == FILTER_REFS_REMOTES)
3008 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
3009 else if (filter->kind == FILTER_REFS_TAGS)
3010 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
3011 else if (filter->kind & FILTER_REFS_ALL)
3012 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
3013 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
3014 head_ref(ref_filter_handler, &ref_cbdata);
3017 clear_contains_cache(&ref_cbdata.contains_cache);
3018 clear_contains_cache(&ref_cbdata.no_contains_cache);
3020 /* Filters that need revision walking */
3021 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
3022 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
3024 save_commit_buffer = save_commit_buffer_orig;
3025 return ret;
3028 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
3030 if (!(a->kind ^ b->kind))
3031 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
3032 if (a->kind & FILTER_REFS_DETACHED_HEAD)
3033 return -1;
3034 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
3035 return 1;
3036 BUG("should have died in the xor check above");
3037 return 0;
3040 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
3042 const char *s1 = vs1, *s2 = vs2;
3043 const char *end = s1 + n;
3045 for (; s1 < end; s1++, s2++) {
3046 int diff = tolower(*s1) - tolower(*s2);
3047 if (diff)
3048 return diff;
3050 return 0;
3053 struct ref_sorting {
3054 struct ref_sorting *next;
3055 int atom; /* index into used_atom array (internal) */
3056 enum ref_sorting_order sort_flags;
3059 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
3061 struct atom_value *va, *vb;
3062 int cmp;
3063 int cmp_detached_head = 0;
3064 cmp_type cmp_type = used_atom[s->atom].type;
3065 struct strbuf err = STRBUF_INIT;
3067 if (get_ref_atom_value(a, s->atom, &va, &err))
3068 die("%s", err.buf);
3069 if (get_ref_atom_value(b, s->atom, &vb, &err))
3070 die("%s", err.buf);
3071 strbuf_release(&err);
3072 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
3073 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
3074 cmp = compare_detached_head(a, b);
3075 cmp_detached_head = 1;
3076 } else if (s->sort_flags & REF_SORTING_VERSION) {
3077 cmp = versioncmp(va->s, vb->s);
3078 } else if (cmp_type == FIELD_STR) {
3079 if (va->s_size < 0 && vb->s_size < 0) {
3080 int (*cmp_fn)(const char *, const char *);
3081 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3082 ? strcasecmp : strcmp;
3083 cmp = cmp_fn(va->s, vb->s);
3084 } else {
3085 size_t a_size = va->s_size < 0 ?
3086 strlen(va->s) : va->s_size;
3087 size_t b_size = vb->s_size < 0 ?
3088 strlen(vb->s) : vb->s_size;
3089 int (*cmp_fn)(const void *, const void *, size_t);
3090 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3091 ? memcasecmp : memcmp;
3093 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3094 a_size : b_size);
3095 if (!cmp) {
3096 if (a_size > b_size)
3097 cmp = 1;
3098 else if (a_size < b_size)
3099 cmp = -1;
3102 } else {
3103 if (va->value < vb->value)
3104 cmp = -1;
3105 else if (va->value == vb->value)
3106 cmp = 0;
3107 else
3108 cmp = 1;
3111 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3112 ? -cmp : cmp;
3115 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3117 struct ref_array_item *a = *((struct ref_array_item **)a_);
3118 struct ref_array_item *b = *((struct ref_array_item **)b_);
3119 struct ref_sorting *s;
3121 for (s = ref_sorting; s; s = s->next) {
3122 int cmp = cmp_ref_sorting(s, a, b);
3123 if (cmp)
3124 return cmp;
3126 s = ref_sorting;
3127 return s && s->sort_flags & REF_SORTING_ICASE ?
3128 strcasecmp(a->refname, b->refname) :
3129 strcmp(a->refname, b->refname);
3132 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3133 unsigned int mask, int on)
3135 for (; sorting; sorting = sorting->next) {
3136 if (on)
3137 sorting->sort_flags |= mask;
3138 else
3139 sorting->sort_flags &= ~mask;
3143 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3145 QSORT_S(array->items, array->nr, compare_refs, sorting);
3148 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3150 struct strbuf *s = &state->stack->output;
3152 while (*cp && (!ep || cp < ep)) {
3153 if (*cp == '%') {
3154 if (cp[1] == '%')
3155 cp++;
3156 else {
3157 int ch = hex2chr(cp + 1);
3158 if (0 <= ch) {
3159 strbuf_addch(s, ch);
3160 cp += 3;
3161 continue;
3165 strbuf_addch(s, *cp);
3166 cp++;
3170 int format_ref_array_item(struct ref_array_item *info,
3171 struct ref_format *format,
3172 struct strbuf *final_buf,
3173 struct strbuf *error_buf)
3175 const char *cp, *sp, *ep;
3176 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3178 state.quote_style = format->quote_style;
3179 push_stack_element(&state.stack);
3181 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3182 struct atom_value *atomv;
3183 int pos;
3185 ep = strchr(sp, ')');
3186 if (cp < sp)
3187 append_literal(cp, sp, &state);
3188 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3189 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3190 atomv->handler(atomv, &state, error_buf)) {
3191 pop_stack_element(&state.stack);
3192 return -1;
3195 if (*cp) {
3196 sp = cp + strlen(cp);
3197 append_literal(cp, sp, &state);
3199 if (format->need_color_reset_at_eol) {
3200 struct atom_value resetv = ATOM_VALUE_INIT;
3201 resetv.s = GIT_COLOR_RESET;
3202 if (append_atom(&resetv, &state, error_buf)) {
3203 pop_stack_element(&state.stack);
3204 return -1;
3207 if (state.stack->prev) {
3208 pop_stack_element(&state.stack);
3209 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3211 strbuf_addbuf(final_buf, &state.stack->output);
3212 pop_stack_element(&state.stack);
3213 return 0;
3216 void pretty_print_ref(const char *name, const struct object_id *oid,
3217 struct ref_format *format)
3219 struct ref_array_item *ref_item;
3220 struct strbuf output = STRBUF_INIT;
3221 struct strbuf err = STRBUF_INIT;
3223 ref_item = new_ref_array_item(name, oid);
3224 ref_item->kind = ref_kind_from_refname(name);
3225 if (format_ref_array_item(ref_item, format, &output, &err))
3226 die("%s", err.buf);
3227 fwrite(output.buf, 1, output.len, stdout);
3228 putchar('\n');
3230 strbuf_release(&err);
3231 strbuf_release(&output);
3232 free_array_item(ref_item);
3235 static int parse_sorting_atom(const char *atom)
3238 * This parses an atom using a dummy ref_format, since we don't
3239 * actually care about the formatting details.
3241 struct ref_format dummy = REF_FORMAT_INIT;
3242 const char *end = atom + strlen(atom);
3243 struct strbuf err = STRBUF_INIT;
3244 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3245 if (res < 0)
3246 die("%s", err.buf);
3247 strbuf_release(&err);
3248 return res;
3251 /* If no sorting option is given, use refname to sort as default */
3252 static struct ref_sorting *ref_default_sorting(void)
3254 static const char cstr_name[] = "refname";
3256 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
3258 sorting->next = NULL;
3259 sorting->atom = parse_sorting_atom(cstr_name);
3260 return sorting;
3263 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3265 struct ref_sorting *s;
3267 CALLOC_ARRAY(s, 1);
3268 s->next = *sorting_tail;
3269 *sorting_tail = s;
3271 if (*arg == '-') {
3272 s->sort_flags |= REF_SORTING_REVERSE;
3273 arg++;
3275 if (skip_prefix(arg, "version:", &arg) ||
3276 skip_prefix(arg, "v:", &arg))
3277 s->sort_flags |= REF_SORTING_VERSION;
3278 s->atom = parse_sorting_atom(arg);
3281 struct ref_sorting *ref_sorting_options(struct string_list *options)
3283 struct string_list_item *item;
3284 struct ref_sorting *sorting = NULL, **tail = &sorting;
3286 if (!options->nr) {
3287 sorting = ref_default_sorting();
3288 } else {
3289 for_each_string_list_item(item, options)
3290 parse_ref_sorting(tail, item->string);
3294 * From here on, the ref_sorting list should be used to talk
3295 * about the sort order used for the output. The caller
3296 * should not touch the string form anymore.
3298 string_list_clear(options, 0);
3299 return sorting;
3302 void ref_sorting_release(struct ref_sorting *sorting)
3304 while (sorting) {
3305 struct ref_sorting *next = sorting->next;
3306 free(sorting);
3307 sorting = next;
3311 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3313 struct ref_filter *rf = opt->value;
3314 struct object_id oid;
3315 struct commit *merge_commit;
3317 BUG_ON_OPT_NEG(unset);
3319 if (repo_get_oid(the_repository, arg, &oid))
3320 die(_("malformed object name %s"), arg);
3322 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3324 if (!merge_commit)
3325 return error(_("option `%s' must point to a commit"), opt->long_name);
3327 if (starts_with(opt->long_name, "no"))
3328 commit_list_insert(merge_commit, &rf->unreachable_from);
3329 else
3330 commit_list_insert(merge_commit, &rf->reachable_from);
3332 return 0;
3335 void ref_filter_init(struct ref_filter *filter)
3337 struct ref_filter blank = REF_FILTER_INIT;
3338 memcpy(filter, &blank, sizeof(blank));
3341 void ref_filter_clear(struct ref_filter *filter)
3343 strvec_clear(&filter->exclude);
3344 oid_array_clear(&filter->points_at);
3345 free_commit_list(filter->with_commit);
3346 free_commit_list(filter->no_commit);
3347 free_commit_list(filter->reachable_from);
3348 free_commit_list(filter->unreachable_from);
3349 ref_filter_init(filter);