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