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