Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
3
4 #include "git-compat-util.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "config.h"
8 #include "gpg-interface.h"
9 #include "hex.h"
10 #include "parse-options.h"
11 #include "run-command.h"
12 #include "refs.h"
13 #include "wildmatch.h"
14 #include "object-name.h"
15 #include "odb.h"
16 #include "oid-array.h"
17 #include "repo-settings.h"
18 #include "repository.h"
19 #include "commit.h"
20 #include "mailmap.h"
21 #include "ident.h"
22 #include "remote.h"
23 #include "color.h"
24 #include "tag.h"
25 #include "quote.h"
26 #include "ref-filter.h"
27 #include "revision.h"
28 #include "utf8.h"
29 #include "versioncmp.h"
30 #include "trailer.h"
31 #include "wt-status.h"
32 #include "commit-slab.h"
33 #include "commit-reach.h"
34 #include "worktree.h"
35 #include "hashmap.h"
36
37 static struct ref_msg {
38 const char *gone;
39 const char *ahead;
40 const char *behind;
41 const char *ahead_behind;
42 } msgs = {
43 /* Untranslated plumbing messages: */
44 "gone",
45 "ahead %d",
46 "behind %d",
47 "ahead %d, behind %d"
48 };
49
50 void setup_ref_filter_porcelain_msg(void)
51 {
52 msgs.gone = _("gone");
53 msgs.ahead = _("ahead %d");
54 msgs.behind = _("behind %d");
55 msgs.ahead_behind = _("ahead %d, behind %d");
56 }
57
58 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
59 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
60 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
61
62 struct align {
63 align_type position;
64 unsigned int width;
65 };
66
67 struct if_then_else {
68 cmp_status cmp_status;
69 const char *str;
70 unsigned int then_atom_seen : 1,
71 else_atom_seen : 1,
72 condition_satisfied : 1;
73 };
74
75 struct refname_atom {
76 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
77 int lstrip, rstrip;
78 };
79
80 struct ref_trailer_buf {
81 struct string_list filter_list;
82 struct strbuf sepbuf;
83 struct strbuf kvsepbuf;
84 };
85
86 static struct expand_data {
87 struct object_id oid;
88 enum object_type type;
89 size_t size;
90 off_t disk_size;
91 struct object_id delta_base_oid;
92 void *content;
93
94 struct object *maybe_object;
95 struct object_info info;
96 } oi, oi_deref;
97
98 struct ref_to_worktree_entry {
99 struct hashmap_entry ent;
100 struct worktree *wt; /* key is wt->head_ref */
101 };
102
103 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
104 const struct hashmap_entry *eptr,
105 const struct hashmap_entry *kptr,
106 const void *keydata_aka_refname)
107 {
108 const struct ref_to_worktree_entry *e, *k;
109
110 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
111 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
112
113 return strcmp(e->wt->head_ref,
114 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
115 }
116
117 static struct ref_to_worktree_map {
118 struct hashmap map;
119 struct worktree **worktrees;
120 } ref_to_worktree_map;
121
122 /*
123 * The enum atom_type is used as the index of valid_atom array.
124 * In the atom parsing stage, it will be passed to used_atom.atom_type
125 * as the identifier of the atom type. We can check the type of used_atom
126 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
127 */
128 enum atom_type {
129 ATOM_REFNAME,
130 ATOM_OBJECTTYPE,
131 ATOM_OBJECTSIZE,
132 ATOM_OBJECTNAME,
133 ATOM_DELTABASE,
134 ATOM_TREE,
135 ATOM_PARENT,
136 ATOM_NUMPARENT,
137 ATOM_OBJECT,
138 ATOM_TYPE,
139 ATOM_TAG,
140 ATOM_AUTHOR,
141 ATOM_AUTHORNAME,
142 ATOM_AUTHOREMAIL,
143 ATOM_AUTHORDATE,
144 ATOM_COMMITTER,
145 ATOM_COMMITTERNAME,
146 ATOM_COMMITTEREMAIL,
147 ATOM_COMMITTERDATE,
148 ATOM_TAGGER,
149 ATOM_TAGGERNAME,
150 ATOM_TAGGEREMAIL,
151 ATOM_TAGGERDATE,
152 ATOM_CREATOR,
153 ATOM_CREATORDATE,
154 ATOM_DESCRIBE,
155 ATOM_SUBJECT,
156 ATOM_BODY,
157 ATOM_TRAILERS,
158 ATOM_CONTENTS,
159 ATOM_SIGNATURE,
160 ATOM_RAW,
161 ATOM_UPSTREAM,
162 ATOM_PUSH,
163 ATOM_SYMREF,
164 ATOM_FLAG,
165 ATOM_HEAD,
166 ATOM_COLOR,
167 ATOM_WORKTREEPATH,
168 ATOM_ALIGN,
169 ATOM_END,
170 ATOM_IF,
171 ATOM_THEN,
172 ATOM_ELSE,
173 ATOM_REST,
174 ATOM_AHEADBEHIND,
175 ATOM_ISBASE,
176 };
177
178 /*
179 * An atom is a valid field atom listed below, possibly prefixed with
180 * a "*" to denote deref_tag().
181 *
182 * We parse given format string and sort specifiers, and make a list
183 * of properties that we need to extract out of objects. ref_array_item
184 * structure will hold an array of values extracted that can be
185 * indexed with the "atom number", which is an index into this
186 * array.
187 */
188 static struct used_atom {
189 enum atom_type atom_type;
190 const char *name;
191 cmp_type type;
192 info_source source;
193 union {
194 char color[COLOR_MAXLEN];
195 struct align align;
196 struct {
197 enum {
198 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
199 } option;
200 struct refname_atom refname;
201 unsigned int nobracket : 1, push : 1, push_remote : 1;
202 } remote_ref;
203 struct {
204 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
205 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
206 struct process_trailer_options trailer_opts;
207 struct ref_trailer_buf *trailer_buf;
208 unsigned int nlines;
209 } contents;
210 struct {
211 enum { RAW_BARE, RAW_LENGTH } option;
212 } raw_data;
213 struct {
214 cmp_status cmp_status;
215 const char *str;
216 } if_then_else;
217 struct {
218 enum { O_FULL, O_LENGTH, O_SHORT } option;
219 unsigned int length;
220 } oid;
221 struct {
222 enum { O_SIZE, O_SIZE_DISK } option;
223 } objectsize;
224 struct {
225 enum { N_RAW, N_MAILMAP } option;
226 } name_option;
227 struct {
228 enum {
229 EO_RAW = 0,
230 EO_TRIM = 1<<0,
231 EO_LOCALPART = 1<<1,
232 EO_MAILMAP = 1<<2,
233 } option;
234 } email_option;
235 struct {
236 enum { S_BARE, S_GRADE, S_SIGNER, S_KEY,
237 S_FINGERPRINT, S_PRI_KEY_FP, S_TRUST_LEVEL } option;
238 } signature;
239 struct {
240 char *name;
241 struct commit *commit;
242 } base;
243 struct strvec describe_args;
244 struct refname_atom refname;
245 char *head;
246 } u;
247 } *used_atom;
248 static int used_atom_cnt, need_tagged, need_symref;
249
250 /*
251 * Expand string, append it to strbuf *sb, then return error code ret.
252 * Allow to save few lines of code.
253 */
254 __attribute__((format (printf, 3, 4)))
255 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
256 {
257 va_list ap;
258 va_start(ap, fmt);
259 strbuf_vaddf(sb, fmt, ap);
260 va_end(ap);
261 return ret;
262 }
263
264 static int err_no_arg(struct strbuf *sb, const char *name)
265 {
266 size_t namelen = strchrnul(name, ':') - name;
267 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
268 (int)namelen, name);
269 return -1;
270 }
271
272 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
273 {
274 size_t namelen = strchrnul(name, ':') - name;
275 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
276 (int)namelen, name, arg);
277 return -1;
278 }
279
280 /*
281 * Parse option of name "candidate" in the option string "to_parse" of
282 * the form
283 *
284 * "candidate1[=val1],candidate2[=val2],candidate3[=val3],..."
285 *
286 * The remaining part of "to_parse" is stored in "end" (if we are
287 * parsing the last candidate, then this is NULL) and the value of
288 * the candidate is stored in "valuestart" and its length in "valuelen",
289 * that is the portion after "=". Since it is possible for a "candidate"
290 * to not have a value, in such cases, "valuestart" is set to point to
291 * NULL and "valuelen" to 0.
292 *
293 * The function returns 1 on success. It returns 0 if we don't find
294 * "candidate" in "to_parse" or we find "candidate" but it is followed
295 * by more chars (for example, "candidatefoo"), that is, we don't find
296 * an exact match.
297 *
298 * This function only does the above for one "candidate" at a time. So
299 * it has to be called each time trying to parse a "candidate" in the
300 * option string "to_parse".
301 */
302 static int match_atom_arg_value(const char *to_parse, const char *candidate,
303 const char **end, const char **valuestart,
304 size_t *valuelen)
305 {
306 const char *atom;
307
308 if (!skip_prefix(to_parse, candidate, &atom))
309 return 0; /* definitely not "candidate" */
310
311 if (*atom == '=') {
312 /* we just saw "candidate=" */
313 *valuestart = atom + 1;
314 atom = strchrnul(*valuestart, ',');
315 *valuelen = atom - *valuestart;
316 } else if (*atom != ',' && *atom != '\0') {
317 /* key begins with "candidate" but has more chars */
318 return 0;
319 } else {
320 /* just "candidate" without "=val" */
321 *valuestart = NULL;
322 *valuelen = 0;
323 }
324
325 /* atom points at either the ',' or NUL after this key[=val] */
326 if (*atom == ',')
327 atom++;
328 else if (*atom)
329 BUG("Why is *atom not NULL yet?");
330
331 *end = atom;
332 return 1;
333 }
334
335 /*
336 * Parse boolean option of name "candidate" in the option list "to_parse"
337 * of the form
338 *
339 * "candidate1[=bool1],candidate2[=bool2],candidate3[=bool3],..."
340 *
341 * The remaining part of "to_parse" is stored in "end" (if we are parsing
342 * the last candidate, then this is NULL) and the value (if given) is
343 * parsed and stored in "val", so "val" always points to either 0 or 1.
344 * If the value is not given, then "val" is set to point to 1.
345 *
346 * The boolean value is parsed using "git_parse_maybe_bool()", so the
347 * accepted values are
348 *
349 * to set true - "1", "yes", "true"
350 * to set false - "0", "no", "false"
351 *
352 * This function returns 1 on success. It returns 0 when we don't find
353 * an exact match for "candidate" or when the boolean value given is
354 * not valid.
355 */
356 static int match_atom_bool_arg(const char *to_parse, const char *candidate,
357 const char **end, int *val)
358 {
359 const char *argval;
360 char *strval;
361 size_t arglen;
362 int v;
363
364 if (!match_atom_arg_value(to_parse, candidate, end, &argval, &arglen))
365 return 0;
366
367 if (!argval) {
368 *val = 1;
369 return 1;
370 }
371
372 strval = xstrndup(argval, arglen);
373 v = git_parse_maybe_bool(strval);
374 free(strval);
375
376 if (v == -1)
377 return 0;
378
379 *val = v;
380
381 return 1;
382 }
383
384 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
385 const char *color_value, struct strbuf *err)
386 {
387 if (!color_value)
388 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
389 if (color_parse(color_value, atom->u.color) < 0)
390 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
391 color_value);
392 /*
393 * We check this after we've parsed the color, which lets us complain
394 * about syntactically bogus color names even if they won't be used.
395 */
396 if (!want_color(format->use_color))
397 color_parse("", atom->u.color);
398 return 0;
399 }
400
401 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
402 const char *name, struct strbuf *err)
403 {
404 if (!arg)
405 atom->option = R_NORMAL;
406 else if (!strcmp(arg, "short"))
407 atom->option = R_SHORT;
408 else if (skip_prefix(arg, "lstrip=", &arg) ||
409 skip_prefix(arg, "strip=", &arg)) {
410 atom->option = R_LSTRIP;
411 if (strtol_i(arg, 10, &atom->lstrip))
412 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
413 } else if (skip_prefix(arg, "rstrip=", &arg)) {
414 atom->option = R_RSTRIP;
415 if (strtol_i(arg, 10, &atom->rstrip))
416 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
417 } else
418 return err_bad_arg(err, name, arg);
419 return 0;
420 }
421
422 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
423 struct used_atom *atom,
424 const char *arg, struct strbuf *err)
425 {
426 struct string_list params = STRING_LIST_INIT_DUP;
427 int i;
428
429 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
430 atom->u.remote_ref.push = 1;
431
432 if (!arg) {
433 atom->u.remote_ref.option = RR_REF;
434 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
435 arg, atom->name, err);
436 }
437
438 atom->u.remote_ref.nobracket = 0;
439 string_list_split(&params, arg, ",", -1);
440
441 for (i = 0; i < params.nr; i++) {
442 const char *s = params.items[i].string;
443
444 if (!strcmp(s, "track"))
445 atom->u.remote_ref.option = RR_TRACK;
446 else if (!strcmp(s, "trackshort"))
447 atom->u.remote_ref.option = RR_TRACKSHORT;
448 else if (!strcmp(s, "nobracket"))
449 atom->u.remote_ref.nobracket = 1;
450 else if (!strcmp(s, "remotename")) {
451 atom->u.remote_ref.option = RR_REMOTE_NAME;
452 atom->u.remote_ref.push_remote = 1;
453 } else if (!strcmp(s, "remoteref")) {
454 atom->u.remote_ref.option = RR_REMOTE_REF;
455 atom->u.remote_ref.push_remote = 1;
456 } else {
457 atom->u.remote_ref.option = RR_REF;
458 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
459 arg, atom->name, err)) {
460 string_list_clear(&params, 0);
461 return -1;
462 }
463 }
464 }
465
466 string_list_clear(&params, 0);
467 return 0;
468 }
469
470 static int objecttype_atom_parser(struct ref_format *format UNUSED,
471 struct used_atom *atom,
472 const char *arg, struct strbuf *err)
473 {
474 if (arg)
475 return err_no_arg(err, "objecttype");
476 if (*atom->name == '*')
477 oi_deref.info.typep = &oi_deref.type;
478 else
479 oi.info.typep = &oi.type;
480 return 0;
481 }
482
483 static int objectsize_atom_parser(struct ref_format *format UNUSED,
484 struct used_atom *atom,
485 const char *arg, struct strbuf *err)
486 {
487 if (!arg) {
488 atom->u.objectsize.option = O_SIZE;
489 if (*atom->name == '*')
490 oi_deref.info.sizep = &oi_deref.size;
491 else
492 oi.info.sizep = &oi.size;
493 } else if (!strcmp(arg, "disk")) {
494 atom->u.objectsize.option = O_SIZE_DISK;
495 if (*atom->name == '*')
496 oi_deref.info.disk_sizep = &oi_deref.disk_size;
497 else
498 oi.info.disk_sizep = &oi.disk_size;
499 } else
500 return err_bad_arg(err, "objectsize", arg);
501 return 0;
502 }
503
504 static int deltabase_atom_parser(struct ref_format *format UNUSED,
505 struct used_atom *atom,
506 const char *arg, struct strbuf *err)
507 {
508 if (arg)
509 return err_no_arg(err, "deltabase");
510 if (*atom->name == '*')
511 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
512 else
513 oi.info.delta_base_oid = &oi.delta_base_oid;
514 return 0;
515 }
516
517 static int body_atom_parser(struct ref_format *format UNUSED,
518 struct used_atom *atom,
519 const char *arg, struct strbuf *err)
520 {
521 if (arg)
522 return err_no_arg(err, "body");
523 atom->u.contents.option = C_BODY_DEP;
524 return 0;
525 }
526
527 static int subject_atom_parser(struct ref_format *format UNUSED,
528 struct used_atom *atom,
529 const char *arg, struct strbuf *err)
530 {
531 if (!arg)
532 atom->u.contents.option = C_SUB;
533 else if (!strcmp(arg, "sanitize"))
534 atom->u.contents.option = C_SUB_SANITIZE;
535 else
536 return err_bad_arg(err, "subject", arg);
537 return 0;
538 }
539
540 static int parse_signature_option(const char *arg)
541 {
542 if (!arg)
543 return S_BARE;
544 else if (!strcmp(arg, "signer"))
545 return S_SIGNER;
546 else if (!strcmp(arg, "grade"))
547 return S_GRADE;
548 else if (!strcmp(arg, "key"))
549 return S_KEY;
550 else if (!strcmp(arg, "fingerprint"))
551 return S_FINGERPRINT;
552 else if (!strcmp(arg, "primarykeyfingerprint"))
553 return S_PRI_KEY_FP;
554 else if (!strcmp(arg, "trustlevel"))
555 return S_TRUST_LEVEL;
556 return -1;
557 }
558
559 static int signature_atom_parser(struct ref_format *format UNUSED,
560 struct used_atom *atom,
561 const char *arg, struct strbuf *err)
562 {
563 int opt = parse_signature_option(arg);
564 if (opt < 0)
565 return err_bad_arg(err, "signature", arg);
566 atom->u.signature.option = opt;
567 return 0;
568 }
569
570 static int trailers_atom_parser(struct ref_format *format UNUSED,
571 struct used_atom *atom,
572 const char *arg, struct strbuf *err)
573 {
574 atom->u.contents.trailer_opts.no_divider = 1;
575
576 if (arg) {
577 char *argbuf = xstrfmt("%s)", arg);
578 const char *arg = argbuf;
579 char *invalid_arg = NULL;
580 struct ref_trailer_buf *tb;
581
582 /*
583 * Do not inline these directly into the used_atom struct!
584 * When we parse them in format_set_trailers_options(),
585 * we will make pointer references directly to them,
586 * which will not survive a realloc() of the used_atom list.
587 * They must be allocated in a separate, stable struct.
588 */
589 atom->u.contents.trailer_buf = tb = xmalloc(sizeof(*tb));
590 string_list_init_dup(&tb->filter_list);
591 strbuf_init(&tb->sepbuf, 0);
592 strbuf_init(&tb->kvsepbuf, 0);
593
594 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
595 &tb->filter_list,
596 &tb->sepbuf, &tb->kvsepbuf,
597 &arg, &invalid_arg)) {
598 if (!invalid_arg)
599 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
600 else
601 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
602 free(invalid_arg);
603 free(argbuf);
604 return -1;
605 }
606 free(argbuf);
607 }
608 atom->u.contents.option = C_TRAILERS;
609 return 0;
610 }
611
612 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
613 const char *arg, struct strbuf *err)
614 {
615 if (!arg)
616 atom->u.contents.option = C_BARE;
617 else if (!strcmp(arg, "body"))
618 atom->u.contents.option = C_BODY;
619 else if (!strcmp(arg, "size")) {
620 atom->type = FIELD_ULONG;
621 atom->u.contents.option = C_LENGTH;
622 } else if (!strcmp(arg, "signature"))
623 atom->u.contents.option = C_SIG;
624 else if (!strcmp(arg, "subject"))
625 atom->u.contents.option = C_SUB;
626 else if (!strcmp(arg, "trailers")) {
627 if (trailers_atom_parser(format, atom, NULL, err))
628 return -1;
629 } else if (skip_prefix(arg, "trailers:", &arg)) {
630 if (trailers_atom_parser(format, atom, arg, err))
631 return -1;
632 } else if (skip_prefix(arg, "lines=", &arg)) {
633 atom->u.contents.option = C_LINES;
634 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
635 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
636 } else
637 return err_bad_arg(err, "contents", arg);
638 return 0;
639 }
640
641 static int describe_atom_option_parser(struct strvec *args, const char **arg,
642 struct strbuf *err)
643 {
644 const char *argval;
645 size_t arglen = 0;
646 int optval = 0;
647
648 if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {
649 if (!optval)
650 strvec_push(args, "--no-tags");
651 else
652 strvec_push(args, "--tags");
653 return 1;
654 }
655
656 if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {
657 char *endptr;
658
659 if (!arglen)
660 return strbuf_addf_ret(err, -1,
661 _("argument expected for %s"),
662 "describe:abbrev");
663 if (strtol(argval, &endptr, 10) < 0)
664 return strbuf_addf_ret(err, -1,
665 _("positive value expected %s=%s"),
666 "describe:abbrev", argval);
667 if (endptr - argval != arglen)
668 return strbuf_addf_ret(err, -1,
669 _("cannot fully parse %s=%s"),
670 "describe:abbrev", argval);
671
672 strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);
673 return 1;
674 }
675
676 if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {
677 if (!arglen)
678 return strbuf_addf_ret(err, -1,
679 _("value expected %s="),
680 "describe:match");
681
682 strvec_pushf(args, "--match=%.*s", (int)arglen, argval);
683 return 1;
684 }
685
686 if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {
687 if (!arglen)
688 return strbuf_addf_ret(err, -1,
689 _("value expected %s="),
690 "describe:exclude");
691
692 strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);
693 return 1;
694 }
695
696 return 0;
697 }
698
699 static int describe_atom_parser(struct ref_format *format UNUSED,
700 struct used_atom *atom,
701 const char *arg, struct strbuf *err)
702 {
703 strvec_init(&atom->u.describe_args);
704
705 for (;;) {
706 int found = 0;
707 const char *bad_arg = arg;
708
709 if (!arg || !*arg)
710 break;
711
712 found = describe_atom_option_parser(&atom->u.describe_args, &arg, err);
713 if (found < 0)
714 return found;
715 if (!found)
716 return err_bad_arg(err, "describe", bad_arg);
717 }
718 return 0;
719 }
720
721 static int raw_atom_parser(struct ref_format *format UNUSED,
722 struct used_atom *atom,
723 const char *arg, struct strbuf *err)
724 {
725 if (!arg)
726 atom->u.raw_data.option = RAW_BARE;
727 else if (!strcmp(arg, "size")) {
728 atom->type = FIELD_ULONG;
729 atom->u.raw_data.option = RAW_LENGTH;
730 } else
731 return err_bad_arg(err, "raw", arg);
732 return 0;
733 }
734
735 static int oid_atom_parser(struct ref_format *format UNUSED,
736 struct used_atom *atom,
737 const char *arg, struct strbuf *err)
738 {
739 if (!arg)
740 atom->u.oid.option = O_FULL;
741 else if (!strcmp(arg, "short"))
742 atom->u.oid.option = O_SHORT;
743 else if (skip_prefix(arg, "short=", &arg)) {
744 atom->u.oid.option = O_LENGTH;
745 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
746 atom->u.oid.length == 0)
747 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
748 if (atom->u.oid.length < MINIMUM_ABBREV)
749 atom->u.oid.length = MINIMUM_ABBREV;
750 } else
751 return err_bad_arg(err, atom->name, arg);
752 return 0;
753 }
754
755 static int person_name_atom_parser(struct ref_format *format UNUSED,
756 struct used_atom *atom,
757 const char *arg, struct strbuf *err)
758 {
759 if (!arg)
760 atom->u.name_option.option = N_RAW;
761 else if (!strcmp(arg, "mailmap"))
762 atom->u.name_option.option = N_MAILMAP;
763 else
764 return err_bad_arg(err, atom->name, arg);
765 return 0;
766 }
767
768 static int email_atom_option_parser(const char **arg)
769 {
770 if (!*arg)
771 return EO_RAW;
772 if (skip_prefix(*arg, "trim", arg))
773 return EO_TRIM;
774 if (skip_prefix(*arg, "localpart", arg))
775 return EO_LOCALPART;
776 if (skip_prefix(*arg, "mailmap", arg))
777 return EO_MAILMAP;
778 return -1;
779 }
780
781 static int person_email_atom_parser(struct ref_format *format UNUSED,
782 struct used_atom *atom,
783 const char *arg, struct strbuf *err)
784 {
785 for (;;) {
786 int opt = email_atom_option_parser(&arg);
787 const char *bad_arg = arg;
788
789 if (opt < 0)
790 return err_bad_arg(err, atom->name, bad_arg);
791 atom->u.email_option.option |= opt;
792
793 if (!arg || !*arg)
794 break;
795 if (*arg == ',')
796 arg++;
797 else
798 return err_bad_arg(err, atom->name, bad_arg);
799 }
800 return 0;
801 }
802
803 static int refname_atom_parser(struct ref_format *format UNUSED,
804 struct used_atom *atom,
805 const char *arg, struct strbuf *err)
806 {
807 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
808 }
809
810 static align_type parse_align_position(const char *s)
811 {
812 if (!strcmp(s, "right"))
813 return ALIGN_RIGHT;
814 else if (!strcmp(s, "middle"))
815 return ALIGN_MIDDLE;
816 else if (!strcmp(s, "left"))
817 return ALIGN_LEFT;
818 return -1;
819 }
820
821 static int align_atom_parser(struct ref_format *format UNUSED,
822 struct used_atom *atom,
823 const char *arg, struct strbuf *err)
824 {
825 struct align *align = &atom->u.align;
826 struct string_list params = STRING_LIST_INIT_DUP;
827 int i;
828 unsigned int width = ~0U;
829
830 if (!arg)
831 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
832
833 align->position = ALIGN_LEFT;
834
835 string_list_split(&params, arg, ",", -1);
836 for (i = 0; i < params.nr; i++) {
837 const char *s = params.items[i].string;
838 int position;
839
840 if (skip_prefix(s, "position=", &s)) {
841 position = parse_align_position(s);
842 if (position < 0) {
843 strbuf_addf(err, _("unrecognized position:%s"), s);
844 string_list_clear(&params, 0);
845 return -1;
846 }
847 align->position = position;
848 } else if (skip_prefix(s, "width=", &s)) {
849 if (strtoul_ui(s, 10, &width)) {
850 strbuf_addf(err, _("unrecognized width:%s"), s);
851 string_list_clear(&params, 0);
852 return -1;
853 }
854 } else if (!strtoul_ui(s, 10, &width))
855 ;
856 else if ((position = parse_align_position(s)) >= 0)
857 align->position = position;
858 else {
859 strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);
860 string_list_clear(&params, 0);
861 return -1;
862 }
863 }
864
865 if (width == ~0U) {
866 string_list_clear(&params, 0);
867 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
868 }
869 align->width = width;
870 string_list_clear(&params, 0);
871 return 0;
872 }
873
874 static int if_atom_parser(struct ref_format *format UNUSED,
875 struct used_atom *atom,
876 const char *arg, struct strbuf *err)
877 {
878 if (!arg) {
879 atom->u.if_then_else.cmp_status = COMPARE_NONE;
880 return 0;
881 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
882 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
883 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
884 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
885 } else
886 return err_bad_arg(err, "if", arg);
887 return 0;
888 }
889
890 static int rest_atom_parser(struct ref_format *format UNUSED,
891 struct used_atom *atom UNUSED,
892 const char *arg, struct strbuf *err)
893 {
894 if (arg)
895 return err_no_arg(err, "rest");
896 return 0;
897 }
898
899 static int ahead_behind_atom_parser(struct ref_format *format UNUSED,
900 struct used_atom *atom,
901 const char *arg, struct strbuf *err)
902 {
903 if (!arg)
904 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
905
906 atom->u.base.commit = lookup_commit_reference_by_name(arg);
907 if (!atom->u.base.commit)
908 die("failed to find '%s'", arg);
909
910 return 0;
911 }
912
913 static int is_base_atom_parser(struct ref_format *format UNUSED,
914 struct used_atom *atom,
915 const char *arg, struct strbuf *err)
916 {
917 if (!arg)
918 return strbuf_addf_ret(err, -1, _("expected format: %%(is-base:<committish>)"));
919
920 atom->u.base.name = xstrdup(arg);
921 atom->u.base.commit = lookup_commit_reference_by_name(arg);
922 if (!atom->u.base.commit)
923 die("failed to find '%s'", arg);
924
925 return 0;
926 }
927
928 static int head_atom_parser(struct ref_format *format UNUSED,
929 struct used_atom *atom,
930 const char *arg, struct strbuf *err)
931 {
932 if (arg)
933 return err_no_arg(err, "HEAD");
934 atom->u.head = refs_resolve_refdup(get_main_ref_store(the_repository),
935 "HEAD", RESOLVE_REF_READING, NULL,
936 NULL);
937 return 0;
938 }
939
940 static struct {
941 const char *name;
942 info_source source;
943 cmp_type cmp_type;
944 int (*parser)(struct ref_format *format, struct used_atom *atom,
945 const char *arg, struct strbuf *err);
946 } valid_atom[] = {
947 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
948 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
949 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
950 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
951 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
952 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
953 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
954 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
955 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
956 [ATOM_TYPE] = { "type", SOURCE_OBJ },
957 [ATOM_TAG] = { "tag", SOURCE_OBJ },
958 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
959 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
960 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
961 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
962 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
963 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
964 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
965 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
966 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
967 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },
968 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
969 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
970 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
971 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
972 [ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },
973 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
974 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
975 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
976 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
977 [ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },
978 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
979 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
980 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
981 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
982 [ATOM_FLAG] = { "flag", SOURCE_NONE },
983 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
984 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
985 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
986 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
987 [ATOM_END] = { "end", SOURCE_NONE },
988 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
989 [ATOM_THEN] = { "then", SOURCE_NONE },
990 [ATOM_ELSE] = { "else", SOURCE_NONE },
991 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
992 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
993 [ATOM_ISBASE] = { "is-base", SOURCE_OTHER, FIELD_STR, is_base_atom_parser },
994 /*
995 * Please update $__git_ref_fieldlist in git-completion.bash
996 * when you add new atoms
997 */
998 };
999
1000 #define REF_FORMATTING_STATE_INIT { 0 }
1001
1002 struct ref_formatting_stack {
1003 struct ref_formatting_stack *prev;
1004 struct strbuf output;
1005 void (*at_end)(struct ref_formatting_stack **stack);
1006 void (*at_end_data_free)(void *data);
1007 void *at_end_data;
1008 };
1009
1010 struct ref_formatting_state {
1011 int quote_style;
1012 struct ref_formatting_stack *stack;
1013 };
1014
1015 struct atom_value {
1016 const char *s;
1017 ssize_t s_size;
1018 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
1019 struct strbuf *err);
1020 uintmax_t value; /* used for sorting when not FIELD_STR */
1021 struct used_atom *atom;
1022 };
1023
1024 #define ATOM_SIZE_UNSPECIFIED (-1)
1025
1026 #define ATOM_VALUE_INIT { \
1027 .s_size = ATOM_SIZE_UNSPECIFIED \
1028 }
1029
1030 /*
1031 * Used to parse format string and sort specifiers
1032 */
1033 static int parse_ref_filter_atom(struct ref_format *format,
1034 const char *atom, const char *ep,
1035 struct strbuf *err)
1036 {
1037 const char *sp;
1038 const char *arg;
1039 int i, at, atom_len;
1040
1041 sp = atom;
1042 if (*sp == '*' && sp < ep)
1043 sp++; /* deref */
1044 if (ep <= sp)
1045 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
1046 (int)(ep-atom), atom);
1047
1048 /*
1049 * If the atom name has a colon, strip it and everything after
1050 * it off - it specifies the format for this entry, and
1051 * shouldn't be used for checking against the valid_atom
1052 * table.
1053 */
1054 arg = memchr(sp, ':', ep - sp);
1055 atom_len = (arg ? arg : ep) - sp;
1056
1057 /* Do we have the atom already used elsewhere? */
1058 for (i = 0; i < used_atom_cnt; i++) {
1059 int len = strlen(used_atom[i].name);
1060 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
1061 return i;
1062 }
1063
1064 /* Is the atom a valid one? */
1065 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
1066 int len = strlen(valid_atom[i].name);
1067 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
1068 break;
1069 }
1070
1071 if (ARRAY_SIZE(valid_atom) <= i)
1072 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
1073 (int)(ep-atom), atom);
1074 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
1075 return strbuf_addf_ret(err, -1,
1076 _("not a git repository, but the field '%.*s' requires access to object data"),
1077 (int)(ep-atom), atom);
1078
1079 /* Add it in, including the deref prefix */
1080 at = used_atom_cnt;
1081 used_atom_cnt++;
1082 REALLOC_ARRAY(used_atom, used_atom_cnt);
1083 used_atom[at].atom_type = i;
1084 used_atom[at].name = xmemdupz(atom, ep - atom);
1085 used_atom[at].type = valid_atom[i].cmp_type;
1086 used_atom[at].source = valid_atom[i].source;
1087 if (used_atom[at].source == SOURCE_OBJ) {
1088 if (*atom == '*')
1089 oi_deref.info.contentp = &oi_deref.content;
1090 else
1091 oi.info.contentp = &oi.content;
1092 }
1093 if (arg) {
1094 arg = used_atom[at].name + (arg - atom) + 1;
1095 if (!*arg) {
1096 /*
1097 * Treat empty sub-arguments list as NULL (i.e.,
1098 * "%(atom:)" is equivalent to "%(atom)").
1099 */
1100 arg = NULL;
1101 }
1102 }
1103 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
1104 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
1105 return -1;
1106 if (*atom == '*')
1107 need_tagged = 1;
1108 if (i == ATOM_SYMREF)
1109 need_symref = 1;
1110 return at;
1111 }
1112
1113 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
1114 {
1115 switch (quote_style) {
1116 case QUOTE_NONE:
1117 if (len < 0)
1118 strbuf_addstr(s, str);
1119 else
1120 strbuf_add(s, str, len);
1121 break;
1122 case QUOTE_SHELL:
1123 sq_quote_buf(s, str);
1124 break;
1125 case QUOTE_PERL:
1126 if (len < 0)
1127 perl_quote_buf(s, str);
1128 else
1129 perl_quote_buf_with_len(s, str, len);
1130 break;
1131 case QUOTE_PYTHON:
1132 python_quote_buf(s, str);
1133 break;
1134 case QUOTE_TCL:
1135 tcl_quote_buf(s, str);
1136 break;
1137 }
1138 }
1139
1140 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
1141 struct strbuf *err UNUSED)
1142 {
1143 /*
1144 * Quote formatting is only done when the stack has a single
1145 * element. Otherwise quote formatting is done on the
1146 * element's entire output strbuf when the %(end) atom is
1147 * encountered.
1148 */
1149 if (!state->stack->prev)
1150 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
1151 else if (v->s_size < 0)
1152 strbuf_addstr(&state->stack->output, v->s);
1153 else
1154 strbuf_add(&state->stack->output, v->s, v->s_size);
1155 return 0;
1156 }
1157
1158 static void push_stack_element(struct ref_formatting_stack **stack)
1159 {
1160 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
1161
1162 strbuf_init(&s->output, 0);
1163 s->prev = *stack;
1164 *stack = s;
1165 }
1166
1167 static void pop_stack_element(struct ref_formatting_stack **stack)
1168 {
1169 struct ref_formatting_stack *current = *stack;
1170 struct ref_formatting_stack *prev = current->prev;
1171
1172 if (prev)
1173 strbuf_addbuf(&prev->output, &current->output);
1174 strbuf_release(&current->output);
1175 if (current->at_end_data_free)
1176 current->at_end_data_free(current->at_end_data);
1177 free(current);
1178 *stack = prev;
1179 }
1180
1181 static void end_align_handler(struct ref_formatting_stack **stack)
1182 {
1183 struct ref_formatting_stack *cur = *stack;
1184 struct align *align = (struct align *)cur->at_end_data;
1185 struct strbuf s = STRBUF_INIT;
1186
1187 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
1188 strbuf_swap(&cur->output, &s);
1189 strbuf_release(&s);
1190 }
1191
1192 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1193 struct strbuf *err UNUSED)
1194 {
1195 struct ref_formatting_stack *new_stack;
1196
1197 push_stack_element(&state->stack);
1198 new_stack = state->stack;
1199 new_stack->at_end = end_align_handler;
1200 new_stack->at_end_data = &atomv->atom->u.align;
1201 return 0;
1202 }
1203
1204 static void if_then_else_handler(struct ref_formatting_stack **stack)
1205 {
1206 struct ref_formatting_stack *cur = *stack;
1207 struct ref_formatting_stack *prev = cur->prev;
1208 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
1209
1210 if (!if_then_else->then_atom_seen)
1211 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
1212
1213 if (if_then_else->else_atom_seen) {
1214 /*
1215 * There is an %(else) atom: we need to drop one state from the
1216 * stack, either the %(else) branch if the condition is satisfied, or
1217 * the %(then) branch if it isn't.
1218 */
1219 if (if_then_else->condition_satisfied) {
1220 strbuf_reset(&cur->output);
1221 pop_stack_element(&cur);
1222 } else {
1223 strbuf_swap(&cur->output, &prev->output);
1224 strbuf_reset(&cur->output);
1225 pop_stack_element(&cur);
1226 }
1227 } else if (!if_then_else->condition_satisfied) {
1228 /*
1229 * No %(else) atom: just drop the %(then) branch if the
1230 * condition is not satisfied.
1231 */
1232 strbuf_reset(&cur->output);
1233 }
1234
1235 *stack = cur;
1236 }
1237
1238 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
1239 struct strbuf *err UNUSED)
1240 {
1241 struct ref_formatting_stack *new_stack;
1242 struct if_then_else *if_then_else = xcalloc(1, sizeof(*if_then_else));
1243
1244 if_then_else->str = atomv->atom->u.if_then_else.str;
1245 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
1246
1247 push_stack_element(&state->stack);
1248 new_stack = state->stack;
1249 new_stack->at_end = if_then_else_handler;
1250 new_stack->at_end_data = if_then_else;
1251 new_stack->at_end_data_free = free;
1252 return 0;
1253 }
1254
1255 static int is_empty(struct strbuf *buf)
1256 {
1257 const char *cur = buf->buf;
1258 const char *end = buf->buf + buf->len;
1259
1260 while (cur != end && (isspace(*cur)))
1261 cur++;
1262
1263 return cur == end;
1264 }
1265
1266 static int then_atom_handler(struct atom_value *atomv UNUSED,
1267 struct ref_formatting_state *state,
1268 struct strbuf *err)
1269 {
1270 struct ref_formatting_stack *cur = state->stack;
1271 struct if_then_else *if_then_else = NULL;
1272 size_t str_len = 0;
1273
1274 if (cur->at_end == if_then_else_handler)
1275 if_then_else = (struct if_then_else *)cur->at_end_data;
1276 if (!if_then_else)
1277 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
1278 if (if_then_else->then_atom_seen)
1279 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
1280 if (if_then_else->else_atom_seen)
1281 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
1282 if_then_else->then_atom_seen = 1;
1283 if (if_then_else->str)
1284 str_len = strlen(if_then_else->str);
1285 /*
1286 * If the 'equals' or 'notequals' attribute is used then
1287 * perform the required comparison. If not, only non-empty
1288 * strings satisfy the 'if' condition.
1289 */
1290 if (if_then_else->cmp_status == COMPARE_EQUAL) {
1291 if (str_len == cur->output.len &&
1292 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1293 if_then_else->condition_satisfied = 1;
1294 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
1295 if (str_len != cur->output.len ||
1296 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
1297 if_then_else->condition_satisfied = 1;
1298 } else if (cur->output.len && !is_empty(&cur->output))
1299 if_then_else->condition_satisfied = 1;
1300 strbuf_reset(&cur->output);
1301 return 0;
1302 }
1303
1304 static int else_atom_handler(struct atom_value *atomv UNUSED,
1305 struct ref_formatting_state *state,
1306 struct strbuf *err)
1307 {
1308 struct ref_formatting_stack *prev = state->stack;
1309 struct if_then_else *if_then_else = NULL;
1310
1311 if (prev->at_end == if_then_else_handler)
1312 if_then_else = (struct if_then_else *)prev->at_end_data;
1313 if (!if_then_else)
1314 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1315 if (!if_then_else->then_atom_seen)
1316 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1317 if (if_then_else->else_atom_seen)
1318 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1319 if_then_else->else_atom_seen = 1;
1320 push_stack_element(&state->stack);
1321 state->stack->at_end_data = prev->at_end_data;
1322 state->stack->at_end = prev->at_end;
1323 return 0;
1324 }
1325
1326 static int end_atom_handler(struct atom_value *atomv UNUSED,
1327 struct ref_formatting_state *state,
1328 struct strbuf *err)
1329 {
1330 struct ref_formatting_stack *current = state->stack;
1331 struct strbuf s = STRBUF_INIT;
1332
1333 if (!current->at_end)
1334 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1335 current->at_end(&state->stack);
1336
1337 /* Stack may have been popped within at_end(), hence reset the current pointer */
1338 current = state->stack;
1339
1340 /*
1341 * Perform quote formatting when the stack element is that of
1342 * a supporting atom. If nested then perform quote formatting
1343 * only on the topmost supporting atom.
1344 */
1345 if (!current->prev->prev) {
1346 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1347 strbuf_swap(&current->output, &s);
1348 }
1349 strbuf_release(&s);
1350 pop_stack_element(&state->stack);
1351 return 0;
1352 }
1353
1354 /*
1355 * In a format string, find the next occurrence of %(atom).
1356 */
1357 static const char *find_next(const char *cp)
1358 {
1359 while (*cp) {
1360 if (*cp == '%') {
1361 /*
1362 * %( is the start of an atom;
1363 * %% is a quoted per-cent.
1364 */
1365 if (cp[1] == '(')
1366 return cp;
1367 else if (cp[1] == '%')
1368 cp++; /* skip over two % */
1369 /* otherwise this is a singleton, literal % */
1370 }
1371 cp++;
1372 }
1373 return NULL;
1374 }
1375
1376 static int reject_atom(enum atom_type atom_type)
1377 {
1378 return atom_type == ATOM_REST;
1379 }
1380
1381 /*
1382 * Make sure the format string is well formed, and parse out
1383 * the used atoms.
1384 */
1385 int verify_ref_format(struct ref_format *format)
1386 {
1387 const char *cp, *sp;
1388
1389 format->need_color_reset_at_eol = 0;
1390 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1391 struct strbuf err = STRBUF_INIT;
1392 const char *color, *ep = strchr(sp, ')');
1393 int at;
1394
1395 if (!ep)
1396 return error(_("malformed format string %s"), sp);
1397 /* sp points at "%(" and ep points at the closing ")" */
1398 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1399 if (at < 0)
1400 die("%s", err.buf);
1401 if (reject_atom(used_atom[at].atom_type))
1402 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1403
1404 if ((format->quote_style == QUOTE_PYTHON ||
1405 format->quote_style == QUOTE_SHELL ||
1406 format->quote_style == QUOTE_TCL) &&
1407 used_atom[at].atom_type == ATOM_RAW &&
1408 used_atom[at].u.raw_data.option == RAW_BARE)
1409 die(_("--format=%.*s cannot be used with "
1410 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1411 cp = ep + 1;
1412
1413 if (skip_prefix(used_atom[at].name, "color:", &color))
1414 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1415 strbuf_release(&err);
1416 }
1417 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1418 format->need_color_reset_at_eol = 0;
1419 return 0;
1420 }
1421
1422 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1423 struct used_atom *atom)
1424 {
1425 switch (atom->u.oid.option) {
1426 case O_FULL:
1427 return oid_to_hex(oid);
1428 case O_LENGTH:
1429 return repo_find_unique_abbrev(the_repository, oid,
1430 atom->u.oid.length);
1431 case O_SHORT:
1432 return repo_find_unique_abbrev(the_repository, oid,
1433 DEFAULT_ABBREV);
1434 default:
1435 BUG("unknown %%(%s) option", field);
1436 }
1437 }
1438
1439 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1440 struct atom_value *v, struct used_atom *atom)
1441 {
1442 if (starts_with(name, field)) {
1443 v->s = xstrdup(do_grab_oid(field, oid, atom));
1444 return 1;
1445 }
1446 return 0;
1447 }
1448
1449 /* See grab_values */
1450 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1451 {
1452 int i;
1453
1454 for (i = 0; i < used_atom_cnt; i++) {
1455 const char *name = used_atom[i].name;
1456 enum atom_type atom_type = used_atom[i].atom_type;
1457 struct atom_value *v = &val[i];
1458 if (!!deref != (*name == '*'))
1459 continue;
1460 if (deref)
1461 name++;
1462 if (atom_type == ATOM_OBJECTTYPE)
1463 v->s = xstrdup(type_name(oi->type));
1464 else if (atom_type == ATOM_OBJECTSIZE) {
1465 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1466 v->value = oi->disk_size;
1467 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1468 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1469 v->value = oi->size;
1470 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1471 }
1472 } else if (atom_type == ATOM_DELTABASE)
1473 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1474 else if (atom_type == ATOM_OBJECTNAME && deref)
1475 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1476 }
1477 }
1478
1479 static struct object *get_or_parse_object(struct expand_data *data, const char *refname,
1480 struct strbuf *err, int *eaten)
1481 {
1482 if (!data->maybe_object) {
1483 data->maybe_object = parse_object_buffer(the_repository, &data->oid, data->type,
1484 data->size, data->content, eaten);
1485 if (!data->maybe_object) {
1486 strbuf_addf(err, _("parse_object_buffer failed on %s for %s"),
1487 oid_to_hex(&data->oid), refname);
1488 return NULL;
1489 }
1490 }
1491
1492 return data->maybe_object;
1493 }
1494
1495 /* See grab_values */
1496 static int grab_tag_values(struct atom_value *val, int deref,
1497 struct expand_data *data, const char *refname,
1498 struct strbuf *err, int *eaten)
1499 {
1500 struct tag *tag = NULL;
1501 int i;
1502
1503 for (i = 0; i < used_atom_cnt; i++) {
1504 const char *name = used_atom[i].name;
1505 enum atom_type atom_type = used_atom[i].atom_type;
1506 struct atom_value *v = &val[i];
1507 if (!!deref != (*name == '*'))
1508 continue;
1509
1510 if (!tag) {
1511 tag = (struct tag *) get_or_parse_object(data, refname,
1512 err, eaten);
1513 if (!tag)
1514 return -1;
1515 }
1516
1517 if (deref)
1518 name++;
1519 if (atom_type == ATOM_TAG)
1520 v->s = xstrdup(tag->tag);
1521 else if (atom_type == ATOM_TYPE && tag->tagged)
1522 v->s = xstrdup(type_name(tag->tagged->type));
1523 else if (atom_type == ATOM_OBJECT && tag->tagged)
1524 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1525 }
1526
1527 return 0;
1528 }
1529
1530 /* See grab_values */
1531 static int grab_commit_values(struct atom_value *val, int deref,
1532 struct expand_data *data, const char *refname,
1533 struct strbuf *err, int *eaten)
1534 {
1535 int i;
1536 struct commit *commit = NULL;
1537
1538 for (i = 0; i < used_atom_cnt; i++) {
1539 const char *name = used_atom[i].name;
1540 enum atom_type atom_type = used_atom[i].atom_type;
1541 struct atom_value *v = &val[i];
1542
1543 if (!!deref != (*name == '*'))
1544 continue;
1545 if (deref)
1546 name++;
1547
1548 if (!commit) {
1549 commit = (struct commit *) get_or_parse_object(data, refname,
1550 err, eaten);
1551 if (!commit)
1552 return -1;
1553 }
1554
1555 if (atom_type == ATOM_TREE &&
1556 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1557 continue;
1558 if (atom_type == ATOM_NUMPARENT) {
1559 v->value = commit_list_count(commit->parents);
1560 v->s = xstrfmt("%lu", (unsigned long)v->value);
1561 }
1562 else if (atom_type == ATOM_PARENT) {
1563 struct commit_list *parents;
1564 struct strbuf s = STRBUF_INIT;
1565 for (parents = commit->parents; parents; parents = parents->next) {
1566 struct object_id *oid = &parents->item->object.oid;
1567 if (parents != commit->parents)
1568 strbuf_addch(&s, ' ');
1569 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1570 }
1571 v->s = strbuf_detach(&s, NULL);
1572 }
1573 }
1574
1575 return 0;
1576 }
1577
1578 static const char *find_wholine(const char *who, int wholen, const char *buf)
1579 {
1580 const char *eol;
1581 while (*buf) {
1582 if (!strncmp(buf, who, wholen) &&
1583 buf[wholen] == ' ')
1584 return buf + wholen + 1;
1585 eol = strchr(buf, '\n');
1586 if (!eol)
1587 return "";
1588 eol++;
1589 if (*eol == '\n')
1590 return ""; /* end of header */
1591 buf = eol;
1592 }
1593 return "";
1594 }
1595
1596 static const char *copy_line(const char *buf)
1597 {
1598 const char *eol = strchrnul(buf, '\n');
1599 return xmemdupz(buf, eol - buf);
1600 }
1601
1602 static const char *copy_name(const char *buf)
1603 {
1604 const char *cp;
1605 for (cp = buf; *cp && *cp != '\n'; cp++) {
1606 if (starts_with(cp, " <"))
1607 return xmemdupz(buf, cp - buf);
1608 }
1609 return xstrdup("");
1610 }
1611
1612 static const char *find_end_of_email(const char *email, int opt)
1613 {
1614 const char *eoemail;
1615
1616 if (opt & EO_LOCALPART) {
1617 eoemail = strchr(email, '@');
1618 if (eoemail)
1619 return eoemail;
1620 return strchr(email, '>');
1621 }
1622
1623 if (opt & EO_TRIM)
1624 return strchr(email, '>');
1625
1626 /*
1627 * The option here is either the raw email option or the raw
1628 * mailmap option (that is EO_RAW or EO_MAILMAP). In such cases,
1629 * we directly grab the whole email including the closing
1630 * angle brackets.
1631 *
1632 * If EO_MAILMAP was set with any other option (that is either
1633 * EO_TRIM or EO_LOCALPART), we already grab the end of email
1634 * above.
1635 */
1636 eoemail = strchr(email, '>');
1637 if (eoemail)
1638 eoemail++;
1639 return eoemail;
1640 }
1641
1642 static const char *copy_email(const char *buf, struct used_atom *atom)
1643 {
1644 const char *email = strchr(buf, '<');
1645 const char *eoemail;
1646 int opt = atom->u.email_option.option;
1647
1648 if (!email)
1649 return xstrdup("");
1650
1651 if (opt & (EO_LOCALPART | EO_TRIM))
1652 email++;
1653
1654 eoemail = find_end_of_email(email, opt);
1655 if (!eoemail)
1656 return xstrdup("");
1657 return xmemdupz(email, eoemail - email);
1658 }
1659
1660 static char *copy_subject(const char *buf, unsigned long len)
1661 {
1662 struct strbuf sb = STRBUF_INIT;
1663 int i;
1664
1665 for (i = 0; i < len; i++) {
1666 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1667 continue; /* ignore CR in CRLF */
1668
1669 if (buf[i] == '\n')
1670 strbuf_addch(&sb, ' ');
1671 else
1672 strbuf_addch(&sb, buf[i]);
1673 }
1674 return strbuf_detach(&sb, NULL);
1675 }
1676
1677 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1678 {
1679 const char *eoemail = strstr(buf, "> ");
1680 char *zone;
1681 timestamp_t timestamp;
1682 long tz;
1683 struct date_mode date_mode = DATE_MODE_INIT;
1684 const char *formatp;
1685
1686 /*
1687 * We got here because atomname ends in "date" or "date<something>";
1688 * it's not possible that <something> is not ":<format>" because
1689 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1690 * ":" means no format is specified, and use the default.
1691 */
1692 formatp = strchr(atomname, ':');
1693 if (formatp) {
1694 formatp++;
1695 parse_date_format(formatp, &date_mode);
1696
1697 /*
1698 * If this is a sort field and a format was specified, we'll
1699 * want to compare formatted date by string value.
1700 */
1701 v->atom->type = FIELD_STR;
1702 }
1703
1704 if (!eoemail)
1705 goto bad;
1706 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1707 if (timestamp == TIME_MAX)
1708 goto bad;
1709 errno = 0;
1710 tz = strtol(zone, NULL, 10);
1711 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1712 goto bad;
1713 v->s = xstrdup(show_date(timestamp, tz, date_mode));
1714 v->value = timestamp;
1715 date_mode_release(&date_mode);
1716 return;
1717 bad:
1718 v->s = xstrdup("");
1719 v->value = 0;
1720 }
1721
1722 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
1723
1724 /* See grab_values */
1725 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1726 {
1727 int i;
1728 int wholen = strlen(who);
1729 const char *wholine = NULL;
1730 const char *headers[] = { "author ", "committer ",
1731 "tagger ", NULL };
1732
1733 for (i = 0; i < used_atom_cnt; i++) {
1734 struct used_atom *atom = &used_atom[i];
1735 const char *name = atom->name;
1736 struct atom_value *v = &val[i];
1737 struct strbuf mailmap_buf = STRBUF_INIT;
1738
1739 if (!!deref != (*name == '*'))
1740 continue;
1741 if (deref)
1742 name++;
1743 if (strncmp(who, name, wholen))
1744 continue;
1745 if (name[wholen] != 0 &&
1746 !starts_with(name + wholen, "name") &&
1747 !starts_with(name + wholen, "email") &&
1748 !starts_with(name + wholen, "date"))
1749 continue;
1750
1751 if ((starts_with(name + wholen, "name") &&
1752 (atom->u.name_option.option == N_MAILMAP)) ||
1753 (starts_with(name + wholen, "email") &&
1754 (atom->u.email_option.option & EO_MAILMAP))) {
1755 if (!mailmap.items)
1756 read_mailmap(the_repository, &mailmap);
1757 strbuf_addstr(&mailmap_buf, buf);
1758 apply_mailmap_to_header(&mailmap_buf, headers, &mailmap);
1759 wholine = find_wholine(who, wholen, mailmap_buf.buf);
1760 } else {
1761 wholine = find_wholine(who, wholen, buf);
1762 }
1763
1764 if (!wholine)
1765 return; /* no point looking for it */
1766 if (name[wholen] == 0)
1767 v->s = copy_line(wholine);
1768 else if (starts_with(name + wholen, "name"))
1769 v->s = copy_name(wholine);
1770 else if (starts_with(name + wholen, "email"))
1771 v->s = copy_email(wholine, &used_atom[i]);
1772 else if (starts_with(name + wholen, "date"))
1773 grab_date(wholine, v, name);
1774
1775 strbuf_release(&mailmap_buf);
1776 }
1777
1778 /*
1779 * For a tag or a commit object, if "creator" or "creatordate" is
1780 * requested, do something special.
1781 */
1782 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1783 return; /* "author" for commit object is not wanted */
1784 if (!wholine)
1785 wholine = find_wholine(who, wholen, buf);
1786 if (!wholine)
1787 return;
1788 for (i = 0; i < used_atom_cnt; i++) {
1789 const char *name = used_atom[i].name;
1790 enum atom_type atom_type = used_atom[i].atom_type;
1791 struct atom_value *v = &val[i];
1792 if (!!deref != (*name == '*'))
1793 continue;
1794 if (deref)
1795 name++;
1796
1797 if (atom_type == ATOM_CREATORDATE)
1798 grab_date(wholine, v, name);
1799 else if (atom_type == ATOM_CREATOR)
1800 v->s = copy_line(wholine);
1801 }
1802 }
1803
1804 static int grab_signature(struct atom_value *val, int deref,
1805 struct expand_data *data, const char *refname,
1806 struct strbuf *err, int *eaten)
1807 {
1808 int i;
1809 struct commit *commit = NULL;
1810 struct signature_check sigc = { 0 };
1811 int signature_checked = 0;
1812
1813 for (i = 0; i < used_atom_cnt; i++) {
1814 struct used_atom *atom = &used_atom[i];
1815 const char *name = atom->name;
1816 struct atom_value *v = &val[i];
1817 int opt;
1818
1819 if (!!deref != (*name == '*'))
1820 continue;
1821 if (deref)
1822 name++;
1823
1824 if (!skip_prefix(name, "signature", &name) ||
1825 (*name && *name != ':'))
1826 continue;
1827 if (!*name)
1828 name = NULL;
1829 else
1830 name++;
1831
1832 opt = parse_signature_option(name);
1833 if (opt < 0)
1834 continue;
1835
1836 if (!signature_checked) {
1837 if (!commit) {
1838 commit = (struct commit *) get_or_parse_object(data, refname,
1839 err, eaten);
1840 if (!commit)
1841 return -1;
1842 }
1843
1844 check_commit_signature(commit, &sigc);
1845 signature_checked = 1;
1846 }
1847
1848 switch (opt) {
1849 case S_BARE:
1850 v->s = xstrdup(sigc.output ? sigc.output: "");
1851 break;
1852 case S_SIGNER:
1853 v->s = xstrdup(sigc.signer ? sigc.signer : "");
1854 break;
1855 case S_GRADE:
1856 switch (sigc.result) {
1857 case 'G':
1858 switch (sigc.trust_level) {
1859 case TRUST_UNDEFINED:
1860 case TRUST_NEVER:
1861 v->s = xstrfmt("%c", (char)'U');
1862 break;
1863 default:
1864 v->s = xstrfmt("%c", (char)'G');
1865 break;
1866 }
1867 break;
1868 case 'B':
1869 case 'E':
1870 case 'N':
1871 case 'X':
1872 case 'Y':
1873 case 'R':
1874 v->s = xstrfmt("%c", (char)sigc.result);
1875 break;
1876 }
1877 break;
1878 case S_KEY:
1879 v->s = xstrdup(sigc.key ? sigc.key : "");
1880 break;
1881 case S_FINGERPRINT:
1882 v->s = xstrdup(sigc.fingerprint ?
1883 sigc.fingerprint : "");
1884 break;
1885 case S_PRI_KEY_FP:
1886 v->s = xstrdup(sigc.primary_key_fingerprint ?
1887 sigc.primary_key_fingerprint : "");
1888 break;
1889 case S_TRUST_LEVEL:
1890 v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));
1891 break;
1892 }
1893 }
1894
1895 if (signature_checked)
1896 signature_check_clear(&sigc);
1897
1898 return 0;
1899 }
1900
1901 static void find_subpos(const char *buf,
1902 const char **sub, size_t *sublen,
1903 const char **body, size_t *bodylen,
1904 size_t *nonsiglen,
1905 const char **sig, size_t *siglen)
1906 {
1907 const char *eol;
1908 const char *end = buf + strlen(buf);
1909 const char *sigstart;
1910
1911 /* skip past header until we hit empty line */
1912 while (*buf && *buf != '\n') {
1913 eol = strchrnul(buf, '\n');
1914 if (*eol)
1915 eol++;
1916 buf = eol;
1917 }
1918 /* skip any empty lines */
1919 while (*buf == '\n')
1920 buf++;
1921 /* parse signature first; we might not even have a subject line */
1922 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1923 *sig = sigstart;
1924 *siglen = end - *sig;
1925
1926 /* subject is first non-empty line */
1927 *sub = buf;
1928 /* subject goes to first empty line before signature begins */
1929 if ((eol = strstr(*sub, "\n\n")) ||
1930 (eol = strstr(*sub, "\r\n\r\n"))) {
1931 eol = eol < sigstart ? eol : sigstart;
1932 } else {
1933 /* treat whole message as subject */
1934 eol = sigstart;
1935 }
1936 buf = eol;
1937 *sublen = buf - *sub;
1938 /* drop trailing newline, if present */
1939 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1940 (*sub)[*sublen - 1] == '\r'))
1941 *sublen -= 1;
1942
1943 /* skip any empty lines */
1944 while (*buf == '\n' || *buf == '\r')
1945 buf++;
1946 *body = buf;
1947 *bodylen = strlen(buf);
1948 *nonsiglen = sigstart - buf;
1949 }
1950
1951 /*
1952 * If 'lines' is greater than 0, append that many lines from the given
1953 * 'buf' of length 'size' to the given strbuf.
1954 */
1955 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1956 {
1957 int i;
1958 const char *sp, *eol;
1959 size_t len;
1960
1961 sp = buf;
1962
1963 for (i = 0; i < lines && sp < buf + size; i++) {
1964 if (i)
1965 strbuf_addstr(out, "\n ");
1966 eol = memchr(sp, '\n', size - (sp - buf));
1967 len = eol ? eol - sp : size - (sp - buf);
1968 strbuf_add(out, sp, len);
1969 if (!eol)
1970 break;
1971 sp = eol + 1;
1972 }
1973 }
1974
1975 static void grab_describe_values(struct atom_value *val, int deref,
1976 struct expand_data *data)
1977 {
1978 int i;
1979
1980 for (i = 0; i < used_atom_cnt; i++) {
1981 struct used_atom *atom = &used_atom[i];
1982 enum atom_type type = atom->atom_type;
1983 const char *name = atom->name;
1984 struct atom_value *v = &val[i];
1985
1986 struct child_process cmd = CHILD_PROCESS_INIT;
1987 struct strbuf out = STRBUF_INIT;
1988 struct strbuf err = STRBUF_INIT;
1989
1990 if (type != ATOM_DESCRIBE)
1991 continue;
1992
1993 if (!!deref != (*name == '*'))
1994 continue;
1995
1996 cmd.git_cmd = 1;
1997 strvec_push(&cmd.args, "describe");
1998 strvec_pushv(&cmd.args, atom->u.describe_args.v);
1999 strvec_push(&cmd.args, oid_to_hex(&data->oid));
2000 if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {
2001 error(_("failed to run 'describe'"));
2002 v->s = xstrdup("");
2003 continue;
2004 }
2005 strbuf_rtrim(&out);
2006 v->s = strbuf_detach(&out, NULL);
2007
2008 strbuf_release(&err);
2009 }
2010 }
2011
2012 /* See grab_values */
2013 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
2014 {
2015 int i;
2016 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
2017 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
2018 void *buf = data->content;
2019
2020 for (i = 0; i < used_atom_cnt; i++) {
2021 struct used_atom *atom = &used_atom[i];
2022 const char *name = atom->name;
2023 struct atom_value *v = &val[i];
2024 enum atom_type atom_type = atom->atom_type;
2025
2026 if (!!deref != (*name == '*'))
2027 continue;
2028 if (deref)
2029 name++;
2030
2031 if (atom_type == ATOM_RAW) {
2032 unsigned long buf_size = data->size;
2033
2034 if (atom->u.raw_data.option == RAW_BARE) {
2035 v->s = xmemdupz(buf, buf_size);
2036 v->s_size = buf_size;
2037 } else if (atom->u.raw_data.option == RAW_LENGTH) {
2038 v->value = buf_size;
2039 v->s = xstrfmt("%"PRIuMAX, v->value);
2040 }
2041 continue;
2042 }
2043
2044 if ((data->type != OBJ_TAG &&
2045 data->type != OBJ_COMMIT) ||
2046 (strcmp(name, "body") &&
2047 !starts_with(name, "subject") &&
2048 !starts_with(name, "trailers") &&
2049 !starts_with(name, "contents")))
2050 continue;
2051 if (!subpos)
2052 find_subpos(buf,
2053 &subpos, &sublen,
2054 &bodypos, &bodylen, &nonsiglen,
2055 &sigpos, &siglen);
2056
2057 if (atom->u.contents.option == C_SUB)
2058 v->s = copy_subject(subpos, sublen);
2059 else if (atom->u.contents.option == C_SUB_SANITIZE) {
2060 struct strbuf sb = STRBUF_INIT;
2061 format_sanitized_subject(&sb, subpos, sublen);
2062 v->s = strbuf_detach(&sb, NULL);
2063 } else if (atom->u.contents.option == C_BODY_DEP)
2064 v->s = xmemdupz(bodypos, bodylen);
2065 else if (atom->u.contents.option == C_LENGTH) {
2066 v->value = strlen(subpos);
2067 v->s = xstrfmt("%"PRIuMAX, v->value);
2068 } else if (atom->u.contents.option == C_BODY)
2069 v->s = xmemdupz(bodypos, nonsiglen);
2070 else if (atom->u.contents.option == C_SIG)
2071 v->s = xmemdupz(sigpos, siglen);
2072 else if (atom->u.contents.option == C_LINES) {
2073 struct strbuf s = STRBUF_INIT;
2074 const char *contents_end = bodypos + nonsiglen;
2075
2076 /* Size is the length of the message after removing the signature */
2077 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
2078 v->s = strbuf_detach(&s, NULL);
2079 } else if (atom->u.contents.option == C_TRAILERS) {
2080 struct strbuf s = STRBUF_INIT;
2081 const char *msg;
2082 char *to_free = NULL;
2083
2084 if (siglen)
2085 msg = to_free = xmemdupz(subpos, sigpos - subpos);
2086 else
2087 msg = subpos;
2088
2089 /* Format the trailer info according to the trailer_opts given */
2090 format_trailers_from_commit(&atom->u.contents.trailer_opts, msg, &s);
2091 free(to_free);
2092
2093 v->s = strbuf_detach(&s, NULL);
2094 } else if (atom->u.contents.option == C_BARE)
2095 v->s = xstrdup(subpos);
2096
2097 }
2098 }
2099
2100 /*
2101 * We want to have empty print-string for field requests
2102 * that do not apply (e.g. "authordate" for a tag object)
2103 */
2104 static void fill_missing_values(struct atom_value *val)
2105 {
2106 int i;
2107 for (i = 0; i < used_atom_cnt; i++) {
2108 struct atom_value *v = &val[i];
2109 if (!v->s)
2110 v->s = xstrdup("");
2111 }
2112 }
2113
2114 /*
2115 * val is a list of atom_value to hold returned values. Extract
2116 * the values for atoms in used_atom array out of (obj, buf, sz).
2117 * when deref is false, (obj, buf, sz) is the object that is
2118 * pointed at by the ref itself; otherwise it is the object the
2119 * ref (which is a tag) refers to.
2120 */
2121 static int grab_values(struct atom_value *val, int deref, struct expand_data *data,
2122 const char *refname, struct strbuf *err, int *eaten)
2123 {
2124 void *buf = data->content;
2125 int ret;
2126
2127 switch (data->type) {
2128 case OBJ_TAG:
2129 ret = grab_tag_values(val, deref, data, refname, err, eaten);
2130 if (ret < 0)
2131 goto out;
2132
2133 grab_sub_body_contents(val, deref, data);
2134 grab_person("tagger", val, deref, buf);
2135 grab_describe_values(val, deref, data);
2136 break;
2137 case OBJ_COMMIT:
2138 ret = grab_commit_values(val, deref, data, refname, err, eaten);
2139 if (ret < 0)
2140 goto out;
2141
2142 grab_sub_body_contents(val, deref, data);
2143 grab_person("author", val, deref, buf);
2144 grab_person("committer", val, deref, buf);
2145
2146 ret = grab_signature(val, deref, data, refname, err, eaten);
2147 if (ret < 0)
2148 goto out;
2149
2150 grab_describe_values(val, deref, data);
2151 break;
2152 case OBJ_TREE:
2153 /* grab_tree_values(val, deref, obj, buf, sz); */
2154 grab_sub_body_contents(val, deref, data);
2155 break;
2156 case OBJ_BLOB:
2157 /* grab_blob_values(val, deref, obj, buf, sz); */
2158 grab_sub_body_contents(val, deref, data);
2159 break;
2160 default:
2161 die("Eh? Object of type %d?", data->type);
2162 }
2163
2164 ret = 0;
2165 out:
2166 return ret;
2167 }
2168
2169 static inline char *copy_advance(char *dst, const char *src)
2170 {
2171 while (*src)
2172 *dst++ = *src++;
2173 return dst;
2174 }
2175
2176 static int normalize_component_count(const char *refname, int len)
2177 {
2178 if (len < 0) {
2179 int slashes = 0;
2180
2181 for (const char *p = refname; *p; p++) {
2182 if (*p == '/')
2183 slashes++;
2184 }
2185
2186 /*
2187 * The number of components we need to strip is now
2188 * the total minus the components to be left (Plus one
2189 * because we count the number of '/', but the number
2190 * of components is one more than the no of '/').
2191 */
2192 len = slashes + len + 1;
2193 }
2194 return len;
2195 }
2196
2197 static const char *lstrip_ref_components(const char *refname, int len)
2198 {
2199 int remaining = normalize_component_count(refname, len);
2200
2201 while (remaining > 0) {
2202 switch (*refname++) {
2203 case '\0':
2204 return xstrdup("");
2205 case '/':
2206 remaining--;
2207 break;
2208 }
2209 }
2210
2211 return xstrdup(refname);
2212 }
2213
2214 static const char *rstrip_ref_components(const char *refname, int len)
2215 {
2216 int remaining = normalize_component_count(refname, len);
2217 const char *end = refname + strlen(refname);
2218
2219 while (remaining > 0) {
2220 if (end == refname)
2221 return xstrdup("");
2222 if (*--end == '/')
2223 remaining--;
2224 }
2225 return xmemdupz(refname, end - refname);
2226 }
2227
2228 static const char *show_ref(struct refname_atom *atom, const char *refname)
2229 {
2230 if (atom->option == R_SHORT)
2231 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
2232 refname,
2233 repo_settings_get_warn_ambiguous_refs(the_repository));
2234 else if (atom->option == R_LSTRIP)
2235 return lstrip_ref_components(refname, atom->lstrip);
2236 else if (atom->option == R_RSTRIP)
2237 return rstrip_ref_components(refname, atom->rstrip);
2238 else
2239 return xstrdup(refname);
2240 }
2241
2242 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
2243 struct branch *branch, const char **s)
2244 {
2245 int num_ours, num_theirs;
2246 if (atom->u.remote_ref.option == RR_REF)
2247 *s = show_ref(&atom->u.remote_ref.refname, refname);
2248 else if (atom->u.remote_ref.option == RR_TRACK) {
2249 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2250 NULL, atom->u.remote_ref.push,
2251 AHEAD_BEHIND_FULL) < 0) {
2252 *s = xstrdup(msgs.gone);
2253 } else if (!num_ours && !num_theirs)
2254 *s = xstrdup("");
2255 else if (!num_ours)
2256 *s = xstrfmt(msgs.behind, num_theirs);
2257 else if (!num_theirs)
2258 *s = xstrfmt(msgs.ahead, num_ours);
2259 else
2260 *s = xstrfmt(msgs.ahead_behind,
2261 num_ours, num_theirs);
2262 if (!atom->u.remote_ref.nobracket && *s[0]) {
2263 const char *to_free = *s;
2264 *s = xstrfmt("[%s]", *s);
2265 free((void *)to_free);
2266 }
2267 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
2268 if (stat_tracking_info(branch, &num_ours, &num_theirs,
2269 NULL, atom->u.remote_ref.push,
2270 AHEAD_BEHIND_FULL) < 0) {
2271 *s = xstrdup("");
2272 return;
2273 }
2274 if (!num_ours && !num_theirs)
2275 *s = xstrdup("=");
2276 else if (!num_ours)
2277 *s = xstrdup("<");
2278 else if (!num_theirs)
2279 *s = xstrdup(">");
2280 else
2281 *s = xstrdup("<>");
2282 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
2283 int explicit;
2284 const char *remote = atom->u.remote_ref.push ?
2285 pushremote_for_branch(branch, &explicit) :
2286 remote_for_branch(branch, &explicit);
2287 *s = xstrdup(explicit ? remote : "");
2288 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
2289 const char *merge;
2290
2291 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
2292 *s = merge ? merge : xstrdup("");
2293 } else
2294 BUG("unhandled RR_* enum");
2295 }
2296
2297 char *get_head_description(void)
2298 {
2299 struct strbuf desc = STRBUF_INIT;
2300 struct wt_status_state state;
2301 memset(&state, 0, sizeof(state));
2302 wt_status_get_state(the_repository, &state, 1);
2303 if (state.rebase_in_progress ||
2304 state.rebase_interactive_in_progress) {
2305 if (state.branch)
2306 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
2307 state.branch);
2308 else
2309 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
2310 state.detached_from);
2311 } else if (state.bisect_in_progress)
2312 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
2313 state.bisecting_from);
2314 else if (state.detached_from) {
2315 if (state.detached_at)
2316 strbuf_addf(&desc, _("(HEAD detached at %s)"),
2317 state.detached_from);
2318 else
2319 strbuf_addf(&desc, _("(HEAD detached from %s)"),
2320 state.detached_from);
2321 } else
2322 strbuf_addstr(&desc, _("(no branch)"));
2323
2324 wt_status_state_free_buffers(&state);
2325
2326 return strbuf_detach(&desc, NULL);
2327 }
2328
2329 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
2330 {
2331 if (!ref->symref)
2332 return xstrdup("");
2333 else
2334 return show_ref(&atom->u.refname, ref->symref);
2335 }
2336
2337 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
2338 {
2339 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
2340 return get_head_description();
2341 return show_ref(&atom->u.refname, ref->refname);
2342 }
2343
2344 static int get_object(struct ref_array_item *ref, int deref,
2345 struct expand_data *oi, struct strbuf *err)
2346 {
2347 /* parse_object_buffer() will set eaten to 1 if free() will be needed */
2348 int eaten = 0;
2349 int ret;
2350
2351 oi->maybe_object = NULL;
2352
2353 if (oi->info.contentp) {
2354 /* We need to know that to use parse_object_buffer properly */
2355 oi->info.sizep = &oi->size;
2356 oi->info.typep = &oi->type;
2357 }
2358
2359 if (odb_read_object_info_extended(the_repository->objects, &oi->oid, &oi->info,
2360 OBJECT_INFO_LOOKUP_REPLACE)) {
2361 ret = strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2362 oid_to_hex(&oi->oid), ref->refname);
2363 goto out;
2364 }
2365 if (oi->info.disk_sizep && oi->disk_size < 0)
2366 BUG("Object size is less than zero.");
2367
2368 if (oi->info.contentp) {
2369 ret = grab_values(ref->value, deref, oi, ref->refname, err, &eaten);
2370 if (ret < 0)
2371 goto out;
2372 }
2373
2374 grab_common_values(ref->value, deref, oi);
2375 ret = 0;
2376
2377 out:
2378 if (!eaten)
2379 free(oi->content);
2380 return ret;
2381 }
2382
2383 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
2384 {
2385 int i;
2386
2387 for (i = 0; worktrees[i]; i++) {
2388 if (worktrees[i]->head_ref) {
2389 struct ref_to_worktree_entry *entry;
2390 entry = xmalloc(sizeof(*entry));
2391 entry->wt = worktrees[i];
2392 hashmap_entry_init(&entry->ent,
2393 strhash(worktrees[i]->head_ref));
2394
2395 hashmap_add(map, &entry->ent);
2396 }
2397 }
2398 }
2399
2400 static void lazy_init_worktree_map(void)
2401 {
2402 if (ref_to_worktree_map.worktrees)
2403 return;
2404
2405 ref_to_worktree_map.worktrees = get_worktrees(the_repository);
2406 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
2407 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
2408 }
2409
2410 static char *get_worktree_path(const struct ref_array_item *ref)
2411 {
2412 struct hashmap_entry entry, *e;
2413 struct ref_to_worktree_entry *lookup_result;
2414
2415 lazy_init_worktree_map();
2416
2417 hashmap_entry_init(&entry, strhash(ref->refname));
2418 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
2419
2420 if (!e)
2421 return xstrdup("");
2422
2423 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
2424
2425 return xstrdup(lookup_result->wt->path);
2426 }
2427
2428 /*
2429 * Parse the object referred by ref, and grab needed value.
2430 */
2431 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
2432 {
2433 int i;
2434 struct object_info empty = OBJECT_INFO_INIT;
2435 int ahead_behind_atoms = 0;
2436 int is_base_atoms = 0;
2437
2438 CALLOC_ARRAY(ref->value, used_atom_cnt);
2439
2440 /**
2441 * NEEDSWORK: The following code might be unnecessary if all codepaths
2442 * that call populate_value() populates the symref member of ref_array_item
2443 * like in apply_ref_filter(). Currently pretty_print_ref() is the only codepath
2444 * that calls populate_value() without first populating symref.
2445 */
2446 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
2447 ref->symref = refs_resolve_refdup(get_main_ref_store(the_repository),
2448 ref->refname,
2449 RESOLVE_REF_READING,
2450 NULL, NULL);
2451 if (!ref->symref)
2452 ref->symref = xstrdup("");
2453 }
2454
2455 /* Fill in specials first */
2456 for (i = 0; i < used_atom_cnt; i++) {
2457 struct used_atom *atom = &used_atom[i];
2458 enum atom_type atom_type = atom->atom_type;
2459 const char *name = used_atom[i].name;
2460 struct atom_value *v = &ref->value[i];
2461 int deref = 0;
2462 const char *refname;
2463 struct branch *branch = NULL;
2464
2465 v->s_size = ATOM_SIZE_UNSPECIFIED;
2466 v->handler = append_atom;
2467 v->value = 0;
2468 v->atom = atom;
2469
2470 if (*name == '*') {
2471 deref = 1;
2472 name++;
2473 }
2474
2475 if (atom_type == ATOM_REFNAME)
2476 refname = get_refname(atom, ref);
2477 else if (atom_type == ATOM_WORKTREEPATH) {
2478 if (ref->kind == FILTER_REFS_BRANCHES)
2479 v->s = get_worktree_path(ref);
2480 else
2481 v->s = xstrdup("");
2482 continue;
2483 }
2484 else if (atom_type == ATOM_SYMREF)
2485 refname = get_symref(atom, ref);
2486 else if (atom_type == ATOM_UPSTREAM) {
2487 const char *branch_name;
2488 /* only local branches may have an upstream */
2489 if (!skip_prefix(ref->refname, "refs/heads/",
2490 &branch_name)) {
2491 v->s = xstrdup("");
2492 continue;
2493 }
2494 branch = branch_get(branch_name);
2495
2496 refname = branch_get_upstream(branch, NULL);
2497 if (refname)
2498 fill_remote_ref_details(atom, refname, branch, &v->s);
2499 else
2500 v->s = xstrdup("");
2501 continue;
2502 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
2503 const char *branch_name;
2504 v->s = xstrdup("");
2505 if (!skip_prefix(ref->refname, "refs/heads/",
2506 &branch_name))
2507 continue;
2508 branch = branch_get(branch_name);
2509
2510 if (atom->u.remote_ref.push_remote)
2511 refname = NULL;
2512 else {
2513 refname = branch_get_push(branch, NULL);
2514 if (!refname)
2515 continue;
2516 }
2517 /* We will definitely re-init v->s on the next line. */
2518 free((char *)v->s);
2519 fill_remote_ref_details(atom, refname, branch, &v->s);
2520 continue;
2521 } else if (atom_type == ATOM_COLOR) {
2522 v->s = xstrdup(atom->u.color);
2523 continue;
2524 } else if (atom_type == ATOM_FLAG) {
2525 char buf[256], *cp = buf;
2526 if (ref->flag & REF_ISSYMREF)
2527 cp = copy_advance(cp, ",symref");
2528 if (ref->flag & REF_ISPACKED)
2529 cp = copy_advance(cp, ",packed");
2530 if (cp == buf)
2531 v->s = xstrdup("");
2532 else {
2533 *cp = '\0';
2534 v->s = xstrdup(buf + 1);
2535 }
2536 continue;
2537 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
2538 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
2539 continue;
2540 } else if (atom_type == ATOM_HEAD) {
2541 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
2542 v->s = xstrdup("*");
2543 else
2544 v->s = xstrdup(" ");
2545 continue;
2546 } else if (atom_type == ATOM_ALIGN) {
2547 v->handler = align_atom_handler;
2548 v->s = xstrdup("");
2549 continue;
2550 } else if (atom_type == ATOM_END) {
2551 v->handler = end_atom_handler;
2552 v->s = xstrdup("");
2553 continue;
2554 } else if (atom_type == ATOM_IF) {
2555 const char *s;
2556 if (skip_prefix(name, "if:", &s))
2557 v->s = xstrdup(s);
2558 else
2559 v->s = xstrdup("");
2560 v->handler = if_atom_handler;
2561 continue;
2562 } else if (atom_type == ATOM_THEN) {
2563 v->handler = then_atom_handler;
2564 v->s = xstrdup("");
2565 continue;
2566 } else if (atom_type == ATOM_ELSE) {
2567 v->handler = else_atom_handler;
2568 v->s = xstrdup("");
2569 continue;
2570 } else if (atom_type == ATOM_REST) {
2571 if (ref->rest)
2572 v->s = xstrdup(ref->rest);
2573 else
2574 v->s = xstrdup("");
2575 continue;
2576 } else if (atom_type == ATOM_AHEADBEHIND) {
2577 if (ref->counts) {
2578 const struct ahead_behind_count *count;
2579 count = ref->counts[ahead_behind_atoms++];
2580 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2581 } else {
2582 /* Not a commit. */
2583 v->s = xstrdup("");
2584 }
2585 continue;
2586 } else if (atom_type == ATOM_ISBASE) {
2587 if (ref->is_base && ref->is_base[is_base_atoms]) {
2588 v->s = xstrfmt("(%s)", ref->is_base[is_base_atoms]);
2589 free(ref->is_base[is_base_atoms]);
2590 } else {
2591 v->s = xstrdup("");
2592 }
2593 is_base_atoms++;
2594 continue;
2595 } else
2596 continue;
2597
2598 if (!deref)
2599 v->s = xstrdup(refname);
2600 else
2601 v->s = xstrfmt("%s^{}", refname);
2602 free((char *)refname);
2603 }
2604
2605 for (i = 0; i < used_atom_cnt; i++) {
2606 struct atom_value *v = &ref->value[i];
2607 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2608 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2609 oid_to_hex(&ref->objectname), ref->refname);
2610 }
2611
2612 if (need_tagged)
2613 oi.info.contentp = &oi.content;
2614 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2615 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2616 return 0;
2617
2618
2619 oi.oid = ref->objectname;
2620 if (get_object(ref, 0, &oi, err))
2621 return -1;
2622
2623 /*
2624 * If there is no atom that wants to know about tagged
2625 * object, we are done.
2626 */
2627 if (!need_tagged || (oi.type != OBJ_TAG))
2628 return 0;
2629
2630 /*
2631 * If it is a tag object, see if we use the peeled value. If we do,
2632 * grab the peeled OID.
2633 */
2634 if (need_tagged) {
2635 if (!is_null_oid(&ref->peeled_oid)) {
2636 oidcpy(&oi_deref.oid, &ref->peeled_oid);
2637 } else if (!peel_object(the_repository, &oi.oid, &oi_deref.oid,
2638 PEEL_OBJECT_VERIFY_TAGGED_OBJECT_TYPE)) {
2639 /* We managed to peel the object ourselves. */
2640 } else {
2641 die("bad tag");
2642 }
2643 }
2644
2645 return get_object(ref, 1, &oi_deref, err);
2646 }
2647
2648 /*
2649 * Given a ref, return the value for the atom. This lazily gets value
2650 * out of the object by calling populate value.
2651 */
2652 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2653 struct atom_value **v, struct strbuf *err)
2654 {
2655 if (!ref->value) {
2656 if (populate_value(ref, err))
2657 return -1;
2658 fill_missing_values(ref->value);
2659 }
2660 *v = &ref->value[atom];
2661 return 0;
2662 }
2663
2664 /*
2665 * Return 1 if the refname matches one of the patterns, otherwise 0.
2666 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2667 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2668 * matches "refs/heads/mas*", too).
2669 */
2670 static int match_pattern(const char **patterns, const char *refname,
2671 int ignore_case)
2672 {
2673 unsigned flags = 0;
2674
2675 if (ignore_case)
2676 flags |= WM_CASEFOLD;
2677
2678 /*
2679 * When no '--format' option is given we need to skip the prefix
2680 * for matching refs of tags and branches.
2681 */
2682 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2683 skip_prefix(refname, "refs/heads/", &refname) ||
2684 skip_prefix(refname, "refs/remotes/", &refname) ||
2685 skip_prefix(refname, "refs/", &refname));
2686
2687 for (; *patterns; patterns++) {
2688 if (!wildmatch(*patterns, refname, flags))
2689 return 1;
2690 }
2691 return 0;
2692 }
2693
2694 /*
2695 * Return 1 if the refname matches one of the patterns, otherwise 0.
2696 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2697 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2698 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2699 */
2700 static int match_name_as_path(const char **pattern, const char *refname,
2701 int ignore_case)
2702 {
2703 int namelen = strlen(refname);
2704 unsigned flags = WM_PATHNAME;
2705
2706 if (ignore_case)
2707 flags |= WM_CASEFOLD;
2708
2709 for (; *pattern; pattern++) {
2710 const char *p = *pattern;
2711 int plen = strlen(p);
2712
2713 if ((plen <= namelen) &&
2714 !strncmp(refname, p, plen) &&
2715 (refname[plen] == '\0' ||
2716 refname[plen] == '/' ||
2717 p[plen-1] == '/'))
2718 return 1;
2719 if (!wildmatch(p, refname, flags))
2720 return 1;
2721 }
2722 return 0;
2723 }
2724
2725 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2726 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2727 {
2728 if (!filter->name_patterns || !*filter->name_patterns)
2729 return 1; /* No pattern always matches */
2730 if (filter->match_as_path)
2731 return match_name_as_path(filter->name_patterns, refname,
2732 filter->ignore_case);
2733 return match_pattern(filter->name_patterns, refname,
2734 filter->ignore_case);
2735 }
2736
2737 static int filter_exclude_match(struct ref_filter *filter, const char *refname)
2738 {
2739 if (!filter->exclude.nr)
2740 return 0;
2741 if (filter->match_as_path)
2742 return match_name_as_path(filter->exclude.v, refname,
2743 filter->ignore_case);
2744 return match_pattern(filter->exclude.v, refname, filter->ignore_case);
2745 }
2746
2747 static const char *short_upstream_name(const char *full_ref)
2748 {
2749 const char *short_name = full_ref;
2750 (void)(skip_prefix(short_name, "refs/heads/", &short_name) ||
2751 skip_prefix(short_name, "refs/remotes/", &short_name));
2752 return short_name;
2753 }
2754
2755 /*
2756 * Match the configured upstream of a branch against the registered
2757 * --forked patterns. Exact patterns are compared against the full
2758 * upstream refname so they are unambiguous; glob patterns are matched
2759 * against the abbreviated upstream so that a glob such as origin/...
2760 * works as typed.
2761 */
2762 static int filter_forked_match(struct ref_filter *filter, const char *refname)
2763 {
2764 const char *short_name;
2765 struct branch *branch;
2766 const char *upstream;
2767 int i;
2768
2769 if (!skip_prefix(refname, "refs/heads/", &short_name))
2770 return 0;
2771 branch = branch_get(short_name);
2772 if (!branch)
2773 return 0;
2774 upstream = branch_get_upstream(branch, NULL);
2775 if (!upstream)
2776 return 0;
2777
2778 for (i = 0; i < filter->forked.nr; i++) {
2779 const char *pattern = filter->forked.v[i];
2780 if (has_glob_specials(pattern)) {
2781 if (!wildmatch(pattern, short_upstream_name(upstream),
2782 WM_PATHNAME))
2783 return 1;
2784 } else if (!strcmp(pattern, upstream)) {
2785 return 1;
2786 }
2787 }
2788 return 0;
2789 }
2790
2791 int ref_filter_forked_add(struct ref_filter *filter, const char *arg)
2792 {
2793 struct object_id oid;
2794 char *full_ref = NULL;
2795
2796 if (has_glob_specials(arg)) {
2797 strvec_push(&filter->forked, arg);
2798 return 0;
2799 }
2800
2801 if (repo_dwim_ref(the_repository, arg, strlen(arg), &oid,
2802 &full_ref, 0) == 1 &&
2803 (starts_with(full_ref, "refs/heads/") ||
2804 starts_with(full_ref, "refs/remotes/"))) {
2805 strvec_push(&filter->forked, full_ref);
2806 free(full_ref);
2807 return 0;
2808 }
2809 free(full_ref);
2810 return -1;
2811 }
2812
2813 /*
2814 * We need to seek to the reference right after a given marker but excluding any
2815 * matching references. So we seek to the lexicographically next reference.
2816 */
2817 static int start_ref_iterator_after(struct ref_iterator *iter, const char *marker)
2818 {
2819 struct strbuf sb = STRBUF_INIT;
2820 int ret;
2821
2822 strbuf_addstr(&sb, marker);
2823 strbuf_addch(&sb, 1);
2824
2825 ret = ref_iterator_seek(iter, sb.buf, 0);
2826
2827 strbuf_release(&sb);
2828 return ret;
2829 }
2830
2831 static int for_each_fullref_with_seek(struct ref_filter *filter, refs_for_each_cb cb,
2832 void *cb_data, unsigned int flags)
2833 {
2834 struct ref_iterator *iter;
2835 int ret = 0;
2836
2837 iter = refs_ref_iterator_begin(get_main_ref_store(the_repository), "",
2838 NULL, 0, flags);
2839 if (filter->start_after)
2840 ret = start_ref_iterator_after(iter, filter->start_after);
2841
2842 if (ret)
2843 return ret;
2844
2845 return do_for_each_ref_iterator(iter, cb, cb_data);
2846 }
2847
2848 /*
2849 * This is the same as for_each_fullref_in(), but it tries to iterate
2850 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2851 * pattern match, so the callback still has to match each ref individually.
2852 */
2853 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2854 refs_for_each_cb cb,
2855 void *cb_data)
2856 {
2857 struct refs_for_each_ref_options opts = {
2858 .exclude_patterns = filter->exclude.v,
2859 };
2860
2861 if (filter->kind & FILTER_REFS_ROOT_REFS) {
2862 /* In this case, we want to print all refs including root refs. */
2863 return for_each_fullref_with_seek(filter, cb, cb_data,
2864 REFS_FOR_EACH_INCLUDE_ROOT_REFS);
2865 }
2866
2867 if (!filter->match_as_path) {
2868 /*
2869 * in this case, the patterns are applied after
2870 * prefixes like "refs/heads/" etc. are stripped off,
2871 * so we have to look at everything:
2872 */
2873 return for_each_fullref_with_seek(filter, cb, cb_data, 0);
2874 }
2875
2876 if (filter->ignore_case) {
2877 /*
2878 * we can't handle case-insensitive comparisons,
2879 * so just return everything and let the caller
2880 * sort it out.
2881 */
2882 return for_each_fullref_with_seek(filter, cb, cb_data, 0);
2883 }
2884
2885 if (!filter->name_patterns || !filter->name_patterns[0]) {
2886 /* no patterns; we have to look at everything */
2887 return for_each_fullref_with_seek(filter, cb, cb_data, 0);
2888 }
2889
2890 return refs_for_each_ref_in_prefixes(get_main_ref_store(the_repository),
2891 filter->name_patterns, &opts,
2892 cb, cb_data);
2893 }
2894
2895 /*
2896 * Given a ref (oid, refname), check if the ref belongs to the array
2897 * of oids. If the given ref is a tag, check if the given tag points
2898 * at one of the oids in the given oid array. Returns non-zero if a
2899 * match is found.
2900 *
2901 * NEEDSWORK:
2902 * As the refs are cached we might know what refname peels to without
2903 * the need to parse the object via parse_object(). peel_ref() might be a
2904 * more efficient alternative to obtain the pointee.
2905 */
2906 static int match_points_at(struct oid_array *points_at,
2907 const struct object_id *oid,
2908 const char *refname)
2909 {
2910 struct object *obj;
2911
2912 if (oid_array_lookup(points_at, oid) >= 0)
2913 return 1;
2914 obj = parse_object_with_flags(the_repository, oid,
2915 PARSE_OBJECT_SKIP_HASH_CHECK);
2916 while (obj && obj->type == OBJ_TAG) {
2917 struct tag *tag = (struct tag *)obj;
2918
2919 if (parse_tag(the_repository, tag) < 0) {
2920 obj = NULL;
2921 break;
2922 }
2923
2924 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2925 return 1;
2926
2927 obj = tag->tagged;
2928 }
2929 if (!obj)
2930 die(_("malformed object at '%s'"), refname);
2931 return 0;
2932 }
2933
2934 /*
2935 * Allocate space for a new ref_array_item and copy the name and oid to it.
2936 *
2937 * Callers can then fill in other struct members at their leisure.
2938 */
2939 static struct ref_array_item *new_ref_array_item(const char *refname,
2940 const struct object_id *oid,
2941 const struct object_id *peeled_oid)
2942 {
2943 struct ref_array_item *ref;
2944
2945 FLEX_ALLOC_STR(ref, refname, refname);
2946 oidcpy(&ref->objectname, oid);
2947 if (peeled_oid)
2948 oidcpy(&ref->peeled_oid, peeled_oid);
2949 ref->rest = NULL;
2950
2951 return ref;
2952 }
2953
2954 static void ref_array_append(struct ref_array *array, struct ref_array_item *ref)
2955 {
2956 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2957 array->items[array->nr++] = ref;
2958 }
2959
2960 struct ref_array_item *ref_array_push(struct ref_array *array,
2961 const char *refname,
2962 const struct object_id *oid,
2963 const struct object_id *peeled_oid)
2964 {
2965 struct ref_array_item *ref = new_ref_array_item(refname, oid, peeled_oid);
2966 ref_array_append(array, ref);
2967 return ref;
2968 }
2969
2970 int ref_kind_from_refname(const char *refname)
2971 {
2972 unsigned int i;
2973
2974 static struct {
2975 const char *prefix;
2976 unsigned int kind;
2977 } ref_kind[] = {
2978 { "refs/heads/" , FILTER_REFS_BRANCHES },
2979 { "refs/remotes/" , FILTER_REFS_REMOTES },
2980 { "refs/tags/", FILTER_REFS_TAGS}
2981 };
2982
2983 if (!strcmp(refname, "HEAD"))
2984 return FILTER_REFS_DETACHED_HEAD;
2985
2986 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2987 if (starts_with(refname, ref_kind[i].prefix))
2988 return ref_kind[i].kind;
2989 }
2990
2991 if (is_pseudo_ref(refname))
2992 return FILTER_REFS_PSEUDOREFS;
2993 if (is_root_ref(refname))
2994 return FILTER_REFS_ROOT_REFS;
2995
2996 return FILTER_REFS_OTHERS;
2997 }
2998
2999 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
3000 {
3001 if (filter->kind == FILTER_REFS_BRANCHES ||
3002 filter->kind == FILTER_REFS_REMOTES ||
3003 filter->kind == FILTER_REFS_TAGS)
3004 return filter->kind;
3005 return ref_kind_from_refname(refname);
3006 }
3007
3008 static struct ref_array_item *apply_ref_filter(const struct reference *ref,
3009 struct ref_filter *filter)
3010 {
3011 struct ref_array_item *item;
3012 struct commit *commit = NULL;
3013 unsigned int kind;
3014
3015 if (ref->flags & REF_BAD_NAME) {
3016 warning(_("ignoring ref with broken name %s"), ref->name);
3017 return NULL;
3018 }
3019
3020 if (ref->flags & REF_ISBROKEN) {
3021 warning(_("ignoring broken ref %s"), ref->name);
3022 return NULL;
3023 }
3024
3025 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
3026 kind = filter_ref_kind(filter, ref->name);
3027
3028 /*
3029 * Generally HEAD refs are printed with special description denoting a rebase,
3030 * detached state and so forth. This is useful when only printing the HEAD ref
3031 * But when it is being printed along with other root refs, it makes sense to
3032 * keep the formatting consistent. So we mask the type to act like a root ref.
3033 */
3034 if (filter->kind & FILTER_REFS_ROOT_REFS && kind == FILTER_REFS_DETACHED_HEAD)
3035 kind = FILTER_REFS_ROOT_REFS;
3036 else if (!(kind & filter->kind))
3037 return NULL;
3038
3039 if (!filter_pattern_match(filter, ref->name))
3040 return NULL;
3041
3042 if (filter_exclude_match(filter, ref->name))
3043 return NULL;
3044
3045 if (filter->points_at.nr && !match_points_at(&filter->points_at, ref->oid, ref->name))
3046 return NULL;
3047
3048 if (filter->forked.nr && !filter_forked_match(filter, ref->name))
3049 return NULL;
3050
3051 /*
3052 * A merge filter is applied on refs pointing to commits. Hence
3053 * obtain the commit using the 'oid' available and discard all
3054 * non-commits early. The actual filtering is done later.
3055 */
3056 if (filter->reachable_from || filter->unreachable_from ||
3057 filter->with_commit || filter->no_commit || filter->verbose) {
3058 commit = lookup_commit_reference_gently(the_repository, ref->oid, 1);
3059 if (!commit)
3060 return NULL;
3061 /* We perform the filtering for the '--contains' option... */
3062 if (filter->with_commit &&
3063 !commit_contains(filter, commit, filter->with_commit, &filter->internal.contains_cache))
3064 return NULL;
3065 /* ...or for the `--no-contains' option */
3066 if (filter->no_commit &&
3067 commit_contains(filter, commit, filter->no_commit, &filter->internal.no_contains_cache))
3068 return NULL;
3069 }
3070
3071 /*
3072 * We do not open the object yet; sort may only need refname
3073 * to do its job and the resulting list may yet to be pruned
3074 * by maxcount logic.
3075 */
3076 item = new_ref_array_item(ref->name, ref->oid, ref->peeled_oid);
3077 item->commit = commit;
3078 item->flag = ref->flags;
3079 item->kind = kind;
3080 item->symref = xstrdup_or_null(ref->target);
3081
3082 return item;
3083 }
3084
3085 struct ref_filter_cbdata {
3086 struct ref_array *array;
3087 struct ref_filter *filter;
3088 };
3089
3090 /*
3091 * A call-back given to for_each_ref(). Filter refs and keep them for
3092 * later object processing.
3093 */
3094 static int filter_one(const struct reference *ref, void *cb_data)
3095 {
3096 struct ref_filter_cbdata *ref_cbdata = cb_data;
3097 struct ref_array_item *item;
3098
3099 item = apply_ref_filter(ref, ref_cbdata->filter);
3100 if (item)
3101 ref_array_append(ref_cbdata->array, item);
3102
3103 return 0;
3104 }
3105
3106 /* Free memory allocated for a ref_array_item */
3107 static void free_array_item(struct ref_array_item *item)
3108 {
3109 free((char *)item->symref);
3110 if (item->value) {
3111 int i;
3112 for (i = 0; i < used_atom_cnt; i++)
3113 free((char *)item->value[i].s);
3114 free(item->value);
3115 }
3116 free(item->counts);
3117 free(item->is_base);
3118 free(item);
3119 }
3120
3121 struct ref_filter_and_format_cbdata {
3122 struct ref_filter *filter;
3123 struct ref_format *format;
3124
3125 struct ref_filter_and_format_internal {
3126 int count;
3127 } internal;
3128 };
3129
3130 static int filter_and_format_one(const struct reference *ref, void *cb_data)
3131 {
3132 struct ref_filter_and_format_cbdata *ref_cbdata = cb_data;
3133 struct ref_array_item *item;
3134 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3135
3136 item = apply_ref_filter(ref, ref_cbdata->filter);
3137 if (!item)
3138 return 0;
3139
3140 if (format_ref_array_item(item, ref_cbdata->format, &output, &err))
3141 die("%s", err.buf);
3142
3143 if (output.len || !ref_cbdata->format->array_opts.omit_empty) {
3144 fwrite(output.buf, 1, output.len, stdout);
3145 putchar('\n');
3146 }
3147
3148 strbuf_release(&output);
3149 strbuf_release(&err);
3150 free_array_item(item);
3151
3152 /*
3153 * Increment the running count of refs that match the filter. If
3154 * max_count is set and we've reached the max, stop the ref
3155 * iteration by returning a nonzero value.
3156 */
3157 if (ref_cbdata->format->array_opts.max_count &&
3158 ++ref_cbdata->internal.count >= ref_cbdata->format->array_opts.max_count)
3159 return 1;
3160
3161 return 0;
3162 }
3163
3164 /* Free all memory allocated for ref_array */
3165 void ref_array_clear(struct ref_array *array)
3166 {
3167 int i;
3168
3169 for (i = 0; i < array->nr; i++)
3170 free_array_item(array->items[i]);
3171 FREE_AND_NULL(array->items);
3172 array->nr = array->alloc = 0;
3173
3174 for (i = 0; i < used_atom_cnt; i++) {
3175 struct used_atom *atom = &used_atom[i];
3176 if (atom->atom_type == ATOM_HEAD)
3177 free(atom->u.head);
3178 else if (atom->atom_type == ATOM_DESCRIBE)
3179 strvec_clear(&atom->u.describe_args);
3180 else if (atom->atom_type == ATOM_ISBASE)
3181 free(atom->u.base.name);
3182 else if (atom->atom_type == ATOM_TRAILERS ||
3183 (atom->atom_type == ATOM_CONTENTS &&
3184 atom->u.contents.option == C_TRAILERS)) {
3185 struct ref_trailer_buf *tb = atom->u.contents.trailer_buf;
3186 if (tb) {
3187 string_list_clear(&tb->filter_list, 0);
3188 strbuf_release(&tb->sepbuf);
3189 strbuf_release(&tb->kvsepbuf);
3190 free(tb);
3191 }
3192 }
3193 free((char *)atom->name);
3194 }
3195 FREE_AND_NULL(used_atom);
3196 used_atom_cnt = 0;
3197
3198 if (ref_to_worktree_map.worktrees) {
3199 hashmap_clear_and_free(&(ref_to_worktree_map.map),
3200 struct ref_to_worktree_entry, ent);
3201 free_worktrees(ref_to_worktree_map.worktrees);
3202 ref_to_worktree_map.worktrees = NULL;
3203 }
3204
3205 FREE_AND_NULL(array->counts);
3206 }
3207
3208 #define EXCLUDE_REACHED 0
3209 #define INCLUDE_REACHED 1
3210 static void reach_filter(struct ref_array *array,
3211 struct commit_list **check_reachable,
3212 int include_reached)
3213 {
3214 size_t i, old_nr;
3215 struct commit **to_clear;
3216
3217 if (!*check_reachable)
3218 return;
3219
3220 CALLOC_ARRAY(to_clear, array->nr);
3221 for (i = 0; i < array->nr; i++) {
3222 struct ref_array_item *item = array->items[i];
3223 to_clear[i] = item->commit;
3224 }
3225
3226 tips_reachable_from_bases(the_repository,
3227 *check_reachable,
3228 to_clear, array->nr,
3229 UNINTERESTING);
3230
3231 old_nr = array->nr;
3232 array->nr = 0;
3233
3234 for (i = 0; i < old_nr; i++) {
3235 struct ref_array_item *item = array->items[i];
3236 struct commit *commit = item->commit;
3237
3238 int is_merged = !!(commit->object.flags & UNINTERESTING);
3239
3240 if (is_merged == include_reached)
3241 array->items[array->nr++] = array->items[i];
3242 else
3243 free_array_item(item);
3244 }
3245
3246 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
3247
3248 while (*check_reachable) {
3249 struct commit *merge_commit = pop_commit(check_reachable);
3250 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
3251 }
3252
3253 free(to_clear);
3254 }
3255
3256 void filter_ahead_behind(struct repository *r,
3257 struct ref_array *array)
3258 {
3259 struct commit **commits;
3260 size_t bases_nr, commits_nr;
3261
3262 if (!array->nr)
3263 return;
3264
3265 for (size_t i = bases_nr = 0; i < used_atom_cnt; i++) {
3266 if (used_atom[i].atom_type == ATOM_AHEADBEHIND)
3267 bases_nr++;
3268 }
3269 if (!bases_nr)
3270 return;
3271
3272 ALLOC_ARRAY(commits, st_add(bases_nr, array->nr));
3273 for (size_t i = 0, j = 0; i < used_atom_cnt; i++) {
3274 if (used_atom[i].atom_type == ATOM_AHEADBEHIND)
3275 commits[j++] = used_atom[i].u.base.commit;
3276 }
3277
3278 ALLOC_ARRAY(array->counts, st_mult(bases_nr, array->nr));
3279
3280 commits_nr = bases_nr;
3281 array->counts_nr = 0;
3282 for (size_t i = 0; i < array->nr; i++) {
3283 const char *name = array->items[i]->refname;
3284 commits[commits_nr] = lookup_commit_reference_by_name(name);
3285
3286 if (!commits[commits_nr])
3287 continue;
3288
3289 CALLOC_ARRAY(array->items[i]->counts, bases_nr);
3290 for (size_t j = 0; j < bases_nr; j++) {
3291 struct ahead_behind_count *count;
3292 count = &array->counts[array->counts_nr++];
3293 count->tip_index = commits_nr;
3294 count->base_index = j;
3295
3296 array->items[i]->counts[j] = count;
3297 }
3298 commits_nr++;
3299 }
3300
3301 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
3302 free(commits);
3303 }
3304
3305 void filter_is_base(struct repository *r,
3306 struct ref_array *array)
3307 {
3308 struct commit **bases;
3309 size_t bases_nr = 0, is_base_nr;
3310 struct ref_array_item **back_index;
3311
3312 if (!array->nr)
3313 return;
3314
3315 for (size_t i = is_base_nr = 0; i < used_atom_cnt; i++) {
3316 if (used_atom[i].atom_type == ATOM_ISBASE)
3317 is_base_nr++;
3318 }
3319 if (!is_base_nr)
3320 return;
3321
3322 CALLOC_ARRAY(back_index, array->nr);
3323 CALLOC_ARRAY(bases, array->nr);
3324
3325 for (size_t i = 0; i < array->nr; i++) {
3326 const char *name = array->items[i]->refname;
3327 struct commit *c = lookup_commit_reference_by_name_gently(name, 1);
3328
3329 CALLOC_ARRAY(array->items[i]->is_base, is_base_nr);
3330
3331 if (!c)
3332 continue;
3333
3334 back_index[bases_nr] = array->items[i];
3335 bases[bases_nr] = c;
3336 bases_nr++;
3337 }
3338
3339 for (size_t i = 0, j = 0; i < used_atom_cnt; i++) {
3340 struct commit *tip;
3341 int base_index;
3342
3343 if (used_atom[i].atom_type != ATOM_ISBASE)
3344 continue;
3345
3346 tip = used_atom[i].u.base.commit;
3347 base_index = get_branch_base_for_tip(r, tip, bases, bases_nr);
3348 if (base_index < 0)
3349 continue;
3350
3351 /* Store the string for use in output later. */
3352 back_index[base_index]->is_base[j++] = xstrdup(used_atom[i].u.base.name);
3353 }
3354
3355 free(back_index);
3356 free(bases);
3357 }
3358
3359 static int do_filter_refs(struct ref_filter *filter, unsigned int type, refs_for_each_cb fn, void *cb_data)
3360 {
3361 const char *prefix = NULL;
3362 int ret = 0;
3363
3364 filter->kind = type & FILTER_REFS_KIND_MASK;
3365
3366 init_contains_cache(&filter->internal.contains_cache);
3367 init_contains_cache(&filter->internal.no_contains_cache);
3368
3369 /* Simple per-ref filtering */
3370 if (!filter->kind)
3371 die("filter_refs: invalid type");
3372
3373 /*
3374 * For common cases where we need only branches or remotes or tags,
3375 * we only iterate through those refs. If a mix of refs is needed,
3376 * we iterate over all refs and filter out required refs with the help
3377 * of filter_ref_kind().
3378 */
3379 if (filter->kind == FILTER_REFS_BRANCHES)
3380 prefix = "refs/heads/";
3381 else if (filter->kind == FILTER_REFS_REMOTES)
3382 prefix = "refs/remotes/";
3383 else if (filter->kind == FILTER_REFS_TAGS)
3384 prefix = "refs/tags/";
3385
3386 if (prefix) {
3387 struct ref_iterator *iter;
3388 struct ref_store *store = get_main_ref_store(the_repository);
3389
3390 if (filter->start_after) {
3391 iter = refs_ref_iterator_begin(store, "", NULL, 0, 0);
3392 ret = start_ref_iterator_after(iter, filter->start_after);
3393 } else {
3394 iter = refs_ref_iterator_begin(store, prefix, NULL, 0, 0);
3395 }
3396
3397 if (!ret)
3398 ret = do_for_each_ref_iterator(iter, fn, cb_data);
3399 } else if (filter->kind & FILTER_REFS_REGULAR) {
3400 ret = for_each_fullref_in_pattern(filter, fn, cb_data);
3401 }
3402
3403 /*
3404 * When printing all ref types, HEAD is already included,
3405 * so we don't want to print HEAD again.
3406 */
3407 if (!ret && !(filter->kind & FILTER_REFS_ROOT_REFS) &&
3408 (filter->kind & FILTER_REFS_DETACHED_HEAD))
3409 refs_head_ref(get_main_ref_store(the_repository), fn,
3410 cb_data);
3411
3412
3413 clear_contains_cache(&filter->internal.contains_cache);
3414 clear_contains_cache(&filter->internal.no_contains_cache);
3415
3416 return ret;
3417 }
3418
3419 /*
3420 * API for filtering a set of refs. Based on the type of refs the user
3421 * has requested, we iterate through those refs and apply filters
3422 * as per the given ref_filter structure and finally store the
3423 * filtered refs in the ref_array structure.
3424 */
3425 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
3426 {
3427 struct ref_filter_cbdata ref_cbdata;
3428 int save_commit_buffer_orig;
3429 int ret = 0;
3430
3431 ref_cbdata.array = array;
3432 ref_cbdata.filter = filter;
3433
3434 save_commit_buffer_orig = save_commit_buffer;
3435 save_commit_buffer = 0;
3436
3437 ret = do_filter_refs(filter, type, filter_one, &ref_cbdata);
3438
3439 /* Filters that need revision walking */
3440 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
3441 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
3442
3443 save_commit_buffer = save_commit_buffer_orig;
3444 return ret;
3445 }
3446
3447 struct ref_sorting {
3448 struct ref_sorting *next;
3449 int atom; /* index into used_atom array (internal) */
3450 enum ref_sorting_order sort_flags;
3451 };
3452
3453 static inline int can_do_iterative_format(struct ref_filter *filter,
3454 struct ref_sorting *sorting)
3455 {
3456 /*
3457 * Reference backends sort patterns lexicographically by refname, so if
3458 * the sorting options ask for exactly that we are able to do iterative
3459 * formatting.
3460 *
3461 * Note that we do not have to worry about multiple name patterns,
3462 * either. Those get sorted and deduplicated eventually in
3463 * `refs_for_each_fullref_in_prefixes()`, so we return names in the
3464 * correct ordering here, too.
3465 */
3466 if (sorting && (sorting->next ||
3467 sorting->sort_flags ||
3468 used_atom[sorting->atom].atom_type != ATOM_REFNAME))
3469 return 0;
3470
3471 /*
3472 * Filtering & formatting results within a single ref iteration
3473 * callback is not compatible with options that require
3474 * post-processing a filtered ref_array. These include:
3475 * - filtering on reachability
3476 * - including ahead-behind information in the formatted output
3477 */
3478 for (size_t i = 0; i < used_atom_cnt; i++) {
3479 if (used_atom[i].atom_type == ATOM_AHEADBEHIND)
3480 return 0;
3481 if (used_atom[i].atom_type == ATOM_ISBASE)
3482 return 0;
3483 }
3484 return !(filter->reachable_from || filter->unreachable_from);
3485 }
3486
3487 void filter_and_format_refs(struct ref_filter *filter, unsigned int type,
3488 struct ref_sorting *sorting,
3489 struct ref_format *format)
3490 {
3491 if (can_do_iterative_format(filter, sorting)) {
3492 int save_commit_buffer_orig;
3493 struct ref_filter_and_format_cbdata ref_cbdata = {
3494 .filter = filter,
3495 .format = format,
3496 };
3497
3498 save_commit_buffer_orig = save_commit_buffer;
3499 save_commit_buffer = 0;
3500
3501 do_filter_refs(filter, type, filter_and_format_one, &ref_cbdata);
3502
3503 save_commit_buffer = save_commit_buffer_orig;
3504 } else {
3505 struct ref_array array = { 0 };
3506 filter_refs(&array, filter, type);
3507 filter_ahead_behind(the_repository, &array);
3508 filter_is_base(the_repository, &array);
3509 ref_array_sort(sorting, &array);
3510 print_formatted_ref_array(&array, format);
3511 ref_array_clear(&array);
3512 }
3513 }
3514
3515 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
3516 {
3517 if (!(a->kind ^ b->kind))
3518 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
3519 if (a->kind & FILTER_REFS_DETACHED_HEAD)
3520 return -1;
3521 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
3522 return 1;
3523 BUG("should have died in the xor check above");
3524 return 0;
3525 }
3526
3527 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
3528 {
3529 const char *s1 = vs1, *s2 = vs2;
3530 const char *end = s1 + n;
3531
3532 for (; s1 < end; s1++, s2++) {
3533 int diff = tolower(*s1) - tolower(*s2);
3534 if (diff)
3535 return diff;
3536 }
3537 return 0;
3538 }
3539
3540 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
3541 {
3542 struct atom_value *va, *vb;
3543 int cmp;
3544 int cmp_detached_head = 0;
3545 cmp_type cmp_type = used_atom[s->atom].type;
3546 struct strbuf err = STRBUF_INIT;
3547
3548 if (get_ref_atom_value(a, s->atom, &va, &err))
3549 die("%s", err.buf);
3550 if (get_ref_atom_value(b, s->atom, &vb, &err))
3551 die("%s", err.buf);
3552 strbuf_release(&err);
3553 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
3554 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
3555 cmp = compare_detached_head(a, b);
3556 cmp_detached_head = 1;
3557 } else if (s->sort_flags & REF_SORTING_VERSION) {
3558 cmp = versioncmp(va->s, vb->s);
3559 } else if (cmp_type == FIELD_STR) {
3560 if (va->s_size < 0 && vb->s_size < 0) {
3561 int (*cmp_fn)(const char *, const char *);
3562 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3563 ? strcasecmp : strcmp;
3564 cmp = cmp_fn(va->s, vb->s);
3565 } else {
3566 size_t a_size = va->s_size < 0 ?
3567 strlen(va->s) : va->s_size;
3568 size_t b_size = vb->s_size < 0 ?
3569 strlen(vb->s) : vb->s_size;
3570 int (*cmp_fn)(const void *, const void *, size_t);
3571 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3572 ? memcasecmp : memcmp;
3573
3574 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3575 a_size : b_size);
3576 if (!cmp) {
3577 if (a_size > b_size)
3578 cmp = 1;
3579 else if (a_size < b_size)
3580 cmp = -1;
3581 }
3582 }
3583 } else {
3584 if (va->value < vb->value)
3585 cmp = -1;
3586 else if (va->value == vb->value)
3587 cmp = 0;
3588 else
3589 cmp = 1;
3590 }
3591
3592 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3593 ? -cmp : cmp;
3594 }
3595
3596 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3597 {
3598 struct ref_array_item *a = *((struct ref_array_item **)a_);
3599 struct ref_array_item *b = *((struct ref_array_item **)b_);
3600 struct ref_sorting *s;
3601
3602 for (s = ref_sorting; s; s = s->next) {
3603 int cmp = cmp_ref_sorting(s, a, b);
3604 if (cmp)
3605 return cmp;
3606 }
3607 s = ref_sorting;
3608 return s && s->sort_flags & REF_SORTING_ICASE ?
3609 strcasecmp(a->refname, b->refname) :
3610 strcmp(a->refname, b->refname);
3611 }
3612
3613 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3614 unsigned int mask, int on)
3615 {
3616 for (; sorting; sorting = sorting->next) {
3617 if (on)
3618 sorting->sort_flags |= mask;
3619 else
3620 sorting->sort_flags &= ~mask;
3621 }
3622 }
3623
3624 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3625 {
3626 if (sorting)
3627 QSORT_S(array->items, array->nr, compare_refs, sorting);
3628 }
3629
3630 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3631 {
3632 struct strbuf *s = &state->stack->output;
3633
3634 while (*cp && (!ep || cp < ep)) {
3635 if (*cp == '%') {
3636 if (cp[1] == '%')
3637 cp++;
3638 else {
3639 int ch = hex2chr(cp + 1);
3640 if (0 <= ch) {
3641 strbuf_addch(s, ch);
3642 cp += 3;
3643 continue;
3644 }
3645 }
3646 }
3647 strbuf_addch(s, *cp);
3648 cp++;
3649 }
3650 }
3651
3652 int format_ref_array_item(struct ref_array_item *info,
3653 struct ref_format *format,
3654 struct strbuf *final_buf,
3655 struct strbuf *error_buf)
3656 {
3657 const char *cp, *sp, *ep;
3658 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3659
3660 state.quote_style = format->quote_style;
3661 push_stack_element(&state.stack);
3662
3663 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3664 struct atom_value *atomv;
3665 int pos;
3666
3667 ep = strchr(sp, ')');
3668 if (cp < sp)
3669 append_literal(cp, sp, &state);
3670 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3671 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3672 atomv->handler(atomv, &state, error_buf)) {
3673 pop_stack_element(&state.stack);
3674 return -1;
3675 }
3676 }
3677 if (*cp) {
3678 sp = cp + strlen(cp);
3679 append_literal(cp, sp, &state);
3680 }
3681 if (format->need_color_reset_at_eol) {
3682 struct atom_value resetv = ATOM_VALUE_INIT;
3683 resetv.s = GIT_COLOR_RESET;
3684 if (append_atom(&resetv, &state, error_buf)) {
3685 pop_stack_element(&state.stack);
3686 return -1;
3687 }
3688 }
3689 if (state.stack->prev) {
3690 pop_stack_element(&state.stack);
3691 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3692 }
3693 strbuf_addbuf(final_buf, &state.stack->output);
3694 pop_stack_element(&state.stack);
3695 return 0;
3696 }
3697
3698 void print_formatted_ref_array(struct ref_array *array, struct ref_format *format)
3699 {
3700 int total;
3701 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3702
3703 total = format->array_opts.max_count;
3704 if (!total || array->nr < total)
3705 total = array->nr;
3706 for (int i = 0; i < total; i++) {
3707 strbuf_reset(&err);
3708 strbuf_reset(&output);
3709 if (format_ref_array_item(array->items[i], format, &output, &err))
3710 die("%s", err.buf);
3711 if (output.len || !format->array_opts.omit_empty) {
3712 fwrite(output.buf, 1, output.len, stdout);
3713 putchar('\n');
3714 }
3715 }
3716
3717 strbuf_release(&err);
3718 strbuf_release(&output);
3719 }
3720
3721 void pretty_print_ref(const char *name, const struct object_id *oid,
3722 const struct object_id *peeled_oid,
3723 struct ref_format *format)
3724 {
3725 struct ref_array_item *ref_item;
3726 struct strbuf output = STRBUF_INIT;
3727 struct strbuf err = STRBUF_INIT;
3728
3729 ref_item = new_ref_array_item(name, oid, peeled_oid);
3730 ref_item->kind = ref_kind_from_refname(name);
3731 if (format_ref_array_item(ref_item, format, &output, &err))
3732 die("%s", err.buf);
3733 fwrite(output.buf, 1, output.len, stdout);
3734 putchar('\n');
3735
3736 strbuf_release(&err);
3737 strbuf_release(&output);
3738 free_array_item(ref_item);
3739 }
3740
3741 static int parse_sorting_atom(const char *atom)
3742 {
3743 /*
3744 * This parses an atom using a dummy ref_format, since we don't
3745 * actually care about the formatting details.
3746 */
3747 struct ref_format dummy = REF_FORMAT_INIT;
3748 const char *end = atom + strlen(atom);
3749 struct strbuf err = STRBUF_INIT;
3750 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3751 if (res < 0)
3752 die("%s", err.buf);
3753 strbuf_release(&err);
3754 return res;
3755 }
3756
3757 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3758 {
3759 struct ref_sorting *s;
3760
3761 CALLOC_ARRAY(s, 1);
3762 s->next = *sorting_tail;
3763 *sorting_tail = s;
3764
3765 if (*arg == '-') {
3766 s->sort_flags |= REF_SORTING_REVERSE;
3767 arg++;
3768 }
3769 if (skip_prefix(arg, "version:", &arg) ||
3770 skip_prefix(arg, "v:", &arg))
3771 s->sort_flags |= REF_SORTING_VERSION;
3772 s->atom = parse_sorting_atom(arg);
3773 }
3774
3775 struct ref_sorting *ref_sorting_options(struct string_list *options)
3776 {
3777 struct string_list_item *item;
3778 struct ref_sorting *sorting = NULL, **tail = &sorting;
3779
3780 if (options->nr) {
3781 for_each_string_list_item(item, options)
3782 parse_ref_sorting(tail, item->string);
3783 }
3784
3785 /*
3786 * From here on, the ref_sorting list should be used to talk
3787 * about the sort order used for the output. The caller
3788 * should not touch the string form anymore.
3789 */
3790 string_list_clear(options, 0);
3791 return sorting;
3792 }
3793
3794 void ref_sorting_release(struct ref_sorting *sorting)
3795 {
3796 while (sorting) {
3797 struct ref_sorting *next = sorting->next;
3798 free(sorting);
3799 sorting = next;
3800 }
3801 }
3802
3803 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3804 {
3805 struct ref_filter *rf = opt->value;
3806 struct object_id oid;
3807 struct commit *merge_commit;
3808
3809 BUG_ON_OPT_NEG(unset);
3810
3811 if (repo_get_oid(the_repository, arg, &oid))
3812 die(_("malformed object name %s"), arg);
3813
3814 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3815
3816 if (!merge_commit)
3817 return error(_("option `%s' must point to a commit"), opt->long_name);
3818
3819 if (starts_with(opt->long_name, "no"))
3820 commit_list_insert(merge_commit, &rf->unreachable_from);
3821 else
3822 commit_list_insert(merge_commit, &rf->reachable_from);
3823
3824 return 0;
3825 }
3826
3827 void ref_filter_init(struct ref_filter *filter)
3828 {
3829 struct ref_filter blank = REF_FILTER_INIT;
3830 memcpy(filter, &blank, sizeof(blank));
3831 }
3832
3833 void ref_filter_clear(struct ref_filter *filter)
3834 {
3835 strvec_clear(&filter->exclude);
3836 strvec_clear(&filter->forked);
3837 oid_array_clear(&filter->points_at);
3838 commit_list_free(filter->with_commit);
3839 commit_list_free(filter->no_commit);
3840 commit_list_free(filter->reachable_from);
3841 commit_list_free(filter->unreachable_from);
3842 ref_filter_init(filter);
3843 }