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();
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 /*
2748 * We need to seek to the reference right after a given marker but excluding any
2749 * matching references. So we seek to the lexicographically next reference.
2750 */
2751 static int start_ref_iterator_after(struct ref_iterator *iter, const char *marker)
2752 {
2753 struct strbuf sb = STRBUF_INIT;
2754 int ret;
2755
2756 strbuf_addstr(&sb, marker);
2757 strbuf_addch(&sb, 1);
2758
2759 ret = ref_iterator_seek(iter, sb.buf, 0);
2760
2761 strbuf_release(&sb);
2762 return ret;
2763 }
2764
2765 static int for_each_fullref_with_seek(struct ref_filter *filter, refs_for_each_cb cb,
2766 void *cb_data, unsigned int flags)
2767 {
2768 struct ref_iterator *iter;
2769 int ret = 0;
2770
2771 iter = refs_ref_iterator_begin(get_main_ref_store(the_repository), "",
2772 NULL, 0, flags);
2773 if (filter->start_after)
2774 ret = start_ref_iterator_after(iter, filter->start_after);
2775
2776 if (ret)
2777 return ret;
2778
2779 return do_for_each_ref_iterator(iter, cb, cb_data);
2780 }
2781
2782 /*
2783 * This is the same as for_each_fullref_in(), but it tries to iterate
2784 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2785 * pattern match, so the callback still has to match each ref individually.
2786 */
2787 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2788 refs_for_each_cb cb,
2789 void *cb_data)
2790 {
2791 struct refs_for_each_ref_options opts = {
2792 .exclude_patterns = filter->exclude.v,
2793 };
2794
2795 if (filter->kind & FILTER_REFS_ROOT_REFS) {
2796 /* In this case, we want to print all refs including root refs. */
2797 return for_each_fullref_with_seek(filter, cb, cb_data,
2798 REFS_FOR_EACH_INCLUDE_ROOT_REFS);
2799 }
2800
2801 if (!filter->match_as_path) {
2802 /*
2803 * in this case, the patterns are applied after
2804 * prefixes like "refs/heads/" etc. are stripped off,
2805 * so we have to look at everything:
2806 */
2807 return for_each_fullref_with_seek(filter, cb, cb_data, 0);
2808 }
2809
2810 if (filter->ignore_case) {
2811 /*
2812 * we can't handle case-insensitive comparisons,
2813 * so just return everything and let the caller
2814 * sort it out.
2815 */
2816 return for_each_fullref_with_seek(filter, cb, cb_data, 0);
2817 }
2818
2819 if (!filter->name_patterns || !filter->name_patterns[0]) {
2820 /* no patterns; we have to look at everything */
2821 return for_each_fullref_with_seek(filter, cb, cb_data, 0);
2822 }
2823
2824 return refs_for_each_ref_in_prefixes(get_main_ref_store(the_repository),
2825 filter->name_patterns, &opts,
2826 cb, cb_data);
2827 }
2828
2829 /*
2830 * Given a ref (oid, refname), check if the ref belongs to the array
2831 * of oids. If the given ref is a tag, check if the given tag points
2832 * at one of the oids in the given oid array. Returns non-zero if a
2833 * match is found.
2834 *
2835 * NEEDSWORK:
2836 * As the refs are cached we might know what refname peels to without
2837 * the need to parse the object via parse_object(). peel_ref() might be a
2838 * more efficient alternative to obtain the pointee.
2839 */
2840 static int match_points_at(struct oid_array *points_at,
2841 const struct object_id *oid,
2842 const char *refname)
2843 {
2844 struct object *obj;
2845
2846 if (oid_array_lookup(points_at, oid) >= 0)
2847 return 1;
2848 obj = parse_object_with_flags(the_repository, oid,
2849 PARSE_OBJECT_SKIP_HASH_CHECK);
2850 while (obj && obj->type == OBJ_TAG) {
2851 struct tag *tag = (struct tag *)obj;
2852
2853 if (parse_tag(the_repository, tag) < 0) {
2854 obj = NULL;
2855 break;
2856 }
2857
2858 if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)
2859 return 1;
2860
2861 obj = tag->tagged;
2862 }
2863 if (!obj)
2864 die(_("malformed object at '%s'"), refname);
2865 return 0;
2866 }
2867
2868 /*
2869 * Allocate space for a new ref_array_item and copy the name and oid to it.
2870 *
2871 * Callers can then fill in other struct members at their leisure.
2872 */
2873 static struct ref_array_item *new_ref_array_item(const char *refname,
2874 const struct object_id *oid,
2875 const struct object_id *peeled_oid)
2876 {
2877 struct ref_array_item *ref;
2878
2879 FLEX_ALLOC_STR(ref, refname, refname);
2880 oidcpy(&ref->objectname, oid);
2881 if (peeled_oid)
2882 oidcpy(&ref->peeled_oid, peeled_oid);
2883 ref->rest = NULL;
2884
2885 return ref;
2886 }
2887
2888 static void ref_array_append(struct ref_array *array, struct ref_array_item *ref)
2889 {
2890 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2891 array->items[array->nr++] = ref;
2892 }
2893
2894 struct ref_array_item *ref_array_push(struct ref_array *array,
2895 const char *refname,
2896 const struct object_id *oid,
2897 const struct object_id *peeled_oid)
2898 {
2899 struct ref_array_item *ref = new_ref_array_item(refname, oid, peeled_oid);
2900 ref_array_append(array, ref);
2901 return ref;
2902 }
2903
2904 int ref_kind_from_refname(const char *refname)
2905 {
2906 unsigned int i;
2907
2908 static struct {
2909 const char *prefix;
2910 unsigned int kind;
2911 } ref_kind[] = {
2912 { "refs/heads/" , FILTER_REFS_BRANCHES },
2913 { "refs/remotes/" , FILTER_REFS_REMOTES },
2914 { "refs/tags/", FILTER_REFS_TAGS}
2915 };
2916
2917 if (!strcmp(refname, "HEAD"))
2918 return FILTER_REFS_DETACHED_HEAD;
2919
2920 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2921 if (starts_with(refname, ref_kind[i].prefix))
2922 return ref_kind[i].kind;
2923 }
2924
2925 if (is_pseudo_ref(refname))
2926 return FILTER_REFS_PSEUDOREFS;
2927 if (is_root_ref(refname))
2928 return FILTER_REFS_ROOT_REFS;
2929
2930 return FILTER_REFS_OTHERS;
2931 }
2932
2933 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2934 {
2935 if (filter->kind == FILTER_REFS_BRANCHES ||
2936 filter->kind == FILTER_REFS_REMOTES ||
2937 filter->kind == FILTER_REFS_TAGS)
2938 return filter->kind;
2939 return ref_kind_from_refname(refname);
2940 }
2941
2942 static struct ref_array_item *apply_ref_filter(const struct reference *ref,
2943 struct ref_filter *filter)
2944 {
2945 struct ref_array_item *item;
2946 struct commit *commit = NULL;
2947 unsigned int kind;
2948
2949 if (ref->flags & REF_BAD_NAME) {
2950 warning(_("ignoring ref with broken name %s"), ref->name);
2951 return NULL;
2952 }
2953
2954 if (ref->flags & REF_ISBROKEN) {
2955 warning(_("ignoring broken ref %s"), ref->name);
2956 return NULL;
2957 }
2958
2959 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2960 kind = filter_ref_kind(filter, ref->name);
2961
2962 /*
2963 * Generally HEAD refs are printed with special description denoting a rebase,
2964 * detached state and so forth. This is useful when only printing the HEAD ref
2965 * But when it is being printed along with other root refs, it makes sense to
2966 * keep the formatting consistent. So we mask the type to act like a root ref.
2967 */
2968 if (filter->kind & FILTER_REFS_ROOT_REFS && kind == FILTER_REFS_DETACHED_HEAD)
2969 kind = FILTER_REFS_ROOT_REFS;
2970 else if (!(kind & filter->kind))
2971 return NULL;
2972
2973 if (!filter_pattern_match(filter, ref->name))
2974 return NULL;
2975
2976 if (filter_exclude_match(filter, ref->name))
2977 return NULL;
2978
2979 if (filter->points_at.nr && !match_points_at(&filter->points_at, ref->oid, ref->name))
2980 return NULL;
2981
2982 /*
2983 * A merge filter is applied on refs pointing to commits. Hence
2984 * obtain the commit using the 'oid' available and discard all
2985 * non-commits early. The actual filtering is done later.
2986 */
2987 if (filter->reachable_from || filter->unreachable_from ||
2988 filter->with_commit || filter->no_commit || filter->verbose) {
2989 commit = lookup_commit_reference_gently(the_repository, ref->oid, 1);
2990 if (!commit)
2991 return NULL;
2992 /* We perform the filtering for the '--contains' option... */
2993 if (filter->with_commit &&
2994 !commit_contains(filter, commit, filter->with_commit, &filter->internal.contains_cache))
2995 return NULL;
2996 /* ...or for the `--no-contains' option */
2997 if (filter->no_commit &&
2998 commit_contains(filter, commit, filter->no_commit, &filter->internal.no_contains_cache))
2999 return NULL;
3000 }
3001
3002 /*
3003 * We do not open the object yet; sort may only need refname
3004 * to do its job and the resulting list may yet to be pruned
3005 * by maxcount logic.
3006 */
3007 item = new_ref_array_item(ref->name, ref->oid, ref->peeled_oid);
3008 item->commit = commit;
3009 item->flag = ref->flags;
3010 item->kind = kind;
3011 item->symref = xstrdup_or_null(ref->target);
3012
3013 return item;
3014 }
3015
3016 struct ref_filter_cbdata {
3017 struct ref_array *array;
3018 struct ref_filter *filter;
3019 };
3020
3021 /*
3022 * A call-back given to for_each_ref(). Filter refs and keep them for
3023 * later object processing.
3024 */
3025 static int filter_one(const struct reference *ref, void *cb_data)
3026 {
3027 struct ref_filter_cbdata *ref_cbdata = cb_data;
3028 struct ref_array_item *item;
3029
3030 item = apply_ref_filter(ref, ref_cbdata->filter);
3031 if (item)
3032 ref_array_append(ref_cbdata->array, item);
3033
3034 return 0;
3035 }
3036
3037 /* Free memory allocated for a ref_array_item */
3038 static void free_array_item(struct ref_array_item *item)
3039 {
3040 free((char *)item->symref);
3041 if (item->value) {
3042 int i;
3043 for (i = 0; i < used_atom_cnt; i++)
3044 free((char *)item->value[i].s);
3045 free(item->value);
3046 }
3047 free(item->counts);
3048 free(item->is_base);
3049 free(item);
3050 }
3051
3052 struct ref_filter_and_format_cbdata {
3053 struct ref_filter *filter;
3054 struct ref_format *format;
3055
3056 struct ref_filter_and_format_internal {
3057 int count;
3058 } internal;
3059 };
3060
3061 static int filter_and_format_one(const struct reference *ref, void *cb_data)
3062 {
3063 struct ref_filter_and_format_cbdata *ref_cbdata = cb_data;
3064 struct ref_array_item *item;
3065 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3066
3067 item = apply_ref_filter(ref, ref_cbdata->filter);
3068 if (!item)
3069 return 0;
3070
3071 if (format_ref_array_item(item, ref_cbdata->format, &output, &err))
3072 die("%s", err.buf);
3073
3074 if (output.len || !ref_cbdata->format->array_opts.omit_empty) {
3075 fwrite(output.buf, 1, output.len, stdout);
3076 putchar('\n');
3077 }
3078
3079 strbuf_release(&output);
3080 strbuf_release(&err);
3081 free_array_item(item);
3082
3083 /*
3084 * Increment the running count of refs that match the filter. If
3085 * max_count is set and we've reached the max, stop the ref
3086 * iteration by returning a nonzero value.
3087 */
3088 if (ref_cbdata->format->array_opts.max_count &&
3089 ++ref_cbdata->internal.count >= ref_cbdata->format->array_opts.max_count)
3090 return 1;
3091
3092 return 0;
3093 }
3094
3095 /* Free all memory allocated for ref_array */
3096 void ref_array_clear(struct ref_array *array)
3097 {
3098 int i;
3099
3100 for (i = 0; i < array->nr; i++)
3101 free_array_item(array->items[i]);
3102 FREE_AND_NULL(array->items);
3103 array->nr = array->alloc = 0;
3104
3105 for (i = 0; i < used_atom_cnt; i++) {
3106 struct used_atom *atom = &used_atom[i];
3107 if (atom->atom_type == ATOM_HEAD)
3108 free(atom->u.head);
3109 else if (atom->atom_type == ATOM_DESCRIBE)
3110 strvec_clear(&atom->u.describe_args);
3111 else if (atom->atom_type == ATOM_ISBASE)
3112 free(atom->u.base.name);
3113 else if (atom->atom_type == ATOM_TRAILERS ||
3114 (atom->atom_type == ATOM_CONTENTS &&
3115 atom->u.contents.option == C_TRAILERS)) {
3116 struct ref_trailer_buf *tb = atom->u.contents.trailer_buf;
3117 if (tb) {
3118 string_list_clear(&tb->filter_list, 0);
3119 strbuf_release(&tb->sepbuf);
3120 strbuf_release(&tb->kvsepbuf);
3121 free(tb);
3122 }
3123 }
3124 free((char *)atom->name);
3125 }
3126 FREE_AND_NULL(used_atom);
3127 used_atom_cnt = 0;
3128
3129 if (ref_to_worktree_map.worktrees) {
3130 hashmap_clear_and_free(&(ref_to_worktree_map.map),
3131 struct ref_to_worktree_entry, ent);
3132 free_worktrees(ref_to_worktree_map.worktrees);
3133 ref_to_worktree_map.worktrees = NULL;
3134 }
3135
3136 FREE_AND_NULL(array->counts);
3137 }
3138
3139 #define EXCLUDE_REACHED 0
3140 #define INCLUDE_REACHED 1
3141 static void reach_filter(struct ref_array *array,
3142 struct commit_list **check_reachable,
3143 int include_reached)
3144 {
3145 size_t i, old_nr;
3146 struct commit **to_clear;
3147
3148 if (!*check_reachable)
3149 return;
3150
3151 CALLOC_ARRAY(to_clear, array->nr);
3152 for (i = 0; i < array->nr; i++) {
3153 struct ref_array_item *item = array->items[i];
3154 to_clear[i] = item->commit;
3155 }
3156
3157 tips_reachable_from_bases(the_repository,
3158 *check_reachable,
3159 to_clear, array->nr,
3160 UNINTERESTING);
3161
3162 old_nr = array->nr;
3163 array->nr = 0;
3164
3165 for (i = 0; i < old_nr; i++) {
3166 struct ref_array_item *item = array->items[i];
3167 struct commit *commit = item->commit;
3168
3169 int is_merged = !!(commit->object.flags & UNINTERESTING);
3170
3171 if (is_merged == include_reached)
3172 array->items[array->nr++] = array->items[i];
3173 else
3174 free_array_item(item);
3175 }
3176
3177 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
3178
3179 while (*check_reachable) {
3180 struct commit *merge_commit = pop_commit(check_reachable);
3181 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
3182 }
3183
3184 free(to_clear);
3185 }
3186
3187 void filter_ahead_behind(struct repository *r,
3188 struct ref_array *array)
3189 {
3190 struct commit **commits;
3191 size_t bases_nr, commits_nr;
3192
3193 if (!array->nr)
3194 return;
3195
3196 for (size_t i = bases_nr = 0; i < used_atom_cnt; i++) {
3197 if (used_atom[i].atom_type == ATOM_AHEADBEHIND)
3198 bases_nr++;
3199 }
3200 if (!bases_nr)
3201 return;
3202
3203 ALLOC_ARRAY(commits, st_add(bases_nr, array->nr));
3204 for (size_t i = 0, j = 0; i < used_atom_cnt; i++) {
3205 if (used_atom[i].atom_type == ATOM_AHEADBEHIND)
3206 commits[j++] = used_atom[i].u.base.commit;
3207 }
3208
3209 ALLOC_ARRAY(array->counts, st_mult(bases_nr, array->nr));
3210
3211 commits_nr = bases_nr;
3212 array->counts_nr = 0;
3213 for (size_t i = 0; i < array->nr; i++) {
3214 const char *name = array->items[i]->refname;
3215 commits[commits_nr] = lookup_commit_reference_by_name(name);
3216
3217 if (!commits[commits_nr])
3218 continue;
3219
3220 CALLOC_ARRAY(array->items[i]->counts, bases_nr);
3221 for (size_t j = 0; j < bases_nr; j++) {
3222 struct ahead_behind_count *count;
3223 count = &array->counts[array->counts_nr++];
3224 count->tip_index = commits_nr;
3225 count->base_index = j;
3226
3227 array->items[i]->counts[j] = count;
3228 }
3229 commits_nr++;
3230 }
3231
3232 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
3233 free(commits);
3234 }
3235
3236 void filter_is_base(struct repository *r,
3237 struct ref_array *array)
3238 {
3239 struct commit **bases;
3240 size_t bases_nr = 0, is_base_nr;
3241 struct ref_array_item **back_index;
3242
3243 if (!array->nr)
3244 return;
3245
3246 for (size_t i = is_base_nr = 0; i < used_atom_cnt; i++) {
3247 if (used_atom[i].atom_type == ATOM_ISBASE)
3248 is_base_nr++;
3249 }
3250 if (!is_base_nr)
3251 return;
3252
3253 CALLOC_ARRAY(back_index, array->nr);
3254 CALLOC_ARRAY(bases, array->nr);
3255
3256 for (size_t i = 0; i < array->nr; i++) {
3257 const char *name = array->items[i]->refname;
3258 struct commit *c = lookup_commit_reference_by_name_gently(name, 1);
3259
3260 CALLOC_ARRAY(array->items[i]->is_base, is_base_nr);
3261
3262 if (!c)
3263 continue;
3264
3265 back_index[bases_nr] = array->items[i];
3266 bases[bases_nr] = c;
3267 bases_nr++;
3268 }
3269
3270 for (size_t i = 0, j = 0; i < used_atom_cnt; i++) {
3271 struct commit *tip;
3272 int base_index;
3273
3274 if (used_atom[i].atom_type != ATOM_ISBASE)
3275 continue;
3276
3277 tip = used_atom[i].u.base.commit;
3278 base_index = get_branch_base_for_tip(r, tip, bases, bases_nr);
3279 if (base_index < 0)
3280 continue;
3281
3282 /* Store the string for use in output later. */
3283 back_index[base_index]->is_base[j++] = xstrdup(used_atom[i].u.base.name);
3284 }
3285
3286 free(back_index);
3287 free(bases);
3288 }
3289
3290 static int do_filter_refs(struct ref_filter *filter, unsigned int type, refs_for_each_cb fn, void *cb_data)
3291 {
3292 const char *prefix = NULL;
3293 int ret = 0;
3294
3295 filter->kind = type & FILTER_REFS_KIND_MASK;
3296
3297 init_contains_cache(&filter->internal.contains_cache);
3298 init_contains_cache(&filter->internal.no_contains_cache);
3299
3300 /* Simple per-ref filtering */
3301 if (!filter->kind)
3302 die("filter_refs: invalid type");
3303
3304 /*
3305 * For common cases where we need only branches or remotes or tags,
3306 * we only iterate through those refs. If a mix of refs is needed,
3307 * we iterate over all refs and filter out required refs with the help
3308 * of filter_ref_kind().
3309 */
3310 if (filter->kind == FILTER_REFS_BRANCHES)
3311 prefix = "refs/heads/";
3312 else if (filter->kind == FILTER_REFS_REMOTES)
3313 prefix = "refs/remotes/";
3314 else if (filter->kind == FILTER_REFS_TAGS)
3315 prefix = "refs/tags/";
3316
3317 if (prefix) {
3318 struct ref_iterator *iter;
3319
3320 iter = refs_ref_iterator_begin(get_main_ref_store(the_repository),
3321 "", NULL, 0, 0);
3322
3323 if (filter->start_after)
3324 ret = start_ref_iterator_after(iter, filter->start_after);
3325 else
3326 ret = ref_iterator_seek(iter, prefix,
3327 REF_ITERATOR_SEEK_SET_PREFIX);
3328
3329 if (!ret)
3330 ret = do_for_each_ref_iterator(iter, fn, cb_data);
3331 } else if (filter->kind & FILTER_REFS_REGULAR) {
3332 ret = for_each_fullref_in_pattern(filter, fn, cb_data);
3333 }
3334
3335 /*
3336 * When printing all ref types, HEAD is already included,
3337 * so we don't want to print HEAD again.
3338 */
3339 if (!ret && !(filter->kind & FILTER_REFS_ROOT_REFS) &&
3340 (filter->kind & FILTER_REFS_DETACHED_HEAD))
3341 refs_head_ref(get_main_ref_store(the_repository), fn,
3342 cb_data);
3343
3344
3345 clear_contains_cache(&filter->internal.contains_cache);
3346 clear_contains_cache(&filter->internal.no_contains_cache);
3347
3348 return ret;
3349 }
3350
3351 /*
3352 * API for filtering a set of refs. Based on the type of refs the user
3353 * has requested, we iterate through those refs and apply filters
3354 * as per the given ref_filter structure and finally store the
3355 * filtered refs in the ref_array structure.
3356 */
3357 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
3358 {
3359 struct ref_filter_cbdata ref_cbdata;
3360 int save_commit_buffer_orig;
3361 int ret = 0;
3362
3363 ref_cbdata.array = array;
3364 ref_cbdata.filter = filter;
3365
3366 save_commit_buffer_orig = save_commit_buffer;
3367 save_commit_buffer = 0;
3368
3369 ret = do_filter_refs(filter, type, filter_one, &ref_cbdata);
3370
3371 /* Filters that need revision walking */
3372 reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);
3373 reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);
3374
3375 save_commit_buffer = save_commit_buffer_orig;
3376 return ret;
3377 }
3378
3379 struct ref_sorting {
3380 struct ref_sorting *next;
3381 int atom; /* index into used_atom array (internal) */
3382 enum ref_sorting_order sort_flags;
3383 };
3384
3385 static inline int can_do_iterative_format(struct ref_filter *filter,
3386 struct ref_sorting *sorting)
3387 {
3388 /*
3389 * Reference backends sort patterns lexicographically by refname, so if
3390 * the sorting options ask for exactly that we are able to do iterative
3391 * formatting.
3392 *
3393 * Note that we do not have to worry about multiple name patterns,
3394 * either. Those get sorted and deduplicated eventually in
3395 * `refs_for_each_fullref_in_prefixes()`, so we return names in the
3396 * correct ordering here, too.
3397 */
3398 if (sorting && (sorting->next ||
3399 sorting->sort_flags ||
3400 used_atom[sorting->atom].atom_type != ATOM_REFNAME))
3401 return 0;
3402
3403 /*
3404 * Filtering & formatting results within a single ref iteration
3405 * callback is not compatible with options that require
3406 * post-processing a filtered ref_array. These include:
3407 * - filtering on reachability
3408 * - including ahead-behind information in the formatted output
3409 */
3410 for (size_t i = 0; i < used_atom_cnt; i++) {
3411 if (used_atom[i].atom_type == ATOM_AHEADBEHIND)
3412 return 0;
3413 if (used_atom[i].atom_type == ATOM_ISBASE)
3414 return 0;
3415 }
3416 return !(filter->reachable_from || filter->unreachable_from);
3417 }
3418
3419 void filter_and_format_refs(struct ref_filter *filter, unsigned int type,
3420 struct ref_sorting *sorting,
3421 struct ref_format *format)
3422 {
3423 if (can_do_iterative_format(filter, sorting)) {
3424 int save_commit_buffer_orig;
3425 struct ref_filter_and_format_cbdata ref_cbdata = {
3426 .filter = filter,
3427 .format = format,
3428 };
3429
3430 save_commit_buffer_orig = save_commit_buffer;
3431 save_commit_buffer = 0;
3432
3433 do_filter_refs(filter, type, filter_and_format_one, &ref_cbdata);
3434
3435 save_commit_buffer = save_commit_buffer_orig;
3436 } else {
3437 struct ref_array array = { 0 };
3438 filter_refs(&array, filter, type);
3439 filter_ahead_behind(the_repository, &array);
3440 filter_is_base(the_repository, &array);
3441 ref_array_sort(sorting, &array);
3442 print_formatted_ref_array(&array, format);
3443 ref_array_clear(&array);
3444 }
3445 }
3446
3447 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
3448 {
3449 if (!(a->kind ^ b->kind))
3450 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
3451 if (a->kind & FILTER_REFS_DETACHED_HEAD)
3452 return -1;
3453 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
3454 return 1;
3455 BUG("should have died in the xor check above");
3456 return 0;
3457 }
3458
3459 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
3460 {
3461 const char *s1 = vs1, *s2 = vs2;
3462 const char *end = s1 + n;
3463
3464 for (; s1 < end; s1++, s2++) {
3465 int diff = tolower(*s1) - tolower(*s2);
3466 if (diff)
3467 return diff;
3468 }
3469 return 0;
3470 }
3471
3472 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
3473 {
3474 struct atom_value *va, *vb;
3475 int cmp;
3476 int cmp_detached_head = 0;
3477 cmp_type cmp_type = used_atom[s->atom].type;
3478 struct strbuf err = STRBUF_INIT;
3479
3480 if (get_ref_atom_value(a, s->atom, &va, &err))
3481 die("%s", err.buf);
3482 if (get_ref_atom_value(b, s->atom, &vb, &err))
3483 die("%s", err.buf);
3484 strbuf_release(&err);
3485 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
3486 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
3487 cmp = compare_detached_head(a, b);
3488 cmp_detached_head = 1;
3489 } else if (s->sort_flags & REF_SORTING_VERSION) {
3490 cmp = versioncmp(va->s, vb->s);
3491 } else if (cmp_type == FIELD_STR) {
3492 if (va->s_size < 0 && vb->s_size < 0) {
3493 int (*cmp_fn)(const char *, const char *);
3494 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3495 ? strcasecmp : strcmp;
3496 cmp = cmp_fn(va->s, vb->s);
3497 } else {
3498 size_t a_size = va->s_size < 0 ?
3499 strlen(va->s) : va->s_size;
3500 size_t b_size = vb->s_size < 0 ?
3501 strlen(vb->s) : vb->s_size;
3502 int (*cmp_fn)(const void *, const void *, size_t);
3503 cmp_fn = s->sort_flags & REF_SORTING_ICASE
3504 ? memcasecmp : memcmp;
3505
3506 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
3507 a_size : b_size);
3508 if (!cmp) {
3509 if (a_size > b_size)
3510 cmp = 1;
3511 else if (a_size < b_size)
3512 cmp = -1;
3513 }
3514 }
3515 } else {
3516 if (va->value < vb->value)
3517 cmp = -1;
3518 else if (va->value == vb->value)
3519 cmp = 0;
3520 else
3521 cmp = 1;
3522 }
3523
3524 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
3525 ? -cmp : cmp;
3526 }
3527
3528 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
3529 {
3530 struct ref_array_item *a = *((struct ref_array_item **)a_);
3531 struct ref_array_item *b = *((struct ref_array_item **)b_);
3532 struct ref_sorting *s;
3533
3534 for (s = ref_sorting; s; s = s->next) {
3535 int cmp = cmp_ref_sorting(s, a, b);
3536 if (cmp)
3537 return cmp;
3538 }
3539 s = ref_sorting;
3540 return s && s->sort_flags & REF_SORTING_ICASE ?
3541 strcasecmp(a->refname, b->refname) :
3542 strcmp(a->refname, b->refname);
3543 }
3544
3545 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
3546 unsigned int mask, int on)
3547 {
3548 for (; sorting; sorting = sorting->next) {
3549 if (on)
3550 sorting->sort_flags |= mask;
3551 else
3552 sorting->sort_flags &= ~mask;
3553 }
3554 }
3555
3556 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
3557 {
3558 if (sorting)
3559 QSORT_S(array->items, array->nr, compare_refs, sorting);
3560 }
3561
3562 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
3563 {
3564 struct strbuf *s = &state->stack->output;
3565
3566 while (*cp && (!ep || cp < ep)) {
3567 if (*cp == '%') {
3568 if (cp[1] == '%')
3569 cp++;
3570 else {
3571 int ch = hex2chr(cp + 1);
3572 if (0 <= ch) {
3573 strbuf_addch(s, ch);
3574 cp += 3;
3575 continue;
3576 }
3577 }
3578 }
3579 strbuf_addch(s, *cp);
3580 cp++;
3581 }
3582 }
3583
3584 int format_ref_array_item(struct ref_array_item *info,
3585 struct ref_format *format,
3586 struct strbuf *final_buf,
3587 struct strbuf *error_buf)
3588 {
3589 const char *cp, *sp, *ep;
3590 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
3591
3592 state.quote_style = format->quote_style;
3593 push_stack_element(&state.stack);
3594
3595 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
3596 struct atom_value *atomv;
3597 int pos;
3598
3599 ep = strchr(sp, ')');
3600 if (cp < sp)
3601 append_literal(cp, sp, &state);
3602 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
3603 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
3604 atomv->handler(atomv, &state, error_buf)) {
3605 pop_stack_element(&state.stack);
3606 return -1;
3607 }
3608 }
3609 if (*cp) {
3610 sp = cp + strlen(cp);
3611 append_literal(cp, sp, &state);
3612 }
3613 if (format->need_color_reset_at_eol) {
3614 struct atom_value resetv = ATOM_VALUE_INIT;
3615 resetv.s = GIT_COLOR_RESET;
3616 if (append_atom(&resetv, &state, error_buf)) {
3617 pop_stack_element(&state.stack);
3618 return -1;
3619 }
3620 }
3621 if (state.stack->prev) {
3622 pop_stack_element(&state.stack);
3623 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
3624 }
3625 strbuf_addbuf(final_buf, &state.stack->output);
3626 pop_stack_element(&state.stack);
3627 return 0;
3628 }
3629
3630 void print_formatted_ref_array(struct ref_array *array, struct ref_format *format)
3631 {
3632 int total;
3633 struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;
3634
3635 total = format->array_opts.max_count;
3636 if (!total || array->nr < total)
3637 total = array->nr;
3638 for (int i = 0; i < total; i++) {
3639 strbuf_reset(&err);
3640 strbuf_reset(&output);
3641 if (format_ref_array_item(array->items[i], format, &output, &err))
3642 die("%s", err.buf);
3643 if (output.len || !format->array_opts.omit_empty) {
3644 fwrite(output.buf, 1, output.len, stdout);
3645 putchar('\n');
3646 }
3647 }
3648
3649 strbuf_release(&err);
3650 strbuf_release(&output);
3651 }
3652
3653 void pretty_print_ref(const char *name, const struct object_id *oid,
3654 const struct object_id *peeled_oid,
3655 struct ref_format *format)
3656 {
3657 struct ref_array_item *ref_item;
3658 struct strbuf output = STRBUF_INIT;
3659 struct strbuf err = STRBUF_INIT;
3660
3661 ref_item = new_ref_array_item(name, oid, peeled_oid);
3662 ref_item->kind = ref_kind_from_refname(name);
3663 if (format_ref_array_item(ref_item, format, &output, &err))
3664 die("%s", err.buf);
3665 fwrite(output.buf, 1, output.len, stdout);
3666 putchar('\n');
3667
3668 strbuf_release(&err);
3669 strbuf_release(&output);
3670 free_array_item(ref_item);
3671 }
3672
3673 static int parse_sorting_atom(const char *atom)
3674 {
3675 /*
3676 * This parses an atom using a dummy ref_format, since we don't
3677 * actually care about the formatting details.
3678 */
3679 struct ref_format dummy = REF_FORMAT_INIT;
3680 const char *end = atom + strlen(atom);
3681 struct strbuf err = STRBUF_INIT;
3682 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
3683 if (res < 0)
3684 die("%s", err.buf);
3685 strbuf_release(&err);
3686 return res;
3687 }
3688
3689 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
3690 {
3691 struct ref_sorting *s;
3692
3693 CALLOC_ARRAY(s, 1);
3694 s->next = *sorting_tail;
3695 *sorting_tail = s;
3696
3697 if (*arg == '-') {
3698 s->sort_flags |= REF_SORTING_REVERSE;
3699 arg++;
3700 }
3701 if (skip_prefix(arg, "version:", &arg) ||
3702 skip_prefix(arg, "v:", &arg))
3703 s->sort_flags |= REF_SORTING_VERSION;
3704 s->atom = parse_sorting_atom(arg);
3705 }
3706
3707 struct ref_sorting *ref_sorting_options(struct string_list *options)
3708 {
3709 struct string_list_item *item;
3710 struct ref_sorting *sorting = NULL, **tail = &sorting;
3711
3712 if (options->nr) {
3713 for_each_string_list_item(item, options)
3714 parse_ref_sorting(tail, item->string);
3715 }
3716
3717 /*
3718 * From here on, the ref_sorting list should be used to talk
3719 * about the sort order used for the output. The caller
3720 * should not touch the string form anymore.
3721 */
3722 string_list_clear(options, 0);
3723 return sorting;
3724 }
3725
3726 void ref_sorting_release(struct ref_sorting *sorting)
3727 {
3728 while (sorting) {
3729 struct ref_sorting *next = sorting->next;
3730 free(sorting);
3731 sorting = next;
3732 }
3733 }
3734
3735 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
3736 {
3737 struct ref_filter *rf = opt->value;
3738 struct object_id oid;
3739 struct commit *merge_commit;
3740
3741 BUG_ON_OPT_NEG(unset);
3742
3743 if (repo_get_oid(the_repository, arg, &oid))
3744 die(_("malformed object name %s"), arg);
3745
3746 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
3747
3748 if (!merge_commit)
3749 return error(_("option `%s' must point to a commit"), opt->long_name);
3750
3751 if (starts_with(opt->long_name, "no"))
3752 commit_list_insert(merge_commit, &rf->unreachable_from);
3753 else
3754 commit_list_insert(merge_commit, &rf->reachable_from);
3755
3756 return 0;
3757 }
3758
3759 void ref_filter_init(struct ref_filter *filter)
3760 {
3761 struct ref_filter blank = REF_FILTER_INIT;
3762 memcpy(filter, &blank, sizeof(blank));
3763 }
3764
3765 void ref_filter_clear(struct ref_filter *filter)
3766 {
3767 strvec_clear(&filter->exclude);
3768 oid_array_clear(&filter->points_at);
3769 commit_list_free(filter->with_commit);
3770 commit_list_free(filter->no_commit);
3771 commit_list_free(filter->reachable_from);
3772 commit_list_free(filter->unreachable_from);
3773 ref_filter_init(filter);
3774 }