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