refs: make repo_dwim_log() accept a NULL oid
[git/debian.git] / ref-filter.c
blob4db0e40ff4c6251aa808738e1630db1e397956de
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_UPSTREAM,
148 ATOM_PUSH,
149 ATOM_SYMREF,
150 ATOM_FLAG,
151 ATOM_HEAD,
152 ATOM_COLOR,
153 ATOM_WORKTREEPATH,
154 ATOM_ALIGN,
155 ATOM_END,
156 ATOM_IF,
157 ATOM_THEN,
158 ATOM_ELSE,
162 * An atom is a valid field atom listed below, possibly prefixed with
163 * a "*" to denote deref_tag().
165 * We parse given format string and sort specifiers, and make a list
166 * of properties that we need to extract out of objects. ref_array_item
167 * structure will hold an array of values extracted that can be
168 * indexed with the "atom number", which is an index into this
169 * array.
171 static struct used_atom {
172 enum atom_type atom_type;
173 const char *name;
174 cmp_type type;
175 info_source source;
176 union {
177 char color[COLOR_MAXLEN];
178 struct align align;
179 struct {
180 enum {
181 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
182 } option;
183 struct refname_atom refname;
184 unsigned int nobracket : 1, push : 1, push_remote : 1;
185 } remote_ref;
186 struct {
187 enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,
188 C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;
189 struct process_trailer_options trailer_opts;
190 unsigned int nlines;
191 } contents;
192 struct {
193 cmp_status cmp_status;
194 const char *str;
195 } if_then_else;
196 struct {
197 enum { O_FULL, O_LENGTH, O_SHORT } option;
198 unsigned int length;
199 } oid;
200 struct {
201 enum { O_SIZE, O_SIZE_DISK } option;
202 } objectsize;
203 struct email_option {
204 enum { EO_RAW, EO_TRIM, EO_LOCALPART } option;
205 } email_option;
206 struct refname_atom refname;
207 char *head;
208 } u;
209 } *used_atom;
210 static int used_atom_cnt, need_tagged, need_symref;
213 * Expand string, append it to strbuf *sb, then return error code ret.
214 * Allow to save few lines of code.
216 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
218 va_list ap;
219 va_start(ap, fmt);
220 strbuf_vaddf(sb, fmt, ap);
221 va_end(ap);
222 return ret;
225 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
226 const char *color_value, struct strbuf *err)
228 if (!color_value)
229 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
230 if (color_parse(color_value, atom->u.color) < 0)
231 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
232 color_value);
234 * We check this after we've parsed the color, which lets us complain
235 * about syntactically bogus color names even if they won't be used.
237 if (!want_color(format->use_color))
238 color_parse("", atom->u.color);
239 return 0;
242 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
243 const char *name, struct strbuf *err)
245 if (!arg)
246 atom->option = R_NORMAL;
247 else if (!strcmp(arg, "short"))
248 atom->option = R_SHORT;
249 else if (skip_prefix(arg, "lstrip=", &arg) ||
250 skip_prefix(arg, "strip=", &arg)) {
251 atom->option = R_LSTRIP;
252 if (strtol_i(arg, 10, &atom->lstrip))
253 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
254 } else if (skip_prefix(arg, "rstrip=", &arg)) {
255 atom->option = R_RSTRIP;
256 if (strtol_i(arg, 10, &atom->rstrip))
257 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
258 } else
259 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
260 return 0;
263 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
264 const char *arg, struct strbuf *err)
266 struct string_list params = STRING_LIST_INIT_DUP;
267 int i;
269 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
270 atom->u.remote_ref.push = 1;
272 if (!arg) {
273 atom->u.remote_ref.option = RR_REF;
274 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
275 arg, atom->name, err);
278 atom->u.remote_ref.nobracket = 0;
279 string_list_split(&params, arg, ',', -1);
281 for (i = 0; i < params.nr; i++) {
282 const char *s = params.items[i].string;
284 if (!strcmp(s, "track"))
285 atom->u.remote_ref.option = RR_TRACK;
286 else if (!strcmp(s, "trackshort"))
287 atom->u.remote_ref.option = RR_TRACKSHORT;
288 else if (!strcmp(s, "nobracket"))
289 atom->u.remote_ref.nobracket = 1;
290 else if (!strcmp(s, "remotename")) {
291 atom->u.remote_ref.option = RR_REMOTE_NAME;
292 atom->u.remote_ref.push_remote = 1;
293 } else if (!strcmp(s, "remoteref")) {
294 atom->u.remote_ref.option = RR_REMOTE_REF;
295 atom->u.remote_ref.push_remote = 1;
296 } else {
297 atom->u.remote_ref.option = RR_REF;
298 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
299 arg, atom->name, err)) {
300 string_list_clear(&params, 0);
301 return -1;
306 string_list_clear(&params, 0);
307 return 0;
310 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
311 const char *arg, struct strbuf *err)
313 if (arg)
314 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
315 if (*atom->name == '*')
316 oi_deref.info.typep = &oi_deref.type;
317 else
318 oi.info.typep = &oi.type;
319 return 0;
322 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
323 const char *arg, struct strbuf *err)
325 if (!arg) {
326 atom->u.objectsize.option = O_SIZE;
327 if (*atom->name == '*')
328 oi_deref.info.sizep = &oi_deref.size;
329 else
330 oi.info.sizep = &oi.size;
331 } else if (!strcmp(arg, "disk")) {
332 atom->u.objectsize.option = O_SIZE_DISK;
333 if (*atom->name == '*')
334 oi_deref.info.disk_sizep = &oi_deref.disk_size;
335 else
336 oi.info.disk_sizep = &oi.disk_size;
337 } else
338 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
339 return 0;
342 static int deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom,
343 const char *arg, struct strbuf *err)
345 if (arg)
346 return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
347 if (*atom->name == '*')
348 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
349 else
350 oi.info.delta_base_oid = &oi.delta_base_oid;
351 return 0;
354 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
355 const char *arg, struct strbuf *err)
357 if (arg)
358 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
359 atom->u.contents.option = C_BODY_DEP;
360 return 0;
363 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
364 const char *arg, struct strbuf *err)
366 if (!arg)
367 atom->u.contents.option = C_SUB;
368 else if (!strcmp(arg, "sanitize"))
369 atom->u.contents.option = C_SUB_SANITIZE;
370 else
371 return strbuf_addf_ret(err, -1, _("unrecognized %%(subject) argument: %s"), arg);
372 return 0;
375 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
376 const char *arg, struct strbuf *err)
378 atom->u.contents.trailer_opts.no_divider = 1;
380 if (arg) {
381 const char *argbuf = xstrfmt("%s)", arg);
382 char *invalid_arg = NULL;
384 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
385 &ref_trailer_buf.filter_list,
386 &ref_trailer_buf.sepbuf,
387 &ref_trailer_buf.kvsepbuf,
388 &argbuf, &invalid_arg)) {
389 if (!invalid_arg)
390 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
391 else
392 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
393 free((char *)invalid_arg);
394 return -1;
397 atom->u.contents.option = C_TRAILERS;
398 return 0;
401 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
402 const char *arg, struct strbuf *err)
404 if (!arg)
405 atom->u.contents.option = C_BARE;
406 else if (!strcmp(arg, "body"))
407 atom->u.contents.option = C_BODY;
408 else if (!strcmp(arg, "size"))
409 atom->u.contents.option = C_LENGTH;
410 else if (!strcmp(arg, "signature"))
411 atom->u.contents.option = C_SIG;
412 else if (!strcmp(arg, "subject"))
413 atom->u.contents.option = C_SUB;
414 else if (!strcmp(arg, "trailers")) {
415 if (trailers_atom_parser(format, atom, NULL, err))
416 return -1;
417 } else if (skip_prefix(arg, "trailers:", &arg)) {
418 if (trailers_atom_parser(format, atom, arg, err))
419 return -1;
420 } else if (skip_prefix(arg, "lines=", &arg)) {
421 atom->u.contents.option = C_LINES;
422 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
423 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
424 } else
425 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
426 return 0;
429 static int oid_atom_parser(const struct ref_format *format, struct used_atom *atom,
430 const char *arg, struct strbuf *err)
432 if (!arg)
433 atom->u.oid.option = O_FULL;
434 else if (!strcmp(arg, "short"))
435 atom->u.oid.option = O_SHORT;
436 else if (skip_prefix(arg, "short=", &arg)) {
437 atom->u.oid.option = O_LENGTH;
438 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
439 atom->u.oid.length == 0)
440 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
441 if (atom->u.oid.length < MINIMUM_ABBREV)
442 atom->u.oid.length = MINIMUM_ABBREV;
443 } else
444 return strbuf_addf_ret(err, -1, _("unrecognized argument '%s' in %%(%s)"), arg, atom->name);
445 return 0;
448 static int person_email_atom_parser(const struct ref_format *format, struct used_atom *atom,
449 const char *arg, struct strbuf *err)
451 if (!arg)
452 atom->u.email_option.option = EO_RAW;
453 else if (!strcmp(arg, "trim"))
454 atom->u.email_option.option = EO_TRIM;
455 else if (!strcmp(arg, "localpart"))
456 atom->u.email_option.option = EO_LOCALPART;
457 else
458 return strbuf_addf_ret(err, -1, _("unrecognized email option: %s"), arg);
459 return 0;
462 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
463 const char *arg, struct strbuf *err)
465 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
468 static align_type parse_align_position(const char *s)
470 if (!strcmp(s, "right"))
471 return ALIGN_RIGHT;
472 else if (!strcmp(s, "middle"))
473 return ALIGN_MIDDLE;
474 else if (!strcmp(s, "left"))
475 return ALIGN_LEFT;
476 return -1;
479 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
480 const char *arg, struct strbuf *err)
482 struct align *align = &atom->u.align;
483 struct string_list params = STRING_LIST_INIT_DUP;
484 int i;
485 unsigned int width = ~0U;
487 if (!arg)
488 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
490 align->position = ALIGN_LEFT;
492 string_list_split(&params, arg, ',', -1);
493 for (i = 0; i < params.nr; i++) {
494 const char *s = params.items[i].string;
495 int position;
497 if (skip_prefix(s, "position=", &s)) {
498 position = parse_align_position(s);
499 if (position < 0) {
500 strbuf_addf(err, _("unrecognized position:%s"), s);
501 string_list_clear(&params, 0);
502 return -1;
504 align->position = position;
505 } else if (skip_prefix(s, "width=", &s)) {
506 if (strtoul_ui(s, 10, &width)) {
507 strbuf_addf(err, _("unrecognized width:%s"), s);
508 string_list_clear(&params, 0);
509 return -1;
511 } else if (!strtoul_ui(s, 10, &width))
513 else if ((position = parse_align_position(s)) >= 0)
514 align->position = position;
515 else {
516 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
517 string_list_clear(&params, 0);
518 return -1;
522 if (width == ~0U) {
523 string_list_clear(&params, 0);
524 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
526 align->width = width;
527 string_list_clear(&params, 0);
528 return 0;
531 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
532 const char *arg, struct strbuf *err)
534 if (!arg) {
535 atom->u.if_then_else.cmp_status = COMPARE_NONE;
536 return 0;
537 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
538 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
539 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
540 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
541 } else
542 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
543 return 0;
546 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
547 const char *arg, struct strbuf *unused_err)
549 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
550 return 0;
553 static struct {
554 const char *name;
555 info_source source;
556 cmp_type cmp_type;
557 int (*parser)(const struct ref_format *format, struct used_atom *atom,
558 const char *arg, struct strbuf *err);
559 } valid_atom[] = {
560 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
561 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
562 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
563 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
564 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
565 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
566 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
567 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
568 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
569 [ATOM_TYPE] = { "type", SOURCE_OBJ },
570 [ATOM_TAG] = { "tag", SOURCE_OBJ },
571 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
572 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
573 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
574 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
575 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
576 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
577 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
578 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
579 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
580 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
581 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
582 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
583 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
584 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
585 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
586 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
587 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
588 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
589 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
590 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
591 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
592 [ATOM_FLAG] = { "flag", SOURCE_NONE },
593 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
594 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
595 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
596 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
597 [ATOM_END] = { "end", SOURCE_NONE },
598 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
599 [ATOM_THEN] = { "then", SOURCE_NONE },
600 [ATOM_ELSE] = { "else", SOURCE_NONE },
602 * Please update $__git_ref_fieldlist in git-completion.bash
603 * when you add new atoms
607 #define REF_FORMATTING_STATE_INIT { 0, NULL }
609 struct ref_formatting_stack {
610 struct ref_formatting_stack *prev;
611 struct strbuf output;
612 void (*at_end)(struct ref_formatting_stack **stack);
613 void *at_end_data;
616 struct ref_formatting_state {
617 int quote_style;
618 struct ref_formatting_stack *stack;
621 struct atom_value {
622 const char *s;
623 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
624 struct strbuf *err);
625 uintmax_t value; /* used for sorting when not FIELD_STR */
626 struct used_atom *atom;
630 * Used to parse format string and sort specifiers
632 static int parse_ref_filter_atom(const struct ref_format *format,
633 const char *atom, const char *ep,
634 struct strbuf *err)
636 const char *sp;
637 const char *arg;
638 int i, at, atom_len;
640 sp = atom;
641 if (*sp == '*' && sp < ep)
642 sp++; /* deref */
643 if (ep <= sp)
644 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
645 (int)(ep-atom), atom);
647 /* Do we have the atom already used elsewhere? */
648 for (i = 0; i < used_atom_cnt; i++) {
649 int len = strlen(used_atom[i].name);
650 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
651 return i;
655 * If the atom name has a colon, strip it and everything after
656 * it off - it specifies the format for this entry, and
657 * shouldn't be used for checking against the valid_atom
658 * table.
660 arg = memchr(sp, ':', ep - sp);
661 atom_len = (arg ? arg : ep) - sp;
663 /* Is the atom a valid one? */
664 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
665 int len = strlen(valid_atom[i].name);
666 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
667 break;
670 if (ARRAY_SIZE(valid_atom) <= i)
671 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
672 (int)(ep-atom), atom);
673 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
674 return strbuf_addf_ret(err, -1,
675 _("not a git repository, but the field '%.*s' requires access to object data"),
676 (int)(ep-atom), atom);
678 /* Add it in, including the deref prefix */
679 at = used_atom_cnt;
680 used_atom_cnt++;
681 REALLOC_ARRAY(used_atom, used_atom_cnt);
682 used_atom[at].atom_type = i;
683 used_atom[at].name = xmemdupz(atom, ep - atom);
684 used_atom[at].type = valid_atom[i].cmp_type;
685 used_atom[at].source = valid_atom[i].source;
686 if (used_atom[at].source == SOURCE_OBJ) {
687 if (*atom == '*')
688 oi_deref.info.contentp = &oi_deref.content;
689 else
690 oi.info.contentp = &oi.content;
692 if (arg) {
693 arg = used_atom[at].name + (arg - atom) + 1;
694 if (!*arg) {
696 * Treat empty sub-arguments list as NULL (i.e.,
697 * "%(atom:)" is equivalent to "%(atom)").
699 arg = NULL;
702 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
703 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
704 return -1;
705 if (*atom == '*')
706 need_tagged = 1;
707 if (i == ATOM_SYMREF)
708 need_symref = 1;
709 return at;
712 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
714 switch (quote_style) {
715 case QUOTE_NONE:
716 strbuf_addstr(s, str);
717 break;
718 case QUOTE_SHELL:
719 sq_quote_buf(s, str);
720 break;
721 case QUOTE_PERL:
722 perl_quote_buf(s, str);
723 break;
724 case QUOTE_PYTHON:
725 python_quote_buf(s, str);
726 break;
727 case QUOTE_TCL:
728 tcl_quote_buf(s, str);
729 break;
733 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
734 struct strbuf *unused_err)
737 * Quote formatting is only done when the stack has a single
738 * element. Otherwise quote formatting is done on the
739 * element's entire output strbuf when the %(end) atom is
740 * encountered.
742 if (!state->stack->prev)
743 quote_formatting(&state->stack->output, v->s, state->quote_style);
744 else
745 strbuf_addstr(&state->stack->output, v->s);
746 return 0;
749 static void push_stack_element(struct ref_formatting_stack **stack)
751 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
753 strbuf_init(&s->output, 0);
754 s->prev = *stack;
755 *stack = s;
758 static void pop_stack_element(struct ref_formatting_stack **stack)
760 struct ref_formatting_stack *current = *stack;
761 struct ref_formatting_stack *prev = current->prev;
763 if (prev)
764 strbuf_addbuf(&prev->output, &current->output);
765 strbuf_release(&current->output);
766 free(current);
767 *stack = prev;
770 static void end_align_handler(struct ref_formatting_stack **stack)
772 struct ref_formatting_stack *cur = *stack;
773 struct align *align = (struct align *)cur->at_end_data;
774 struct strbuf s = STRBUF_INIT;
776 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
777 strbuf_swap(&cur->output, &s);
778 strbuf_release(&s);
781 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
782 struct strbuf *unused_err)
784 struct ref_formatting_stack *new_stack;
786 push_stack_element(&state->stack);
787 new_stack = state->stack;
788 new_stack->at_end = end_align_handler;
789 new_stack->at_end_data = &atomv->atom->u.align;
790 return 0;
793 static void if_then_else_handler(struct ref_formatting_stack **stack)
795 struct ref_formatting_stack *cur = *stack;
796 struct ref_formatting_stack *prev = cur->prev;
797 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
799 if (!if_then_else->then_atom_seen)
800 die(_("format: %%(if) atom used without a %%(then) atom"));
802 if (if_then_else->else_atom_seen) {
804 * There is an %(else) atom: we need to drop one state from the
805 * stack, either the %(else) branch if the condition is satisfied, or
806 * the %(then) branch if it isn't.
808 if (if_then_else->condition_satisfied) {
809 strbuf_reset(&cur->output);
810 pop_stack_element(&cur);
811 } else {
812 strbuf_swap(&cur->output, &prev->output);
813 strbuf_reset(&cur->output);
814 pop_stack_element(&cur);
816 } else if (!if_then_else->condition_satisfied) {
818 * No %(else) atom: just drop the %(then) branch if the
819 * condition is not satisfied.
821 strbuf_reset(&cur->output);
824 *stack = cur;
825 free(if_then_else);
828 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
829 struct strbuf *unused_err)
831 struct ref_formatting_stack *new_stack;
832 struct if_then_else *if_then_else = xcalloc(1,
833 sizeof(struct if_then_else));
835 if_then_else->str = atomv->atom->u.if_then_else.str;
836 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
838 push_stack_element(&state->stack);
839 new_stack = state->stack;
840 new_stack->at_end = if_then_else_handler;
841 new_stack->at_end_data = if_then_else;
842 return 0;
845 static int is_empty(const char *s)
847 while (*s != '\0') {
848 if (!isspace(*s))
849 return 0;
850 s++;
852 return 1;
855 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
856 struct strbuf *err)
858 struct ref_formatting_stack *cur = state->stack;
859 struct if_then_else *if_then_else = NULL;
861 if (cur->at_end == if_then_else_handler)
862 if_then_else = (struct if_then_else *)cur->at_end_data;
863 if (!if_then_else)
864 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
865 if (if_then_else->then_atom_seen)
866 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
867 if (if_then_else->else_atom_seen)
868 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
869 if_then_else->then_atom_seen = 1;
871 * If the 'equals' or 'notequals' attribute is used then
872 * perform the required comparison. If not, only non-empty
873 * strings satisfy the 'if' condition.
875 if (if_then_else->cmp_status == COMPARE_EQUAL) {
876 if (!strcmp(if_then_else->str, cur->output.buf))
877 if_then_else->condition_satisfied = 1;
878 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
879 if (strcmp(if_then_else->str, cur->output.buf))
880 if_then_else->condition_satisfied = 1;
881 } else if (cur->output.len && !is_empty(cur->output.buf))
882 if_then_else->condition_satisfied = 1;
883 strbuf_reset(&cur->output);
884 return 0;
887 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
888 struct strbuf *err)
890 struct ref_formatting_stack *prev = state->stack;
891 struct if_then_else *if_then_else = NULL;
893 if (prev->at_end == if_then_else_handler)
894 if_then_else = (struct if_then_else *)prev->at_end_data;
895 if (!if_then_else)
896 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
897 if (!if_then_else->then_atom_seen)
898 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
899 if (if_then_else->else_atom_seen)
900 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
901 if_then_else->else_atom_seen = 1;
902 push_stack_element(&state->stack);
903 state->stack->at_end_data = prev->at_end_data;
904 state->stack->at_end = prev->at_end;
905 return 0;
908 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
909 struct strbuf *err)
911 struct ref_formatting_stack *current = state->stack;
912 struct strbuf s = STRBUF_INIT;
914 if (!current->at_end)
915 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
916 current->at_end(&state->stack);
918 /* Stack may have been popped within at_end(), hence reset the current pointer */
919 current = state->stack;
922 * Perform quote formatting when the stack element is that of
923 * a supporting atom. If nested then perform quote formatting
924 * only on the topmost supporting atom.
926 if (!current->prev->prev) {
927 quote_formatting(&s, current->output.buf, state->quote_style);
928 strbuf_swap(&current->output, &s);
930 strbuf_release(&s);
931 pop_stack_element(&state->stack);
932 return 0;
936 * In a format string, find the next occurrence of %(atom).
938 static const char *find_next(const char *cp)
940 while (*cp) {
941 if (*cp == '%') {
943 * %( is the start of an atom;
944 * %% is a quoted per-cent.
946 if (cp[1] == '(')
947 return cp;
948 else if (cp[1] == '%')
949 cp++; /* skip over two % */
950 /* otherwise this is a singleton, literal % */
952 cp++;
954 return NULL;
958 * Make sure the format string is well formed, and parse out
959 * the used atoms.
961 int verify_ref_format(struct ref_format *format)
963 const char *cp, *sp;
965 format->need_color_reset_at_eol = 0;
966 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
967 struct strbuf err = STRBUF_INIT;
968 const char *color, *ep = strchr(sp, ')');
969 int at;
971 if (!ep)
972 return error(_("malformed format string %s"), sp);
973 /* sp points at "%(" and ep points at the closing ")" */
974 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
975 if (at < 0)
976 die("%s", err.buf);
977 cp = ep + 1;
979 if (skip_prefix(used_atom[at].name, "color:", &color))
980 format->need_color_reset_at_eol = !!strcmp(color, "reset");
981 strbuf_release(&err);
983 if (format->need_color_reset_at_eol && !want_color(format->use_color))
984 format->need_color_reset_at_eol = 0;
985 return 0;
988 static const char *do_grab_oid(const char *field, const struct object_id *oid,
989 struct used_atom *atom)
991 switch (atom->u.oid.option) {
992 case O_FULL:
993 return oid_to_hex(oid);
994 case O_LENGTH:
995 return find_unique_abbrev(oid, atom->u.oid.length);
996 case O_SHORT:
997 return find_unique_abbrev(oid, DEFAULT_ABBREV);
998 default:
999 BUG("unknown %%(%s) option", field);
1003 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1004 struct atom_value *v, struct used_atom *atom)
1006 if (starts_with(name, field)) {
1007 v->s = xstrdup(do_grab_oid(field, oid, atom));
1008 return 1;
1010 return 0;
1013 /* See grab_values */
1014 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1016 int i;
1018 for (i = 0; i < used_atom_cnt; i++) {
1019 const char *name = used_atom[i].name;
1020 enum atom_type atom_type = used_atom[i].atom_type;
1021 struct atom_value *v = &val[i];
1022 if (!!deref != (*name == '*'))
1023 continue;
1024 if (deref)
1025 name++;
1026 if (atom_type == ATOM_OBJECTTYPE)
1027 v->s = xstrdup(type_name(oi->type));
1028 else if (atom_type == ATOM_OBJECTSIZE) {
1029 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1030 v->value = oi->disk_size;
1031 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1032 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1033 v->value = oi->size;
1034 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1036 } else if (atom_type == ATOM_DELTABASE)
1037 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1038 else if (atom_type == ATOM_OBJECTNAME && deref)
1039 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1043 /* See grab_values */
1044 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1046 int i;
1047 struct tag *tag = (struct tag *) obj;
1049 for (i = 0; i < used_atom_cnt; i++) {
1050 const char *name = used_atom[i].name;
1051 enum atom_type atom_type = used_atom[i].atom_type;
1052 struct atom_value *v = &val[i];
1053 if (!!deref != (*name == '*'))
1054 continue;
1055 if (deref)
1056 name++;
1057 if (atom_type == ATOM_TAG)
1058 v->s = xstrdup(tag->tag);
1059 else if (atom_type == ATOM_TYPE && tag->tagged)
1060 v->s = xstrdup(type_name(tag->tagged->type));
1061 else if (atom_type == ATOM_OBJECT && tag->tagged)
1062 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1066 /* See grab_values */
1067 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1069 int i;
1070 struct commit *commit = (struct commit *) obj;
1072 for (i = 0; i < used_atom_cnt; i++) {
1073 const char *name = used_atom[i].name;
1074 enum atom_type atom_type = used_atom[i].atom_type;
1075 struct atom_value *v = &val[i];
1076 if (!!deref != (*name == '*'))
1077 continue;
1078 if (deref)
1079 name++;
1080 if (atom_type == ATOM_TREE &&
1081 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1082 continue;
1083 if (atom_type == ATOM_NUMPARENT) {
1084 v->value = commit_list_count(commit->parents);
1085 v->s = xstrfmt("%lu", (unsigned long)v->value);
1087 else if (atom_type == ATOM_PARENT) {
1088 struct commit_list *parents;
1089 struct strbuf s = STRBUF_INIT;
1090 for (parents = commit->parents; parents; parents = parents->next) {
1091 struct object_id *oid = &parents->item->object.oid;
1092 if (parents != commit->parents)
1093 strbuf_addch(&s, ' ');
1094 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1096 v->s = strbuf_detach(&s, NULL);
1101 static const char *find_wholine(const char *who, int wholen, const char *buf)
1103 const char *eol;
1104 while (*buf) {
1105 if (!strncmp(buf, who, wholen) &&
1106 buf[wholen] == ' ')
1107 return buf + wholen + 1;
1108 eol = strchr(buf, '\n');
1109 if (!eol)
1110 return "";
1111 eol++;
1112 if (*eol == '\n')
1113 return ""; /* end of header */
1114 buf = eol;
1116 return "";
1119 static const char *copy_line(const char *buf)
1121 const char *eol = strchrnul(buf, '\n');
1122 return xmemdupz(buf, eol - buf);
1125 static const char *copy_name(const char *buf)
1127 const char *cp;
1128 for (cp = buf; *cp && *cp != '\n'; cp++) {
1129 if (!strncmp(cp, " <", 2))
1130 return xmemdupz(buf, cp - buf);
1132 return xstrdup("");
1135 static const char *copy_email(const char *buf, struct used_atom *atom)
1137 const char *email = strchr(buf, '<');
1138 const char *eoemail;
1139 if (!email)
1140 return xstrdup("");
1141 switch (atom->u.email_option.option) {
1142 case EO_RAW:
1143 eoemail = strchr(email, '>');
1144 if (eoemail)
1145 eoemail++;
1146 break;
1147 case EO_TRIM:
1148 email++;
1149 eoemail = strchr(email, '>');
1150 break;
1151 case EO_LOCALPART:
1152 email++;
1153 eoemail = strchr(email, '@');
1154 if (!eoemail)
1155 eoemail = strchr(email, '>');
1156 break;
1157 default:
1158 BUG("unknown email option");
1161 if (!eoemail)
1162 return xstrdup("");
1163 return xmemdupz(email, eoemail - email);
1166 static char *copy_subject(const char *buf, unsigned long len)
1168 struct strbuf sb = STRBUF_INIT;
1169 int i;
1171 for (i = 0; i < len; i++) {
1172 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1173 continue; /* ignore CR in CRLF */
1175 if (buf[i] == '\n')
1176 strbuf_addch(&sb, ' ');
1177 else
1178 strbuf_addch(&sb, buf[i]);
1180 return strbuf_detach(&sb, NULL);
1183 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1185 const char *eoemail = strstr(buf, "> ");
1186 char *zone;
1187 timestamp_t timestamp;
1188 long tz;
1189 struct date_mode date_mode = { DATE_NORMAL };
1190 const char *formatp;
1193 * We got here because atomname ends in "date" or "date<something>";
1194 * it's not possible that <something> is not ":<format>" because
1195 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1196 * ":" means no format is specified, and use the default.
1198 formatp = strchr(atomname, ':');
1199 if (formatp != NULL) {
1200 formatp++;
1201 parse_date_format(formatp, &date_mode);
1204 if (!eoemail)
1205 goto bad;
1206 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1207 if (timestamp == TIME_MAX)
1208 goto bad;
1209 tz = strtol(zone, NULL, 10);
1210 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1211 goto bad;
1212 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1213 v->value = timestamp;
1214 return;
1215 bad:
1216 v->s = xstrdup("");
1217 v->value = 0;
1220 /* See grab_values */
1221 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1223 int i;
1224 int wholen = strlen(who);
1225 const char *wholine = NULL;
1227 for (i = 0; i < used_atom_cnt; i++) {
1228 const char *name = used_atom[i].name;
1229 struct atom_value *v = &val[i];
1230 if (!!deref != (*name == '*'))
1231 continue;
1232 if (deref)
1233 name++;
1234 if (strncmp(who, name, wholen))
1235 continue;
1236 if (name[wholen] != 0 &&
1237 strcmp(name + wholen, "name") &&
1238 !starts_with(name + wholen, "email") &&
1239 !starts_with(name + wholen, "date"))
1240 continue;
1241 if (!wholine)
1242 wholine = find_wholine(who, wholen, buf);
1243 if (!wholine)
1244 return; /* no point looking for it */
1245 if (name[wholen] == 0)
1246 v->s = copy_line(wholine);
1247 else if (!strcmp(name + wholen, "name"))
1248 v->s = copy_name(wholine);
1249 else if (starts_with(name + wholen, "email"))
1250 v->s = copy_email(wholine, &used_atom[i]);
1251 else if (starts_with(name + wholen, "date"))
1252 grab_date(wholine, v, name);
1256 * For a tag or a commit object, if "creator" or "creatordate" is
1257 * requested, do something special.
1259 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1260 return; /* "author" for commit object is not wanted */
1261 if (!wholine)
1262 wholine = find_wholine(who, wholen, buf);
1263 if (!wholine)
1264 return;
1265 for (i = 0; i < used_atom_cnt; i++) {
1266 const char *name = used_atom[i].name;
1267 enum atom_type atom_type = used_atom[i].atom_type;
1268 struct atom_value *v = &val[i];
1269 if (!!deref != (*name == '*'))
1270 continue;
1271 if (deref)
1272 name++;
1274 if (atom_type == ATOM_CREATORDATE)
1275 grab_date(wholine, v, name);
1276 else if (atom_type == ATOM_CREATOR)
1277 v->s = copy_line(wholine);
1281 static void find_subpos(const char *buf,
1282 const char **sub, size_t *sublen,
1283 const char **body, size_t *bodylen,
1284 size_t *nonsiglen,
1285 const char **sig, size_t *siglen)
1287 struct strbuf payload = STRBUF_INIT;
1288 struct strbuf signature = STRBUF_INIT;
1289 const char *eol;
1290 const char *end = buf + strlen(buf);
1291 const char *sigstart;
1293 /* parse signature first; we might not even have a subject line */
1294 parse_signature(buf, end - buf, &payload, &signature);
1296 /* skip past header until we hit empty line */
1297 while (*buf && *buf != '\n') {
1298 eol = strchrnul(buf, '\n');
1299 if (*eol)
1300 eol++;
1301 buf = eol;
1303 /* skip any empty lines */
1304 while (*buf == '\n')
1305 buf++;
1306 *sig = strbuf_detach(&signature, siglen);
1307 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1309 /* subject is first non-empty line */
1310 *sub = buf;
1311 /* subject goes to first empty line before signature begins */
1312 if ((eol = strstr(*sub, "\n\n"))) {
1313 eol = eol < sigstart ? eol : sigstart;
1314 /* check if message uses CRLF */
1315 } else if (! (eol = strstr(*sub, "\r\n\r\n"))) {
1316 /* treat whole message as subject */
1317 eol = strrchr(*sub, '\0');
1319 buf = eol;
1320 *sublen = buf - *sub;
1321 /* drop trailing newline, if present */
1322 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1323 (*sub)[*sublen - 1] == '\r'))
1324 *sublen -= 1;
1326 /* skip any empty lines */
1327 while (*buf == '\n' || *buf == '\r')
1328 buf++;
1329 *body = buf;
1330 *bodylen = strlen(buf);
1331 *nonsiglen = sigstart - buf;
1335 * If 'lines' is greater than 0, append that many lines from the given
1336 * 'buf' of length 'size' to the given strbuf.
1338 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1340 int i;
1341 const char *sp, *eol;
1342 size_t len;
1344 sp = buf;
1346 for (i = 0; i < lines && sp < buf + size; i++) {
1347 if (i)
1348 strbuf_addstr(out, "\n ");
1349 eol = memchr(sp, '\n', size - (sp - buf));
1350 len = eol ? eol - sp : size - (sp - buf);
1351 strbuf_add(out, sp, len);
1352 if (!eol)
1353 break;
1354 sp = eol + 1;
1358 /* See grab_values */
1359 static void grab_sub_body_contents(struct atom_value *val, int deref, void *buf)
1361 int i;
1362 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1363 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1365 for (i = 0; i < used_atom_cnt; i++) {
1366 struct used_atom *atom = &used_atom[i];
1367 const char *name = atom->name;
1368 struct atom_value *v = &val[i];
1370 if (!!deref != (*name == '*'))
1371 continue;
1372 if (deref)
1373 name++;
1374 if (strcmp(name, "body") &&
1375 !starts_with(name, "subject") &&
1376 !starts_with(name, "trailers") &&
1377 !starts_with(name, "contents"))
1378 continue;
1379 if (!subpos)
1380 find_subpos(buf,
1381 &subpos, &sublen,
1382 &bodypos, &bodylen, &nonsiglen,
1383 &sigpos, &siglen);
1385 if (atom->u.contents.option == C_SUB)
1386 v->s = copy_subject(subpos, sublen);
1387 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1388 struct strbuf sb = STRBUF_INIT;
1389 format_sanitized_subject(&sb, subpos, sublen);
1390 v->s = strbuf_detach(&sb, NULL);
1391 } else if (atom->u.contents.option == C_BODY_DEP)
1392 v->s = xmemdupz(bodypos, bodylen);
1393 else if (atom->u.contents.option == C_LENGTH)
1394 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1395 else if (atom->u.contents.option == C_BODY)
1396 v->s = xmemdupz(bodypos, nonsiglen);
1397 else if (atom->u.contents.option == C_SIG)
1398 v->s = xmemdupz(sigpos, siglen);
1399 else if (atom->u.contents.option == C_LINES) {
1400 struct strbuf s = STRBUF_INIT;
1401 const char *contents_end = bodypos + nonsiglen;
1403 /* Size is the length of the message after removing the signature */
1404 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1405 v->s = strbuf_detach(&s, NULL);
1406 } else if (atom->u.contents.option == C_TRAILERS) {
1407 struct strbuf s = STRBUF_INIT;
1409 /* Format the trailer info according to the trailer_opts given */
1410 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1412 v->s = strbuf_detach(&s, NULL);
1413 } else if (atom->u.contents.option == C_BARE)
1414 v->s = xstrdup(subpos);
1417 free((void *)sigpos);
1421 * We want to have empty print-string for field requests
1422 * that do not apply (e.g. "authordate" for a tag object)
1424 static void fill_missing_values(struct atom_value *val)
1426 int i;
1427 for (i = 0; i < used_atom_cnt; i++) {
1428 struct atom_value *v = &val[i];
1429 if (v->s == NULL)
1430 v->s = xstrdup("");
1435 * val is a list of atom_value to hold returned values. Extract
1436 * the values for atoms in used_atom array out of (obj, buf, sz).
1437 * when deref is false, (obj, buf, sz) is the object that is
1438 * pointed at by the ref itself; otherwise it is the object the
1439 * ref (which is a tag) refers to.
1441 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf)
1443 switch (obj->type) {
1444 case OBJ_TAG:
1445 grab_tag_values(val, deref, obj);
1446 grab_sub_body_contents(val, deref, buf);
1447 grab_person("tagger", val, deref, buf);
1448 break;
1449 case OBJ_COMMIT:
1450 grab_commit_values(val, deref, obj);
1451 grab_sub_body_contents(val, deref, buf);
1452 grab_person("author", val, deref, buf);
1453 grab_person("committer", val, deref, buf);
1454 break;
1455 case OBJ_TREE:
1456 /* grab_tree_values(val, deref, obj, buf, sz); */
1457 break;
1458 case OBJ_BLOB:
1459 /* grab_blob_values(val, deref, obj, buf, sz); */
1460 break;
1461 default:
1462 die("Eh? Object of type %d?", obj->type);
1466 static inline char *copy_advance(char *dst, const char *src)
1468 while (*src)
1469 *dst++ = *src++;
1470 return dst;
1473 static const char *lstrip_ref_components(const char *refname, int len)
1475 long remaining = len;
1476 const char *start = xstrdup(refname);
1477 const char *to_free = start;
1479 if (len < 0) {
1480 int i;
1481 const char *p = refname;
1483 /* Find total no of '/' separated path-components */
1484 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1487 * The number of components we need to strip is now
1488 * the total minus the components to be left (Plus one
1489 * because we count the number of '/', but the number
1490 * of components is one more than the no of '/').
1492 remaining = i + len + 1;
1495 while (remaining > 0) {
1496 switch (*start++) {
1497 case '\0':
1498 free((char *)to_free);
1499 return xstrdup("");
1500 case '/':
1501 remaining--;
1502 break;
1506 start = xstrdup(start);
1507 free((char *)to_free);
1508 return start;
1511 static const char *rstrip_ref_components(const char *refname, int len)
1513 long remaining = len;
1514 const char *start = xstrdup(refname);
1515 const char *to_free = start;
1517 if (len < 0) {
1518 int i;
1519 const char *p = refname;
1521 /* Find total no of '/' separated path-components */
1522 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1525 * The number of components we need to strip is now
1526 * the total minus the components to be left (Plus one
1527 * because we count the number of '/', but the number
1528 * of components is one more than the no of '/').
1530 remaining = i + len + 1;
1533 while (remaining-- > 0) {
1534 char *p = strrchr(start, '/');
1535 if (p == NULL) {
1536 free((char *)to_free);
1537 return xstrdup("");
1538 } else
1539 p[0] = '\0';
1541 return start;
1544 static const char *show_ref(struct refname_atom *atom, const char *refname)
1546 if (atom->option == R_SHORT)
1547 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1548 else if (atom->option == R_LSTRIP)
1549 return lstrip_ref_components(refname, atom->lstrip);
1550 else if (atom->option == R_RSTRIP)
1551 return rstrip_ref_components(refname, atom->rstrip);
1552 else
1553 return xstrdup(refname);
1556 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1557 struct branch *branch, const char **s)
1559 int num_ours, num_theirs;
1560 if (atom->u.remote_ref.option == RR_REF)
1561 *s = show_ref(&atom->u.remote_ref.refname, refname);
1562 else if (atom->u.remote_ref.option == RR_TRACK) {
1563 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1564 NULL, atom->u.remote_ref.push,
1565 AHEAD_BEHIND_FULL) < 0) {
1566 *s = xstrdup(msgs.gone);
1567 } else if (!num_ours && !num_theirs)
1568 *s = xstrdup("");
1569 else if (!num_ours)
1570 *s = xstrfmt(msgs.behind, num_theirs);
1571 else if (!num_theirs)
1572 *s = xstrfmt(msgs.ahead, num_ours);
1573 else
1574 *s = xstrfmt(msgs.ahead_behind,
1575 num_ours, num_theirs);
1576 if (!atom->u.remote_ref.nobracket && *s[0]) {
1577 const char *to_free = *s;
1578 *s = xstrfmt("[%s]", *s);
1579 free((void *)to_free);
1581 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1582 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1583 NULL, atom->u.remote_ref.push,
1584 AHEAD_BEHIND_FULL) < 0) {
1585 *s = xstrdup("");
1586 return;
1588 if (!num_ours && !num_theirs)
1589 *s = xstrdup("=");
1590 else if (!num_ours)
1591 *s = xstrdup("<");
1592 else if (!num_theirs)
1593 *s = xstrdup(">");
1594 else
1595 *s = xstrdup("<>");
1596 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1597 int explicit;
1598 const char *remote = atom->u.remote_ref.push ?
1599 pushremote_for_branch(branch, &explicit) :
1600 remote_for_branch(branch, &explicit);
1601 *s = xstrdup(explicit ? remote : "");
1602 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1603 const char *merge;
1605 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1606 *s = xstrdup(merge ? merge : "");
1607 } else
1608 BUG("unhandled RR_* enum");
1611 char *get_head_description(void)
1613 struct strbuf desc = STRBUF_INIT;
1614 struct wt_status_state state;
1615 memset(&state, 0, sizeof(state));
1616 wt_status_get_state(the_repository, &state, 1);
1617 if (state.rebase_in_progress ||
1618 state.rebase_interactive_in_progress) {
1619 if (state.branch)
1620 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1621 state.branch);
1622 else
1623 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1624 state.detached_from);
1625 } else if (state.bisect_in_progress)
1626 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1627 state.branch);
1628 else if (state.detached_from) {
1629 if (state.detached_at)
1630 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1631 state.detached_from);
1632 else
1633 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1634 state.detached_from);
1635 } else
1636 strbuf_addstr(&desc, _("(no branch)"));
1638 return strbuf_detach(&desc, NULL);
1641 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1643 if (!ref->symref)
1644 return xstrdup("");
1645 else
1646 return show_ref(&atom->u.refname, ref->symref);
1649 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1651 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1652 return get_head_description();
1653 return show_ref(&atom->u.refname, ref->refname);
1656 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1657 struct expand_data *oi, struct strbuf *err)
1659 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1660 int eaten = 1;
1661 if (oi->info.contentp) {
1662 /* We need to know that to use parse_object_buffer properly */
1663 oi->info.sizep = &oi->size;
1664 oi->info.typep = &oi->type;
1666 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1667 OBJECT_INFO_LOOKUP_REPLACE))
1668 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1669 oid_to_hex(&oi->oid), ref->refname);
1670 if (oi->info.disk_sizep && oi->disk_size < 0)
1671 BUG("Object size is less than zero.");
1673 if (oi->info.contentp) {
1674 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1675 if (!*obj) {
1676 if (!eaten)
1677 free(oi->content);
1678 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1679 oid_to_hex(&oi->oid), ref->refname);
1681 grab_values(ref->value, deref, *obj, oi->content);
1684 grab_common_values(ref->value, deref, oi);
1685 if (!eaten)
1686 free(oi->content);
1687 return 0;
1690 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1692 int i;
1694 for (i = 0; worktrees[i]; i++) {
1695 if (worktrees[i]->head_ref) {
1696 struct ref_to_worktree_entry *entry;
1697 entry = xmalloc(sizeof(*entry));
1698 entry->wt = worktrees[i];
1699 hashmap_entry_init(&entry->ent,
1700 strhash(worktrees[i]->head_ref));
1702 hashmap_add(map, &entry->ent);
1707 static void lazy_init_worktree_map(void)
1709 if (ref_to_worktree_map.worktrees)
1710 return;
1712 ref_to_worktree_map.worktrees = get_worktrees();
1713 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1714 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1717 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1719 struct hashmap_entry entry, *e;
1720 struct ref_to_worktree_entry *lookup_result;
1722 lazy_init_worktree_map();
1724 hashmap_entry_init(&entry, strhash(ref->refname));
1725 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1727 if (!e)
1728 return xstrdup("");
1730 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1732 return xstrdup(lookup_result->wt->path);
1736 * Parse the object referred by ref, and grab needed value.
1738 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1740 struct object *obj;
1741 int i;
1742 struct object_info empty = OBJECT_INFO_INIT;
1744 CALLOC_ARRAY(ref->value, used_atom_cnt);
1746 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1747 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1748 NULL, NULL);
1749 if (!ref->symref)
1750 ref->symref = xstrdup("");
1753 /* Fill in specials first */
1754 for (i = 0; i < used_atom_cnt; i++) {
1755 struct used_atom *atom = &used_atom[i];
1756 enum atom_type atom_type = atom->atom_type;
1757 const char *name = used_atom[i].name;
1758 struct atom_value *v = &ref->value[i];
1759 int deref = 0;
1760 const char *refname;
1761 struct branch *branch = NULL;
1763 v->handler = append_atom;
1764 v->atom = atom;
1766 if (*name == '*') {
1767 deref = 1;
1768 name++;
1771 if (atom_type == ATOM_REFNAME)
1772 refname = get_refname(atom, ref);
1773 else if (atom_type == ATOM_WORKTREEPATH) {
1774 if (ref->kind == FILTER_REFS_BRANCHES)
1775 v->s = get_worktree_path(atom, ref);
1776 else
1777 v->s = xstrdup("");
1778 continue;
1780 else if (atom_type == ATOM_SYMREF)
1781 refname = get_symref(atom, ref);
1782 else if (atom_type == ATOM_UPSTREAM) {
1783 const char *branch_name;
1784 /* only local branches may have an upstream */
1785 if (!skip_prefix(ref->refname, "refs/heads/",
1786 &branch_name)) {
1787 v->s = xstrdup("");
1788 continue;
1790 branch = branch_get(branch_name);
1792 refname = branch_get_upstream(branch, NULL);
1793 if (refname)
1794 fill_remote_ref_details(atom, refname, branch, &v->s);
1795 else
1796 v->s = xstrdup("");
1797 continue;
1798 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1799 const char *branch_name;
1800 v->s = xstrdup("");
1801 if (!skip_prefix(ref->refname, "refs/heads/",
1802 &branch_name))
1803 continue;
1804 branch = branch_get(branch_name);
1806 if (atom->u.remote_ref.push_remote)
1807 refname = NULL;
1808 else {
1809 refname = branch_get_push(branch, NULL);
1810 if (!refname)
1811 continue;
1813 /* We will definitely re-init v->s on the next line. */
1814 free((char *)v->s);
1815 fill_remote_ref_details(atom, refname, branch, &v->s);
1816 continue;
1817 } else if (atom_type == ATOM_COLOR) {
1818 v->s = xstrdup(atom->u.color);
1819 continue;
1820 } else if (atom_type == ATOM_FLAG) {
1821 char buf[256], *cp = buf;
1822 if (ref->flag & REF_ISSYMREF)
1823 cp = copy_advance(cp, ",symref");
1824 if (ref->flag & REF_ISPACKED)
1825 cp = copy_advance(cp, ",packed");
1826 if (cp == buf)
1827 v->s = xstrdup("");
1828 else {
1829 *cp = '\0';
1830 v->s = xstrdup(buf + 1);
1832 continue;
1833 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1834 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1835 continue;
1836 } else if (atom_type == ATOM_HEAD) {
1837 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1838 v->s = xstrdup("*");
1839 else
1840 v->s = xstrdup(" ");
1841 continue;
1842 } else if (atom_type == ATOM_ALIGN) {
1843 v->handler = align_atom_handler;
1844 v->s = xstrdup("");
1845 continue;
1846 } else if (atom_type == ATOM_END) {
1847 v->handler = end_atom_handler;
1848 v->s = xstrdup("");
1849 continue;
1850 } else if (atom_type == ATOM_IF) {
1851 const char *s;
1852 if (skip_prefix(name, "if:", &s))
1853 v->s = xstrdup(s);
1854 else
1855 v->s = xstrdup("");
1856 v->handler = if_atom_handler;
1857 continue;
1858 } else if (atom_type == ATOM_THEN) {
1859 v->handler = then_atom_handler;
1860 v->s = xstrdup("");
1861 continue;
1862 } else if (atom_type == ATOM_ELSE) {
1863 v->handler = else_atom_handler;
1864 v->s = xstrdup("");
1865 continue;
1866 } else
1867 continue;
1869 if (!deref)
1870 v->s = xstrdup(refname);
1871 else
1872 v->s = xstrfmt("%s^{}", refname);
1873 free((char *)refname);
1876 for (i = 0; i < used_atom_cnt; i++) {
1877 struct atom_value *v = &ref->value[i];
1878 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1879 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1880 oid_to_hex(&ref->objectname), ref->refname);
1883 if (need_tagged)
1884 oi.info.contentp = &oi.content;
1885 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1886 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1887 return 0;
1890 oi.oid = ref->objectname;
1891 if (get_object(ref, 0, &obj, &oi, err))
1892 return -1;
1895 * If there is no atom that wants to know about tagged
1896 * object, we are done.
1898 if (!need_tagged || (obj->type != OBJ_TAG))
1899 return 0;
1902 * If it is a tag object, see if we use a value that derefs
1903 * the object, and if we do grab the object it refers to.
1905 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
1908 * NEEDSWORK: This derefs tag only once, which
1909 * is good to deal with chains of trust, but
1910 * is not consistent with what deref_tag() does
1911 * which peels the onion to the core.
1913 return get_object(ref, 1, &obj, &oi_deref, err);
1917 * Given a ref, return the value for the atom. This lazily gets value
1918 * out of the object by calling populate value.
1920 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1921 struct atom_value **v, struct strbuf *err)
1923 if (!ref->value) {
1924 if (populate_value(ref, err))
1925 return -1;
1926 fill_missing_values(ref->value);
1928 *v = &ref->value[atom];
1929 return 0;
1933 * Return 1 if the refname matches one of the patterns, otherwise 0.
1934 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1935 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1936 * matches "refs/heads/mas*", too).
1938 static int match_pattern(const struct ref_filter *filter, const char *refname)
1940 const char **patterns = filter->name_patterns;
1941 unsigned flags = 0;
1943 if (filter->ignore_case)
1944 flags |= WM_CASEFOLD;
1947 * When no '--format' option is given we need to skip the prefix
1948 * for matching refs of tags and branches.
1950 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1951 skip_prefix(refname, "refs/heads/", &refname) ||
1952 skip_prefix(refname, "refs/remotes/", &refname) ||
1953 skip_prefix(refname, "refs/", &refname));
1955 for (; *patterns; patterns++) {
1956 if (!wildmatch(*patterns, refname, flags))
1957 return 1;
1959 return 0;
1963 * Return 1 if the refname matches one of the patterns, otherwise 0.
1964 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1965 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1966 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1968 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1970 const char **pattern = filter->name_patterns;
1971 int namelen = strlen(refname);
1972 unsigned flags = WM_PATHNAME;
1974 if (filter->ignore_case)
1975 flags |= WM_CASEFOLD;
1977 for (; *pattern; pattern++) {
1978 const char *p = *pattern;
1979 int plen = strlen(p);
1981 if ((plen <= namelen) &&
1982 !strncmp(refname, p, plen) &&
1983 (refname[plen] == '\0' ||
1984 refname[plen] == '/' ||
1985 p[plen-1] == '/'))
1986 return 1;
1987 if (!wildmatch(p, refname, flags))
1988 return 1;
1990 return 0;
1993 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1994 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1996 if (!*filter->name_patterns)
1997 return 1; /* No pattern always matches */
1998 if (filter->match_as_path)
1999 return match_name_as_path(filter, refname);
2000 return match_pattern(filter, refname);
2004 * This is the same as for_each_fullref_in(), but it tries to iterate
2005 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2006 * pattern match, so the callback still has to match each ref individually.
2008 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2009 each_ref_fn cb,
2010 void *cb_data,
2011 int broken)
2013 if (!filter->match_as_path) {
2015 * in this case, the patterns are applied after
2016 * prefixes like "refs/heads/" etc. are stripped off,
2017 * so we have to look at everything:
2019 return for_each_fullref_in("", cb, cb_data, broken);
2022 if (filter->ignore_case) {
2024 * we can't handle case-insensitive comparisons,
2025 * so just return everything and let the caller
2026 * sort it out.
2028 return for_each_fullref_in("", cb, cb_data, broken);
2031 if (!filter->name_patterns[0]) {
2032 /* no patterns; we have to look at everything */
2033 return for_each_fullref_in("", cb, cb_data, broken);
2036 return for_each_fullref_in_prefixes(NULL, filter->name_patterns,
2037 cb, cb_data, broken);
2041 * Given a ref (oid, refname), check if the ref belongs to the array
2042 * of oids. If the given ref is a tag, check if the given tag points
2043 * at one of the oids in the given oid array.
2044 * NEEDSWORK:
2045 * 1. Only a single level of indirection is obtained, we might want to
2046 * change this to account for multiple levels (e.g. annotated tags
2047 * pointing to annotated tags pointing to a commit.)
2048 * 2. As the refs are cached we might know what refname peels to without
2049 * the need to parse the object via parse_object(). peel_ref() might be a
2050 * more efficient alternative to obtain the pointee.
2052 static const struct object_id *match_points_at(struct oid_array *points_at,
2053 const struct object_id *oid,
2054 const char *refname)
2056 const struct object_id *tagged_oid = NULL;
2057 struct object *obj;
2059 if (oid_array_lookup(points_at, oid) >= 0)
2060 return oid;
2061 obj = parse_object(the_repository, oid);
2062 if (!obj)
2063 die(_("malformed object at '%s'"), refname);
2064 if (obj->type == OBJ_TAG)
2065 tagged_oid = get_tagged_oid((struct tag *)obj);
2066 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2067 return tagged_oid;
2068 return NULL;
2072 * Allocate space for a new ref_array_item and copy the name and oid to it.
2074 * Callers can then fill in other struct members at their leisure.
2076 static struct ref_array_item *new_ref_array_item(const char *refname,
2077 const struct object_id *oid)
2079 struct ref_array_item *ref;
2081 FLEX_ALLOC_STR(ref, refname, refname);
2082 oidcpy(&ref->objectname, oid);
2084 return ref;
2087 struct ref_array_item *ref_array_push(struct ref_array *array,
2088 const char *refname,
2089 const struct object_id *oid)
2091 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2093 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2094 array->items[array->nr++] = ref;
2096 return ref;
2099 static int ref_kind_from_refname(const char *refname)
2101 unsigned int i;
2103 static struct {
2104 const char *prefix;
2105 unsigned int kind;
2106 } ref_kind[] = {
2107 { "refs/heads/" , FILTER_REFS_BRANCHES },
2108 { "refs/remotes/" , FILTER_REFS_REMOTES },
2109 { "refs/tags/", FILTER_REFS_TAGS}
2112 if (!strcmp(refname, "HEAD"))
2113 return FILTER_REFS_DETACHED_HEAD;
2115 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2116 if (starts_with(refname, ref_kind[i].prefix))
2117 return ref_kind[i].kind;
2120 return FILTER_REFS_OTHERS;
2123 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2125 if (filter->kind == FILTER_REFS_BRANCHES ||
2126 filter->kind == FILTER_REFS_REMOTES ||
2127 filter->kind == FILTER_REFS_TAGS)
2128 return filter->kind;
2129 return ref_kind_from_refname(refname);
2132 struct ref_filter_cbdata {
2133 struct ref_array *array;
2134 struct ref_filter *filter;
2135 struct contains_cache contains_cache;
2136 struct contains_cache no_contains_cache;
2140 * A call-back given to for_each_ref(). Filter refs and keep them for
2141 * later object processing.
2143 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2145 struct ref_filter_cbdata *ref_cbdata = cb_data;
2146 struct ref_filter *filter = ref_cbdata->filter;
2147 struct ref_array_item *ref;
2148 struct commit *commit = NULL;
2149 unsigned int kind;
2151 if (flag & REF_BAD_NAME) {
2152 warning(_("ignoring ref with broken name %s"), refname);
2153 return 0;
2156 if (flag & REF_ISBROKEN) {
2157 warning(_("ignoring broken ref %s"), refname);
2158 return 0;
2161 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2162 kind = filter_ref_kind(filter, refname);
2163 if (!(kind & filter->kind))
2164 return 0;
2166 if (!filter_pattern_match(filter, refname))
2167 return 0;
2169 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2170 return 0;
2173 * A merge filter is applied on refs pointing to commits. Hence
2174 * obtain the commit using the 'oid' available and discard all
2175 * non-commits early. The actual filtering is done later.
2177 if (filter->reachable_from || filter->unreachable_from ||
2178 filter->with_commit || filter->no_commit || filter->verbose) {
2179 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2180 if (!commit)
2181 return 0;
2182 /* We perform the filtering for the '--contains' option... */
2183 if (filter->with_commit &&
2184 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2185 return 0;
2186 /* ...or for the `--no-contains' option */
2187 if (filter->no_commit &&
2188 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2189 return 0;
2193 * We do not open the object yet; sort may only need refname
2194 * to do its job and the resulting list may yet to be pruned
2195 * by maxcount logic.
2197 ref = ref_array_push(ref_cbdata->array, refname, oid);
2198 ref->commit = commit;
2199 ref->flag = flag;
2200 ref->kind = kind;
2202 return 0;
2205 /* Free memory allocated for a ref_array_item */
2206 static void free_array_item(struct ref_array_item *item)
2208 free((char *)item->symref);
2209 if (item->value) {
2210 int i;
2211 for (i = 0; i < used_atom_cnt; i++)
2212 free((char *)item->value[i].s);
2213 free(item->value);
2215 free(item);
2218 /* Free all memory allocated for ref_array */
2219 void ref_array_clear(struct ref_array *array)
2221 int i;
2223 for (i = 0; i < array->nr; i++)
2224 free_array_item(array->items[i]);
2225 FREE_AND_NULL(array->items);
2226 array->nr = array->alloc = 0;
2228 for (i = 0; i < used_atom_cnt; i++)
2229 free((char *)used_atom[i].name);
2230 FREE_AND_NULL(used_atom);
2231 used_atom_cnt = 0;
2233 if (ref_to_worktree_map.worktrees) {
2234 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2235 struct ref_to_worktree_entry, ent);
2236 free_worktrees(ref_to_worktree_map.worktrees);
2237 ref_to_worktree_map.worktrees = NULL;
2241 #define EXCLUDE_REACHED 0
2242 #define INCLUDE_REACHED 1
2243 static void reach_filter(struct ref_array *array,
2244 struct commit_list *check_reachable,
2245 int include_reached)
2247 struct rev_info revs;
2248 int i, old_nr;
2249 struct commit **to_clear;
2250 struct commit_list *cr;
2252 if (!check_reachable)
2253 return;
2255 CALLOC_ARRAY(to_clear, array->nr);
2257 repo_init_revisions(the_repository, &revs, NULL);
2259 for (i = 0; i < array->nr; i++) {
2260 struct ref_array_item *item = array->items[i];
2261 add_pending_object(&revs, &item->commit->object, item->refname);
2262 to_clear[i] = item->commit;
2265 for (cr = check_reachable; cr; cr = cr->next) {
2266 struct commit *merge_commit = cr->item;
2267 merge_commit->object.flags |= UNINTERESTING;
2268 add_pending_object(&revs, &merge_commit->object, "");
2271 revs.limited = 1;
2272 if (prepare_revision_walk(&revs))
2273 die(_("revision walk setup failed"));
2275 old_nr = array->nr;
2276 array->nr = 0;
2278 for (i = 0; i < old_nr; i++) {
2279 struct ref_array_item *item = array->items[i];
2280 struct commit *commit = item->commit;
2282 int is_merged = !!(commit->object.flags & UNINTERESTING);
2284 if (is_merged == include_reached)
2285 array->items[array->nr++] = array->items[i];
2286 else
2287 free_array_item(item);
2290 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2292 while (check_reachable) {
2293 struct commit *merge_commit = pop_commit(&check_reachable);
2294 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2297 free(to_clear);
2301 * API for filtering a set of refs. Based on the type of refs the user
2302 * has requested, we iterate through those refs and apply filters
2303 * as per the given ref_filter structure and finally store the
2304 * filtered refs in the ref_array structure.
2306 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2308 struct ref_filter_cbdata ref_cbdata;
2309 int ret = 0;
2310 unsigned int broken = 0;
2312 ref_cbdata.array = array;
2313 ref_cbdata.filter = filter;
2315 if (type & FILTER_REFS_INCLUDE_BROKEN)
2316 broken = 1;
2317 filter->kind = type & FILTER_REFS_KIND_MASK;
2319 init_contains_cache(&ref_cbdata.contains_cache);
2320 init_contains_cache(&ref_cbdata.no_contains_cache);
2322 /* Simple per-ref filtering */
2323 if (!filter->kind)
2324 die("filter_refs: invalid type");
2325 else {
2327 * For common cases where we need only branches or remotes or tags,
2328 * we only iterate through those refs. If a mix of refs is needed,
2329 * we iterate over all refs and filter out required refs with the help
2330 * of filter_ref_kind().
2332 if (filter->kind == FILTER_REFS_BRANCHES)
2333 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2334 else if (filter->kind == FILTER_REFS_REMOTES)
2335 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2336 else if (filter->kind == FILTER_REFS_TAGS)
2337 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2338 else if (filter->kind & FILTER_REFS_ALL)
2339 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2340 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2341 head_ref(ref_filter_handler, &ref_cbdata);
2344 clear_contains_cache(&ref_cbdata.contains_cache);
2345 clear_contains_cache(&ref_cbdata.no_contains_cache);
2347 /* Filters that need revision walking */
2348 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2349 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2351 return ret;
2354 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2356 if (!(a->kind ^ b->kind))
2357 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2358 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2359 return -1;
2360 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2361 return 1;
2362 BUG("should have died in the xor check above");
2363 return 0;
2366 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2368 struct atom_value *va, *vb;
2369 int cmp;
2370 int cmp_detached_head = 0;
2371 cmp_type cmp_type = used_atom[s->atom].type;
2372 struct strbuf err = STRBUF_INIT;
2374 if (get_ref_atom_value(a, s->atom, &va, &err))
2375 die("%s", err.buf);
2376 if (get_ref_atom_value(b, s->atom, &vb, &err))
2377 die("%s", err.buf);
2378 strbuf_release(&err);
2379 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2380 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2381 cmp = compare_detached_head(a, b);
2382 cmp_detached_head = 1;
2383 } else if (s->sort_flags & REF_SORTING_VERSION) {
2384 cmp = versioncmp(va->s, vb->s);
2385 } else if (cmp_type == FIELD_STR) {
2386 int (*cmp_fn)(const char *, const char *);
2387 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2388 ? strcasecmp : strcmp;
2389 cmp = cmp_fn(va->s, vb->s);
2390 } else {
2391 if (va->value < vb->value)
2392 cmp = -1;
2393 else if (va->value == vb->value)
2394 cmp = 0;
2395 else
2396 cmp = 1;
2399 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2400 ? -cmp : cmp;
2403 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2405 struct ref_array_item *a = *((struct ref_array_item **)a_);
2406 struct ref_array_item *b = *((struct ref_array_item **)b_);
2407 struct ref_sorting *s;
2409 for (s = ref_sorting; s; s = s->next) {
2410 int cmp = cmp_ref_sorting(s, a, b);
2411 if (cmp)
2412 return cmp;
2414 s = ref_sorting;
2415 return s && s->sort_flags & REF_SORTING_ICASE ?
2416 strcasecmp(a->refname, b->refname) :
2417 strcmp(a->refname, b->refname);
2420 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2421 unsigned int mask, int on)
2423 for (; sorting; sorting = sorting->next) {
2424 if (on)
2425 sorting->sort_flags |= mask;
2426 else
2427 sorting->sort_flags &= ~mask;
2431 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2433 QSORT_S(array->items, array->nr, compare_refs, sorting);
2436 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2438 struct strbuf *s = &state->stack->output;
2440 while (*cp && (!ep || cp < ep)) {
2441 if (*cp == '%') {
2442 if (cp[1] == '%')
2443 cp++;
2444 else {
2445 int ch = hex2chr(cp + 1);
2446 if (0 <= ch) {
2447 strbuf_addch(s, ch);
2448 cp += 3;
2449 continue;
2453 strbuf_addch(s, *cp);
2454 cp++;
2458 int format_ref_array_item(struct ref_array_item *info,
2459 const struct ref_format *format,
2460 struct strbuf *final_buf,
2461 struct strbuf *error_buf)
2463 const char *cp, *sp, *ep;
2464 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2466 state.quote_style = format->quote_style;
2467 push_stack_element(&state.stack);
2469 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2470 struct atom_value *atomv;
2471 int pos;
2473 ep = strchr(sp, ')');
2474 if (cp < sp)
2475 append_literal(cp, sp, &state);
2476 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2477 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2478 atomv->handler(atomv, &state, error_buf)) {
2479 pop_stack_element(&state.stack);
2480 return -1;
2483 if (*cp) {
2484 sp = cp + strlen(cp);
2485 append_literal(cp, sp, &state);
2487 if (format->need_color_reset_at_eol) {
2488 struct atom_value resetv;
2489 resetv.s = GIT_COLOR_RESET;
2490 if (append_atom(&resetv, &state, error_buf)) {
2491 pop_stack_element(&state.stack);
2492 return -1;
2495 if (state.stack->prev) {
2496 pop_stack_element(&state.stack);
2497 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2499 strbuf_addbuf(final_buf, &state.stack->output);
2500 pop_stack_element(&state.stack);
2501 return 0;
2504 void pretty_print_ref(const char *name, const struct object_id *oid,
2505 const struct ref_format *format)
2507 struct ref_array_item *ref_item;
2508 struct strbuf output = STRBUF_INIT;
2509 struct strbuf err = STRBUF_INIT;
2511 ref_item = new_ref_array_item(name, oid);
2512 ref_item->kind = ref_kind_from_refname(name);
2513 if (format_ref_array_item(ref_item, format, &output, &err))
2514 die("%s", err.buf);
2515 fwrite(output.buf, 1, output.len, stdout);
2516 putchar('\n');
2518 strbuf_release(&err);
2519 strbuf_release(&output);
2520 free_array_item(ref_item);
2523 static int parse_sorting_atom(const char *atom)
2526 * This parses an atom using a dummy ref_format, since we don't
2527 * actually care about the formatting details.
2529 struct ref_format dummy = REF_FORMAT_INIT;
2530 const char *end = atom + strlen(atom);
2531 struct strbuf err = STRBUF_INIT;
2532 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2533 if (res < 0)
2534 die("%s", err.buf);
2535 strbuf_release(&err);
2536 return res;
2539 /* If no sorting option is given, use refname to sort as default */
2540 struct ref_sorting *ref_default_sorting(void)
2542 static const char cstr_name[] = "refname";
2544 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2546 sorting->next = NULL;
2547 sorting->atom = parse_sorting_atom(cstr_name);
2548 return sorting;
2551 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2553 struct ref_sorting *s;
2555 CALLOC_ARRAY(s, 1);
2556 s->next = *sorting_tail;
2557 *sorting_tail = s;
2559 if (*arg == '-') {
2560 s->sort_flags |= REF_SORTING_REVERSE;
2561 arg++;
2563 if (skip_prefix(arg, "version:", &arg) ||
2564 skip_prefix(arg, "v:", &arg))
2565 s->sort_flags |= REF_SORTING_VERSION;
2566 s->atom = parse_sorting_atom(arg);
2569 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2572 * NEEDSWORK: We should probably clear the list in this case, but we've
2573 * already munged the global used_atoms list, which would need to be
2574 * undone.
2576 BUG_ON_OPT_NEG(unset);
2578 parse_ref_sorting(opt->value, arg);
2579 return 0;
2582 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2584 struct ref_filter *rf = opt->value;
2585 struct object_id oid;
2586 struct commit *merge_commit;
2588 BUG_ON_OPT_NEG(unset);
2590 if (get_oid(arg, &oid))
2591 die(_("malformed object name %s"), arg);
2593 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2595 if (!merge_commit)
2596 return error(_("option `%s' must point to a commit"), opt->long_name);
2598 if (starts_with(opt->long_name, "no"))
2599 commit_list_insert(merge_commit, &rf->unreachable_from);
2600 else
2601 commit_list_insert(merge_commit, &rf->reachable_from);
2603 return 0;