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