Merge branch 'ja/worktree-orphan' into maint-2.42
[git/debian.git] / ref-filter.c
blob9dbc4f71bd272a25423f131bbbbb23152a248be8
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 "remote.h"
17 #include "color.h"
18 #include "tag.h"
19 #include "quote.h"
20 #include "ref-filter.h"
21 #include "revision.h"
22 #include "utf8.h"
23 #include "version.h"
24 #include "versioncmp.h"
25 #include "trailer.h"
26 #include "wt-status.h"
27 #include "commit-slab.h"
28 #include "commit-graph.h"
29 #include "commit-reach.h"
30 #include "worktree.h"
31 #include "hashmap.h"
32 #include "strvec.h"
34 static struct ref_msg {
35 const char *gone;
36 const char *ahead;
37 const char *behind;
38 const char *ahead_behind;
39 } msgs = {
40 /* Untranslated plumbing messages: */
41 "gone",
42 "ahead %d",
43 "behind %d",
44 "ahead %d, behind %d"
47 void setup_ref_filter_porcelain_msg(void)
49 msgs.gone = _("gone");
50 msgs.ahead = _("ahead %d");
51 msgs.behind = _("behind %d");
52 msgs.ahead_behind = _("ahead %d, behind %d");
55 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
56 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
57 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
59 struct align {
60 align_type position;
61 unsigned int width;
64 struct if_then_else {
65 cmp_status cmp_status;
66 const char *str;
67 unsigned int then_atom_seen : 1,
68 else_atom_seen : 1,
69 condition_satisfied : 1;
72 struct refname_atom {
73 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
74 int lstrip, rstrip;
77 static struct ref_trailer_buf {
78 struct string_list filter_list;
79 struct strbuf sepbuf;
80 struct strbuf kvsepbuf;
81 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
83 static struct expand_data {
84 struct object_id oid;
85 enum object_type type;
86 unsigned long size;
87 off_t disk_size;
88 struct object_id delta_base_oid;
89 void *content;
91 struct object_info info;
92 } oi, oi_deref;
94 struct ref_to_worktree_entry {
95 struct hashmap_entry ent;
96 struct worktree *wt; /* key is wt->head_ref */
99 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
100 const struct hashmap_entry *eptr,
101 const struct hashmap_entry *kptr,
102 const void *keydata_aka_refname)
104 const struct ref_to_worktree_entry *e, *k;
106 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
107 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
109 return strcmp(e->wt->head_ref,
110 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
113 static struct ref_to_worktree_map {
114 struct hashmap map;
115 struct worktree **worktrees;
116 } ref_to_worktree_map;
119 * The enum atom_type is used as the index of valid_atom array.
120 * In the atom parsing stage, it will be passed to used_atom.atom_type
121 * as the identifier of the atom type. We can check the type of used_atom
122 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
124 enum atom_type {
125 ATOM_REFNAME,
126 ATOM_OBJECTTYPE,
127 ATOM_OBJECTSIZE,
128 ATOM_OBJECTNAME,
129 ATOM_DELTABASE,
130 ATOM_TREE,
131 ATOM_PARENT,
132 ATOM_NUMPARENT,
133 ATOM_OBJECT,
134 ATOM_TYPE,
135 ATOM_TAG,
136 ATOM_AUTHOR,
137 ATOM_AUTHORNAME,
138 ATOM_AUTHOREMAIL,
139 ATOM_AUTHORDATE,
140 ATOM_COMMITTER,
141 ATOM_COMMITTERNAME,
142 ATOM_COMMITTEREMAIL,
143 ATOM_COMMITTERDATE,
144 ATOM_TAGGER,
145 ATOM_TAGGERNAME,
146 ATOM_TAGGEREMAIL,
147 ATOM_TAGGERDATE,
148 ATOM_CREATOR,
149 ATOM_CREATORDATE,
150 ATOM_DESCRIBE,
151 ATOM_SUBJECT,
152 ATOM_BODY,
153 ATOM_TRAILERS,
154 ATOM_CONTENTS,
155 ATOM_SIGNATURE,
156 ATOM_RAW,
157 ATOM_UPSTREAM,
158 ATOM_PUSH,
159 ATOM_SYMREF,
160 ATOM_FLAG,
161 ATOM_HEAD,
162 ATOM_COLOR,
163 ATOM_WORKTREEPATH,
164 ATOM_ALIGN,
165 ATOM_END,
166 ATOM_IF,
167 ATOM_THEN,
168 ATOM_ELSE,
169 ATOM_REST,
170 ATOM_AHEADBEHIND,
174 * An atom is a valid field atom listed below, possibly prefixed with
175 * a "*" to denote deref_tag().
177 * We parse given format string and sort specifiers, and make a list
178 * of properties that we need to extract out of objects. ref_array_item
179 * structure will hold an array of values extracted that can be
180 * indexed with the "atom number", which is an index into this
181 * array.
183 static struct used_atom {
184 enum atom_type atom_type;
185 const char *name;
186 cmp_type type;
187 info_source source;
188 union {
189 char color[COLOR_MAXLEN];
190 struct align align;
191 struct {
192 enum {
193 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
194 } option;
195 struct refname_atom refname;
196 unsigned int nobracket : 1, push : 1, push_remote : 1;
197 } remote_ref;
198 struct {
199 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
200 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
201 struct process_trailer_options trailer_opts;
202 unsigned int nlines;
203 } contents;
204 struct {
205 enum { RAW_BARE, RAW_LENGTH } option;
206 } raw_data;
207 struct {
208 cmp_status cmp_status;
209 const char *str;
210 } if_then_else;
211 struct {
212 enum { O_FULL, O_LENGTH, O_SHORT } option;
213 unsigned int length;
214 } oid;
215 struct {
216 enum { O_SIZE, O_SIZE_DISK } option;
217 } objectsize;
218 struct email_option {
219 enum { EO_RAW, EO_TRIM, EO_LOCALPART } option;
220 } email_option;
221 struct {
222 enum { S_BARE, S_GRADE, S_SIGNER, S_KEY,
223 S_FINGERPRINT, S_PRI_KEY_FP, S_TRUST_LEVEL } option;
224 } signature;
225 const char **describe_args;
226 struct refname_atom refname;
227 char *head;
228 } u;
229 } *used_atom;
230 static int used_atom_cnt, need_tagged, need_symref;
233 * Expand string, append it to strbuf *sb, then return error code ret.
234 * Allow to save few lines of code.
236 __attribute__((format (printf, 3, 4)))
237 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
239 va_list ap;
240 va_start(ap, fmt);
241 strbuf_vaddf(sb, fmt, ap);
242 va_end(ap);
243 return ret;
246 static int err_no_arg(struct strbuf *sb, const char *name)
248 size_t namelen = strchrnul(name, ':') - name;
249 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
250 (int)namelen, name);
251 return -1;
254 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
256 size_t namelen = strchrnul(name, ':') - name;
257 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
258 (int)namelen, name, arg);
259 return -1;
263 * Parse option of name "candidate" in the option string "to_parse" of
264 * the form
266 * "candidate1[=val1],candidate2[=val2],candidate3[=val3],..."
268 * The remaining part of "to_parse" is stored in "end" (if we are
269 * parsing the last candidate, then this is NULL) and the value of
270 * the candidate is stored in "valuestart" and its length in "valuelen",
271 * that is the portion after "=". Since it is possible for a "candidate"
272 * to not have a value, in such cases, "valuestart" is set to point to
273 * NULL and "valuelen" to 0.
275 * The function returns 1 on success. It returns 0 if we don't find
276 * "candidate" in "to_parse" or we find "candidate" but it is followed
277 * by more chars (for example, "candidatefoo"), that is, we don't find
278 * an exact match.
280 * This function only does the above for one "candidate" at a time. So
281 * it has to be called each time trying to parse a "candidate" in the
282 * option string "to_parse".
284 static int match_atom_arg_value(const char *to_parse, const char *candidate,
285 const char **end, const char **valuestart,
286 size_t *valuelen)
288 const char *atom;
290 if (!skip_prefix(to_parse, candidate, &atom))
291 return 0; /* definitely not "candidate" */
293 if (*atom == '=') {
294 /* we just saw "candidate=" */
295 *valuestart = atom + 1;
296 atom = strchrnul(*valuestart, ',');
297 *valuelen = atom - *valuestart;
298 } else if (*atom != ',' && *atom != '\0') {
299 /* key begins with "candidate" but has more chars */
300 return 0;
301 } else {
302 /* just "candidate" without "=val" */
303 *valuestart = NULL;
304 *valuelen = 0;
307 /* atom points at either the ',' or NUL after this key[=val] */
308 if (*atom == ',')
309 atom++;
310 else if (*atom)
311 BUG("Why is *atom not NULL yet?");
313 *end = atom;
314 return 1;
318 * Parse boolean option of name "candidate" in the option list "to_parse"
319 * of the form
321 * "candidate1[=bool1],candidate2[=bool2],candidate3[=bool3],..."
323 * The remaining part of "to_parse" is stored in "end" (if we are parsing
324 * the last candidate, then this is NULL) and the value (if given) is
325 * parsed and stored in "val", so "val" always points to either 0 or 1.
326 * If the value is not given, then "val" is set to point to 1.
328 * The boolean value is parsed using "git_parse_maybe_bool()", so the
329 * accepted values are
331 * to set true - "1", "yes", "true"
332 * to set false - "0", "no", "false"
334 * This function returns 1 on success. It returns 0 when we don't find
335 * an exact match for "candidate" or when the boolean value given is
336 * not valid.
338 static int match_atom_bool_arg(const char *to_parse, const char *candidate,
339 const char **end, int *val)
341 const char *argval;
342 char *strval;
343 size_t arglen;
344 int v;
346 if (!match_atom_arg_value(to_parse, candidate, end, &argval, &arglen))
347 return 0;
349 if (!argval) {
350 *val = 1;
351 return 1;
354 strval = xstrndup(argval, arglen);
355 v = git_parse_maybe_bool(strval);
356 free(strval);
358 if (v == -1)
359 return 0;
361 *val = v;
363 return 1;
366 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
367 const char *color_value, struct strbuf *err)
369 if (!color_value)
370 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
371 if (color_parse(color_value, atom->u.color) < 0)
372 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
373 color_value);
375 * We check this after we've parsed the color, which lets us complain
376 * about syntactically bogus color names even if they won't be used.
378 if (!want_color(format->use_color))
379 color_parse("", atom->u.color);
380 return 0;
383 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
384 const char *name, struct strbuf *err)
386 if (!arg)
387 atom->option = R_NORMAL;
388 else if (!strcmp(arg, "short"))
389 atom->option = R_SHORT;
390 else if (skip_prefix(arg, "lstrip=", &arg) ||
391 skip_prefix(arg, "strip=", &arg)) {
392 atom->option = R_LSTRIP;
393 if (strtol_i(arg, 10, &atom->lstrip))
394 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
395 } else if (skip_prefix(arg, "rstrip=", &arg)) {
396 atom->option = R_RSTRIP;
397 if (strtol_i(arg, 10, &atom->rstrip))
398 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
399 } else
400 return err_bad_arg(err, name, arg);
401 return 0;
404 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
405 struct used_atom *atom,
406 const char *arg, struct strbuf *err)
408 struct string_list params = STRING_LIST_INIT_DUP;
409 int i;
411 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
412 atom->u.remote_ref.push = 1;
414 if (!arg) {
415 atom->u.remote_ref.option = RR_REF;
416 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
417 arg, atom->name, err);
420 atom->u.remote_ref.nobracket = 0;
421 string_list_split(&params, arg, ',', -1);
423 for (i = 0; i < params.nr; i++) {
424 const char *s = params.items[i].string;
426 if (!strcmp(s, "track"))
427 atom->u.remote_ref.option = RR_TRACK;
428 else if (!strcmp(s, "trackshort"))
429 atom->u.remote_ref.option = RR_TRACKSHORT;
430 else if (!strcmp(s, "nobracket"))
431 atom->u.remote_ref.nobracket = 1;
432 else if (!strcmp(s, "remotename")) {
433 atom->u.remote_ref.option = RR_REMOTE_NAME;
434 atom->u.remote_ref.push_remote = 1;
435 } else if (!strcmp(s, "remoteref")) {
436 atom->u.remote_ref.option = RR_REMOTE_REF;
437 atom->u.remote_ref.push_remote = 1;
438 } else {
439 atom->u.remote_ref.option = RR_REF;
440 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
441 arg, atom->name, err)) {
442 string_list_clear(&params, 0);
443 return -1;
448 string_list_clear(&params, 0);
449 return 0;
452 static int objecttype_atom_parser(struct ref_format *format UNUSED,
453 struct used_atom *atom,
454 const char *arg, struct strbuf *err)
456 if (arg)
457 return err_no_arg(err, "objecttype");
458 if (*atom->name == '*')
459 oi_deref.info.typep = &oi_deref.type;
460 else
461 oi.info.typep = &oi.type;
462 return 0;
465 static int objectsize_atom_parser(struct ref_format *format UNUSED,
466 struct used_atom *atom,
467 const char *arg, struct strbuf *err)
469 if (!arg) {
470 atom->u.objectsize.option = O_SIZE;
471 if (*atom->name == '*')
472 oi_deref.info.sizep = &oi_deref.size;
473 else
474 oi.info.sizep = &oi.size;
475 } else if (!strcmp(arg, "disk")) {
476 atom->u.objectsize.option = O_SIZE_DISK;
477 if (*atom->name == '*')
478 oi_deref.info.disk_sizep = &oi_deref.disk_size;
479 else
480 oi.info.disk_sizep = &oi.disk_size;
481 } else
482 return err_bad_arg(err, "objectsize", arg);
483 return 0;
486 static int deltabase_atom_parser(struct ref_format *format UNUSED,
487 struct used_atom *atom,
488 const char *arg, struct strbuf *err)
490 if (arg)
491 return err_no_arg(err, "deltabase");
492 if (*atom->name == '*')
493 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
494 else
495 oi.info.delta_base_oid = &oi.delta_base_oid;
496 return 0;
499 static int body_atom_parser(struct ref_format *format UNUSED,
500 struct used_atom *atom,
501 const char *arg, struct strbuf *err)
503 if (arg)
504 return err_no_arg(err, "body");
505 atom->u.contents.option = C_BODY_DEP;
506 return 0;
509 static int subject_atom_parser(struct ref_format *format UNUSED,
510 struct used_atom *atom,
511 const char *arg, struct strbuf *err)
513 if (!arg)
514 atom->u.contents.option = C_SUB;
515 else if (!strcmp(arg, "sanitize"))
516 atom->u.contents.option = C_SUB_SANITIZE;
517 else
518 return err_bad_arg(err, "subject", arg);
519 return 0;
522 static int parse_signature_option(const char *arg)
524 if (!arg)
525 return S_BARE;
526 else if (!strcmp(arg, "signer"))
527 return S_SIGNER;
528 else if (!strcmp(arg, "grade"))
529 return S_GRADE;
530 else if (!strcmp(arg, "key"))
531 return S_KEY;
532 else if (!strcmp(arg, "fingerprint"))
533 return S_FINGERPRINT;
534 else if (!strcmp(arg, "primarykeyfingerprint"))
535 return S_PRI_KEY_FP;
536 else if (!strcmp(arg, "trustlevel"))
537 return S_TRUST_LEVEL;
538 return -1;
541 static int signature_atom_parser(struct ref_format *format UNUSED,
542 struct used_atom *atom,
543 const char *arg, struct strbuf *err)
545 int opt = parse_signature_option(arg);
546 if (opt < 0)
547 return err_bad_arg(err, "signature", arg);
548 atom->u.signature.option = opt;
549 return 0;
552 static int trailers_atom_parser(struct ref_format *format, struct used_atom *atom,
553 const char *arg, struct strbuf *err)
555 atom->u.contents.trailer_opts.no_divider = 1;
557 if (arg) {
558 const char *argbuf = xstrfmt("%s)", arg);
559 char *invalid_arg = NULL;
561 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
562 &ref_trailer_buf.filter_list,
563 &ref_trailer_buf.sepbuf,
564 &ref_trailer_buf.kvsepbuf,
565 &argbuf, &invalid_arg)) {
566 if (!invalid_arg)
567 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
568 else
569 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
570 free((char *)invalid_arg);
571 return -1;
574 atom->u.contents.option = C_TRAILERS;
575 return 0;
578 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
579 const char *arg, struct strbuf *err)
581 if (!arg)
582 atom->u.contents.option = C_BARE;
583 else if (!strcmp(arg, "body"))
584 atom->u.contents.option = C_BODY;
585 else if (!strcmp(arg, "size")) {
586 atom->type = FIELD_ULONG;
587 atom->u.contents.option = C_LENGTH;
588 } else if (!strcmp(arg, "signature"))
589 atom->u.contents.option = C_SIG;
590 else if (!strcmp(arg, "subject"))
591 atom->u.contents.option = C_SUB;
592 else if (!strcmp(arg, "trailers")) {
593 if (trailers_atom_parser(format, atom, NULL, err))
594 return -1;
595 } else if (skip_prefix(arg, "trailers:", &arg)) {
596 if (trailers_atom_parser(format, atom, arg, err))
597 return -1;
598 } else if (skip_prefix(arg, "lines=", &arg)) {
599 atom->u.contents.option = C_LINES;
600 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
601 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
602 } else
603 return err_bad_arg(err, "contents", arg);
604 return 0;
607 static int describe_atom_option_parser(struct strvec *args, const char **arg,
608 struct strbuf *err)
610 const char *argval;
611 size_t arglen = 0;
612 int optval = 0;
614 if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {
615 if (!optval)
616 strvec_push(args, "--no-tags");
617 else
618 strvec_push(args, "--tags");
619 return 1;
622 if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {
623 char *endptr;
625 if (!arglen)
626 return strbuf_addf_ret(err, -1,
627 _("argument expected for %s"),
628 "describe:abbrev");
629 if (strtol(argval, &endptr, 10) < 0)
630 return strbuf_addf_ret(err, -1,
631 _("positive value expected %s=%s"),
632 "describe:abbrev", argval);
633 if (endptr - argval != arglen)
634 return strbuf_addf_ret(err, -1,
635 _("cannot fully parse %s=%s"),
636 "describe:abbrev", argval);
638 strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);
639 return 1;
642 if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {
643 if (!arglen)
644 return strbuf_addf_ret(err, -1,
645 _("value expected %s="),
646 "describe:match");
648 strvec_pushf(args, "--match=%.*s", (int)arglen, argval);
649 return 1;
652 if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {
653 if (!arglen)
654 return strbuf_addf_ret(err, -1,
655 _("value expected %s="),
656 "describe:exclude");
658 strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);
659 return 1;
662 return 0;
665 static int describe_atom_parser(struct ref_format *format UNUSED,
666 struct used_atom *atom,
667 const char *arg, struct strbuf *err)
669 struct strvec args = STRVEC_INIT;
671 for (;;) {
672 int found = 0;
673 const char *bad_arg = arg;
675 if (!arg || !*arg)
676 break;
678 found = describe_atom_option_parser(&args, &arg, err);
679 if (found < 0)
680 return found;
681 if (!found)
682 return err_bad_arg(err, "describe", bad_arg);
684 atom->u.describe_args = strvec_detach(&args);
685 return 0;
688 static int raw_atom_parser(struct ref_format *format UNUSED,
689 struct used_atom *atom,
690 const char *arg, struct strbuf *err)
692 if (!arg)
693 atom->u.raw_data.option = RAW_BARE;
694 else if (!strcmp(arg, "size")) {
695 atom->type = FIELD_ULONG;
696 atom->u.raw_data.option = RAW_LENGTH;
697 } else
698 return err_bad_arg(err, "raw", arg);
699 return 0;
702 static int oid_atom_parser(struct ref_format *format UNUSED,
703 struct used_atom *atom,
704 const char *arg, struct strbuf *err)
706 if (!arg)
707 atom->u.oid.option = O_FULL;
708 else if (!strcmp(arg, "short"))
709 atom->u.oid.option = O_SHORT;
710 else if (skip_prefix(arg, "short=", &arg)) {
711 atom->u.oid.option = O_LENGTH;
712 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
713 atom->u.oid.length == 0)
714 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
715 if (atom->u.oid.length < MINIMUM_ABBREV)
716 atom->u.oid.length = MINIMUM_ABBREV;
717 } else
718 return err_bad_arg(err, atom->name, arg);
719 return 0;
722 static int person_email_atom_parser(struct ref_format *format UNUSED,
723 struct used_atom *atom,
724 const char *arg, struct strbuf *err)
726 if (!arg)
727 atom->u.email_option.option = EO_RAW;
728 else if (!strcmp(arg, "trim"))
729 atom->u.email_option.option = EO_TRIM;
730 else if (!strcmp(arg, "localpart"))
731 atom->u.email_option.option = EO_LOCALPART;
732 else
733 return err_bad_arg(err, atom->name, arg);
734 return 0;
737 static int refname_atom_parser(struct ref_format *format UNUSED,
738 struct used_atom *atom,
739 const char *arg, struct strbuf *err)
741 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
744 static align_type parse_align_position(const char *s)
746 if (!strcmp(s, "right"))
747 return ALIGN_RIGHT;
748 else if (!strcmp(s, "middle"))
749 return ALIGN_MIDDLE;
750 else if (!strcmp(s, "left"))
751 return ALIGN_LEFT;
752 return -1;
755 static int align_atom_parser(struct ref_format *format UNUSED,
756 struct used_atom *atom,
757 const char *arg, struct strbuf *err)
759 struct align *align = &atom->u.align;
760 struct string_list params = STRING_LIST_INIT_DUP;
761 int i;
762 unsigned int width = ~0U;
764 if (!arg)
765 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
767 align->position = ALIGN_LEFT;
769 string_list_split(&params, arg, ',', -1);
770 for (i = 0; i < params.nr; i++) {
771 const char *s = params.items[i].string;
772 int position;
774 if (skip_prefix(s, "position=", &s)) {
775 position = parse_align_position(s);
776 if (position < 0) {
777 strbuf_addf(err, _("unrecognized position:%s"), s);
778 string_list_clear(&params, 0);
779 return -1;
781 align->position = position;
782 } else if (skip_prefix(s, "width=", &s)) {
783 if (strtoul_ui(s, 10, &width)) {
784 strbuf_addf(err, _("unrecognized width:%s"), s);
785 string_list_clear(&params, 0);
786 return -1;
788 } else if (!strtoul_ui(s, 10, &width))
790 else if ((position = parse_align_position(s)) >= 0)
791 align->position = position;
792 else {
793 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
794 string_list_clear(&params, 0);
795 return -1;
799 if (width == ~0U) {
800 string_list_clear(&params, 0);
801 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
803 align->width = width;
804 string_list_clear(&params, 0);
805 return 0;
808 static int if_atom_parser(struct ref_format *format UNUSED,
809 struct used_atom *atom,
810 const char *arg, struct strbuf *err)
812 if (!arg) {
813 atom->u.if_then_else.cmp_status = COMPARE_NONE;
814 return 0;
815 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
816 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
817 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
818 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
819 } else
820 return err_bad_arg(err, "if", arg);
821 return 0;
824 static int rest_atom_parser(struct ref_format *format,
825 struct used_atom *atom UNUSED,
826 const char *arg, struct strbuf *err)
828 if (arg)
829 return err_no_arg(err, "rest");
830 return 0;
833 static int ahead_behind_atom_parser(struct ref_format *format, struct used_atom *atom,
834 const char *arg, struct strbuf *err)
836 struct string_list_item *item;
838 if (!arg)
839 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
841 item = string_list_append(&format->bases, arg);
842 item->util = lookup_commit_reference_by_name(arg);
843 if (!item->util)
844 die("failed to find '%s'", arg);
846 return 0;
849 static int head_atom_parser(struct ref_format *format UNUSED,
850 struct used_atom *atom,
851 const char *arg, struct strbuf *err)
853 if (arg)
854 return err_no_arg(err, "HEAD");
855 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
856 return 0;
859 static struct {
860 const char *name;
861 info_source source;
862 cmp_type cmp_type;
863 int (*parser)(struct ref_format *format, struct used_atom *atom,
864 const char *arg, struct strbuf *err);
865 } valid_atom[] = {
866 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
867 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
868 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
869 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
870 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
871 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
872 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
873 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
874 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
875 [ATOM_TYPE] = { "type", SOURCE_OBJ },
876 [ATOM_TAG] = { "tag", SOURCE_OBJ },
877 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
878 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
879 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
880 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
881 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
882 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
883 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
884 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
885 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
886 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
887 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
888 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
889 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
890 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
891 [ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },
892 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
893 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
894 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
895 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
896 [ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },
897 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
898 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
899 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
900 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
901 [ATOM_FLAG] = { "flag", SOURCE_NONE },
902 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
903 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
904 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
905 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
906 [ATOM_END] = { "end", SOURCE_NONE },
907 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
908 [ATOM_THEN] = { "then", SOURCE_NONE },
909 [ATOM_ELSE] = { "else", SOURCE_NONE },
910 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
911 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
913 * Please update $__git_ref_fieldlist in git-completion.bash
914 * when you add new atoms
918 #define REF_FORMATTING_STATE_INIT { 0 }
920 struct ref_formatting_stack {
921 struct ref_formatting_stack *prev;
922 struct strbuf output;
923 void (*at_end)(struct ref_formatting_stack **stack);
924 void *at_end_data;
927 struct ref_formatting_state {
928 int quote_style;
929 struct ref_formatting_stack *stack;
932 struct atom_value {
933 const char *s;
934 ssize_t s_size;
935 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
936 struct strbuf *err);
937 uintmax_t value; /* used for sorting when not FIELD_STR */
938 struct used_atom *atom;
941 #define ATOM_SIZE_UNSPECIFIED (-1)
943 #define ATOM_VALUE_INIT { \
944 .s_size = ATOM_SIZE_UNSPECIFIED \
948 * Used to parse format string and sort specifiers
950 static int parse_ref_filter_atom(struct ref_format *format,
951 const char *atom, const char *ep,
952 struct strbuf *err)
954 const char *sp;
955 const char *arg;
956 int i, at, atom_len;
958 sp = atom;
959 if (*sp == '*' && sp < ep)
960 sp++; /* deref */
961 if (ep <= sp)
962 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
963 (int)(ep-atom), atom);
966 * If the atom name has a colon, strip it and everything after
967 * it off - it specifies the format for this entry, and
968 * shouldn't be used for checking against the valid_atom
969 * table.
971 arg = memchr(sp, ':', ep - sp);
972 atom_len = (arg ? arg : ep) - sp;
974 /* Do we have the atom already used elsewhere? */
975 for (i = 0; i < used_atom_cnt; i++) {
976 int len = strlen(used_atom[i].name);
977 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
978 return i;
981 /* Is the atom a valid one? */
982 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
983 int len = strlen(valid_atom[i].name);
984 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
985 break;
988 if (ARRAY_SIZE(valid_atom) <= i)
989 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
990 (int)(ep-atom), atom);
991 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
992 return strbuf_addf_ret(err, -1,
993 _("not a git repository, but the field '%.*s' requires access to object data"),
994 (int)(ep-atom), atom);
996 /* Add it in, including the deref prefix */
997 at = used_atom_cnt;
998 used_atom_cnt++;
999 REALLOC_ARRAY(used_atom, used_atom_cnt);
1000 used_atom[at].atom_type = i;
1001 used_atom[at].name = xmemdupz(atom, ep - atom);
1002 used_atom[at].type = valid_atom[i].cmp_type;
1003 used_atom[at].source = valid_atom[i].source;
1004 if (used_atom[at].source == SOURCE_OBJ) {
1005 if (*atom == '*')
1006 oi_deref.info.contentp = &oi_deref.content;
1007 else
1008 oi.info.contentp = &oi.content;
1010 if (arg) {
1011 arg = used_atom[at].name + (arg - atom) + 1;
1012 if (!*arg) {
1014 * Treat empty sub-arguments list as NULL (i.e.,
1015 * "%(atom:)" is equivalent to "%(atom)").
1017 arg = NULL;
1020 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
1021 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
1022 return -1;
1023 if (*atom == '*')
1024 need_tagged = 1;
1025 if (i == ATOM_SYMREF)
1026 need_symref = 1;
1027 return at;
1030 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
1032 switch (quote_style) {
1033 case QUOTE_NONE:
1034 if (len < 0)
1035 strbuf_addstr(s, str);
1036 else
1037 strbuf_add(s, str, len);
1038 break;
1039 case QUOTE_SHELL:
1040 sq_quote_buf(s, str);
1041 break;
1042 case QUOTE_PERL:
1043 if (len < 0)
1044 perl_quote_buf(s, str);
1045 else
1046 perl_quote_buf_with_len(s, str, len);
1047 break;
1048 case QUOTE_PYTHON:
1049 python_quote_buf(s, str);
1050 break;
1051 case QUOTE_TCL:
1052 tcl_quote_buf(s, str);
1053 break;
1057 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
1058 struct strbuf *err UNUSED)
1061 * Quote formatting is only done when the stack has a single
1062 * element. Otherwise quote formatting is done on the
1063 * element's entire output strbuf when the %(end) atom is
1064 * encountered.
1066 if (!state->stack->prev)
1067 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
1068 else if (v->s_size < 0)
1069 strbuf_addstr(&state->stack->output, v->s);
1070 else
1071 strbuf_add(&state->stack->output, v->s, v->s_size);
1072 return 0;
1075 static void push_stack_element(struct ref_formatting_stack **stack)
1077 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
1079 strbuf_init(&s->output, 0);
1080 s->prev = *stack;
1081 *stack = s;
1084 static void pop_stack_element(struct ref_formatting_stack **stack)
1086 struct ref_formatting_stack *current = *stack;
1087 struct ref_formatting_stack *prev = current->prev;
1089 if (prev)
1090 strbuf_addbuf(&prev->output, &current->output);
1091 strbuf_release(&current->output);
1092 free(current);
1093 *stack = prev;
1096 static void end_align_handler(struct ref_formatting_stack **stack)
1098 struct ref_formatting_stack *cur = *stack;
1099 struct align *align = (struct align *)cur->at_end_data;
1100 struct strbuf s = STRBUF_INIT;
1102 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
1103 strbuf_swap(&cur->output, &s);
1104 strbuf_release(&s);
1107 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1108 struct strbuf *err UNUSED)
1110 struct ref_formatting_stack *new_stack;
1112 push_stack_element(&state->stack);
1113 new_stack = state->stack;
1114 new_stack->at_end = end_align_handler;
1115 new_stack->at_end_data = &atomv->atom->u.align;
1116 return 0;
1119 static void if_then_else_handler(struct ref_formatting_stack **stack)
1121 struct ref_formatting_stack *cur = *stack;
1122 struct ref_formatting_stack *prev = cur->prev;
1123 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
1125 if (!if_then_else->then_atom_seen)
1126 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
1128 if (if_then_else->else_atom_seen) {
1130 * There is an %(else) atom: we need to drop one state from the
1131 * stack, either the %(else) branch if the condition is satisfied, or
1132 * the %(then) branch if it isn't.
1134 if (if_then_else->condition_satisfied) {
1135 strbuf_reset(&cur->output);
1136 pop_stack_element(&cur);
1137 } else {
1138 strbuf_swap(&cur->output, &prev->output);
1139 strbuf_reset(&cur->output);
1140 pop_stack_element(&cur);
1142 } else if (!if_then_else->condition_satisfied) {
1144 * No %(else) atom: just drop the %(then) branch if the
1145 * condition is not satisfied.
1147 strbuf_reset(&cur->output);
1150 *stack = cur;
1151 free(if_then_else);
1154 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1155 struct strbuf *err UNUSED)
1157 struct ref_formatting_stack *new_stack;
1158 struct if_then_else *if_then_else = xcalloc(1,
1159 sizeof(struct if_then_else));
1161 if_then_else->str = atomv->atom->u.if_then_else.str;
1162 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
1164 push_stack_element(&state->stack);
1165 new_stack = state->stack;
1166 new_stack->at_end = if_then_else_handler;
1167 new_stack->at_end_data = if_then_else;
1168 return 0;
1171 static int is_empty(struct strbuf *buf)
1173 const char *cur = buf->buf;
1174 const char *end = buf->buf + buf->len;
1176 while (cur != end && (isspace(*cur)))
1177 cur++;
1179 return cur == end;
1182 static int then_atom_handler(struct atom_value *atomv UNUSED,
1183 struct ref_formatting_state *state,
1184 struct strbuf *err)
1186 struct ref_formatting_stack *cur = state->stack;
1187 struct if_then_else *if_then_else = NULL;
1188 size_t str_len = 0;
1190 if (cur->at_end == if_then_else_handler)
1191 if_then_else = (struct if_then_else *)cur->at_end_data;
1192 if (!if_then_else)
1193 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
1194 if (if_then_else->then_atom_seen)
1195 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
1196 if (if_then_else->else_atom_seen)
1197 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
1198 if_then_else->then_atom_seen = 1;
1199 if (if_then_else->str)
1200 str_len = strlen(if_then_else->str);
1202 * If the 'equals' or 'notequals' attribute is used then
1203 * perform the required comparison. If not, only non-empty
1204 * strings satisfy the 'if' condition.
1206 if (if_then_else->cmp_status == COMPARE_EQUAL) {
1207 if (str_len == cur->output.len &&
1208 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1209 if_then_else->condition_satisfied = 1;
1210 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
1211 if (str_len != cur->output.len ||
1212 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1213 if_then_else->condition_satisfied = 1;
1214 } else if (cur->output.len && !is_empty(&cur->output))
1215 if_then_else->condition_satisfied = 1;
1216 strbuf_reset(&cur->output);
1217 return 0;
1220 static int else_atom_handler(struct atom_value *atomv UNUSED,
1221 struct ref_formatting_state *state,
1222 struct strbuf *err)
1224 struct ref_formatting_stack *prev = state->stack;
1225 struct if_then_else *if_then_else = NULL;
1227 if (prev->at_end == if_then_else_handler)
1228 if_then_else = (struct if_then_else *)prev->at_end_data;
1229 if (!if_then_else)
1230 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1231 if (!if_then_else->then_atom_seen)
1232 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1233 if (if_then_else->else_atom_seen)
1234 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1235 if_then_else->else_atom_seen = 1;
1236 push_stack_element(&state->stack);
1237 state->stack->at_end_data = prev->at_end_data;
1238 state->stack->at_end = prev->at_end;
1239 return 0;
1242 static int end_atom_handler(struct atom_value *atomv UNUSED,
1243 struct ref_formatting_state *state,
1244 struct strbuf *err)
1246 struct ref_formatting_stack *current = state->stack;
1247 struct strbuf s = STRBUF_INIT;
1249 if (!current->at_end)
1250 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1251 current->at_end(&state->stack);
1253 /* Stack may have been popped within at_end(), hence reset the current pointer */
1254 current = state->stack;
1257 * Perform quote formatting when the stack element is that of
1258 * a supporting atom. If nested then perform quote formatting
1259 * only on the topmost supporting atom.
1261 if (!current->prev->prev) {
1262 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1263 strbuf_swap(&current->output, &s);
1265 strbuf_release(&s);
1266 pop_stack_element(&state->stack);
1267 return 0;
1271 * In a format string, find the next occurrence of %(atom).
1273 static const char *find_next(const char *cp)
1275 while (*cp) {
1276 if (*cp == '%') {
1278 * %( is the start of an atom;
1279 * %% is a quoted per-cent.
1281 if (cp[1] == '(')
1282 return cp;
1283 else if (cp[1] == '%')
1284 cp++; /* skip over two % */
1285 /* otherwise this is a singleton, literal % */
1287 cp++;
1289 return NULL;
1292 static int reject_atom(enum atom_type atom_type)
1294 return atom_type == ATOM_REST;
1298 * Make sure the format string is well formed, and parse out
1299 * the used atoms.
1301 int verify_ref_format(struct ref_format *format)
1303 const char *cp, *sp;
1305 format->need_color_reset_at_eol = 0;
1306 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1307 struct strbuf err = STRBUF_INIT;
1308 const char *color, *ep = strchr(sp, ')');
1309 int at;
1311 if (!ep)
1312 return error(_("malformed format string %s"), sp);
1313 /* sp points at "%(" and ep points at the closing ")" */
1314 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1315 if (at < 0)
1316 die("%s", err.buf);
1317 if (reject_atom(used_atom[at].atom_type))
1318 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1320 if ((format->quote_style == QUOTE_PYTHON ||
1321 format->quote_style == QUOTE_SHELL ||
1322 format->quote_style == QUOTE_TCL) &&
1323 used_atom[at].atom_type == ATOM_RAW &&
1324 used_atom[at].u.raw_data.option == RAW_BARE)
1325 die(_("--format=%.*s cannot be used with "
1326 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1327 cp = ep + 1;
1329 if (skip_prefix(used_atom[at].name, "color:", &color))
1330 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1331 strbuf_release(&err);
1333 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1334 format->need_color_reset_at_eol = 0;
1335 return 0;
1338 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1339 struct used_atom *atom)
1341 switch (atom->u.oid.option) {
1342 case O_FULL:
1343 return oid_to_hex(oid);
1344 case O_LENGTH:
1345 return repo_find_unique_abbrev(the_repository, oid,
1346 atom->u.oid.length);
1347 case O_SHORT:
1348 return repo_find_unique_abbrev(the_repository, oid,
1349 DEFAULT_ABBREV);
1350 default:
1351 BUG("unknown %%(%s) option", field);
1355 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1356 struct atom_value *v, struct used_atom *atom)
1358 if (starts_with(name, field)) {
1359 v->s = xstrdup(do_grab_oid(field, oid, atom));
1360 return 1;
1362 return 0;
1365 /* See grab_values */
1366 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1368 int i;
1370 for (i = 0; i < used_atom_cnt; i++) {
1371 const char *name = used_atom[i].name;
1372 enum atom_type atom_type = used_atom[i].atom_type;
1373 struct atom_value *v = &val[i];
1374 if (!!deref != (*name == '*'))
1375 continue;
1376 if (deref)
1377 name++;
1378 if (atom_type == ATOM_OBJECTTYPE)
1379 v->s = xstrdup(type_name(oi->type));
1380 else if (atom_type == ATOM_OBJECTSIZE) {
1381 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1382 v->value = oi->disk_size;
1383 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1384 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1385 v->value = oi->size;
1386 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1388 } else if (atom_type == ATOM_DELTABASE)
1389 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1390 else if (atom_type == ATOM_OBJECTNAME && deref)
1391 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1395 /* See grab_values */
1396 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1398 int i;
1399 struct tag *tag = (struct tag *) obj;
1401 for (i = 0; i < used_atom_cnt; i++) {
1402 const char *name = used_atom[i].name;
1403 enum atom_type atom_type = used_atom[i].atom_type;
1404 struct atom_value *v = &val[i];
1405 if (!!deref != (*name == '*'))
1406 continue;
1407 if (deref)
1408 name++;
1409 if (atom_type == ATOM_TAG)
1410 v->s = xstrdup(tag->tag);
1411 else if (atom_type == ATOM_TYPE && tag->tagged)
1412 v->s = xstrdup(type_name(tag->tagged->type));
1413 else if (atom_type == ATOM_OBJECT && tag->tagged)
1414 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1418 /* See grab_values */
1419 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1421 int i;
1422 struct commit *commit = (struct commit *) obj;
1424 for (i = 0; i < used_atom_cnt; i++) {
1425 const char *name = used_atom[i].name;
1426 enum atom_type atom_type = used_atom[i].atom_type;
1427 struct atom_value *v = &val[i];
1428 if (!!deref != (*name == '*'))
1429 continue;
1430 if (deref)
1431 name++;
1432 if (atom_type == ATOM_TREE &&
1433 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1434 continue;
1435 if (atom_type == ATOM_NUMPARENT) {
1436 v->value = commit_list_count(commit->parents);
1437 v->s = xstrfmt("%lu", (unsigned long)v->value);
1439 else if (atom_type == ATOM_PARENT) {
1440 struct commit_list *parents;
1441 struct strbuf s = STRBUF_INIT;
1442 for (parents = commit->parents; parents; parents = parents->next) {
1443 struct object_id *oid = &parents->item->object.oid;
1444 if (parents != commit->parents)
1445 strbuf_addch(&s, ' ');
1446 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1448 v->s = strbuf_detach(&s, NULL);
1453 static const char *find_wholine(const char *who, int wholen, const char *buf)
1455 const char *eol;
1456 while (*buf) {
1457 if (!strncmp(buf, who, wholen) &&
1458 buf[wholen] == ' ')
1459 return buf + wholen + 1;
1460 eol = strchr(buf, '\n');
1461 if (!eol)
1462 return "";
1463 eol++;
1464 if (*eol == '\n')
1465 return ""; /* end of header */
1466 buf = eol;
1468 return "";
1471 static const char *copy_line(const char *buf)
1473 const char *eol = strchrnul(buf, '\n');
1474 return xmemdupz(buf, eol - buf);
1477 static const char *copy_name(const char *buf)
1479 const char *cp;
1480 for (cp = buf; *cp && *cp != '\n'; cp++) {
1481 if (starts_with(cp, " <"))
1482 return xmemdupz(buf, cp - buf);
1484 return xstrdup("");
1487 static const char *copy_email(const char *buf, struct used_atom *atom)
1489 const char *email = strchr(buf, '<');
1490 const char *eoemail;
1491 if (!email)
1492 return xstrdup("");
1493 switch (atom->u.email_option.option) {
1494 case EO_RAW:
1495 eoemail = strchr(email, '>');
1496 if (eoemail)
1497 eoemail++;
1498 break;
1499 case EO_TRIM:
1500 email++;
1501 eoemail = strchr(email, '>');
1502 break;
1503 case EO_LOCALPART:
1504 email++;
1505 eoemail = strchr(email, '@');
1506 if (!eoemail)
1507 eoemail = strchr(email, '>');
1508 break;
1509 default:
1510 BUG("unknown email option");
1513 if (!eoemail)
1514 return xstrdup("");
1515 return xmemdupz(email, eoemail - email);
1518 static char *copy_subject(const char *buf, unsigned long len)
1520 struct strbuf sb = STRBUF_INIT;
1521 int i;
1523 for (i = 0; i < len; i++) {
1524 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1525 continue; /* ignore CR in CRLF */
1527 if (buf[i] == '\n')
1528 strbuf_addch(&sb, ' ');
1529 else
1530 strbuf_addch(&sb, buf[i]);
1532 return strbuf_detach(&sb, NULL);
1535 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1537 const char *eoemail = strstr(buf, "> ");
1538 char *zone;
1539 timestamp_t timestamp;
1540 long tz;
1541 struct date_mode date_mode = DATE_MODE_INIT;
1542 const char *formatp;
1545 * We got here because atomname ends in "date" or "date<something>";
1546 * it's not possible that <something> is not ":<format>" because
1547 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1548 * ":" means no format is specified, and use the default.
1550 formatp = strchr(atomname, ':');
1551 if (formatp) {
1552 formatp++;
1553 parse_date_format(formatp, &date_mode);
1556 if (!eoemail)
1557 goto bad;
1558 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1559 if (timestamp == TIME_MAX)
1560 goto bad;
1561 tz = strtol(zone, NULL, 10);
1562 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1563 goto bad;
1564 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1565 v->value = timestamp;
1566 date_mode_release(&date_mode);
1567 return;
1568 bad:
1569 v->s = xstrdup("");
1570 v->value = 0;
1573 /* See grab_values */
1574 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1576 int i;
1577 int wholen = strlen(who);
1578 const char *wholine = NULL;
1580 for (i = 0; i < used_atom_cnt; i++) {
1581 const char *name = used_atom[i].name;
1582 struct atom_value *v = &val[i];
1583 if (!!deref != (*name == '*'))
1584 continue;
1585 if (deref)
1586 name++;
1587 if (strncmp(who, name, wholen))
1588 continue;
1589 if (name[wholen] != 0 &&
1590 strcmp(name + wholen, "name") &&
1591 !starts_with(name + wholen, "email") &&
1592 !starts_with(name + wholen, "date"))
1593 continue;
1594 if (!wholine)
1595 wholine = find_wholine(who, wholen, buf);
1596 if (!wholine)
1597 return; /* no point looking for it */
1598 if (name[wholen] == 0)
1599 v->s = copy_line(wholine);
1600 else if (!strcmp(name + wholen, "name"))
1601 v->s = copy_name(wholine);
1602 else if (starts_with(name + wholen, "email"))
1603 v->s = copy_email(wholine, &used_atom[i]);
1604 else if (starts_with(name + wholen, "date"))
1605 grab_date(wholine, v, name);
1609 * For a tag or a commit object, if "creator" or "creatordate" is
1610 * requested, do something special.
1612 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1613 return; /* "author" for commit object is not wanted */
1614 if (!wholine)
1615 wholine = find_wholine(who, wholen, buf);
1616 if (!wholine)
1617 return;
1618 for (i = 0; i < used_atom_cnt; i++) {
1619 const char *name = used_atom[i].name;
1620 enum atom_type atom_type = used_atom[i].atom_type;
1621 struct atom_value *v = &val[i];
1622 if (!!deref != (*name == '*'))
1623 continue;
1624 if (deref)
1625 name++;
1627 if (atom_type == ATOM_CREATORDATE)
1628 grab_date(wholine, v, name);
1629 else if (atom_type == ATOM_CREATOR)
1630 v->s = copy_line(wholine);
1634 static void grab_signature(struct atom_value *val, int deref, struct object *obj)
1636 int i;
1637 struct commit *commit = (struct commit *) obj;
1638 struct signature_check sigc = { 0 };
1639 int signature_checked = 0;
1641 for (i = 0; i < used_atom_cnt; i++) {
1642 struct used_atom *atom = &used_atom[i];
1643 const char *name = atom->name;
1644 struct atom_value *v = &val[i];
1645 int opt;
1647 if (!!deref != (*name == '*'))
1648 continue;
1649 if (deref)
1650 name++;
1652 if (!skip_prefix(name, "signature", &name) ||
1653 (*name && *name != ':'))
1654 continue;
1655 if (!*name)
1656 name = NULL;
1657 else
1658 name++;
1660 opt = parse_signature_option(name);
1661 if (opt < 0)
1662 continue;
1664 if (!signature_checked) {
1665 check_commit_signature(commit, &sigc);
1666 signature_checked = 1;
1669 switch (opt) {
1670 case S_BARE:
1671 v->s = xstrdup(sigc.output ? sigc.output: "");
1672 break;
1673 case S_SIGNER:
1674 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1675 break;
1676 case S_GRADE:
1677 switch (sigc.result) {
1678 case 'G':
1679 switch (sigc.trust_level) {
1680 case TRUST_UNDEFINED:
1681 case TRUST_NEVER:
1682 v->s = xstrfmt("%c", (char)'U');
1683 break;
1684 default:
1685 v->s = xstrfmt("%c", (char)'G');
1686 break;
1688 break;
1689 case 'B':
1690 case 'E':
1691 case 'N':
1692 case 'X':
1693 case 'Y':
1694 case 'R':
1695 v->s = xstrfmt("%c", (char)sigc.result);
1696 break;
1698 break;
1699 case S_KEY:
1700 v->s = xstrdup(sigc.key ? sigc.key : "");
1701 break;
1702 case S_FINGERPRINT:
1703 v->s = xstrdup(sigc.fingerprint ?
1704 sigc.fingerprint : "");
1705 break;
1706 case S_PRI_KEY_FP:
1707 v->s = xstrdup(sigc.primary_key_fingerprint ?
1708 sigc.primary_key_fingerprint : "");
1709 break;
1710 case S_TRUST_LEVEL:
1711 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1712 break;
1716 if (signature_checked)
1717 signature_check_clear(&sigc);
1720 static void find_subpos(const char *buf,
1721 const char **sub, size_t *sublen,
1722 const char **body, size_t *bodylen,
1723 size_t *nonsiglen,
1724 const char **sig, size_t *siglen)
1726 struct strbuf payload = STRBUF_INIT;
1727 struct strbuf signature = STRBUF_INIT;
1728 const char *eol;
1729 const char *end = buf + strlen(buf);
1730 const char *sigstart;
1732 /* parse signature first; we might not even have a subject line */
1733 parse_signature(buf, end - buf, &payload, &signature);
1734 strbuf_release(&payload);
1736 /* skip past header until we hit empty line */
1737 while (*buf && *buf != '\n') {
1738 eol = strchrnul(buf, '\n');
1739 if (*eol)
1740 eol++;
1741 buf = eol;
1743 /* skip any empty lines */
1744 while (*buf == '\n')
1745 buf++;
1746 *sig = strbuf_detach(&signature, siglen);
1747 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1749 /* subject is first non-empty line */
1750 *sub = buf;
1751 /* subject goes to first empty line before signature begins */
1752 if ((eol = strstr(*sub, "\n\n")) ||
1753 (eol = strstr(*sub, "\r\n\r\n"))) {
1754 eol = eol < sigstart ? eol : sigstart;
1755 } else {
1756 /* treat whole message as subject */
1757 eol = sigstart;
1759 buf = eol;
1760 *sublen = buf - *sub;
1761 /* drop trailing newline, if present */
1762 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1763 (*sub)[*sublen - 1] == '\r'))
1764 *sublen -= 1;
1766 /* skip any empty lines */
1767 while (*buf == '\n' || *buf == '\r')
1768 buf++;
1769 *body = buf;
1770 *bodylen = strlen(buf);
1771 *nonsiglen = sigstart - buf;
1775 * If 'lines' is greater than 0, append that many lines from the given
1776 * 'buf' of length 'size' to the given strbuf.
1778 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1780 int i;
1781 const char *sp, *eol;
1782 size_t len;
1784 sp = buf;
1786 for (i = 0; i < lines && sp < buf + size; i++) {
1787 if (i)
1788 strbuf_addstr(out, "\n ");
1789 eol = memchr(sp, '\n', size - (sp - buf));
1790 len = eol ? eol - sp : size - (sp - buf);
1791 strbuf_add(out, sp, len);
1792 if (!eol)
1793 break;
1794 sp = eol + 1;
1798 static void grab_describe_values(struct atom_value *val, int deref,
1799 struct object *obj)
1801 struct commit *commit = (struct commit *)obj;
1802 int i;
1804 for (i = 0; i < used_atom_cnt; i++) {
1805 struct used_atom *atom = &used_atom[i];
1806 enum atom_type type = atom->atom_type;
1807 const char *name = atom->name;
1808 struct atom_value *v = &val[i];
1810 struct child_process cmd = CHILD_PROCESS_INIT;
1811 struct strbuf out = STRBUF_INIT;
1812 struct strbuf err = STRBUF_INIT;
1814 if (type != ATOM_DESCRIBE)
1815 continue;
1817 if (!!deref != (*name == '*'))
1818 continue;
1820 cmd.git_cmd = 1;
1821 strvec_push(&cmd.args, "describe");
1822 strvec_pushv(&cmd.args, atom->u.describe_args);
1823 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1824 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
1825 error(_("failed to run 'describe'"));
1826 v->s = xstrdup("");
1827 continue;
1829 strbuf_rtrim(&out);
1830 v->s = strbuf_detach(&out, NULL);
1832 strbuf_release(&err);
1836 /* See grab_values */
1837 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1839 int i;
1840 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1841 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1842 void *buf = data->content;
1844 for (i = 0; i < used_atom_cnt; i++) {
1845 struct used_atom *atom = &used_atom[i];
1846 const char *name = atom->name;
1847 struct atom_value *v = &val[i];
1848 enum atom_type atom_type = atom->atom_type;
1850 if (!!deref != (*name == '*'))
1851 continue;
1852 if (deref)
1853 name++;
1855 if (atom_type == ATOM_RAW) {
1856 unsigned long buf_size = data->size;
1858 if (atom->u.raw_data.option == RAW_BARE) {
1859 v->s = xmemdupz(buf, buf_size);
1860 v->s_size = buf_size;
1861 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1862 v->value = buf_size;
1863 v->s = xstrfmt("%"PRIuMAX, v->value);
1865 continue;
1868 if ((data->type != OBJ_TAG &&
1869 data->type != OBJ_COMMIT) ||
1870 (strcmp(name, "body") &&
1871 !starts_with(name, "subject") &&
1872 !starts_with(name, "trailers") &&
1873 !starts_with(name, "contents")))
1874 continue;
1875 if (!subpos)
1876 find_subpos(buf,
1877 &subpos, &sublen,
1878 &bodypos, &bodylen, &nonsiglen,
1879 &sigpos, &siglen);
1881 if (atom->u.contents.option == C_SUB)
1882 v->s = copy_subject(subpos, sublen);
1883 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1884 struct strbuf sb = STRBUF_INIT;
1885 format_sanitized_subject(&sb, subpos, sublen);
1886 v->s = strbuf_detach(&sb, NULL);
1887 } else if (atom->u.contents.option == C_BODY_DEP)
1888 v->s = xmemdupz(bodypos, bodylen);
1889 else if (atom->u.contents.option == C_LENGTH) {
1890 v->value = strlen(subpos);
1891 v->s = xstrfmt("%"PRIuMAX, v->value);
1892 } else if (atom->u.contents.option == C_BODY)
1893 v->s = xmemdupz(bodypos, nonsiglen);
1894 else if (atom->u.contents.option == C_SIG)
1895 v->s = xmemdupz(sigpos, siglen);
1896 else if (atom->u.contents.option == C_LINES) {
1897 struct strbuf s = STRBUF_INIT;
1898 const char *contents_end = bodypos + nonsiglen;
1900 /* Size is the length of the message after removing the signature */
1901 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1902 v->s = strbuf_detach(&s, NULL);
1903 } else if (atom->u.contents.option == C_TRAILERS) {
1904 struct strbuf s = STRBUF_INIT;
1906 /* Format the trailer info according to the trailer_opts given */
1907 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1909 v->s = strbuf_detach(&s, NULL);
1910 } else if (atom->u.contents.option == C_BARE)
1911 v->s = xstrdup(subpos);
1914 free((void *)sigpos);
1918 * We want to have empty print-string for field requests
1919 * that do not apply (e.g. "authordate" for a tag object)
1921 static void fill_missing_values(struct atom_value *val)
1923 int i;
1924 for (i = 0; i < used_atom_cnt; i++) {
1925 struct atom_value *v = &val[i];
1926 if (!v->s)
1927 v->s = xstrdup("");
1932 * val is a list of atom_value to hold returned values. Extract
1933 * the values for atoms in used_atom array out of (obj, buf, sz).
1934 * when deref is false, (obj, buf, sz) is the object that is
1935 * pointed at by the ref itself; otherwise it is the object the
1936 * ref (which is a tag) refers to.
1938 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1940 void *buf = data->content;
1942 switch (obj->type) {
1943 case OBJ_TAG:
1944 grab_tag_values(val, deref, obj);
1945 grab_sub_body_contents(val, deref, data);
1946 grab_person("tagger", val, deref, buf);
1947 grab_describe_values(val, deref, obj);
1948 break;
1949 case OBJ_COMMIT:
1950 grab_commit_values(val, deref, obj);
1951 grab_sub_body_contents(val, deref, data);
1952 grab_person("author", val, deref, buf);
1953 grab_person("committer", val, deref, buf);
1954 grab_signature(val, deref, obj);
1955 grab_describe_values(val, deref, obj);
1956 break;
1957 case OBJ_TREE:
1958 /* grab_tree_values(val, deref, obj, buf, sz); */
1959 grab_sub_body_contents(val, deref, data);
1960 break;
1961 case OBJ_BLOB:
1962 /* grab_blob_values(val, deref, obj, buf, sz); */
1963 grab_sub_body_contents(val, deref, data);
1964 break;
1965 default:
1966 die("Eh? Object of type %d?", obj->type);
1970 static inline char *copy_advance(char *dst, const char *src)
1972 while (*src)
1973 *dst++ = *src++;
1974 return dst;
1977 static const char *lstrip_ref_components(const char *refname, int len)
1979 long remaining = len;
1980 const char *start = xstrdup(refname);
1981 const char *to_free = start;
1983 if (len < 0) {
1984 int i;
1985 const char *p = refname;
1987 /* Find total no of '/' separated path-components */
1988 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1991 * The number of components we need to strip is now
1992 * the total minus the components to be left (Plus one
1993 * because we count the number of '/', but the number
1994 * of components is one more than the no of '/').
1996 remaining = i + len + 1;
1999 while (remaining > 0) {
2000 switch (*start++) {
2001 case '\0':
2002 free((char *)to_free);
2003 return xstrdup("");
2004 case '/':
2005 remaining--;
2006 break;
2010 start = xstrdup(start);
2011 free((char *)to_free);
2012 return start;
2015 static const char *rstrip_ref_components(const char *refname, int len)
2017 long remaining = len;
2018 const char *start = xstrdup(refname);
2019 const char *to_free = start;
2021 if (len < 0) {
2022 int i;
2023 const char *p = refname;
2025 /* Find total no of '/' separated path-components */
2026 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2029 * The number of components we need to strip is now
2030 * the total minus the components to be left (Plus one
2031 * because we count the number of '/', but the number
2032 * of components is one more than the no of '/').
2034 remaining = i + len + 1;
2037 while (remaining-- > 0) {
2038 char *p = strrchr(start, '/');
2039 if (!p) {
2040 free((char *)to_free);
2041 return xstrdup("");
2042 } else
2043 p[0] = '\0';
2045 return start;
2048 static const char *show_ref(struct refname_atom *atom, const char *refname)
2050 if (atom->option == R_SHORT)
2051 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
2052 else if (atom->option == R_LSTRIP)
2053 return lstrip_ref_components(refname, atom->lstrip);
2054 else if (atom->option == R_RSTRIP)
2055 return rstrip_ref_components(refname, atom->rstrip);
2056 else
2057 return xstrdup(refname);
2060 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2061 struct branch *branch, const char **s)
2063 int num_ours, num_theirs;
2064 if (atom->u.remote_ref.option == RR_REF)
2065 *s = show_ref(&atom->u.remote_ref.refname, refname);
2066 else if (atom->u.remote_ref.option == RR_TRACK) {
2067 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2068 NULL, atom->u.remote_ref.push,
2069 AHEAD_BEHIND_FULL) < 0) {
2070 *s = xstrdup(msgs.gone);
2071 } else if (!num_ours && !num_theirs)
2072 *s = xstrdup("");
2073 else if (!num_ours)
2074 *s = xstrfmt(msgs.behind, num_theirs);
2075 else if (!num_theirs)
2076 *s = xstrfmt(msgs.ahead, num_ours);
2077 else
2078 *s = xstrfmt(msgs.ahead_behind,
2079 num_ours, num_theirs);
2080 if (!atom->u.remote_ref.nobracket && *s[0]) {
2081 const char *to_free = *s;
2082 *s = xstrfmt("[%s]", *s);
2083 free((void *)to_free);
2085 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2086 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2087 NULL, atom->u.remote_ref.push,
2088 AHEAD_BEHIND_FULL) < 0) {
2089 *s = xstrdup("");
2090 return;
2092 if (!num_ours && !num_theirs)
2093 *s = xstrdup("=");
2094 else if (!num_ours)
2095 *s = xstrdup("<");
2096 else if (!num_theirs)
2097 *s = xstrdup(">");
2098 else
2099 *s = xstrdup("<>");
2100 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2101 int explicit;
2102 const char *remote = atom->u.remote_ref.push ?
2103 pushremote_for_branch(branch, &explicit) :
2104 remote_for_branch(branch, &explicit);
2105 *s = xstrdup(explicit ? remote : "");
2106 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2107 const char *merge;
2109 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2110 *s = xstrdup(merge ? merge : "");
2111 } else
2112 BUG("unhandled RR_* enum");
2115 char *get_head_description(void)
2117 struct strbuf desc = STRBUF_INIT;
2118 struct wt_status_state state;
2119 memset(&state, 0, sizeof(state));
2120 wt_status_get_state(the_repository, &state, 1);
2121 if (state.rebase_in_progress ||
2122 state.rebase_interactive_in_progress) {
2123 if (state.branch)
2124 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2125 state.branch);
2126 else
2127 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2128 state.detached_from);
2129 } else if (state.bisect_in_progress)
2130 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2131 state.branch);
2132 else if (state.detached_from) {
2133 if (state.detached_at)
2134 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2135 state.detached_from);
2136 else
2137 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2138 state.detached_from);
2139 } else
2140 strbuf_addstr(&desc, _("(no branch)"));
2142 wt_status_state_free_buffers(&state);
2144 return strbuf_detach(&desc, NULL);
2147 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2149 if (!ref->symref)
2150 return xstrdup("");
2151 else
2152 return show_ref(&atom->u.refname, ref->symref);
2155 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2157 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2158 return get_head_description();
2159 return show_ref(&atom->u.refname, ref->refname);
2162 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
2163 struct expand_data *oi, struct strbuf *err)
2165 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
2166 int eaten = 1;
2167 if (oi->info.contentp) {
2168 /* We need to know that to use parse_object_buffer properly */
2169 oi->info.sizep = &oi->size;
2170 oi->info.typep = &oi->type;
2172 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
2173 OBJECT_INFO_LOOKUP_REPLACE))
2174 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2175 oid_to_hex(&oi->oid), ref->refname);
2176 if (oi->info.disk_sizep && oi->disk_size < 0)
2177 BUG("Object size is less than zero.");
2179 if (oi->info.contentp) {
2180 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
2181 if (!*obj) {
2182 if (!eaten)
2183 free(oi->content);
2184 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
2185 oid_to_hex(&oi->oid), ref->refname);
2187 grab_values(ref->value, deref, *obj, oi);
2190 grab_common_values(ref->value, deref, oi);
2191 if (!eaten)
2192 free(oi->content);
2193 return 0;
2196 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2198 int i;
2200 for (i = 0; worktrees[i]; i++) {
2201 if (worktrees[i]->head_ref) {
2202 struct ref_to_worktree_entry *entry;
2203 entry = xmalloc(sizeof(*entry));
2204 entry->wt = worktrees[i];
2205 hashmap_entry_init(&entry->ent,
2206 strhash(worktrees[i]->head_ref));
2208 hashmap_add(map, &entry->ent);
2213 static void lazy_init_worktree_map(void)
2215 if (ref_to_worktree_map.worktrees)
2216 return;
2218 ref_to_worktree_map.worktrees = get_worktrees();
2219 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2220 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2223 static char *get_worktree_path(const struct ref_array_item *ref)
2225 struct hashmap_entry entry, *e;
2226 struct ref_to_worktree_entry *lookup_result;
2228 lazy_init_worktree_map();
2230 hashmap_entry_init(&entry, strhash(ref->refname));
2231 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2233 if (!e)
2234 return xstrdup("");
2236 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2238 return xstrdup(lookup_result->wt->path);
2242 * Parse the object referred by ref, and grab needed value.
2244 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2246 struct object *obj;
2247 int i;
2248 struct object_info empty = OBJECT_INFO_INIT;
2249 int ahead_behind_atoms = 0;
2251 CALLOC_ARRAY(ref->value, used_atom_cnt);
2253 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2254 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
2255 NULL, NULL);
2256 if (!ref->symref)
2257 ref->symref = xstrdup("");
2260 /* Fill in specials first */
2261 for (i = 0; i < used_atom_cnt; i++) {
2262 struct used_atom *atom = &used_atom[i];
2263 enum atom_type atom_type = atom->atom_type;
2264 const char *name = used_atom[i].name;
2265 struct atom_value *v = &ref->value[i];
2266 int deref = 0;
2267 const char *refname;
2268 struct branch *branch = NULL;
2270 v->s_size = ATOM_SIZE_UNSPECIFIED;
2271 v->handler = append_atom;
2272 v->value = 0;
2273 v->atom = atom;
2275 if (*name == '*') {
2276 deref = 1;
2277 name++;
2280 if (atom_type == ATOM_REFNAME)
2281 refname = get_refname(atom, ref);
2282 else if (atom_type == ATOM_WORKTREEPATH) {
2283 if (ref->kind == FILTER_REFS_BRANCHES)
2284 v->s = get_worktree_path(ref);
2285 else
2286 v->s = xstrdup("");
2287 continue;
2289 else if (atom_type == ATOM_SYMREF)
2290 refname = get_symref(atom, ref);
2291 else if (atom_type == ATOM_UPSTREAM) {
2292 const char *branch_name;
2293 /* only local branches may have an upstream */
2294 if (!skip_prefix(ref->refname, "refs/heads/",
2295 &branch_name)) {
2296 v->s = xstrdup("");
2297 continue;
2299 branch = branch_get(branch_name);
2301 refname = branch_get_upstream(branch, NULL);
2302 if (refname)
2303 fill_remote_ref_details(atom, refname, branch, &v->s);
2304 else
2305 v->s = xstrdup("");
2306 continue;
2307 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2308 const char *branch_name;
2309 v->s = xstrdup("");
2310 if (!skip_prefix(ref->refname, "refs/heads/",
2311 &branch_name))
2312 continue;
2313 branch = branch_get(branch_name);
2315 if (atom->u.remote_ref.push_remote)
2316 refname = NULL;
2317 else {
2318 refname = branch_get_push(branch, NULL);
2319 if (!refname)
2320 continue;
2322 /* We will definitely re-init v->s on the next line. */
2323 free((char *)v->s);
2324 fill_remote_ref_details(atom, refname, branch, &v->s);
2325 continue;
2326 } else if (atom_type == ATOM_COLOR) {
2327 v->s = xstrdup(atom->u.color);
2328 continue;
2329 } else if (atom_type == ATOM_FLAG) {
2330 char buf[256], *cp = buf;
2331 if (ref->flag & REF_ISSYMREF)
2332 cp = copy_advance(cp, ",symref");
2333 if (ref->flag & REF_ISPACKED)
2334 cp = copy_advance(cp, ",packed");
2335 if (cp == buf)
2336 v->s = xstrdup("");
2337 else {
2338 *cp = '\0';
2339 v->s = xstrdup(buf + 1);
2341 continue;
2342 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2343 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2344 continue;
2345 } else if (atom_type == ATOM_HEAD) {
2346 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2347 v->s = xstrdup("*");
2348 else
2349 v->s = xstrdup(" ");
2350 continue;
2351 } else if (atom_type == ATOM_ALIGN) {
2352 v->handler = align_atom_handler;
2353 v->s = xstrdup("");
2354 continue;
2355 } else if (atom_type == ATOM_END) {
2356 v->handler = end_atom_handler;
2357 v->s = xstrdup("");
2358 continue;
2359 } else if (atom_type == ATOM_IF) {
2360 const char *s;
2361 if (skip_prefix(name, "if:", &s))
2362 v->s = xstrdup(s);
2363 else
2364 v->s = xstrdup("");
2365 v->handler = if_atom_handler;
2366 continue;
2367 } else if (atom_type == ATOM_THEN) {
2368 v->handler = then_atom_handler;
2369 v->s = xstrdup("");
2370 continue;
2371 } else if (atom_type == ATOM_ELSE) {
2372 v->handler = else_atom_handler;
2373 v->s = xstrdup("");
2374 continue;
2375 } else if (atom_type == ATOM_REST) {
2376 if (ref->rest)
2377 v->s = xstrdup(ref->rest);
2378 else
2379 v->s = xstrdup("");
2380 continue;
2381 } else if (atom_type == ATOM_AHEADBEHIND) {
2382 if (ref->counts) {
2383 const struct ahead_behind_count *count;
2384 count = ref->counts[ahead_behind_atoms++];
2385 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2386 } else {
2387 /* Not a commit. */
2388 v->s = xstrdup("");
2390 continue;
2391 } else
2392 continue;
2394 if (!deref)
2395 v->s = xstrdup(refname);
2396 else
2397 v->s = xstrfmt("%s^{}", refname);
2398 free((char *)refname);
2401 for (i = 0; i < used_atom_cnt; i++) {
2402 struct atom_value *v = &ref->value[i];
2403 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2404 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2405 oid_to_hex(&ref->objectname), ref->refname);
2408 if (need_tagged)
2409 oi.info.contentp = &oi.content;
2410 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2411 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2412 return 0;
2415 oi.oid = ref->objectname;
2416 if (get_object(ref, 0, &obj, &oi, err))
2417 return -1;
2420 * If there is no atom that wants to know about tagged
2421 * object, we are done.
2423 if (!need_tagged || (obj->type != OBJ_TAG))
2424 return 0;
2427 * If it is a tag object, see if we use a value that derefs
2428 * the object, and if we do grab the object it refers to.
2430 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2433 * NEEDSWORK: This derefs tag only once, which
2434 * is good to deal with chains of trust, but
2435 * is not consistent with what deref_tag() does
2436 * which peels the onion to the core.
2438 return get_object(ref, 1, &obj, &oi_deref, err);
2442 * Given a ref, return the value for the atom. This lazily gets value
2443 * out of the object by calling populate value.
2445 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2446 struct atom_value **v, struct strbuf *err)
2448 if (!ref->value) {
2449 if (populate_value(ref, err))
2450 return -1;
2451 fill_missing_values(ref->value);
2453 *v = &ref->value[atom];
2454 return 0;
2458 * Return 1 if the refname matches one of the patterns, otherwise 0.
2459 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2460 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2461 * matches "refs/heads/mas*", too).
2463 static int match_pattern(const char **patterns, const char *refname,
2464 int ignore_case)
2466 unsigned flags = 0;
2468 if (ignore_case)
2469 flags |= WM_CASEFOLD;
2472 * When no '--format' option is given we need to skip the prefix
2473 * for matching refs of tags and branches.
2475 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2476 skip_prefix(refname, "refs/heads/", &refname) ||
2477 skip_prefix(refname, "refs/remotes/", &refname) ||
2478 skip_prefix(refname, "refs/", &refname));
2480 for (; *patterns; patterns++) {
2481 if (!wildmatch(*patterns, refname, flags))
2482 return 1;
2484 return 0;
2488 * Return 1 if the refname matches one of the patterns, otherwise 0.
2489 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2490 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2491 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2493 static int match_name_as_path(const char **pattern, const char *refname,
2494 int ignore_case)
2496 int namelen = strlen(refname);
2497 unsigned flags = WM_PATHNAME;
2499 if (ignore_case)
2500 flags |= WM_CASEFOLD;
2502 for (; *pattern; pattern++) {
2503 const char *p = *pattern;
2504 int plen = strlen(p);
2506 if ((plen <= namelen) &&
2507 !strncmp(refname, p, plen) &&
2508 (refname[plen] == '\0' ||
2509 refname[plen] == '/' ||
2510 p[plen-1] == '/'))
2511 return 1;
2512 if (!wildmatch(p, refname, flags))
2513 return 1;
2515 return 0;
2518 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2519 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2521 if (!*filter->name_patterns)
2522 return 1; /* No pattern always matches */
2523 if (filter->match_as_path)
2524 return match_name_as_path(filter->name_patterns, refname,
2525 filter->ignore_case);
2526 return match_pattern(filter->name_patterns, refname,
2527 filter->ignore_case);
2530 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2532 if (!filter->exclude.nr)
2533 return 0;
2534 if (filter->match_as_path)
2535 return match_name_as_path(filter->exclude.v, refname,
2536 filter->ignore_case);
2537 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2541 * This is the same as for_each_fullref_in(), but it tries to iterate
2542 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2543 * pattern match, so the callback still has to match each ref individually.
2545 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2546 each_ref_fn cb,
2547 void *cb_data)
2549 if (!filter->match_as_path) {
2551 * in this case, the patterns are applied after
2552 * prefixes like "refs/heads/" etc. are stripped off,
2553 * so we have to look at everything:
2555 return for_each_fullref_in("", cb, cb_data);
2558 if (filter->ignore_case) {
2560 * we can't handle case-insensitive comparisons,
2561 * so just return everything and let the caller
2562 * sort it out.
2564 return for_each_fullref_in("", cb, cb_data);
2567 if (!filter->name_patterns[0]) {
2568 /* no patterns; we have to look at everything */
2569 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2570 "", filter->exclude.v, cb, cb_data);
2573 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2574 NULL, filter->name_patterns,
2575 filter->exclude.v,
2576 cb, cb_data);
2580 * Given a ref (oid, refname), check if the ref belongs to the array
2581 * of oids. If the given ref is a tag, check if the given tag points
2582 * at one of the oids in the given oid array. Returns non-zero if a
2583 * match is found.
2585 * NEEDSWORK:
2586 * As the refs are cached we might know what refname peels to without
2587 * the need to parse the object via parse_object(). peel_ref() might be a
2588 * more efficient alternative to obtain the pointee.
2590 static int match_points_at(struct oid_array *points_at,
2591 const struct object_id *oid,
2592 const char *refname)
2594 struct object *obj;
2596 if (oid_array_lookup(points_at, oid) >= 0)
2597 return 1;
2598 obj = parse_object_with_flags(the_repository, oid,
2599 PARSE_OBJECT_SKIP_HASH_CHECK);
2600 while (obj && obj->type == OBJ_TAG) {
2601 struct tag *tag = (struct tag *)obj;
2603 if (parse_tag(tag) < 0) {
2604 obj = NULL;
2605 break;
2608 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2609 return 1;
2611 obj = tag->tagged;
2613 if (!obj)
2614 die(_("malformed object at '%s'"), refname);
2615 return 0;
2619 * Allocate space for a new ref_array_item and copy the name and oid to it.
2621 * Callers can then fill in other struct members at their leisure.
2623 static struct ref_array_item *new_ref_array_item(const char *refname,
2624 const struct object_id *oid)
2626 struct ref_array_item *ref;
2628 FLEX_ALLOC_STR(ref, refname, refname);
2629 oidcpy(&ref->objectname, oid);
2630 ref->rest = NULL;
2632 return ref;
2635 struct ref_array_item *ref_array_push(struct ref_array *array,
2636 const char *refname,
2637 const struct object_id *oid)
2639 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2641 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2642 array->items[array->nr++] = ref;
2644 return ref;
2647 static int ref_kind_from_refname(const char *refname)
2649 unsigned int i;
2651 static struct {
2652 const char *prefix;
2653 unsigned int kind;
2654 } ref_kind[] = {
2655 { "refs/heads/" , FILTER_REFS_BRANCHES },
2656 { "refs/remotes/" , FILTER_REFS_REMOTES },
2657 { "refs/tags/", FILTER_REFS_TAGS}
2660 if (!strcmp(refname, "HEAD"))
2661 return FILTER_REFS_DETACHED_HEAD;
2663 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2664 if (starts_with(refname, ref_kind[i].prefix))
2665 return ref_kind[i].kind;
2668 return FILTER_REFS_OTHERS;
2671 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2673 if (filter->kind == FILTER_REFS_BRANCHES ||
2674 filter->kind == FILTER_REFS_REMOTES ||
2675 filter->kind == FILTER_REFS_TAGS)
2676 return filter->kind;
2677 return ref_kind_from_refname(refname);
2680 struct ref_filter_cbdata {
2681 struct ref_array *array;
2682 struct ref_filter *filter;
2683 struct contains_cache contains_cache;
2684 struct contains_cache no_contains_cache;
2688 * A call-back given to for_each_ref(). Filter refs and keep them for
2689 * later object processing.
2691 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2693 struct ref_filter_cbdata *ref_cbdata = cb_data;
2694 struct ref_filter *filter = ref_cbdata->filter;
2695 struct ref_array_item *ref;
2696 struct commit *commit = NULL;
2697 unsigned int kind;
2699 if (flag & REF_BAD_NAME) {
2700 warning(_("ignoring ref with broken name %s"), refname);
2701 return 0;
2704 if (flag & REF_ISBROKEN) {
2705 warning(_("ignoring broken ref %s"), refname);
2706 return 0;
2709 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2710 kind = filter_ref_kind(filter, refname);
2711 if (!(kind & filter->kind))
2712 return 0;
2714 if (!filter_pattern_match(filter, refname))
2715 return 0;
2717 if (filter_exclude_match(filter, refname))
2718 return 0;
2720 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2721 return 0;
2724 * A merge filter is applied on refs pointing to commits. Hence
2725 * obtain the commit using the 'oid' available and discard all
2726 * non-commits early. The actual filtering is done later.
2728 if (filter->reachable_from || filter->unreachable_from ||
2729 filter->with_commit || filter->no_commit || filter->verbose) {
2730 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2731 if (!commit)
2732 return 0;
2733 /* We perform the filtering for the '--contains' option... */
2734 if (filter->with_commit &&
2735 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2736 return 0;
2737 /* ...or for the `--no-contains' option */
2738 if (filter->no_commit &&
2739 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2740 return 0;
2744 * We do not open the object yet; sort may only need refname
2745 * to do its job and the resulting list may yet to be pruned
2746 * by maxcount logic.
2748 ref = ref_array_push(ref_cbdata->array, refname, oid);
2749 ref->commit = commit;
2750 ref->flag = flag;
2751 ref->kind = kind;
2753 return 0;
2756 /* Free memory allocated for a ref_array_item */
2757 static void free_array_item(struct ref_array_item *item)
2759 free((char *)item->symref);
2760 if (item->value) {
2761 int i;
2762 for (i = 0; i < used_atom_cnt; i++)
2763 free((char *)item->value[i].s);
2764 free(item->value);
2766 free(item->counts);
2767 free(item);
2770 /* Free all memory allocated for ref_array */
2771 void ref_array_clear(struct ref_array *array)
2773 int i;
2775 for (i = 0; i < array->nr; i++)
2776 free_array_item(array->items[i]);
2777 FREE_AND_NULL(array->items);
2778 array->nr = array->alloc = 0;
2780 for (i = 0; i < used_atom_cnt; i++) {
2781 struct used_atom *atom = &used_atom[i];
2782 if (atom->atom_type == ATOM_HEAD)
2783 free(atom->u.head);
2784 free((char *)atom->name);
2786 FREE_AND_NULL(used_atom);
2787 used_atom_cnt = 0;
2789 if (ref_to_worktree_map.worktrees) {
2790 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2791 struct ref_to_worktree_entry, ent);
2792 free_worktrees(ref_to_worktree_map.worktrees);
2793 ref_to_worktree_map.worktrees = NULL;
2796 FREE_AND_NULL(array->counts);
2799 #define EXCLUDE_REACHED 0
2800 #define INCLUDE_REACHED 1
2801 static void reach_filter(struct ref_array *array,
2802 struct commit_list **check_reachable,
2803 int include_reached)
2805 int i, old_nr;
2806 struct commit **to_clear;
2808 if (!*check_reachable)
2809 return;
2811 CALLOC_ARRAY(to_clear, array->nr);
2812 for (i = 0; i < array->nr; i++) {
2813 struct ref_array_item *item = array->items[i];
2814 to_clear[i] = item->commit;
2817 tips_reachable_from_bases(the_repository,
2818 *check_reachable,
2819 to_clear, array->nr,
2820 UNINTERESTING);
2822 old_nr = array->nr;
2823 array->nr = 0;
2825 for (i = 0; i < old_nr; i++) {
2826 struct ref_array_item *item = array->items[i];
2827 struct commit *commit = item->commit;
2829 int is_merged = !!(commit->object.flags & UNINTERESTING);
2831 if (is_merged == include_reached)
2832 array->items[array->nr++] = array->items[i];
2833 else
2834 free_array_item(item);
2837 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2839 while (*check_reachable) {
2840 struct commit *merge_commit = pop_commit(check_reachable);
2841 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2844 free(to_clear);
2847 void filter_ahead_behind(struct repository *r,
2848 struct ref_format *format,
2849 struct ref_array *array)
2851 struct commit **commits;
2852 size_t commits_nr = format->bases.nr + array->nr;
2854 if (!format->bases.nr || !array->nr)
2855 return;
2857 ALLOC_ARRAY(commits, commits_nr);
2858 for (size_t i = 0; i < format->bases.nr; i++)
2859 commits[i] = format->bases.items[i].util;
2861 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
2863 commits_nr = format->bases.nr;
2864 array->counts_nr = 0;
2865 for (size_t i = 0; i < array->nr; i++) {
2866 const char *name = array->items[i]->refname;
2867 commits[commits_nr] = lookup_commit_reference_by_name(name);
2869 if (!commits[commits_nr])
2870 continue;
2872 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
2873 for (size_t j = 0; j < format->bases.nr; j++) {
2874 struct ahead_behind_count *count;
2875 count = &array->counts[array->counts_nr++];
2876 count->tip_index = commits_nr;
2877 count->base_index = j;
2879 array->items[i]->counts[j] = count;
2881 commits_nr++;
2884 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
2885 free(commits);
2889 * API for filtering a set of refs. Based on the type of refs the user
2890 * has requested, we iterate through those refs and apply filters
2891 * as per the given ref_filter structure and finally store the
2892 * filtered refs in the ref_array structure.
2894 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2896 struct ref_filter_cbdata ref_cbdata;
2897 int save_commit_buffer_orig;
2898 int ret = 0;
2900 ref_cbdata.array = array;
2901 ref_cbdata.filter = filter;
2903 filter->kind = type & FILTER_REFS_KIND_MASK;
2905 save_commit_buffer_orig = save_commit_buffer;
2906 save_commit_buffer = 0;
2908 init_contains_cache(&ref_cbdata.contains_cache);
2909 init_contains_cache(&ref_cbdata.no_contains_cache);
2911 /* Simple per-ref filtering */
2912 if (!filter->kind)
2913 die("filter_refs: invalid type");
2914 else {
2916 * For common cases where we need only branches or remotes or tags,
2917 * we only iterate through those refs. If a mix of refs is needed,
2918 * we iterate over all refs and filter out required refs with the help
2919 * of filter_ref_kind().
2921 if (filter->kind == FILTER_REFS_BRANCHES)
2922 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2923 else if (filter->kind == FILTER_REFS_REMOTES)
2924 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2925 else if (filter->kind == FILTER_REFS_TAGS)
2926 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2927 else if (filter->kind & FILTER_REFS_ALL)
2928 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2929 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2930 head_ref(ref_filter_handler, &ref_cbdata);
2933 clear_contains_cache(&ref_cbdata.contains_cache);
2934 clear_contains_cache(&ref_cbdata.no_contains_cache);
2936 /* Filters that need revision walking */
2937 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
2938 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
2940 save_commit_buffer = save_commit_buffer_orig;
2941 return ret;
2944 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2946 if (!(a->kind ^ b->kind))
2947 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2948 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2949 return -1;
2950 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2951 return 1;
2952 BUG("should have died in the xor check above");
2953 return 0;
2956 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2958 const char *s1 = vs1, *s2 = vs2;
2959 const char *end = s1 + n;
2961 for (; s1 < end; s1++, s2++) {
2962 int diff = tolower(*s1) - tolower(*s2);
2963 if (diff)
2964 return diff;
2966 return 0;
2969 struct ref_sorting {
2970 struct ref_sorting *next;
2971 int atom; /* index into used_atom array (internal) */
2972 enum ref_sorting_order sort_flags;
2975 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2977 struct atom_value *va, *vb;
2978 int cmp;
2979 int cmp_detached_head = 0;
2980 cmp_type cmp_type = used_atom[s->atom].type;
2981 struct strbuf err = STRBUF_INIT;
2983 if (get_ref_atom_value(a, s->atom, &va, &err))
2984 die("%s", err.buf);
2985 if (get_ref_atom_value(b, s->atom, &vb, &err))
2986 die("%s", err.buf);
2987 strbuf_release(&err);
2988 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2989 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2990 cmp = compare_detached_head(a, b);
2991 cmp_detached_head = 1;
2992 } else if (s->sort_flags & REF_SORTING_VERSION) {
2993 cmp = versioncmp(va->s, vb->s);
2994 } else if (cmp_type == FIELD_STR) {
2995 if (va->s_size < 0 && vb->s_size < 0) {
2996 int (*cmp_fn)(const char *, const char *);
2997 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2998 ? strcasecmp : strcmp;
2999 cmp = cmp_fn(va->s, vb->s);
3000 } else {
3001 size_t a_size = va->s_size < 0 ?
3002 strlen(va->s) : va->s_size;
3003 size_t b_size = vb->s_size < 0 ?
3004 strlen(vb->s) : vb->s_size;
3005 int (*cmp_fn)(const void *, const void *, size_t);
3006 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3007 ? memcasecmp : memcmp;
3009 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3010 a_size : b_size);
3011 if (!cmp) {
3012 if (a_size > b_size)
3013 cmp = 1;
3014 else if (a_size < b_size)
3015 cmp = -1;
3018 } else {
3019 if (va->value < vb->value)
3020 cmp = -1;
3021 else if (va->value == vb->value)
3022 cmp = 0;
3023 else
3024 cmp = 1;
3027 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3028 ? -cmp : cmp;
3031 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3033 struct ref_array_item *a = *((struct ref_array_item **)a_);
3034 struct ref_array_item *b = *((struct ref_array_item **)b_);
3035 struct ref_sorting *s;
3037 for (s = ref_sorting; s; s = s->next) {
3038 int cmp = cmp_ref_sorting(s, a, b);
3039 if (cmp)
3040 return cmp;
3042 s = ref_sorting;
3043 return s && s->sort_flags & REF_SORTING_ICASE ?
3044 strcasecmp(a->refname, b->refname) :
3045 strcmp(a->refname, b->refname);
3048 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3049 unsigned int mask, int on)
3051 for (; sorting; sorting = sorting->next) {
3052 if (on)
3053 sorting->sort_flags |= mask;
3054 else
3055 sorting->sort_flags &= ~mask;
3059 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3061 QSORT_S(array->items, array->nr, compare_refs, sorting);
3064 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3066 struct strbuf *s = &state->stack->output;
3068 while (*cp && (!ep || cp < ep)) {
3069 if (*cp == '%') {
3070 if (cp[1] == '%')
3071 cp++;
3072 else {
3073 int ch = hex2chr(cp + 1);
3074 if (0 <= ch) {
3075 strbuf_addch(s, ch);
3076 cp += 3;
3077 continue;
3081 strbuf_addch(s, *cp);
3082 cp++;
3086 int format_ref_array_item(struct ref_array_item *info,
3087 struct ref_format *format,
3088 struct strbuf *final_buf,
3089 struct strbuf *error_buf)
3091 const char *cp, *sp, *ep;
3092 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3094 state.quote_style = format->quote_style;
3095 push_stack_element(&state.stack);
3097 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3098 struct atom_value *atomv;
3099 int pos;
3101 ep = strchr(sp, ')');
3102 if (cp < sp)
3103 append_literal(cp, sp, &state);
3104 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3105 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3106 atomv->handler(atomv, &state, error_buf)) {
3107 pop_stack_element(&state.stack);
3108 return -1;
3111 if (*cp) {
3112 sp = cp + strlen(cp);
3113 append_literal(cp, sp, &state);
3115 if (format->need_color_reset_at_eol) {
3116 struct atom_value resetv = ATOM_VALUE_INIT;
3117 resetv.s = GIT_COLOR_RESET;
3118 if (append_atom(&resetv, &state, error_buf)) {
3119 pop_stack_element(&state.stack);
3120 return -1;
3123 if (state.stack->prev) {
3124 pop_stack_element(&state.stack);
3125 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3127 strbuf_addbuf(final_buf, &state.stack->output);
3128 pop_stack_element(&state.stack);
3129 return 0;
3132 void pretty_print_ref(const char *name, const struct object_id *oid,
3133 struct ref_format *format)
3135 struct ref_array_item *ref_item;
3136 struct strbuf output = STRBUF_INIT;
3137 struct strbuf err = STRBUF_INIT;
3139 ref_item = new_ref_array_item(name, oid);
3140 ref_item->kind = ref_kind_from_refname(name);
3141 if (format_ref_array_item(ref_item, format, &output, &err))
3142 die("%s", err.buf);
3143 fwrite(output.buf, 1, output.len, stdout);
3144 putchar('\n');
3146 strbuf_release(&err);
3147 strbuf_release(&output);
3148 free_array_item(ref_item);
3151 static int parse_sorting_atom(const char *atom)
3154 * This parses an atom using a dummy ref_format, since we don't
3155 * actually care about the formatting details.
3157 struct ref_format dummy = REF_FORMAT_INIT;
3158 const char *end = atom + strlen(atom);
3159 struct strbuf err = STRBUF_INIT;
3160 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3161 if (res < 0)
3162 die("%s", err.buf);
3163 strbuf_release(&err);
3164 return res;
3167 /* If no sorting option is given, use refname to sort as default */
3168 static struct ref_sorting *ref_default_sorting(void)
3170 static const char cstr_name[] = "refname";
3172 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
3174 sorting->next = NULL;
3175 sorting->atom = parse_sorting_atom(cstr_name);
3176 return sorting;
3179 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3181 struct ref_sorting *s;
3183 CALLOC_ARRAY(s, 1);
3184 s->next = *sorting_tail;
3185 *sorting_tail = s;
3187 if (*arg == '-') {
3188 s->sort_flags |= REF_SORTING_REVERSE;
3189 arg++;
3191 if (skip_prefix(arg, "version:", &arg) ||
3192 skip_prefix(arg, "v:", &arg))
3193 s->sort_flags |= REF_SORTING_VERSION;
3194 s->atom = parse_sorting_atom(arg);
3197 struct ref_sorting *ref_sorting_options(struct string_list *options)
3199 struct string_list_item *item;
3200 struct ref_sorting *sorting = NULL, **tail = &sorting;
3202 if (!options->nr) {
3203 sorting = ref_default_sorting();
3204 } else {
3205 for_each_string_list_item(item, options)
3206 parse_ref_sorting(tail, item->string);
3210 * From here on, the ref_sorting list should be used to talk
3211 * about the sort order used for the output. The caller
3212 * should not touch the string form anymore.
3214 string_list_clear(options, 0);
3215 return sorting;
3218 void ref_sorting_release(struct ref_sorting *sorting)
3220 while (sorting) {
3221 struct ref_sorting *next = sorting->next;
3222 free(sorting);
3223 sorting = next;
3227 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3229 struct ref_filter *rf = opt->value;
3230 struct object_id oid;
3231 struct commit *merge_commit;
3233 BUG_ON_OPT_NEG(unset);
3235 if (repo_get_oid(the_repository, arg, &oid))
3236 die(_("malformed object name %s"), arg);
3238 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3240 if (!merge_commit)
3241 return error(_("option `%s' must point to a commit"), opt->long_name);
3243 if (starts_with(opt->long_name, "no"))
3244 commit_list_insert(merge_commit, &rf->unreachable_from);
3245 else
3246 commit_list_insert(merge_commit, &rf->reachable_from);
3248 return 0;
3251 void ref_filter_init(struct ref_filter *filter)
3253 struct ref_filter blank = REF_FILTER_INIT;
3254 memcpy(filter, &blank, sizeof(blank));
3257 void ref_filter_clear(struct ref_filter *filter)
3259 strvec_clear(&filter->exclude);
3260 oid_array_clear(&filter->points_at);
3261 free_commit_list(filter->with_commit);
3262 free_commit_list(filter->no_commit);
3263 free_commit_list(filter->reachable_from);
3264 free_commit_list(filter->unreachable_from);
3265 ref_filter_init(filter);