commit: check result of resolve_ref_unsafe
[git.git] / ref-filter.c
blobf3e53d4448f10ca1002e546890ca682c02ecc9ad
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "refs.h"
5 #include "wildmatch.h"
6 #include "commit.h"
7 #include "remote.h"
8 #include "color.h"
9 #include "tag.h"
10 #include "quote.h"
11 #include "ref-filter.h"
12 #include "revision.h"
13 #include "utf8.h"
14 #include "git-compat-util.h"
15 #include "version.h"
16 #include "trailer.h"
17 #include "wt-status.h"
18 #include "commit-slab.h"
20 static struct ref_msg {
21 const char *gone;
22 const char *ahead;
23 const char *behind;
24 const char *ahead_behind;
25 } msgs = {
26 /* Untranslated plumbing messages: */
27 "gone",
28 "ahead %d",
29 "behind %d",
30 "ahead %d, behind %d"
33 void setup_ref_filter_porcelain_msg(void)
35 msgs.gone = _("gone");
36 msgs.ahead = _("ahead %d");
37 msgs.behind = _("behind %d");
38 msgs.ahead_behind = _("ahead %d, behind %d");
41 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
42 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
44 struct align {
45 align_type position;
46 unsigned int width;
49 struct if_then_else {
50 cmp_status cmp_status;
51 const char *str;
52 unsigned int then_atom_seen : 1,
53 else_atom_seen : 1,
54 condition_satisfied : 1;
57 struct refname_atom {
58 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
59 int lstrip, rstrip;
63 * An atom is a valid field atom listed below, possibly prefixed with
64 * a "*" to denote deref_tag().
66 * We parse given format string and sort specifiers, and make a list
67 * of properties that we need to extract out of objects. ref_array_item
68 * structure will hold an array of values extracted that can be
69 * indexed with the "atom number", which is an index into this
70 * array.
72 static struct used_atom {
73 const char *name;
74 cmp_type type;
75 union {
76 char color[COLOR_MAXLEN];
77 struct align align;
78 struct {
79 enum { RR_REF, RR_TRACK, RR_TRACKSHORT } option;
80 struct refname_atom refname;
81 unsigned int nobracket : 1;
82 } remote_ref;
83 struct {
84 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
85 unsigned int nlines;
86 } contents;
87 struct {
88 cmp_status cmp_status;
89 const char *str;
90 } if_then_else;
91 struct {
92 enum { O_FULL, O_LENGTH, O_SHORT } option;
93 unsigned int length;
94 } objectname;
95 struct refname_atom refname;
96 char *head;
97 } u;
98 } *used_atom;
99 static int used_atom_cnt, need_tagged, need_symref;
101 static void color_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *color_value)
103 if (!color_value)
104 die(_("expected format: %%(color:<color>)"));
105 if (color_parse(color_value, atom->u.color) < 0)
106 die(_("unrecognized color: %%(color:%s)"), color_value);
108 * We check this after we've parsed the color, which lets us complain
109 * about syntactically bogus color names even if they won't be used.
111 if (!want_color(format->use_color))
112 color_parse("", atom->u.color);
115 static void refname_atom_parser_internal(struct refname_atom *atom,
116 const char *arg, const char *name)
118 if (!arg)
119 atom->option = R_NORMAL;
120 else if (!strcmp(arg, "short"))
121 atom->option = R_SHORT;
122 else if (skip_prefix(arg, "lstrip=", &arg) ||
123 skip_prefix(arg, "strip=", &arg)) {
124 atom->option = R_LSTRIP;
125 if (strtol_i(arg, 10, &atom->lstrip))
126 die(_("Integer value expected refname:lstrip=%s"), arg);
127 } else if (skip_prefix(arg, "rstrip=", &arg)) {
128 atom->option = R_RSTRIP;
129 if (strtol_i(arg, 10, &atom->rstrip))
130 die(_("Integer value expected refname:rstrip=%s"), arg);
131 } else
132 die(_("unrecognized %%(%s) argument: %s"), name, arg);
135 static void remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
137 struct string_list params = STRING_LIST_INIT_DUP;
138 int i;
140 if (!arg) {
141 atom->u.remote_ref.option = RR_REF;
142 refname_atom_parser_internal(&atom->u.remote_ref.refname,
143 arg, atom->name);
144 return;
147 atom->u.remote_ref.nobracket = 0;
148 string_list_split(&params, arg, ',', -1);
150 for (i = 0; i < params.nr; i++) {
151 const char *s = params.items[i].string;
153 if (!strcmp(s, "track"))
154 atom->u.remote_ref.option = RR_TRACK;
155 else if (!strcmp(s, "trackshort"))
156 atom->u.remote_ref.option = RR_TRACKSHORT;
157 else if (!strcmp(s, "nobracket"))
158 atom->u.remote_ref.nobracket = 1;
159 else {
160 atom->u.remote_ref.option = RR_REF;
161 refname_atom_parser_internal(&atom->u.remote_ref.refname,
162 arg, atom->name);
166 string_list_clear(&params, 0);
169 static void body_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
171 if (arg)
172 die(_("%%(body) does not take arguments"));
173 atom->u.contents.option = C_BODY_DEP;
176 static void subject_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
178 if (arg)
179 die(_("%%(subject) does not take arguments"));
180 atom->u.contents.option = C_SUB;
183 static void trailers_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
185 if (arg)
186 die(_("%%(trailers) does not take arguments"));
187 atom->u.contents.option = C_TRAILERS;
190 static void contents_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
192 if (!arg)
193 atom->u.contents.option = C_BARE;
194 else if (!strcmp(arg, "body"))
195 atom->u.contents.option = C_BODY;
196 else if (!strcmp(arg, "signature"))
197 atom->u.contents.option = C_SIG;
198 else if (!strcmp(arg, "subject"))
199 atom->u.contents.option = C_SUB;
200 else if (!strcmp(arg, "trailers"))
201 atom->u.contents.option = C_TRAILERS;
202 else if (skip_prefix(arg, "lines=", &arg)) {
203 atom->u.contents.option = C_LINES;
204 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
205 die(_("positive value expected contents:lines=%s"), arg);
206 } else
207 die(_("unrecognized %%(contents) argument: %s"), arg);
210 static void objectname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
212 if (!arg)
213 atom->u.objectname.option = O_FULL;
214 else if (!strcmp(arg, "short"))
215 atom->u.objectname.option = O_SHORT;
216 else if (skip_prefix(arg, "short=", &arg)) {
217 atom->u.objectname.option = O_LENGTH;
218 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
219 atom->u.objectname.length == 0)
220 die(_("positive value expected objectname:short=%s"), arg);
221 if (atom->u.objectname.length < MINIMUM_ABBREV)
222 atom->u.objectname.length = MINIMUM_ABBREV;
223 } else
224 die(_("unrecognized %%(objectname) argument: %s"), arg);
227 static void refname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
229 refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
232 static align_type parse_align_position(const char *s)
234 if (!strcmp(s, "right"))
235 return ALIGN_RIGHT;
236 else if (!strcmp(s, "middle"))
237 return ALIGN_MIDDLE;
238 else if (!strcmp(s, "left"))
239 return ALIGN_LEFT;
240 return -1;
243 static void align_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
245 struct align *align = &atom->u.align;
246 struct string_list params = STRING_LIST_INIT_DUP;
247 int i;
248 unsigned int width = ~0U;
250 if (!arg)
251 die(_("expected format: %%(align:<width>,<position>)"));
253 align->position = ALIGN_LEFT;
255 string_list_split(&params, arg, ',', -1);
256 for (i = 0; i < params.nr; i++) {
257 const char *s = params.items[i].string;
258 int position;
260 if (skip_prefix(s, "position=", &s)) {
261 position = parse_align_position(s);
262 if (position < 0)
263 die(_("unrecognized position:%s"), s);
264 align->position = position;
265 } else if (skip_prefix(s, "width=", &s)) {
266 if (strtoul_ui(s, 10, &width))
267 die(_("unrecognized width:%s"), s);
268 } else if (!strtoul_ui(s, 10, &width))
270 else if ((position = parse_align_position(s)) >= 0)
271 align->position = position;
272 else
273 die(_("unrecognized %%(align) argument: %s"), s);
276 if (width == ~0U)
277 die(_("positive width expected with the %%(align) atom"));
278 align->width = width;
279 string_list_clear(&params, 0);
282 static void if_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
284 if (!arg) {
285 atom->u.if_then_else.cmp_status = COMPARE_NONE;
286 return;
287 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
288 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
289 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
290 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
291 } else {
292 die(_("unrecognized %%(if) argument: %s"), arg);
296 static void head_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
298 struct object_id unused;
300 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, unused.hash, NULL);
303 static struct {
304 const char *name;
305 cmp_type cmp_type;
306 void (*parser)(const struct ref_format *format, struct used_atom *atom, const char *arg);
307 } valid_atom[] = {
308 { "refname" , FIELD_STR, refname_atom_parser },
309 { "objecttype" },
310 { "objectsize", FIELD_ULONG },
311 { "objectname", FIELD_STR, objectname_atom_parser },
312 { "tree" },
313 { "parent" },
314 { "numparent", FIELD_ULONG },
315 { "object" },
316 { "type" },
317 { "tag" },
318 { "author" },
319 { "authorname" },
320 { "authoremail" },
321 { "authordate", FIELD_TIME },
322 { "committer" },
323 { "committername" },
324 { "committeremail" },
325 { "committerdate", FIELD_TIME },
326 { "tagger" },
327 { "taggername" },
328 { "taggeremail" },
329 { "taggerdate", FIELD_TIME },
330 { "creator" },
331 { "creatordate", FIELD_TIME },
332 { "subject", FIELD_STR, subject_atom_parser },
333 { "body", FIELD_STR, body_atom_parser },
334 { "trailers", FIELD_STR, trailers_atom_parser },
335 { "contents", FIELD_STR, contents_atom_parser },
336 { "upstream", FIELD_STR, remote_ref_atom_parser },
337 { "push", FIELD_STR, remote_ref_atom_parser },
338 { "symref", FIELD_STR, refname_atom_parser },
339 { "flag" },
340 { "HEAD", FIELD_STR, head_atom_parser },
341 { "color", FIELD_STR, color_atom_parser },
342 { "align", FIELD_STR, align_atom_parser },
343 { "end" },
344 { "if", FIELD_STR, if_atom_parser },
345 { "then" },
346 { "else" },
349 #define REF_FORMATTING_STATE_INIT { 0, NULL }
351 struct ref_formatting_stack {
352 struct ref_formatting_stack *prev;
353 struct strbuf output;
354 void (*at_end)(struct ref_formatting_stack **stack);
355 void *at_end_data;
358 struct ref_formatting_state {
359 int quote_style;
360 struct ref_formatting_stack *stack;
363 struct atom_value {
364 const char *s;
365 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
366 uintmax_t value; /* used for sorting when not FIELD_STR */
367 struct used_atom *atom;
371 * Used to parse format string and sort specifiers
373 static int parse_ref_filter_atom(const struct ref_format *format,
374 const char *atom, const char *ep)
376 const char *sp;
377 const char *arg;
378 int i, at, atom_len;
380 sp = atom;
381 if (*sp == '*' && sp < ep)
382 sp++; /* deref */
383 if (ep <= sp)
384 die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
386 /* Do we have the atom already used elsewhere? */
387 for (i = 0; i < used_atom_cnt; i++) {
388 int len = strlen(used_atom[i].name);
389 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
390 return i;
394 * If the atom name has a colon, strip it and everything after
395 * it off - it specifies the format for this entry, and
396 * shouldn't be used for checking against the valid_atom
397 * table.
399 arg = memchr(sp, ':', ep - sp);
400 atom_len = (arg ? arg : ep) - sp;
402 /* Is the atom a valid one? */
403 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
404 int len = strlen(valid_atom[i].name);
405 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
406 break;
409 if (ARRAY_SIZE(valid_atom) <= i)
410 die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
412 /* Add it in, including the deref prefix */
413 at = used_atom_cnt;
414 used_atom_cnt++;
415 REALLOC_ARRAY(used_atom, used_atom_cnt);
416 used_atom[at].name = xmemdupz(atom, ep - atom);
417 used_atom[at].type = valid_atom[i].cmp_type;
418 if (arg) {
419 arg = used_atom[at].name + (arg - atom) + 1;
420 if (!*arg) {
422 * Treat empty sub-arguments list as NULL (i.e.,
423 * "%(atom:)" is equivalent to "%(atom)").
425 arg = NULL;
428 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
429 if (valid_atom[i].parser)
430 valid_atom[i].parser(format, &used_atom[at], arg);
431 if (*atom == '*')
432 need_tagged = 1;
433 if (!strcmp(valid_atom[i].name, "symref"))
434 need_symref = 1;
435 return at;
438 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
440 switch (quote_style) {
441 case QUOTE_NONE:
442 strbuf_addstr(s, str);
443 break;
444 case QUOTE_SHELL:
445 sq_quote_buf(s, str);
446 break;
447 case QUOTE_PERL:
448 perl_quote_buf(s, str);
449 break;
450 case QUOTE_PYTHON:
451 python_quote_buf(s, str);
452 break;
453 case QUOTE_TCL:
454 tcl_quote_buf(s, str);
455 break;
459 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
462 * Quote formatting is only done when the stack has a single
463 * element. Otherwise quote formatting is done on the
464 * element's entire output strbuf when the %(end) atom is
465 * encountered.
467 if (!state->stack->prev)
468 quote_formatting(&state->stack->output, v->s, state->quote_style);
469 else
470 strbuf_addstr(&state->stack->output, v->s);
473 static void push_stack_element(struct ref_formatting_stack **stack)
475 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
477 strbuf_init(&s->output, 0);
478 s->prev = *stack;
479 *stack = s;
482 static void pop_stack_element(struct ref_formatting_stack **stack)
484 struct ref_formatting_stack *current = *stack;
485 struct ref_formatting_stack *prev = current->prev;
487 if (prev)
488 strbuf_addbuf(&prev->output, &current->output);
489 strbuf_release(&current->output);
490 free(current);
491 *stack = prev;
494 static void end_align_handler(struct ref_formatting_stack **stack)
496 struct ref_formatting_stack *cur = *stack;
497 struct align *align = (struct align *)cur->at_end_data;
498 struct strbuf s = STRBUF_INIT;
500 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
501 strbuf_swap(&cur->output, &s);
502 strbuf_release(&s);
505 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
507 struct ref_formatting_stack *new;
509 push_stack_element(&state->stack);
510 new = state->stack;
511 new->at_end = end_align_handler;
512 new->at_end_data = &atomv->atom->u.align;
515 static void if_then_else_handler(struct ref_formatting_stack **stack)
517 struct ref_formatting_stack *cur = *stack;
518 struct ref_formatting_stack *prev = cur->prev;
519 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
521 if (!if_then_else->then_atom_seen)
522 die(_("format: %%(if) atom used without a %%(then) atom"));
524 if (if_then_else->else_atom_seen) {
526 * There is an %(else) atom: we need to drop one state from the
527 * stack, either the %(else) branch if the condition is satisfied, or
528 * the %(then) branch if it isn't.
530 if (if_then_else->condition_satisfied) {
531 strbuf_reset(&cur->output);
532 pop_stack_element(&cur);
533 } else {
534 strbuf_swap(&cur->output, &prev->output);
535 strbuf_reset(&cur->output);
536 pop_stack_element(&cur);
538 } else if (!if_then_else->condition_satisfied) {
540 * No %(else) atom: just drop the %(then) branch if the
541 * condition is not satisfied.
543 strbuf_reset(&cur->output);
546 *stack = cur;
547 free(if_then_else);
550 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
552 struct ref_formatting_stack *new;
553 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
555 if_then_else->str = atomv->atom->u.if_then_else.str;
556 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
558 push_stack_element(&state->stack);
559 new = state->stack;
560 new->at_end = if_then_else_handler;
561 new->at_end_data = if_then_else;
564 static int is_empty(const char *s)
566 while (*s != '\0') {
567 if (!isspace(*s))
568 return 0;
569 s++;
571 return 1;
574 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
576 struct ref_formatting_stack *cur = state->stack;
577 struct if_then_else *if_then_else = NULL;
579 if (cur->at_end == if_then_else_handler)
580 if_then_else = (struct if_then_else *)cur->at_end_data;
581 if (!if_then_else)
582 die(_("format: %%(then) atom used without an %%(if) atom"));
583 if (if_then_else->then_atom_seen)
584 die(_("format: %%(then) atom used more than once"));
585 if (if_then_else->else_atom_seen)
586 die(_("format: %%(then) atom used after %%(else)"));
587 if_then_else->then_atom_seen = 1;
589 * If the 'equals' or 'notequals' attribute is used then
590 * perform the required comparison. If not, only non-empty
591 * strings satisfy the 'if' condition.
593 if (if_then_else->cmp_status == COMPARE_EQUAL) {
594 if (!strcmp(if_then_else->str, cur->output.buf))
595 if_then_else->condition_satisfied = 1;
596 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
597 if (strcmp(if_then_else->str, cur->output.buf))
598 if_then_else->condition_satisfied = 1;
599 } else if (cur->output.len && !is_empty(cur->output.buf))
600 if_then_else->condition_satisfied = 1;
601 strbuf_reset(&cur->output);
604 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
606 struct ref_formatting_stack *prev = state->stack;
607 struct if_then_else *if_then_else = NULL;
609 if (prev->at_end == if_then_else_handler)
610 if_then_else = (struct if_then_else *)prev->at_end_data;
611 if (!if_then_else)
612 die(_("format: %%(else) atom used without an %%(if) atom"));
613 if (!if_then_else->then_atom_seen)
614 die(_("format: %%(else) atom used without a %%(then) atom"));
615 if (if_then_else->else_atom_seen)
616 die(_("format: %%(else) atom used more than once"));
617 if_then_else->else_atom_seen = 1;
618 push_stack_element(&state->stack);
619 state->stack->at_end_data = prev->at_end_data;
620 state->stack->at_end = prev->at_end;
623 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
625 struct ref_formatting_stack *current = state->stack;
626 struct strbuf s = STRBUF_INIT;
628 if (!current->at_end)
629 die(_("format: %%(end) atom used without corresponding atom"));
630 current->at_end(&state->stack);
632 /* Stack may have been popped within at_end(), hence reset the current pointer */
633 current = state->stack;
636 * Perform quote formatting when the stack element is that of
637 * a supporting atom. If nested then perform quote formatting
638 * only on the topmost supporting atom.
640 if (!current->prev->prev) {
641 quote_formatting(&s, current->output.buf, state->quote_style);
642 strbuf_swap(&current->output, &s);
644 strbuf_release(&s);
645 pop_stack_element(&state->stack);
649 * In a format string, find the next occurrence of %(atom).
651 static const char *find_next(const char *cp)
653 while (*cp) {
654 if (*cp == '%') {
656 * %( is the start of an atom;
657 * %% is a quoted per-cent.
659 if (cp[1] == '(')
660 return cp;
661 else if (cp[1] == '%')
662 cp++; /* skip over two % */
663 /* otherwise this is a singleton, literal % */
665 cp++;
667 return NULL;
671 * Make sure the format string is well formed, and parse out
672 * the used atoms.
674 int verify_ref_format(struct ref_format *format)
676 const char *cp, *sp;
678 format->need_color_reset_at_eol = 0;
679 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
680 const char *color, *ep = strchr(sp, ')');
681 int at;
683 if (!ep)
684 return error(_("malformed format string %s"), sp);
685 /* sp points at "%(" and ep points at the closing ")" */
686 at = parse_ref_filter_atom(format, sp + 2, ep);
687 cp = ep + 1;
689 if (skip_prefix(used_atom[at].name, "color:", &color))
690 format->need_color_reset_at_eol = !!strcmp(color, "reset");
692 if (format->need_color_reset_at_eol && !want_color(format->use_color))
693 format->need_color_reset_at_eol = 0;
694 return 0;
698 * Given an object name, read the object data and size, and return a
699 * "struct object". If the object data we are returning is also borrowed
700 * by the "struct object" representation, set *eaten as well---it is a
701 * signal from parse_object_buffer to us not to free the buffer.
703 static void *get_obj(const struct object_id *oid, struct object **obj, unsigned long *sz, int *eaten)
705 enum object_type type;
706 void *buf = read_sha1_file(oid->hash, &type, sz);
708 if (buf)
709 *obj = parse_object_buffer(oid, type, *sz, buf, eaten);
710 else
711 *obj = NULL;
712 return buf;
715 static int grab_objectname(const char *name, const unsigned char *sha1,
716 struct atom_value *v, struct used_atom *atom)
718 if (starts_with(name, "objectname")) {
719 if (atom->u.objectname.option == O_SHORT) {
720 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
721 return 1;
722 } else if (atom->u.objectname.option == O_FULL) {
723 v->s = xstrdup(sha1_to_hex(sha1));
724 return 1;
725 } else if (atom->u.objectname.option == O_LENGTH) {
726 v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
727 return 1;
728 } else
729 die("BUG: unknown %%(objectname) option");
731 return 0;
734 /* See grab_values */
735 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
737 int i;
739 for (i = 0; i < used_atom_cnt; i++) {
740 const char *name = used_atom[i].name;
741 struct atom_value *v = &val[i];
742 if (!!deref != (*name == '*'))
743 continue;
744 if (deref)
745 name++;
746 if (!strcmp(name, "objecttype"))
747 v->s = typename(obj->type);
748 else if (!strcmp(name, "objectsize")) {
749 v->value = sz;
750 v->s = xstrfmt("%lu", sz);
752 else if (deref)
753 grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
757 /* See grab_values */
758 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
760 int i;
761 struct tag *tag = (struct tag *) obj;
763 for (i = 0; i < used_atom_cnt; i++) {
764 const char *name = used_atom[i].name;
765 struct atom_value *v = &val[i];
766 if (!!deref != (*name == '*'))
767 continue;
768 if (deref)
769 name++;
770 if (!strcmp(name, "tag"))
771 v->s = tag->tag;
772 else if (!strcmp(name, "type") && tag->tagged)
773 v->s = typename(tag->tagged->type);
774 else if (!strcmp(name, "object") && tag->tagged)
775 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
779 /* See grab_values */
780 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
782 int i;
783 struct commit *commit = (struct commit *) obj;
785 for (i = 0; i < used_atom_cnt; i++) {
786 const char *name = used_atom[i].name;
787 struct atom_value *v = &val[i];
788 if (!!deref != (*name == '*'))
789 continue;
790 if (deref)
791 name++;
792 if (!strcmp(name, "tree")) {
793 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
795 else if (!strcmp(name, "numparent")) {
796 v->value = commit_list_count(commit->parents);
797 v->s = xstrfmt("%lu", (unsigned long)v->value);
799 else if (!strcmp(name, "parent")) {
800 struct commit_list *parents;
801 struct strbuf s = STRBUF_INIT;
802 for (parents = commit->parents; parents; parents = parents->next) {
803 struct commit *parent = parents->item;
804 if (parents != commit->parents)
805 strbuf_addch(&s, ' ');
806 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
808 v->s = strbuf_detach(&s, NULL);
813 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
815 const char *eol;
816 while (*buf) {
817 if (!strncmp(buf, who, wholen) &&
818 buf[wholen] == ' ')
819 return buf + wholen + 1;
820 eol = strchr(buf, '\n');
821 if (!eol)
822 return "";
823 eol++;
824 if (*eol == '\n')
825 return ""; /* end of header */
826 buf = eol;
828 return "";
831 static const char *copy_line(const char *buf)
833 const char *eol = strchrnul(buf, '\n');
834 return xmemdupz(buf, eol - buf);
837 static const char *copy_name(const char *buf)
839 const char *cp;
840 for (cp = buf; *cp && *cp != '\n'; cp++) {
841 if (!strncmp(cp, " <", 2))
842 return xmemdupz(buf, cp - buf);
844 return "";
847 static const char *copy_email(const char *buf)
849 const char *email = strchr(buf, '<');
850 const char *eoemail;
851 if (!email)
852 return "";
853 eoemail = strchr(email, '>');
854 if (!eoemail)
855 return "";
856 return xmemdupz(email, eoemail + 1 - email);
859 static char *copy_subject(const char *buf, unsigned long len)
861 char *r = xmemdupz(buf, len);
862 int i;
864 for (i = 0; i < len; i++)
865 if (r[i] == '\n')
866 r[i] = ' ';
868 return r;
871 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
873 const char *eoemail = strstr(buf, "> ");
874 char *zone;
875 timestamp_t timestamp;
876 long tz;
877 struct date_mode date_mode = { DATE_NORMAL };
878 const char *formatp;
881 * We got here because atomname ends in "date" or "date<something>";
882 * it's not possible that <something> is not ":<format>" because
883 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
884 * ":" means no format is specified, and use the default.
886 formatp = strchr(atomname, ':');
887 if (formatp != NULL) {
888 formatp++;
889 parse_date_format(formatp, &date_mode);
892 if (!eoemail)
893 goto bad;
894 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
895 if (timestamp == TIME_MAX)
896 goto bad;
897 tz = strtol(zone, NULL, 10);
898 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
899 goto bad;
900 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
901 v->value = timestamp;
902 return;
903 bad:
904 v->s = "";
905 v->value = 0;
908 /* See grab_values */
909 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
911 int i;
912 int wholen = strlen(who);
913 const char *wholine = NULL;
915 for (i = 0; i < used_atom_cnt; i++) {
916 const char *name = used_atom[i].name;
917 struct atom_value *v = &val[i];
918 if (!!deref != (*name == '*'))
919 continue;
920 if (deref)
921 name++;
922 if (strncmp(who, name, wholen))
923 continue;
924 if (name[wholen] != 0 &&
925 strcmp(name + wholen, "name") &&
926 strcmp(name + wholen, "email") &&
927 !starts_with(name + wholen, "date"))
928 continue;
929 if (!wholine)
930 wholine = find_wholine(who, wholen, buf, sz);
931 if (!wholine)
932 return; /* no point looking for it */
933 if (name[wholen] == 0)
934 v->s = copy_line(wholine);
935 else if (!strcmp(name + wholen, "name"))
936 v->s = copy_name(wholine);
937 else if (!strcmp(name + wholen, "email"))
938 v->s = copy_email(wholine);
939 else if (starts_with(name + wholen, "date"))
940 grab_date(wholine, v, name);
944 * For a tag or a commit object, if "creator" or "creatordate" is
945 * requested, do something special.
947 if (strcmp(who, "tagger") && strcmp(who, "committer"))
948 return; /* "author" for commit object is not wanted */
949 if (!wholine)
950 wholine = find_wholine(who, wholen, buf, sz);
951 if (!wholine)
952 return;
953 for (i = 0; i < used_atom_cnt; i++) {
954 const char *name = used_atom[i].name;
955 struct atom_value *v = &val[i];
956 if (!!deref != (*name == '*'))
957 continue;
958 if (deref)
959 name++;
961 if (starts_with(name, "creatordate"))
962 grab_date(wholine, v, name);
963 else if (!strcmp(name, "creator"))
964 v->s = copy_line(wholine);
968 static void find_subpos(const char *buf, unsigned long sz,
969 const char **sub, unsigned long *sublen,
970 const char **body, unsigned long *bodylen,
971 unsigned long *nonsiglen,
972 const char **sig, unsigned long *siglen)
974 const char *eol;
975 /* skip past header until we hit empty line */
976 while (*buf && *buf != '\n') {
977 eol = strchrnul(buf, '\n');
978 if (*eol)
979 eol++;
980 buf = eol;
982 /* skip any empty lines */
983 while (*buf == '\n')
984 buf++;
986 /* parse signature first; we might not even have a subject line */
987 *sig = buf + parse_signature(buf, strlen(buf));
988 *siglen = strlen(*sig);
990 /* subject is first non-empty line */
991 *sub = buf;
992 /* subject goes to first empty line */
993 while (buf < *sig && *buf && *buf != '\n') {
994 eol = strchrnul(buf, '\n');
995 if (*eol)
996 eol++;
997 buf = eol;
999 *sublen = buf - *sub;
1000 /* drop trailing newline, if present */
1001 if (*sublen && (*sub)[*sublen - 1] == '\n')
1002 *sublen -= 1;
1004 /* skip any empty lines */
1005 while (*buf == '\n')
1006 buf++;
1007 *body = buf;
1008 *bodylen = strlen(buf);
1009 *nonsiglen = *sig - buf;
1013 * If 'lines' is greater than 0, append that many lines from the given
1014 * 'buf' of length 'size' to the given strbuf.
1016 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1018 int i;
1019 const char *sp, *eol;
1020 size_t len;
1022 sp = buf;
1024 for (i = 0; i < lines && sp < buf + size; i++) {
1025 if (i)
1026 strbuf_addstr(out, "\n ");
1027 eol = memchr(sp, '\n', size - (sp - buf));
1028 len = eol ? eol - sp : size - (sp - buf);
1029 strbuf_add(out, sp, len);
1030 if (!eol)
1031 break;
1032 sp = eol + 1;
1036 /* See grab_values */
1037 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1039 int i;
1040 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1041 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1043 for (i = 0; i < used_atom_cnt; i++) {
1044 struct used_atom *atom = &used_atom[i];
1045 const char *name = atom->name;
1046 struct atom_value *v = &val[i];
1047 if (!!deref != (*name == '*'))
1048 continue;
1049 if (deref)
1050 name++;
1051 if (strcmp(name, "subject") &&
1052 strcmp(name, "body") &&
1053 strcmp(name, "trailers") &&
1054 !starts_with(name, "contents"))
1055 continue;
1056 if (!subpos)
1057 find_subpos(buf, sz,
1058 &subpos, &sublen,
1059 &bodypos, &bodylen, &nonsiglen,
1060 &sigpos, &siglen);
1062 if (atom->u.contents.option == C_SUB)
1063 v->s = copy_subject(subpos, sublen);
1064 else if (atom->u.contents.option == C_BODY_DEP)
1065 v->s = xmemdupz(bodypos, bodylen);
1066 else if (atom->u.contents.option == C_BODY)
1067 v->s = xmemdupz(bodypos, nonsiglen);
1068 else if (atom->u.contents.option == C_SIG)
1069 v->s = xmemdupz(sigpos, siglen);
1070 else if (atom->u.contents.option == C_LINES) {
1071 struct strbuf s = STRBUF_INIT;
1072 const char *contents_end = bodylen + bodypos - siglen;
1074 /* Size is the length of the message after removing the signature */
1075 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1076 v->s = strbuf_detach(&s, NULL);
1077 } else if (atom->u.contents.option == C_TRAILERS) {
1078 struct trailer_info info;
1080 /* Search for trailer info */
1081 trailer_info_get(&info, subpos);
1082 v->s = xmemdupz(info.trailer_start,
1083 info.trailer_end - info.trailer_start);
1084 trailer_info_release(&info);
1085 } else if (atom->u.contents.option == C_BARE)
1086 v->s = xstrdup(subpos);
1091 * We want to have empty print-string for field requests
1092 * that do not apply (e.g. "authordate" for a tag object)
1094 static void fill_missing_values(struct atom_value *val)
1096 int i;
1097 for (i = 0; i < used_atom_cnt; i++) {
1098 struct atom_value *v = &val[i];
1099 if (v->s == NULL)
1100 v->s = "";
1105 * val is a list of atom_value to hold returned values. Extract
1106 * the values for atoms in used_atom array out of (obj, buf, sz).
1107 * when deref is false, (obj, buf, sz) is the object that is
1108 * pointed at by the ref itself; otherwise it is the object the
1109 * ref (which is a tag) refers to.
1111 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1113 grab_common_values(val, deref, obj, buf, sz);
1114 switch (obj->type) {
1115 case OBJ_TAG:
1116 grab_tag_values(val, deref, obj, buf, sz);
1117 grab_sub_body_contents(val, deref, obj, buf, sz);
1118 grab_person("tagger", val, deref, obj, buf, sz);
1119 break;
1120 case OBJ_COMMIT:
1121 grab_commit_values(val, deref, obj, buf, sz);
1122 grab_sub_body_contents(val, deref, obj, buf, sz);
1123 grab_person("author", val, deref, obj, buf, sz);
1124 grab_person("committer", val, deref, obj, buf, sz);
1125 break;
1126 case OBJ_TREE:
1127 /* grab_tree_values(val, deref, obj, buf, sz); */
1128 break;
1129 case OBJ_BLOB:
1130 /* grab_blob_values(val, deref, obj, buf, sz); */
1131 break;
1132 default:
1133 die("Eh? Object of type %d?", obj->type);
1137 static inline char *copy_advance(char *dst, const char *src)
1139 while (*src)
1140 *dst++ = *src++;
1141 return dst;
1144 static const char *lstrip_ref_components(const char *refname, int len)
1146 long remaining = len;
1147 const char *start = refname;
1149 if (len < 0) {
1150 int i;
1151 const char *p = refname;
1153 /* Find total no of '/' separated path-components */
1154 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1157 * The number of components we need to strip is now
1158 * the total minus the components to be left (Plus one
1159 * because we count the number of '/', but the number
1160 * of components is one more than the no of '/').
1162 remaining = i + len + 1;
1165 while (remaining > 0) {
1166 switch (*start++) {
1167 case '\0':
1168 return "";
1169 case '/':
1170 remaining--;
1171 break;
1175 return start;
1178 static const char *rstrip_ref_components(const char *refname, int len)
1180 long remaining = len;
1181 char *start = xstrdup(refname);
1183 if (len < 0) {
1184 int i;
1185 const char *p = refname;
1187 /* Find total no of '/' separated path-components */
1188 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1191 * The number of components we need to strip is now
1192 * the total minus the components to be left (Plus one
1193 * because we count the number of '/', but the number
1194 * of components is one more than the no of '/').
1196 remaining = i + len + 1;
1199 while (remaining-- > 0) {
1200 char *p = strrchr(start, '/');
1201 if (p == NULL)
1202 return "";
1203 else
1204 p[0] = '\0';
1206 return start;
1209 static const char *show_ref(struct refname_atom *atom, const char *refname)
1211 if (atom->option == R_SHORT)
1212 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1213 else if (atom->option == R_LSTRIP)
1214 return lstrip_ref_components(refname, atom->lstrip);
1215 else if (atom->option == R_RSTRIP)
1216 return rstrip_ref_components(refname, atom->rstrip);
1217 else
1218 return refname;
1221 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1222 struct branch *branch, const char **s)
1224 int num_ours, num_theirs;
1225 if (atom->u.remote_ref.option == RR_REF)
1226 *s = show_ref(&atom->u.remote_ref.refname, refname);
1227 else if (atom->u.remote_ref.option == RR_TRACK) {
1228 if (stat_tracking_info(branch, &num_ours,
1229 &num_theirs, NULL)) {
1230 *s = xstrdup(msgs.gone);
1231 } else if (!num_ours && !num_theirs)
1232 *s = "";
1233 else if (!num_ours)
1234 *s = xstrfmt(msgs.behind, num_theirs);
1235 else if (!num_theirs)
1236 *s = xstrfmt(msgs.ahead, num_ours);
1237 else
1238 *s = xstrfmt(msgs.ahead_behind,
1239 num_ours, num_theirs);
1240 if (!atom->u.remote_ref.nobracket && *s[0]) {
1241 const char *to_free = *s;
1242 *s = xstrfmt("[%s]", *s);
1243 free((void *)to_free);
1245 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1246 if (stat_tracking_info(branch, &num_ours,
1247 &num_theirs, NULL))
1248 return;
1250 if (!num_ours && !num_theirs)
1251 *s = "=";
1252 else if (!num_ours)
1253 *s = "<";
1254 else if (!num_theirs)
1255 *s = ">";
1256 else
1257 *s = "<>";
1258 } else
1259 die("BUG: unhandled RR_* enum");
1262 char *get_head_description(void)
1264 struct strbuf desc = STRBUF_INIT;
1265 struct wt_status_state state;
1266 memset(&state, 0, sizeof(state));
1267 wt_status_get_state(&state, 1);
1268 if (state.rebase_in_progress ||
1269 state.rebase_interactive_in_progress)
1270 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1271 state.branch);
1272 else if (state.bisect_in_progress)
1273 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1274 state.branch);
1275 else if (state.detached_from) {
1276 if (state.detached_at)
1278 * TRANSLATORS: make sure this matches "HEAD
1279 * detached at " in wt-status.c
1281 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1282 state.detached_from);
1283 else
1285 * TRANSLATORS: make sure this matches "HEAD
1286 * detached from " in wt-status.c
1288 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1289 state.detached_from);
1291 else
1292 strbuf_addstr(&desc, _("(no branch)"));
1293 free(state.branch);
1294 free(state.onto);
1295 free(state.detached_from);
1296 return strbuf_detach(&desc, NULL);
1299 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1301 if (!ref->symref)
1302 return "";
1303 else
1304 return show_ref(&atom->u.refname, ref->symref);
1307 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1309 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1310 return get_head_description();
1311 return show_ref(&atom->u.refname, ref->refname);
1315 * Parse the object referred by ref, and grab needed value.
1317 static void populate_value(struct ref_array_item *ref)
1319 void *buf;
1320 struct object *obj;
1321 int eaten, i;
1322 unsigned long size;
1323 const struct object_id *tagged;
1325 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1327 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1328 struct object_id unused1;
1329 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1330 unused1.hash, NULL);
1331 if (!ref->symref)
1332 ref->symref = "";
1335 /* Fill in specials first */
1336 for (i = 0; i < used_atom_cnt; i++) {
1337 struct used_atom *atom = &used_atom[i];
1338 const char *name = used_atom[i].name;
1339 struct atom_value *v = &ref->value[i];
1340 int deref = 0;
1341 const char *refname;
1342 struct branch *branch = NULL;
1344 v->handler = append_atom;
1345 v->atom = atom;
1347 if (*name == '*') {
1348 deref = 1;
1349 name++;
1352 if (starts_with(name, "refname"))
1353 refname = get_refname(atom, ref);
1354 else if (starts_with(name, "symref"))
1355 refname = get_symref(atom, ref);
1356 else if (starts_with(name, "upstream")) {
1357 const char *branch_name;
1358 /* only local branches may have an upstream */
1359 if (!skip_prefix(ref->refname, "refs/heads/",
1360 &branch_name))
1361 continue;
1362 branch = branch_get(branch_name);
1364 refname = branch_get_upstream(branch, NULL);
1365 if (refname)
1366 fill_remote_ref_details(atom, refname, branch, &v->s);
1367 continue;
1368 } else if (starts_with(name, "push")) {
1369 const char *branch_name;
1370 if (!skip_prefix(ref->refname, "refs/heads/",
1371 &branch_name))
1372 continue;
1373 branch = branch_get(branch_name);
1375 refname = branch_get_push(branch, NULL);
1376 if (!refname)
1377 continue;
1378 fill_remote_ref_details(atom, refname, branch, &v->s);
1379 continue;
1380 } else if (starts_with(name, "color:")) {
1381 v->s = atom->u.color;
1382 continue;
1383 } else if (!strcmp(name, "flag")) {
1384 char buf[256], *cp = buf;
1385 if (ref->flag & REF_ISSYMREF)
1386 cp = copy_advance(cp, ",symref");
1387 if (ref->flag & REF_ISPACKED)
1388 cp = copy_advance(cp, ",packed");
1389 if (cp == buf)
1390 v->s = "";
1391 else {
1392 *cp = '\0';
1393 v->s = xstrdup(buf + 1);
1395 continue;
1396 } else if (!deref && grab_objectname(name, ref->objectname.hash, v, atom)) {
1397 continue;
1398 } else if (!strcmp(name, "HEAD")) {
1399 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1400 v->s = "*";
1401 else
1402 v->s = " ";
1403 continue;
1404 } else if (starts_with(name, "align")) {
1405 v->handler = align_atom_handler;
1406 continue;
1407 } else if (!strcmp(name, "end")) {
1408 v->handler = end_atom_handler;
1409 continue;
1410 } else if (starts_with(name, "if")) {
1411 const char *s;
1413 if (skip_prefix(name, "if:", &s))
1414 v->s = xstrdup(s);
1415 v->handler = if_atom_handler;
1416 continue;
1417 } else if (!strcmp(name, "then")) {
1418 v->handler = then_atom_handler;
1419 continue;
1420 } else if (!strcmp(name, "else")) {
1421 v->handler = else_atom_handler;
1422 continue;
1423 } else
1424 continue;
1426 if (!deref)
1427 v->s = refname;
1428 else
1429 v->s = xstrfmt("%s^{}", refname);
1432 for (i = 0; i < used_atom_cnt; i++) {
1433 struct atom_value *v = &ref->value[i];
1434 if (v->s == NULL)
1435 goto need_obj;
1437 return;
1439 need_obj:
1440 buf = get_obj(&ref->objectname, &obj, &size, &eaten);
1441 if (!buf)
1442 die(_("missing object %s for %s"),
1443 oid_to_hex(&ref->objectname), ref->refname);
1444 if (!obj)
1445 die(_("parse_object_buffer failed on %s for %s"),
1446 oid_to_hex(&ref->objectname), ref->refname);
1448 grab_values(ref->value, 0, obj, buf, size);
1449 if (!eaten)
1450 free(buf);
1453 * If there is no atom that wants to know about tagged
1454 * object, we are done.
1456 if (!need_tagged || (obj->type != OBJ_TAG))
1457 return;
1460 * If it is a tag object, see if we use a value that derefs
1461 * the object, and if we do grab the object it refers to.
1463 tagged = &((struct tag *)obj)->tagged->oid;
1466 * NEEDSWORK: This derefs tag only once, which
1467 * is good to deal with chains of trust, but
1468 * is not consistent with what deref_tag() does
1469 * which peels the onion to the core.
1471 buf = get_obj(tagged, &obj, &size, &eaten);
1472 if (!buf)
1473 die(_("missing object %s for %s"),
1474 oid_to_hex(tagged), ref->refname);
1475 if (!obj)
1476 die(_("parse_object_buffer failed on %s for %s"),
1477 oid_to_hex(tagged), ref->refname);
1478 grab_values(ref->value, 1, obj, buf, size);
1479 if (!eaten)
1480 free(buf);
1484 * Given a ref, return the value for the atom. This lazily gets value
1485 * out of the object by calling populate value.
1487 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1489 if (!ref->value) {
1490 populate_value(ref);
1491 fill_missing_values(ref->value);
1493 *v = &ref->value[atom];
1497 * Unknown has to be "0" here, because that's the default value for
1498 * contains_cache slab entries that have not yet been assigned.
1500 enum contains_result {
1501 CONTAINS_UNKNOWN = 0,
1502 CONTAINS_NO,
1503 CONTAINS_YES
1506 define_commit_slab(contains_cache, enum contains_result);
1508 struct ref_filter_cbdata {
1509 struct ref_array *array;
1510 struct ref_filter *filter;
1511 struct contains_cache contains_cache;
1512 struct contains_cache no_contains_cache;
1516 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1517 * overflows.
1519 * At each recursion step, the stack items points to the commits whose
1520 * ancestors are to be inspected.
1522 struct contains_stack {
1523 int nr, alloc;
1524 struct contains_stack_entry {
1525 struct commit *commit;
1526 struct commit_list *parents;
1527 } *contains_stack;
1530 static int in_commit_list(const struct commit_list *want, struct commit *c)
1532 for (; want; want = want->next)
1533 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1534 return 1;
1535 return 0;
1539 * Test whether the candidate or one of its parents is contained in the list.
1540 * Do not recurse to find out, though, but return -1 if inconclusive.
1542 static enum contains_result contains_test(struct commit *candidate,
1543 const struct commit_list *want,
1544 struct contains_cache *cache)
1546 enum contains_result *cached = contains_cache_at(cache, candidate);
1548 /* If we already have the answer cached, return that. */
1549 if (*cached)
1550 return *cached;
1552 /* or are we it? */
1553 if (in_commit_list(want, candidate)) {
1554 *cached = CONTAINS_YES;
1555 return CONTAINS_YES;
1558 /* Otherwise, we don't know; prepare to recurse */
1559 parse_commit_or_die(candidate);
1560 return CONTAINS_UNKNOWN;
1563 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1565 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1566 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1567 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1570 static enum contains_result contains_tag_algo(struct commit *candidate,
1571 const struct commit_list *want,
1572 struct contains_cache *cache)
1574 struct contains_stack contains_stack = { 0, 0, NULL };
1575 enum contains_result result = contains_test(candidate, want, cache);
1577 if (result != CONTAINS_UNKNOWN)
1578 return result;
1580 push_to_contains_stack(candidate, &contains_stack);
1581 while (contains_stack.nr) {
1582 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1583 struct commit *commit = entry->commit;
1584 struct commit_list *parents = entry->parents;
1586 if (!parents) {
1587 *contains_cache_at(cache, commit) = CONTAINS_NO;
1588 contains_stack.nr--;
1591 * If we just popped the stack, parents->item has been marked,
1592 * therefore contains_test will return a meaningful yes/no.
1594 else switch (contains_test(parents->item, want, cache)) {
1595 case CONTAINS_YES:
1596 *contains_cache_at(cache, commit) = CONTAINS_YES;
1597 contains_stack.nr--;
1598 break;
1599 case CONTAINS_NO:
1600 entry->parents = parents->next;
1601 break;
1602 case CONTAINS_UNKNOWN:
1603 push_to_contains_stack(parents->item, &contains_stack);
1604 break;
1607 free(contains_stack.contains_stack);
1608 return contains_test(candidate, want, cache);
1611 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1612 struct commit_list *list, struct contains_cache *cache)
1614 if (filter->with_commit_tag_algo)
1615 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1616 return is_descendant_of(commit, list);
1620 * Return 1 if the refname matches one of the patterns, otherwise 0.
1621 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1622 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1623 * matches "refs/heads/mas*", too).
1625 static int match_pattern(const struct ref_filter *filter, const char *refname)
1627 const char **patterns = filter->name_patterns;
1628 unsigned flags = 0;
1630 if (filter->ignore_case)
1631 flags |= WM_CASEFOLD;
1634 * When no '--format' option is given we need to skip the prefix
1635 * for matching refs of tags and branches.
1637 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1638 skip_prefix(refname, "refs/heads/", &refname) ||
1639 skip_prefix(refname, "refs/remotes/", &refname) ||
1640 skip_prefix(refname, "refs/", &refname));
1642 for (; *patterns; patterns++) {
1643 if (!wildmatch(*patterns, refname, flags))
1644 return 1;
1646 return 0;
1650 * Return 1 if the refname matches one of the patterns, otherwise 0.
1651 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1652 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1653 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1655 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1657 const char **pattern = filter->name_patterns;
1658 int namelen = strlen(refname);
1659 unsigned flags = WM_PATHNAME;
1661 if (filter->ignore_case)
1662 flags |= WM_CASEFOLD;
1664 for (; *pattern; pattern++) {
1665 const char *p = *pattern;
1666 int plen = strlen(p);
1668 if ((plen <= namelen) &&
1669 !strncmp(refname, p, plen) &&
1670 (refname[plen] == '\0' ||
1671 refname[plen] == '/' ||
1672 p[plen-1] == '/'))
1673 return 1;
1674 if (!wildmatch(p, refname, WM_PATHNAME))
1675 return 1;
1677 return 0;
1680 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1681 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1683 if (!*filter->name_patterns)
1684 return 1; /* No pattern always matches */
1685 if (filter->match_as_path)
1686 return match_name_as_path(filter, refname);
1687 return match_pattern(filter, refname);
1691 * Find the longest prefix of pattern we can pass to
1692 * `for_each_fullref_in()`, namely the part of pattern preceding the
1693 * first glob character. (Note that `for_each_fullref_in()` is
1694 * perfectly happy working with a prefix that doesn't end at a
1695 * pathname component boundary.)
1697 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1699 const char *p;
1701 for (p = pattern; *p && !is_glob_special(*p); p++)
1704 strbuf_add(out, pattern, p - pattern);
1708 * This is the same as for_each_fullref_in(), but it tries to iterate
1709 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1710 * pattern match, so the callback still has to match each ref individually.
1712 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1713 each_ref_fn cb,
1714 void *cb_data,
1715 int broken)
1717 struct strbuf prefix = STRBUF_INIT;
1718 int ret;
1720 if (!filter->match_as_path) {
1722 * in this case, the patterns are applied after
1723 * prefixes like "refs/heads/" etc. are stripped off,
1724 * so we have to look at everything:
1726 return for_each_fullref_in("", cb, cb_data, broken);
1729 if (!filter->name_patterns[0]) {
1730 /* no patterns; we have to look at everything */
1731 return for_each_fullref_in("", cb, cb_data, broken);
1734 if (filter->name_patterns[1]) {
1736 * multiple patterns; in theory this could still work as long
1737 * as the patterns are disjoint. We'd just make multiple calls
1738 * to for_each_ref(). But if they're not disjoint, we'd end up
1739 * reporting the same ref multiple times. So let's punt on that
1740 * for now.
1742 return for_each_fullref_in("", cb, cb_data, broken);
1745 find_longest_prefix(&prefix, filter->name_patterns[0]);
1747 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1748 strbuf_release(&prefix);
1749 return ret;
1753 * Given a ref (sha1, refname), check if the ref belongs to the array
1754 * of sha1s. If the given ref is a tag, check if the given tag points
1755 * at one of the sha1s in the given sha1 array.
1756 * the given sha1_array.
1757 * NEEDSWORK:
1758 * 1. Only a single level of inderection is obtained, we might want to
1759 * change this to account for multiple levels (e.g. annotated tags
1760 * pointing to annotated tags pointing to a commit.)
1761 * 2. As the refs are cached we might know what refname peels to without
1762 * the need to parse the object via parse_object(). peel_ref() might be a
1763 * more efficient alternative to obtain the pointee.
1765 static const struct object_id *match_points_at(struct oid_array *points_at,
1766 const struct object_id *oid,
1767 const char *refname)
1769 const struct object_id *tagged_oid = NULL;
1770 struct object *obj;
1772 if (oid_array_lookup(points_at, oid) >= 0)
1773 return oid;
1774 obj = parse_object(oid);
1775 if (!obj)
1776 die(_("malformed object at '%s'"), refname);
1777 if (obj->type == OBJ_TAG)
1778 tagged_oid = &((struct tag *)obj)->tagged->oid;
1779 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1780 return tagged_oid;
1781 return NULL;
1784 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1785 static struct ref_array_item *new_ref_array_item(const char *refname,
1786 const unsigned char *objectname,
1787 int flag)
1789 struct ref_array_item *ref;
1790 FLEX_ALLOC_STR(ref, refname, refname);
1791 hashcpy(ref->objectname.hash, objectname);
1792 ref->flag = flag;
1794 return ref;
1797 static int ref_kind_from_refname(const char *refname)
1799 unsigned int i;
1801 static struct {
1802 const char *prefix;
1803 unsigned int kind;
1804 } ref_kind[] = {
1805 { "refs/heads/" , FILTER_REFS_BRANCHES },
1806 { "refs/remotes/" , FILTER_REFS_REMOTES },
1807 { "refs/tags/", FILTER_REFS_TAGS}
1810 if (!strcmp(refname, "HEAD"))
1811 return FILTER_REFS_DETACHED_HEAD;
1813 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1814 if (starts_with(refname, ref_kind[i].prefix))
1815 return ref_kind[i].kind;
1818 return FILTER_REFS_OTHERS;
1821 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1823 if (filter->kind == FILTER_REFS_BRANCHES ||
1824 filter->kind == FILTER_REFS_REMOTES ||
1825 filter->kind == FILTER_REFS_TAGS)
1826 return filter->kind;
1827 return ref_kind_from_refname(refname);
1831 * A call-back given to for_each_ref(). Filter refs and keep them for
1832 * later object processing.
1834 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1836 struct ref_filter_cbdata *ref_cbdata = cb_data;
1837 struct ref_filter *filter = ref_cbdata->filter;
1838 struct ref_array_item *ref;
1839 struct commit *commit = NULL;
1840 unsigned int kind;
1842 if (flag & REF_BAD_NAME) {
1843 warning(_("ignoring ref with broken name %s"), refname);
1844 return 0;
1847 if (flag & REF_ISBROKEN) {
1848 warning(_("ignoring broken ref %s"), refname);
1849 return 0;
1852 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1853 kind = filter_ref_kind(filter, refname);
1854 if (!(kind & filter->kind))
1855 return 0;
1857 if (!filter_pattern_match(filter, refname))
1858 return 0;
1860 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1861 return 0;
1864 * A merge filter is applied on refs pointing to commits. Hence
1865 * obtain the commit using the 'oid' available and discard all
1866 * non-commits early. The actual filtering is done later.
1868 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1869 commit = lookup_commit_reference_gently(oid, 1);
1870 if (!commit)
1871 return 0;
1872 /* We perform the filtering for the '--contains' option... */
1873 if (filter->with_commit &&
1874 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1875 return 0;
1876 /* ...or for the `--no-contains' option */
1877 if (filter->no_commit &&
1878 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1879 return 0;
1883 * We do not open the object yet; sort may only need refname
1884 * to do its job and the resulting list may yet to be pruned
1885 * by maxcount logic.
1887 ref = new_ref_array_item(refname, oid->hash, flag);
1888 ref->commit = commit;
1890 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1891 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1892 ref->kind = kind;
1893 return 0;
1896 /* Free memory allocated for a ref_array_item */
1897 static void free_array_item(struct ref_array_item *item)
1899 free((char *)item->symref);
1900 free(item);
1903 /* Free all memory allocated for ref_array */
1904 void ref_array_clear(struct ref_array *array)
1906 int i;
1908 for (i = 0; i < array->nr; i++)
1909 free_array_item(array->items[i]);
1910 FREE_AND_NULL(array->items);
1911 array->nr = array->alloc = 0;
1914 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1916 struct rev_info revs;
1917 int i, old_nr;
1918 struct ref_filter *filter = ref_cbdata->filter;
1919 struct ref_array *array = ref_cbdata->array;
1920 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1922 init_revisions(&revs, NULL);
1924 for (i = 0; i < array->nr; i++) {
1925 struct ref_array_item *item = array->items[i];
1926 add_pending_object(&revs, &item->commit->object, item->refname);
1927 to_clear[i] = item->commit;
1930 filter->merge_commit->object.flags |= UNINTERESTING;
1931 add_pending_object(&revs, &filter->merge_commit->object, "");
1933 revs.limited = 1;
1934 if (prepare_revision_walk(&revs))
1935 die(_("revision walk setup failed"));
1937 old_nr = array->nr;
1938 array->nr = 0;
1940 for (i = 0; i < old_nr; i++) {
1941 struct ref_array_item *item = array->items[i];
1942 struct commit *commit = item->commit;
1944 int is_merged = !!(commit->object.flags & UNINTERESTING);
1946 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1947 array->items[array->nr++] = array->items[i];
1948 else
1949 free_array_item(item);
1952 for (i = 0; i < old_nr; i++)
1953 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1954 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1955 free(to_clear);
1959 * API for filtering a set of refs. Based on the type of refs the user
1960 * has requested, we iterate through those refs and apply filters
1961 * as per the given ref_filter structure and finally store the
1962 * filtered refs in the ref_array structure.
1964 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1966 struct ref_filter_cbdata ref_cbdata;
1967 int ret = 0;
1968 unsigned int broken = 0;
1970 ref_cbdata.array = array;
1971 ref_cbdata.filter = filter;
1973 if (type & FILTER_REFS_INCLUDE_BROKEN)
1974 broken = 1;
1975 filter->kind = type & FILTER_REFS_KIND_MASK;
1977 init_contains_cache(&ref_cbdata.contains_cache);
1978 init_contains_cache(&ref_cbdata.no_contains_cache);
1980 /* Simple per-ref filtering */
1981 if (!filter->kind)
1982 die("filter_refs: invalid type");
1983 else {
1985 * For common cases where we need only branches or remotes or tags,
1986 * we only iterate through those refs. If a mix of refs is needed,
1987 * we iterate over all refs and filter out required refs with the help
1988 * of filter_ref_kind().
1990 if (filter->kind == FILTER_REFS_BRANCHES)
1991 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1992 else if (filter->kind == FILTER_REFS_REMOTES)
1993 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1994 else if (filter->kind == FILTER_REFS_TAGS)
1995 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1996 else if (filter->kind & FILTER_REFS_ALL)
1997 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
1998 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1999 head_ref(ref_filter_handler, &ref_cbdata);
2002 clear_contains_cache(&ref_cbdata.contains_cache);
2003 clear_contains_cache(&ref_cbdata.no_contains_cache);
2005 /* Filters that need revision walking */
2006 if (filter->merge_commit)
2007 do_merge_filter(&ref_cbdata);
2009 return ret;
2012 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2014 struct atom_value *va, *vb;
2015 int cmp;
2016 cmp_type cmp_type = used_atom[s->atom].type;
2017 int (*cmp_fn)(const char *, const char *);
2019 get_ref_atom_value(a, s->atom, &va);
2020 get_ref_atom_value(b, s->atom, &vb);
2021 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2022 if (s->version)
2023 cmp = versioncmp(va->s, vb->s);
2024 else if (cmp_type == FIELD_STR)
2025 cmp = cmp_fn(va->s, vb->s);
2026 else {
2027 if (va->value < vb->value)
2028 cmp = -1;
2029 else if (va->value == vb->value)
2030 cmp = cmp_fn(a->refname, b->refname);
2031 else
2032 cmp = 1;
2035 return (s->reverse) ? -cmp : cmp;
2038 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2040 struct ref_array_item *a = *((struct ref_array_item **)a_);
2041 struct ref_array_item *b = *((struct ref_array_item **)b_);
2042 struct ref_sorting *s;
2044 for (s = ref_sorting; s; s = s->next) {
2045 int cmp = cmp_ref_sorting(s, a, b);
2046 if (cmp)
2047 return cmp;
2049 return 0;
2052 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2054 QSORT_S(array->items, array->nr, compare_refs, sorting);
2057 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2059 struct strbuf *s = &state->stack->output;
2061 while (*cp && (!ep || cp < ep)) {
2062 if (*cp == '%') {
2063 if (cp[1] == '%')
2064 cp++;
2065 else {
2066 int ch = hex2chr(cp + 1);
2067 if (0 <= ch) {
2068 strbuf_addch(s, ch);
2069 cp += 3;
2070 continue;
2074 strbuf_addch(s, *cp);
2075 cp++;
2079 void format_ref_array_item(struct ref_array_item *info,
2080 const struct ref_format *format,
2081 struct strbuf *final_buf)
2083 const char *cp, *sp, *ep;
2084 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2086 state.quote_style = format->quote_style;
2087 push_stack_element(&state.stack);
2089 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2090 struct atom_value *atomv;
2092 ep = strchr(sp, ')');
2093 if (cp < sp)
2094 append_literal(cp, sp, &state);
2095 get_ref_atom_value(info,
2096 parse_ref_filter_atom(format, sp + 2, ep),
2097 &atomv);
2098 atomv->handler(atomv, &state);
2100 if (*cp) {
2101 sp = cp + strlen(cp);
2102 append_literal(cp, sp, &state);
2104 if (format->need_color_reset_at_eol) {
2105 struct atom_value resetv;
2106 resetv.s = GIT_COLOR_RESET;
2107 append_atom(&resetv, &state);
2109 if (state.stack->prev)
2110 die(_("format: %%(end) atom missing"));
2111 strbuf_addbuf(final_buf, &state.stack->output);
2112 pop_stack_element(&state.stack);
2115 void show_ref_array_item(struct ref_array_item *info,
2116 const struct ref_format *format)
2118 struct strbuf final_buf = STRBUF_INIT;
2120 format_ref_array_item(info, format, &final_buf);
2121 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2122 strbuf_release(&final_buf);
2123 putchar('\n');
2126 void pretty_print_ref(const char *name, const unsigned char *sha1,
2127 const struct ref_format *format)
2129 struct ref_array_item *ref_item;
2130 ref_item = new_ref_array_item(name, sha1, 0);
2131 ref_item->kind = ref_kind_from_refname(name);
2132 show_ref_array_item(ref_item, format);
2133 free_array_item(ref_item);
2136 static int parse_sorting_atom(const char *atom)
2139 * This parses an atom using a dummy ref_format, since we don't
2140 * actually care about the formatting details.
2142 struct ref_format dummy = REF_FORMAT_INIT;
2143 const char *end = atom + strlen(atom);
2144 return parse_ref_filter_atom(&dummy, atom, end);
2147 /* If no sorting option is given, use refname to sort as default */
2148 struct ref_sorting *ref_default_sorting(void)
2150 static const char cstr_name[] = "refname";
2152 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2154 sorting->next = NULL;
2155 sorting->atom = parse_sorting_atom(cstr_name);
2156 return sorting;
2159 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2161 struct ref_sorting *s;
2163 s = xcalloc(1, sizeof(*s));
2164 s->next = *sorting_tail;
2165 *sorting_tail = s;
2167 if (*arg == '-') {
2168 s->reverse = 1;
2169 arg++;
2171 if (skip_prefix(arg, "version:", &arg) ||
2172 skip_prefix(arg, "v:", &arg))
2173 s->version = 1;
2174 s->atom = parse_sorting_atom(arg);
2177 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2179 if (!arg) /* should --no-sort void the list ? */
2180 return -1;
2181 parse_ref_sorting(opt->value, arg);
2182 return 0;
2185 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2187 struct ref_filter *rf = opt->value;
2188 struct object_id oid;
2189 int no_merged = starts_with(opt->long_name, "no");
2191 if (rf->merge) {
2192 if (no_merged) {
2193 return opterror(opt, "is incompatible with --merged", 0);
2194 } else {
2195 return opterror(opt, "is incompatible with --no-merged", 0);
2199 rf->merge = no_merged
2200 ? REF_FILTER_MERGED_OMIT
2201 : REF_FILTER_MERGED_INCLUDE;
2203 if (get_oid(arg, &oid))
2204 die(_("malformed object name %s"), arg);
2206 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2207 if (!rf->merge_commit)
2208 return opterror(opt, "must point to a commit", 0);
2210 return 0;