commit: fix duplication regression in permission error output
[alt-git.git] / ref-filter.c
blob0cfef7b719bb2b42a5d3a711a8074d167182fa14
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 __attribute__((format (printf, 3, 4)))
217 static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
219 va_list ap;
220 va_start(ap, fmt);
221 strbuf_vaddf(sb, fmt, ap);
222 va_end(ap);
223 return ret;
226 static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
227 const char *color_value, struct strbuf *err)
229 if (!color_value)
230 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
231 if (color_parse(color_value, atom->u.color) < 0)
232 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
233 color_value);
235 * We check this after we've parsed the color, which lets us complain
236 * about syntactically bogus color names even if they won't be used.
238 if (!want_color(format->use_color))
239 color_parse("", atom->u.color);
240 return 0;
243 static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
244 const char *name, struct strbuf *err)
246 if (!arg)
247 atom->option = R_NORMAL;
248 else if (!strcmp(arg, "short"))
249 atom->option = R_SHORT;
250 else if (skip_prefix(arg, "lstrip=", &arg) ||
251 skip_prefix(arg, "strip=", &arg)) {
252 atom->option = R_LSTRIP;
253 if (strtol_i(arg, 10, &atom->lstrip))
254 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
255 } else if (skip_prefix(arg, "rstrip=", &arg)) {
256 atom->option = R_RSTRIP;
257 if (strtol_i(arg, 10, &atom->rstrip))
258 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
259 } else
260 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
261 return 0;
264 static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
265 const char *arg, struct strbuf *err)
267 struct string_list params = STRING_LIST_INIT_DUP;
268 int i;
270 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
271 atom->u.remote_ref.push = 1;
273 if (!arg) {
274 atom->u.remote_ref.option = RR_REF;
275 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
276 arg, atom->name, err);
279 atom->u.remote_ref.nobracket = 0;
280 string_list_split(&params, arg, ',', -1);
282 for (i = 0; i < params.nr; i++) {
283 const char *s = params.items[i].string;
285 if (!strcmp(s, "track"))
286 atom->u.remote_ref.option = RR_TRACK;
287 else if (!strcmp(s, "trackshort"))
288 atom->u.remote_ref.option = RR_TRACKSHORT;
289 else if (!strcmp(s, "nobracket"))
290 atom->u.remote_ref.nobracket = 1;
291 else if (!strcmp(s, "remotename")) {
292 atom->u.remote_ref.option = RR_REMOTE_NAME;
293 atom->u.remote_ref.push_remote = 1;
294 } else if (!strcmp(s, "remoteref")) {
295 atom->u.remote_ref.option = RR_REMOTE_REF;
296 atom->u.remote_ref.push_remote = 1;
297 } else {
298 atom->u.remote_ref.option = RR_REF;
299 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
300 arg, atom->name, err)) {
301 string_list_clear(&params, 0);
302 return -1;
307 string_list_clear(&params, 0);
308 return 0;
311 static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
312 const char *arg, struct strbuf *err)
314 if (arg)
315 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
316 if (*atom->name == '*')
317 oi_deref.info.typep = &oi_deref.type;
318 else
319 oi.info.typep = &oi.type;
320 return 0;
323 static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
324 const char *arg, struct strbuf *err)
326 if (!arg) {
327 atom->u.objectsize.option = O_SIZE;
328 if (*atom->name == '*')
329 oi_deref.info.sizep = &oi_deref.size;
330 else
331 oi.info.sizep = &oi.size;
332 } else if (!strcmp(arg, "disk")) {
333 atom->u.objectsize.option = O_SIZE_DISK;
334 if (*atom->name == '*')
335 oi_deref.info.disk_sizep = &oi_deref.disk_size;
336 else
337 oi.info.disk_sizep = &oi.disk_size;
338 } else
339 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectsize) argument: %s"), arg);
340 return 0;
343 static int deltabase_atom_parser(const struct ref_format *format, struct used_atom *atom,
344 const char *arg, struct strbuf *err)
346 if (arg)
347 return strbuf_addf_ret(err, -1, _("%%(deltabase) does not take arguments"));
348 if (*atom->name == '*')
349 oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;
350 else
351 oi.info.delta_base_oid = &oi.delta_base_oid;
352 return 0;
355 static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
356 const char *arg, struct strbuf *err)
358 if (arg)
359 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
360 atom->u.contents.option = C_BODY_DEP;
361 return 0;
364 static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
365 const char *arg, struct strbuf *err)
367 if (!arg)
368 atom->u.contents.option = C_SUB;
369 else if (!strcmp(arg, "sanitize"))
370 atom->u.contents.option = C_SUB_SANITIZE;
371 else
372 return strbuf_addf_ret(err, -1, _("unrecognized %%(subject) argument: %s"), arg);
373 return 0;
376 static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
377 const char *arg, struct strbuf *err)
379 atom->u.contents.trailer_opts.no_divider = 1;
381 if (arg) {
382 const char *argbuf = xstrfmt("%s)", arg);
383 char *invalid_arg = NULL;
385 if (format_set_trailers_options(&atom->u.contents.trailer_opts,
386 &ref_trailer_buf.filter_list,
387 &ref_trailer_buf.sepbuf,
388 &ref_trailer_buf.kvsepbuf,
389 &argbuf, &invalid_arg)) {
390 if (!invalid_arg)
391 strbuf_addf(err, _("expected %%(trailers:key=<value>)"));
392 else
393 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);
394 free((char *)invalid_arg);
395 return -1;
398 atom->u.contents.option = C_TRAILERS;
399 return 0;
402 static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
403 const char *arg, struct strbuf *err)
405 if (!arg)
406 atom->u.contents.option = C_BARE;
407 else if (!strcmp(arg, "body"))
408 atom->u.contents.option = C_BODY;
409 else if (!strcmp(arg, "size"))
410 atom->u.contents.option = C_LENGTH;
411 else if (!strcmp(arg, "signature"))
412 atom->u.contents.option = C_SIG;
413 else if (!strcmp(arg, "subject"))
414 atom->u.contents.option = C_SUB;
415 else if (!strcmp(arg, "trailers")) {
416 if (trailers_atom_parser(format, atom, NULL, err))
417 return -1;
418 } else if (skip_prefix(arg, "trailers:", &arg)) {
419 if (trailers_atom_parser(format, atom, arg, err))
420 return -1;
421 } else if (skip_prefix(arg, "lines=", &arg)) {
422 atom->u.contents.option = C_LINES;
423 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
424 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
425 } else
426 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
427 return 0;
430 static int oid_atom_parser(const struct ref_format *format, struct used_atom *atom,
431 const char *arg, struct strbuf *err)
433 if (!arg)
434 atom->u.oid.option = O_FULL;
435 else if (!strcmp(arg, "short"))
436 atom->u.oid.option = O_SHORT;
437 else if (skip_prefix(arg, "short=", &arg)) {
438 atom->u.oid.option = O_LENGTH;
439 if (strtoul_ui(arg, 10, &atom->u.oid.length) ||
440 atom->u.oid.length == 0)
441 return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);
442 if (atom->u.oid.length < MINIMUM_ABBREV)
443 atom->u.oid.length = MINIMUM_ABBREV;
444 } else
445 return strbuf_addf_ret(err, -1, _("unrecognized argument '%s' in %%(%s)"), arg, atom->name);
446 return 0;
449 static int person_email_atom_parser(const struct ref_format *format, struct used_atom *atom,
450 const char *arg, struct strbuf *err)
452 if (!arg)
453 atom->u.email_option.option = EO_RAW;
454 else if (!strcmp(arg, "trim"))
455 atom->u.email_option.option = EO_TRIM;
456 else if (!strcmp(arg, "localpart"))
457 atom->u.email_option.option = EO_LOCALPART;
458 else
459 return strbuf_addf_ret(err, -1, _("unrecognized email option: %s"), arg);
460 return 0;
463 static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
464 const char *arg, struct strbuf *err)
466 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
469 static align_type parse_align_position(const char *s)
471 if (!strcmp(s, "right"))
472 return ALIGN_RIGHT;
473 else if (!strcmp(s, "middle"))
474 return ALIGN_MIDDLE;
475 else if (!strcmp(s, "left"))
476 return ALIGN_LEFT;
477 return -1;
480 static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
481 const char *arg, struct strbuf *err)
483 struct align *align = &atom->u.align;
484 struct string_list params = STRING_LIST_INIT_DUP;
485 int i;
486 unsigned int width = ~0U;
488 if (!arg)
489 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
491 align->position = ALIGN_LEFT;
493 string_list_split(&params, arg, ',', -1);
494 for (i = 0; i < params.nr; i++) {
495 const char *s = params.items[i].string;
496 int position;
498 if (skip_prefix(s, "position=", &s)) {
499 position = parse_align_position(s);
500 if (position < 0) {
501 strbuf_addf(err, _("unrecognized position:%s"), s);
502 string_list_clear(&params, 0);
503 return -1;
505 align->position = position;
506 } else if (skip_prefix(s, "width=", &s)) {
507 if (strtoul_ui(s, 10, &width)) {
508 strbuf_addf(err, _("unrecognized width:%s"), s);
509 string_list_clear(&params, 0);
510 return -1;
512 } else if (!strtoul_ui(s, 10, &width))
514 else if ((position = parse_align_position(s)) >= 0)
515 align->position = position;
516 else {
517 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
518 string_list_clear(&params, 0);
519 return -1;
523 if (width == ~0U) {
524 string_list_clear(&params, 0);
525 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
527 align->width = width;
528 string_list_clear(&params, 0);
529 return 0;
532 static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
533 const char *arg, struct strbuf *err)
535 if (!arg) {
536 atom->u.if_then_else.cmp_status = COMPARE_NONE;
537 return 0;
538 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
539 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
540 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
541 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
542 } else
543 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
544 return 0;
547 static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
548 const char *arg, struct strbuf *unused_err)
550 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
551 return 0;
554 static struct {
555 const char *name;
556 info_source source;
557 cmp_type cmp_type;
558 int (*parser)(const struct ref_format *format, struct used_atom *atom,
559 const char *arg, struct strbuf *err);
560 } valid_atom[] = {
561 [ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
562 [ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
563 [ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
564 [ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },
565 [ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },
566 [ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
567 [ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },
568 [ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },
569 [ATOM_OBJECT] = { "object", SOURCE_OBJ },
570 [ATOM_TYPE] = { "type", SOURCE_OBJ },
571 [ATOM_TAG] = { "tag", SOURCE_OBJ },
572 [ATOM_AUTHOR] = { "author", SOURCE_OBJ },
573 [ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ },
574 [ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
575 [ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },
576 [ATOM_COMMITTER] = { "committer", SOURCE_OBJ },
577 [ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ },
578 [ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
579 [ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },
580 [ATOM_TAGGER] = { "tagger", SOURCE_OBJ },
581 [ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ },
582 [ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },
583 [ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },
584 [ATOM_CREATOR] = { "creator", SOURCE_OBJ },
585 [ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },
586 [ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
587 [ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
588 [ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
589 [ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
590 [ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
591 [ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
592 [ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
593 [ATOM_FLAG] = { "flag", SOURCE_NONE },
594 [ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
595 [ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
596 [ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },
597 [ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
598 [ATOM_END] = { "end", SOURCE_NONE },
599 [ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
600 [ATOM_THEN] = { "then", SOURCE_NONE },
601 [ATOM_ELSE] = { "else", SOURCE_NONE },
603 * Please update $__git_ref_fieldlist in git-completion.bash
604 * when you add new atoms
608 #define REF_FORMATTING_STATE_INIT { 0, NULL }
610 struct ref_formatting_stack {
611 struct ref_formatting_stack *prev;
612 struct strbuf output;
613 void (*at_end)(struct ref_formatting_stack **stack);
614 void *at_end_data;
617 struct ref_formatting_state {
618 int quote_style;
619 struct ref_formatting_stack *stack;
622 struct atom_value {
623 const char *s;
624 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
625 struct strbuf *err);
626 uintmax_t value; /* used for sorting when not FIELD_STR */
627 struct used_atom *atom;
631 * Used to parse format string and sort specifiers
633 static int parse_ref_filter_atom(const struct ref_format *format,
634 const char *atom, const char *ep,
635 struct strbuf *err)
637 const char *sp;
638 const char *arg;
639 int i, at, atom_len;
641 sp = atom;
642 if (*sp == '*' && sp < ep)
643 sp++; /* deref */
644 if (ep <= sp)
645 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
646 (int)(ep-atom), atom);
648 /* Do we have the atom already used elsewhere? */
649 for (i = 0; i < used_atom_cnt; i++) {
650 int len = strlen(used_atom[i].name);
651 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
652 return i;
656 * If the atom name has a colon, strip it and everything after
657 * it off - it specifies the format for this entry, and
658 * shouldn't be used for checking against the valid_atom
659 * table.
661 arg = memchr(sp, ':', ep - sp);
662 atom_len = (arg ? arg : ep) - sp;
664 /* Is the atom a valid one? */
665 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
666 int len = strlen(valid_atom[i].name);
667 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
668 break;
671 if (ARRAY_SIZE(valid_atom) <= i)
672 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
673 (int)(ep-atom), atom);
674 if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())
675 return strbuf_addf_ret(err, -1,
676 _("not a git repository, but the field '%.*s' requires access to object data"),
677 (int)(ep-atom), atom);
679 /* Add it in, including the deref prefix */
680 at = used_atom_cnt;
681 used_atom_cnt++;
682 REALLOC_ARRAY(used_atom, used_atom_cnt);
683 used_atom[at].atom_type = i;
684 used_atom[at].name = xmemdupz(atom, ep - atom);
685 used_atom[at].type = valid_atom[i].cmp_type;
686 used_atom[at].source = valid_atom[i].source;
687 if (used_atom[at].source == SOURCE_OBJ) {
688 if (*atom == '*')
689 oi_deref.info.contentp = &oi_deref.content;
690 else
691 oi.info.contentp = &oi.content;
693 if (arg) {
694 arg = used_atom[at].name + (arg - atom) + 1;
695 if (!*arg) {
697 * Treat empty sub-arguments list as NULL (i.e.,
698 * "%(atom:)" is equivalent to "%(atom)").
700 arg = NULL;
703 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
704 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
705 return -1;
706 if (*atom == '*')
707 need_tagged = 1;
708 if (i == ATOM_SYMREF)
709 need_symref = 1;
710 return at;
713 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
715 switch (quote_style) {
716 case QUOTE_NONE:
717 strbuf_addstr(s, str);
718 break;
719 case QUOTE_SHELL:
720 sq_quote_buf(s, str);
721 break;
722 case QUOTE_PERL:
723 perl_quote_buf(s, str);
724 break;
725 case QUOTE_PYTHON:
726 python_quote_buf(s, str);
727 break;
728 case QUOTE_TCL:
729 tcl_quote_buf(s, str);
730 break;
734 static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
735 struct strbuf *unused_err)
738 * Quote formatting is only done when the stack has a single
739 * element. Otherwise quote formatting is done on the
740 * element's entire output strbuf when the %(end) atom is
741 * encountered.
743 if (!state->stack->prev)
744 quote_formatting(&state->stack->output, v->s, state->quote_style);
745 else
746 strbuf_addstr(&state->stack->output, v->s);
747 return 0;
750 static void push_stack_element(struct ref_formatting_stack **stack)
752 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
754 strbuf_init(&s->output, 0);
755 s->prev = *stack;
756 *stack = s;
759 static void pop_stack_element(struct ref_formatting_stack **stack)
761 struct ref_formatting_stack *current = *stack;
762 struct ref_formatting_stack *prev = current->prev;
764 if (prev)
765 strbuf_addbuf(&prev->output, &current->output);
766 strbuf_release(&current->output);
767 free(current);
768 *stack = prev;
771 static void end_align_handler(struct ref_formatting_stack **stack)
773 struct ref_formatting_stack *cur = *stack;
774 struct align *align = (struct align *)cur->at_end_data;
775 struct strbuf s = STRBUF_INIT;
777 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
778 strbuf_swap(&cur->output, &s);
779 strbuf_release(&s);
782 static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
783 struct strbuf *unused_err)
785 struct ref_formatting_stack *new_stack;
787 push_stack_element(&state->stack);
788 new_stack = state->stack;
789 new_stack->at_end = end_align_handler;
790 new_stack->at_end_data = &atomv->atom->u.align;
791 return 0;
794 static void if_then_else_handler(struct ref_formatting_stack **stack)
796 struct ref_formatting_stack *cur = *stack;
797 struct ref_formatting_stack *prev = cur->prev;
798 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
800 if (!if_then_else->then_atom_seen)
801 die(_("format: %%(if) atom used without a %%(then) atom"));
803 if (if_then_else->else_atom_seen) {
805 * There is an %(else) atom: we need to drop one state from the
806 * stack, either the %(else) branch if the condition is satisfied, or
807 * the %(then) branch if it isn't.
809 if (if_then_else->condition_satisfied) {
810 strbuf_reset(&cur->output);
811 pop_stack_element(&cur);
812 } else {
813 strbuf_swap(&cur->output, &prev->output);
814 strbuf_reset(&cur->output);
815 pop_stack_element(&cur);
817 } else if (!if_then_else->condition_satisfied) {
819 * No %(else) atom: just drop the %(then) branch if the
820 * condition is not satisfied.
822 strbuf_reset(&cur->output);
825 *stack = cur;
826 free(if_then_else);
829 static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
830 struct strbuf *unused_err)
832 struct ref_formatting_stack *new_stack;
833 struct if_then_else *if_then_else = xcalloc(1,
834 sizeof(struct if_then_else));
836 if_then_else->str = atomv->atom->u.if_then_else.str;
837 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
839 push_stack_element(&state->stack);
840 new_stack = state->stack;
841 new_stack->at_end = if_then_else_handler;
842 new_stack->at_end_data = if_then_else;
843 return 0;
846 static int is_empty(const char *s)
848 while (*s != '\0') {
849 if (!isspace(*s))
850 return 0;
851 s++;
853 return 1;
856 static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
857 struct strbuf *err)
859 struct ref_formatting_stack *cur = state->stack;
860 struct if_then_else *if_then_else = NULL;
862 if (cur->at_end == if_then_else_handler)
863 if_then_else = (struct if_then_else *)cur->at_end_data;
864 if (!if_then_else)
865 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
866 if (if_then_else->then_atom_seen)
867 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
868 if (if_then_else->else_atom_seen)
869 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
870 if_then_else->then_atom_seen = 1;
872 * If the 'equals' or 'notequals' attribute is used then
873 * perform the required comparison. If not, only non-empty
874 * strings satisfy the 'if' condition.
876 if (if_then_else->cmp_status == COMPARE_EQUAL) {
877 if (!strcmp(if_then_else->str, cur->output.buf))
878 if_then_else->condition_satisfied = 1;
879 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
880 if (strcmp(if_then_else->str, cur->output.buf))
881 if_then_else->condition_satisfied = 1;
882 } else if (cur->output.len && !is_empty(cur->output.buf))
883 if_then_else->condition_satisfied = 1;
884 strbuf_reset(&cur->output);
885 return 0;
888 static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
889 struct strbuf *err)
891 struct ref_formatting_stack *prev = state->stack;
892 struct if_then_else *if_then_else = NULL;
894 if (prev->at_end == if_then_else_handler)
895 if_then_else = (struct if_then_else *)prev->at_end_data;
896 if (!if_then_else)
897 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
898 if (!if_then_else->then_atom_seen)
899 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
900 if (if_then_else->else_atom_seen)
901 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
902 if_then_else->else_atom_seen = 1;
903 push_stack_element(&state->stack);
904 state->stack->at_end_data = prev->at_end_data;
905 state->stack->at_end = prev->at_end;
906 return 0;
909 static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
910 struct strbuf *err)
912 struct ref_formatting_stack *current = state->stack;
913 struct strbuf s = STRBUF_INIT;
915 if (!current->at_end)
916 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
917 current->at_end(&state->stack);
919 /* Stack may have been popped within at_end(), hence reset the current pointer */
920 current = state->stack;
923 * Perform quote formatting when the stack element is that of
924 * a supporting atom. If nested then perform quote formatting
925 * only on the topmost supporting atom.
927 if (!current->prev->prev) {
928 quote_formatting(&s, current->output.buf, state->quote_style);
929 strbuf_swap(&current->output, &s);
931 strbuf_release(&s);
932 pop_stack_element(&state->stack);
933 return 0;
937 * In a format string, find the next occurrence of %(atom).
939 static const char *find_next(const char *cp)
941 while (*cp) {
942 if (*cp == '%') {
944 * %( is the start of an atom;
945 * %% is a quoted per-cent.
947 if (cp[1] == '(')
948 return cp;
949 else if (cp[1] == '%')
950 cp++; /* skip over two % */
951 /* otherwise this is a singleton, literal % */
953 cp++;
955 return NULL;
959 * Make sure the format string is well formed, and parse out
960 * the used atoms.
962 int verify_ref_format(struct ref_format *format)
964 const char *cp, *sp;
966 format->need_color_reset_at_eol = 0;
967 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
968 struct strbuf err = STRBUF_INIT;
969 const char *color, *ep = strchr(sp, ')');
970 int at;
972 if (!ep)
973 return error(_("malformed format string %s"), sp);
974 /* sp points at "%(" and ep points at the closing ")" */
975 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
976 if (at < 0)
977 die("%s", err.buf);
978 cp = ep + 1;
980 if (skip_prefix(used_atom[at].name, "color:", &color))
981 format->need_color_reset_at_eol = !!strcmp(color, "reset");
982 strbuf_release(&err);
984 if (format->need_color_reset_at_eol && !want_color(format->use_color))
985 format->need_color_reset_at_eol = 0;
986 return 0;
989 static const char *do_grab_oid(const char *field, const struct object_id *oid,
990 struct used_atom *atom)
992 switch (atom->u.oid.option) {
993 case O_FULL:
994 return oid_to_hex(oid);
995 case O_LENGTH:
996 return find_unique_abbrev(oid, atom->u.oid.length);
997 case O_SHORT:
998 return find_unique_abbrev(oid, DEFAULT_ABBREV);
999 default:
1000 BUG("unknown %%(%s) option", field);
1004 static int grab_oid(const char *name, const char *field, const struct object_id *oid,
1005 struct atom_value *v, struct used_atom *atom)
1007 if (starts_with(name, field)) {
1008 v->s = xstrdup(do_grab_oid(field, oid, atom));
1009 return 1;
1011 return 0;
1014 /* See grab_values */
1015 static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
1017 int i;
1019 for (i = 0; i < used_atom_cnt; i++) {
1020 const char *name = used_atom[i].name;
1021 enum atom_type atom_type = used_atom[i].atom_type;
1022 struct atom_value *v = &val[i];
1023 if (!!deref != (*name == '*'))
1024 continue;
1025 if (deref)
1026 name++;
1027 if (atom_type == ATOM_OBJECTTYPE)
1028 v->s = xstrdup(type_name(oi->type));
1029 else if (atom_type == ATOM_OBJECTSIZE) {
1030 if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {
1031 v->value = oi->disk_size;
1032 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);
1033 } else if (used_atom[i].u.objectsize.option == O_SIZE) {
1034 v->value = oi->size;
1035 v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);
1037 } else if (atom_type == ATOM_DELTABASE)
1038 v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));
1039 else if (atom_type == ATOM_OBJECTNAME && deref)
1040 grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);
1044 /* See grab_values */
1045 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)
1047 int i;
1048 struct tag *tag = (struct tag *) obj;
1050 for (i = 0; i < used_atom_cnt; i++) {
1051 const char *name = used_atom[i].name;
1052 enum atom_type atom_type = used_atom[i].atom_type;
1053 struct atom_value *v = &val[i];
1054 if (!!deref != (*name == '*'))
1055 continue;
1056 if (deref)
1057 name++;
1058 if (atom_type == ATOM_TAG)
1059 v->s = xstrdup(tag->tag);
1060 else if (atom_type == ATOM_TYPE && tag->tagged)
1061 v->s = xstrdup(type_name(tag->tagged->type));
1062 else if (atom_type == ATOM_OBJECT && tag->tagged)
1063 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
1067 /* See grab_values */
1068 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)
1070 int i;
1071 struct commit *commit = (struct commit *) obj;
1073 for (i = 0; i < used_atom_cnt; i++) {
1074 const char *name = used_atom[i].name;
1075 enum atom_type atom_type = used_atom[i].atom_type;
1076 struct atom_value *v = &val[i];
1077 if (!!deref != (*name == '*'))
1078 continue;
1079 if (deref)
1080 name++;
1081 if (atom_type == ATOM_TREE &&
1082 grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))
1083 continue;
1084 if (atom_type == ATOM_NUMPARENT) {
1085 v->value = commit_list_count(commit->parents);
1086 v->s = xstrfmt("%lu", (unsigned long)v->value);
1088 else if (atom_type == ATOM_PARENT) {
1089 struct commit_list *parents;
1090 struct strbuf s = STRBUF_INIT;
1091 for (parents = commit->parents; parents; parents = parents->next) {
1092 struct object_id *oid = &parents->item->object.oid;
1093 if (parents != commit->parents)
1094 strbuf_addch(&s, ' ');
1095 strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));
1097 v->s = strbuf_detach(&s, NULL);
1102 static const char *find_wholine(const char *who, int wholen, const char *buf)
1104 const char *eol;
1105 while (*buf) {
1106 if (!strncmp(buf, who, wholen) &&
1107 buf[wholen] == ' ')
1108 return buf + wholen + 1;
1109 eol = strchr(buf, '\n');
1110 if (!eol)
1111 return "";
1112 eol++;
1113 if (*eol == '\n')
1114 return ""; /* end of header */
1115 buf = eol;
1117 return "";
1120 static const char *copy_line(const char *buf)
1122 const char *eol = strchrnul(buf, '\n');
1123 return xmemdupz(buf, eol - buf);
1126 static const char *copy_name(const char *buf)
1128 const char *cp;
1129 for (cp = buf; *cp && *cp != '\n'; cp++) {
1130 if (!strncmp(cp, " <", 2))
1131 return xmemdupz(buf, cp - buf);
1133 return xstrdup("");
1136 static const char *copy_email(const char *buf, struct used_atom *atom)
1138 const char *email = strchr(buf, '<');
1139 const char *eoemail;
1140 if (!email)
1141 return xstrdup("");
1142 switch (atom->u.email_option.option) {
1143 case EO_RAW:
1144 eoemail = strchr(email, '>');
1145 if (eoemail)
1146 eoemail++;
1147 break;
1148 case EO_TRIM:
1149 email++;
1150 eoemail = strchr(email, '>');
1151 break;
1152 case EO_LOCALPART:
1153 email++;
1154 eoemail = strchr(email, '@');
1155 if (!eoemail)
1156 eoemail = strchr(email, '>');
1157 break;
1158 default:
1159 BUG("unknown email option");
1162 if (!eoemail)
1163 return xstrdup("");
1164 return xmemdupz(email, eoemail - email);
1167 static char *copy_subject(const char *buf, unsigned long len)
1169 struct strbuf sb = STRBUF_INIT;
1170 int i;
1172 for (i = 0; i < len; i++) {
1173 if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')
1174 continue; /* ignore CR in CRLF */
1176 if (buf[i] == '\n')
1177 strbuf_addch(&sb, ' ');
1178 else
1179 strbuf_addch(&sb, buf[i]);
1181 return strbuf_detach(&sb, NULL);
1184 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1186 const char *eoemail = strstr(buf, "> ");
1187 char *zone;
1188 timestamp_t timestamp;
1189 long tz;
1190 struct date_mode date_mode = { DATE_NORMAL };
1191 const char *formatp;
1194 * We got here because atomname ends in "date" or "date<something>";
1195 * it's not possible that <something> is not ":<format>" because
1196 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1197 * ":" means no format is specified, and use the default.
1199 formatp = strchr(atomname, ':');
1200 if (formatp != NULL) {
1201 formatp++;
1202 parse_date_format(formatp, &date_mode);
1205 if (!eoemail)
1206 goto bad;
1207 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
1208 if (timestamp == TIME_MAX)
1209 goto bad;
1210 tz = strtol(zone, NULL, 10);
1211 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1212 goto bad;
1213 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
1214 v->value = timestamp;
1215 return;
1216 bad:
1217 v->s = xstrdup("");
1218 v->value = 0;
1221 /* See grab_values */
1222 static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)
1224 int i;
1225 int wholen = strlen(who);
1226 const char *wholine = NULL;
1228 for (i = 0; i < used_atom_cnt; i++) {
1229 const char *name = used_atom[i].name;
1230 struct atom_value *v = &val[i];
1231 if (!!deref != (*name == '*'))
1232 continue;
1233 if (deref)
1234 name++;
1235 if (strncmp(who, name, wholen))
1236 continue;
1237 if (name[wholen] != 0 &&
1238 strcmp(name + wholen, "name") &&
1239 !starts_with(name + wholen, "email") &&
1240 !starts_with(name + wholen, "date"))
1241 continue;
1242 if (!wholine)
1243 wholine = find_wholine(who, wholen, buf);
1244 if (!wholine)
1245 return; /* no point looking for it */
1246 if (name[wholen] == 0)
1247 v->s = copy_line(wholine);
1248 else if (!strcmp(name + wholen, "name"))
1249 v->s = copy_name(wholine);
1250 else if (starts_with(name + wholen, "email"))
1251 v->s = copy_email(wholine, &used_atom[i]);
1252 else if (starts_with(name + wholen, "date"))
1253 grab_date(wholine, v, name);
1257 * For a tag or a commit object, if "creator" or "creatordate" is
1258 * requested, do something special.
1260 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1261 return; /* "author" for commit object is not wanted */
1262 if (!wholine)
1263 wholine = find_wholine(who, wholen, buf);
1264 if (!wholine)
1265 return;
1266 for (i = 0; i < used_atom_cnt; i++) {
1267 const char *name = used_atom[i].name;
1268 enum atom_type atom_type = used_atom[i].atom_type;
1269 struct atom_value *v = &val[i];
1270 if (!!deref != (*name == '*'))
1271 continue;
1272 if (deref)
1273 name++;
1275 if (atom_type == ATOM_CREATORDATE)
1276 grab_date(wholine, v, name);
1277 else if (atom_type == ATOM_CREATOR)
1278 v->s = copy_line(wholine);
1282 static void find_subpos(const char *buf,
1283 const char **sub, size_t *sublen,
1284 const char **body, size_t *bodylen,
1285 size_t *nonsiglen,
1286 const char **sig, size_t *siglen)
1288 struct strbuf payload = STRBUF_INIT;
1289 struct strbuf signature = STRBUF_INIT;
1290 const char *eol;
1291 const char *end = buf + strlen(buf);
1292 const char *sigstart;
1294 /* parse signature first; we might not even have a subject line */
1295 parse_signature(buf, end - buf, &payload, &signature);
1297 /* skip past header until we hit empty line */
1298 while (*buf && *buf != '\n') {
1299 eol = strchrnul(buf, '\n');
1300 if (*eol)
1301 eol++;
1302 buf = eol;
1304 /* skip any empty lines */
1305 while (*buf == '\n')
1306 buf++;
1307 *sig = strbuf_detach(&signature, siglen);
1308 sigstart = buf + parse_signed_buffer(buf, strlen(buf));
1310 /* subject is first non-empty line */
1311 *sub = buf;
1312 /* subject goes to first empty line before signature begins */
1313 if ((eol = strstr(*sub, "\n\n"))) {
1314 eol = eol < sigstart ? eol : sigstart;
1315 /* check if message uses CRLF */
1316 } else if (! (eol = strstr(*sub, "\r\n\r\n"))) {
1317 /* treat whole message as subject */
1318 eol = strrchr(*sub, '\0');
1320 buf = eol;
1321 *sublen = buf - *sub;
1322 /* drop trailing newline, if present */
1323 while (*sublen && ((*sub)[*sublen - 1] == '\n' ||
1324 (*sub)[*sublen - 1] == '\r'))
1325 *sublen -= 1;
1327 /* skip any empty lines */
1328 while (*buf == '\n' || *buf == '\r')
1329 buf++;
1330 *body = buf;
1331 *bodylen = strlen(buf);
1332 *nonsiglen = sigstart - buf;
1336 * If 'lines' is greater than 0, append that many lines from the given
1337 * 'buf' of length 'size' to the given strbuf.
1339 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1341 int i;
1342 const char *sp, *eol;
1343 size_t len;
1345 sp = buf;
1347 for (i = 0; i < lines && sp < buf + size; i++) {
1348 if (i)
1349 strbuf_addstr(out, "\n ");
1350 eol = memchr(sp, '\n', size - (sp - buf));
1351 len = eol ? eol - sp : size - (sp - buf);
1352 strbuf_add(out, sp, len);
1353 if (!eol)
1354 break;
1355 sp = eol + 1;
1359 /* See grab_values */
1360 static void grab_sub_body_contents(struct atom_value *val, int deref, void *buf)
1362 int i;
1363 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1364 size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1366 for (i = 0; i < used_atom_cnt; i++) {
1367 struct used_atom *atom = &used_atom[i];
1368 const char *name = atom->name;
1369 struct atom_value *v = &val[i];
1371 if (!!deref != (*name == '*'))
1372 continue;
1373 if (deref)
1374 name++;
1375 if (strcmp(name, "body") &&
1376 !starts_with(name, "subject") &&
1377 !starts_with(name, "trailers") &&
1378 !starts_with(name, "contents"))
1379 continue;
1380 if (!subpos)
1381 find_subpos(buf,
1382 &subpos, &sublen,
1383 &bodypos, &bodylen, &nonsiglen,
1384 &sigpos, &siglen);
1386 if (atom->u.contents.option == C_SUB)
1387 v->s = copy_subject(subpos, sublen);
1388 else if (atom->u.contents.option == C_SUB_SANITIZE) {
1389 struct strbuf sb = STRBUF_INIT;
1390 format_sanitized_subject(&sb, subpos, sublen);
1391 v->s = strbuf_detach(&sb, NULL);
1392 } else if (atom->u.contents.option == C_BODY_DEP)
1393 v->s = xmemdupz(bodypos, bodylen);
1394 else if (atom->u.contents.option == C_LENGTH)
1395 v->s = xstrfmt("%"PRIuMAX, (uintmax_t)strlen(subpos));
1396 else if (atom->u.contents.option == C_BODY)
1397 v->s = xmemdupz(bodypos, nonsiglen);
1398 else if (atom->u.contents.option == C_SIG)
1399 v->s = xmemdupz(sigpos, siglen);
1400 else if (atom->u.contents.option == C_LINES) {
1401 struct strbuf s = STRBUF_INIT;
1402 const char *contents_end = bodypos + nonsiglen;
1404 /* Size is the length of the message after removing the signature */
1405 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1406 v->s = strbuf_detach(&s, NULL);
1407 } else if (atom->u.contents.option == C_TRAILERS) {
1408 struct strbuf s = STRBUF_INIT;
1410 /* Format the trailer info according to the trailer_opts given */
1411 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1413 v->s = strbuf_detach(&s, NULL);
1414 } else if (atom->u.contents.option == C_BARE)
1415 v->s = xstrdup(subpos);
1418 free((void *)sigpos);
1422 * We want to have empty print-string for field requests
1423 * that do not apply (e.g. "authordate" for a tag object)
1425 static void fill_missing_values(struct atom_value *val)
1427 int i;
1428 for (i = 0; i < used_atom_cnt; i++) {
1429 struct atom_value *v = &val[i];
1430 if (v->s == NULL)
1431 v->s = xstrdup("");
1436 * val is a list of atom_value to hold returned values. Extract
1437 * the values for atoms in used_atom array out of (obj, buf, sz).
1438 * when deref is false, (obj, buf, sz) is the object that is
1439 * pointed at by the ref itself; otherwise it is the object the
1440 * ref (which is a tag) refers to.
1442 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf)
1444 switch (obj->type) {
1445 case OBJ_TAG:
1446 grab_tag_values(val, deref, obj);
1447 grab_sub_body_contents(val, deref, buf);
1448 grab_person("tagger", val, deref, buf);
1449 break;
1450 case OBJ_COMMIT:
1451 grab_commit_values(val, deref, obj);
1452 grab_sub_body_contents(val, deref, buf);
1453 grab_person("author", val, deref, buf);
1454 grab_person("committer", val, deref, buf);
1455 break;
1456 case OBJ_TREE:
1457 /* grab_tree_values(val, deref, obj, buf, sz); */
1458 break;
1459 case OBJ_BLOB:
1460 /* grab_blob_values(val, deref, obj, buf, sz); */
1461 break;
1462 default:
1463 die("Eh? Object of type %d?", obj->type);
1467 static inline char *copy_advance(char *dst, const char *src)
1469 while (*src)
1470 *dst++ = *src++;
1471 return dst;
1474 static const char *lstrip_ref_components(const char *refname, int len)
1476 long remaining = len;
1477 const char *start = xstrdup(refname);
1478 const char *to_free = start;
1480 if (len < 0) {
1481 int i;
1482 const char *p = refname;
1484 /* Find total no of '/' separated path-components */
1485 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1488 * The number of components we need to strip is now
1489 * the total minus the components to be left (Plus one
1490 * because we count the number of '/', but the number
1491 * of components is one more than the no of '/').
1493 remaining = i + len + 1;
1496 while (remaining > 0) {
1497 switch (*start++) {
1498 case '\0':
1499 free((char *)to_free);
1500 return xstrdup("");
1501 case '/':
1502 remaining--;
1503 break;
1507 start = xstrdup(start);
1508 free((char *)to_free);
1509 return start;
1512 static const char *rstrip_ref_components(const char *refname, int len)
1514 long remaining = len;
1515 const char *start = xstrdup(refname);
1516 const char *to_free = start;
1518 if (len < 0) {
1519 int i;
1520 const char *p = refname;
1522 /* Find total no of '/' separated path-components */
1523 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1526 * The number of components we need to strip is now
1527 * the total minus the components to be left (Plus one
1528 * because we count the number of '/', but the number
1529 * of components is one more than the no of '/').
1531 remaining = i + len + 1;
1534 while (remaining-- > 0) {
1535 char *p = strrchr(start, '/');
1536 if (p == NULL) {
1537 free((char *)to_free);
1538 return xstrdup("");
1539 } else
1540 p[0] = '\0';
1542 return start;
1545 static const char *show_ref(struct refname_atom *atom, const char *refname)
1547 if (atom->option == R_SHORT)
1548 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1549 else if (atom->option == R_LSTRIP)
1550 return lstrip_ref_components(refname, atom->lstrip);
1551 else if (atom->option == R_RSTRIP)
1552 return rstrip_ref_components(refname, atom->rstrip);
1553 else
1554 return xstrdup(refname);
1557 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1558 struct branch *branch, const char **s)
1560 int num_ours, num_theirs;
1561 if (atom->u.remote_ref.option == RR_REF)
1562 *s = show_ref(&atom->u.remote_ref.refname, refname);
1563 else if (atom->u.remote_ref.option == RR_TRACK) {
1564 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1565 NULL, atom->u.remote_ref.push,
1566 AHEAD_BEHIND_FULL) < 0) {
1567 *s = xstrdup(msgs.gone);
1568 } else if (!num_ours && !num_theirs)
1569 *s = xstrdup("");
1570 else if (!num_ours)
1571 *s = xstrfmt(msgs.behind, num_theirs);
1572 else if (!num_theirs)
1573 *s = xstrfmt(msgs.ahead, num_ours);
1574 else
1575 *s = xstrfmt(msgs.ahead_behind,
1576 num_ours, num_theirs);
1577 if (!atom->u.remote_ref.nobracket && *s[0]) {
1578 const char *to_free = *s;
1579 *s = xstrfmt("[%s]", *s);
1580 free((void *)to_free);
1582 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1583 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1584 NULL, atom->u.remote_ref.push,
1585 AHEAD_BEHIND_FULL) < 0) {
1586 *s = xstrdup("");
1587 return;
1589 if (!num_ours && !num_theirs)
1590 *s = xstrdup("=");
1591 else if (!num_ours)
1592 *s = xstrdup("<");
1593 else if (!num_theirs)
1594 *s = xstrdup(">");
1595 else
1596 *s = xstrdup("<>");
1597 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1598 int explicit;
1599 const char *remote = atom->u.remote_ref.push ?
1600 pushremote_for_branch(branch, &explicit) :
1601 remote_for_branch(branch, &explicit);
1602 *s = xstrdup(explicit ? remote : "");
1603 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1604 const char *merge;
1606 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);
1607 *s = xstrdup(merge ? merge : "");
1608 } else
1609 BUG("unhandled RR_* enum");
1612 char *get_head_description(void)
1614 struct strbuf desc = STRBUF_INIT;
1615 struct wt_status_state state;
1616 memset(&state, 0, sizeof(state));
1617 wt_status_get_state(the_repository, &state, 1);
1618 if (state.rebase_in_progress ||
1619 state.rebase_interactive_in_progress) {
1620 if (state.branch)
1621 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1622 state.branch);
1623 else
1624 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1625 state.detached_from);
1626 } else if (state.bisect_in_progress)
1627 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1628 state.branch);
1629 else if (state.detached_from) {
1630 if (state.detached_at)
1631 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1632 state.detached_from);
1633 else
1634 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1635 state.detached_from);
1636 } else
1637 strbuf_addstr(&desc, _("(no branch)"));
1639 return strbuf_detach(&desc, NULL);
1642 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1644 if (!ref->symref)
1645 return xstrdup("");
1646 else
1647 return show_ref(&atom->u.refname, ref->symref);
1650 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1652 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1653 return get_head_description();
1654 return show_ref(&atom->u.refname, ref->refname);
1657 static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1658 struct expand_data *oi, struct strbuf *err)
1660 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1661 int eaten = 1;
1662 if (oi->info.contentp) {
1663 /* We need to know that to use parse_object_buffer properly */
1664 oi->info.sizep = &oi->size;
1665 oi->info.typep = &oi->type;
1667 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1668 OBJECT_INFO_LOOKUP_REPLACE))
1669 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1670 oid_to_hex(&oi->oid), ref->refname);
1671 if (oi->info.disk_sizep && oi->disk_size < 0)
1672 BUG("Object size is less than zero.");
1674 if (oi->info.contentp) {
1675 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1676 if (!*obj) {
1677 if (!eaten)
1678 free(oi->content);
1679 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1680 oid_to_hex(&oi->oid), ref->refname);
1682 grab_values(ref->value, deref, *obj, oi->content);
1685 grab_common_values(ref->value, deref, oi);
1686 if (!eaten)
1687 free(oi->content);
1688 return 0;
1691 static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)
1693 int i;
1695 for (i = 0; worktrees[i]; i++) {
1696 if (worktrees[i]->head_ref) {
1697 struct ref_to_worktree_entry *entry;
1698 entry = xmalloc(sizeof(*entry));
1699 entry->wt = worktrees[i];
1700 hashmap_entry_init(&entry->ent,
1701 strhash(worktrees[i]->head_ref));
1703 hashmap_add(map, &entry->ent);
1708 static void lazy_init_worktree_map(void)
1710 if (ref_to_worktree_map.worktrees)
1711 return;
1713 ref_to_worktree_map.worktrees = get_worktrees();
1714 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1715 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1718 static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1720 struct hashmap_entry entry, *e;
1721 struct ref_to_worktree_entry *lookup_result;
1723 lazy_init_worktree_map();
1725 hashmap_entry_init(&entry, strhash(ref->refname));
1726 e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1728 if (!e)
1729 return xstrdup("");
1731 lookup_result = container_of(e, struct ref_to_worktree_entry, ent);
1733 return xstrdup(lookup_result->wt->path);
1737 * Parse the object referred by ref, and grab needed value.
1739 static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1741 struct object *obj;
1742 int i;
1743 struct object_info empty = OBJECT_INFO_INIT;
1745 CALLOC_ARRAY(ref->value, used_atom_cnt);
1747 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1748 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1749 NULL, NULL);
1750 if (!ref->symref)
1751 ref->symref = xstrdup("");
1754 /* Fill in specials first */
1755 for (i = 0; i < used_atom_cnt; i++) {
1756 struct used_atom *atom = &used_atom[i];
1757 enum atom_type atom_type = atom->atom_type;
1758 const char *name = used_atom[i].name;
1759 struct atom_value *v = &ref->value[i];
1760 int deref = 0;
1761 const char *refname;
1762 struct branch *branch = NULL;
1764 v->handler = append_atom;
1765 v->atom = atom;
1767 if (*name == '*') {
1768 deref = 1;
1769 name++;
1772 if (atom_type == ATOM_REFNAME)
1773 refname = get_refname(atom, ref);
1774 else if (atom_type == ATOM_WORKTREEPATH) {
1775 if (ref->kind == FILTER_REFS_BRANCHES)
1776 v->s = get_worktree_path(atom, ref);
1777 else
1778 v->s = xstrdup("");
1779 continue;
1781 else if (atom_type == ATOM_SYMREF)
1782 refname = get_symref(atom, ref);
1783 else if (atom_type == ATOM_UPSTREAM) {
1784 const char *branch_name;
1785 /* only local branches may have an upstream */
1786 if (!skip_prefix(ref->refname, "refs/heads/",
1787 &branch_name)) {
1788 v->s = xstrdup("");
1789 continue;
1791 branch = branch_get(branch_name);
1793 refname = branch_get_upstream(branch, NULL);
1794 if (refname)
1795 fill_remote_ref_details(atom, refname, branch, &v->s);
1796 else
1797 v->s = xstrdup("");
1798 continue;
1799 } else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {
1800 const char *branch_name;
1801 v->s = xstrdup("");
1802 if (!skip_prefix(ref->refname, "refs/heads/",
1803 &branch_name))
1804 continue;
1805 branch = branch_get(branch_name);
1807 if (atom->u.remote_ref.push_remote)
1808 refname = NULL;
1809 else {
1810 refname = branch_get_push(branch, NULL);
1811 if (!refname)
1812 continue;
1814 /* We will definitely re-init v->s on the next line. */
1815 free((char *)v->s);
1816 fill_remote_ref_details(atom, refname, branch, &v->s);
1817 continue;
1818 } else if (atom_type == ATOM_COLOR) {
1819 v->s = xstrdup(atom->u.color);
1820 continue;
1821 } else if (atom_type == ATOM_FLAG) {
1822 char buf[256], *cp = buf;
1823 if (ref->flag & REF_ISSYMREF)
1824 cp = copy_advance(cp, ",symref");
1825 if (ref->flag & REF_ISPACKED)
1826 cp = copy_advance(cp, ",packed");
1827 if (cp == buf)
1828 v->s = xstrdup("");
1829 else {
1830 *cp = '\0';
1831 v->s = xstrdup(buf + 1);
1833 continue;
1834 } else if (!deref && atom_type == ATOM_OBJECTNAME &&
1835 grab_oid(name, "objectname", &ref->objectname, v, atom)) {
1836 continue;
1837 } else if (atom_type == ATOM_HEAD) {
1838 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1839 v->s = xstrdup("*");
1840 else
1841 v->s = xstrdup(" ");
1842 continue;
1843 } else if (atom_type == ATOM_ALIGN) {
1844 v->handler = align_atom_handler;
1845 v->s = xstrdup("");
1846 continue;
1847 } else if (atom_type == ATOM_END) {
1848 v->handler = end_atom_handler;
1849 v->s = xstrdup("");
1850 continue;
1851 } else if (atom_type == ATOM_IF) {
1852 const char *s;
1853 if (skip_prefix(name, "if:", &s))
1854 v->s = xstrdup(s);
1855 else
1856 v->s = xstrdup("");
1857 v->handler = if_atom_handler;
1858 continue;
1859 } else if (atom_type == ATOM_THEN) {
1860 v->handler = then_atom_handler;
1861 v->s = xstrdup("");
1862 continue;
1863 } else if (atom_type == ATOM_ELSE) {
1864 v->handler = else_atom_handler;
1865 v->s = xstrdup("");
1866 continue;
1867 } else
1868 continue;
1870 if (!deref)
1871 v->s = xstrdup(refname);
1872 else
1873 v->s = xstrfmt("%s^{}", refname);
1874 free((char *)refname);
1877 for (i = 0; i < used_atom_cnt; i++) {
1878 struct atom_value *v = &ref->value[i];
1879 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1880 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1881 oid_to_hex(&ref->objectname), ref->refname);
1884 if (need_tagged)
1885 oi.info.contentp = &oi.content;
1886 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1887 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1888 return 0;
1891 oi.oid = ref->objectname;
1892 if (get_object(ref, 0, &obj, &oi, err))
1893 return -1;
1896 * If there is no atom that wants to know about tagged
1897 * object, we are done.
1899 if (!need_tagged || (obj->type != OBJ_TAG))
1900 return 0;
1903 * If it is a tag object, see if we use a value that derefs
1904 * the object, and if we do grab the object it refers to.
1906 oi_deref.oid = *get_tagged_oid((struct tag *)obj);
1909 * NEEDSWORK: This derefs tag only once, which
1910 * is good to deal with chains of trust, but
1911 * is not consistent with what deref_tag() does
1912 * which peels the onion to the core.
1914 return get_object(ref, 1, &obj, &oi_deref, err);
1918 * Given a ref, return the value for the atom. This lazily gets value
1919 * out of the object by calling populate value.
1921 static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1922 struct atom_value **v, struct strbuf *err)
1924 if (!ref->value) {
1925 if (populate_value(ref, err))
1926 return -1;
1927 fill_missing_values(ref->value);
1929 *v = &ref->value[atom];
1930 return 0;
1934 * Return 1 if the refname matches one of the patterns, otherwise 0.
1935 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1936 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1937 * matches "refs/heads/mas*", too).
1939 static int match_pattern(const struct ref_filter *filter, const char *refname)
1941 const char **patterns = filter->name_patterns;
1942 unsigned flags = 0;
1944 if (filter->ignore_case)
1945 flags |= WM_CASEFOLD;
1948 * When no '--format' option is given we need to skip the prefix
1949 * for matching refs of tags and branches.
1951 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1952 skip_prefix(refname, "refs/heads/", &refname) ||
1953 skip_prefix(refname, "refs/remotes/", &refname) ||
1954 skip_prefix(refname, "refs/", &refname));
1956 for (; *patterns; patterns++) {
1957 if (!wildmatch(*patterns, refname, flags))
1958 return 1;
1960 return 0;
1964 * Return 1 if the refname matches one of the patterns, otherwise 0.
1965 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1966 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1967 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1969 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1971 const char **pattern = filter->name_patterns;
1972 int namelen = strlen(refname);
1973 unsigned flags = WM_PATHNAME;
1975 if (filter->ignore_case)
1976 flags |= WM_CASEFOLD;
1978 for (; *pattern; pattern++) {
1979 const char *p = *pattern;
1980 int plen = strlen(p);
1982 if ((plen <= namelen) &&
1983 !strncmp(refname, p, plen) &&
1984 (refname[plen] == '\0' ||
1985 refname[plen] == '/' ||
1986 p[plen-1] == '/'))
1987 return 1;
1988 if (!wildmatch(p, refname, flags))
1989 return 1;
1991 return 0;
1994 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1995 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1997 if (!*filter->name_patterns)
1998 return 1; /* No pattern always matches */
1999 if (filter->match_as_path)
2000 return match_name_as_path(filter, refname);
2001 return match_pattern(filter, refname);
2005 * This is the same as for_each_fullref_in(), but it tries to iterate
2006 * only over the patterns we'll care about. Note that it _doesn't_ do a full
2007 * pattern match, so the callback still has to match each ref individually.
2009 static int for_each_fullref_in_pattern(struct ref_filter *filter,
2010 each_ref_fn cb,
2011 void *cb_data,
2012 int broken)
2014 if (!filter->match_as_path) {
2016 * in this case, the patterns are applied after
2017 * prefixes like "refs/heads/" etc. are stripped off,
2018 * so we have to look at everything:
2020 return for_each_fullref_in("", cb, cb_data, broken);
2023 if (filter->ignore_case) {
2025 * we can't handle case-insensitive comparisons,
2026 * so just return everything and let the caller
2027 * sort it out.
2029 return for_each_fullref_in("", cb, cb_data, broken);
2032 if (!filter->name_patterns[0]) {
2033 /* no patterns; we have to look at everything */
2034 return for_each_fullref_in("", cb, cb_data, broken);
2037 return for_each_fullref_in_prefixes(NULL, filter->name_patterns,
2038 cb, cb_data, broken);
2042 * Given a ref (oid, refname), check if the ref belongs to the array
2043 * of oids. If the given ref is a tag, check if the given tag points
2044 * at one of the oids in the given oid array.
2045 * NEEDSWORK:
2046 * 1. Only a single level of indirection is obtained, we might want to
2047 * change this to account for multiple levels (e.g. annotated tags
2048 * pointing to annotated tags pointing to a commit.)
2049 * 2. As the refs are cached we might know what refname peels to without
2050 * the need to parse the object via parse_object(). peel_ref() might be a
2051 * more efficient alternative to obtain the pointee.
2053 static const struct object_id *match_points_at(struct oid_array *points_at,
2054 const struct object_id *oid,
2055 const char *refname)
2057 const struct object_id *tagged_oid = NULL;
2058 struct object *obj;
2060 if (oid_array_lookup(points_at, oid) >= 0)
2061 return oid;
2062 obj = parse_object(the_repository, oid);
2063 if (!obj)
2064 die(_("malformed object at '%s'"), refname);
2065 if (obj->type == OBJ_TAG)
2066 tagged_oid = get_tagged_oid((struct tag *)obj);
2067 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
2068 return tagged_oid;
2069 return NULL;
2073 * Allocate space for a new ref_array_item and copy the name and oid to it.
2075 * Callers can then fill in other struct members at their leisure.
2077 static struct ref_array_item *new_ref_array_item(const char *refname,
2078 const struct object_id *oid)
2080 struct ref_array_item *ref;
2082 FLEX_ALLOC_STR(ref, refname, refname);
2083 oidcpy(&ref->objectname, oid);
2085 return ref;
2088 struct ref_array_item *ref_array_push(struct ref_array *array,
2089 const char *refname,
2090 const struct object_id *oid)
2092 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2094 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2095 array->items[array->nr++] = ref;
2097 return ref;
2100 static int ref_kind_from_refname(const char *refname)
2102 unsigned int i;
2104 static struct {
2105 const char *prefix;
2106 unsigned int kind;
2107 } ref_kind[] = {
2108 { "refs/heads/" , FILTER_REFS_BRANCHES },
2109 { "refs/remotes/" , FILTER_REFS_REMOTES },
2110 { "refs/tags/", FILTER_REFS_TAGS}
2113 if (!strcmp(refname, "HEAD"))
2114 return FILTER_REFS_DETACHED_HEAD;
2116 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2117 if (starts_with(refname, ref_kind[i].prefix))
2118 return ref_kind[i].kind;
2121 return FILTER_REFS_OTHERS;
2124 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2126 if (filter->kind == FILTER_REFS_BRANCHES ||
2127 filter->kind == FILTER_REFS_REMOTES ||
2128 filter->kind == FILTER_REFS_TAGS)
2129 return filter->kind;
2130 return ref_kind_from_refname(refname);
2133 struct ref_filter_cbdata {
2134 struct ref_array *array;
2135 struct ref_filter *filter;
2136 struct contains_cache contains_cache;
2137 struct contains_cache no_contains_cache;
2141 * A call-back given to for_each_ref(). Filter refs and keep them for
2142 * later object processing.
2144 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
2146 struct ref_filter_cbdata *ref_cbdata = cb_data;
2147 struct ref_filter *filter = ref_cbdata->filter;
2148 struct ref_array_item *ref;
2149 struct commit *commit = NULL;
2150 unsigned int kind;
2152 if (flag & REF_BAD_NAME) {
2153 warning(_("ignoring ref with broken name %s"), refname);
2154 return 0;
2157 if (flag & REF_ISBROKEN) {
2158 warning(_("ignoring broken ref %s"), refname);
2159 return 0;
2162 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2163 kind = filter_ref_kind(filter, refname);
2164 if (!(kind & filter->kind))
2165 return 0;
2167 if (!filter_pattern_match(filter, refname))
2168 return 0;
2170 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
2171 return 0;
2174 * A merge filter is applied on refs pointing to commits. Hence
2175 * obtain the commit using the 'oid' available and discard all
2176 * non-commits early. The actual filtering is done later.
2178 if (filter->reachable_from || filter->unreachable_from ||
2179 filter->with_commit || filter->no_commit || filter->verbose) {
2180 commit = lookup_commit_reference_gently(the_repository, oid, 1);
2181 if (!commit)
2182 return 0;
2183 /* We perform the filtering for the '--contains' option... */
2184 if (filter->with_commit &&
2185 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2186 return 0;
2187 /* ...or for the `--no-contains' option */
2188 if (filter->no_commit &&
2189 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
2190 return 0;
2194 * We do not open the object yet; sort may only need refname
2195 * to do its job and the resulting list may yet to be pruned
2196 * by maxcount logic.
2198 ref = ref_array_push(ref_cbdata->array, refname, oid);
2199 ref->commit = commit;
2200 ref->flag = flag;
2201 ref->kind = kind;
2203 return 0;
2206 /* Free memory allocated for a ref_array_item */
2207 static void free_array_item(struct ref_array_item *item)
2209 free((char *)item->symref);
2210 if (item->value) {
2211 int i;
2212 for (i = 0; i < used_atom_cnt; i++)
2213 free((char *)item->value[i].s);
2214 free(item->value);
2216 free(item);
2219 /* Free all memory allocated for ref_array */
2220 void ref_array_clear(struct ref_array *array)
2222 int i;
2224 for (i = 0; i < array->nr; i++)
2225 free_array_item(array->items[i]);
2226 FREE_AND_NULL(array->items);
2227 array->nr = array->alloc = 0;
2229 for (i = 0; i < used_atom_cnt; i++) {
2230 struct used_atom *atom = &used_atom[i];
2231 if (atom->atom_type == ATOM_HEAD)
2232 free(atom->u.head);
2233 free((char *)atom->name);
2235 FREE_AND_NULL(used_atom);
2236 used_atom_cnt = 0;
2238 if (ref_to_worktree_map.worktrees) {
2239 hashmap_clear_and_free(&(ref_to_worktree_map.map),
2240 struct ref_to_worktree_entry, ent);
2241 free_worktrees(ref_to_worktree_map.worktrees);
2242 ref_to_worktree_map.worktrees = NULL;
2246 #define EXCLUDE_REACHED 0
2247 #define INCLUDE_REACHED 1
2248 static void reach_filter(struct ref_array *array,
2249 struct commit_list *check_reachable,
2250 int include_reached)
2252 struct rev_info revs;
2253 int i, old_nr;
2254 struct commit **to_clear;
2255 struct commit_list *cr;
2257 if (!check_reachable)
2258 return;
2260 CALLOC_ARRAY(to_clear, array->nr);
2262 repo_init_revisions(the_repository, &revs, NULL);
2264 for (i = 0; i < array->nr; i++) {
2265 struct ref_array_item *item = array->items[i];
2266 add_pending_object(&revs, &item->commit->object, item->refname);
2267 to_clear[i] = item->commit;
2270 for (cr = check_reachable; cr; cr = cr->next) {
2271 struct commit *merge_commit = cr->item;
2272 merge_commit->object.flags |= UNINTERESTING;
2273 add_pending_object(&revs, &merge_commit->object, "");
2276 revs.limited = 1;
2277 if (prepare_revision_walk(&revs))
2278 die(_("revision walk setup failed"));
2280 old_nr = array->nr;
2281 array->nr = 0;
2283 for (i = 0; i < old_nr; i++) {
2284 struct ref_array_item *item = array->items[i];
2285 struct commit *commit = item->commit;
2287 int is_merged = !!(commit->object.flags & UNINTERESTING);
2289 if (is_merged == include_reached)
2290 array->items[array->nr++] = array->items[i];
2291 else
2292 free_array_item(item);
2295 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2297 while (check_reachable) {
2298 struct commit *merge_commit = pop_commit(&check_reachable);
2299 clear_commit_marks(merge_commit, ALL_REV_FLAGS);
2302 free(to_clear);
2306 * API for filtering a set of refs. Based on the type of refs the user
2307 * has requested, we iterate through those refs and apply filters
2308 * as per the given ref_filter structure and finally store the
2309 * filtered refs in the ref_array structure.
2311 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2313 struct ref_filter_cbdata ref_cbdata;
2314 int ret = 0;
2315 unsigned int broken = 0;
2317 ref_cbdata.array = array;
2318 ref_cbdata.filter = filter;
2320 if (type & FILTER_REFS_INCLUDE_BROKEN)
2321 broken = 1;
2322 filter->kind = type & FILTER_REFS_KIND_MASK;
2324 init_contains_cache(&ref_cbdata.contains_cache);
2325 init_contains_cache(&ref_cbdata.no_contains_cache);
2327 /* Simple per-ref filtering */
2328 if (!filter->kind)
2329 die("filter_refs: invalid type");
2330 else {
2332 * For common cases where we need only branches or remotes or tags,
2333 * we only iterate through those refs. If a mix of refs is needed,
2334 * we iterate over all refs and filter out required refs with the help
2335 * of filter_ref_kind().
2337 if (filter->kind == FILTER_REFS_BRANCHES)
2338 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2339 else if (filter->kind == FILTER_REFS_REMOTES)
2340 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2341 else if (filter->kind == FILTER_REFS_TAGS)
2342 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2343 else if (filter->kind & FILTER_REFS_ALL)
2344 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2345 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2346 head_ref(ref_filter_handler, &ref_cbdata);
2349 clear_contains_cache(&ref_cbdata.contains_cache);
2350 clear_contains_cache(&ref_cbdata.no_contains_cache);
2352 /* Filters that need revision walking */
2353 reach_filter(array, filter->reachable_from, INCLUDE_REACHED);
2354 reach_filter(array, filter->unreachable_from, EXCLUDE_REACHED);
2356 return ret;
2359 static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)
2361 if (!(a->kind ^ b->kind))
2362 BUG("ref_kind_from_refname() should only mark one ref as HEAD");
2363 if (a->kind & FILTER_REFS_DETACHED_HEAD)
2364 return -1;
2365 else if (b->kind & FILTER_REFS_DETACHED_HEAD)
2366 return 1;
2367 BUG("should have died in the xor check above");
2368 return 0;
2371 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2373 struct atom_value *va, *vb;
2374 int cmp;
2375 int cmp_detached_head = 0;
2376 cmp_type cmp_type = used_atom[s->atom].type;
2377 struct strbuf err = STRBUF_INIT;
2379 if (get_ref_atom_value(a, s->atom, &va, &err))
2380 die("%s", err.buf);
2381 if (get_ref_atom_value(b, s->atom, &vb, &err))
2382 die("%s", err.buf);
2383 strbuf_release(&err);
2384 if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&
2385 ((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {
2386 cmp = compare_detached_head(a, b);
2387 cmp_detached_head = 1;
2388 } else if (s->sort_flags & REF_SORTING_VERSION) {
2389 cmp = versioncmp(va->s, vb->s);
2390 } else if (cmp_type == FIELD_STR) {
2391 int (*cmp_fn)(const char *, const char *);
2392 cmp_fn = s->sort_flags & REF_SORTING_ICASE
2393 ? strcasecmp : strcmp;
2394 cmp = cmp_fn(va->s, vb->s);
2395 } else {
2396 if (va->value < vb->value)
2397 cmp = -1;
2398 else if (va->value == vb->value)
2399 cmp = 0;
2400 else
2401 cmp = 1;
2404 return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)
2405 ? -cmp : cmp;
2408 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2410 struct ref_array_item *a = *((struct ref_array_item **)a_);
2411 struct ref_array_item *b = *((struct ref_array_item **)b_);
2412 struct ref_sorting *s;
2414 for (s = ref_sorting; s; s = s->next) {
2415 int cmp = cmp_ref_sorting(s, a, b);
2416 if (cmp)
2417 return cmp;
2419 s = ref_sorting;
2420 return s && s->sort_flags & REF_SORTING_ICASE ?
2421 strcasecmp(a->refname, b->refname) :
2422 strcmp(a->refname, b->refname);
2425 void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,
2426 unsigned int mask, int on)
2428 for (; sorting; sorting = sorting->next) {
2429 if (on)
2430 sorting->sort_flags |= mask;
2431 else
2432 sorting->sort_flags &= ~mask;
2436 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2438 QSORT_S(array->items, array->nr, compare_refs, sorting);
2441 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2443 struct strbuf *s = &state->stack->output;
2445 while (*cp && (!ep || cp < ep)) {
2446 if (*cp == '%') {
2447 if (cp[1] == '%')
2448 cp++;
2449 else {
2450 int ch = hex2chr(cp + 1);
2451 if (0 <= ch) {
2452 strbuf_addch(s, ch);
2453 cp += 3;
2454 continue;
2458 strbuf_addch(s, *cp);
2459 cp++;
2463 int format_ref_array_item(struct ref_array_item *info,
2464 const struct ref_format *format,
2465 struct strbuf *final_buf,
2466 struct strbuf *error_buf)
2468 const char *cp, *sp, *ep;
2469 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2471 state.quote_style = format->quote_style;
2472 push_stack_element(&state.stack);
2474 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2475 struct atom_value *atomv;
2476 int pos;
2478 ep = strchr(sp, ')');
2479 if (cp < sp)
2480 append_literal(cp, sp, &state);
2481 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2482 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2483 atomv->handler(atomv, &state, error_buf)) {
2484 pop_stack_element(&state.stack);
2485 return -1;
2488 if (*cp) {
2489 sp = cp + strlen(cp);
2490 append_literal(cp, sp, &state);
2492 if (format->need_color_reset_at_eol) {
2493 struct atom_value resetv;
2494 resetv.s = GIT_COLOR_RESET;
2495 if (append_atom(&resetv, &state, error_buf)) {
2496 pop_stack_element(&state.stack);
2497 return -1;
2500 if (state.stack->prev) {
2501 pop_stack_element(&state.stack);
2502 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2504 strbuf_addbuf(final_buf, &state.stack->output);
2505 pop_stack_element(&state.stack);
2506 return 0;
2509 void pretty_print_ref(const char *name, const struct object_id *oid,
2510 const struct ref_format *format)
2512 struct ref_array_item *ref_item;
2513 struct strbuf output = STRBUF_INIT;
2514 struct strbuf err = STRBUF_INIT;
2516 ref_item = new_ref_array_item(name, oid);
2517 ref_item->kind = ref_kind_from_refname(name);
2518 if (format_ref_array_item(ref_item, format, &output, &err))
2519 die("%s", err.buf);
2520 fwrite(output.buf, 1, output.len, stdout);
2521 putchar('\n');
2523 strbuf_release(&err);
2524 strbuf_release(&output);
2525 free_array_item(ref_item);
2528 static int parse_sorting_atom(const char *atom)
2531 * This parses an atom using a dummy ref_format, since we don't
2532 * actually care about the formatting details.
2534 struct ref_format dummy = REF_FORMAT_INIT;
2535 const char *end = atom + strlen(atom);
2536 struct strbuf err = STRBUF_INIT;
2537 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2538 if (res < 0)
2539 die("%s", err.buf);
2540 strbuf_release(&err);
2541 return res;
2544 /* If no sorting option is given, use refname to sort as default */
2545 struct ref_sorting *ref_default_sorting(void)
2547 static const char cstr_name[] = "refname";
2549 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2551 sorting->next = NULL;
2552 sorting->atom = parse_sorting_atom(cstr_name);
2553 return sorting;
2556 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2558 struct ref_sorting *s;
2560 CALLOC_ARRAY(s, 1);
2561 s->next = *sorting_tail;
2562 *sorting_tail = s;
2564 if (*arg == '-') {
2565 s->sort_flags |= REF_SORTING_REVERSE;
2566 arg++;
2568 if (skip_prefix(arg, "version:", &arg) ||
2569 skip_prefix(arg, "v:", &arg))
2570 s->sort_flags |= REF_SORTING_VERSION;
2571 s->atom = parse_sorting_atom(arg);
2574 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2577 * NEEDSWORK: We should probably clear the list in this case, but we've
2578 * already munged the global used_atoms list, which would need to be
2579 * undone.
2581 BUG_ON_OPT_NEG(unset);
2583 parse_ref_sorting(opt->value, arg);
2584 return 0;
2587 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2589 struct ref_filter *rf = opt->value;
2590 struct object_id oid;
2591 struct commit *merge_commit;
2593 BUG_ON_OPT_NEG(unset);
2595 if (get_oid(arg, &oid))
2596 die(_("malformed object name %s"), arg);
2598 merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);
2600 if (!merge_commit)
2601 return error(_("option `%s' must point to a commit"), opt->long_name);
2603 if (starts_with(opt->long_name, "no"))
2604 commit_list_insert(merge_commit, &rf->unreachable_from);
2605 else
2606 commit_list_insert(merge_commit, &rf->reachable_from);
2608 return 0;