builtin/repack.c: extract common cruft pack loop
[git/gitster.git] / ref-filter.c
blob1bfaf20fbff664b09d1c902be499040c8396e363
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->u.contents.option = C_LENGTH;
587 else if (!strcmp(arg, "signature"))
588 atom->u.contents.option = C_SIG;
589 else if (!strcmp(arg, "subject"))
590 atom->u.contents.option = C_SUB;
591 else if (!strcmp(arg, "trailers")) {
592 if (trailers_atom_parser(format, atom, NULL, err))
593 return -1;
594 } else if (skip_prefix(arg, "trailers:", &arg)) {
595 if (trailers_atom_parser(format, atom, arg, err))
596 return -1;
597 } else if (skip_prefix(arg, "lines=", &arg)) {
598 atom->u.contents.option = C_LINES;
599 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
600 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
601 } else
602 return err_bad_arg(err, "contents", arg);
603 return 0;
606 static int describe_atom_option_parser(struct strvec *args, const char **arg,
607 struct strbuf *err)
609 const char *argval;
610 size_t arglen = 0;
611 int optval = 0;
613 if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {
614 if (!optval)
615 strvec_push(args, "--no-tags");
616 else
617 strvec_push(args, "--tags");
618 return 1;
621 if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {
622 char *endptr;
624 if (!arglen)
625 return strbuf_addf_ret(err, -1,
626 _("argument expected for %s"),
627 "describe:abbrev");
628 if (strtol(argval, &endptr, 10) < 0)
629 return strbuf_addf_ret(err, -1,
630 _("positive value expected %s=%s"),
631 "describe:abbrev", argval);
632 if (endptr - argval != arglen)
633 return strbuf_addf_ret(err, -1,
634 _("cannot fully parse %s=%s"),
635 "describe:abbrev", argval);
637 strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);
638 return 1;
641 if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {
642 if (!arglen)
643 return strbuf_addf_ret(err, -1,
644 _("value expected %s="),
645 "describe:match");
647 strvec_pushf(args, "--match=%.*s", (int)arglen, argval);
648 return 1;
651 if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {
652 if (!arglen)
653 return strbuf_addf_ret(err, -1,
654 _("value expected %s="),
655 "describe:exclude");
657 strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);
658 return 1;
661 return 0;
664 static int describe_atom_parser(struct ref_format *format UNUSED,
665 struct used_atom *atom,
666 const char *arg, struct strbuf *err)
668 struct strvec args = STRVEC_INIT;
670 for (;;) {
671 int found = 0;
672 const char *bad_arg = arg;
674 if (!arg || !*arg)
675 break;
677 found = describe_atom_option_parser(&args, &arg, err);
678 if (found < 0)
679 return found;
680 if (!found)
681 return err_bad_arg(err, "describe", bad_arg);
683 atom->u.describe_args = strvec_detach(&args);
684 return 0;
687 static int raw_atom_parser(struct ref_format *format UNUSED,
688 struct used_atom *atom,
689 const char *arg, struct strbuf *err)
691 if (!arg)
692 atom->u.raw_data.option = RAW_BARE;
693 else if (!strcmp(arg, "size"))
694 atom->u.raw_data.option = RAW_LENGTH;
695 else
696 return err_bad_arg(err, "raw", arg);
697 return 0;
700 static int oid_atom_parser(struct ref_format *format UNUSED,
701 struct used_atom *atom,
702 const char *arg, struct strbuf *err)
704 if (!arg)
705 atom->u.oid.option = O_FULL;
706 else if (!strcmp(arg, "short"))
707 atom->u.oid.option = O_SHORT;
708 else if (skip_prefix(arg, "short=", &arg)) {
709 atom->u.oid.option = O_LENGTH;
710 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
711 atom->u.oid.length == 0)
712 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
713 if (atom->u.oid.length < MINIMUM_ABBREV)
714 atom->u.oid.length = MINIMUM_ABBREV;
715 } else
716 return err_bad_arg(err, atom->name, arg);
717 return 0;
720 static int person_email_atom_parser(struct ref_format *format UNUSED,
721 struct used_atom *atom,
722 const char *arg, struct strbuf *err)
724 if (!arg)
725 atom->u.email_option.option = EO_RAW;
726 else if (!strcmp(arg, "trim"))
727 atom->u.email_option.option = EO_TRIM;
728 else if (!strcmp(arg, "localpart"))
729 atom->u.email_option.option = EO_LOCALPART;
730 else
731 return err_bad_arg(err, atom->name, arg);
732 return 0;
735 static int refname_atom_parser(struct ref_format *format UNUSED,
736 struct used_atom *atom,
737 const char *arg, struct strbuf *err)
739 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
742 static align_type parse_align_position(const char *s)
744 if (!strcmp(s, "right"))
745 return ALIGN_RIGHT;
746 else if (!strcmp(s, "middle"))
747 return ALIGN_MIDDLE;
748 else if (!strcmp(s, "left"))
749 return ALIGN_LEFT;
750 return -1;
753 static int align_atom_parser(struct ref_format *format UNUSED,
754 struct used_atom *atom,
755 const char *arg, struct strbuf *err)
757 struct align *align = &atom->u.align;
758 struct string_list params = STRING_LIST_INIT_DUP;
759 int i;
760 unsigned int width = ~0U;
762 if (!arg)
763 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
765 align->position = ALIGN_LEFT;
767 string_list_split(&params, arg, ',', -1);
768 for (i = 0; i < params.nr; i++) {
769 const char *s = params.items[i].string;
770 int position;
772 if (skip_prefix(s, "position=", &s)) {
773 position = parse_align_position(s);
774 if (position < 0) {
775 strbuf_addf(err, _("unrecognized position:%s"), s);
776 string_list_clear(&params, 0);
777 return -1;
779 align->position = position;
780 } else if (skip_prefix(s, "width=", &s)) {
781 if (strtoul_ui(s, 10, &width)) {
782 strbuf_addf(err, _("unrecognized width:%s"), s);
783 string_list_clear(&params, 0);
784 return -1;
786 } else if (!strtoul_ui(s, 10, &width))
788 else if ((position = parse_align_position(s)) >= 0)
789 align->position = position;
790 else {
791 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
792 string_list_clear(&params, 0);
793 return -1;
797 if (width == ~0U) {
798 string_list_clear(&params, 0);
799 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
801 align->width = width;
802 string_list_clear(&params, 0);
803 return 0;
806 static int if_atom_parser(struct ref_format *format UNUSED,
807 struct used_atom *atom,
808 const char *arg, struct strbuf *err)
810 if (!arg) {
811 atom->u.if_then_else.cmp_status = COMPARE_NONE;
812 return 0;
813 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
814 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
815 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
816 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
817 } else
818 return err_bad_arg(err, "if", arg);
819 return 0;
822 static int rest_atom_parser(struct ref_format *format,
823 struct used_atom *atom UNUSED,
824 const char *arg, struct strbuf *err)
826 if (arg)
827 return err_no_arg(err, "rest");
828 return 0;
831 static int ahead_behind_atom_parser(struct ref_format *format, struct used_atom *atom,
832 const char *arg, struct strbuf *err)
834 struct string_list_item *item;
836 if (!arg)
837 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
839 item = string_list_append(&format->bases, arg);
840 item->util = lookup_commit_reference_by_name(arg);
841 if (!item->util)
842 die("failed to find '%s'", arg);
844 return 0;
847 static int head_atom_parser(struct ref_format *format UNUSED,
848 struct used_atom *atom,
849 const char *arg, struct strbuf *err)
851 if (arg)
852 return err_no_arg(err, "HEAD");
853 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
854 return 0;
857 static struct {
858 const char *name;
859 info_source source;
860 cmp_type cmp_type;
861 int (*parser)(struct ref_format *format, struct used_atom *atom,
862 const char *arg, struct strbuf *err);
863 } valid_atom[] = {
864 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
865 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
866 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
867 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
868 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
869 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
870 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
871 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
872 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
873 [ATOM_TYPE] = { "type", SOURCE_OBJ },
874 [ATOM_TAG] = { "tag", SOURCE_OBJ },
875 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
876 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
877 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
878 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
879 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
880 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
881 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
882 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
883 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
884 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
885 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
886 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
887 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
888 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
889 [ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },
890 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
891 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
892 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
893 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
894 [ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },
895 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
896 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
897 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
898 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
899 [ATOM_FLAG] = { "flag", SOURCE_NONE },
900 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
901 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
902 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
903 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
904 [ATOM_END] = { "end", SOURCE_NONE },
905 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
906 [ATOM_THEN] = { "then", SOURCE_NONE },
907 [ATOM_ELSE] = { "else", SOURCE_NONE },
908 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
909 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
911 * Please update $__git_ref_fieldlist in git-completion.bash
912 * when you add new atoms
916 #define REF_FORMATTING_STATE_INIT { 0 }
918 struct ref_formatting_stack {
919 struct ref_formatting_stack *prev;
920 struct strbuf output;
921 void (*at_end)(struct ref_formatting_stack **stack);
922 void *at_end_data;
925 struct ref_formatting_state {
926 int quote_style;
927 struct ref_formatting_stack *stack;
930 struct atom_value {
931 const char *s;
932 ssize_t s_size;
933 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
934 struct strbuf *err);
935 uintmax_t value; /* used for sorting when not FIELD_STR */
936 struct used_atom *atom;
939 #define ATOM_SIZE_UNSPECIFIED (-1)
941 #define ATOM_VALUE_INIT { \
942 .s_size = ATOM_SIZE_UNSPECIFIED \
946 * Used to parse format string and sort specifiers
948 static int parse_ref_filter_atom(struct ref_format *format,
949 const char *atom, const char *ep,
950 struct strbuf *err)
952 const char *sp;
953 const char *arg;
954 int i, at, atom_len;
956 sp = atom;
957 if (*sp == '*' && sp < ep)
958 sp++; /* deref */
959 if (ep <= sp)
960 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
961 (int)(ep-atom), atom);
964 * If the atom name has a colon, strip it and everything after
965 * it off - it specifies the format for this entry, and
966 * shouldn't be used for checking against the valid_atom
967 * table.
969 arg = memchr(sp, ':', ep - sp);
970 atom_len = (arg ? arg : ep) - sp;
972 /* Do we have the atom already used elsewhere? */
973 for (i = 0; i < used_atom_cnt; i++) {
974 int len = strlen(used_atom[i].name);
975 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
976 return i;
979 /* Is the atom a valid one? */
980 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
981 int len = strlen(valid_atom[i].name);
982 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
983 break;
986 if (ARRAY_SIZE(valid_atom) <= i)
987 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
988 (int)(ep-atom), atom);
989 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
990 return strbuf_addf_ret(err, -1,
991 _("not a git repository, but the field '%.*s' requires access to object data"),
992 (int)(ep-atom), atom);
994 /* Add it in, including the deref prefix */
995 at = used_atom_cnt;
996 used_atom_cnt++;
997 REALLOC_ARRAY(used_atom, used_atom_cnt);
998 used_atom[at].atom_type = i;
999 used_atom[at].name = xmemdupz(atom, ep - atom);
1000 used_atom[at].type = valid_atom[i].cmp_type;
1001 used_atom[at].source = valid_atom[i].source;
1002 if (used_atom[at].source == SOURCE_OBJ) {
1003 if (*atom == '*')
1004 oi_deref.info.contentp = &oi_deref.content;
1005 else
1006 oi.info.contentp = &oi.content;
1008 if (arg) {
1009 arg = used_atom[at].name + (arg - atom) + 1;
1010 if (!*arg) {
1012 * Treat empty sub-arguments list as NULL (i.e.,
1013 * "%(atom:)" is equivalent to "%(atom)").
1015 arg = NULL;
1018 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
1019 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
1020 return -1;
1021 if (*atom == '*')
1022 need_tagged = 1;
1023 if (i == ATOM_SYMREF)
1024 need_symref = 1;
1025 return at;
1028 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
1030 switch (quote_style) {
1031 case QUOTE_NONE:
1032 if (len < 0)
1033 strbuf_addstr(s, str);
1034 else
1035 strbuf_add(s, str, len);
1036 break;
1037 case QUOTE_SHELL:
1038 sq_quote_buf(s, str);
1039 break;
1040 case QUOTE_PERL:
1041 if (len < 0)
1042 perl_quote_buf(s, str);
1043 else
1044 perl_quote_buf_with_len(s, str, len);
1045 break;
1046 case QUOTE_PYTHON:
1047 python_quote_buf(s, str);
1048 break;
1049 case QUOTE_TCL:
1050 tcl_quote_buf(s, str);
1051 break;
1055 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
1056 struct strbuf *err UNUSED)
1059 * Quote formatting is only done when the stack has a single
1060 * element. Otherwise quote formatting is done on the
1061 * element's entire output strbuf when the %(end) atom is
1062 * encountered.
1064 if (!state->stack->prev)
1065 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
1066 else if (v->s_size < 0)
1067 strbuf_addstr(&state->stack->output, v->s);
1068 else
1069 strbuf_add(&state->stack->output, v->s, v->s_size);
1070 return 0;
1073 static void push_stack_element(struct ref_formatting_stack **stack)
1075 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
1077 strbuf_init(&s->output, 0);
1078 s->prev = *stack;
1079 *stack = s;
1082 static void pop_stack_element(struct ref_formatting_stack **stack)
1084 struct ref_formatting_stack *current = *stack;
1085 struct ref_formatting_stack *prev = current->prev;
1087 if (prev)
1088 strbuf_addbuf(&prev->output, &current->output);
1089 strbuf_release(&current->output);
1090 free(current);
1091 *stack = prev;
1094 static void end_align_handler(struct ref_formatting_stack **stack)
1096 struct ref_formatting_stack *cur = *stack;
1097 struct align *align = (struct align *)cur->at_end_data;
1098 struct strbuf s = STRBUF_INIT;
1100 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
1101 strbuf_swap(&cur->output, &s);
1102 strbuf_release(&s);
1105 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1106 struct strbuf *err UNUSED)
1108 struct ref_formatting_stack *new_stack;
1110 push_stack_element(&state->stack);
1111 new_stack = state->stack;
1112 new_stack->at_end = end_align_handler;
1113 new_stack->at_end_data = &atomv->atom->u.align;
1114 return 0;
1117 static void if_then_else_handler(struct ref_formatting_stack **stack)
1119 struct ref_formatting_stack *cur = *stack;
1120 struct ref_formatting_stack *prev = cur->prev;
1121 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
1123 if (!if_then_else->then_atom_seen)
1124 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
1126 if (if_then_else->else_atom_seen) {
1128 * There is an %(else) atom: we need to drop one state from the
1129 * stack, either the %(else) branch if the condition is satisfied, or
1130 * the %(then) branch if it isn't.
1132 if (if_then_else->condition_satisfied) {
1133 strbuf_reset(&cur->output);
1134 pop_stack_element(&cur);
1135 } else {
1136 strbuf_swap(&cur->output, &prev->output);
1137 strbuf_reset(&cur->output);
1138 pop_stack_element(&cur);
1140 } else if (!if_then_else->condition_satisfied) {
1142 * No %(else) atom: just drop the %(then) branch if the
1143 * condition is not satisfied.
1145 strbuf_reset(&cur->output);
1148 *stack = cur;
1149 free(if_then_else);
1152 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1153 struct strbuf *err UNUSED)
1155 struct ref_formatting_stack *new_stack;
1156 struct if_then_else *if_then_else = xcalloc(1,
1157 sizeof(struct if_then_else));
1159 if_then_else->str = atomv->atom->u.if_then_else.str;
1160 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
1162 push_stack_element(&state->stack);
1163 new_stack = state->stack;
1164 new_stack->at_end = if_then_else_handler;
1165 new_stack->at_end_data = if_then_else;
1166 return 0;
1169 static int is_empty(struct strbuf *buf)
1171 const char *cur = buf->buf;
1172 const char *end = buf->buf + buf->len;
1174 while (cur != end && (isspace(*cur)))
1175 cur++;
1177 return cur == end;
1180 static int then_atom_handler(struct atom_value *atomv UNUSED,
1181 struct ref_formatting_state *state,
1182 struct strbuf *err)
1184 struct ref_formatting_stack *cur = state->stack;
1185 struct if_then_else *if_then_else = NULL;
1186 size_t str_len = 0;
1188 if (cur->at_end == if_then_else_handler)
1189 if_then_else = (struct if_then_else *)cur->at_end_data;
1190 if (!if_then_else)
1191 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
1192 if (if_then_else->then_atom_seen)
1193 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
1194 if (if_then_else->else_atom_seen)
1195 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
1196 if_then_else->then_atom_seen = 1;
1197 if (if_then_else->str)
1198 str_len = strlen(if_then_else->str);
1200 * If the 'equals' or 'notequals' attribute is used then
1201 * perform the required comparison. If not, only non-empty
1202 * strings satisfy the 'if' condition.
1204 if (if_then_else->cmp_status == COMPARE_EQUAL) {
1205 if (str_len == cur->output.len &&
1206 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1207 if_then_else->condition_satisfied = 1;
1208 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
1209 if (str_len != cur->output.len ||
1210 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1211 if_then_else->condition_satisfied = 1;
1212 } else if (cur->output.len && !is_empty(&cur->output))
1213 if_then_else->condition_satisfied = 1;
1214 strbuf_reset(&cur->output);
1215 return 0;
1218 static int else_atom_handler(struct atom_value *atomv UNUSED,
1219 struct ref_formatting_state *state,
1220 struct strbuf *err)
1222 struct ref_formatting_stack *prev = state->stack;
1223 struct if_then_else *if_then_else = NULL;
1225 if (prev->at_end == if_then_else_handler)
1226 if_then_else = (struct if_then_else *)prev->at_end_data;
1227 if (!if_then_else)
1228 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1229 if (!if_then_else->then_atom_seen)
1230 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1231 if (if_then_else->else_atom_seen)
1232 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1233 if_then_else->else_atom_seen = 1;
1234 push_stack_element(&state->stack);
1235 state->stack->at_end_data = prev->at_end_data;
1236 state->stack->at_end = prev->at_end;
1237 return 0;
1240 static int end_atom_handler(struct atom_value *atomv UNUSED,
1241 struct ref_formatting_state *state,
1242 struct strbuf *err)
1244 struct ref_formatting_stack *current = state->stack;
1245 struct strbuf s = STRBUF_INIT;
1247 if (!current->at_end)
1248 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1249 current->at_end(&state->stack);
1251 /* Stack may have been popped within at_end(), hence reset the current pointer */
1252 current = state->stack;
1255 * Perform quote formatting when the stack element is that of
1256 * a supporting atom. If nested then perform quote formatting
1257 * only on the topmost supporting atom.
1259 if (!current->prev->prev) {
1260 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1261 strbuf_swap(&current->output, &s);
1263 strbuf_release(&s);
1264 pop_stack_element(&state->stack);
1265 return 0;
1269 * In a format string, find the next occurrence of %(atom).
1271 static const char *find_next(const char *cp)
1273 while (*cp) {
1274 if (*cp == '%') {
1276 * %( is the start of an atom;
1277 * %% is a quoted per-cent.
1279 if (cp[1] == '(')
1280 return cp;
1281 else if (cp[1] == '%')
1282 cp++; /* skip over two % */
1283 /* otherwise this is a singleton, literal % */
1285 cp++;
1287 return NULL;
1290 static int reject_atom(enum atom_type atom_type)
1292 return atom_type == ATOM_REST;
1296 * Make sure the format string is well formed, and parse out
1297 * the used atoms.
1299 int verify_ref_format(struct ref_format *format)
1301 const char *cp, *sp;
1303 format->need_color_reset_at_eol = 0;
1304 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1305 struct strbuf err = STRBUF_INIT;
1306 const char *color, *ep = strchr(sp, ')');
1307 int at;
1309 if (!ep)
1310 return error(_("malformed format string %s"), sp);
1311 /* sp points at "%(" and ep points at the closing ")" */
1312 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1313 if (at < 0)
1314 die("%s", err.buf);
1315 if (reject_atom(used_atom[at].atom_type))
1316 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1318 if ((format->quote_style == QUOTE_PYTHON ||
1319 format->quote_style == QUOTE_SHELL ||
1320 format->quote_style == QUOTE_TCL) &&
1321 used_atom[at].atom_type == ATOM_RAW &&
1322 used_atom[at].u.raw_data.option == RAW_BARE)
1323 die(_("--format=%.*s cannot be used with "
1324 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1325 cp = ep + 1;
1327 if (skip_prefix(used_atom[at].name, "color:", &color))
1328 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1329 strbuf_release(&err);
1331 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1332 format->need_color_reset_at_eol = 0;
1333 return 0;
1336 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1337 struct used_atom *atom)
1339 switch (atom->u.oid.option) {
1340 case O_FULL:
1341 return oid_to_hex(oid);
1342 case O_LENGTH:
1343 return repo_find_unique_abbrev(the_repository, oid,
1344 atom->u.oid.length);
1345 case O_SHORT:
1346 return repo_find_unique_abbrev(the_repository, oid,
1347 DEFAULT_ABBREV);
1348 default:
1349 BUG("unknown %%(%s) option", field);
1353 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1354 struct atom_value *v, struct used_atom *atom)
1356 if (starts_with(name, field)) {
1357 v->s = xstrdup(do_grab_oid(field, oid, atom));
1358 return 1;
1360 return 0;
1363 /* See grab_values */
1364 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1366 int i;
1368 for (i = 0; i < used_atom_cnt; i++) {
1369 const char *name = used_atom[i].name;
1370 enum atom_type atom_type = used_atom[i].atom_type;
1371 struct atom_value *v = &val[i];
1372 if (!!deref != (*name == '*'))
1373 continue;
1374 if (deref)
1375 name++;
1376 if (atom_type == ATOM_OBJECTTYPE)
1377 v->s = xstrdup(type_name(oi->type));
1378 else if (atom_type == ATOM_OBJECTSIZE) {
1379 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1380 v->value = oi->disk_size;
1381 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1382 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1383 v->value = oi->size;
1384 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1386 } else if (atom_type == ATOM_DELTABASE)
1387 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1388 else if (atom_type == ATOM_OBJECTNAME && deref)
1389 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1393 /* See grab_values */
1394 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1396 int i;
1397 struct tag *tag = (struct tag *) obj;
1399 for (i = 0; i < used_atom_cnt; i++) {
1400 const char *name = used_atom[i].name;
1401 enum atom_type atom_type = used_atom[i].atom_type;
1402 struct atom_value *v = &val[i];
1403 if (!!deref != (*name == '*'))
1404 continue;
1405 if (deref)
1406 name++;
1407 if (atom_type == ATOM_TAG)
1408 v->s = xstrdup(tag->tag);
1409 else if (atom_type == ATOM_TYPE && tag->tagged)
1410 v->s = xstrdup(type_name(tag->tagged->type));
1411 else if (atom_type == ATOM_OBJECT && tag->tagged)
1412 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1416 /* See grab_values */
1417 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1419 int i;
1420 struct commit *commit = (struct commit *) obj;
1422 for (i = 0; i < used_atom_cnt; i++) {
1423 const char *name = used_atom[i].name;
1424 enum atom_type atom_type = used_atom[i].atom_type;
1425 struct atom_value *v = &val[i];
1426 if (!!deref != (*name == '*'))
1427 continue;
1428 if (deref)
1429 name++;
1430 if (atom_type == ATOM_TREE &&
1431 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1432 continue;
1433 if (atom_type == ATOM_NUMPARENT) {
1434 v->value = commit_list_count(commit->parents);
1435 v->s = xstrfmt("%lu", (unsigned long)v->value);
1437 else if (atom_type == ATOM_PARENT) {
1438 struct commit_list *parents;
1439 struct strbuf s = STRBUF_INIT;
1440 for (parents = commit->parents; parents; parents = parents->next) {
1441 struct object_id *oid = &parents->item->object.oid;
1442 if (parents != commit->parents)
1443 strbuf_addch(&s, ' ');
1444 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1446 v->s = strbuf_detach(&s, NULL);
1451 static const char *find_wholine(const char *who, int wholen, const char *buf)
1453 const char *eol;
1454 while (*buf) {
1455 if (!strncmp(buf, who, wholen) &&
1456 buf[wholen] == ' ')
1457 return buf + wholen + 1;
1458 eol = strchr(buf, '\n');
1459 if (!eol)
1460 return "";
1461 eol++;
1462 if (*eol == '\n')
1463 return ""; /* end of header */
1464 buf = eol;
1466 return "";
1469 static const char *copy_line(const char *buf)
1471 const char *eol = strchrnul(buf, '\n');
1472 return xmemdupz(buf, eol - buf);
1475 static const char *copy_name(const char *buf)
1477 const char *cp;
1478 for (cp = buf; *cp && *cp != '\n'; cp++) {
1479 if (starts_with(cp, " <"))
1480 return xmemdupz(buf, cp - buf);
1482 return xstrdup("");
1485 static const char *copy_email(const char *buf, struct used_atom *atom)
1487 const char *email = strchr(buf, '<');
1488 const char *eoemail;
1489 if (!email)
1490 return xstrdup("");
1491 switch (atom->u.email_option.option) {
1492 case EO_RAW:
1493 eoemail = strchr(email, '>');
1494 if (eoemail)
1495 eoemail++;
1496 break;
1497 case EO_TRIM:
1498 email++;
1499 eoemail = strchr(email, '>');
1500 break;
1501 case EO_LOCALPART:
1502 email++;
1503 eoemail = strchr(email, '@');
1504 if (!eoemail)
1505 eoemail = strchr(email, '>');
1506 break;
1507 default:
1508 BUG("unknown email option");
1511 if (!eoemail)
1512 return xstrdup("");
1513 return xmemdupz(email, eoemail - email);
1516 static char *copy_subject(const char *buf, unsigned long len)
1518 struct strbuf sb = STRBUF_INIT;
1519 int i;
1521 for (i = 0; i < len; i++) {
1522 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1523 continue; /* ignore CR in CRLF */
1525 if (buf[i] == '\n')
1526 strbuf_addch(&sb, ' ');
1527 else
1528 strbuf_addch(&sb, buf[i]);
1530 return strbuf_detach(&sb, NULL);
1533 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1535 const char *eoemail = strstr(buf, "> ");
1536 char *zone;
1537 timestamp_t timestamp;
1538 long tz;
1539 struct date_mode date_mode = DATE_MODE_INIT;
1540 const char *formatp;
1543 * We got here because atomname ends in "date" or "date<something>";
1544 * it's not possible that <something> is not ":<format>" because
1545 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1546 * ":" means no format is specified, and use the default.
1548 formatp = strchr(atomname, ':');
1549 if (formatp) {
1550 formatp++;
1551 parse_date_format(formatp, &date_mode);
1554 if (!eoemail)
1555 goto bad;
1556 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1557 if (timestamp == TIME_MAX)
1558 goto bad;
1559 tz = strtol(zone, NULL, 10);
1560 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1561 goto bad;
1562 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1563 v->value = timestamp;
1564 date_mode_release(&date_mode);
1565 return;
1566 bad:
1567 v->s = xstrdup("");
1568 v->value = 0;
1571 /* See grab_values */
1572 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1574 int i;
1575 int wholen = strlen(who);
1576 const char *wholine = NULL;
1578 for (i = 0; i < used_atom_cnt; i++) {
1579 const char *name = used_atom[i].name;
1580 struct atom_value *v = &val[i];
1581 if (!!deref != (*name == '*'))
1582 continue;
1583 if (deref)
1584 name++;
1585 if (strncmp(who, name, wholen))
1586 continue;
1587 if (name[wholen] != 0 &&
1588 strcmp(name + wholen, "name") &&
1589 !starts_with(name + wholen, "email") &&
1590 !starts_with(name + wholen, "date"))
1591 continue;
1592 if (!wholine)
1593 wholine = find_wholine(who, wholen, buf);
1594 if (!wholine)
1595 return; /* no point looking for it */
1596 if (name[wholen] == 0)
1597 v->s = copy_line(wholine);
1598 else if (!strcmp(name + wholen, "name"))
1599 v->s = copy_name(wholine);
1600 else if (starts_with(name + wholen, "email"))
1601 v->s = copy_email(wholine, &used_atom[i]);
1602 else if (starts_with(name + wholen, "date"))
1603 grab_date(wholine, v, name);
1607 * For a tag or a commit object, if "creator" or "creatordate" is
1608 * requested, do something special.
1610 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1611 return; /* "author" for commit object is not wanted */
1612 if (!wholine)
1613 wholine = find_wholine(who, wholen, buf);
1614 if (!wholine)
1615 return;
1616 for (i = 0; i < used_atom_cnt; i++) {
1617 const char *name = used_atom[i].name;
1618 enum atom_type atom_type = used_atom[i].atom_type;
1619 struct atom_value *v = &val[i];
1620 if (!!deref != (*name == '*'))
1621 continue;
1622 if (deref)
1623 name++;
1625 if (atom_type == ATOM_CREATORDATE)
1626 grab_date(wholine, v, name);
1627 else if (atom_type == ATOM_CREATOR)
1628 v->s = copy_line(wholine);
1632 static void grab_signature(struct atom_value *val, int deref, struct object *obj)
1634 int i;
1635 struct commit *commit = (struct commit *) obj;
1636 struct signature_check sigc = { 0 };
1637 int signature_checked = 0;
1639 for (i = 0; i < used_atom_cnt; i++) {
1640 struct used_atom *atom = &used_atom[i];
1641 const char *name = atom->name;
1642 struct atom_value *v = &val[i];
1643 int opt;
1645 if (!!deref != (*name == '*'))
1646 continue;
1647 if (deref)
1648 name++;
1650 if (!skip_prefix(name, "signature", &name) ||
1651 (*name && *name != ':'))
1652 continue;
1653 if (!*name)
1654 name = NULL;
1655 else
1656 name++;
1658 opt = parse_signature_option(name);
1659 if (opt < 0)
1660 continue;
1662 if (!signature_checked) {
1663 check_commit_signature(commit, &sigc);
1664 signature_checked = 1;
1667 switch (opt) {
1668 case S_BARE:
1669 v->s = xstrdup(sigc.output ? sigc.output: "");
1670 break;
1671 case S_SIGNER:
1672 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1673 break;
1674 case S_GRADE:
1675 switch (sigc.result) {
1676 case 'G':
1677 switch (sigc.trust_level) {
1678 case TRUST_UNDEFINED:
1679 case TRUST_NEVER:
1680 v->s = xstrfmt("%c", (char)'U');
1681 break;
1682 default:
1683 v->s = xstrfmt("%c", (char)'G');
1684 break;
1686 break;
1687 case 'B':
1688 case 'E':
1689 case 'N':
1690 case 'X':
1691 case 'Y':
1692 case 'R':
1693 v->s = xstrfmt("%c", (char)sigc.result);
1694 break;
1696 break;
1697 case S_KEY:
1698 v->s = xstrdup(sigc.key ? sigc.key : "");
1699 break;
1700 case S_FINGERPRINT:
1701 v->s = xstrdup(sigc.fingerprint ?
1702 sigc.fingerprint : "");
1703 break;
1704 case S_PRI_KEY_FP:
1705 v->s = xstrdup(sigc.primary_key_fingerprint ?
1706 sigc.primary_key_fingerprint : "");
1707 break;
1708 case S_TRUST_LEVEL:
1709 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1710 break;
1714 if (signature_checked)
1715 signature_check_clear(&sigc);
1718 static void find_subpos(const char *buf,
1719 const char **sub, size_t *sublen,
1720 const char **body, size_t *bodylen,
1721 size_t *nonsiglen,
1722 const char **sig, size_t *siglen)
1724 struct strbuf payload = STRBUF_INIT;
1725 struct strbuf signature = STRBUF_INIT;
1726 const char *eol;
1727 const char *end = buf + strlen(buf);
1728 const char *sigstart;
1730 /* parse signature first; we might not even have a subject line */
1731 parse_signature(buf, end - buf, &payload, &signature);
1732 strbuf_release(&payload);
1734 /* skip past header until we hit empty line */
1735 while (*buf && *buf != '\n') {
1736 eol = strchrnul(buf, '\n');
1737 if (*eol)
1738 eol++;
1739 buf = eol;
1741 /* skip any empty lines */
1742 while (*buf == '\n')
1743 buf++;
1744 *sig = strbuf_detach(&signature, siglen);
1745 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1747 /* subject is first non-empty line */
1748 *sub = buf;
1749 /* subject goes to first empty line before signature begins */
1750 if ((eol = strstr(*sub, "\n\n")) ||
1751 (eol = strstr(*sub, "\r\n\r\n"))) {
1752 eol = eol < sigstart ? eol : sigstart;
1753 } else {
1754 /* treat whole message as subject */
1755 eol = sigstart;
1757 buf = eol;
1758 *sublen = buf - *sub;
1759 /* drop trailing newline, if present */
1760 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1761 (*sub)[*sublen - 1] == '\r'))
1762 *sublen -= 1;
1764 /* skip any empty lines */
1765 while (*buf == '\n' || *buf == '\r')
1766 buf++;
1767 *body = buf;
1768 *bodylen = strlen(buf);
1769 *nonsiglen = sigstart - buf;
1773 * If 'lines' is greater than 0, append that many lines from the given
1774 * 'buf' of length 'size' to the given strbuf.
1776 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1778 int i;
1779 const char *sp, *eol;
1780 size_t len;
1782 sp = buf;
1784 for (i = 0; i < lines && sp < buf + size; i++) {
1785 if (i)
1786 strbuf_addstr(out, "\n ");
1787 eol = memchr(sp, '\n', size - (sp - buf));
1788 len = eol ? eol - sp : size - (sp - buf);
1789 strbuf_add(out, sp, len);
1790 if (!eol)
1791 break;
1792 sp = eol + 1;
1796 static void grab_describe_values(struct atom_value *val, int deref,
1797 struct object *obj)
1799 struct commit *commit = (struct commit *)obj;
1800 int i;
1802 for (i = 0; i < used_atom_cnt; i++) {
1803 struct used_atom *atom = &used_atom[i];
1804 enum atom_type type = atom->atom_type;
1805 const char *name = atom->name;
1806 struct atom_value *v = &val[i];
1808 struct child_process cmd = CHILD_PROCESS_INIT;
1809 struct strbuf out = STRBUF_INIT;
1810 struct strbuf err = STRBUF_INIT;
1812 if (type != ATOM_DESCRIBE)
1813 continue;
1815 if (!!deref != (*name == '*'))
1816 continue;
1818 cmd.git_cmd = 1;
1819 strvec_push(&cmd.args, "describe");
1820 strvec_pushv(&cmd.args, atom->u.describe_args);
1821 strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));
1822 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
1823 error(_("failed to run 'describe'"));
1824 v->s = xstrdup("");
1825 continue;
1827 strbuf_rtrim(&out);
1828 v->s = strbuf_detach(&out, NULL);
1830 strbuf_release(&err);
1834 /* See grab_values */
1835 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1837 int i;
1838 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1839 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1840 void *buf = data->content;
1842 for (i = 0; i < used_atom_cnt; i++) {
1843 struct used_atom *atom = &used_atom[i];
1844 const char *name = atom->name;
1845 struct atom_value *v = &val[i];
1846 enum atom_type atom_type = atom->atom_type;
1848 if (!!deref != (*name == '*'))
1849 continue;
1850 if (deref)
1851 name++;
1853 if (atom_type == ATOM_RAW) {
1854 unsigned long buf_size = data->size;
1856 if (atom->u.raw_data.option == RAW_BARE) {
1857 v->s = xmemdupz(buf, buf_size);
1858 v->s_size = buf_size;
1859 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1860 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1862 continue;
1865 if ((data->type != OBJ_TAG &&
1866 data->type != OBJ_COMMIT) ||
1867 (strcmp(name, "body") &&
1868 !starts_with(name, "subject") &&
1869 !starts_with(name, "trailers") &&
1870 !starts_with(name, "contents")))
1871 continue;
1872 if (!subpos)
1873 find_subpos(buf,
1874 &subpos, &sublen,
1875 &bodypos, &bodylen, &nonsiglen,
1876 &sigpos, &siglen);
1878 if (atom->u.contents.option == C_SUB)
1879 v->s = copy_subject(subpos, sublen);
1880 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1881 struct strbuf sb = STRBUF_INIT;
1882 format_sanitized_subject(&sb, subpos, sublen);
1883 v->s = strbuf_detach(&sb, NULL);
1884 } else if (atom->u.contents.option == C_BODY_DEP)
1885 v->s = xmemdupz(bodypos, bodylen);
1886 else if (atom->u.contents.option == C_LENGTH)
1887 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1888 else if (atom->u.contents.option == C_BODY)
1889 v->s = xmemdupz(bodypos, nonsiglen);
1890 else if (atom->u.contents.option == C_SIG)
1891 v->s = xmemdupz(sigpos, siglen);
1892 else if (atom->u.contents.option == C_LINES) {
1893 struct strbuf s = STRBUF_INIT;
1894 const char *contents_end = bodypos + nonsiglen;
1896 /* Size is the length of the message after removing the signature */
1897 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1898 v->s = strbuf_detach(&s, NULL);
1899 } else if (atom->u.contents.option == C_TRAILERS) {
1900 struct strbuf s = STRBUF_INIT;
1902 /* Format the trailer info according to the trailer_opts given */
1903 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1905 v->s = strbuf_detach(&s, NULL);
1906 } else if (atom->u.contents.option == C_BARE)
1907 v->s = xstrdup(subpos);
1910 free((void *)sigpos);
1914 * We want to have empty print-string for field requests
1915 * that do not apply (e.g. "authordate" for a tag object)
1917 static void fill_missing_values(struct atom_value *val)
1919 int i;
1920 for (i = 0; i < used_atom_cnt; i++) {
1921 struct atom_value *v = &val[i];
1922 if (!v->s)
1923 v->s = xstrdup("");
1928 * val is a list of atom_value to hold returned values. Extract
1929 * the values for atoms in used_atom array out of (obj, buf, sz).
1930 * when deref is false, (obj, buf, sz) is the object that is
1931 * pointed at by the ref itself; otherwise it is the object the
1932 * ref (which is a tag) refers to.
1934 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1936 void *buf = data->content;
1938 switch (obj->type) {
1939 case OBJ_TAG:
1940 grab_tag_values(val, deref, obj);
1941 grab_sub_body_contents(val, deref, data);
1942 grab_person("tagger", val, deref, buf);
1943 grab_describe_values(val, deref, obj);
1944 break;
1945 case OBJ_COMMIT:
1946 grab_commit_values(val, deref, obj);
1947 grab_sub_body_contents(val, deref, data);
1948 grab_person("author", val, deref, buf);
1949 grab_person("committer", val, deref, buf);
1950 grab_signature(val, deref, obj);
1951 grab_describe_values(val, deref, obj);
1952 break;
1953 case OBJ_TREE:
1954 /* grab_tree_values(val, deref, obj, buf, sz); */
1955 grab_sub_body_contents(val, deref, data);
1956 break;
1957 case OBJ_BLOB:
1958 /* grab_blob_values(val, deref, obj, buf, sz); */
1959 grab_sub_body_contents(val, deref, data);
1960 break;
1961 default:
1962 die("Eh? Object of type %d?", obj->type);
1966 static inline char *copy_advance(char *dst, const char *src)
1968 while (*src)
1969 *dst++ = *src++;
1970 return dst;
1973 static const char *lstrip_ref_components(const char *refname, int len)
1975 long remaining = len;
1976 const char *start = xstrdup(refname);
1977 const char *to_free = start;
1979 if (len < 0) {
1980 int i;
1981 const char *p = refname;
1983 /* Find total no of '/' separated path-components */
1984 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1987 * The number of components we need to strip is now
1988 * the total minus the components to be left (Plus one
1989 * because we count the number of '/', but the number
1990 * of components is one more than the no of '/').
1992 remaining = i + len + 1;
1995 while (remaining > 0) {
1996 switch (*start++) {
1997 case '\0':
1998 free((char *)to_free);
1999 return xstrdup("");
2000 case '/':
2001 remaining--;
2002 break;
2006 start = xstrdup(start);
2007 free((char *)to_free);
2008 return start;
2011 static const char *rstrip_ref_components(const char *refname, int len)
2013 long remaining = len;
2014 const char *start = xstrdup(refname);
2015 const char *to_free = start;
2017 if (len < 0) {
2018 int i;
2019 const char *p = refname;
2021 /* Find total no of '/' separated path-components */
2022 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
2025 * The number of components we need to strip is now
2026 * the total minus the components to be left (Plus one
2027 * because we count the number of '/', but the number
2028 * of components is one more than the no of '/').
2030 remaining = i + len + 1;
2033 while (remaining-- > 0) {
2034 char *p = strrchr(start, '/');
2035 if (!p) {
2036 free((char *)to_free);
2037 return xstrdup("");
2038 } else
2039 p[0] = '\0';
2041 return start;
2044 static const char *show_ref(struct refname_atom *atom, const char *refname)
2046 if (atom->option == R_SHORT)
2047 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
2048 else if (atom->option == R_LSTRIP)
2049 return lstrip_ref_components(refname, atom->lstrip);
2050 else if (atom->option == R_RSTRIP)
2051 return rstrip_ref_components(refname, atom->rstrip);
2052 else
2053 return xstrdup(refname);
2056 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2057 struct branch *branch, const char **s)
2059 int num_ours, num_theirs;
2060 if (atom->u.remote_ref.option == RR_REF)
2061 *s = show_ref(&atom->u.remote_ref.refname, refname);
2062 else if (atom->u.remote_ref.option == RR_TRACK) {
2063 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2064 NULL, atom->u.remote_ref.push,
2065 AHEAD_BEHIND_FULL) < 0) {
2066 *s = xstrdup(msgs.gone);
2067 } else if (!num_ours && !num_theirs)
2068 *s = xstrdup("");
2069 else if (!num_ours)
2070 *s = xstrfmt(msgs.behind, num_theirs);
2071 else if (!num_theirs)
2072 *s = xstrfmt(msgs.ahead, num_ours);
2073 else
2074 *s = xstrfmt(msgs.ahead_behind,
2075 num_ours, num_theirs);
2076 if (!atom->u.remote_ref.nobracket && *s[0]) {
2077 const char *to_free = *s;
2078 *s = xstrfmt("[%s]", *s);
2079 free((void *)to_free);
2081 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2082 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2083 NULL, atom->u.remote_ref.push,
2084 AHEAD_BEHIND_FULL) < 0) {
2085 *s = xstrdup("");
2086 return;
2088 if (!num_ours && !num_theirs)
2089 *s = xstrdup("=");
2090 else if (!num_ours)
2091 *s = xstrdup("<");
2092 else if (!num_theirs)
2093 *s = xstrdup(">");
2094 else
2095 *s = xstrdup("<>");
2096 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2097 int explicit;
2098 const char *remote = atom->u.remote_ref.push ?
2099 pushremote_for_branch(branch, &explicit) :
2100 remote_for_branch(branch, &explicit);
2101 *s = xstrdup(explicit ? remote : "");
2102 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2103 const char *merge;
2105 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2106 *s = xstrdup(merge ? merge : "");
2107 } else
2108 BUG("unhandled RR_* enum");
2111 char *get_head_description(void)
2113 struct strbuf desc = STRBUF_INIT;
2114 struct wt_status_state state;
2115 memset(&state, 0, sizeof(state));
2116 wt_status_get_state(the_repository, &state, 1);
2117 if (state.rebase_in_progress ||
2118 state.rebase_interactive_in_progress) {
2119 if (state.branch)
2120 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2121 state.branch);
2122 else
2123 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2124 state.detached_from);
2125 } else if (state.bisect_in_progress)
2126 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2127 state.branch);
2128 else if (state.detached_from) {
2129 if (state.detached_at)
2130 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2131 state.detached_from);
2132 else
2133 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2134 state.detached_from);
2135 } else
2136 strbuf_addstr(&desc, _("(no branch)"));
2138 wt_status_state_free_buffers(&state);
2140 return strbuf_detach(&desc, NULL);
2143 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2145 if (!ref->symref)
2146 return xstrdup("");
2147 else
2148 return show_ref(&atom->u.refname, ref->symref);
2151 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2153 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2154 return get_head_description();
2155 return show_ref(&atom->u.refname, ref->refname);
2158 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
2159 struct expand_data *oi, struct strbuf *err)
2161 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
2162 int eaten = 1;
2163 if (oi->info.contentp) {
2164 /* We need to know that to use parse_object_buffer properly */
2165 oi->info.sizep = &oi->size;
2166 oi->info.typep = &oi->type;
2168 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
2169 OBJECT_INFO_LOOKUP_REPLACE))
2170 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2171 oid_to_hex(&oi->oid), ref->refname);
2172 if (oi->info.disk_sizep && oi->disk_size < 0)
2173 BUG("Object size is less than zero.");
2175 if (oi->info.contentp) {
2176 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
2177 if (!*obj) {
2178 if (!eaten)
2179 free(oi->content);
2180 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
2181 oid_to_hex(&oi->oid), ref->refname);
2183 grab_values(ref->value, deref, *obj, oi);
2186 grab_common_values(ref->value, deref, oi);
2187 if (!eaten)
2188 free(oi->content);
2189 return 0;
2192 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2194 int i;
2196 for (i = 0; worktrees[i]; i++) {
2197 if (worktrees[i]->head_ref) {
2198 struct ref_to_worktree_entry *entry;
2199 entry = xmalloc(sizeof(*entry));
2200 entry->wt = worktrees[i];
2201 hashmap_entry_init(&entry->ent,
2202 strhash(worktrees[i]->head_ref));
2204 hashmap_add(map, &entry->ent);
2209 static void lazy_init_worktree_map(void)
2211 if (ref_to_worktree_map.worktrees)
2212 return;
2214 ref_to_worktree_map.worktrees = get_worktrees();
2215 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2216 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2219 static char *get_worktree_path(const struct ref_array_item *ref)
2221 struct hashmap_entry entry, *e;
2222 struct ref_to_worktree_entry *lookup_result;
2224 lazy_init_worktree_map();
2226 hashmap_entry_init(&entry, strhash(ref->refname));
2227 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2229 if (!e)
2230 return xstrdup("");
2232 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2234 return xstrdup(lookup_result->wt->path);
2238 * Parse the object referred by ref, and grab needed value.
2240 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2242 struct object *obj;
2243 int i;
2244 struct object_info empty = OBJECT_INFO_INIT;
2245 int ahead_behind_atoms = 0;
2247 CALLOC_ARRAY(ref->value, used_atom_cnt);
2249 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2250 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
2251 NULL, NULL);
2252 if (!ref->symref)
2253 ref->symref = xstrdup("");
2256 /* Fill in specials first */
2257 for (i = 0; i < used_atom_cnt; i++) {
2258 struct used_atom *atom = &used_atom[i];
2259 enum atom_type atom_type = atom->atom_type;
2260 const char *name = used_atom[i].name;
2261 struct atom_value *v = &ref->value[i];
2262 int deref = 0;
2263 const char *refname;
2264 struct branch *branch = NULL;
2266 v->s_size = ATOM_SIZE_UNSPECIFIED;
2267 v->handler = append_atom;
2268 v->atom = atom;
2270 if (*name == '*') {
2271 deref = 1;
2272 name++;
2275 if (atom_type == ATOM_REFNAME)
2276 refname = get_refname(atom, ref);
2277 else if (atom_type == ATOM_WORKTREEPATH) {
2278 if (ref->kind == FILTER_REFS_BRANCHES)
2279 v->s = get_worktree_path(ref);
2280 else
2281 v->s = xstrdup("");
2282 continue;
2284 else if (atom_type == ATOM_SYMREF)
2285 refname = get_symref(atom, ref);
2286 else if (atom_type == ATOM_UPSTREAM) {
2287 const char *branch_name;
2288 /* only local branches may have an upstream */
2289 if (!skip_prefix(ref->refname, "refs/heads/",
2290 &branch_name)) {
2291 v->s = xstrdup("");
2292 continue;
2294 branch = branch_get(branch_name);
2296 refname = branch_get_upstream(branch, NULL);
2297 if (refname)
2298 fill_remote_ref_details(atom, refname, branch, &v->s);
2299 else
2300 v->s = xstrdup("");
2301 continue;
2302 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2303 const char *branch_name;
2304 v->s = xstrdup("");
2305 if (!skip_prefix(ref->refname, "refs/heads/",
2306 &branch_name))
2307 continue;
2308 branch = branch_get(branch_name);
2310 if (atom->u.remote_ref.push_remote)
2311 refname = NULL;
2312 else {
2313 refname = branch_get_push(branch, NULL);
2314 if (!refname)
2315 continue;
2317 /* We will definitely re-init v->s on the next line. */
2318 free((char *)v->s);
2319 fill_remote_ref_details(atom, refname, branch, &v->s);
2320 continue;
2321 } else if (atom_type == ATOM_COLOR) {
2322 v->s = xstrdup(atom->u.color);
2323 continue;
2324 } else if (atom_type == ATOM_FLAG) {
2325 char buf[256], *cp = buf;
2326 if (ref->flag & REF_ISSYMREF)
2327 cp = copy_advance(cp, ",symref");
2328 if (ref->flag & REF_ISPACKED)
2329 cp = copy_advance(cp, ",packed");
2330 if (cp == buf)
2331 v->s = xstrdup("");
2332 else {
2333 *cp = '\0';
2334 v->s = xstrdup(buf + 1);
2336 continue;
2337 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2338 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2339 continue;
2340 } else if (atom_type == ATOM_HEAD) {
2341 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2342 v->s = xstrdup("*");
2343 else
2344 v->s = xstrdup(" ");
2345 continue;
2346 } else if (atom_type == ATOM_ALIGN) {
2347 v->handler = align_atom_handler;
2348 v->s = xstrdup("");
2349 continue;
2350 } else if (atom_type == ATOM_END) {
2351 v->handler = end_atom_handler;
2352 v->s = xstrdup("");
2353 continue;
2354 } else if (atom_type == ATOM_IF) {
2355 const char *s;
2356 if (skip_prefix(name, "if:", &s))
2357 v->s = xstrdup(s);
2358 else
2359 v->s = xstrdup("");
2360 v->handler = if_atom_handler;
2361 continue;
2362 } else if (atom_type == ATOM_THEN) {
2363 v->handler = then_atom_handler;
2364 v->s = xstrdup("");
2365 continue;
2366 } else if (atom_type == ATOM_ELSE) {
2367 v->handler = else_atom_handler;
2368 v->s = xstrdup("");
2369 continue;
2370 } else if (atom_type == ATOM_REST) {
2371 if (ref->rest)
2372 v->s = xstrdup(ref->rest);
2373 else
2374 v->s = xstrdup("");
2375 continue;
2376 } else if (atom_type == ATOM_AHEADBEHIND) {
2377 if (ref->counts) {
2378 const struct ahead_behind_count *count;
2379 count = ref->counts[ahead_behind_atoms++];
2380 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2381 } else {
2382 /* Not a commit. */
2383 v->s = xstrdup("");
2385 continue;
2386 } else
2387 continue;
2389 if (!deref)
2390 v->s = xstrdup(refname);
2391 else
2392 v->s = xstrfmt("%s^{}", refname);
2393 free((char *)refname);
2396 for (i = 0; i < used_atom_cnt; i++) {
2397 struct atom_value *v = &ref->value[i];
2398 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2399 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2400 oid_to_hex(&ref->objectname), ref->refname);
2403 if (need_tagged)
2404 oi.info.contentp = &oi.content;
2405 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2406 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2407 return 0;
2410 oi.oid = ref->objectname;
2411 if (get_object(ref, 0, &obj, &oi, err))
2412 return -1;
2415 * If there is no atom that wants to know about tagged
2416 * object, we are done.
2418 if (!need_tagged || (obj->type != OBJ_TAG))
2419 return 0;
2422 * If it is a tag object, see if we use a value that derefs
2423 * the object, and if we do grab the object it refers to.
2425 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2428 * NEEDSWORK: This derefs tag only once, which
2429 * is good to deal with chains of trust, but
2430 * is not consistent with what deref_tag() does
2431 * which peels the onion to the core.
2433 return get_object(ref, 1, &obj, &oi_deref, err);
2437 * Given a ref, return the value for the atom. This lazily gets value
2438 * out of the object by calling populate value.
2440 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2441 struct atom_value **v, struct strbuf *err)
2443 if (!ref->value) {
2444 if (populate_value(ref, err))
2445 return -1;
2446 fill_missing_values(ref->value);
2448 *v = &ref->value[atom];
2449 return 0;
2453 * Return 1 if the refname matches one of the patterns, otherwise 0.
2454 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2455 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2456 * matches "refs/heads/mas*", too).
2458 static int match_pattern(const char **patterns, const char *refname,
2459 int ignore_case)
2461 unsigned flags = 0;
2463 if (ignore_case)
2464 flags |= WM_CASEFOLD;
2467 * When no '--format' option is given we need to skip the prefix
2468 * for matching refs of tags and branches.
2470 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2471 skip_prefix(refname, "refs/heads/", &refname) ||
2472 skip_prefix(refname, "refs/remotes/", &refname) ||
2473 skip_prefix(refname, "refs/", &refname));
2475 for (; *patterns; patterns++) {
2476 if (!wildmatch(*patterns, refname, flags))
2477 return 1;
2479 return 0;
2483 * Return 1 if the refname matches one of the patterns, otherwise 0.
2484 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2485 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2486 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2488 static int match_name_as_path(const char **pattern, const char *refname,
2489 int ignore_case)
2491 int namelen = strlen(refname);
2492 unsigned flags = WM_PATHNAME;
2494 if (ignore_case)
2495 flags |= WM_CASEFOLD;
2497 for (; *pattern; pattern++) {
2498 const char *p = *pattern;
2499 int plen = strlen(p);
2501 if ((plen <= namelen) &&
2502 !strncmp(refname, p, plen) &&
2503 (refname[plen] == '\0' ||
2504 refname[plen] == '/' ||
2505 p[plen-1] == '/'))
2506 return 1;
2507 if (!wildmatch(p, refname, flags))
2508 return 1;
2510 return 0;
2513 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2514 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2516 if (!*filter->name_patterns)
2517 return 1; /* No pattern always matches */
2518 if (filter->match_as_path)
2519 return match_name_as_path(filter->name_patterns, refname,
2520 filter->ignore_case);
2521 return match_pattern(filter->name_patterns, refname,
2522 filter->ignore_case);
2525 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2527 if (!filter->exclude.nr)
2528 return 0;
2529 if (filter->match_as_path)
2530 return match_name_as_path(filter->exclude.v, refname,
2531 filter->ignore_case);
2532 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2536 * This is the same as for_each_fullref_in(), but it tries to iterate
2537 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2538 * pattern match, so the callback still has to match each ref individually.
2540 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2541 each_ref_fn cb,
2542 void *cb_data)
2544 if (!filter->match_as_path) {
2546 * in this case, the patterns are applied after
2547 * prefixes like "refs/heads/" etc. are stripped off,
2548 * so we have to look at everything:
2550 return for_each_fullref_in("", cb, cb_data);
2553 if (filter->ignore_case) {
2555 * we can't handle case-insensitive comparisons,
2556 * so just return everything and let the caller
2557 * sort it out.
2559 return for_each_fullref_in("", cb, cb_data);
2562 if (!filter->name_patterns[0]) {
2563 /* no patterns; we have to look at everything */
2564 return refs_for_each_fullref_in(get_main_ref_store(the_repository),
2565 "", filter->exclude.v, cb, cb_data);
2568 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2569 NULL, filter->name_patterns,
2570 filter->exclude.v,
2571 cb, cb_data);
2575 * Given a ref (oid, refname), check if the ref belongs to the array
2576 * of oids. If the given ref is a tag, check if the given tag points
2577 * at one of the oids in the given oid array. Returns non-zero if a
2578 * match is found.
2580 * NEEDSWORK:
2581 * As the refs are cached we might know what refname peels to without
2582 * the need to parse the object via parse_object(). peel_ref() might be a
2583 * more efficient alternative to obtain the pointee.
2585 static int match_points_at(struct oid_array *points_at,
2586 const struct object_id *oid,
2587 const char *refname)
2589 struct object *obj;
2591 if (oid_array_lookup(points_at, oid) >= 0)
2592 return 1;
2593 obj = parse_object_with_flags(the_repository, oid,
2594 PARSE_OBJECT_SKIP_HASH_CHECK);
2595 while (obj && obj->type == OBJ_TAG) {
2596 struct tag *tag = (struct tag *)obj;
2598 if (parse_tag(tag) < 0) {
2599 obj = NULL;
2600 break;
2603 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2604 return 1;
2606 obj = tag->tagged;
2608 if (!obj)
2609 die(_("malformed object at '%s'"), refname);
2610 return 0;
2614 * Allocate space for a new ref_array_item and copy the name and oid to it.
2616 * Callers can then fill in other struct members at their leisure.
2618 static struct ref_array_item *new_ref_array_item(const char *refname,
2619 const struct object_id *oid)
2621 struct ref_array_item *ref;
2623 FLEX_ALLOC_STR(ref, refname, refname);
2624 oidcpy(&ref->objectname, oid);
2625 ref->rest = NULL;
2627 return ref;
2630 struct ref_array_item *ref_array_push(struct ref_array *array,
2631 const char *refname,
2632 const struct object_id *oid)
2634 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2636 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2637 array->items[array->nr++] = ref;
2639 return ref;
2642 static int ref_kind_from_refname(const char *refname)
2644 unsigned int i;
2646 static struct {
2647 const char *prefix;
2648 unsigned int kind;
2649 } ref_kind[] = {
2650 { "refs/heads/" , FILTER_REFS_BRANCHES },
2651 { "refs/remotes/" , FILTER_REFS_REMOTES },
2652 { "refs/tags/", FILTER_REFS_TAGS}
2655 if (!strcmp(refname, "HEAD"))
2656 return FILTER_REFS_DETACHED_HEAD;
2658 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2659 if (starts_with(refname, ref_kind[i].prefix))
2660 return ref_kind[i].kind;
2663 return FILTER_REFS_OTHERS;
2666 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2668 if (filter->kind == FILTER_REFS_BRANCHES ||
2669 filter->kind == FILTER_REFS_REMOTES ||
2670 filter->kind == FILTER_REFS_TAGS)
2671 return filter->kind;
2672 return ref_kind_from_refname(refname);
2675 struct ref_filter_cbdata {
2676 struct ref_array *array;
2677 struct ref_filter *filter;
2678 struct contains_cache contains_cache;
2679 struct contains_cache no_contains_cache;
2683 * A call-back given to for_each_ref(). Filter refs and keep them for
2684 * later object processing.
2686 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2688 struct ref_filter_cbdata *ref_cbdata = cb_data;
2689 struct ref_filter *filter = ref_cbdata->filter;
2690 struct ref_array_item *ref;
2691 struct commit *commit = NULL;
2692 unsigned int kind;
2694 if (flag & REF_BAD_NAME) {
2695 warning(_("ignoring ref with broken name %s"), refname);
2696 return 0;
2699 if (flag & REF_ISBROKEN) {
2700 warning(_("ignoring broken ref %s"), refname);
2701 return 0;
2704 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2705 kind = filter_ref_kind(filter, refname);
2706 if (!(kind & filter->kind))
2707 return 0;
2709 if (!filter_pattern_match(filter, refname))
2710 return 0;
2712 if (filter_exclude_match(filter, refname))
2713 return 0;
2715 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2716 return 0;
2719 * A merge filter is applied on refs pointing to commits. Hence
2720 * obtain the commit using the 'oid' available and discard all
2721 * non-commits early. The actual filtering is done later.
2723 if (filter->reachable_from || filter->unreachable_from ||
2724 filter->with_commit || filter->no_commit || filter->verbose) {
2725 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2726 if (!commit)
2727 return 0;
2728 /* We perform the filtering for the '--contains' option... */
2729 if (filter->with_commit &&
2730 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2731 return 0;
2732 /* ...or for the `--no-contains' option */
2733 if (filter->no_commit &&
2734 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2735 return 0;
2739 * We do not open the object yet; sort may only need refname
2740 * to do its job and the resulting list may yet to be pruned
2741 * by maxcount logic.
2743 ref = ref_array_push(ref_cbdata->array, refname, oid);
2744 ref->commit = commit;
2745 ref->flag = flag;
2746 ref->kind = kind;
2748 return 0;
2751 /* Free memory allocated for a ref_array_item */
2752 static void free_array_item(struct ref_array_item *item)
2754 free((char *)item->symref);
2755 if (item->value) {
2756 int i;
2757 for (i = 0; i < used_atom_cnt; i++)
2758 free((char *)item->value[i].s);
2759 free(item->value);
2761 free(item->counts);
2762 free(item);
2765 /* Free all memory allocated for ref_array */
2766 void ref_array_clear(struct ref_array *array)
2768 int i;
2770 for (i = 0; i < array->nr; i++)
2771 free_array_item(array->items[i]);
2772 FREE_AND_NULL(array->items);
2773 array->nr = array->alloc = 0;
2775 for (i = 0; i < used_atom_cnt; i++) {
2776 struct used_atom *atom = &used_atom[i];
2777 if (atom->atom_type == ATOM_HEAD)
2778 free(atom->u.head);
2779 free((char *)atom->name);
2781 FREE_AND_NULL(used_atom);
2782 used_atom_cnt = 0;
2784 if (ref_to_worktree_map.worktrees) {
2785 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2786 struct ref_to_worktree_entry, ent);
2787 free_worktrees(ref_to_worktree_map.worktrees);
2788 ref_to_worktree_map.worktrees = NULL;
2791 FREE_AND_NULL(array->counts);
2794 #define EXCLUDE_REACHED 0
2795 #define INCLUDE_REACHED 1
2796 static void reach_filter(struct ref_array *array,
2797 struct commit_list **check_reachable,
2798 int include_reached)
2800 int i, old_nr;
2801 struct commit **to_clear;
2803 if (!*check_reachable)
2804 return;
2806 CALLOC_ARRAY(to_clear, array->nr);
2807 for (i = 0; i < array->nr; i++) {
2808 struct ref_array_item *item = array->items[i];
2809 to_clear[i] = item->commit;
2812 tips_reachable_from_bases(the_repository,
2813 *check_reachable,
2814 to_clear, array->nr,
2815 UNINTERESTING);
2817 old_nr = array->nr;
2818 array->nr = 0;
2820 for (i = 0; i < old_nr; i++) {
2821 struct ref_array_item *item = array->items[i];
2822 struct commit *commit = item->commit;
2824 int is_merged = !!(commit->object.flags & UNINTERESTING);
2826 if (is_merged == include_reached)
2827 array->items[array->nr++] = array->items[i];
2828 else
2829 free_array_item(item);
2832 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2834 while (*check_reachable) {
2835 struct commit *merge_commit = pop_commit(check_reachable);
2836 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2839 free(to_clear);
2842 void filter_ahead_behind(struct repository *r,
2843 struct ref_format *format,
2844 struct ref_array *array)
2846 struct commit **commits;
2847 size_t commits_nr = format->bases.nr + array->nr;
2849 if (!format->bases.nr || !array->nr)
2850 return;
2852 ALLOC_ARRAY(commits, commits_nr);
2853 for (size_t i = 0; i < format->bases.nr; i++)
2854 commits[i] = format->bases.items[i].util;
2856 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
2858 commits_nr = format->bases.nr;
2859 array->counts_nr = 0;
2860 for (size_t i = 0; i < array->nr; i++) {
2861 const char *name = array->items[i]->refname;
2862 commits[commits_nr] = lookup_commit_reference_by_name(name);
2864 if (!commits[commits_nr])
2865 continue;
2867 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
2868 for (size_t j = 0; j < format->bases.nr; j++) {
2869 struct ahead_behind_count *count;
2870 count = &array->counts[array->counts_nr++];
2871 count->tip_index = commits_nr;
2872 count->base_index = j;
2874 array->items[i]->counts[j] = count;
2876 commits_nr++;
2879 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
2880 free(commits);
2884 * API for filtering a set of refs. Based on the type of refs the user
2885 * has requested, we iterate through those refs and apply filters
2886 * as per the given ref_filter structure and finally store the
2887 * filtered refs in the ref_array structure.
2889 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2891 struct ref_filter_cbdata ref_cbdata;
2892 int save_commit_buffer_orig;
2893 int ret = 0;
2895 ref_cbdata.array = array;
2896 ref_cbdata.filter = filter;
2898 filter->kind = type & FILTER_REFS_KIND_MASK;
2900 save_commit_buffer_orig = save_commit_buffer;
2901 save_commit_buffer = 0;
2903 init_contains_cache(&ref_cbdata.contains_cache);
2904 init_contains_cache(&ref_cbdata.no_contains_cache);
2906 /* Simple per-ref filtering */
2907 if (!filter->kind)
2908 die("filter_refs: invalid type");
2909 else {
2911 * For common cases where we need only branches or remotes or tags,
2912 * we only iterate through those refs. If a mix of refs is needed,
2913 * we iterate over all refs and filter out required refs with the help
2914 * of filter_ref_kind().
2916 if (filter->kind == FILTER_REFS_BRANCHES)
2917 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2918 else if (filter->kind == FILTER_REFS_REMOTES)
2919 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2920 else if (filter->kind == FILTER_REFS_TAGS)
2921 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2922 else if (filter->kind & FILTER_REFS_ALL)
2923 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2924 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2925 head_ref(ref_filter_handler, &ref_cbdata);
2928 clear_contains_cache(&ref_cbdata.contains_cache);
2929 clear_contains_cache(&ref_cbdata.no_contains_cache);
2931 /* Filters that need revision walking */
2932 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
2933 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
2935 save_commit_buffer = save_commit_buffer_orig;
2936 return ret;
2939 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2941 if (!(a->kind ^ b->kind))
2942 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2943 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2944 return -1;
2945 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2946 return 1;
2947 BUG("should have died in the xor check above");
2948 return 0;
2951 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2953 const char *s1 = vs1, *s2 = vs2;
2954 const char *end = s1 + n;
2956 for (; s1 < end; s1++, s2++) {
2957 int diff = tolower(*s1) - tolower(*s2);
2958 if (diff)
2959 return diff;
2961 return 0;
2964 struct ref_sorting {
2965 struct ref_sorting *next;
2966 int atom; /* index into used_atom array (internal) */
2967 enum ref_sorting_order sort_flags;
2970 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2972 struct atom_value *va, *vb;
2973 int cmp;
2974 int cmp_detached_head = 0;
2975 cmp_type cmp_type = used_atom[s->atom].type;
2976 struct strbuf err = STRBUF_INIT;
2978 if (get_ref_atom_value(a, s->atom, &va, &err))
2979 die("%s", err.buf);
2980 if (get_ref_atom_value(b, s->atom, &vb, &err))
2981 die("%s", err.buf);
2982 strbuf_release(&err);
2983 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2984 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2985 cmp = compare_detached_head(a, b);
2986 cmp_detached_head = 1;
2987 } else if (s->sort_flags & REF_SORTING_VERSION) {
2988 cmp = versioncmp(va->s, vb->s);
2989 } else if (cmp_type == FIELD_STR) {
2990 if (va->s_size < 0 && vb->s_size < 0) {
2991 int (*cmp_fn)(const char *, const char *);
2992 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2993 ? strcasecmp : strcmp;
2994 cmp = cmp_fn(va->s, vb->s);
2995 } else {
2996 size_t a_size = va->s_size < 0 ?
2997 strlen(va->s) : va->s_size;
2998 size_t b_size = vb->s_size < 0 ?
2999 strlen(vb->s) : vb->s_size;
3000 int (*cmp_fn)(const void *, const void *, size_t);
3001 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3002 ? memcasecmp : memcmp;
3004 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3005 a_size : b_size);
3006 if (!cmp) {
3007 if (a_size > b_size)
3008 cmp = 1;
3009 else if (a_size < b_size)
3010 cmp = -1;
3013 } else {
3014 if (va->value < vb->value)
3015 cmp = -1;
3016 else if (va->value == vb->value)
3017 cmp = 0;
3018 else
3019 cmp = 1;
3022 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3023 ? -cmp : cmp;
3026 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3028 struct ref_array_item *a = *((struct ref_array_item **)a_);
3029 struct ref_array_item *b = *((struct ref_array_item **)b_);
3030 struct ref_sorting *s;
3032 for (s = ref_sorting; s; s = s->next) {
3033 int cmp = cmp_ref_sorting(s, a, b);
3034 if (cmp)
3035 return cmp;
3037 s = ref_sorting;
3038 return s && s->sort_flags & REF_SORTING_ICASE ?
3039 strcasecmp(a->refname, b->refname) :
3040 strcmp(a->refname, b->refname);
3043 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3044 unsigned int mask, int on)
3046 for (; sorting; sorting = sorting->next) {
3047 if (on)
3048 sorting->sort_flags |= mask;
3049 else
3050 sorting->sort_flags &= ~mask;
3054 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3056 QSORT_S(array->items, array->nr, compare_refs, sorting);
3059 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3061 struct strbuf *s = &state->stack->output;
3063 while (*cp && (!ep || cp < ep)) {
3064 if (*cp == '%') {
3065 if (cp[1] == '%')
3066 cp++;
3067 else {
3068 int ch = hex2chr(cp + 1);
3069 if (0 <= ch) {
3070 strbuf_addch(s, ch);
3071 cp += 3;
3072 continue;
3076 strbuf_addch(s, *cp);
3077 cp++;
3081 int format_ref_array_item(struct ref_array_item *info,
3082 struct ref_format *format,
3083 struct strbuf *final_buf,
3084 struct strbuf *error_buf)
3086 const char *cp, *sp, *ep;
3087 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3089 state.quote_style = format->quote_style;
3090 push_stack_element(&state.stack);
3092 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3093 struct atom_value *atomv;
3094 int pos;
3096 ep = strchr(sp, ')');
3097 if (cp < sp)
3098 append_literal(cp, sp, &state);
3099 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3100 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3101 atomv->handler(atomv, &state, error_buf)) {
3102 pop_stack_element(&state.stack);
3103 return -1;
3106 if (*cp) {
3107 sp = cp + strlen(cp);
3108 append_literal(cp, sp, &state);
3110 if (format->need_color_reset_at_eol) {
3111 struct atom_value resetv = ATOM_VALUE_INIT;
3112 resetv.s = GIT_COLOR_RESET;
3113 if (append_atom(&resetv, &state, error_buf)) {
3114 pop_stack_element(&state.stack);
3115 return -1;
3118 if (state.stack->prev) {
3119 pop_stack_element(&state.stack);
3120 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3122 strbuf_addbuf(final_buf, &state.stack->output);
3123 pop_stack_element(&state.stack);
3124 return 0;
3127 void pretty_print_ref(const char *name, const struct object_id *oid,
3128 struct ref_format *format)
3130 struct ref_array_item *ref_item;
3131 struct strbuf output = STRBUF_INIT;
3132 struct strbuf err = STRBUF_INIT;
3134 ref_item = new_ref_array_item(name, oid);
3135 ref_item->kind = ref_kind_from_refname(name);
3136 if (format_ref_array_item(ref_item, format, &output, &err))
3137 die("%s", err.buf);
3138 fwrite(output.buf, 1, output.len, stdout);
3139 putchar('\n');
3141 strbuf_release(&err);
3142 strbuf_release(&output);
3143 free_array_item(ref_item);
3146 static int parse_sorting_atom(const char *atom)
3149 * This parses an atom using a dummy ref_format, since we don't
3150 * actually care about the formatting details.
3152 struct ref_format dummy = REF_FORMAT_INIT;
3153 const char *end = atom + strlen(atom);
3154 struct strbuf err = STRBUF_INIT;
3155 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3156 if (res < 0)
3157 die("%s", err.buf);
3158 strbuf_release(&err);
3159 return res;
3162 /* If no sorting option is given, use refname to sort as default */
3163 static struct ref_sorting *ref_default_sorting(void)
3165 static const char cstr_name[] = "refname";
3167 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
3169 sorting->next = NULL;
3170 sorting->atom = parse_sorting_atom(cstr_name);
3171 return sorting;
3174 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3176 struct ref_sorting *s;
3178 CALLOC_ARRAY(s, 1);
3179 s->next = *sorting_tail;
3180 *sorting_tail = s;
3182 if (*arg == '-') {
3183 s->sort_flags |= REF_SORTING_REVERSE;
3184 arg++;
3186 if (skip_prefix(arg, "version:", &arg) ||
3187 skip_prefix(arg, "v:", &arg))
3188 s->sort_flags |= REF_SORTING_VERSION;
3189 s->atom = parse_sorting_atom(arg);
3192 struct ref_sorting *ref_sorting_options(struct string_list *options)
3194 struct string_list_item *item;
3195 struct ref_sorting *sorting = NULL, **tail = &sorting;
3197 if (!options->nr) {
3198 sorting = ref_default_sorting();
3199 } else {
3200 for_each_string_list_item(item, options)
3201 parse_ref_sorting(tail, item->string);
3205 * From here on, the ref_sorting list should be used to talk
3206 * about the sort order used for the output. The caller
3207 * should not touch the string form anymore.
3209 string_list_clear(options, 0);
3210 return sorting;
3213 void ref_sorting_release(struct ref_sorting *sorting)
3215 while (sorting) {
3216 struct ref_sorting *next = sorting->next;
3217 free(sorting);
3218 sorting = next;
3222 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3224 struct ref_filter *rf = opt->value;
3225 struct object_id oid;
3226 struct commit *merge_commit;
3228 BUG_ON_OPT_NEG(unset);
3230 if (repo_get_oid(the_repository, arg, &oid))
3231 die(_("malformed object name %s"), arg);
3233 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3235 if (!merge_commit)
3236 return error(_("option `%s' must point to a commit"), opt->long_name);
3238 if (starts_with(opt->long_name, "no"))
3239 commit_list_insert(merge_commit, &rf->unreachable_from);
3240 else
3241 commit_list_insert(merge_commit, &rf->reachable_from);
3243 return 0;
3246 void ref_filter_init(struct ref_filter *filter)
3248 struct ref_filter blank = REF_FILTER_INIT;
3249 memcpy(filter, &blank, sizeof(blank));
3252 void ref_filter_clear(struct ref_filter *filter)
3254 strvec_clear(&filter->exclude);
3255 oid_array_clear(&filter->points_at);
3256 free_commit_list(filter->with_commit);
3257 free_commit_list(filter->no_commit);
3258 free_commit_list(filter->reachable_from);
3259 free_commit_list(filter->unreachable_from);
3260 ref_filter_init(filter);