packed_ref_store: implement reference transactions
[git/debian.git] / ref-filter.c
blobbc591f4f3de0c07b0cfe3813d5d9daaf1ad44b63
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 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
421 if (valid_atom[i].parser)
422 valid_atom[i].parser(format, &used_atom[at], arg);
423 if (*atom == '*')
424 need_tagged = 1;
425 if (!strcmp(valid_atom[i].name, "symref"))
426 need_symref = 1;
427 return at;
430 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
432 switch (quote_style) {
433 case QUOTE_NONE:
434 strbuf_addstr(s, str);
435 break;
436 case QUOTE_SHELL:
437 sq_quote_buf(s, str);
438 break;
439 case QUOTE_PERL:
440 perl_quote_buf(s, str);
441 break;
442 case QUOTE_PYTHON:
443 python_quote_buf(s, str);
444 break;
445 case QUOTE_TCL:
446 tcl_quote_buf(s, str);
447 break;
451 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
454 * Quote formatting is only done when the stack has a single
455 * element. Otherwise quote formatting is done on the
456 * element's entire output strbuf when the %(end) atom is
457 * encountered.
459 if (!state->stack->prev)
460 quote_formatting(&state->stack->output, v->s, state->quote_style);
461 else
462 strbuf_addstr(&state->stack->output, v->s);
465 static void push_stack_element(struct ref_formatting_stack **stack)
467 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
469 strbuf_init(&s->output, 0);
470 s->prev = *stack;
471 *stack = s;
474 static void pop_stack_element(struct ref_formatting_stack **stack)
476 struct ref_formatting_stack *current = *stack;
477 struct ref_formatting_stack *prev = current->prev;
479 if (prev)
480 strbuf_addbuf(&prev->output, &current->output);
481 strbuf_release(&current->output);
482 free(current);
483 *stack = prev;
486 static void end_align_handler(struct ref_formatting_stack **stack)
488 struct ref_formatting_stack *cur = *stack;
489 struct align *align = (struct align *)cur->at_end_data;
490 struct strbuf s = STRBUF_INIT;
492 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
493 strbuf_swap(&cur->output, &s);
494 strbuf_release(&s);
497 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
499 struct ref_formatting_stack *new;
501 push_stack_element(&state->stack);
502 new = state->stack;
503 new->at_end = end_align_handler;
504 new->at_end_data = &atomv->atom->u.align;
507 static void if_then_else_handler(struct ref_formatting_stack **stack)
509 struct ref_formatting_stack *cur = *stack;
510 struct ref_formatting_stack *prev = cur->prev;
511 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
513 if (!if_then_else->then_atom_seen)
514 die(_("format: %%(if) atom used without a %%(then) atom"));
516 if (if_then_else->else_atom_seen) {
518 * There is an %(else) atom: we need to drop one state from the
519 * stack, either the %(else) branch if the condition is satisfied, or
520 * the %(then) branch if it isn't.
522 if (if_then_else->condition_satisfied) {
523 strbuf_reset(&cur->output);
524 pop_stack_element(&cur);
525 } else {
526 strbuf_swap(&cur->output, &prev->output);
527 strbuf_reset(&cur->output);
528 pop_stack_element(&cur);
530 } else if (!if_then_else->condition_satisfied) {
532 * No %(else) atom: just drop the %(then) branch if the
533 * condition is not satisfied.
535 strbuf_reset(&cur->output);
538 *stack = cur;
539 free(if_then_else);
542 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
544 struct ref_formatting_stack *new;
545 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
547 if_then_else->str = atomv->atom->u.if_then_else.str;
548 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
550 push_stack_element(&state->stack);
551 new = state->stack;
552 new->at_end = if_then_else_handler;
553 new->at_end_data = if_then_else;
556 static int is_empty(const char *s)
558 while (*s != '\0') {
559 if (!isspace(*s))
560 return 0;
561 s++;
563 return 1;
566 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
568 struct ref_formatting_stack *cur = state->stack;
569 struct if_then_else *if_then_else = NULL;
571 if (cur->at_end == if_then_else_handler)
572 if_then_else = (struct if_then_else *)cur->at_end_data;
573 if (!if_then_else)
574 die(_("format: %%(then) atom used without an %%(if) atom"));
575 if (if_then_else->then_atom_seen)
576 die(_("format: %%(then) atom used more than once"));
577 if (if_then_else->else_atom_seen)
578 die(_("format: %%(then) atom used after %%(else)"));
579 if_then_else->then_atom_seen = 1;
581 * If the 'equals' or 'notequals' attribute is used then
582 * perform the required comparison. If not, only non-empty
583 * strings satisfy the 'if' condition.
585 if (if_then_else->cmp_status == COMPARE_EQUAL) {
586 if (!strcmp(if_then_else->str, cur->output.buf))
587 if_then_else->condition_satisfied = 1;
588 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
589 if (strcmp(if_then_else->str, cur->output.buf))
590 if_then_else->condition_satisfied = 1;
591 } else if (cur->output.len && !is_empty(cur->output.buf))
592 if_then_else->condition_satisfied = 1;
593 strbuf_reset(&cur->output);
596 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
598 struct ref_formatting_stack *prev = state->stack;
599 struct if_then_else *if_then_else = NULL;
601 if (prev->at_end == if_then_else_handler)
602 if_then_else = (struct if_then_else *)prev->at_end_data;
603 if (!if_then_else)
604 die(_("format: %%(else) atom used without an %%(if) atom"));
605 if (!if_then_else->then_atom_seen)
606 die(_("format: %%(else) atom used without a %%(then) atom"));
607 if (if_then_else->else_atom_seen)
608 die(_("format: %%(else) atom used more than once"));
609 if_then_else->else_atom_seen = 1;
610 push_stack_element(&state->stack);
611 state->stack->at_end_data = prev->at_end_data;
612 state->stack->at_end = prev->at_end;
615 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
617 struct ref_formatting_stack *current = state->stack;
618 struct strbuf s = STRBUF_INIT;
620 if (!current->at_end)
621 die(_("format: %%(end) atom used without corresponding atom"));
622 current->at_end(&state->stack);
624 /* Stack may have been popped within at_end(), hence reset the current pointer */
625 current = state->stack;
628 * Perform quote formatting when the stack element is that of
629 * a supporting atom. If nested then perform quote formatting
630 * only on the topmost supporting atom.
632 if (!current->prev->prev) {
633 quote_formatting(&s, current->output.buf, state->quote_style);
634 strbuf_swap(&current->output, &s);
636 strbuf_release(&s);
637 pop_stack_element(&state->stack);
641 * In a format string, find the next occurrence of %(atom).
643 static const char *find_next(const char *cp)
645 while (*cp) {
646 if (*cp == '%') {
648 * %( is the start of an atom;
649 * %% is a quoted per-cent.
651 if (cp[1] == '(')
652 return cp;
653 else if (cp[1] == '%')
654 cp++; /* skip over two % */
655 /* otherwise this is a singleton, literal % */
657 cp++;
659 return NULL;
663 * Make sure the format string is well formed, and parse out
664 * the used atoms.
666 int verify_ref_format(struct ref_format *format)
668 const char *cp, *sp;
670 format->need_color_reset_at_eol = 0;
671 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
672 const char *color, *ep = strchr(sp, ')');
673 int at;
675 if (!ep)
676 return error(_("malformed format string %s"), sp);
677 /* sp points at "%(" and ep points at the closing ")" */
678 at = parse_ref_filter_atom(format, sp + 2, ep);
679 cp = ep + 1;
681 if (skip_prefix(used_atom[at].name, "color:", &color))
682 format->need_color_reset_at_eol = !!strcmp(color, "reset");
684 if (format->need_color_reset_at_eol && !want_color(format->use_color))
685 format->need_color_reset_at_eol = 0;
686 return 0;
690 * Given an object name, read the object data and size, and return a
691 * "struct object". If the object data we are returning is also borrowed
692 * by the "struct object" representation, set *eaten as well---it is a
693 * signal from parse_object_buffer to us not to free the buffer.
695 static void *get_obj(const struct object_id *oid, struct object **obj, unsigned long *sz, int *eaten)
697 enum object_type type;
698 void *buf = read_sha1_file(oid->hash, &type, sz);
700 if (buf)
701 *obj = parse_object_buffer(oid, type, *sz, buf, eaten);
702 else
703 *obj = NULL;
704 return buf;
707 static int grab_objectname(const char *name, const unsigned char *sha1,
708 struct atom_value *v, struct used_atom *atom)
710 if (starts_with(name, "objectname")) {
711 if (atom->u.objectname.option == O_SHORT) {
712 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
713 return 1;
714 } else if (atom->u.objectname.option == O_FULL) {
715 v->s = xstrdup(sha1_to_hex(sha1));
716 return 1;
717 } else if (atom->u.objectname.option == O_LENGTH) {
718 v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
719 return 1;
720 } else
721 die("BUG: unknown %%(objectname) option");
723 return 0;
726 /* See grab_values */
727 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
729 int i;
731 for (i = 0; i < used_atom_cnt; i++) {
732 const char *name = used_atom[i].name;
733 struct atom_value *v = &val[i];
734 if (!!deref != (*name == '*'))
735 continue;
736 if (deref)
737 name++;
738 if (!strcmp(name, "objecttype"))
739 v->s = typename(obj->type);
740 else if (!strcmp(name, "objectsize")) {
741 v->value = sz;
742 v->s = xstrfmt("%lu", sz);
744 else if (deref)
745 grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
749 /* See grab_values */
750 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
752 int i;
753 struct tag *tag = (struct tag *) obj;
755 for (i = 0; i < used_atom_cnt; i++) {
756 const char *name = used_atom[i].name;
757 struct atom_value *v = &val[i];
758 if (!!deref != (*name == '*'))
759 continue;
760 if (deref)
761 name++;
762 if (!strcmp(name, "tag"))
763 v->s = tag->tag;
764 else if (!strcmp(name, "type") && tag->tagged)
765 v->s = typename(tag->tagged->type);
766 else if (!strcmp(name, "object") && tag->tagged)
767 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
771 /* See grab_values */
772 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
774 int i;
775 struct commit *commit = (struct commit *) obj;
777 for (i = 0; i < used_atom_cnt; i++) {
778 const char *name = used_atom[i].name;
779 struct atom_value *v = &val[i];
780 if (!!deref != (*name == '*'))
781 continue;
782 if (deref)
783 name++;
784 if (!strcmp(name, "tree")) {
785 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
787 else if (!strcmp(name, "numparent")) {
788 v->value = commit_list_count(commit->parents);
789 v->s = xstrfmt("%lu", (unsigned long)v->value);
791 else if (!strcmp(name, "parent")) {
792 struct commit_list *parents;
793 struct strbuf s = STRBUF_INIT;
794 for (parents = commit->parents; parents; parents = parents->next) {
795 struct commit *parent = parents->item;
796 if (parents != commit->parents)
797 strbuf_addch(&s, ' ');
798 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
800 v->s = strbuf_detach(&s, NULL);
805 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
807 const char *eol;
808 while (*buf) {
809 if (!strncmp(buf, who, wholen) &&
810 buf[wholen] == ' ')
811 return buf + wholen + 1;
812 eol = strchr(buf, '\n');
813 if (!eol)
814 return "";
815 eol++;
816 if (*eol == '\n')
817 return ""; /* end of header */
818 buf = eol;
820 return "";
823 static const char *copy_line(const char *buf)
825 const char *eol = strchrnul(buf, '\n');
826 return xmemdupz(buf, eol - buf);
829 static const char *copy_name(const char *buf)
831 const char *cp;
832 for (cp = buf; *cp && *cp != '\n'; cp++) {
833 if (!strncmp(cp, " <", 2))
834 return xmemdupz(buf, cp - buf);
836 return "";
839 static const char *copy_email(const char *buf)
841 const char *email = strchr(buf, '<');
842 const char *eoemail;
843 if (!email)
844 return "";
845 eoemail = strchr(email, '>');
846 if (!eoemail)
847 return "";
848 return xmemdupz(email, eoemail + 1 - email);
851 static char *copy_subject(const char *buf, unsigned long len)
853 char *r = xmemdupz(buf, len);
854 int i;
856 for (i = 0; i < len; i++)
857 if (r[i] == '\n')
858 r[i] = ' ';
860 return r;
863 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
865 const char *eoemail = strstr(buf, "> ");
866 char *zone;
867 timestamp_t timestamp;
868 long tz;
869 struct date_mode date_mode = { DATE_NORMAL };
870 const char *formatp;
873 * We got here because atomname ends in "date" or "date<something>";
874 * it's not possible that <something> is not ":<format>" because
875 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
876 * ":" means no format is specified, and use the default.
878 formatp = strchr(atomname, ':');
879 if (formatp != NULL) {
880 formatp++;
881 parse_date_format(formatp, &date_mode);
884 if (!eoemail)
885 goto bad;
886 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
887 if (timestamp == TIME_MAX)
888 goto bad;
889 tz = strtol(zone, NULL, 10);
890 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
891 goto bad;
892 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
893 v->value = timestamp;
894 return;
895 bad:
896 v->s = "";
897 v->value = 0;
900 /* See grab_values */
901 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
903 int i;
904 int wholen = strlen(who);
905 const char *wholine = NULL;
907 for (i = 0; i < used_atom_cnt; i++) {
908 const char *name = used_atom[i].name;
909 struct atom_value *v = &val[i];
910 if (!!deref != (*name == '*'))
911 continue;
912 if (deref)
913 name++;
914 if (strncmp(who, name, wholen))
915 continue;
916 if (name[wholen] != 0 &&
917 strcmp(name + wholen, "name") &&
918 strcmp(name + wholen, "email") &&
919 !starts_with(name + wholen, "date"))
920 continue;
921 if (!wholine)
922 wholine = find_wholine(who, wholen, buf, sz);
923 if (!wholine)
924 return; /* no point looking for it */
925 if (name[wholen] == 0)
926 v->s = copy_line(wholine);
927 else if (!strcmp(name + wholen, "name"))
928 v->s = copy_name(wholine);
929 else if (!strcmp(name + wholen, "email"))
930 v->s = copy_email(wholine);
931 else if (starts_with(name + wholen, "date"))
932 grab_date(wholine, v, name);
936 * For a tag or a commit object, if "creator" or "creatordate" is
937 * requested, do something special.
939 if (strcmp(who, "tagger") && strcmp(who, "committer"))
940 return; /* "author" for commit object is not wanted */
941 if (!wholine)
942 wholine = find_wholine(who, wholen, buf, sz);
943 if (!wholine)
944 return;
945 for (i = 0; i < used_atom_cnt; i++) {
946 const char *name = used_atom[i].name;
947 struct atom_value *v = &val[i];
948 if (!!deref != (*name == '*'))
949 continue;
950 if (deref)
951 name++;
953 if (starts_with(name, "creatordate"))
954 grab_date(wholine, v, name);
955 else if (!strcmp(name, "creator"))
956 v->s = copy_line(wholine);
960 static void find_subpos(const char *buf, unsigned long sz,
961 const char **sub, unsigned long *sublen,
962 const char **body, unsigned long *bodylen,
963 unsigned long *nonsiglen,
964 const char **sig, unsigned long *siglen)
966 const char *eol;
967 /* skip past header until we hit empty line */
968 while (*buf && *buf != '\n') {
969 eol = strchrnul(buf, '\n');
970 if (*eol)
971 eol++;
972 buf = eol;
974 /* skip any empty lines */
975 while (*buf == '\n')
976 buf++;
978 /* parse signature first; we might not even have a subject line */
979 *sig = buf + parse_signature(buf, strlen(buf));
980 *siglen = strlen(*sig);
982 /* subject is first non-empty line */
983 *sub = buf;
984 /* subject goes to first empty line */
985 while (buf < *sig && *buf && *buf != '\n') {
986 eol = strchrnul(buf, '\n');
987 if (*eol)
988 eol++;
989 buf = eol;
991 *sublen = buf - *sub;
992 /* drop trailing newline, if present */
993 if (*sublen && (*sub)[*sublen - 1] == '\n')
994 *sublen -= 1;
996 /* skip any empty lines */
997 while (*buf == '\n')
998 buf++;
999 *body = buf;
1000 *bodylen = strlen(buf);
1001 *nonsiglen = *sig - buf;
1005 * If 'lines' is greater than 0, append that many lines from the given
1006 * 'buf' of length 'size' to the given strbuf.
1008 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1010 int i;
1011 const char *sp, *eol;
1012 size_t len;
1014 sp = buf;
1016 for (i = 0; i < lines && sp < buf + size; i++) {
1017 if (i)
1018 strbuf_addstr(out, "\n ");
1019 eol = memchr(sp, '\n', size - (sp - buf));
1020 len = eol ? eol - sp : size - (sp - buf);
1021 strbuf_add(out, sp, len);
1022 if (!eol)
1023 break;
1024 sp = eol + 1;
1028 /* See grab_values */
1029 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1031 int i;
1032 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1033 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1035 for (i = 0; i < used_atom_cnt; i++) {
1036 struct used_atom *atom = &used_atom[i];
1037 const char *name = atom->name;
1038 struct atom_value *v = &val[i];
1039 if (!!deref != (*name == '*'))
1040 continue;
1041 if (deref)
1042 name++;
1043 if (strcmp(name, "subject") &&
1044 strcmp(name, "body") &&
1045 strcmp(name, "trailers") &&
1046 !starts_with(name, "contents"))
1047 continue;
1048 if (!subpos)
1049 find_subpos(buf, sz,
1050 &subpos, &sublen,
1051 &bodypos, &bodylen, &nonsiglen,
1052 &sigpos, &siglen);
1054 if (atom->u.contents.option == C_SUB)
1055 v->s = copy_subject(subpos, sublen);
1056 else if (atom->u.contents.option == C_BODY_DEP)
1057 v->s = xmemdupz(bodypos, bodylen);
1058 else if (atom->u.contents.option == C_BODY)
1059 v->s = xmemdupz(bodypos, nonsiglen);
1060 else if (atom->u.contents.option == C_SIG)
1061 v->s = xmemdupz(sigpos, siglen);
1062 else if (atom->u.contents.option == C_LINES) {
1063 struct strbuf s = STRBUF_INIT;
1064 const char *contents_end = bodylen + bodypos - siglen;
1066 /* Size is the length of the message after removing the signature */
1067 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1068 v->s = strbuf_detach(&s, NULL);
1069 } else if (atom->u.contents.option == C_TRAILERS) {
1070 struct trailer_info info;
1072 /* Search for trailer info */
1073 trailer_info_get(&info, subpos);
1074 v->s = xmemdupz(info.trailer_start,
1075 info.trailer_end - info.trailer_start);
1076 trailer_info_release(&info);
1077 } else if (atom->u.contents.option == C_BARE)
1078 v->s = xstrdup(subpos);
1083 * We want to have empty print-string for field requests
1084 * that do not apply (e.g. "authordate" for a tag object)
1086 static void fill_missing_values(struct atom_value *val)
1088 int i;
1089 for (i = 0; i < used_atom_cnt; i++) {
1090 struct atom_value *v = &val[i];
1091 if (v->s == NULL)
1092 v->s = "";
1097 * val is a list of atom_value to hold returned values. Extract
1098 * the values for atoms in used_atom array out of (obj, buf, sz).
1099 * when deref is false, (obj, buf, sz) is the object that is
1100 * pointed at by the ref itself; otherwise it is the object the
1101 * ref (which is a tag) refers to.
1103 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1105 grab_common_values(val, deref, obj, buf, sz);
1106 switch (obj->type) {
1107 case OBJ_TAG:
1108 grab_tag_values(val, deref, obj, buf, sz);
1109 grab_sub_body_contents(val, deref, obj, buf, sz);
1110 grab_person("tagger", val, deref, obj, buf, sz);
1111 break;
1112 case OBJ_COMMIT:
1113 grab_commit_values(val, deref, obj, buf, sz);
1114 grab_sub_body_contents(val, deref, obj, buf, sz);
1115 grab_person("author", val, deref, obj, buf, sz);
1116 grab_person("committer", val, deref, obj, buf, sz);
1117 break;
1118 case OBJ_TREE:
1119 /* grab_tree_values(val, deref, obj, buf, sz); */
1120 break;
1121 case OBJ_BLOB:
1122 /* grab_blob_values(val, deref, obj, buf, sz); */
1123 break;
1124 default:
1125 die("Eh? Object of type %d?", obj->type);
1129 static inline char *copy_advance(char *dst, const char *src)
1131 while (*src)
1132 *dst++ = *src++;
1133 return dst;
1136 static const char *lstrip_ref_components(const char *refname, int len)
1138 long remaining = len;
1139 const char *start = refname;
1141 if (len < 0) {
1142 int i;
1143 const char *p = refname;
1145 /* Find total no of '/' separated path-components */
1146 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1149 * The number of components we need to strip is now
1150 * the total minus the components to be left (Plus one
1151 * because we count the number of '/', but the number
1152 * of components is one more than the no of '/').
1154 remaining = i + len + 1;
1157 while (remaining > 0) {
1158 switch (*start++) {
1159 case '\0':
1160 return "";
1161 case '/':
1162 remaining--;
1163 break;
1167 return start;
1170 static const char *rstrip_ref_components(const char *refname, int len)
1172 long remaining = len;
1173 char *start = xstrdup(refname);
1175 if (len < 0) {
1176 int i;
1177 const char *p = refname;
1179 /* Find total no of '/' separated path-components */
1180 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1183 * The number of components we need to strip is now
1184 * the total minus the components to be left (Plus one
1185 * because we count the number of '/', but the number
1186 * of components is one more than the no of '/').
1188 remaining = i + len + 1;
1191 while (remaining-- > 0) {
1192 char *p = strrchr(start, '/');
1193 if (p == NULL)
1194 return "";
1195 else
1196 p[0] = '\0';
1198 return start;
1201 static const char *show_ref(struct refname_atom *atom, const char *refname)
1203 if (atom->option == R_SHORT)
1204 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1205 else if (atom->option == R_LSTRIP)
1206 return lstrip_ref_components(refname, atom->lstrip);
1207 else if (atom->option == R_RSTRIP)
1208 return rstrip_ref_components(refname, atom->rstrip);
1209 else
1210 return refname;
1213 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1214 struct branch *branch, const char **s)
1216 int num_ours, num_theirs;
1217 if (atom->u.remote_ref.option == RR_REF)
1218 *s = show_ref(&atom->u.remote_ref.refname, refname);
1219 else if (atom->u.remote_ref.option == RR_TRACK) {
1220 if (stat_tracking_info(branch, &num_ours,
1221 &num_theirs, NULL)) {
1222 *s = xstrdup(msgs.gone);
1223 } else if (!num_ours && !num_theirs)
1224 *s = "";
1225 else if (!num_ours)
1226 *s = xstrfmt(msgs.behind, num_theirs);
1227 else if (!num_theirs)
1228 *s = xstrfmt(msgs.ahead, num_ours);
1229 else
1230 *s = xstrfmt(msgs.ahead_behind,
1231 num_ours, num_theirs);
1232 if (!atom->u.remote_ref.nobracket && *s[0]) {
1233 const char *to_free = *s;
1234 *s = xstrfmt("[%s]", *s);
1235 free((void *)to_free);
1237 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1238 if (stat_tracking_info(branch, &num_ours,
1239 &num_theirs, NULL))
1240 return;
1242 if (!num_ours && !num_theirs)
1243 *s = "=";
1244 else if (!num_ours)
1245 *s = "<";
1246 else if (!num_theirs)
1247 *s = ">";
1248 else
1249 *s = "<>";
1250 } else
1251 die("BUG: unhandled RR_* enum");
1254 char *get_head_description(void)
1256 struct strbuf desc = STRBUF_INIT;
1257 struct wt_status_state state;
1258 memset(&state, 0, sizeof(state));
1259 wt_status_get_state(&state, 1);
1260 if (state.rebase_in_progress ||
1261 state.rebase_interactive_in_progress)
1262 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1263 state.branch);
1264 else if (state.bisect_in_progress)
1265 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1266 state.branch);
1267 else if (state.detached_from) {
1268 if (state.detached_at)
1270 * TRANSLATORS: make sure this matches "HEAD
1271 * detached at " in wt-status.c
1273 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1274 state.detached_from);
1275 else
1277 * TRANSLATORS: make sure this matches "HEAD
1278 * detached from " in wt-status.c
1280 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1281 state.detached_from);
1283 else
1284 strbuf_addstr(&desc, _("(no branch)"));
1285 free(state.branch);
1286 free(state.onto);
1287 free(state.detached_from);
1288 return strbuf_detach(&desc, NULL);
1291 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1293 if (!ref->symref)
1294 return "";
1295 else
1296 return show_ref(&atom->u.refname, ref->symref);
1299 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1301 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1302 return get_head_description();
1303 return show_ref(&atom->u.refname, ref->refname);
1307 * Parse the object referred by ref, and grab needed value.
1309 static void populate_value(struct ref_array_item *ref)
1311 void *buf;
1312 struct object *obj;
1313 int eaten, i;
1314 unsigned long size;
1315 const struct object_id *tagged;
1317 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1319 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1320 struct object_id unused1;
1321 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1322 unused1.hash, NULL);
1323 if (!ref->symref)
1324 ref->symref = "";
1327 /* Fill in specials first */
1328 for (i = 0; i < used_atom_cnt; i++) {
1329 struct used_atom *atom = &used_atom[i];
1330 const char *name = used_atom[i].name;
1331 struct atom_value *v = &ref->value[i];
1332 int deref = 0;
1333 const char *refname;
1334 struct branch *branch = NULL;
1336 v->handler = append_atom;
1337 v->atom = atom;
1339 if (*name == '*') {
1340 deref = 1;
1341 name++;
1344 if (starts_with(name, "refname"))
1345 refname = get_refname(atom, ref);
1346 else if (starts_with(name, "symref"))
1347 refname = get_symref(atom, ref);
1348 else if (starts_with(name, "upstream")) {
1349 const char *branch_name;
1350 /* only local branches may have an upstream */
1351 if (!skip_prefix(ref->refname, "refs/heads/",
1352 &branch_name))
1353 continue;
1354 branch = branch_get(branch_name);
1356 refname = branch_get_upstream(branch, NULL);
1357 if (refname)
1358 fill_remote_ref_details(atom, refname, branch, &v->s);
1359 continue;
1360 } else if (starts_with(name, "push")) {
1361 const char *branch_name;
1362 if (!skip_prefix(ref->refname, "refs/heads/",
1363 &branch_name))
1364 continue;
1365 branch = branch_get(branch_name);
1367 refname = branch_get_push(branch, NULL);
1368 if (!refname)
1369 continue;
1370 fill_remote_ref_details(atom, refname, branch, &v->s);
1371 continue;
1372 } else if (starts_with(name, "color:")) {
1373 v->s = atom->u.color;
1374 continue;
1375 } else if (!strcmp(name, "flag")) {
1376 char buf[256], *cp = buf;
1377 if (ref->flag & REF_ISSYMREF)
1378 cp = copy_advance(cp, ",symref");
1379 if (ref->flag & REF_ISPACKED)
1380 cp = copy_advance(cp, ",packed");
1381 if (cp == buf)
1382 v->s = "";
1383 else {
1384 *cp = '\0';
1385 v->s = xstrdup(buf + 1);
1387 continue;
1388 } else if (!deref && grab_objectname(name, ref->objectname.hash, v, atom)) {
1389 continue;
1390 } else if (!strcmp(name, "HEAD")) {
1391 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1392 v->s = "*";
1393 else
1394 v->s = " ";
1395 continue;
1396 } else if (starts_with(name, "align")) {
1397 v->handler = align_atom_handler;
1398 continue;
1399 } else if (!strcmp(name, "end")) {
1400 v->handler = end_atom_handler;
1401 continue;
1402 } else if (starts_with(name, "if")) {
1403 const char *s;
1405 if (skip_prefix(name, "if:", &s))
1406 v->s = xstrdup(s);
1407 v->handler = if_atom_handler;
1408 continue;
1409 } else if (!strcmp(name, "then")) {
1410 v->handler = then_atom_handler;
1411 continue;
1412 } else if (!strcmp(name, "else")) {
1413 v->handler = else_atom_handler;
1414 continue;
1415 } else
1416 continue;
1418 if (!deref)
1419 v->s = refname;
1420 else
1421 v->s = xstrfmt("%s^{}", refname);
1424 for (i = 0; i < used_atom_cnt; i++) {
1425 struct atom_value *v = &ref->value[i];
1426 if (v->s == NULL)
1427 goto need_obj;
1429 return;
1431 need_obj:
1432 buf = get_obj(&ref->objectname, &obj, &size, &eaten);
1433 if (!buf)
1434 die(_("missing object %s for %s"),
1435 oid_to_hex(&ref->objectname), ref->refname);
1436 if (!obj)
1437 die(_("parse_object_buffer failed on %s for %s"),
1438 oid_to_hex(&ref->objectname), ref->refname);
1440 grab_values(ref->value, 0, obj, buf, size);
1441 if (!eaten)
1442 free(buf);
1445 * If there is no atom that wants to know about tagged
1446 * object, we are done.
1448 if (!need_tagged || (obj->type != OBJ_TAG))
1449 return;
1452 * If it is a tag object, see if we use a value that derefs
1453 * the object, and if we do grab the object it refers to.
1455 tagged = &((struct tag *)obj)->tagged->oid;
1458 * NEEDSWORK: This derefs tag only once, which
1459 * is good to deal with chains of trust, but
1460 * is not consistent with what deref_tag() does
1461 * which peels the onion to the core.
1463 buf = get_obj(tagged, &obj, &size, &eaten);
1464 if (!buf)
1465 die(_("missing object %s for %s"),
1466 oid_to_hex(tagged), ref->refname);
1467 if (!obj)
1468 die(_("parse_object_buffer failed on %s for %s"),
1469 oid_to_hex(tagged), ref->refname);
1470 grab_values(ref->value, 1, obj, buf, size);
1471 if (!eaten)
1472 free(buf);
1476 * Given a ref, return the value for the atom. This lazily gets value
1477 * out of the object by calling populate value.
1479 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1481 if (!ref->value) {
1482 populate_value(ref);
1483 fill_missing_values(ref->value);
1485 *v = &ref->value[atom];
1489 * Unknown has to be "0" here, because that's the default value for
1490 * contains_cache slab entries that have not yet been assigned.
1492 enum contains_result {
1493 CONTAINS_UNKNOWN = 0,
1494 CONTAINS_NO,
1495 CONTAINS_YES
1498 define_commit_slab(contains_cache, enum contains_result);
1500 struct ref_filter_cbdata {
1501 struct ref_array *array;
1502 struct ref_filter *filter;
1503 struct contains_cache contains_cache;
1504 struct contains_cache no_contains_cache;
1508 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1509 * overflows.
1511 * At each recursion step, the stack items points to the commits whose
1512 * ancestors are to be inspected.
1514 struct contains_stack {
1515 int nr, alloc;
1516 struct contains_stack_entry {
1517 struct commit *commit;
1518 struct commit_list *parents;
1519 } *contains_stack;
1522 static int in_commit_list(const struct commit_list *want, struct commit *c)
1524 for (; want; want = want->next)
1525 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1526 return 1;
1527 return 0;
1531 * Test whether the candidate or one of its parents is contained in the list.
1532 * Do not recurse to find out, though, but return -1 if inconclusive.
1534 static enum contains_result contains_test(struct commit *candidate,
1535 const struct commit_list *want,
1536 struct contains_cache *cache)
1538 enum contains_result *cached = contains_cache_at(cache, candidate);
1540 /* If we already have the answer cached, return that. */
1541 if (*cached)
1542 return *cached;
1544 /* or are we it? */
1545 if (in_commit_list(want, candidate)) {
1546 *cached = CONTAINS_YES;
1547 return CONTAINS_YES;
1550 /* Otherwise, we don't know; prepare to recurse */
1551 parse_commit_or_die(candidate);
1552 return CONTAINS_UNKNOWN;
1555 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1557 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1558 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1559 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1562 static enum contains_result contains_tag_algo(struct commit *candidate,
1563 const struct commit_list *want,
1564 struct contains_cache *cache)
1566 struct contains_stack contains_stack = { 0, 0, NULL };
1567 enum contains_result result = contains_test(candidate, want, cache);
1569 if (result != CONTAINS_UNKNOWN)
1570 return result;
1572 push_to_contains_stack(candidate, &contains_stack);
1573 while (contains_stack.nr) {
1574 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1575 struct commit *commit = entry->commit;
1576 struct commit_list *parents = entry->parents;
1578 if (!parents) {
1579 *contains_cache_at(cache, commit) = CONTAINS_NO;
1580 contains_stack.nr--;
1583 * If we just popped the stack, parents->item has been marked,
1584 * therefore contains_test will return a meaningful yes/no.
1586 else switch (contains_test(parents->item, want, cache)) {
1587 case CONTAINS_YES:
1588 *contains_cache_at(cache, commit) = CONTAINS_YES;
1589 contains_stack.nr--;
1590 break;
1591 case CONTAINS_NO:
1592 entry->parents = parents->next;
1593 break;
1594 case CONTAINS_UNKNOWN:
1595 push_to_contains_stack(parents->item, &contains_stack);
1596 break;
1599 free(contains_stack.contains_stack);
1600 return contains_test(candidate, want, cache);
1603 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1604 struct commit_list *list, struct contains_cache *cache)
1606 if (filter->with_commit_tag_algo)
1607 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1608 return is_descendant_of(commit, list);
1612 * Return 1 if the refname matches one of the patterns, otherwise 0.
1613 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1614 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1615 * matches "refs/heads/mas*", too).
1617 static int match_pattern(const struct ref_filter *filter, const char *refname)
1619 const char **patterns = filter->name_patterns;
1620 unsigned flags = 0;
1622 if (filter->ignore_case)
1623 flags |= WM_CASEFOLD;
1626 * When no '--format' option is given we need to skip the prefix
1627 * for matching refs of tags and branches.
1629 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1630 skip_prefix(refname, "refs/heads/", &refname) ||
1631 skip_prefix(refname, "refs/remotes/", &refname) ||
1632 skip_prefix(refname, "refs/", &refname));
1634 for (; *patterns; patterns++) {
1635 if (!wildmatch(*patterns, refname, flags))
1636 return 1;
1638 return 0;
1642 * Return 1 if the refname matches one of the patterns, otherwise 0.
1643 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1644 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1645 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1647 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1649 const char **pattern = filter->name_patterns;
1650 int namelen = strlen(refname);
1651 unsigned flags = WM_PATHNAME;
1653 if (filter->ignore_case)
1654 flags |= WM_CASEFOLD;
1656 for (; *pattern; pattern++) {
1657 const char *p = *pattern;
1658 int plen = strlen(p);
1660 if ((plen <= namelen) &&
1661 !strncmp(refname, p, plen) &&
1662 (refname[plen] == '\0' ||
1663 refname[plen] == '/' ||
1664 p[plen-1] == '/'))
1665 return 1;
1666 if (!wildmatch(p, refname, WM_PATHNAME))
1667 return 1;
1669 return 0;
1672 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1673 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1675 if (!*filter->name_patterns)
1676 return 1; /* No pattern always matches */
1677 if (filter->match_as_path)
1678 return match_name_as_path(filter, refname);
1679 return match_pattern(filter, refname);
1683 * Find the longest prefix of pattern we can pass to
1684 * `for_each_fullref_in()`, namely the part of pattern preceding the
1685 * first glob character. (Note that `for_each_fullref_in()` is
1686 * perfectly happy working with a prefix that doesn't end at a
1687 * pathname component boundary.)
1689 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1691 const char *p;
1693 for (p = pattern; *p && !is_glob_special(*p); p++)
1696 strbuf_add(out, pattern, p - pattern);
1700 * This is the same as for_each_fullref_in(), but it tries to iterate
1701 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1702 * pattern match, so the callback still has to match each ref individually.
1704 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1705 each_ref_fn cb,
1706 void *cb_data,
1707 int broken)
1709 struct strbuf prefix = STRBUF_INIT;
1710 int ret;
1712 if (!filter->match_as_path) {
1714 * in this case, the patterns are applied after
1715 * prefixes like "refs/heads/" etc. are stripped off,
1716 * so we have to look at everything:
1718 return for_each_fullref_in("", cb, cb_data, broken);
1721 if (!filter->name_patterns[0]) {
1722 /* no patterns; we have to look at everything */
1723 return for_each_fullref_in("", cb, cb_data, broken);
1726 if (filter->name_patterns[1]) {
1728 * multiple patterns; in theory this could still work as long
1729 * as the patterns are disjoint. We'd just make multiple calls
1730 * to for_each_ref(). But if they're not disjoint, we'd end up
1731 * reporting the same ref multiple times. So let's punt on that
1732 * for now.
1734 return for_each_fullref_in("", cb, cb_data, broken);
1737 find_longest_prefix(&prefix, filter->name_patterns[0]);
1739 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1740 strbuf_release(&prefix);
1741 return ret;
1745 * Given a ref (sha1, refname), check if the ref belongs to the array
1746 * of sha1s. If the given ref is a tag, check if the given tag points
1747 * at one of the sha1s in the given sha1 array.
1748 * the given sha1_array.
1749 * NEEDSWORK:
1750 * 1. Only a single level of inderection is obtained, we might want to
1751 * change this to account for multiple levels (e.g. annotated tags
1752 * pointing to annotated tags pointing to a commit.)
1753 * 2. As the refs are cached we might know what refname peels to without
1754 * the need to parse the object via parse_object(). peel_ref() might be a
1755 * more efficient alternative to obtain the pointee.
1757 static const struct object_id *match_points_at(struct oid_array *points_at,
1758 const struct object_id *oid,
1759 const char *refname)
1761 const struct object_id *tagged_oid = NULL;
1762 struct object *obj;
1764 if (oid_array_lookup(points_at, oid) >= 0)
1765 return oid;
1766 obj = parse_object(oid);
1767 if (!obj)
1768 die(_("malformed object at '%s'"), refname);
1769 if (obj->type == OBJ_TAG)
1770 tagged_oid = &((struct tag *)obj)->tagged->oid;
1771 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1772 return tagged_oid;
1773 return NULL;
1776 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1777 static struct ref_array_item *new_ref_array_item(const char *refname,
1778 const unsigned char *objectname,
1779 int flag)
1781 struct ref_array_item *ref;
1782 FLEX_ALLOC_STR(ref, refname, refname);
1783 hashcpy(ref->objectname.hash, objectname);
1784 ref->flag = flag;
1786 return ref;
1789 static int ref_kind_from_refname(const char *refname)
1791 unsigned int i;
1793 static struct {
1794 const char *prefix;
1795 unsigned int kind;
1796 } ref_kind[] = {
1797 { "refs/heads/" , FILTER_REFS_BRANCHES },
1798 { "refs/remotes/" , FILTER_REFS_REMOTES },
1799 { "refs/tags/", FILTER_REFS_TAGS}
1802 if (!strcmp(refname, "HEAD"))
1803 return FILTER_REFS_DETACHED_HEAD;
1805 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1806 if (starts_with(refname, ref_kind[i].prefix))
1807 return ref_kind[i].kind;
1810 return FILTER_REFS_OTHERS;
1813 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1815 if (filter->kind == FILTER_REFS_BRANCHES ||
1816 filter->kind == FILTER_REFS_REMOTES ||
1817 filter->kind == FILTER_REFS_TAGS)
1818 return filter->kind;
1819 return ref_kind_from_refname(refname);
1823 * A call-back given to for_each_ref(). Filter refs and keep them for
1824 * later object processing.
1826 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1828 struct ref_filter_cbdata *ref_cbdata = cb_data;
1829 struct ref_filter *filter = ref_cbdata->filter;
1830 struct ref_array_item *ref;
1831 struct commit *commit = NULL;
1832 unsigned int kind;
1834 if (flag & REF_BAD_NAME) {
1835 warning(_("ignoring ref with broken name %s"), refname);
1836 return 0;
1839 if (flag & REF_ISBROKEN) {
1840 warning(_("ignoring broken ref %s"), refname);
1841 return 0;
1844 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1845 kind = filter_ref_kind(filter, refname);
1846 if (!(kind & filter->kind))
1847 return 0;
1849 if (!filter_pattern_match(filter, refname))
1850 return 0;
1852 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1853 return 0;
1856 * A merge filter is applied on refs pointing to commits. Hence
1857 * obtain the commit using the 'oid' available and discard all
1858 * non-commits early. The actual filtering is done later.
1860 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1861 commit = lookup_commit_reference_gently(oid, 1);
1862 if (!commit)
1863 return 0;
1864 /* We perform the filtering for the '--contains' option... */
1865 if (filter->with_commit &&
1866 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1867 return 0;
1868 /* ...or for the `--no-contains' option */
1869 if (filter->no_commit &&
1870 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1871 return 0;
1875 * We do not open the object yet; sort may only need refname
1876 * to do its job and the resulting list may yet to be pruned
1877 * by maxcount logic.
1879 ref = new_ref_array_item(refname, oid->hash, flag);
1880 ref->commit = commit;
1882 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1883 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1884 ref->kind = kind;
1885 return 0;
1888 /* Free memory allocated for a ref_array_item */
1889 static void free_array_item(struct ref_array_item *item)
1891 free((char *)item->symref);
1892 free(item);
1895 /* Free all memory allocated for ref_array */
1896 void ref_array_clear(struct ref_array *array)
1898 int i;
1900 for (i = 0; i < array->nr; i++)
1901 free_array_item(array->items[i]);
1902 FREE_AND_NULL(array->items);
1903 array->nr = array->alloc = 0;
1906 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1908 struct rev_info revs;
1909 int i, old_nr;
1910 struct ref_filter *filter = ref_cbdata->filter;
1911 struct ref_array *array = ref_cbdata->array;
1912 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1914 init_revisions(&revs, NULL);
1916 for (i = 0; i < array->nr; i++) {
1917 struct ref_array_item *item = array->items[i];
1918 add_pending_object(&revs, &item->commit->object, item->refname);
1919 to_clear[i] = item->commit;
1922 filter->merge_commit->object.flags |= UNINTERESTING;
1923 add_pending_object(&revs, &filter->merge_commit->object, "");
1925 revs.limited = 1;
1926 if (prepare_revision_walk(&revs))
1927 die(_("revision walk setup failed"));
1929 old_nr = array->nr;
1930 array->nr = 0;
1932 for (i = 0; i < old_nr; i++) {
1933 struct ref_array_item *item = array->items[i];
1934 struct commit *commit = item->commit;
1936 int is_merged = !!(commit->object.flags & UNINTERESTING);
1938 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1939 array->items[array->nr++] = array->items[i];
1940 else
1941 free_array_item(item);
1944 for (i = 0; i < old_nr; i++)
1945 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1946 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1947 free(to_clear);
1951 * API for filtering a set of refs. Based on the type of refs the user
1952 * has requested, we iterate through those refs and apply filters
1953 * as per the given ref_filter structure and finally store the
1954 * filtered refs in the ref_array structure.
1956 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1958 struct ref_filter_cbdata ref_cbdata;
1959 int ret = 0;
1960 unsigned int broken = 0;
1962 ref_cbdata.array = array;
1963 ref_cbdata.filter = filter;
1965 if (type & FILTER_REFS_INCLUDE_BROKEN)
1966 broken = 1;
1967 filter->kind = type & FILTER_REFS_KIND_MASK;
1969 init_contains_cache(&ref_cbdata.contains_cache);
1970 init_contains_cache(&ref_cbdata.no_contains_cache);
1972 /* Simple per-ref filtering */
1973 if (!filter->kind)
1974 die("filter_refs: invalid type");
1975 else {
1977 * For common cases where we need only branches or remotes or tags,
1978 * we only iterate through those refs. If a mix of refs is needed,
1979 * we iterate over all refs and filter out required refs with the help
1980 * of filter_ref_kind().
1982 if (filter->kind == FILTER_REFS_BRANCHES)
1983 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1984 else if (filter->kind == FILTER_REFS_REMOTES)
1985 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1986 else if (filter->kind == FILTER_REFS_TAGS)
1987 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1988 else if (filter->kind & FILTER_REFS_ALL)
1989 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
1990 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1991 head_ref(ref_filter_handler, &ref_cbdata);
1994 clear_contains_cache(&ref_cbdata.contains_cache);
1995 clear_contains_cache(&ref_cbdata.no_contains_cache);
1997 /* Filters that need revision walking */
1998 if (filter->merge_commit)
1999 do_merge_filter(&ref_cbdata);
2001 return ret;
2004 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2006 struct atom_value *va, *vb;
2007 int cmp;
2008 cmp_type cmp_type = used_atom[s->atom].type;
2009 int (*cmp_fn)(const char *, const char *);
2011 get_ref_atom_value(a, s->atom, &va);
2012 get_ref_atom_value(b, s->atom, &vb);
2013 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2014 if (s->version)
2015 cmp = versioncmp(va->s, vb->s);
2016 else if (cmp_type == FIELD_STR)
2017 cmp = cmp_fn(va->s, vb->s);
2018 else {
2019 if (va->value < vb->value)
2020 cmp = -1;
2021 else if (va->value == vb->value)
2022 cmp = cmp_fn(a->refname, b->refname);
2023 else
2024 cmp = 1;
2027 return (s->reverse) ? -cmp : cmp;
2030 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2032 struct ref_array_item *a = *((struct ref_array_item **)a_);
2033 struct ref_array_item *b = *((struct ref_array_item **)b_);
2034 struct ref_sorting *s;
2036 for (s = ref_sorting; s; s = s->next) {
2037 int cmp = cmp_ref_sorting(s, a, b);
2038 if (cmp)
2039 return cmp;
2041 return 0;
2044 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2046 QSORT_S(array->items, array->nr, compare_refs, sorting);
2049 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2051 struct strbuf *s = &state->stack->output;
2053 while (*cp && (!ep || cp < ep)) {
2054 if (*cp == '%') {
2055 if (cp[1] == '%')
2056 cp++;
2057 else {
2058 int ch = hex2chr(cp + 1);
2059 if (0 <= ch) {
2060 strbuf_addch(s, ch);
2061 cp += 3;
2062 continue;
2066 strbuf_addch(s, *cp);
2067 cp++;
2071 void format_ref_array_item(struct ref_array_item *info,
2072 const struct ref_format *format,
2073 struct strbuf *final_buf)
2075 const char *cp, *sp, *ep;
2076 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2078 state.quote_style = format->quote_style;
2079 push_stack_element(&state.stack);
2081 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2082 struct atom_value *atomv;
2084 ep = strchr(sp, ')');
2085 if (cp < sp)
2086 append_literal(cp, sp, &state);
2087 get_ref_atom_value(info,
2088 parse_ref_filter_atom(format, sp + 2, ep),
2089 &atomv);
2090 atomv->handler(atomv, &state);
2092 if (*cp) {
2093 sp = cp + strlen(cp);
2094 append_literal(cp, sp, &state);
2096 if (format->need_color_reset_at_eol) {
2097 struct atom_value resetv;
2098 resetv.s = GIT_COLOR_RESET;
2099 append_atom(&resetv, &state);
2101 if (state.stack->prev)
2102 die(_("format: %%(end) atom missing"));
2103 strbuf_addbuf(final_buf, &state.stack->output);
2104 pop_stack_element(&state.stack);
2107 void show_ref_array_item(struct ref_array_item *info,
2108 const struct ref_format *format)
2110 struct strbuf final_buf = STRBUF_INIT;
2112 format_ref_array_item(info, format, &final_buf);
2113 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2114 strbuf_release(&final_buf);
2115 putchar('\n');
2118 void pretty_print_ref(const char *name, const unsigned char *sha1,
2119 const struct ref_format *format)
2121 struct ref_array_item *ref_item;
2122 ref_item = new_ref_array_item(name, sha1, 0);
2123 ref_item->kind = ref_kind_from_refname(name);
2124 show_ref_array_item(ref_item, format);
2125 free_array_item(ref_item);
2128 static int parse_sorting_atom(const char *atom)
2131 * This parses an atom using a dummy ref_format, since we don't
2132 * actually care about the formatting details.
2134 struct ref_format dummy = REF_FORMAT_INIT;
2135 const char *end = atom + strlen(atom);
2136 return parse_ref_filter_atom(&dummy, atom, end);
2139 /* If no sorting option is given, use refname to sort as default */
2140 struct ref_sorting *ref_default_sorting(void)
2142 static const char cstr_name[] = "refname";
2144 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2146 sorting->next = NULL;
2147 sorting->atom = parse_sorting_atom(cstr_name);
2148 return sorting;
2151 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2153 struct ref_sorting *s;
2155 s = xcalloc(1, sizeof(*s));
2156 s->next = *sorting_tail;
2157 *sorting_tail = s;
2159 if (*arg == '-') {
2160 s->reverse = 1;
2161 arg++;
2163 if (skip_prefix(arg, "version:", &arg) ||
2164 skip_prefix(arg, "v:", &arg))
2165 s->version = 1;
2166 s->atom = parse_sorting_atom(arg);
2169 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2171 if (!arg) /* should --no-sort void the list ? */
2172 return -1;
2173 parse_ref_sorting(opt->value, arg);
2174 return 0;
2177 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2179 struct ref_filter *rf = opt->value;
2180 struct object_id oid;
2181 int no_merged = starts_with(opt->long_name, "no");
2183 if (rf->merge) {
2184 if (no_merged) {
2185 return opterror(opt, "is incompatible with --merged", 0);
2186 } else {
2187 return opterror(opt, "is incompatible with --no-merged", 0);
2191 rf->merge = no_merged
2192 ? REF_FILTER_MERGED_OMIT
2193 : REF_FILTER_MERGED_INCLUDE;
2195 if (get_oid(arg, &oid))
2196 die(_("malformed object name %s"), arg);
2198 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2199 if (!rf->merge_commit)
2200 return opterror(opt, "must point to a commit", 0);
2202 return 0;