ref-filter: add %(raw) atom
[alt-git.git] / ref-filter.c
blob0d5eb91ed5432b50bb95baf33679944f9de9bc93
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 *unused_lookupdata,
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,
163 * An atom is a valid field atom listed below, possibly prefixed with
164 * a "*" to denote deref_tag().
166 * We parse given format string and sort specifiers, and make a list
167 * of properties that we need to extract out of objects. ref_array_item
168 * structure will hold an array of values extracted that can be
169 * indexed with the "atom number", which is an index into this
170 * array.
172 static struct used_atom {
173 enum atom_type atom_type;
174 const char *name;
175 cmp_type type;
176 info_source source;
177 union {
178 char color[COLOR_MAXLEN];
179 struct align align;
180 struct {
181 enum {
182 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
183 } option;
184 struct refname_atom refname;
185 unsigned int nobracket : 1, push : 1, push_remote : 1;
186 } remote_ref;
187 struct {
188 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
189 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
190 struct process_trailer_options trailer_opts;
191 unsigned int nlines;
192 } contents;
193 struct {
194 enum { RAW_BARE, RAW_LENGTH } option;
195 } raw_data;
196 struct {
197 cmp_status cmp_status;
198 const char *str;
199 } if_then_else;
200 struct {
201 enum { O_FULL, O_LENGTH, O_SHORT } option;
202 unsigned int length;
203 } oid;
204 struct {
205 enum { O_SIZE, O_SIZE_DISK } option;
206 } objectsize;
207 struct email_option {
208 enum { EO_RAW, EO_TRIM, EO_LOCALPART } option;
209 } email_option;
210 struct refname_atom refname;
211 char *head;
212 } u;
213 } *used_atom;
214 static int used_atom_cnt, need_tagged, need_symref;
217 * Expand string, append it to strbuf *sb, then return error code ret.
218 * Allow to save few lines of code.
220 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
222 va_list ap;
223 va_start(ap, fmt);
224 strbuf_vaddf(sb, fmt, ap);
225 va_end(ap);
226 return ret;
229 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
230 const char *color_value, struct strbuf *err)
232 if (!color_value)
233 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
234 if (color_parse(color_value, atom->u.color) < 0)
235 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
236 color_value);
238 * We check this after we've parsed the color, which lets us complain
239 * about syntactically bogus color names even if they won't be used.
241 if (!want_color(format->use_color))
242 color_parse("", atom->u.color);
243 return 0;
246 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
247 const char *name, struct strbuf *err)
249 if (!arg)
250 atom->option = R_NORMAL;
251 else if (!strcmp(arg, "short"))
252 atom->option = R_SHORT;
253 else if (skip_prefix(arg, "lstrip=", &arg) ||
254 skip_prefix(arg, "strip=", &arg)) {
255 atom->option = R_LSTRIP;
256 if (strtol_i(arg, 10, &atom->lstrip))
257 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
258 } else if (skip_prefix(arg, "rstrip=", &arg)) {
259 atom->option = R_RSTRIP;
260 if (strtol_i(arg, 10, &atom->rstrip))
261 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
262 } else
263 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
264 return 0;
267 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
268 const char *arg, struct strbuf *err)
270 struct string_list params = STRING_LIST_INIT_DUP;
271 int i;
273 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
274 atom->u.remote_ref.push = 1;
276 if (!arg) {
277 atom->u.remote_ref.option = RR_REF;
278 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
279 arg, atom->name, err);
282 atom->u.remote_ref.nobracket = 0;
283 string_list_split(&params, arg, ',', -1);
285 for (i = 0; i < params.nr; i++) {
286 const char *s = params.items[i].string;
288 if (!strcmp(s, "track"))
289 atom->u.remote_ref.option = RR_TRACK;
290 else if (!strcmp(s, "trackshort"))
291 atom->u.remote_ref.option = RR_TRACKSHORT;
292 else if (!strcmp(s, "nobracket"))
293 atom->u.remote_ref.nobracket = 1;
294 else if (!strcmp(s, "remotename")) {
295 atom->u.remote_ref.option = RR_REMOTE_NAME;
296 atom->u.remote_ref.push_remote = 1;
297 } else if (!strcmp(s, "remoteref")) {
298 atom->u.remote_ref.option = RR_REMOTE_REF;
299 atom->u.remote_ref.push_remote = 1;
300 } else {
301 atom->u.remote_ref.option = RR_REF;
302 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
303 arg, atom->name, err)) {
304 string_list_clear(&params, 0);
305 return -1;
310 string_list_clear(&params, 0);
311 return 0;
314 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
315 const char *arg, struct strbuf *err)
317 if (arg)
318 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
319 if (*atom->name == '*')
320 oi_deref.info.typep = &oi_deref.type;
321 else
322 oi.info.typep = &oi.type;
323 return 0;
326 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
327 const char *arg, struct strbuf *err)
329 if (!arg) {
330 atom->u.objectsize.option = O_SIZE;
331 if (*atom->name == '*')
332 oi_deref.info.sizep = &oi_deref.size;
333 else
334 oi.info.sizep = &oi.size;
335 } else if (!strcmp(arg, "disk")) {
336 atom->u.objectsize.option = O_SIZE_DISK;
337 if (*atom->name == '*')
338 oi_deref.info.disk_sizep = &oi_deref.disk_size;
339 else
340 oi.info.disk_sizep = &oi.disk_size;
341 } else
342 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
343 return 0;
346 static int deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom,
347 const char *arg, struct strbuf *err)
349 if (arg)
350 return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
351 if (*atom->name == '*')
352 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
353 else
354 oi.info.delta_base_oid = &oi.delta_base_oid;
355 return 0;
358 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
359 const char *arg, struct strbuf *err)
361 if (arg)
362 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
363 atom->u.contents.option = C_BODY_DEP;
364 return 0;
367 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
368 const char *arg, struct strbuf *err)
370 if (!arg)
371 atom->u.contents.option = C_SUB;
372 else if (!strcmp(arg, "sanitize"))
373 atom->u.contents.option = C_SUB_SANITIZE;
374 else
375 return strbuf_addf_ret(err, -1, _("unrecognized %%(subject) argument: %s"), arg);
376 return 0;
379 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
380 const char *arg, struct strbuf *err)
382 atom->u.contents.trailer_opts.no_divider = 1;
384 if (arg) {
385 const char *argbuf = xstrfmt("%s)", arg);
386 char *invalid_arg = NULL;
388 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
389 &ref_trailer_buf.filter_list,
390 &ref_trailer_buf.sepbuf,
391 &ref_trailer_buf.kvsepbuf,
392 &argbuf, &invalid_arg)) {
393 if (!invalid_arg)
394 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
395 else
396 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
397 free((char *)invalid_arg);
398 return -1;
401 atom->u.contents.option = C_TRAILERS;
402 return 0;
405 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
406 const char *arg, struct strbuf *err)
408 if (!arg)
409 atom->u.contents.option = C_BARE;
410 else if (!strcmp(arg, "body"))
411 atom->u.contents.option = C_BODY;
412 else if (!strcmp(arg, "size"))
413 atom->u.contents.option = C_LENGTH;
414 else if (!strcmp(arg, "signature"))
415 atom->u.contents.option = C_SIG;
416 else if (!strcmp(arg, "subject"))
417 atom->u.contents.option = C_SUB;
418 else if (!strcmp(arg, "trailers")) {
419 if (trailers_atom_parser(format, atom, NULL, err))
420 return -1;
421 } else if (skip_prefix(arg, "trailers:", &arg)) {
422 if (trailers_atom_parser(format, atom, arg, err))
423 return -1;
424 } else if (skip_prefix(arg, "lines=", &arg)) {
425 atom->u.contents.option = C_LINES;
426 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
427 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
428 } else
429 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
430 return 0;
433 static int raw_atom_parser(const struct ref_format *format, struct used_atom *atom,
434 const char *arg, struct strbuf *err)
436 if (!arg)
437 atom->u.raw_data.option = RAW_BARE;
438 else if (!strcmp(arg, "size"))
439 atom->u.raw_data.option = RAW_LENGTH;
440 else
441 return strbuf_addf_ret(err, -1, _("unrecognized %%(raw) argument: %s"), arg);
442 return 0;
445 static int oid_atom_parser(const struct ref_format *format, struct used_atom *atom,
446 const char *arg, struct strbuf *err)
448 if (!arg)
449 atom->u.oid.option = O_FULL;
450 else if (!strcmp(arg, "short"))
451 atom->u.oid.option = O_SHORT;
452 else if (skip_prefix(arg, "short=", &arg)) {
453 atom->u.oid.option = O_LENGTH;
454 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
455 atom->u.oid.length == 0)
456 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
457 if (atom->u.oid.length < MINIMUM_ABBREV)
458 atom->u.oid.length = MINIMUM_ABBREV;
459 } else
460 return strbuf_addf_ret(err, -1, _("unrecognized argument '%s' in %%(%s)"), arg, atom->name);
461 return 0;
464 static int person_email_atom_parser(const struct ref_format *format, struct used_atom *atom,
465 const char *arg, struct strbuf *err)
467 if (!arg)
468 atom->u.email_option.option = EO_RAW;
469 else if (!strcmp(arg, "trim"))
470 atom->u.email_option.option = EO_TRIM;
471 else if (!strcmp(arg, "localpart"))
472 atom->u.email_option.option = EO_LOCALPART;
473 else
474 return strbuf_addf_ret(err, -1, _("unrecognized email option: %s"), arg);
475 return 0;
478 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
479 const char *arg, struct strbuf *err)
481 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
484 static align_type parse_align_position(const char *s)
486 if (!strcmp(s, "right"))
487 return ALIGN_RIGHT;
488 else if (!strcmp(s, "middle"))
489 return ALIGN_MIDDLE;
490 else if (!strcmp(s, "left"))
491 return ALIGN_LEFT;
492 return -1;
495 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
496 const char *arg, struct strbuf *err)
498 struct align *align = &atom->u.align;
499 struct string_list params = STRING_LIST_INIT_DUP;
500 int i;
501 unsigned int width = ~0U;
503 if (!arg)
504 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
506 align->position = ALIGN_LEFT;
508 string_list_split(&params, arg, ',', -1);
509 for (i = 0; i < params.nr; i++) {
510 const char *s = params.items[i].string;
511 int position;
513 if (skip_prefix(s, "position=", &s)) {
514 position = parse_align_position(s);
515 if (position < 0) {
516 strbuf_addf(err, _("unrecognized position:%s"), s);
517 string_list_clear(&params, 0);
518 return -1;
520 align->position = position;
521 } else if (skip_prefix(s, "width=", &s)) {
522 if (strtoul_ui(s, 10, &width)) {
523 strbuf_addf(err, _("unrecognized width:%s"), s);
524 string_list_clear(&params, 0);
525 return -1;
527 } else if (!strtoul_ui(s, 10, &width))
529 else if ((position = parse_align_position(s)) >= 0)
530 align->position = position;
531 else {
532 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
533 string_list_clear(&params, 0);
534 return -1;
538 if (width == ~0U) {
539 string_list_clear(&params, 0);
540 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
542 align->width = width;
543 string_list_clear(&params, 0);
544 return 0;
547 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
548 const char *arg, struct strbuf *err)
550 if (!arg) {
551 atom->u.if_then_else.cmp_status = COMPARE_NONE;
552 return 0;
553 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
554 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
555 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
556 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
557 } else
558 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
559 return 0;
562 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
563 const char *arg, struct strbuf *unused_err)
565 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
566 return 0;
569 static struct {
570 const char *name;
571 info_source source;
572 cmp_type cmp_type;
573 int (*parser)(const struct ref_format *format, struct used_atom *atom,
574 const char *arg, struct strbuf *err);
575 } valid_atom[] = {
576 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
577 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
578 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
579 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
580 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
581 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
582 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
583 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
584 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
585 [ATOM_TYPE] = { "type", SOURCE_OBJ },
586 [ATOM_TAG] = { "tag", SOURCE_OBJ },
587 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
588 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
589 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
590 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
591 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
592 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
593 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
594 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
595 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
596 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
597 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
598 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
599 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
600 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
601 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
602 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
603 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
604 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
605 [ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },
606 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
607 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
608 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
609 [ATOM_FLAG] = { "flag", SOURCE_NONE },
610 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
611 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
612 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
613 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
614 [ATOM_END] = { "end", SOURCE_NONE },
615 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
616 [ATOM_THEN] = { "then", SOURCE_NONE },
617 [ATOM_ELSE] = { "else", SOURCE_NONE },
619 * Please update $__git_ref_fieldlist in git-completion.bash
620 * when you add new atoms
624 #define REF_FORMATTING_STATE_INIT { 0, NULL }
626 struct ref_formatting_stack {
627 struct ref_formatting_stack *prev;
628 struct strbuf output;
629 void (*at_end)(struct ref_formatting_stack **stack);
630 void *at_end_data;
633 struct ref_formatting_state {
634 int quote_style;
635 struct ref_formatting_stack *stack;
638 struct atom_value {
639 const char *s;
640 ssize_t s_size;
641 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
642 struct strbuf *err);
643 uintmax_t value; /* used for sorting when not FIELD_STR */
644 struct used_atom *atom;
647 #define ATOM_SIZE_UNSPECIFIED (-1)
649 #define ATOM_VALUE_INIT { \
650 .s_size = ATOM_SIZE_UNSPECIFIED \
654 * Used to parse format string and sort specifiers
656 static int parse_ref_filter_atom(const struct ref_format *format,
657 const char *atom, const char *ep,
658 struct strbuf *err)
660 const char *sp;
661 const char *arg;
662 int i, at, atom_len;
664 sp = atom;
665 if (*sp == '*' && sp < ep)
666 sp++; /* deref */
667 if (ep <= sp)
668 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
669 (int)(ep-atom), atom);
672 * If the atom name has a colon, strip it and everything after
673 * it off - it specifies the format for this entry, and
674 * shouldn't be used for checking against the valid_atom
675 * table.
677 arg = memchr(sp, ':', ep - sp);
678 atom_len = (arg ? arg : ep) - sp;
680 /* Do we have the atom already used elsewhere? */
681 for (i = 0; i < used_atom_cnt; i++) {
682 int len = strlen(used_atom[i].name);
683 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
684 return i;
687 /* Is the atom a valid one? */
688 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
689 int len = strlen(valid_atom[i].name);
690 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
691 break;
694 if (ARRAY_SIZE(valid_atom) <= i)
695 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
696 (int)(ep-atom), atom);
697 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
698 return strbuf_addf_ret(err, -1,
699 _("not a git repository, but the field '%.*s' requires access to object data"),
700 (int)(ep-atom), atom);
702 /* Add it in, including the deref prefix */
703 at = used_atom_cnt;
704 used_atom_cnt++;
705 REALLOC_ARRAY(used_atom, used_atom_cnt);
706 used_atom[at].atom_type = i;
707 used_atom[at].name = xmemdupz(atom, ep - atom);
708 used_atom[at].type = valid_atom[i].cmp_type;
709 used_atom[at].source = valid_atom[i].source;
710 if (used_atom[at].source == SOURCE_OBJ) {
711 if (*atom == '*')
712 oi_deref.info.contentp = &oi_deref.content;
713 else
714 oi.info.contentp = &oi.content;
716 if (arg) {
717 arg = used_atom[at].name + (arg - atom) + 1;
718 if (!*arg) {
720 * Treat empty sub-arguments list as NULL (i.e.,
721 * "%(atom:)" is equivalent to "%(atom)").
723 arg = NULL;
726 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
727 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
728 return -1;
729 if (*atom == '*')
730 need_tagged = 1;
731 if (i == ATOM_SYMREF)
732 need_symref = 1;
733 return at;
736 static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)
738 switch (quote_style) {
739 case QUOTE_NONE:
740 if (len < 0)
741 strbuf_addstr(s, str);
742 else
743 strbuf_add(s, str, len);
744 break;
745 case QUOTE_SHELL:
746 sq_quote_buf(s, str);
747 break;
748 case QUOTE_PERL:
749 perl_quote_buf(s, str);
750 break;
751 case QUOTE_PYTHON:
752 python_quote_buf(s, str);
753 break;
754 case QUOTE_TCL:
755 tcl_quote_buf(s, str);
756 break;
760 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
761 struct strbuf *unused_err)
764 * Quote formatting is only done when the stack has a single
765 * element. Otherwise quote formatting is done on the
766 * element's entire output strbuf when the %(end) atom is
767 * encountered.
769 if (!state->stack->prev)
770 quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);
771 else if (v->s_size < 0)
772 strbuf_addstr(&state->stack->output, v->s);
773 else
774 strbuf_add(&state->stack->output, v->s, v->s_size);
775 return 0;
778 static void push_stack_element(struct ref_formatting_stack **stack)
780 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
782 strbuf_init(&s->output, 0);
783 s->prev = *stack;
784 *stack = s;
787 static void pop_stack_element(struct ref_formatting_stack **stack)
789 struct ref_formatting_stack *current = *stack;
790 struct ref_formatting_stack *prev = current->prev;
792 if (prev)
793 strbuf_addbuf(&prev->output, &current->output);
794 strbuf_release(&current->output);
795 free(current);
796 *stack = prev;
799 static void end_align_handler(struct ref_formatting_stack **stack)
801 struct ref_formatting_stack *cur = *stack;
802 struct align *align = (struct align *)cur->at_end_data;
803 struct strbuf s = STRBUF_INIT;
805 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
806 strbuf_swap(&cur->output, &s);
807 strbuf_release(&s);
810 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
811 struct strbuf *unused_err)
813 struct ref_formatting_stack *new_stack;
815 push_stack_element(&state->stack);
816 new_stack = state->stack;
817 new_stack->at_end = end_align_handler;
818 new_stack->at_end_data = &atomv->atom->u.align;
819 return 0;
822 static void if_then_else_handler(struct ref_formatting_stack **stack)
824 struct ref_formatting_stack *cur = *stack;
825 struct ref_formatting_stack *prev = cur->prev;
826 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
828 if (!if_then_else->then_atom_seen)
829 die(_("format: %%(if) atom used without a %%(then) atom"));
831 if (if_then_else->else_atom_seen) {
833 * There is an %(else) atom: we need to drop one state from the
834 * stack, either the %(else) branch if the condition is satisfied, or
835 * the %(then) branch if it isn't.
837 if (if_then_else->condition_satisfied) {
838 strbuf_reset(&cur->output);
839 pop_stack_element(&cur);
840 } else {
841 strbuf_swap(&cur->output, &prev->output);
842 strbuf_reset(&cur->output);
843 pop_stack_element(&cur);
845 } else if (!if_then_else->condition_satisfied) {
847 * No %(else) atom: just drop the %(then) branch if the
848 * condition is not satisfied.
850 strbuf_reset(&cur->output);
853 *stack = cur;
854 free(if_then_else);
857 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
858 struct strbuf *unused_err)
860 struct ref_formatting_stack *new_stack;
861 struct if_then_else *if_then_else = xcalloc(1,
862 sizeof(struct if_then_else));
864 if_then_else->str = atomv->atom->u.if_then_else.str;
865 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
867 push_stack_element(&state->stack);
868 new_stack = state->stack;
869 new_stack->at_end = if_then_else_handler;
870 new_stack->at_end_data = if_then_else;
871 return 0;
874 static int is_empty(struct strbuf *buf)
876 const char *cur = buf->buf;
877 const char *end = buf->buf + buf->len;
879 while (cur != end && (isspace(*cur)))
880 cur++;
882 return cur == end;
885 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
886 struct strbuf *err)
888 struct ref_formatting_stack *cur = state->stack;
889 struct if_then_else *if_then_else = NULL;
890 size_t str_len = 0;
892 if (cur->at_end == if_then_else_handler)
893 if_then_else = (struct if_then_else *)cur->at_end_data;
894 if (!if_then_else)
895 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
896 if (if_then_else->then_atom_seen)
897 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
898 if (if_then_else->else_atom_seen)
899 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
900 if_then_else->then_atom_seen = 1;
901 if (if_then_else->str)
902 str_len = strlen(if_then_else->str);
904 * If the 'equals' or 'notequals' attribute is used then
905 * perform the required comparison. If not, only non-empty
906 * strings satisfy the 'if' condition.
908 if (if_then_else->cmp_status == COMPARE_EQUAL) {
909 if (str_len == cur->output.len &&
910 !memcmp(if_then_else->str, cur->output.buf, cur->output.len))
911 if_then_else->condition_satisfied = 1;
912 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
913 if (str_len != cur->output.len ||
914 memcmp(if_then_else->str, cur->output.buf, cur->output.len))
915 if_then_else->condition_satisfied = 1;
916 } else if (cur->output.len && !is_empty(&cur->output))
917 if_then_else->condition_satisfied = 1;
918 strbuf_reset(&cur->output);
919 return 0;
922 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
923 struct strbuf *err)
925 struct ref_formatting_stack *prev = state->stack;
926 struct if_then_else *if_then_else = NULL;
928 if (prev->at_end == if_then_else_handler)
929 if_then_else = (struct if_then_else *)prev->at_end_data;
930 if (!if_then_else)
931 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
932 if (!if_then_else->then_atom_seen)
933 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
934 if (if_then_else->else_atom_seen)
935 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
936 if_then_else->else_atom_seen = 1;
937 push_stack_element(&state->stack);
938 state->stack->at_end_data = prev->at_end_data;
939 state->stack->at_end = prev->at_end;
940 return 0;
943 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
944 struct strbuf *err)
946 struct ref_formatting_stack *current = state->stack;
947 struct strbuf s = STRBUF_INIT;
949 if (!current->at_end)
950 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
951 current->at_end(&state->stack);
953 /* Stack may have been popped within at_end(), hence reset the current pointer */
954 current = state->stack;
957 * Perform quote formatting when the stack element is that of
958 * a supporting atom. If nested then perform quote formatting
959 * only on the topmost supporting atom.
961 if (!current->prev->prev) {
962 quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);
963 strbuf_swap(&current->output, &s);
965 strbuf_release(&s);
966 pop_stack_element(&state->stack);
967 return 0;
971 * In a format string, find the next occurrence of %(atom).
973 static const char *find_next(const char *cp)
975 while (*cp) {
976 if (*cp == '%') {
978 * %( is the start of an atom;
979 * %% is a quoted per-cent.
981 if (cp[1] == '(')
982 return cp;
983 else if (cp[1] == '%')
984 cp++; /* skip over two % */
985 /* otherwise this is a singleton, literal % */
987 cp++;
989 return NULL;
993 * Make sure the format string is well formed, and parse out
994 * the used atoms.
996 int verify_ref_format(struct ref_format *format)
998 const char *cp, *sp;
1000 format->need_color_reset_at_eol = 0;
1001 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
1002 struct strbuf err = STRBUF_INIT;
1003 const char *color, *ep = strchr(sp, ')');
1004 int at;
1006 if (!ep)
1007 return error(_("malformed format string %s"), sp);
1008 /* sp points at "%(" and ep points at the closing ")" */
1009 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
1010 if (at < 0)
1011 die("%s", err.buf);
1012 if (format->quote_style && used_atom[at].atom_type == ATOM_RAW &&
1013 used_atom[at].u.raw_data.option == RAW_BARE)
1014 die(_("--format=%.*s cannot be used with"
1015 "--python, --shell, --tcl, --perl"), (int)(ep - sp - 2), sp + 2);
1016 cp = ep + 1;
1018 if (skip_prefix(used_atom[at].name, "color:", &color))
1019 format->need_color_reset_at_eol = !!strcmp(color, "reset");
1020 strbuf_release(&err);
1022 if (format->need_color_reset_at_eol && !want_color(format->use_color))
1023 format->need_color_reset_at_eol = 0;
1024 return 0;
1027 static const char *do_grab_oid(const char *field, const struct object_id *oid,
1028 struct used_atom *atom)
1030 switch (atom->u.oid.option) {
1031 case O_FULL:
1032 return oid_to_hex(oid);
1033 case O_LENGTH:
1034 return find_unique_abbrev(oid, atom->u.oid.length);
1035 case O_SHORT:
1036 return find_unique_abbrev(oid, DEFAULT_ABBREV);
1037 default:
1038 BUG("unknown %%(%s) option", field);
1042 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1043 struct atom_value *v, struct used_atom *atom)
1045 if (starts_with(name, field)) {
1046 v->s = xstrdup(do_grab_oid(field, oid, atom));
1047 return 1;
1049 return 0;
1052 /* See grab_values */
1053 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1055 int i;
1057 for (i = 0; i < used_atom_cnt; i++) {
1058 const char *name = used_atom[i].name;
1059 enum atom_type atom_type = used_atom[i].atom_type;
1060 struct atom_value *v = &val[i];
1061 if (!!deref != (*name == '*'))
1062 continue;
1063 if (deref)
1064 name++;
1065 if (atom_type == ATOM_OBJECTTYPE)
1066 v->s = xstrdup(type_name(oi->type));
1067 else if (atom_type == ATOM_OBJECTSIZE) {
1068 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1069 v->value = oi->disk_size;
1070 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1071 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1072 v->value = oi->size;
1073 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1075 } else if (atom_type == ATOM_DELTABASE)
1076 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1077 else if (atom_type == ATOM_OBJECTNAME && deref)
1078 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1082 /* See grab_values */
1083 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1085 int i;
1086 struct tag *tag = (struct tag *) obj;
1088 for (i = 0; i < used_atom_cnt; i++) {
1089 const char *name = used_atom[i].name;
1090 enum atom_type atom_type = used_atom[i].atom_type;
1091 struct atom_value *v = &val[i];
1092 if (!!deref != (*name == '*'))
1093 continue;
1094 if (deref)
1095 name++;
1096 if (atom_type == ATOM_TAG)
1097 v->s = xstrdup(tag->tag);
1098 else if (atom_type == ATOM_TYPE && tag->tagged)
1099 v->s = xstrdup(type_name(tag->tagged->type));
1100 else if (atom_type == ATOM_OBJECT && tag->tagged)
1101 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1105 /* See grab_values */
1106 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1108 int i;
1109 struct commit *commit = (struct commit *) obj;
1111 for (i = 0; i < used_atom_cnt; i++) {
1112 const char *name = used_atom[i].name;
1113 enum atom_type atom_type = used_atom[i].atom_type;
1114 struct atom_value *v = &val[i];
1115 if (!!deref != (*name == '*'))
1116 continue;
1117 if (deref)
1118 name++;
1119 if (atom_type == ATOM_TREE &&
1120 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1121 continue;
1122 if (atom_type == ATOM_NUMPARENT) {
1123 v->value = commit_list_count(commit->parents);
1124 v->s = xstrfmt("%lu", (unsigned long)v->value);
1126 else if (atom_type == ATOM_PARENT) {
1127 struct commit_list *parents;
1128 struct strbuf s = STRBUF_INIT;
1129 for (parents = commit->parents; parents; parents = parents->next) {
1130 struct object_id *oid = &parents->item->object.oid;
1131 if (parents != commit->parents)
1132 strbuf_addch(&s, ' ');
1133 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1135 v->s = strbuf_detach(&s, NULL);
1140 static const char *find_wholine(const char *who, int wholen, const char *buf)
1142 const char *eol;
1143 while (*buf) {
1144 if (!strncmp(buf, who, wholen) &&
1145 buf[wholen] == ' ')
1146 return buf + wholen + 1;
1147 eol = strchr(buf, '\n');
1148 if (!eol)
1149 return "";
1150 eol++;
1151 if (*eol == '\n')
1152 return ""; /* end of header */
1153 buf = eol;
1155 return "";
1158 static const char *copy_line(const char *buf)
1160 const char *eol = strchrnul(buf, '\n');
1161 return xmemdupz(buf, eol - buf);
1164 static const char *copy_name(const char *buf)
1166 const char *cp;
1167 for (cp = buf; *cp && *cp != '\n'; cp++) {
1168 if (!strncmp(cp, " <", 2))
1169 return xmemdupz(buf, cp - buf);
1171 return xstrdup("");
1174 static const char *copy_email(const char *buf, struct used_atom *atom)
1176 const char *email = strchr(buf, '<');
1177 const char *eoemail;
1178 if (!email)
1179 return xstrdup("");
1180 switch (atom->u.email_option.option) {
1181 case EO_RAW:
1182 eoemail = strchr(email, '>');
1183 if (eoemail)
1184 eoemail++;
1185 break;
1186 case EO_TRIM:
1187 email++;
1188 eoemail = strchr(email, '>');
1189 break;
1190 case EO_LOCALPART:
1191 email++;
1192 eoemail = strchr(email, '@');
1193 if (!eoemail)
1194 eoemail = strchr(email, '>');
1195 break;
1196 default:
1197 BUG("unknown email option");
1200 if (!eoemail)
1201 return xstrdup("");
1202 return xmemdupz(email, eoemail - email);
1205 static char *copy_subject(const char *buf, unsigned long len)
1207 struct strbuf sb = STRBUF_INIT;
1208 int i;
1210 for (i = 0; i < len; i++) {
1211 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1212 continue; /* ignore CR in CRLF */
1214 if (buf[i] == '\n')
1215 strbuf_addch(&sb, ' ');
1216 else
1217 strbuf_addch(&sb, buf[i]);
1219 return strbuf_detach(&sb, NULL);
1222 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1224 const char *eoemail = strstr(buf, "> ");
1225 char *zone;
1226 timestamp_t timestamp;
1227 long tz;
1228 struct date_mode date_mode = { DATE_NORMAL };
1229 const char *formatp;
1232 * We got here because atomname ends in "date" or "date<something>";
1233 * it's not possible that <something> is not ":<format>" because
1234 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1235 * ":" means no format is specified, and use the default.
1237 formatp = strchr(atomname, ':');
1238 if (formatp != NULL) {
1239 formatp++;
1240 parse_date_format(formatp, &date_mode);
1243 if (!eoemail)
1244 goto bad;
1245 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1246 if (timestamp == TIME_MAX)
1247 goto bad;
1248 tz = strtol(zone, NULL, 10);
1249 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1250 goto bad;
1251 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1252 v->value = timestamp;
1253 return;
1254 bad:
1255 v->s = xstrdup("");
1256 v->value = 0;
1259 /* See grab_values */
1260 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1262 int i;
1263 int wholen = strlen(who);
1264 const char *wholine = NULL;
1266 for (i = 0; i < used_atom_cnt; i++) {
1267 const char *name = used_atom[i].name;
1268 struct atom_value *v = &val[i];
1269 if (!!deref != (*name == '*'))
1270 continue;
1271 if (deref)
1272 name++;
1273 if (strncmp(who, name, wholen))
1274 continue;
1275 if (name[wholen] != 0 &&
1276 strcmp(name + wholen, "name") &&
1277 !starts_with(name + wholen, "email") &&
1278 !starts_with(name + wholen, "date"))
1279 continue;
1280 if (!wholine)
1281 wholine = find_wholine(who, wholen, buf);
1282 if (!wholine)
1283 return; /* no point looking for it */
1284 if (name[wholen] == 0)
1285 v->s = copy_line(wholine);
1286 else if (!strcmp(name + wholen, "name"))
1287 v->s = copy_name(wholine);
1288 else if (starts_with(name + wholen, "email"))
1289 v->s = copy_email(wholine, &used_atom[i]);
1290 else if (starts_with(name + wholen, "date"))
1291 grab_date(wholine, v, name);
1295 * For a tag or a commit object, if "creator" or "creatordate" is
1296 * requested, do something special.
1298 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1299 return; /* "author" for commit object is not wanted */
1300 if (!wholine)
1301 wholine = find_wholine(who, wholen, buf);
1302 if (!wholine)
1303 return;
1304 for (i = 0; i < used_atom_cnt; i++) {
1305 const char *name = used_atom[i].name;
1306 enum atom_type atom_type = used_atom[i].atom_type;
1307 struct atom_value *v = &val[i];
1308 if (!!deref != (*name == '*'))
1309 continue;
1310 if (deref)
1311 name++;
1313 if (atom_type == ATOM_CREATORDATE)
1314 grab_date(wholine, v, name);
1315 else if (atom_type == ATOM_CREATOR)
1316 v->s = copy_line(wholine);
1320 static void find_subpos(const char *buf,
1321 const char **sub, size_t *sublen,
1322 const char **body, size_t *bodylen,
1323 size_t *nonsiglen,
1324 const char **sig, size_t *siglen)
1326 struct strbuf payload = STRBUF_INIT;
1327 struct strbuf signature = STRBUF_INIT;
1328 const char *eol;
1329 const char *end = buf + strlen(buf);
1330 const char *sigstart;
1332 /* parse signature first; we might not even have a subject line */
1333 parse_signature(buf, end - buf, &payload, &signature);
1335 /* skip past header until we hit empty line */
1336 while (*buf && *buf != '\n') {
1337 eol = strchrnul(buf, '\n');
1338 if (*eol)
1339 eol++;
1340 buf = eol;
1342 /* skip any empty lines */
1343 while (*buf == '\n')
1344 buf++;
1345 *sig = strbuf_detach(&signature, siglen);
1346 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1348 /* subject is first non-empty line */
1349 *sub = buf;
1350 /* subject goes to first empty line before signature begins */
1351 if ((eol = strstr(*sub, "\n\n"))) {
1352 eol = eol < sigstart ? eol : sigstart;
1353 /* check if message uses CRLF */
1354 } else if (! (eol = strstr(*sub, "\r\n\r\n"))) {
1355 /* treat whole message as subject */
1356 eol = strrchr(*sub, '\0');
1358 buf = eol;
1359 *sublen = buf - *sub;
1360 /* drop trailing newline, if present */
1361 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1362 (*sub)[*sublen - 1] == '\r'))
1363 *sublen -= 1;
1365 /* skip any empty lines */
1366 while (*buf == '\n' || *buf == '\r')
1367 buf++;
1368 *body = buf;
1369 *bodylen = strlen(buf);
1370 *nonsiglen = sigstart - buf;
1374 * If 'lines' is greater than 0, append that many lines from the given
1375 * 'buf' of length 'size' to the given strbuf.
1377 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1379 int i;
1380 const char *sp, *eol;
1381 size_t len;
1383 sp = buf;
1385 for (i = 0; i < lines && sp < buf + size; i++) {
1386 if (i)
1387 strbuf_addstr(out, "\n ");
1388 eol = memchr(sp, '\n', size - (sp - buf));
1389 len = eol ? eol - sp : size - (sp - buf);
1390 strbuf_add(out, sp, len);
1391 if (!eol)
1392 break;
1393 sp = eol + 1;
1397 /* See grab_values */
1398 static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)
1400 int i;
1401 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1402 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1403 void *buf = data->content;
1405 for (i = 0; i < used_atom_cnt; i++) {
1406 struct used_atom *atom = &used_atom[i];
1407 const char *name = atom->name;
1408 struct atom_value *v = &val[i];
1409 enum atom_type atom_type = atom->atom_type;
1411 if (!!deref != (*name == '*'))
1412 continue;
1413 if (deref)
1414 name++;
1416 if (atom_type == ATOM_RAW) {
1417 unsigned long buf_size = data->size;
1419 if (atom->u.raw_data.option == RAW_BARE) {
1420 v->s = xmemdupz(buf, buf_size);
1421 v->s_size = buf_size;
1422 } else if (atom->u.raw_data.option == RAW_LENGTH) {
1423 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)buf_size);
1425 continue;
1428 if ((data->type != OBJ_TAG &&
1429 data->type != OBJ_COMMIT) ||
1430 (strcmp(name, "body") &&
1431 !starts_with(name, "subject") &&
1432 !starts_with(name, "trailers") &&
1433 !starts_with(name, "contents")))
1434 continue;
1435 if (!subpos)
1436 find_subpos(buf,
1437 &subpos, &sublen,
1438 &bodypos, &bodylen, &nonsiglen,
1439 &sigpos, &siglen);
1441 if (atom->u.contents.option == C_SUB)
1442 v->s = copy_subject(subpos, sublen);
1443 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1444 struct strbuf sb = STRBUF_INIT;
1445 format_sanitized_subject(&sb, subpos, sublen);
1446 v->s = strbuf_detach(&sb, NULL);
1447 } else if (atom->u.contents.option == C_BODY_DEP)
1448 v->s = xmemdupz(bodypos, bodylen);
1449 else if (atom->u.contents.option == C_LENGTH)
1450 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1451 else if (atom->u.contents.option == C_BODY)
1452 v->s = xmemdupz(bodypos, nonsiglen);
1453 else if (atom->u.contents.option == C_SIG)
1454 v->s = xmemdupz(sigpos, siglen);
1455 else if (atom->u.contents.option == C_LINES) {
1456 struct strbuf s = STRBUF_INIT;
1457 const char *contents_end = bodypos + nonsiglen;
1459 /* Size is the length of the message after removing the signature */
1460 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1461 v->s = strbuf_detach(&s, NULL);
1462 } else if (atom->u.contents.option == C_TRAILERS) {
1463 struct strbuf s = STRBUF_INIT;
1465 /* Format the trailer info according to the trailer_opts given */
1466 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1468 v->s = strbuf_detach(&s, NULL);
1469 } else if (atom->u.contents.option == C_BARE)
1470 v->s = xstrdup(subpos);
1473 free((void *)sigpos);
1477 * We want to have empty print-string for field requests
1478 * that do not apply (e.g. "authordate" for a tag object)
1480 static void fill_missing_values(struct atom_value *val)
1482 int i;
1483 for (i = 0; i < used_atom_cnt; i++) {
1484 struct atom_value *v = &val[i];
1485 if (v->s == NULL)
1486 v->s = xstrdup("");
1491 * val is a list of atom_value to hold returned values. Extract
1492 * the values for atoms in used_atom array out of (obj, buf, sz).
1493 * when deref is false, (obj, buf, sz) is the object that is
1494 * pointed at by the ref itself; otherwise it is the object the
1495 * ref (which is a tag) refers to.
1497 static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)
1499 void *buf = data->content;
1501 switch (obj->type) {
1502 case OBJ_TAG:
1503 grab_tag_values(val, deref, obj);
1504 grab_sub_body_contents(val, deref, data);
1505 grab_person("tagger", val, deref, buf);
1506 break;
1507 case OBJ_COMMIT:
1508 grab_commit_values(val, deref, obj);
1509 grab_sub_body_contents(val, deref, data);
1510 grab_person("author", val, deref, buf);
1511 grab_person("committer", val, deref, buf);
1512 break;
1513 case OBJ_TREE:
1514 /* grab_tree_values(val, deref, obj, buf, sz); */
1515 grab_sub_body_contents(val, deref, data);
1516 break;
1517 case OBJ_BLOB:
1518 /* grab_blob_values(val, deref, obj, buf, sz); */
1519 grab_sub_body_contents(val, deref, data);
1520 break;
1521 default:
1522 die("Eh? Object of type %d?", obj->type);
1526 static inline char *copy_advance(char *dst, const char *src)
1528 while (*src)
1529 *dst++ = *src++;
1530 return dst;
1533 static const char *lstrip_ref_components(const char *refname, int len)
1535 long remaining = len;
1536 const char *start = xstrdup(refname);
1537 const char *to_free = start;
1539 if (len < 0) {
1540 int i;
1541 const char *p = refname;
1543 /* Find total no of '/' separated path-components */
1544 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1547 * The number of components we need to strip is now
1548 * the total minus the components to be left (Plus one
1549 * because we count the number of '/', but the number
1550 * of components is one more than the no of '/').
1552 remaining = i + len + 1;
1555 while (remaining > 0) {
1556 switch (*start++) {
1557 case '\0':
1558 free((char *)to_free);
1559 return xstrdup("");
1560 case '/':
1561 remaining--;
1562 break;
1566 start = xstrdup(start);
1567 free((char *)to_free);
1568 return start;
1571 static const char *rstrip_ref_components(const char *refname, int len)
1573 long remaining = len;
1574 const char *start = xstrdup(refname);
1575 const char *to_free = start;
1577 if (len < 0) {
1578 int i;
1579 const char *p = refname;
1581 /* Find total no of '/' separated path-components */
1582 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1585 * The number of components we need to strip is now
1586 * the total minus the components to be left (Plus one
1587 * because we count the number of '/', but the number
1588 * of components is one more than the no of '/').
1590 remaining = i + len + 1;
1593 while (remaining-- > 0) {
1594 char *p = strrchr(start, '/');
1595 if (p == NULL) {
1596 free((char *)to_free);
1597 return xstrdup("");
1598 } else
1599 p[0] = '\0';
1601 return start;
1604 static const char *show_ref(struct refname_atom *atom, const char *refname)
1606 if (atom->option == R_SHORT)
1607 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1608 else if (atom->option == R_LSTRIP)
1609 return lstrip_ref_components(refname, atom->lstrip);
1610 else if (atom->option == R_RSTRIP)
1611 return rstrip_ref_components(refname, atom->rstrip);
1612 else
1613 return xstrdup(refname);
1616 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1617 struct branch *branch, const char **s)
1619 int num_ours, num_theirs;
1620 if (atom->u.remote_ref.option == RR_REF)
1621 *s = show_ref(&atom->u.remote_ref.refname, refname);
1622 else if (atom->u.remote_ref.option == RR_TRACK) {
1623 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1624 NULL, atom->u.remote_ref.push,
1625 AHEAD_BEHIND_FULL) < 0) {
1626 *s = xstrdup(msgs.gone);
1627 } else if (!num_ours && !num_theirs)
1628 *s = xstrdup("");
1629 else if (!num_ours)
1630 *s = xstrfmt(msgs.behind, num_theirs);
1631 else if (!num_theirs)
1632 *s = xstrfmt(msgs.ahead, num_ours);
1633 else
1634 *s = xstrfmt(msgs.ahead_behind,
1635 num_ours, num_theirs);
1636 if (!atom->u.remote_ref.nobracket && *s[0]) {
1637 const char *to_free = *s;
1638 *s = xstrfmt("[%s]", *s);
1639 free((void *)to_free);
1641 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1642 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1643 NULL, atom->u.remote_ref.push,
1644 AHEAD_BEHIND_FULL) < 0) {
1645 *s = xstrdup("");
1646 return;
1648 if (!num_ours && !num_theirs)
1649 *s = xstrdup("=");
1650 else if (!num_ours)
1651 *s = xstrdup("<");
1652 else if (!num_theirs)
1653 *s = xstrdup(">");
1654 else
1655 *s = xstrdup("<>");
1656 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1657 int explicit;
1658 const char *remote = atom->u.remote_ref.push ?
1659 pushremote_for_branch(branch, &explicit) :
1660 remote_for_branch(branch, &explicit);
1661 *s = xstrdup(explicit ? remote : "");
1662 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1663 const char *merge;
1665 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1666 *s = xstrdup(merge ? merge : "");
1667 } else
1668 BUG("unhandled RR_* enum");
1671 char *get_head_description(void)
1673 struct strbuf desc = STRBUF_INIT;
1674 struct wt_status_state state;
1675 memset(&state, 0, sizeof(state));
1676 wt_status_get_state(the_repository, &state, 1);
1677 if (state.rebase_in_progress ||
1678 state.rebase_interactive_in_progress) {
1679 if (state.branch)
1680 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1681 state.branch);
1682 else
1683 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1684 state.detached_from);
1685 } else if (state.bisect_in_progress)
1686 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1687 state.branch);
1688 else if (state.detached_from) {
1689 if (state.detached_at)
1690 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1691 state.detached_from);
1692 else
1693 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1694 state.detached_from);
1695 } else
1696 strbuf_addstr(&desc, _("(no branch)"));
1698 return strbuf_detach(&desc, NULL);
1701 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1703 if (!ref->symref)
1704 return xstrdup("");
1705 else
1706 return show_ref(&atom->u.refname, ref->symref);
1709 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1711 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1712 return get_head_description();
1713 return show_ref(&atom->u.refname, ref->refname);
1716 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1717 struct expand_data *oi, struct strbuf *err)
1719 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1720 int eaten = 1;
1721 if (oi->info.contentp) {
1722 /* We need to know that to use parse_object_buffer properly */
1723 oi->info.sizep = &oi->size;
1724 oi->info.typep = &oi->type;
1726 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1727 OBJECT_INFO_LOOKUP_REPLACE))
1728 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1729 oid_to_hex(&oi->oid), ref->refname);
1730 if (oi->info.disk_sizep && oi->disk_size < 0)
1731 BUG("Object size is less than zero.");
1733 if (oi->info.contentp) {
1734 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1735 if (!*obj) {
1736 if (!eaten)
1737 free(oi->content);
1738 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1739 oid_to_hex(&oi->oid), ref->refname);
1741 grab_values(ref->value, deref, *obj, oi);
1744 grab_common_values(ref->value, deref, oi);
1745 if (!eaten)
1746 free(oi->content);
1747 return 0;
1750 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1752 int i;
1754 for (i = 0; worktrees[i]; i++) {
1755 if (worktrees[i]->head_ref) {
1756 struct ref_to_worktree_entry *entry;
1757 entry = xmalloc(sizeof(*entry));
1758 entry->wt = worktrees[i];
1759 hashmap_entry_init(&entry->ent,
1760 strhash(worktrees[i]->head_ref));
1762 hashmap_add(map, &entry->ent);
1767 static void lazy_init_worktree_map(void)
1769 if (ref_to_worktree_map.worktrees)
1770 return;
1772 ref_to_worktree_map.worktrees = get_worktrees();
1773 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1774 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1777 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1779 struct hashmap_entry entry, *e;
1780 struct ref_to_worktree_entry *lookup_result;
1782 lazy_init_worktree_map();
1784 hashmap_entry_init(&entry, strhash(ref->refname));
1785 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1787 if (!e)
1788 return xstrdup("");
1790 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1792 return xstrdup(lookup_result->wt->path);
1796 * Parse the object referred by ref, and grab needed value.
1798 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1800 struct object *obj;
1801 int i;
1802 struct object_info empty = OBJECT_INFO_INIT;
1804 CALLOC_ARRAY(ref->value, used_atom_cnt);
1806 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1807 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1808 NULL, NULL);
1809 if (!ref->symref)
1810 ref->symref = xstrdup("");
1813 /* Fill in specials first */
1814 for (i = 0; i < used_atom_cnt; i++) {
1815 struct used_atom *atom = &used_atom[i];
1816 enum atom_type atom_type = atom->atom_type;
1817 const char *name = used_atom[i].name;
1818 struct atom_value *v = &ref->value[i];
1819 int deref = 0;
1820 const char *refname;
1821 struct branch *branch = NULL;
1823 v->s_size = ATOM_SIZE_UNSPECIFIED;
1824 v->handler = append_atom;
1825 v->atom = atom;
1827 if (*name == '*') {
1828 deref = 1;
1829 name++;
1832 if (atom_type == ATOM_REFNAME)
1833 refname = get_refname(atom, ref);
1834 else if (atom_type == ATOM_WORKTREEPATH) {
1835 if (ref->kind == FILTER_REFS_BRANCHES)
1836 v->s = get_worktree_path(atom, ref);
1837 else
1838 v->s = xstrdup("");
1839 continue;
1841 else if (atom_type == ATOM_SYMREF)
1842 refname = get_symref(atom, ref);
1843 else if (atom_type == ATOM_UPSTREAM) {
1844 const char *branch_name;
1845 /* only local branches may have an upstream */
1846 if (!skip_prefix(ref->refname, "refs/heads/",
1847 &branch_name)) {
1848 v->s = xstrdup("");
1849 continue;
1851 branch = branch_get(branch_name);
1853 refname = branch_get_upstream(branch, NULL);
1854 if (refname)
1855 fill_remote_ref_details(atom, refname, branch, &v->s);
1856 else
1857 v->s = xstrdup("");
1858 continue;
1859 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1860 const char *branch_name;
1861 v->s = xstrdup("");
1862 if (!skip_prefix(ref->refname, "refs/heads/",
1863 &branch_name))
1864 continue;
1865 branch = branch_get(branch_name);
1867 if (atom->u.remote_ref.push_remote)
1868 refname = NULL;
1869 else {
1870 refname = branch_get_push(branch, NULL);
1871 if (!refname)
1872 continue;
1874 /* We will definitely re-init v->s on the next line. */
1875 free((char *)v->s);
1876 fill_remote_ref_details(atom, refname, branch, &v->s);
1877 continue;
1878 } else if (atom_type == ATOM_COLOR) {
1879 v->s = xstrdup(atom->u.color);
1880 continue;
1881 } else if (atom_type == ATOM_FLAG) {
1882 char buf[256], *cp = buf;
1883 if (ref->flag & REF_ISSYMREF)
1884 cp = copy_advance(cp, ",symref");
1885 if (ref->flag & REF_ISPACKED)
1886 cp = copy_advance(cp, ",packed");
1887 if (cp == buf)
1888 v->s = xstrdup("");
1889 else {
1890 *cp = '\0';
1891 v->s = xstrdup(buf + 1);
1893 continue;
1894 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1895 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1896 continue;
1897 } else if (atom_type == ATOM_HEAD) {
1898 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1899 v->s = xstrdup("*");
1900 else
1901 v->s = xstrdup(" ");
1902 continue;
1903 } else if (atom_type == ATOM_ALIGN) {
1904 v->handler = align_atom_handler;
1905 v->s = xstrdup("");
1906 continue;
1907 } else if (atom_type == ATOM_END) {
1908 v->handler = end_atom_handler;
1909 v->s = xstrdup("");
1910 continue;
1911 } else if (atom_type == ATOM_IF) {
1912 const char *s;
1913 if (skip_prefix(name, "if:", &s))
1914 v->s = xstrdup(s);
1915 else
1916 v->s = xstrdup("");
1917 v->handler = if_atom_handler;
1918 continue;
1919 } else if (atom_type == ATOM_THEN) {
1920 v->handler = then_atom_handler;
1921 v->s = xstrdup("");
1922 continue;
1923 } else if (atom_type == ATOM_ELSE) {
1924 v->handler = else_atom_handler;
1925 v->s = xstrdup("");
1926 continue;
1927 } else
1928 continue;
1930 if (!deref)
1931 v->s = xstrdup(refname);
1932 else
1933 v->s = xstrfmt("%s^{}", refname);
1934 free((char *)refname);
1937 for (i = 0; i < used_atom_cnt; i++) {
1938 struct atom_value *v = &ref->value[i];
1939 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1940 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1941 oid_to_hex(&ref->objectname), ref->refname);
1944 if (need_tagged)
1945 oi.info.contentp = &oi.content;
1946 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1947 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1948 return 0;
1951 oi.oid = ref->objectname;
1952 if (get_object(ref, 0, &obj, &oi, err))
1953 return -1;
1956 * If there is no atom that wants to know about tagged
1957 * object, we are done.
1959 if (!need_tagged || (obj->type != OBJ_TAG))
1960 return 0;
1963 * If it is a tag object, see if we use a value that derefs
1964 * the object, and if we do grab the object it refers to.
1966 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
1969 * NEEDSWORK: This derefs tag only once, which
1970 * is good to deal with chains of trust, but
1971 * is not consistent with what deref_tag() does
1972 * which peels the onion to the core.
1974 return get_object(ref, 1, &obj, &oi_deref, err);
1978 * Given a ref, return the value for the atom. This lazily gets value
1979 * out of the object by calling populate value.
1981 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1982 struct atom_value **v, struct strbuf *err)
1984 if (!ref->value) {
1985 if (populate_value(ref, err))
1986 return -1;
1987 fill_missing_values(ref->value);
1989 *v = &ref->value[atom];
1990 return 0;
1994 * Return 1 if the refname matches one of the patterns, otherwise 0.
1995 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1996 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1997 * matches "refs/heads/mas*", too).
1999 static int match_pattern(const struct ref_filter *filter, const char *refname)
2001 const char **patterns = filter->name_patterns;
2002 unsigned flags = 0;
2004 if (filter->ignore_case)
2005 flags |= WM_CASEFOLD;
2008 * When no '--format' option is given we need to skip the prefix
2009 * for matching refs of tags and branches.
2011 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
2012 skip_prefix(refname, "refs/heads/", &refname) ||
2013 skip_prefix(refname, "refs/remotes/", &refname) ||
2014 skip_prefix(refname, "refs/", &refname));
2016 for (; *patterns; patterns++) {
2017 if (!wildmatch(*patterns, refname, flags))
2018 return 1;
2020 return 0;
2024 * Return 1 if the refname matches one of the patterns, otherwise 0.
2025 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
2026 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
2027 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
2029 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
2031 const char **pattern = filter->name_patterns;
2032 int namelen = strlen(refname);
2033 unsigned flags = WM_PATHNAME;
2035 if (filter->ignore_case)
2036 flags |= WM_CASEFOLD;
2038 for (; *pattern; pattern++) {
2039 const char *p = *pattern;
2040 int plen = strlen(p);
2042 if ((plen <= namelen) &&
2043 !strncmp(refname, p, plen) &&
2044 (refname[plen] == '\0' ||
2045 refname[plen] == '/' ||
2046 p[plen-1] == '/'))
2047 return 1;
2048 if (!wildmatch(p, refname, flags))
2049 return 1;
2051 return 0;
2054 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
2055 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
2057 if (!*filter->name_patterns)
2058 return 1; /* No pattern always matches */
2059 if (filter->match_as_path)
2060 return match_name_as_path(filter, refname);
2061 return match_pattern(filter, refname);
2065 * This is the same as for_each_fullref_in(), but it tries to iterate
2066 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2067 * pattern match, so the callback still has to match each ref individually.
2069 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2070 each_ref_fn cb,
2071 void *cb_data,
2072 int broken)
2074 if (!filter->match_as_path) {
2076 * in this case, the patterns are applied after
2077 * prefixes like "refs/heads/" etc. are stripped off,
2078 * so we have to look at everything:
2080 return for_each_fullref_in("", cb, cb_data, broken);
2083 if (filter->ignore_case) {
2085 * we can't handle case-insensitive comparisons,
2086 * so just return everything and let the caller
2087 * sort it out.
2089 return for_each_fullref_in("", cb, cb_data, broken);
2092 if (!filter->name_patterns[0]) {
2093 /* no patterns; we have to look at everything */
2094 return for_each_fullref_in("", cb, cb_data, broken);
2097 return for_each_fullref_in_prefixes(NULL, filter->name_patterns,
2098 cb, cb_data, broken);
2102 * Given a ref (oid, refname), check if the ref belongs to the array
2103 * of oids. If the given ref is a tag, check if the given tag points
2104 * at one of the oids in the given oid array.
2105 * NEEDSWORK:
2106 * 1. Only a single level of indirection is obtained, we might want to
2107 * change this to account for multiple levels (e.g. annotated tags
2108 * pointing to annotated tags pointing to a commit.)
2109 * 2. As the refs are cached we might know what refname peels to without
2110 * the need to parse the object via parse_object(). peel_ref() might be a
2111 * more efficient alternative to obtain the pointee.
2113 static const struct object_id *match_points_at(struct oid_array *points_at,
2114 const struct object_id *oid,
2115 const char *refname)
2117 const struct object_id *tagged_oid = NULL;
2118 struct object *obj;
2120 if (oid_array_lookup(points_at, oid) >= 0)
2121 return oid;
2122 obj = parse_object(the_repository, oid);
2123 if (!obj)
2124 die(_("malformed object at '%s'"), refname);
2125 if (obj->type == OBJ_TAG)
2126 tagged_oid = get_tagged_oid((struct tag *)obj);
2127 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2128 return tagged_oid;
2129 return NULL;
2133 * Allocate space for a new ref_array_item and copy the name and oid to it.
2135 * Callers can then fill in other struct members at their leisure.
2137 static struct ref_array_item *new_ref_array_item(const char *refname,
2138 const struct object_id *oid)
2140 struct ref_array_item *ref;
2142 FLEX_ALLOC_STR(ref, refname, refname);
2143 oidcpy(&ref->objectname, oid);
2145 return ref;
2148 struct ref_array_item *ref_array_push(struct ref_array *array,
2149 const char *refname,
2150 const struct object_id *oid)
2152 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2154 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2155 array->items[array->nr++] = ref;
2157 return ref;
2160 static int ref_kind_from_refname(const char *refname)
2162 unsigned int i;
2164 static struct {
2165 const char *prefix;
2166 unsigned int kind;
2167 } ref_kind[] = {
2168 { "refs/heads/" , FILTER_REFS_BRANCHES },
2169 { "refs/remotes/" , FILTER_REFS_REMOTES },
2170 { "refs/tags/", FILTER_REFS_TAGS}
2173 if (!strcmp(refname, "HEAD"))
2174 return FILTER_REFS_DETACHED_HEAD;
2176 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2177 if (starts_with(refname, ref_kind[i].prefix))
2178 return ref_kind[i].kind;
2181 return FILTER_REFS_OTHERS;
2184 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2186 if (filter->kind == FILTER_REFS_BRANCHES ||
2187 filter->kind == FILTER_REFS_REMOTES ||
2188 filter->kind == FILTER_REFS_TAGS)
2189 return filter->kind;
2190 return ref_kind_from_refname(refname);
2193 struct ref_filter_cbdata {
2194 struct ref_array *array;
2195 struct ref_filter *filter;
2196 struct contains_cache contains_cache;
2197 struct contains_cache no_contains_cache;
2201 * A call-back given to for_each_ref(). Filter refs and keep them for
2202 * later object processing.
2204 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2206 struct ref_filter_cbdata *ref_cbdata = cb_data;
2207 struct ref_filter *filter = ref_cbdata->filter;
2208 struct ref_array_item *ref;
2209 struct commit *commit = NULL;
2210 unsigned int kind;
2212 if (flag & REF_BAD_NAME) {
2213 warning(_("ignoring ref with broken name %s"), refname);
2214 return 0;
2217 if (flag & REF_ISBROKEN) {
2218 warning(_("ignoring broken ref %s"), refname);
2219 return 0;
2222 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2223 kind = filter_ref_kind(filter, refname);
2224 if (!(kind & filter->kind))
2225 return 0;
2227 if (!filter_pattern_match(filter, refname))
2228 return 0;
2230 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2231 return 0;
2234 * A merge filter is applied on refs pointing to commits. Hence
2235 * obtain the commit using the 'oid' available and discard all
2236 * non-commits early. The actual filtering is done later.
2238 if (filter->reachable_from || filter->unreachable_from ||
2239 filter->with_commit || filter->no_commit || filter->verbose) {
2240 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2241 if (!commit)
2242 return 0;
2243 /* We perform the filtering for the '--contains' option... */
2244 if (filter->with_commit &&
2245 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2246 return 0;
2247 /* ...or for the `--no-contains' option */
2248 if (filter->no_commit &&
2249 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2250 return 0;
2254 * We do not open the object yet; sort may only need refname
2255 * to do its job and the resulting list may yet to be pruned
2256 * by maxcount logic.
2258 ref = ref_array_push(ref_cbdata->array, refname, oid);
2259 ref->commit = commit;
2260 ref->flag = flag;
2261 ref->kind = kind;
2263 return 0;
2266 /* Free memory allocated for a ref_array_item */
2267 static void free_array_item(struct ref_array_item *item)
2269 free((char *)item->symref);
2270 if (item->value) {
2271 int i;
2272 for (i = 0; i < used_atom_cnt; i++)
2273 free((char *)item->value[i].s);
2274 free(item->value);
2276 free(item);
2279 /* Free all memory allocated for ref_array */
2280 void ref_array_clear(struct ref_array *array)
2282 int i;
2284 for (i = 0; i < array->nr; i++)
2285 free_array_item(array->items[i]);
2286 FREE_AND_NULL(array->items);
2287 array->nr = array->alloc = 0;
2289 for (i = 0; i < used_atom_cnt; i++)
2290 free((char *)used_atom[i].name);
2291 FREE_AND_NULL(used_atom);
2292 used_atom_cnt = 0;
2294 if (ref_to_worktree_map.worktrees) {
2295 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2296 struct ref_to_worktree_entry, ent);
2297 free_worktrees(ref_to_worktree_map.worktrees);
2298 ref_to_worktree_map.worktrees = NULL;
2302 #define EXCLUDE_REACHED 0
2303 #define INCLUDE_REACHED 1
2304 static void reach_filter(struct ref_array *array,
2305 struct commit_list *check_reachable,
2306 int include_reached)
2308 struct rev_info revs;
2309 int i, old_nr;
2310 struct commit **to_clear;
2311 struct commit_list *cr;
2313 if (!check_reachable)
2314 return;
2316 CALLOC_ARRAY(to_clear, array->nr);
2318 repo_init_revisions(the_repository, &revs, NULL);
2320 for (i = 0; i < array->nr; i++) {
2321 struct ref_array_item *item = array->items[i];
2322 add_pending_object(&revs, &item->commit->object, item->refname);
2323 to_clear[i] = item->commit;
2326 for (cr = check_reachable; cr; cr = cr->next) {
2327 struct commit *merge_commit = cr->item;
2328 merge_commit->object.flags |= UNINTERESTING;
2329 add_pending_object(&revs, &merge_commit->object, "");
2332 revs.limited = 1;
2333 if (prepare_revision_walk(&revs))
2334 die(_("revision walk setup failed"));
2336 old_nr = array->nr;
2337 array->nr = 0;
2339 for (i = 0; i < old_nr; i++) {
2340 struct ref_array_item *item = array->items[i];
2341 struct commit *commit = item->commit;
2343 int is_merged = !!(commit->object.flags & UNINTERESTING);
2345 if (is_merged == include_reached)
2346 array->items[array->nr++] = array->items[i];
2347 else
2348 free_array_item(item);
2351 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2353 while (check_reachable) {
2354 struct commit *merge_commit = pop_commit(&check_reachable);
2355 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2358 free(to_clear);
2362 * API for filtering a set of refs. Based on the type of refs the user
2363 * has requested, we iterate through those refs and apply filters
2364 * as per the given ref_filter structure and finally store the
2365 * filtered refs in the ref_array structure.
2367 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2369 struct ref_filter_cbdata ref_cbdata;
2370 int ret = 0;
2371 unsigned int broken = 0;
2373 ref_cbdata.array = array;
2374 ref_cbdata.filter = filter;
2376 if (type & FILTER_REFS_INCLUDE_BROKEN)
2377 broken = 1;
2378 filter->kind = type & FILTER_REFS_KIND_MASK;
2380 init_contains_cache(&ref_cbdata.contains_cache);
2381 init_contains_cache(&ref_cbdata.no_contains_cache);
2383 /* Simple per-ref filtering */
2384 if (!filter->kind)
2385 die("filter_refs: invalid type");
2386 else {
2388 * For common cases where we need only branches or remotes or tags,
2389 * we only iterate through those refs. If a mix of refs is needed,
2390 * we iterate over all refs and filter out required refs with the help
2391 * of filter_ref_kind().
2393 if (filter->kind == FILTER_REFS_BRANCHES)
2394 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2395 else if (filter->kind == FILTER_REFS_REMOTES)
2396 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2397 else if (filter->kind == FILTER_REFS_TAGS)
2398 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2399 else if (filter->kind & FILTER_REFS_ALL)
2400 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2401 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2402 head_ref(ref_filter_handler, &ref_cbdata);
2405 clear_contains_cache(&ref_cbdata.contains_cache);
2406 clear_contains_cache(&ref_cbdata.no_contains_cache);
2408 /* Filters that need revision walking */
2409 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2410 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2412 return ret;
2415 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2417 if (!(a->kind ^ b->kind))
2418 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2419 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2420 return -1;
2421 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2422 return 1;
2423 BUG("should have died in the xor check above");
2424 return 0;
2427 static int memcasecmp(const void *vs1, const void *vs2, size_t n)
2429 const char *s1 = vs1, *s2 = vs2;
2430 const char *end = s1 + n;
2432 for (; s1 < end; s1++, s2++) {
2433 int diff = tolower(*s1) - tolower(*s2);
2434 if (diff)
2435 return diff;
2437 return 0;
2440 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2442 struct atom_value *va, *vb;
2443 int cmp;
2444 int cmp_detached_head = 0;
2445 cmp_type cmp_type = used_atom[s->atom].type;
2446 struct strbuf err = STRBUF_INIT;
2448 if (get_ref_atom_value(a, s->atom, &va, &err))
2449 die("%s", err.buf);
2450 if (get_ref_atom_value(b, s->atom, &vb, &err))
2451 die("%s", err.buf);
2452 strbuf_release(&err);
2453 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2454 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2455 cmp = compare_detached_head(a, b);
2456 cmp_detached_head = 1;
2457 } else if (s->sort_flags & REF_SORTING_VERSION) {
2458 cmp = versioncmp(va->s, vb->s);
2459 } else if (cmp_type == FIELD_STR) {
2460 if (va->s_size < 0 && vb->s_size < 0) {
2461 int (*cmp_fn)(const char *, const char *);
2462 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2463 ? strcasecmp : strcmp;
2464 cmp = cmp_fn(va->s, vb->s);
2465 } else {
2466 size_t a_size = va->s_size < 0 ?
2467 strlen(va->s) : va->s_size;
2468 size_t b_size = vb->s_size < 0 ?
2469 strlen(vb->s) : vb->s_size;
2470 int (*cmp_fn)(const void *, const void *, size_t);
2471 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2472 ? memcasecmp : memcmp;
2474 cmp = cmp_fn(va->s, vb->s, b_size > a_size ?
2475 a_size : b_size);
2476 if (!cmp) {
2477 if (a_size > b_size)
2478 cmp = 1;
2479 else if (a_size < b_size)
2480 cmp = -1;
2483 } else {
2484 if (va->value < vb->value)
2485 cmp = -1;
2486 else if (va->value == vb->value)
2487 cmp = 0;
2488 else
2489 cmp = 1;
2492 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2493 ? -cmp : cmp;
2496 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2498 struct ref_array_item *a = *((struct ref_array_item **)a_);
2499 struct ref_array_item *b = *((struct ref_array_item **)b_);
2500 struct ref_sorting *s;
2502 for (s = ref_sorting; s; s = s->next) {
2503 int cmp = cmp_ref_sorting(s, a, b);
2504 if (cmp)
2505 return cmp;
2507 s = ref_sorting;
2508 return s && s->sort_flags & REF_SORTING_ICASE ?
2509 strcasecmp(a->refname, b->refname) :
2510 strcmp(a->refname, b->refname);
2513 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2514 unsigned int mask, int on)
2516 for (; sorting; sorting = sorting->next) {
2517 if (on)
2518 sorting->sort_flags |= mask;
2519 else
2520 sorting->sort_flags &= ~mask;
2524 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2526 QSORT_S(array->items, array->nr, compare_refs, sorting);
2529 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2531 struct strbuf *s = &state->stack->output;
2533 while (*cp && (!ep || cp < ep)) {
2534 if (*cp == '%') {
2535 if (cp[1] == '%')
2536 cp++;
2537 else {
2538 int ch = hex2chr(cp + 1);
2539 if (0 <= ch) {
2540 strbuf_addch(s, ch);
2541 cp += 3;
2542 continue;
2546 strbuf_addch(s, *cp);
2547 cp++;
2551 int format_ref_array_item(struct ref_array_item *info,
2552 const struct ref_format *format,
2553 struct strbuf *final_buf,
2554 struct strbuf *error_buf)
2556 const char *cp, *sp, *ep;
2557 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2559 state.quote_style = format->quote_style;
2560 push_stack_element(&state.stack);
2562 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2563 struct atom_value *atomv;
2564 int pos;
2566 ep = strchr(sp, ')');
2567 if (cp < sp)
2568 append_literal(cp, sp, &state);
2569 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2570 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2571 atomv->handler(atomv, &state, error_buf)) {
2572 pop_stack_element(&state.stack);
2573 return -1;
2576 if (*cp) {
2577 sp = cp + strlen(cp);
2578 append_literal(cp, sp, &state);
2580 if (format->need_color_reset_at_eol) {
2581 struct atom_value resetv = ATOM_VALUE_INIT;
2582 resetv.s = GIT_COLOR_RESET;
2583 if (append_atom(&resetv, &state, error_buf)) {
2584 pop_stack_element(&state.stack);
2585 return -1;
2588 if (state.stack->prev) {
2589 pop_stack_element(&state.stack);
2590 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2592 strbuf_addbuf(final_buf, &state.stack->output);
2593 pop_stack_element(&state.stack);
2594 return 0;
2597 void pretty_print_ref(const char *name, const struct object_id *oid,
2598 const struct ref_format *format)
2600 struct ref_array_item *ref_item;
2601 struct strbuf output = STRBUF_INIT;
2602 struct strbuf err = STRBUF_INIT;
2604 ref_item = new_ref_array_item(name, oid);
2605 ref_item->kind = ref_kind_from_refname(name);
2606 if (format_ref_array_item(ref_item, format, &output, &err))
2607 die("%s", err.buf);
2608 fwrite(output.buf, 1, output.len, stdout);
2609 putchar('\n');
2611 strbuf_release(&err);
2612 strbuf_release(&output);
2613 free_array_item(ref_item);
2616 static int parse_sorting_atom(const char *atom)
2619 * This parses an atom using a dummy ref_format, since we don't
2620 * actually care about the formatting details.
2622 struct ref_format dummy = REF_FORMAT_INIT;
2623 const char *end = atom + strlen(atom);
2624 struct strbuf err = STRBUF_INIT;
2625 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2626 if (res < 0)
2627 die("%s", err.buf);
2628 strbuf_release(&err);
2629 return res;
2632 /* If no sorting option is given, use refname to sort as default */
2633 struct ref_sorting *ref_default_sorting(void)
2635 static const char cstr_name[] = "refname";
2637 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2639 sorting->next = NULL;
2640 sorting->atom = parse_sorting_atom(cstr_name);
2641 return sorting;
2644 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2646 struct ref_sorting *s;
2648 CALLOC_ARRAY(s, 1);
2649 s->next = *sorting_tail;
2650 *sorting_tail = s;
2652 if (*arg == '-') {
2653 s->sort_flags |= REF_SORTING_REVERSE;
2654 arg++;
2656 if (skip_prefix(arg, "version:", &arg) ||
2657 skip_prefix(arg, "v:", &arg))
2658 s->sort_flags |= REF_SORTING_VERSION;
2659 s->atom = parse_sorting_atom(arg);
2662 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2665 * NEEDSWORK: We should probably clear the list in this case, but we've
2666 * already munged the global used_atoms list, which would need to be
2667 * undone.
2669 BUG_ON_OPT_NEG(unset);
2671 parse_ref_sorting(opt->value, arg);
2672 return 0;
2675 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2677 struct ref_filter *rf = opt->value;
2678 struct object_id oid;
2679 struct commit *merge_commit;
2681 BUG_ON_OPT_NEG(unset);
2683 if (get_oid(arg, &oid))
2684 die(_("malformed object name %s"), arg);
2686 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2688 if (!merge_commit)
2689 return error(_("option `%s' must point to a commit"), opt->long_name);
2691 if (starts_with(opt->long_name, "no"))
2692 commit_list_insert(merge_commit, &rf->unreachable_from);
2693 else
2694 commit_list_insert(merge_commit, &rf->reachable_from);
2696 return 0;