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