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