object: add object_array initializer helper function
[git/gitster.git] / ref-filter.c
blob10aab14f030a63b452090002cd47caecb4b4671c
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 "trailer.h"
23 #include "wt-status.h"
24 #include "commit-slab.h"
25 #include "commit-graph.h"
26 #include "commit-reach.h"
27 #include "worktree.h"
28 #include "hashmap.h"
29 #include "strvec.h"
31 static struct ref_msg {
32 const char *gone;
33 const char *ahead;
34 const char *behind;
35 const char *ahead_behind;
36 } msgs = {
37 /* Untranslated plumbing messages: */
38 "gone",
39 "ahead %d",
40 "behind %d",
41 "ahead %d, behind %d"
44 void setup_ref_filter_porcelain_msg(void)
46 msgs.gone = _("gone");
47 msgs.ahead = _("ahead %d");
48 msgs.behind = _("behind %d");
49 msgs.ahead_behind = _("ahead %d, behind %d");
52 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
53 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
54 typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
56 struct align {
57 align_type position;
58 unsigned int width;
61 struct if_then_else {
62 cmp_status cmp_status;
63 const char *str;
64 unsigned int then_atom_seen : 1,
65 else_atom_seen : 1,
66 condition_satisfied : 1;
69 struct refname_atom {
70 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
71 int lstrip, rstrip;
74 static struct ref_trailer_buf {
75 struct string_list filter_list;
76 struct strbuf sepbuf;
77 struct strbuf kvsepbuf;
78 } ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};
80 static struct expand_data {
81 struct object_id oid;
82 enum object_type type;
83 unsigned long size;
84 off_t disk_size;
85 struct object_id delta_base_oid;
86 void *content;
88 struct object_info info;
89 } oi, oi_deref;
91 struct ref_to_worktree_entry {
92 struct hashmap_entry ent;
93 struct worktree *wt; /* key is wt->head_ref */
96 static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,
97 const struct hashmap_entry *eptr,
98 const struct hashmap_entry *kptr,
99 const void *keydata_aka_refname)
101 const struct ref_to_worktree_entry *e, *k;
103 e = container_of(eptr, const struct ref_to_worktree_entry, ent);
104 k = container_of(kptr, const struct ref_to_worktree_entry, ent);
106 return strcmp(e->wt->head_ref,
107 keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);
110 static struct ref_to_worktree_map {
111 struct hashmap map;
112 struct worktree **worktrees;
113 } ref_to_worktree_map;
116 * The enum atom_type is used as the index of valid_atom array.
117 * In the atom parsing stage, it will be passed to used_atom.atom_type
118 * as the identifier of the atom type. We can check the type of used_atom
119 * entry by `if (used_atom[i].atom_type == ATOM_*)`.
121 enum atom_type {
122 ATOM_REFNAME,
123 ATOM_OBJECTTYPE,
124 ATOM_OBJECTSIZE,
125 ATOM_OBJECTNAME,
126 ATOM_DELTABASE,
127 ATOM_TREE,
128 ATOM_PARENT,
129 ATOM_NUMPARENT,
130 ATOM_OBJECT,
131 ATOM_TYPE,
132 ATOM_TAG,
133 ATOM_AUTHOR,
134 ATOM_AUTHORNAME,
135 ATOM_AUTHOREMAIL,
136 ATOM_AUTHORDATE,
137 ATOM_COMMITTER,
138 ATOM_COMMITTERNAME,
139 ATOM_COMMITTEREMAIL,
140 ATOM_COMMITTERDATE,
141 ATOM_TAGGER,
142 ATOM_TAGGERNAME,
143 ATOM_TAGGEREMAIL,
144 ATOM_TAGGERDATE,
145 ATOM_CREATOR,
146 ATOM_CREATORDATE,
147 ATOM_SUBJECT,
148 ATOM_BODY,
149 ATOM_TRAILERS,
150 ATOM_CONTENTS,
151 ATOM_RAW,
152 ATOM_UPSTREAM,
153 ATOM_PUSH,
154 ATOM_SYMREF,
155 ATOM_FLAG,
156 ATOM_HEAD,
157 ATOM_COLOR,
158 ATOM_WORKTREEPATH,
159 ATOM_ALIGN,
160 ATOM_END,
161 ATOM_IF,
162 ATOM_THEN,
163 ATOM_ELSE,
164 ATOM_REST,
165 ATOM_AHEADBEHIND,
169 * An atom is a valid field atom listed below, possibly prefixed with
170 * a "*" to denote deref_tag().
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.
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;
223 * Expand string, append it to strbuf *sb, then return error code ret.
224 * Allow to save few lines of code.
226 __attribute__((format (printf, 3, 4)))
227 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
229 va_list ap;
230 va_start(ap, fmt);
231 strbuf_vaddf(sb, fmt, ap);
232 va_end(ap);
233 return ret;
236 static int err_no_arg(struct strbuf *sb, const char *name)
238 size_t namelen = strchrnul(name, ':') - name;
239 strbuf_addf(sb, _("%%(%.*s) does not take arguments"),
240 (int)namelen, name);
241 return -1;
244 static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)
246 size_t namelen = strchrnul(name, ':') - name;
247 strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),
248 (int)namelen, name, arg);
249 return -1;
252 static int color_atom_parser(struct ref_format *format, struct used_atom *atom,
253 const char *color_value, struct strbuf *err)
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);
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.
264 if (!want_color(format->use_color))
265 color_parse("", atom->u.color);
266 return 0;
269 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
270 const char *name, struct strbuf *err)
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;
290 static int remote_ref_atom_parser(struct ref_format *format UNUSED,
291 struct used_atom *atom,
292 const char *arg, struct strbuf *err)
294 struct string_list params = STRING_LIST_INIT_DUP;
295 int i;
297 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
298 atom->u.remote_ref.push = 1;
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);
306 atom->u.remote_ref.nobracket = 0;
307 string_list_split(&params, arg, ',', -1);
309 for (i = 0; i < params.nr; i++) {
310 const char *s = params.items[i].string;
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;
334 string_list_clear(&params, 0);
335 return 0;
338 static int objecttype_atom_parser(struct ref_format *format UNUSED,
339 struct used_atom *atom,
340 const char *arg, struct strbuf *err)
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;
351 static int objectsize_atom_parser(struct ref_format *format UNUSED,
352 struct used_atom *atom,
353 const char *arg, struct strbuf *err)
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;
372 static int deltabase_atom_parser(struct ref_format *format UNUSED,
373 struct used_atom *atom,
374 const char *arg, struct strbuf *err)
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;
385 static int body_atom_parser(struct ref_format *format UNUSED,
386 struct used_atom *atom,
387 const char *arg, struct strbuf *err)
389 if (arg)
390 return err_no_arg(err, "body");
391 atom->u.contents.option = C_BODY_DEP;
392 return 0;
395 static int subject_atom_parser(struct ref_format *format UNUSED,
396 struct used_atom *atom,
397 const char *arg, struct strbuf *err)
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;
408 static int trailers_atom_parser(struct ref_format *format UNUSED,
409 struct used_atom *atom,
410 const char *arg, struct strbuf *err)
412 atom->u.contents.trailer_opts.no_divider = 1;
414 if (arg) {
415 const char *argbuf = xstrfmt("%s)", arg);
416 char *invalid_arg = NULL;
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;
431 atom->u.contents.option = C_TRAILERS;
432 return 0;
435 static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,
436 const char *arg, struct strbuf *err)
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;
463 static int raw_atom_parser(struct ref_format *format UNUSED,
464 struct used_atom *atom,
465 const char *arg, struct strbuf *err)
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;
476 static int oid_atom_parser(struct ref_format *format UNUSED,
477 struct used_atom *atom,
478 const char *arg, struct strbuf *err)
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;
496 static int person_email_atom_parser(struct ref_format *format UNUSED,
497 struct used_atom *atom,
498 const char *arg, struct strbuf *err)
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;
511 static int refname_atom_parser(struct ref_format *format UNUSED,
512 struct used_atom *atom,
513 const char *arg, struct strbuf *err)
515 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
518 static align_type parse_align_position(const char *s)
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;
529 static int align_atom_parser(struct ref_format *format UNUSED,
530 struct used_atom *atom,
531 const char *arg, struct strbuf *err)
533 struct align *align = &atom->u.align;
534 struct string_list params = STRING_LIST_INIT_DUP;
535 int i;
536 unsigned int width = ~0U;
538 if (!arg)
539 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
541 align->position = ALIGN_LEFT;
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;
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;
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;
562 } else if (!strtoul_ui(s, 10, &width))
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;
573 if (width == ~0U) {
574 string_list_clear(&params, 0);
575 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
577 align->width = width;
578 string_list_clear(&params, 0);
579 return 0;
582 static int if_atom_parser(struct ref_format *format UNUSED,
583 struct used_atom *atom,
584 const char *arg, struct strbuf *err)
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;
598 static int rest_atom_parser(struct ref_format *format,
599 struct used_atom *atom UNUSED,
600 const char *arg, struct strbuf *err)
602 if (arg)
603 return err_no_arg(err, "rest");
604 return 0;
607 static int ahead_behind_atom_parser(struct ref_format *format, struct used_atom *atom,
608 const char *arg, struct strbuf *err)
610 struct string_list_item *item;
612 if (!arg)
613 return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));
615 item = string_list_append(&format->bases, arg);
616 item->util = lookup_commit_reference_by_name(arg);
617 if (!item->util)
618 die("failed to find '%s'", arg);
620 return 0;
623 static int head_atom_parser(struct ref_format *format UNUSED,
624 struct used_atom *atom,
625 const char *arg, struct strbuf *err)
627 if (arg)
628 return err_no_arg(err, "HEAD");
629 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
630 return 0;
633 static struct {
634 const char *name;
635 info_source source;
636 cmp_type cmp_type;
637 int (*parser)(struct ref_format *format, struct used_atom *atom,
638 const char *arg, struct strbuf *err);
639 } valid_atom[] = {
640 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
641 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
642 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
643 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
644 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
645 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
646 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
647 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
648 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
649 [ATOM_TYPE] = { "type", SOURCE_OBJ },
650 [ATOM_TAG] = { "tag", SOURCE_OBJ },
651 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
652 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
653 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
654 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
655 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
656 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
657 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
658 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
659 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
660 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
661 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
662 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
663 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
664 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
665 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
666 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
667 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
668 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
669 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
670 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
671 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
672 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
673 [ATOM_FLAG] = { "flag", SOURCE_NONE },
674 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
675 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
676 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
677 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
678 [ATOM_END] = { "end", SOURCE_NONE },
679 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
680 [ATOM_THEN] = { "then", SOURCE_NONE },
681 [ATOM_ELSE] = { "else", SOURCE_NONE },
682 [ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },
683 [ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },
685 * Please update $__git_ref_fieldlist in git-completion.bash
686 * when you add new atoms
690 #define REF_FORMATTING_STATE_INIT { 0 }
692 struct ref_formatting_stack {
693 struct ref_formatting_stack *prev;
694 struct strbuf output;
695 void (*at_end)(struct ref_formatting_stack **stack);
696 void *at_end_data;
699 struct ref_formatting_state {
700 int quote_style;
701 struct ref_formatting_stack *stack;
704 struct atom_value {
705 const char *s;
706 ssize_t s_size;
707 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
708 struct strbuf *err);
709 uintmax_t value; /* used for sorting when not FIELD_STR */
710 struct used_atom *atom;
713 #define ATOM_SIZE_UNSPECIFIED (-1)
715 #define ATOM_VALUE_INIT { \
716 .s_size = ATOM_SIZE_UNSPECIFIED \
720 * Used to parse format string and sort specifiers
722 static int parse_ref_filter_atom(struct ref_format *format,
723 const char *atom, const char *ep,
724 struct strbuf *err)
726 const char *sp;
727 const char *arg;
728 int i, at, atom_len;
730 sp = atom;
731 if (*sp == '*' && sp < ep)
732 sp++; /* deref */
733 if (ep <= sp)
734 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
735 (int)(ep-atom), atom);
738 * If the atom name has a colon, strip it and everything after
739 * it off - it specifies the format for this entry, and
740 * shouldn't be used for checking against the valid_atom
741 * table.
743 arg = memchr(sp, ':', ep - sp);
744 atom_len = (arg ? arg : ep) - sp;
746 /* Do we have the atom already used elsewhere? */
747 for (i = 0; i < used_atom_cnt; i++) {
748 int len = strlen(used_atom[i].name);
749 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
750 return i;
753 /* Is the atom a valid one? */
754 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
755 int len = strlen(valid_atom[i].name);
756 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
757 break;
760 if (ARRAY_SIZE(valid_atom) <= i)
761 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
762 (int)(ep-atom), atom);
763 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
764 return strbuf_addf_ret(err, -1,
765 _("not a git repository, but the field '%.*s' requires access to object data"),
766 (int)(ep-atom), atom);
768 /* Add it in, including the deref prefix */
769 at = used_atom_cnt;
770 used_atom_cnt++;
771 REALLOC_ARRAY(used_atom, used_atom_cnt);
772 used_atom[at].atom_type = i;
773 used_atom[at].name = xmemdupz(atom, ep - atom);
774 used_atom[at].type = valid_atom[i].cmp_type;
775 used_atom[at].source = valid_atom[i].source;
776 if (used_atom[at].source == SOURCE_OBJ) {
777 if (*atom == '*')
778 oi_deref.info.contentp = &oi_deref.content;
779 else
780 oi.info.contentp = &oi.content;
782 if (arg) {
783 arg = used_atom[at].name + (arg - atom) + 1;
784 if (!*arg) {
786 * Treat empty sub-arguments list as NULL (i.e.,
787 * "%(atom:)" is equivalent to "%(atom)").
789 arg = NULL;
792 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
793 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
794 return -1;
795 if (*atom == '*')
796 need_tagged = 1;
797 if (i == ATOM_SYMREF)
798 need_symref = 1;
799 return at;
802 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
804 switch (quote_style) {
805 case QUOTE_NONE:
806 if (len < 0)
807 strbuf_addstr(s, str);
808 else
809 strbuf_add(s, str, len);
810 break;
811 case QUOTE_SHELL:
812 sq_quote_buf(s, str);
813 break;
814 case QUOTE_PERL:
815 if (len < 0)
816 perl_quote_buf(s, str);
817 else
818 perl_quote_buf_with_len(s, str, len);
819 break;
820 case QUOTE_PYTHON:
821 python_quote_buf(s, str);
822 break;
823 case QUOTE_TCL:
824 tcl_quote_buf(s, str);
825 break;
829 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
830 struct strbuf *err UNUSED)
833 * Quote formatting is only done when the stack has a single
834 * element. Otherwise quote formatting is done on the
835 * element's entire output strbuf when the %(end) atom is
836 * encountered.
838 if (!state->stack->prev)
839 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
840 else if (v->s_size < 0)
841 strbuf_addstr(&state->stack->output, v->s);
842 else
843 strbuf_add(&state->stack->output, v->s, v->s_size);
844 return 0;
847 static void push_stack_element(struct ref_formatting_stack **stack)
849 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
851 strbuf_init(&s->output, 0);
852 s->prev = *stack;
853 *stack = s;
856 static void pop_stack_element(struct ref_formatting_stack **stack)
858 struct ref_formatting_stack *current = *stack;
859 struct ref_formatting_stack *prev = current->prev;
861 if (prev)
862 strbuf_addbuf(&prev->output, &current->output);
863 strbuf_release(&current->output);
864 free(current);
865 *stack = prev;
868 static void end_align_handler(struct ref_formatting_stack **stack)
870 struct ref_formatting_stack *cur = *stack;
871 struct align *align = (struct align *)cur->at_end_data;
872 struct strbuf s = STRBUF_INIT;
874 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
875 strbuf_swap(&cur->output, &s);
876 strbuf_release(&s);
879 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
880 struct strbuf *err UNUSED)
882 struct ref_formatting_stack *new_stack;
884 push_stack_element(&state->stack);
885 new_stack = state->stack;
886 new_stack->at_end = end_align_handler;
887 new_stack->at_end_data = &atomv->atom->u.align;
888 return 0;
891 static void if_then_else_handler(struct ref_formatting_stack **stack)
893 struct ref_formatting_stack *cur = *stack;
894 struct ref_formatting_stack *prev = cur->prev;
895 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
897 if (!if_then_else->then_atom_seen)
898 die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");
900 if (if_then_else->else_atom_seen) {
902 * There is an %(else) atom: we need to drop one state from the
903 * stack, either the %(else) branch if the condition is satisfied, or
904 * the %(then) branch if it isn't.
906 if (if_then_else->condition_satisfied) {
907 strbuf_reset(&cur->output);
908 pop_stack_element(&cur);
909 } else {
910 strbuf_swap(&cur->output, &prev->output);
911 strbuf_reset(&cur->output);
912 pop_stack_element(&cur);
914 } else if (!if_then_else->condition_satisfied) {
916 * No %(else) atom: just drop the %(then) branch if the
917 * condition is not satisfied.
919 strbuf_reset(&cur->output);
922 *stack = cur;
923 free(if_then_else);
926 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
927 struct strbuf *err UNUSED)
929 struct ref_formatting_stack *new_stack;
930 struct if_then_else *if_then_else = xcalloc(1,
931 sizeof(struct if_then_else));
933 if_then_else->str = atomv->atom->u.if_then_else.str;
934 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
936 push_stack_element(&state->stack);
937 new_stack = state->stack;
938 new_stack->at_end = if_then_else_handler;
939 new_stack->at_end_data = if_then_else;
940 return 0;
943 static int is_empty(struct strbuf *buf)
945 const char *cur = buf->buf;
946 const char *end = buf->buf + buf->len;
948 while (cur != end && (isspace(*cur)))
949 cur++;
951 return cur == end;
954 static int then_atom_handler(struct atom_value *atomv UNUSED,
955 struct ref_formatting_state *state,
956 struct strbuf *err)
958 struct ref_formatting_stack *cur = state->stack;
959 struct if_then_else *if_then_else = NULL;
960 size_t str_len = 0;
962 if (cur->at_end == if_then_else_handler)
963 if_then_else = (struct if_then_else *)cur->at_end_data;
964 if (!if_then_else)
965 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");
966 if (if_then_else->then_atom_seen)
967 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
968 if (if_then_else->else_atom_seen)
969 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
970 if_then_else->then_atom_seen = 1;
971 if (if_then_else->str)
972 str_len = strlen(if_then_else->str);
974 * If the 'equals' or 'notequals' attribute is used then
975 * perform the required comparison. If not, only non-empty
976 * strings satisfy the 'if' condition.
978 if (if_then_else->cmp_status == COMPARE_EQUAL) {
979 if (str_len == cur->output.len &&
980 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
981 if_then_else->condition_satisfied = 1;
982 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
983 if (str_len != cur->output.len ||
984 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
985 if_then_else->condition_satisfied = 1;
986 } else if (cur->output.len && !is_empty(&cur->output))
987 if_then_else->condition_satisfied = 1;
988 strbuf_reset(&cur->output);
989 return 0;
992 static int else_atom_handler(struct atom_value *atomv UNUSED,
993 struct ref_formatting_state *state,
994 struct strbuf *err)
996 struct ref_formatting_stack *prev = state->stack;
997 struct if_then_else *if_then_else = NULL;
999 if (prev->at_end == if_then_else_handler)
1000 if_then_else = (struct if_then_else *)prev->at_end_data;
1001 if (!if_then_else)
1002 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");
1003 if (!if_then_else->then_atom_seen)
1004 return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");
1005 if (if_then_else->else_atom_seen)
1006 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
1007 if_then_else->else_atom_seen = 1;
1008 push_stack_element(&state->stack);
1009 state->stack->at_end_data = prev->at_end_data;
1010 state->stack->at_end = prev->at_end;
1011 return 0;
1014 static int end_atom_handler(struct atom_value *atomv UNUSED,
1015 struct ref_formatting_state *state,
1016 struct strbuf *err)
1018 struct ref_formatting_stack *current = state->stack;
1019 struct strbuf s = STRBUF_INIT;
1021 if (!current->at_end)
1022 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
1023 current->at_end(&state->stack);
1025 /* Stack may have been popped within at_end(), hence reset the current pointer */
1026 current = state->stack;
1029 * Perform quote formatting when the stack element is that of
1030 * a supporting atom. If nested then perform quote formatting
1031 * only on the topmost supporting atom.
1033 if (!current->prev->prev) {
1034 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
1035 strbuf_swap(&current->output, &s);
1037 strbuf_release(&s);
1038 pop_stack_element(&state->stack);
1039 return 0;
1043 * In a format string, find the next occurrence of %(atom).
1045 static const char *find_next(const char *cp)
1047 while (*cp) {
1048 if (*cp == '%') {
1050 * %( is the start of an atom;
1051 * %% is a quoted per-cent.
1053 if (cp[1] == '(')
1054 return cp;
1055 else if (cp[1] == '%')
1056 cp++; /* skip over two % */
1057 /* otherwise this is a singleton, literal % */
1059 cp++;
1061 return NULL;
1064 static int reject_atom(enum atom_type atom_type)
1066 return atom_type == ATOM_REST;
1070 * Make sure the format string is well formed, and parse out
1071 * the used atoms.
1073 int verify_ref_format(struct ref_format *format)
1075 const char *cp, *sp;
1077 format->need_color_reset_at_eol = 0;
1078 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1079 struct strbuf err = STRBUF_INIT;
1080 const char *color, *ep = strchr(sp, ')');
1081 int at;
1083 if (!ep)
1084 return error(_("malformed format string %s"), sp);
1085 /* sp points at "%(" and ep points at the closing ")" */
1086 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1087 if (at < 0)
1088 die("%s", err.buf);
1089 if (reject_atom(used_atom[at].atom_type))
1090 die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);
1092 if ((format->quote_style == QUOTE_PYTHON ||
1093 format->quote_style == QUOTE_SHELL ||
1094 format->quote_style == QUOTE_TCL) &&
1095 used_atom[at].atom_type == ATOM_RAW &&
1096 used_atom[at].u.raw_data.option == RAW_BARE)
1097 die(_("--format=%.*s cannot be used with "
1098 "--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);
1099 cp = ep + 1;
1101 if (skip_prefix(used_atom[at].name, "color:", &color))
1102 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1103 strbuf_release(&err);
1105 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1106 format->need_color_reset_at_eol = 0;
1107 return 0;
1110 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1111 struct used_atom *atom)
1113 switch (atom->u.oid.option) {
1114 case O_FULL:
1115 return oid_to_hex(oid);
1116 case O_LENGTH:
1117 return repo_find_unique_abbrev(the_repository, oid,
1118 atom->u.oid.length);
1119 case O_SHORT:
1120 return repo_find_unique_abbrev(the_repository, oid,
1121 DEFAULT_ABBREV);
1122 default:
1123 BUG("unknown %%(%s) option", field);
1127 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1128 struct atom_value *v, struct used_atom *atom)
1130 if (starts_with(name, field)) {
1131 v->s = xstrdup(do_grab_oid(field, oid, atom));
1132 return 1;
1134 return 0;
1137 /* See grab_values */
1138 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1140 int i;
1142 for (i = 0; i < used_atom_cnt; i++) {
1143 const char *name = used_atom[i].name;
1144 enum atom_type atom_type = used_atom[i].atom_type;
1145 struct atom_value *v = &val[i];
1146 if (!!deref != (*name == '*'))
1147 continue;
1148 if (deref)
1149 name++;
1150 if (atom_type == ATOM_OBJECTTYPE)
1151 v->s = xstrdup(type_name(oi->type));
1152 else if (atom_type == ATOM_OBJECTSIZE) {
1153 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1154 v->value = oi->disk_size;
1155 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1156 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1157 v->value = oi->size;
1158 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1160 } else if (atom_type == ATOM_DELTABASE)
1161 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1162 else if (atom_type == ATOM_OBJECTNAME && deref)
1163 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1167 /* See grab_values */
1168 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1170 int i;
1171 struct tag *tag = (struct tag *) obj;
1173 for (i = 0; i < used_atom_cnt; i++) {
1174 const char *name = used_atom[i].name;
1175 enum atom_type atom_type = used_atom[i].atom_type;
1176 struct atom_value *v = &val[i];
1177 if (!!deref != (*name == '*'))
1178 continue;
1179 if (deref)
1180 name++;
1181 if (atom_type == ATOM_TAG)
1182 v->s = xstrdup(tag->tag);
1183 else if (atom_type == ATOM_TYPE && tag->tagged)
1184 v->s = xstrdup(type_name(tag->tagged->type));
1185 else if (atom_type == ATOM_OBJECT && tag->tagged)
1186 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1190 /* See grab_values */
1191 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1193 int i;
1194 struct commit *commit = (struct commit *) obj;
1196 for (i = 0; i < used_atom_cnt; i++) {
1197 const char *name = used_atom[i].name;
1198 enum atom_type atom_type = used_atom[i].atom_type;
1199 struct atom_value *v = &val[i];
1200 if (!!deref != (*name == '*'))
1201 continue;
1202 if (deref)
1203 name++;
1204 if (atom_type == ATOM_TREE &&
1205 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1206 continue;
1207 if (atom_type == ATOM_NUMPARENT) {
1208 v->value = commit_list_count(commit->parents);
1209 v->s = xstrfmt("%lu", (unsigned long)v->value);
1211 else if (atom_type == ATOM_PARENT) {
1212 struct commit_list *parents;
1213 struct strbuf s = STRBUF_INIT;
1214 for (parents = commit->parents; parents; parents = parents->next) {
1215 struct object_id *oid = &parents->item->object.oid;
1216 if (parents != commit->parents)
1217 strbuf_addch(&s, ' ');
1218 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1220 v->s = strbuf_detach(&s, NULL);
1225 static const char *find_wholine(const char *who, int wholen, const char *buf)
1227 const char *eol;
1228 while (*buf) {
1229 if (!strncmp(buf, who, wholen) &&
1230 buf[wholen] == ' ')
1231 return buf + wholen + 1;
1232 eol = strchr(buf, '\n');
1233 if (!eol)
1234 return "";
1235 eol++;
1236 if (*eol == '\n')
1237 return ""; /* end of header */
1238 buf = eol;
1240 return "";
1243 static const char *copy_line(const char *buf)
1245 const char *eol = strchrnul(buf, '\n');
1246 return xmemdupz(buf, eol - buf);
1249 static const char *copy_name(const char *buf)
1251 const char *cp;
1252 for (cp = buf; *cp && *cp != '\n'; cp++) {
1253 if (starts_with(cp, " <"))
1254 return xmemdupz(buf, cp - buf);
1256 return xstrdup("");
1259 static const char *copy_email(const char *buf, struct used_atom *atom)
1261 const char *email = strchr(buf, '<');
1262 const char *eoemail;
1263 if (!email)
1264 return xstrdup("");
1265 switch (atom->u.email_option.option) {
1266 case EO_RAW:
1267 eoemail = strchr(email, '>');
1268 if (eoemail)
1269 eoemail++;
1270 break;
1271 case EO_TRIM:
1272 email++;
1273 eoemail = strchr(email, '>');
1274 break;
1275 case EO_LOCALPART:
1276 email++;
1277 eoemail = strchr(email, '@');
1278 if (!eoemail)
1279 eoemail = strchr(email, '>');
1280 break;
1281 default:
1282 BUG("unknown email option");
1285 if (!eoemail)
1286 return xstrdup("");
1287 return xmemdupz(email, eoemail - email);
1290 static char *copy_subject(const char *buf, unsigned long len)
1292 struct strbuf sb = STRBUF_INIT;
1293 int i;
1295 for (i = 0; i < len; i++) {
1296 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1297 continue; /* ignore CR in CRLF */
1299 if (buf[i] == '\n')
1300 strbuf_addch(&sb, ' ');
1301 else
1302 strbuf_addch(&sb, buf[i]);
1304 return strbuf_detach(&sb, NULL);
1307 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1309 const char *eoemail = strstr(buf, "> ");
1310 char *zone;
1311 timestamp_t timestamp;
1312 long tz;
1313 struct date_mode date_mode = DATE_MODE_INIT;
1314 const char *formatp;
1317 * We got here because atomname ends in "date" or "date<something>";
1318 * it's not possible that <something> is not ":<format>" because
1319 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1320 * ":" means no format is specified, and use the default.
1322 formatp = strchr(atomname, ':');
1323 if (formatp) {
1324 formatp++;
1325 parse_date_format(formatp, &date_mode);
1328 if (!eoemail)
1329 goto bad;
1330 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1331 if (timestamp == TIME_MAX)
1332 goto bad;
1333 tz = strtol(zone, NULL, 10);
1334 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1335 goto bad;
1336 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1337 v->value = timestamp;
1338 date_mode_release(&date_mode);
1339 return;
1340 bad:
1341 v->s = xstrdup("");
1342 v->value = 0;
1345 /* See grab_values */
1346 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1348 int i;
1349 int wholen = strlen(who);
1350 const char *wholine = NULL;
1352 for (i = 0; i < used_atom_cnt; i++) {
1353 const char *name = used_atom[i].name;
1354 struct atom_value *v = &val[i];
1355 if (!!deref != (*name == '*'))
1356 continue;
1357 if (deref)
1358 name++;
1359 if (strncmp(who, name, wholen))
1360 continue;
1361 if (name[wholen] != 0 &&
1362 strcmp(name + wholen, "name") &&
1363 !starts_with(name + wholen, "email") &&
1364 !starts_with(name + wholen, "date"))
1365 continue;
1366 if (!wholine)
1367 wholine = find_wholine(who, wholen, buf);
1368 if (!wholine)
1369 return; /* no point looking for it */
1370 if (name[wholen] == 0)
1371 v->s = copy_line(wholine);
1372 else if (!strcmp(name + wholen, "name"))
1373 v->s = copy_name(wholine);
1374 else if (starts_with(name + wholen, "email"))
1375 v->s = copy_email(wholine, &used_atom[i]);
1376 else if (starts_with(name + wholen, "date"))
1377 grab_date(wholine, v, name);
1381 * For a tag or a commit object, if "creator" or "creatordate" is
1382 * requested, do something special.
1384 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1385 return; /* "author" for commit object is not wanted */
1386 if (!wholine)
1387 wholine = find_wholine(who, wholen, buf);
1388 if (!wholine)
1389 return;
1390 for (i = 0; i < used_atom_cnt; i++) {
1391 const char *name = used_atom[i].name;
1392 enum atom_type atom_type = used_atom[i].atom_type;
1393 struct atom_value *v = &val[i];
1394 if (!!deref != (*name == '*'))
1395 continue;
1396 if (deref)
1397 name++;
1399 if (atom_type == ATOM_CREATORDATE)
1400 grab_date(wholine, v, name);
1401 else if (atom_type == ATOM_CREATOR)
1402 v->s = copy_line(wholine);
1406 static void find_subpos(const char *buf,
1407 const char **sub, size_t *sublen,
1408 const char **body, size_t *bodylen,
1409 size_t *nonsiglen,
1410 const char **sig, size_t *siglen)
1412 struct strbuf payload = STRBUF_INIT;
1413 struct strbuf signature = STRBUF_INIT;
1414 const char *eol;
1415 const char *end = buf + strlen(buf);
1416 const char *sigstart;
1418 /* parse signature first; we might not even have a subject line */
1419 parse_signature(buf, end - buf, &payload, &signature);
1420 strbuf_release(&payload);
1422 /* skip past header until we hit empty line */
1423 while (*buf && *buf != '\n') {
1424 eol = strchrnul(buf, '\n');
1425 if (*eol)
1426 eol++;
1427 buf = eol;
1429 /* skip any empty lines */
1430 while (*buf == '\n')
1431 buf++;
1432 *sig = strbuf_detach(&signature, siglen);
1433 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1435 /* subject is first non-empty line */
1436 *sub = buf;
1437 /* subject goes to first empty line before signature begins */
1438 if ((eol = strstr(*sub, "\n\n")) ||
1439 (eol = strstr(*sub, "\r\n\r\n"))) {
1440 eol = eol < sigstart ? eol : sigstart;
1441 } else {
1442 /* treat whole message as subject */
1443 eol = sigstart;
1445 buf = eol;
1446 *sublen = buf - *sub;
1447 /* drop trailing newline, if present */
1448 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1449 (*sub)[*sublen - 1] == '\r'))
1450 *sublen -= 1;
1452 /* skip any empty lines */
1453 while (*buf == '\n' || *buf == '\r')
1454 buf++;
1455 *body = buf;
1456 *bodylen = strlen(buf);
1457 *nonsiglen = sigstart - buf;
1461 * If 'lines' is greater than 0, append that many lines from the given
1462 * 'buf' of length 'size' to the given strbuf.
1464 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1466 int i;
1467 const char *sp, *eol;
1468 size_t len;
1470 sp = buf;
1472 for (i = 0; i < lines && sp < buf + size; i++) {
1473 if (i)
1474 strbuf_addstr(out, "\n ");
1475 eol = memchr(sp, '\n', size - (sp - buf));
1476 len = eol ? eol - sp : size - (sp - buf);
1477 strbuf_add(out, sp, len);
1478 if (!eol)
1479 break;
1480 sp = eol + 1;
1484 /* See grab_values */
1485 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1487 int i;
1488 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1489 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1490 void *buf = data->content;
1492 for (i = 0; i < used_atom_cnt; i++) {
1493 struct used_atom *atom = &used_atom[i];
1494 const char *name = atom->name;
1495 struct atom_value *v = &val[i];
1496 enum atom_type atom_type = atom->atom_type;
1498 if (!!deref != (*name == '*'))
1499 continue;
1500 if (deref)
1501 name++;
1503 if (atom_type == ATOM_RAW) {
1504 unsigned long buf_size = data->size;
1506 if (atom->u.raw_data.option == RAW_BARE) {
1507 v->s = xmemdupz(buf, buf_size);
1508 v->s_size = buf_size;
1509 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1510 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1512 continue;
1515 if ((data->type != OBJ_TAG &&
1516 data->type != OBJ_COMMIT) ||
1517 (strcmp(name, "body") &&
1518 !starts_with(name, "subject") &&
1519 !starts_with(name, "trailers") &&
1520 !starts_with(name, "contents")))
1521 continue;
1522 if (!subpos)
1523 find_subpos(buf,
1524 &subpos, &sublen,
1525 &bodypos, &bodylen, &nonsiglen,
1526 &sigpos, &siglen);
1528 if (atom->u.contents.option == C_SUB)
1529 v->s = copy_subject(subpos, sublen);
1530 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1531 struct strbuf sb = STRBUF_INIT;
1532 format_sanitized_subject(&sb, subpos, sublen);
1533 v->s = strbuf_detach(&sb, NULL);
1534 } else if (atom->u.contents.option == C_BODY_DEP)
1535 v->s = xmemdupz(bodypos, bodylen);
1536 else if (atom->u.contents.option == C_LENGTH)
1537 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1538 else if (atom->u.contents.option == C_BODY)
1539 v->s = xmemdupz(bodypos, nonsiglen);
1540 else if (atom->u.contents.option == C_SIG)
1541 v->s = xmemdupz(sigpos, siglen);
1542 else if (atom->u.contents.option == C_LINES) {
1543 struct strbuf s = STRBUF_INIT;
1544 const char *contents_end = bodypos + nonsiglen;
1546 /* Size is the length of the message after removing the signature */
1547 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1548 v->s = strbuf_detach(&s, NULL);
1549 } else if (atom->u.contents.option == C_TRAILERS) {
1550 struct strbuf s = STRBUF_INIT;
1552 /* Format the trailer info according to the trailer_opts given */
1553 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1555 v->s = strbuf_detach(&s, NULL);
1556 } else if (atom->u.contents.option == C_BARE)
1557 v->s = xstrdup(subpos);
1560 free((void *)sigpos);
1564 * We want to have empty print-string for field requests
1565 * that do not apply (e.g. "authordate" for a tag object)
1567 static void fill_missing_values(struct atom_value *val)
1569 int i;
1570 for (i = 0; i < used_atom_cnt; i++) {
1571 struct atom_value *v = &val[i];
1572 if (!v->s)
1573 v->s = xstrdup("");
1578 * val is a list of atom_value to hold returned values. Extract
1579 * the values for atoms in used_atom array out of (obj, buf, sz).
1580 * when deref is false, (obj, buf, sz) is the object that is
1581 * pointed at by the ref itself; otherwise it is the object the
1582 * ref (which is a tag) refers to.
1584 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1586 void *buf = data->content;
1588 switch (obj->type) {
1589 case OBJ_TAG:
1590 grab_tag_values(val, deref, obj);
1591 grab_sub_body_contents(val, deref, data);
1592 grab_person("tagger", val, deref, buf);
1593 break;
1594 case OBJ_COMMIT:
1595 grab_commit_values(val, deref, obj);
1596 grab_sub_body_contents(val, deref, data);
1597 grab_person("author", val, deref, buf);
1598 grab_person("committer", val, deref, buf);
1599 break;
1600 case OBJ_TREE:
1601 /* grab_tree_values(val, deref, obj, buf, sz); */
1602 grab_sub_body_contents(val, deref, data);
1603 break;
1604 case OBJ_BLOB:
1605 /* grab_blob_values(val, deref, obj, buf, sz); */
1606 grab_sub_body_contents(val, deref, data);
1607 break;
1608 default:
1609 die("Eh? Object of type %d?", obj->type);
1613 static inline char *copy_advance(char *dst, const char *src)
1615 while (*src)
1616 *dst++ = *src++;
1617 return dst;
1620 static const char *lstrip_ref_components(const char *refname, int len)
1622 long remaining = len;
1623 const char *start = xstrdup(refname);
1624 const char *to_free = start;
1626 if (len < 0) {
1627 int i;
1628 const char *p = refname;
1630 /* Find total no of '/' separated path-components */
1631 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1634 * The number of components we need to strip is now
1635 * the total minus the components to be left (Plus one
1636 * because we count the number of '/', but the number
1637 * of components is one more than the no of '/').
1639 remaining = i + len + 1;
1642 while (remaining > 0) {
1643 switch (*start++) {
1644 case '\0':
1645 free((char *)to_free);
1646 return xstrdup("");
1647 case '/':
1648 remaining--;
1649 break;
1653 start = xstrdup(start);
1654 free((char *)to_free);
1655 return start;
1658 static const char *rstrip_ref_components(const char *refname, int len)
1660 long remaining = len;
1661 const char *start = xstrdup(refname);
1662 const char *to_free = start;
1664 if (len < 0) {
1665 int i;
1666 const char *p = refname;
1668 /* Find total no of '/' separated path-components */
1669 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1672 * The number of components we need to strip is now
1673 * the total minus the components to be left (Plus one
1674 * because we count the number of '/', but the number
1675 * of components is one more than the no of '/').
1677 remaining = i + len + 1;
1680 while (remaining-- > 0) {
1681 char *p = strrchr(start, '/');
1682 if (!p) {
1683 free((char *)to_free);
1684 return xstrdup("");
1685 } else
1686 p[0] = '\0';
1688 return start;
1691 static const char *show_ref(struct refname_atom *atom, const char *refname)
1693 if (atom->option == R_SHORT)
1694 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1695 else if (atom->option == R_LSTRIP)
1696 return lstrip_ref_components(refname, atom->lstrip);
1697 else if (atom->option == R_RSTRIP)
1698 return rstrip_ref_components(refname, atom->rstrip);
1699 else
1700 return xstrdup(refname);
1703 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1704 struct branch *branch, const char **s)
1706 int num_ours, num_theirs;
1707 if (atom->u.remote_ref.option == RR_REF)
1708 *s = show_ref(&atom->u.remote_ref.refname, refname);
1709 else if (atom->u.remote_ref.option == RR_TRACK) {
1710 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1711 NULL, atom->u.remote_ref.push,
1712 AHEAD_BEHIND_FULL) < 0) {
1713 *s = xstrdup(msgs.gone);
1714 } else if (!num_ours && !num_theirs)
1715 *s = xstrdup("");
1716 else if (!num_ours)
1717 *s = xstrfmt(msgs.behind, num_theirs);
1718 else if (!num_theirs)
1719 *s = xstrfmt(msgs.ahead, num_ours);
1720 else
1721 *s = xstrfmt(msgs.ahead_behind,
1722 num_ours, num_theirs);
1723 if (!atom->u.remote_ref.nobracket && *s[0]) {
1724 const char *to_free = *s;
1725 *s = xstrfmt("[%s]", *s);
1726 free((void *)to_free);
1728 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1729 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1730 NULL, atom->u.remote_ref.push,
1731 AHEAD_BEHIND_FULL) < 0) {
1732 *s = xstrdup("");
1733 return;
1735 if (!num_ours && !num_theirs)
1736 *s = xstrdup("=");
1737 else if (!num_ours)
1738 *s = xstrdup("<");
1739 else if (!num_theirs)
1740 *s = xstrdup(">");
1741 else
1742 *s = xstrdup("<>");
1743 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1744 int explicit;
1745 const char *remote = atom->u.remote_ref.push ?
1746 pushremote_for_branch(branch, &explicit) :
1747 remote_for_branch(branch, &explicit);
1748 *s = xstrdup(explicit ? remote : "");
1749 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1750 const char *merge;
1752 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1753 *s = xstrdup(merge ? merge : "");
1754 } else
1755 BUG("unhandled RR_* enum");
1758 char *get_head_description(void)
1760 struct strbuf desc = STRBUF_INIT;
1761 struct wt_status_state state;
1762 memset(&state, 0, sizeof(state));
1763 wt_status_get_state(the_repository, &state, 1);
1764 if (state.rebase_in_progress ||
1765 state.rebase_interactive_in_progress) {
1766 if (state.branch)
1767 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1768 state.branch);
1769 else
1770 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1771 state.detached_from);
1772 } else if (state.bisect_in_progress)
1773 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1774 state.branch);
1775 else if (state.detached_from) {
1776 if (state.detached_at)
1777 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1778 state.detached_from);
1779 else
1780 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1781 state.detached_from);
1782 } else
1783 strbuf_addstr(&desc, _("(no branch)"));
1785 wt_status_state_free_buffers(&state);
1787 return strbuf_detach(&desc, NULL);
1790 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1792 if (!ref->symref)
1793 return xstrdup("");
1794 else
1795 return show_ref(&atom->u.refname, ref->symref);
1798 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1800 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1801 return get_head_description();
1802 return show_ref(&atom->u.refname, ref->refname);
1805 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1806 struct expand_data *oi, struct strbuf *err)
1808 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1809 int eaten = 1;
1810 if (oi->info.contentp) {
1811 /* We need to know that to use parse_object_buffer properly */
1812 oi->info.sizep = &oi->size;
1813 oi->info.typep = &oi->type;
1815 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1816 OBJECT_INFO_LOOKUP_REPLACE))
1817 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1818 oid_to_hex(&oi->oid), ref->refname);
1819 if (oi->info.disk_sizep && oi->disk_size < 0)
1820 BUG("Object size is less than zero.");
1822 if (oi->info.contentp) {
1823 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1824 if (!*obj) {
1825 if (!eaten)
1826 free(oi->content);
1827 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1828 oid_to_hex(&oi->oid), ref->refname);
1830 grab_values(ref->value, deref, *obj, oi);
1833 grab_common_values(ref->value, deref, oi);
1834 if (!eaten)
1835 free(oi->content);
1836 return 0;
1839 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1841 int i;
1843 for (i = 0; worktrees[i]; i++) {
1844 if (worktrees[i]->head_ref) {
1845 struct ref_to_worktree_entry *entry;
1846 entry = xmalloc(sizeof(*entry));
1847 entry->wt = worktrees[i];
1848 hashmap_entry_init(&entry->ent,
1849 strhash(worktrees[i]->head_ref));
1851 hashmap_add(map, &entry->ent);
1856 static void lazy_init_worktree_map(void)
1858 if (ref_to_worktree_map.worktrees)
1859 return;
1861 ref_to_worktree_map.worktrees = get_worktrees();
1862 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1863 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1866 static char *get_worktree_path(const struct ref_array_item *ref)
1868 struct hashmap_entry entry, *e;
1869 struct ref_to_worktree_entry *lookup_result;
1871 lazy_init_worktree_map();
1873 hashmap_entry_init(&entry, strhash(ref->refname));
1874 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1876 if (!e)
1877 return xstrdup("");
1879 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1881 return xstrdup(lookup_result->wt->path);
1885 * Parse the object referred by ref, and grab needed value.
1887 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1889 struct object *obj;
1890 int i;
1891 struct object_info empty = OBJECT_INFO_INIT;
1892 int ahead_behind_atoms = 0;
1894 CALLOC_ARRAY(ref->value, used_atom_cnt);
1896 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1897 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1898 NULL, NULL);
1899 if (!ref->symref)
1900 ref->symref = xstrdup("");
1903 /* Fill in specials first */
1904 for (i = 0; i < used_atom_cnt; i++) {
1905 struct used_atom *atom = &used_atom[i];
1906 enum atom_type atom_type = atom->atom_type;
1907 const char *name = used_atom[i].name;
1908 struct atom_value *v = &ref->value[i];
1909 int deref = 0;
1910 const char *refname;
1911 struct branch *branch = NULL;
1913 v->s_size = ATOM_SIZE_UNSPECIFIED;
1914 v->handler = append_atom;
1915 v->atom = atom;
1917 if (*name == '*') {
1918 deref = 1;
1919 name++;
1922 if (atom_type == ATOM_REFNAME)
1923 refname = get_refname(atom, ref);
1924 else if (atom_type == ATOM_WORKTREEPATH) {
1925 if (ref->kind == FILTER_REFS_BRANCHES)
1926 v->s = get_worktree_path(ref);
1927 else
1928 v->s = xstrdup("");
1929 continue;
1931 else if (atom_type == ATOM_SYMREF)
1932 refname = get_symref(atom, ref);
1933 else if (atom_type == ATOM_UPSTREAM) {
1934 const char *branch_name;
1935 /* only local branches may have an upstream */
1936 if (!skip_prefix(ref->refname, "refs/heads/",
1937 &branch_name)) {
1938 v->s = xstrdup("");
1939 continue;
1941 branch = branch_get(branch_name);
1943 refname = branch_get_upstream(branch, NULL);
1944 if (refname)
1945 fill_remote_ref_details(atom, refname, branch, &v->s);
1946 else
1947 v->s = xstrdup("");
1948 continue;
1949 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1950 const char *branch_name;
1951 v->s = xstrdup("");
1952 if (!skip_prefix(ref->refname, "refs/heads/",
1953 &branch_name))
1954 continue;
1955 branch = branch_get(branch_name);
1957 if (atom->u.remote_ref.push_remote)
1958 refname = NULL;
1959 else {
1960 refname = branch_get_push(branch, NULL);
1961 if (!refname)
1962 continue;
1964 /* We will definitely re-init v->s on the next line. */
1965 free((char *)v->s);
1966 fill_remote_ref_details(atom, refname, branch, &v->s);
1967 continue;
1968 } else if (atom_type == ATOM_COLOR) {
1969 v->s = xstrdup(atom->u.color);
1970 continue;
1971 } else if (atom_type == ATOM_FLAG) {
1972 char buf[256], *cp = buf;
1973 if (ref->flag & REF_ISSYMREF)
1974 cp = copy_advance(cp, ",symref");
1975 if (ref->flag & REF_ISPACKED)
1976 cp = copy_advance(cp, ",packed");
1977 if (cp == buf)
1978 v->s = xstrdup("");
1979 else {
1980 *cp = '\0';
1981 v->s = xstrdup(buf + 1);
1983 continue;
1984 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1985 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1986 continue;
1987 } else if (atom_type == ATOM_HEAD) {
1988 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1989 v->s = xstrdup("*");
1990 else
1991 v->s = xstrdup(" ");
1992 continue;
1993 } else if (atom_type == ATOM_ALIGN) {
1994 v->handler = align_atom_handler;
1995 v->s = xstrdup("");
1996 continue;
1997 } else if (atom_type == ATOM_END) {
1998 v->handler = end_atom_handler;
1999 v->s = xstrdup("");
2000 continue;
2001 } else if (atom_type == ATOM_IF) {
2002 const char *s;
2003 if (skip_prefix(name, "if:", &s))
2004 v->s = xstrdup(s);
2005 else
2006 v->s = xstrdup("");
2007 v->handler = if_atom_handler;
2008 continue;
2009 } else if (atom_type == ATOM_THEN) {
2010 v->handler = then_atom_handler;
2011 v->s = xstrdup("");
2012 continue;
2013 } else if (atom_type == ATOM_ELSE) {
2014 v->handler = else_atom_handler;
2015 v->s = xstrdup("");
2016 continue;
2017 } else if (atom_type == ATOM_REST) {
2018 if (ref->rest)
2019 v->s = xstrdup(ref->rest);
2020 else
2021 v->s = xstrdup("");
2022 continue;
2023 } else if (atom_type == ATOM_AHEADBEHIND) {
2024 if (ref->counts) {
2025 const struct ahead_behind_count *count;
2026 count = ref->counts[ahead_behind_atoms++];
2027 v->s = xstrfmt("%d %d", count->ahead, count->behind);
2028 } else {
2029 /* Not a commit. */
2030 v->s = xstrdup("");
2032 continue;
2033 } else
2034 continue;
2036 if (!deref)
2037 v->s = xstrdup(refname);
2038 else
2039 v->s = xstrfmt("%s^{}", refname);
2040 free((char *)refname);
2043 for (i = 0; i < used_atom_cnt; i++) {
2044 struct atom_value *v = &ref->value[i];
2045 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
2046 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
2047 oid_to_hex(&ref->objectname), ref->refname);
2050 if (need_tagged)
2051 oi.info.contentp = &oi.content;
2052 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
2053 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
2054 return 0;
2057 oi.oid = ref->objectname;
2058 if (get_object(ref, 0, &obj, &oi, err))
2059 return -1;
2062 * If there is no atom that wants to know about tagged
2063 * object, we are done.
2065 if (!need_tagged || (obj->type != OBJ_TAG))
2066 return 0;
2069 * If it is a tag object, see if we use a value that derefs
2070 * the object, and if we do grab the object it refers to.
2072 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
2075 * NEEDSWORK: This derefs tag only once, which
2076 * is good to deal with chains of trust, but
2077 * is not consistent with what deref_tag() does
2078 * which peels the onion to the core.
2080 return get_object(ref, 1, &obj, &oi_deref, err);
2084 * Given a ref, return the value for the atom. This lazily gets value
2085 * out of the object by calling populate value.
2087 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
2088 struct atom_value **v, struct strbuf *err)
2090 if (!ref->value) {
2091 if (populate_value(ref, err))
2092 return -1;
2093 fill_missing_values(ref->value);
2095 *v = &ref->value[atom];
2096 return 0;
2100 * Return 1 if the refname matches one of the patterns, otherwise 0.
2101 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2102 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2103 * matches "refs/heads/mas*", too).
2105 static int match_pattern(const struct ref_filter *filter, const char *refname)
2107 const char **patterns = filter->name_patterns;
2108 unsigned flags = 0;
2110 if (filter->ignore_case)
2111 flags |= WM_CASEFOLD;
2114 * When no '--format' option is given we need to skip the prefix
2115 * for matching refs of tags and branches.
2117 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2118 skip_prefix(refname, "refs/heads/", &refname) ||
2119 skip_prefix(refname, "refs/remotes/", &refname) ||
2120 skip_prefix(refname, "refs/", &refname));
2122 for (; *patterns; patterns++) {
2123 if (!wildmatch(*patterns, refname, flags))
2124 return 1;
2126 return 0;
2130 * Return 1 if the refname matches one of the patterns, otherwise 0.
2131 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2132 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2133 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2135 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2137 const char **pattern = filter->name_patterns;
2138 int namelen = strlen(refname);
2139 unsigned flags = WM_PATHNAME;
2141 if (filter->ignore_case)
2142 flags |= WM_CASEFOLD;
2144 for (; *pattern; pattern++) {
2145 const char *p = *pattern;
2146 int plen = strlen(p);
2148 if ((plen <= namelen) &&
2149 !strncmp(refname, p, plen) &&
2150 (refname[plen] == '\0' ||
2151 refname[plen] == '/' ||
2152 p[plen-1] == '/'))
2153 return 1;
2154 if (!wildmatch(p, refname, flags))
2155 return 1;
2157 return 0;
2160 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2161 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2163 if (!*filter->name_patterns)
2164 return 1; /* No pattern always matches */
2165 if (filter->match_as_path)
2166 return match_name_as_path(filter, refname);
2167 return match_pattern(filter, refname);
2171 * This is the same as for_each_fullref_in(), but it tries to iterate
2172 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2173 * pattern match, so the callback still has to match each ref individually.
2175 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2176 each_ref_fn cb,
2177 void *cb_data)
2179 if (!filter->match_as_path) {
2181 * in this case, the patterns are applied after
2182 * prefixes like "refs/heads/" etc. are stripped off,
2183 * so we have to look at everything:
2185 return for_each_fullref_in("", cb, cb_data);
2188 if (filter->ignore_case) {
2190 * we can't handle case-insensitive comparisons,
2191 * so just return everything and let the caller
2192 * sort it out.
2194 return for_each_fullref_in("", cb, cb_data);
2197 if (!filter->name_patterns[0]) {
2198 /* no patterns; we have to look at everything */
2199 return for_each_fullref_in("", cb, cb_data);
2202 return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),
2203 NULL, filter->name_patterns,
2204 cb, cb_data);
2208 * Given a ref (oid, refname), check if the ref belongs to the array
2209 * of oids. If the given ref is a tag, check if the given tag points
2210 * at one of the oids in the given oid array.
2211 * NEEDSWORK:
2212 * 1. Only a single level of indirection is obtained, we might want to
2213 * change this to account for multiple levels (e.g. annotated tags
2214 * pointing to annotated tags pointing to a commit.)
2215 * 2. As the refs are cached we might know what refname peels to without
2216 * the need to parse the object via parse_object(). peel_ref() might be a
2217 * more efficient alternative to obtain the pointee.
2219 static const struct object_id *match_points_at(struct oid_array *points_at,
2220 const struct object_id *oid,
2221 const char *refname)
2223 const struct object_id *tagged_oid = NULL;
2224 struct object *obj;
2226 if (oid_array_lookup(points_at, oid) >= 0)
2227 return oid;
2228 obj = parse_object(the_repository, oid);
2229 if (!obj)
2230 die(_("malformed object at '%s'"), refname);
2231 if (obj->type == OBJ_TAG)
2232 tagged_oid = get_tagged_oid((struct tag *)obj);
2233 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2234 return tagged_oid;
2235 return NULL;
2239 * Allocate space for a new ref_array_item and copy the name and oid to it.
2241 * Callers can then fill in other struct members at their leisure.
2243 static struct ref_array_item *new_ref_array_item(const char *refname,
2244 const struct object_id *oid)
2246 struct ref_array_item *ref;
2248 FLEX_ALLOC_STR(ref, refname, refname);
2249 oidcpy(&ref->objectname, oid);
2250 ref->rest = NULL;
2252 return ref;
2255 struct ref_array_item *ref_array_push(struct ref_array *array,
2256 const char *refname,
2257 const struct object_id *oid)
2259 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2261 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2262 array->items[array->nr++] = ref;
2264 return ref;
2267 static int ref_kind_from_refname(const char *refname)
2269 unsigned int i;
2271 static struct {
2272 const char *prefix;
2273 unsigned int kind;
2274 } ref_kind[] = {
2275 { "refs/heads/" , FILTER_REFS_BRANCHES },
2276 { "refs/remotes/" , FILTER_REFS_REMOTES },
2277 { "refs/tags/", FILTER_REFS_TAGS}
2280 if (!strcmp(refname, "HEAD"))
2281 return FILTER_REFS_DETACHED_HEAD;
2283 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2284 if (starts_with(refname, ref_kind[i].prefix))
2285 return ref_kind[i].kind;
2288 return FILTER_REFS_OTHERS;
2291 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2293 if (filter->kind == FILTER_REFS_BRANCHES ||
2294 filter->kind == FILTER_REFS_REMOTES ||
2295 filter->kind == FILTER_REFS_TAGS)
2296 return filter->kind;
2297 return ref_kind_from_refname(refname);
2300 struct ref_filter_cbdata {
2301 struct ref_array *array;
2302 struct ref_filter *filter;
2303 struct contains_cache contains_cache;
2304 struct contains_cache no_contains_cache;
2308 * A call-back given to for_each_ref(). Filter refs and keep them for
2309 * later object processing.
2311 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2313 struct ref_filter_cbdata *ref_cbdata = cb_data;
2314 struct ref_filter *filter = ref_cbdata->filter;
2315 struct ref_array_item *ref;
2316 struct commit *commit = NULL;
2317 unsigned int kind;
2319 if (flag & REF_BAD_NAME) {
2320 warning(_("ignoring ref with broken name %s"), refname);
2321 return 0;
2324 if (flag & REF_ISBROKEN) {
2325 warning(_("ignoring broken ref %s"), refname);
2326 return 0;
2329 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2330 kind = filter_ref_kind(filter, refname);
2331 if (!(kind & filter->kind))
2332 return 0;
2334 if (!filter_pattern_match(filter, refname))
2335 return 0;
2337 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2338 return 0;
2341 * A merge filter is applied on refs pointing to commits. Hence
2342 * obtain the commit using the 'oid' available and discard all
2343 * non-commits early. The actual filtering is done later.
2345 if (filter->reachable_from || filter->unreachable_from ||
2346 filter->with_commit || filter->no_commit || filter->verbose) {
2347 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2348 if (!commit)
2349 return 0;
2350 /* We perform the filtering for the '--contains' option... */
2351 if (filter->with_commit &&
2352 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2353 return 0;
2354 /* ...or for the `--no-contains' option */
2355 if (filter->no_commit &&
2356 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2357 return 0;
2361 * We do not open the object yet; sort may only need refname
2362 * to do its job and the resulting list may yet to be pruned
2363 * by maxcount logic.
2365 ref = ref_array_push(ref_cbdata->array, refname, oid);
2366 ref->commit = commit;
2367 ref->flag = flag;
2368 ref->kind = kind;
2370 return 0;
2373 /* Free memory allocated for a ref_array_item */
2374 static void free_array_item(struct ref_array_item *item)
2376 free((char *)item->symref);
2377 if (item->value) {
2378 int i;
2379 for (i = 0; i < used_atom_cnt; i++)
2380 free((char *)item->value[i].s);
2381 free(item->value);
2383 free(item->counts);
2384 free(item);
2387 /* Free all memory allocated for ref_array */
2388 void ref_array_clear(struct ref_array *array)
2390 int i;
2392 for (i = 0; i < array->nr; i++)
2393 free_array_item(array->items[i]);
2394 FREE_AND_NULL(array->items);
2395 array->nr = array->alloc = 0;
2397 for (i = 0; i < used_atom_cnt; i++) {
2398 struct used_atom *atom = &used_atom[i];
2399 if (atom->atom_type == ATOM_HEAD)
2400 free(atom->u.head);
2401 free((char *)atom->name);
2403 FREE_AND_NULL(used_atom);
2404 used_atom_cnt = 0;
2406 if (ref_to_worktree_map.worktrees) {
2407 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2408 struct ref_to_worktree_entry, ent);
2409 free_worktrees(ref_to_worktree_map.worktrees);
2410 ref_to_worktree_map.worktrees = NULL;
2413 FREE_AND_NULL(array->counts);
2416 #define EXCLUDE_REACHED 0
2417 #define INCLUDE_REACHED 1
2418 static void reach_filter(struct ref_array *array,
2419 struct commit_list *check_reachable,
2420 int include_reached)
2422 int i, old_nr;
2423 struct commit **to_clear;
2425 if (!check_reachable)
2426 return;
2428 CALLOC_ARRAY(to_clear, array->nr);
2429 for (i = 0; i < array->nr; i++) {
2430 struct ref_array_item *item = array->items[i];
2431 to_clear[i] = item->commit;
2434 tips_reachable_from_bases(the_repository,
2435 check_reachable,
2436 to_clear, array->nr,
2437 UNINTERESTING);
2439 old_nr = array->nr;
2440 array->nr = 0;
2442 for (i = 0; i < old_nr; i++) {
2443 struct ref_array_item *item = array->items[i];
2444 struct commit *commit = item->commit;
2446 int is_merged = !!(commit->object.flags & UNINTERESTING);
2448 if (is_merged == include_reached)
2449 array->items[array->nr++] = array->items[i];
2450 else
2451 free_array_item(item);
2454 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2456 while (check_reachable) {
2457 struct commit *merge_commit = pop_commit(&check_reachable);
2458 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2461 free(to_clear);
2464 void filter_ahead_behind(struct repository *r,
2465 struct ref_format *format,
2466 struct ref_array *array)
2468 struct commit **commits;
2469 size_t commits_nr = format->bases.nr + array->nr;
2471 if (!format->bases.nr || !array->nr)
2472 return;
2474 ALLOC_ARRAY(commits, commits_nr);
2475 for (size_t i = 0; i < format->bases.nr; i++)
2476 commits[i] = format->bases.items[i].util;
2478 ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));
2480 commits_nr = format->bases.nr;
2481 array->counts_nr = 0;
2482 for (size_t i = 0; i < array->nr; i++) {
2483 const char *name = array->items[i]->refname;
2484 commits[commits_nr] = lookup_commit_reference_by_name(name);
2486 if (!commits[commits_nr])
2487 continue;
2489 CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);
2490 for (size_t j = 0; j < format->bases.nr; j++) {
2491 struct ahead_behind_count *count;
2492 count = &array->counts[array->counts_nr++];
2493 count->tip_index = commits_nr;
2494 count->base_index = j;
2496 array->items[i]->counts[j] = count;
2498 commits_nr++;
2501 ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);
2502 free(commits);
2506 * API for filtering a set of refs. Based on the type of refs the user
2507 * has requested, we iterate through those refs and apply filters
2508 * as per the given ref_filter structure and finally store the
2509 * filtered refs in the ref_array structure.
2511 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2513 struct ref_filter_cbdata ref_cbdata;
2514 int save_commit_buffer_orig;
2515 int ret = 0;
2517 ref_cbdata.array = array;
2518 ref_cbdata.filter = filter;
2520 filter->kind = type & FILTER_REFS_KIND_MASK;
2522 save_commit_buffer_orig = save_commit_buffer;
2523 save_commit_buffer = 0;
2525 init_contains_cache(&ref_cbdata.contains_cache);
2526 init_contains_cache(&ref_cbdata.no_contains_cache);
2528 /* Simple per-ref filtering */
2529 if (!filter->kind)
2530 die("filter_refs: invalid type");
2531 else {
2533 * For common cases where we need only branches or remotes or tags,
2534 * we only iterate through those refs. If a mix of refs is needed,
2535 * we iterate over all refs and filter out required refs with the help
2536 * of filter_ref_kind().
2538 if (filter->kind == FILTER_REFS_BRANCHES)
2539 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata);
2540 else if (filter->kind == FILTER_REFS_REMOTES)
2541 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata);
2542 else if (filter->kind == FILTER_REFS_TAGS)
2543 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata);
2544 else if (filter->kind & FILTER_REFS_ALL)
2545 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata);
2546 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2547 head_ref(ref_filter_handler, &ref_cbdata);
2550 clear_contains_cache(&ref_cbdata.contains_cache);
2551 clear_contains_cache(&ref_cbdata.no_contains_cache);
2553 /* Filters that need revision walking */
2554 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2555 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2557 save_commit_buffer = save_commit_buffer_orig;
2558 return ret;
2561 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2563 if (!(a->kind ^ b->kind))
2564 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2565 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2566 return -1;
2567 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2568 return 1;
2569 BUG("should have died in the xor check above");
2570 return 0;
2573 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2575 const char *s1 = vs1, *s2 = vs2;
2576 const char *end = s1 + n;
2578 for (; s1 < end; s1++, s2++) {
2579 int diff = tolower(*s1) - tolower(*s2);
2580 if (diff)
2581 return diff;
2583 return 0;
2586 struct ref_sorting {
2587 struct ref_sorting *next;
2588 int atom; /* index into used_atom array (internal) */
2589 enum ref_sorting_order sort_flags;
2592 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2594 struct atom_value *va, *vb;
2595 int cmp;
2596 int cmp_detached_head = 0;
2597 cmp_type cmp_type = used_atom[s->atom].type;
2598 struct strbuf err = STRBUF_INIT;
2600 if (get_ref_atom_value(a, s->atom, &va, &err))
2601 die("%s", err.buf);
2602 if (get_ref_atom_value(b, s->atom, &vb, &err))
2603 die("%s", err.buf);
2604 strbuf_release(&err);
2605 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2606 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2607 cmp = compare_detached_head(a, b);
2608 cmp_detached_head = 1;
2609 } else if (s->sort_flags & REF_SORTING_VERSION) {
2610 cmp = versioncmp(va->s, vb->s);
2611 } else if (cmp_type == FIELD_STR) {
2612 if (va->s_size < 0 && vb->s_size < 0) {
2613 int (*cmp_fn)(const char *, const char *);
2614 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2615 ? strcasecmp : strcmp;
2616 cmp = cmp_fn(va->s, vb->s);
2617 } else {
2618 size_t a_size = va->s_size < 0 ?
2619 strlen(va->s) : va->s_size;
2620 size_t b_size = vb->s_size < 0 ?
2621 strlen(vb->s) : vb->s_size;
2622 int (*cmp_fn)(const void *, const void *, size_t);
2623 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2624 ? memcasecmp : memcmp;
2626 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2627 a_size : b_size);
2628 if (!cmp) {
2629 if (a_size > b_size)
2630 cmp = 1;
2631 else if (a_size < b_size)
2632 cmp = -1;
2635 } else {
2636 if (va->value < vb->value)
2637 cmp = -1;
2638 else if (va->value == vb->value)
2639 cmp = 0;
2640 else
2641 cmp = 1;
2644 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2645 ? -cmp : cmp;
2648 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2650 struct ref_array_item *a = *((struct ref_array_item **)a_);
2651 struct ref_array_item *b = *((struct ref_array_item **)b_);
2652 struct ref_sorting *s;
2654 for (s = ref_sorting; s; s = s->next) {
2655 int cmp = cmp_ref_sorting(s, a, b);
2656 if (cmp)
2657 return cmp;
2659 s = ref_sorting;
2660 return s && s->sort_flags & REF_SORTING_ICASE ?
2661 strcasecmp(a->refname, b->refname) :
2662 strcmp(a->refname, b->refname);
2665 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2666 unsigned int mask, int on)
2668 for (; sorting; sorting = sorting->next) {
2669 if (on)
2670 sorting->sort_flags |= mask;
2671 else
2672 sorting->sort_flags &= ~mask;
2676 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2678 QSORT_S(array->items, array->nr, compare_refs, sorting);
2681 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2683 struct strbuf *s = &state->stack->output;
2685 while (*cp && (!ep || cp < ep)) {
2686 if (*cp == '%') {
2687 if (cp[1] == '%')
2688 cp++;
2689 else {
2690 int ch = hex2chr(cp + 1);
2691 if (0 <= ch) {
2692 strbuf_addch(s, ch);
2693 cp += 3;
2694 continue;
2698 strbuf_addch(s, *cp);
2699 cp++;
2703 int format_ref_array_item(struct ref_array_item *info,
2704 struct ref_format *format,
2705 struct strbuf *final_buf,
2706 struct strbuf *error_buf)
2708 const char *cp, *sp, *ep;
2709 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2711 state.quote_style = format->quote_style;
2712 push_stack_element(&state.stack);
2714 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2715 struct atom_value *atomv;
2716 int pos;
2718 ep = strchr(sp, ')');
2719 if (cp < sp)
2720 append_literal(cp, sp, &state);
2721 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2722 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2723 atomv->handler(atomv, &state, error_buf)) {
2724 pop_stack_element(&state.stack);
2725 return -1;
2728 if (*cp) {
2729 sp = cp + strlen(cp);
2730 append_literal(cp, sp, &state);
2732 if (format->need_color_reset_at_eol) {
2733 struct atom_value resetv = ATOM_VALUE_INIT;
2734 resetv.s = GIT_COLOR_RESET;
2735 if (append_atom(&resetv, &state, error_buf)) {
2736 pop_stack_element(&state.stack);
2737 return -1;
2740 if (state.stack->prev) {
2741 pop_stack_element(&state.stack);
2742 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2744 strbuf_addbuf(final_buf, &state.stack->output);
2745 pop_stack_element(&state.stack);
2746 return 0;
2749 void pretty_print_ref(const char *name, const struct object_id *oid,
2750 struct ref_format *format)
2752 struct ref_array_item *ref_item;
2753 struct strbuf output = STRBUF_INIT;
2754 struct strbuf err = STRBUF_INIT;
2756 ref_item = new_ref_array_item(name, oid);
2757 ref_item->kind = ref_kind_from_refname(name);
2758 if (format_ref_array_item(ref_item, format, &output, &err))
2759 die("%s", err.buf);
2760 fwrite(output.buf, 1, output.len, stdout);
2761 putchar('\n');
2763 strbuf_release(&err);
2764 strbuf_release(&output);
2765 free_array_item(ref_item);
2768 static int parse_sorting_atom(const char *atom)
2771 * This parses an atom using a dummy ref_format, since we don't
2772 * actually care about the formatting details.
2774 struct ref_format dummy = REF_FORMAT_INIT;
2775 const char *end = atom + strlen(atom);
2776 struct strbuf err = STRBUF_INIT;
2777 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2778 if (res < 0)
2779 die("%s", err.buf);
2780 strbuf_release(&err);
2781 return res;
2784 /* If no sorting option is given, use refname to sort as default */
2785 static struct ref_sorting *ref_default_sorting(void)
2787 static const char cstr_name[] = "refname";
2789 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2791 sorting->next = NULL;
2792 sorting->atom = parse_sorting_atom(cstr_name);
2793 return sorting;
2796 static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2798 struct ref_sorting *s;
2800 CALLOC_ARRAY(s, 1);
2801 s->next = *sorting_tail;
2802 *sorting_tail = s;
2804 if (*arg == '-') {
2805 s->sort_flags |= REF_SORTING_REVERSE;
2806 arg++;
2808 if (skip_prefix(arg, "version:", &arg) ||
2809 skip_prefix(arg, "v:", &arg))
2810 s->sort_flags |= REF_SORTING_VERSION;
2811 s->atom = parse_sorting_atom(arg);
2814 struct ref_sorting *ref_sorting_options(struct string_list *options)
2816 struct string_list_item *item;
2817 struct ref_sorting *sorting = NULL, **tail = &sorting;
2819 if (!options->nr) {
2820 sorting = ref_default_sorting();
2821 } else {
2822 for_each_string_list_item(item, options)
2823 parse_ref_sorting(tail, item->string);
2827 * From here on, the ref_sorting list should be used to talk
2828 * about the sort order used for the output. The caller
2829 * should not touch the string form anymore.
2831 string_list_clear(options, 0);
2832 return sorting;
2835 void ref_sorting_release(struct ref_sorting *sorting)
2837 while (sorting) {
2838 struct ref_sorting *next = sorting->next;
2839 free(sorting);
2840 sorting = next;
2844 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2846 struct ref_filter *rf = opt->value;
2847 struct object_id oid;
2848 struct commit *merge_commit;
2850 BUG_ON_OPT_NEG(unset);
2852 if (repo_get_oid(the_repository, arg, &oid))
2853 die(_("malformed object name %s"), arg);
2855 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2857 if (!merge_commit)
2858 return error(_("option `%s' must point to a commit"), opt->long_name);
2860 if (starts_with(opt->long_name, "no"))
2861 commit_list_insert(merge_commit, &rf->unreachable_from);
2862 else
2863 commit_list_insert(merge_commit, &rf->reachable_from);
2865 return 0;