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