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