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