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