notes: convert internal structures to struct object_id
[git.git] / ref-filter.c
blob3742abbf85ce4044641bc937a70504c059ed8822
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;
100 static int need_color_reset_at_eol;
102 static void color_atom_parser(struct used_atom *atom, const char *color_value)
104 if (!color_value)
105 die(_("expected format: %%(color:<color>)"));
106 if (color_parse(color_value, atom->u.color) < 0)
107 die(_("unrecognized color: %%(color:%s)"), color_value);
110 static void refname_atom_parser_internal(struct refname_atom *atom,
111 const char *arg, const char *name)
113 if (!arg)
114 atom->option = R_NORMAL;
115 else if (!strcmp(arg, "short"))
116 atom->option = R_SHORT;
117 else if (skip_prefix(arg, "lstrip=", &arg) ||
118 skip_prefix(arg, "strip=", &arg)) {
119 atom->option = R_LSTRIP;
120 if (strtol_i(arg, 10, &atom->lstrip))
121 die(_("Integer value expected refname:lstrip=%s"), arg);
122 } else if (skip_prefix(arg, "rstrip=", &arg)) {
123 atom->option = R_RSTRIP;
124 if (strtol_i(arg, 10, &atom->rstrip))
125 die(_("Integer value expected refname:rstrip=%s"), arg);
126 } else
127 die(_("unrecognized %%(%s) argument: %s"), name, arg);
130 static void remote_ref_atom_parser(struct used_atom *atom, const char *arg)
132 struct string_list params = STRING_LIST_INIT_DUP;
133 int i;
135 if (!arg) {
136 atom->u.remote_ref.option = RR_REF;
137 refname_atom_parser_internal(&atom->u.remote_ref.refname,
138 arg, atom->name);
139 return;
142 atom->u.remote_ref.nobracket = 0;
143 string_list_split(&params, arg, ',', -1);
145 for (i = 0; i < params.nr; i++) {
146 const char *s = params.items[i].string;
148 if (!strcmp(s, "track"))
149 atom->u.remote_ref.option = RR_TRACK;
150 else if (!strcmp(s, "trackshort"))
151 atom->u.remote_ref.option = RR_TRACKSHORT;
152 else if (!strcmp(s, "nobracket"))
153 atom->u.remote_ref.nobracket = 1;
154 else {
155 atom->u.remote_ref.option = RR_REF;
156 refname_atom_parser_internal(&atom->u.remote_ref.refname,
157 arg, atom->name);
161 string_list_clear(&params, 0);
164 static void body_atom_parser(struct used_atom *atom, const char *arg)
166 if (arg)
167 die(_("%%(body) does not take arguments"));
168 atom->u.contents.option = C_BODY_DEP;
171 static void subject_atom_parser(struct used_atom *atom, const char *arg)
173 if (arg)
174 die(_("%%(subject) does not take arguments"));
175 atom->u.contents.option = C_SUB;
178 static void trailers_atom_parser(struct used_atom *atom, const char *arg)
180 if (arg)
181 die(_("%%(trailers) does not take arguments"));
182 atom->u.contents.option = C_TRAILERS;
185 static void contents_atom_parser(struct used_atom *atom, const char *arg)
187 if (!arg)
188 atom->u.contents.option = C_BARE;
189 else if (!strcmp(arg, "body"))
190 atom->u.contents.option = C_BODY;
191 else if (!strcmp(arg, "signature"))
192 atom->u.contents.option = C_SIG;
193 else if (!strcmp(arg, "subject"))
194 atom->u.contents.option = C_SUB;
195 else if (!strcmp(arg, "trailers"))
196 atom->u.contents.option = C_TRAILERS;
197 else if (skip_prefix(arg, "lines=", &arg)) {
198 atom->u.contents.option = C_LINES;
199 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
200 die(_("positive value expected contents:lines=%s"), arg);
201 } else
202 die(_("unrecognized %%(contents) argument: %s"), arg);
205 static void objectname_atom_parser(struct used_atom *atom, const char *arg)
207 if (!arg)
208 atom->u.objectname.option = O_FULL;
209 else if (!strcmp(arg, "short"))
210 atom->u.objectname.option = O_SHORT;
211 else if (skip_prefix(arg, "short=", &arg)) {
212 atom->u.objectname.option = O_LENGTH;
213 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
214 atom->u.objectname.length == 0)
215 die(_("positive value expected objectname:short=%s"), arg);
216 if (atom->u.objectname.length < MINIMUM_ABBREV)
217 atom->u.objectname.length = MINIMUM_ABBREV;
218 } else
219 die(_("unrecognized %%(objectname) argument: %s"), arg);
222 static void refname_atom_parser(struct used_atom *atom, const char *arg)
224 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
227 static align_type parse_align_position(const char *s)
229 if (!strcmp(s, "right"))
230 return ALIGN_RIGHT;
231 else if (!strcmp(s, "middle"))
232 return ALIGN_MIDDLE;
233 else if (!strcmp(s, "left"))
234 return ALIGN_LEFT;
235 return -1;
238 static void align_atom_parser(struct used_atom *atom, const char *arg)
240 struct align *align = &atom->u.align;
241 struct string_list params = STRING_LIST_INIT_DUP;
242 int i;
243 unsigned int width = ~0U;
245 if (!arg)
246 die(_("expected format: %%(align:<width>,<position>)"));
248 align->position = ALIGN_LEFT;
250 string_list_split(&params, arg, ',', -1);
251 for (i = 0; i < params.nr; i++) {
252 const char *s = params.items[i].string;
253 int position;
255 if (skip_prefix(s, "position=", &s)) {
256 position = parse_align_position(s);
257 if (position < 0)
258 die(_("unrecognized position:%s"), s);
259 align->position = position;
260 } else if (skip_prefix(s, "width=", &s)) {
261 if (strtoul_ui(s, 10, &width))
262 die(_("unrecognized width:%s"), s);
263 } else if (!strtoul_ui(s, 10, &width))
265 else if ((position = parse_align_position(s)) >= 0)
266 align->position = position;
267 else
268 die(_("unrecognized %%(align) argument: %s"), s);
271 if (width == ~0U)
272 die(_("positive width expected with the %%(align) atom"));
273 align->width = width;
274 string_list_clear(&params, 0);
277 static void if_atom_parser(struct used_atom *atom, const char *arg)
279 if (!arg) {
280 atom->u.if_then_else.cmp_status = COMPARE_NONE;
281 return;
282 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
283 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
284 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
285 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
286 } else {
287 die(_("unrecognized %%(if) argument: %s"), arg);
291 static void head_atom_parser(struct used_atom *atom, const char *arg)
293 struct object_id unused;
295 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, unused.hash, NULL);
298 static struct {
299 const char *name;
300 cmp_type cmp_type;
301 void (*parser)(struct used_atom *atom, const char *arg);
302 } valid_atom[] = {
303 { "refname" , FIELD_STR, refname_atom_parser },
304 { "objecttype" },
305 { "objectsize", FIELD_ULONG },
306 { "objectname", FIELD_STR, objectname_atom_parser },
307 { "tree" },
308 { "parent" },
309 { "numparent", FIELD_ULONG },
310 { "object" },
311 { "type" },
312 { "tag" },
313 { "author" },
314 { "authorname" },
315 { "authoremail" },
316 { "authordate", FIELD_TIME },
317 { "committer" },
318 { "committername" },
319 { "committeremail" },
320 { "committerdate", FIELD_TIME },
321 { "tagger" },
322 { "taggername" },
323 { "taggeremail" },
324 { "taggerdate", FIELD_TIME },
325 { "creator" },
326 { "creatordate", FIELD_TIME },
327 { "subject", FIELD_STR, subject_atom_parser },
328 { "body", FIELD_STR, body_atom_parser },
329 { "trailers", FIELD_STR, trailers_atom_parser },
330 { "contents", FIELD_STR, contents_atom_parser },
331 { "upstream", FIELD_STR, remote_ref_atom_parser },
332 { "push", FIELD_STR, remote_ref_atom_parser },
333 { "symref", FIELD_STR, refname_atom_parser },
334 { "flag" },
335 { "HEAD", FIELD_STR, head_atom_parser },
336 { "color", FIELD_STR, color_atom_parser },
337 { "align", FIELD_STR, align_atom_parser },
338 { "end" },
339 { "if", FIELD_STR, if_atom_parser },
340 { "then" },
341 { "else" },
344 #define REF_FORMATTING_STATE_INIT { 0, NULL }
346 struct ref_formatting_stack {
347 struct ref_formatting_stack *prev;
348 struct strbuf output;
349 void (*at_end)(struct ref_formatting_stack **stack);
350 void *at_end_data;
353 struct ref_formatting_state {
354 int quote_style;
355 struct ref_formatting_stack *stack;
358 struct atom_value {
359 const char *s;
360 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
361 uintmax_t value; /* used for sorting when not FIELD_STR */
362 struct used_atom *atom;
366 * Used to parse format string and sort specifiers
368 int parse_ref_filter_atom(const char *atom, const char *ep)
370 const char *sp;
371 const char *arg;
372 int i, at, atom_len;
374 sp = atom;
375 if (*sp == '*' && sp < ep)
376 sp++; /* deref */
377 if (ep <= sp)
378 die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
380 /* Do we have the atom already used elsewhere? */
381 for (i = 0; i < used_atom_cnt; i++) {
382 int len = strlen(used_atom[i].name);
383 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
384 return i;
388 * If the atom name has a colon, strip it and everything after
389 * it off - it specifies the format for this entry, and
390 * shouldn't be used for checking against the valid_atom
391 * table.
393 arg = memchr(sp, ':', ep - sp);
394 atom_len = (arg ? arg : ep) - sp;
396 /* Is the atom a valid one? */
397 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
398 int len = strlen(valid_atom[i].name);
399 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
400 break;
403 if (ARRAY_SIZE(valid_atom) <= i)
404 die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
406 /* Add it in, including the deref prefix */
407 at = used_atom_cnt;
408 used_atom_cnt++;
409 REALLOC_ARRAY(used_atom, used_atom_cnt);
410 used_atom[at].name = xmemdupz(atom, ep - atom);
411 used_atom[at].type = valid_atom[i].cmp_type;
412 if (arg)
413 arg = used_atom[at].name + (arg - atom) + 1;
414 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
415 if (valid_atom[i].parser)
416 valid_atom[i].parser(&used_atom[at], arg);
417 if (*atom == '*')
418 need_tagged = 1;
419 if (!strcmp(valid_atom[i].name, "symref"))
420 need_symref = 1;
421 return at;
424 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
426 switch (quote_style) {
427 case QUOTE_NONE:
428 strbuf_addstr(s, str);
429 break;
430 case QUOTE_SHELL:
431 sq_quote_buf(s, str);
432 break;
433 case QUOTE_PERL:
434 perl_quote_buf(s, str);
435 break;
436 case QUOTE_PYTHON:
437 python_quote_buf(s, str);
438 break;
439 case QUOTE_TCL:
440 tcl_quote_buf(s, str);
441 break;
445 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
448 * Quote formatting is only done when the stack has a single
449 * element. Otherwise quote formatting is done on the
450 * element's entire output strbuf when the %(end) atom is
451 * encountered.
453 if (!state->stack->prev)
454 quote_formatting(&state->stack->output, v->s, state->quote_style);
455 else
456 strbuf_addstr(&state->stack->output, v->s);
459 static void push_stack_element(struct ref_formatting_stack **stack)
461 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
463 strbuf_init(&s->output, 0);
464 s->prev = *stack;
465 *stack = s;
468 static void pop_stack_element(struct ref_formatting_stack **stack)
470 struct ref_formatting_stack *current = *stack;
471 struct ref_formatting_stack *prev = current->prev;
473 if (prev)
474 strbuf_addbuf(&prev->output, &current->output);
475 strbuf_release(&current->output);
476 free(current);
477 *stack = prev;
480 static void end_align_handler(struct ref_formatting_stack **stack)
482 struct ref_formatting_stack *cur = *stack;
483 struct align *align = (struct align *)cur->at_end_data;
484 struct strbuf s = STRBUF_INIT;
486 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
487 strbuf_swap(&cur->output, &s);
488 strbuf_release(&s);
491 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
493 struct ref_formatting_stack *new;
495 push_stack_element(&state->stack);
496 new = state->stack;
497 new->at_end = end_align_handler;
498 new->at_end_data = &atomv->atom->u.align;
501 static void if_then_else_handler(struct ref_formatting_stack **stack)
503 struct ref_formatting_stack *cur = *stack;
504 struct ref_formatting_stack *prev = cur->prev;
505 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
507 if (!if_then_else->then_atom_seen)
508 die(_("format: %%(if) atom used without a %%(then) atom"));
510 if (if_then_else->else_atom_seen) {
512 * There is an %(else) atom: we need to drop one state from the
513 * stack, either the %(else) branch if the condition is satisfied, or
514 * the %(then) branch if it isn't.
516 if (if_then_else->condition_satisfied) {
517 strbuf_reset(&cur->output);
518 pop_stack_element(&cur);
519 } else {
520 strbuf_swap(&cur->output, &prev->output);
521 strbuf_reset(&cur->output);
522 pop_stack_element(&cur);
524 } else if (!if_then_else->condition_satisfied) {
526 * No %(else) atom: just drop the %(then) branch if the
527 * condition is not satisfied.
529 strbuf_reset(&cur->output);
532 *stack = cur;
533 free(if_then_else);
536 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
538 struct ref_formatting_stack *new;
539 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
541 if_then_else->str = atomv->atom->u.if_then_else.str;
542 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
544 push_stack_element(&state->stack);
545 new = state->stack;
546 new->at_end = if_then_else_handler;
547 new->at_end_data = if_then_else;
550 static int is_empty(const char *s)
552 while (*s != '\0') {
553 if (!isspace(*s))
554 return 0;
555 s++;
557 return 1;
560 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
562 struct ref_formatting_stack *cur = state->stack;
563 struct if_then_else *if_then_else = NULL;
565 if (cur->at_end == if_then_else_handler)
566 if_then_else = (struct if_then_else *)cur->at_end_data;
567 if (!if_then_else)
568 die(_("format: %%(then) atom used without an %%(if) atom"));
569 if (if_then_else->then_atom_seen)
570 die(_("format: %%(then) atom used more than once"));
571 if (if_then_else->else_atom_seen)
572 die(_("format: %%(then) atom used after %%(else)"));
573 if_then_else->then_atom_seen = 1;
575 * If the 'equals' or 'notequals' attribute is used then
576 * perform the required comparison. If not, only non-empty
577 * strings satisfy the 'if' condition.
579 if (if_then_else->cmp_status == COMPARE_EQUAL) {
580 if (!strcmp(if_then_else->str, cur->output.buf))
581 if_then_else->condition_satisfied = 1;
582 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
583 if (strcmp(if_then_else->str, cur->output.buf))
584 if_then_else->condition_satisfied = 1;
585 } else if (cur->output.len && !is_empty(cur->output.buf))
586 if_then_else->condition_satisfied = 1;
587 strbuf_reset(&cur->output);
590 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
592 struct ref_formatting_stack *prev = state->stack;
593 struct if_then_else *if_then_else = NULL;
595 if (prev->at_end == if_then_else_handler)
596 if_then_else = (struct if_then_else *)prev->at_end_data;
597 if (!if_then_else)
598 die(_("format: %%(else) atom used without an %%(if) atom"));
599 if (!if_then_else->then_atom_seen)
600 die(_("format: %%(else) atom used without a %%(then) atom"));
601 if (if_then_else->else_atom_seen)
602 die(_("format: %%(else) atom used more than once"));
603 if_then_else->else_atom_seen = 1;
604 push_stack_element(&state->stack);
605 state->stack->at_end_data = prev->at_end_data;
606 state->stack->at_end = prev->at_end;
609 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
611 struct ref_formatting_stack *current = state->stack;
612 struct strbuf s = STRBUF_INIT;
614 if (!current->at_end)
615 die(_("format: %%(end) atom used without corresponding atom"));
616 current->at_end(&state->stack);
618 /* Stack may have been popped within at_end(), hence reset the current pointer */
619 current = state->stack;
622 * Perform quote formatting when the stack element is that of
623 * a supporting atom. If nested then perform quote formatting
624 * only on the topmost supporting atom.
626 if (!current->prev->prev) {
627 quote_formatting(&s, current->output.buf, state->quote_style);
628 strbuf_swap(&current->output, &s);
630 strbuf_release(&s);
631 pop_stack_element(&state->stack);
635 * In a format string, find the next occurrence of %(atom).
637 static const char *find_next(const char *cp)
639 while (*cp) {
640 if (*cp == '%') {
642 * %( is the start of an atom;
643 * %% is a quoted per-cent.
645 if (cp[1] == '(')
646 return cp;
647 else if (cp[1] == '%')
648 cp++; /* skip over two % */
649 /* otherwise this is a singleton, literal % */
651 cp++;
653 return NULL;
657 * Make sure the format string is well formed, and parse out
658 * the used atoms.
660 int verify_ref_format(const char *format)
662 const char *cp, *sp;
664 need_color_reset_at_eol = 0;
665 for (cp = format; *cp && (sp = find_next(cp)); ) {
666 const char *color, *ep = strchr(sp, ')');
667 int at;
669 if (!ep)
670 return error(_("malformed format string %s"), sp);
671 /* sp points at "%(" and ep points at the closing ")" */
672 at = parse_ref_filter_atom(sp + 2, ep);
673 cp = ep + 1;
675 if (skip_prefix(used_atom[at].name, "color:", &color))
676 need_color_reset_at_eol = !!strcmp(color, "reset");
678 return 0;
682 * Given an object name, read the object data and size, and return a
683 * "struct object". If the object data we are returning is also borrowed
684 * by the "struct object" representation, set *eaten as well---it is a
685 * signal from parse_object_buffer to us not to free the buffer.
687 static void *get_obj(const struct object_id *oid, struct object **obj, unsigned long *sz, int *eaten)
689 enum object_type type;
690 void *buf = read_sha1_file(oid->hash, &type, sz);
692 if (buf)
693 *obj = parse_object_buffer(oid, type, *sz, buf, eaten);
694 else
695 *obj = NULL;
696 return buf;
699 static int grab_objectname(const char *name, const unsigned char *sha1,
700 struct atom_value *v, struct used_atom *atom)
702 if (starts_with(name, "objectname")) {
703 if (atom->u.objectname.option == O_SHORT) {
704 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
705 return 1;
706 } else if (atom->u.objectname.option == O_FULL) {
707 v->s = xstrdup(sha1_to_hex(sha1));
708 return 1;
709 } else if (atom->u.objectname.option == O_LENGTH) {
710 v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
711 return 1;
712 } else
713 die("BUG: unknown %%(objectname) option");
715 return 0;
718 /* See grab_values */
719 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
721 int i;
723 for (i = 0; i < used_atom_cnt; i++) {
724 const char *name = used_atom[i].name;
725 struct atom_value *v = &val[i];
726 if (!!deref != (*name == '*'))
727 continue;
728 if (deref)
729 name++;
730 if (!strcmp(name, "objecttype"))
731 v->s = typename(obj->type);
732 else if (!strcmp(name, "objectsize")) {
733 v->value = sz;
734 v->s = xstrfmt("%lu", sz);
736 else if (deref)
737 grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
741 /* See grab_values */
742 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
744 int i;
745 struct tag *tag = (struct tag *) obj;
747 for (i = 0; i < used_atom_cnt; i++) {
748 const char *name = used_atom[i].name;
749 struct atom_value *v = &val[i];
750 if (!!deref != (*name == '*'))
751 continue;
752 if (deref)
753 name++;
754 if (!strcmp(name, "tag"))
755 v->s = tag->tag;
756 else if (!strcmp(name, "type") && tag->tagged)
757 v->s = typename(tag->tagged->type);
758 else if (!strcmp(name, "object") && tag->tagged)
759 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
763 /* See grab_values */
764 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
766 int i;
767 struct commit *commit = (struct commit *) obj;
769 for (i = 0; i < used_atom_cnt; i++) {
770 const char *name = used_atom[i].name;
771 struct atom_value *v = &val[i];
772 if (!!deref != (*name == '*'))
773 continue;
774 if (deref)
775 name++;
776 if (!strcmp(name, "tree")) {
777 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
779 else if (!strcmp(name, "numparent")) {
780 v->value = commit_list_count(commit->parents);
781 v->s = xstrfmt("%lu", (unsigned long)v->value);
783 else if (!strcmp(name, "parent")) {
784 struct commit_list *parents;
785 struct strbuf s = STRBUF_INIT;
786 for (parents = commit->parents; parents; parents = parents->next) {
787 struct commit *parent = parents->item;
788 if (parents != commit->parents)
789 strbuf_addch(&s, ' ');
790 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
792 v->s = strbuf_detach(&s, NULL);
797 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
799 const char *eol;
800 while (*buf) {
801 if (!strncmp(buf, who, wholen) &&
802 buf[wholen] == ' ')
803 return buf + wholen + 1;
804 eol = strchr(buf, '\n');
805 if (!eol)
806 return "";
807 eol++;
808 if (*eol == '\n')
809 return ""; /* end of header */
810 buf = eol;
812 return "";
815 static const char *copy_line(const char *buf)
817 const char *eol = strchrnul(buf, '\n');
818 return xmemdupz(buf, eol - buf);
821 static const char *copy_name(const char *buf)
823 const char *cp;
824 for (cp = buf; *cp && *cp != '\n'; cp++) {
825 if (!strncmp(cp, " <", 2))
826 return xmemdupz(buf, cp - buf);
828 return "";
831 static const char *copy_email(const char *buf)
833 const char *email = strchr(buf, '<');
834 const char *eoemail;
835 if (!email)
836 return "";
837 eoemail = strchr(email, '>');
838 if (!eoemail)
839 return "";
840 return xmemdupz(email, eoemail + 1 - email);
843 static char *copy_subject(const char *buf, unsigned long len)
845 char *r = xmemdupz(buf, len);
846 int i;
848 for (i = 0; i < len; i++)
849 if (r[i] == '\n')
850 r[i] = ' ';
852 return r;
855 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
857 const char *eoemail = strstr(buf, "> ");
858 char *zone;
859 timestamp_t timestamp;
860 long tz;
861 struct date_mode date_mode = { DATE_NORMAL };
862 const char *formatp;
865 * We got here because atomname ends in "date" or "date<something>";
866 * it's not possible that <something> is not ":<format>" because
867 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
868 * ":" means no format is specified, and use the default.
870 formatp = strchr(atomname, ':');
871 if (formatp != NULL) {
872 formatp++;
873 parse_date_format(formatp, &date_mode);
876 if (!eoemail)
877 goto bad;
878 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
879 if (timestamp == TIME_MAX)
880 goto bad;
881 tz = strtol(zone, NULL, 10);
882 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
883 goto bad;
884 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
885 v->value = timestamp;
886 return;
887 bad:
888 v->s = "";
889 v->value = 0;
892 /* See grab_values */
893 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
895 int i;
896 int wholen = strlen(who);
897 const char *wholine = NULL;
899 for (i = 0; i < used_atom_cnt; i++) {
900 const char *name = used_atom[i].name;
901 struct atom_value *v = &val[i];
902 if (!!deref != (*name == '*'))
903 continue;
904 if (deref)
905 name++;
906 if (strncmp(who, name, wholen))
907 continue;
908 if (name[wholen] != 0 &&
909 strcmp(name + wholen, "name") &&
910 strcmp(name + wholen, "email") &&
911 !starts_with(name + wholen, "date"))
912 continue;
913 if (!wholine)
914 wholine = find_wholine(who, wholen, buf, sz);
915 if (!wholine)
916 return; /* no point looking for it */
917 if (name[wholen] == 0)
918 v->s = copy_line(wholine);
919 else if (!strcmp(name + wholen, "name"))
920 v->s = copy_name(wholine);
921 else if (!strcmp(name + wholen, "email"))
922 v->s = copy_email(wholine);
923 else if (starts_with(name + wholen, "date"))
924 grab_date(wholine, v, name);
928 * For a tag or a commit object, if "creator" or "creatordate" is
929 * requested, do something special.
931 if (strcmp(who, "tagger") && strcmp(who, "committer"))
932 return; /* "author" for commit object is not wanted */
933 if (!wholine)
934 wholine = find_wholine(who, wholen, buf, sz);
935 if (!wholine)
936 return;
937 for (i = 0; i < used_atom_cnt; i++) {
938 const char *name = used_atom[i].name;
939 struct atom_value *v = &val[i];
940 if (!!deref != (*name == '*'))
941 continue;
942 if (deref)
943 name++;
945 if (starts_with(name, "creatordate"))
946 grab_date(wholine, v, name);
947 else if (!strcmp(name, "creator"))
948 v->s = copy_line(wholine);
952 static void find_subpos(const char *buf, unsigned long sz,
953 const char **sub, unsigned long *sublen,
954 const char **body, unsigned long *bodylen,
955 unsigned long *nonsiglen,
956 const char **sig, unsigned long *siglen)
958 const char *eol;
959 /* skip past header until we hit empty line */
960 while (*buf && *buf != '\n') {
961 eol = strchrnul(buf, '\n');
962 if (*eol)
963 eol++;
964 buf = eol;
966 /* skip any empty lines */
967 while (*buf == '\n')
968 buf++;
970 /* parse signature first; we might not even have a subject line */
971 *sig = buf + parse_signature(buf, strlen(buf));
972 *siglen = strlen(*sig);
974 /* subject is first non-empty line */
975 *sub = buf;
976 /* subject goes to first empty line */
977 while (buf < *sig && *buf && *buf != '\n') {
978 eol = strchrnul(buf, '\n');
979 if (*eol)
980 eol++;
981 buf = eol;
983 *sublen = buf - *sub;
984 /* drop trailing newline, if present */
985 if (*sublen && (*sub)[*sublen - 1] == '\n')
986 *sublen -= 1;
988 /* skip any empty lines */
989 while (*buf == '\n')
990 buf++;
991 *body = buf;
992 *bodylen = strlen(buf);
993 *nonsiglen = *sig - buf;
997 * If 'lines' is greater than 0, append that many lines from the given
998 * 'buf' of length 'size' to the given strbuf.
1000 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1002 int i;
1003 const char *sp, *eol;
1004 size_t len;
1006 sp = buf;
1008 for (i = 0; i < lines && sp < buf + size; i++) {
1009 if (i)
1010 strbuf_addstr(out, "\n ");
1011 eol = memchr(sp, '\n', size - (sp - buf));
1012 len = eol ? eol - sp : size - (sp - buf);
1013 strbuf_add(out, sp, len);
1014 if (!eol)
1015 break;
1016 sp = eol + 1;
1020 /* See grab_values */
1021 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1023 int i;
1024 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1025 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1027 for (i = 0; i < used_atom_cnt; i++) {
1028 struct used_atom *atom = &used_atom[i];
1029 const char *name = atom->name;
1030 struct atom_value *v = &val[i];
1031 if (!!deref != (*name == '*'))
1032 continue;
1033 if (deref)
1034 name++;
1035 if (strcmp(name, "subject") &&
1036 strcmp(name, "body") &&
1037 strcmp(name, "trailers") &&
1038 !starts_with(name, "contents"))
1039 continue;
1040 if (!subpos)
1041 find_subpos(buf, sz,
1042 &subpos, &sublen,
1043 &bodypos, &bodylen, &nonsiglen,
1044 &sigpos, &siglen);
1046 if (atom->u.contents.option == C_SUB)
1047 v->s = copy_subject(subpos, sublen);
1048 else if (atom->u.contents.option == C_BODY_DEP)
1049 v->s = xmemdupz(bodypos, bodylen);
1050 else if (atom->u.contents.option == C_BODY)
1051 v->s = xmemdupz(bodypos, nonsiglen);
1052 else if (atom->u.contents.option == C_SIG)
1053 v->s = xmemdupz(sigpos, siglen);
1054 else if (atom->u.contents.option == C_LINES) {
1055 struct strbuf s = STRBUF_INIT;
1056 const char *contents_end = bodylen + bodypos - siglen;
1058 /* Size is the length of the message after removing the signature */
1059 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1060 v->s = strbuf_detach(&s, NULL);
1061 } else if (atom->u.contents.option == C_TRAILERS) {
1062 struct trailer_info info;
1064 /* Search for trailer info */
1065 trailer_info_get(&info, subpos);
1066 v->s = xmemdupz(info.trailer_start,
1067 info.trailer_end - info.trailer_start);
1068 trailer_info_release(&info);
1069 } else if (atom->u.contents.option == C_BARE)
1070 v->s = xstrdup(subpos);
1075 * We want to have empty print-string for field requests
1076 * that do not apply (e.g. "authordate" for a tag object)
1078 static void fill_missing_values(struct atom_value *val)
1080 int i;
1081 for (i = 0; i < used_atom_cnt; i++) {
1082 struct atom_value *v = &val[i];
1083 if (v->s == NULL)
1084 v->s = "";
1089 * val is a list of atom_value to hold returned values. Extract
1090 * the values for atoms in used_atom array out of (obj, buf, sz).
1091 * when deref is false, (obj, buf, sz) is the object that is
1092 * pointed at by the ref itself; otherwise it is the object the
1093 * ref (which is a tag) refers to.
1095 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1097 grab_common_values(val, deref, obj, buf, sz);
1098 switch (obj->type) {
1099 case OBJ_TAG:
1100 grab_tag_values(val, deref, obj, buf, sz);
1101 grab_sub_body_contents(val, deref, obj, buf, sz);
1102 grab_person("tagger", val, deref, obj, buf, sz);
1103 break;
1104 case OBJ_COMMIT:
1105 grab_commit_values(val, deref, obj, buf, sz);
1106 grab_sub_body_contents(val, deref, obj, buf, sz);
1107 grab_person("author", val, deref, obj, buf, sz);
1108 grab_person("committer", val, deref, obj, buf, sz);
1109 break;
1110 case OBJ_TREE:
1111 /* grab_tree_values(val, deref, obj, buf, sz); */
1112 break;
1113 case OBJ_BLOB:
1114 /* grab_blob_values(val, deref, obj, buf, sz); */
1115 break;
1116 default:
1117 die("Eh? Object of type %d?", obj->type);
1121 static inline char *copy_advance(char *dst, const char *src)
1123 while (*src)
1124 *dst++ = *src++;
1125 return dst;
1128 static const char *lstrip_ref_components(const char *refname, int len)
1130 long remaining = len;
1131 const char *start = refname;
1133 if (len < 0) {
1134 int i;
1135 const char *p = refname;
1137 /* Find total no of '/' separated path-components */
1138 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1141 * The number of components we need to strip is now
1142 * the total minus the components to be left (Plus one
1143 * because we count the number of '/', but the number
1144 * of components is one more than the no of '/').
1146 remaining = i + len + 1;
1149 while (remaining > 0) {
1150 switch (*start++) {
1151 case '\0':
1152 return "";
1153 case '/':
1154 remaining--;
1155 break;
1159 return start;
1162 static const char *rstrip_ref_components(const char *refname, int len)
1164 long remaining = len;
1165 char *start = xstrdup(refname);
1167 if (len < 0) {
1168 int i;
1169 const char *p = refname;
1171 /* Find total no of '/' separated path-components */
1172 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1175 * The number of components we need to strip is now
1176 * the total minus the components to be left (Plus one
1177 * because we count the number of '/', but the number
1178 * of components is one more than the no of '/').
1180 remaining = i + len + 1;
1183 while (remaining-- > 0) {
1184 char *p = strrchr(start, '/');
1185 if (p == NULL)
1186 return "";
1187 else
1188 p[0] = '\0';
1190 return start;
1193 static const char *show_ref(struct refname_atom *atom, const char *refname)
1195 if (atom->option == R_SHORT)
1196 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1197 else if (atom->option == R_LSTRIP)
1198 return lstrip_ref_components(refname, atom->lstrip);
1199 else if (atom->option == R_RSTRIP)
1200 return rstrip_ref_components(refname, atom->rstrip);
1201 else
1202 return refname;
1205 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1206 struct branch *branch, const char **s)
1208 int num_ours, num_theirs;
1209 if (atom->u.remote_ref.option == RR_REF)
1210 *s = show_ref(&atom->u.remote_ref.refname, refname);
1211 else if (atom->u.remote_ref.option == RR_TRACK) {
1212 if (stat_tracking_info(branch, &num_ours,
1213 &num_theirs, NULL)) {
1214 *s = xstrdup(msgs.gone);
1215 } else if (!num_ours && !num_theirs)
1216 *s = "";
1217 else if (!num_ours)
1218 *s = xstrfmt(msgs.behind, num_theirs);
1219 else if (!num_theirs)
1220 *s = xstrfmt(msgs.ahead, num_ours);
1221 else
1222 *s = xstrfmt(msgs.ahead_behind,
1223 num_ours, num_theirs);
1224 if (!atom->u.remote_ref.nobracket && *s[0]) {
1225 const char *to_free = *s;
1226 *s = xstrfmt("[%s]", *s);
1227 free((void *)to_free);
1229 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1230 if (stat_tracking_info(branch, &num_ours,
1231 &num_theirs, NULL))
1232 return;
1234 if (!num_ours && !num_theirs)
1235 *s = "=";
1236 else if (!num_ours)
1237 *s = "<";
1238 else if (!num_theirs)
1239 *s = ">";
1240 else
1241 *s = "<>";
1242 } else
1243 die("BUG: unhandled RR_* enum");
1246 char *get_head_description(void)
1248 struct strbuf desc = STRBUF_INIT;
1249 struct wt_status_state state;
1250 memset(&state, 0, sizeof(state));
1251 wt_status_get_state(&state, 1);
1252 if (state.rebase_in_progress ||
1253 state.rebase_interactive_in_progress)
1254 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1255 state.branch);
1256 else if (state.bisect_in_progress)
1257 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1258 state.branch);
1259 else if (state.detached_from) {
1260 if (state.detached_at)
1261 /* TRANSLATORS: make sure this matches
1262 "HEAD detached at " in wt-status.c */
1263 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1264 state.detached_from);
1265 else
1266 /* TRANSLATORS: make sure this matches
1267 "HEAD detached from " in wt-status.c */
1268 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1269 state.detached_from);
1271 else
1272 strbuf_addstr(&desc, _("(no branch)"));
1273 free(state.branch);
1274 free(state.onto);
1275 free(state.detached_from);
1276 return strbuf_detach(&desc, NULL);
1279 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1281 if (!ref->symref)
1282 return "";
1283 else
1284 return show_ref(&atom->u.refname, ref->symref);
1287 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1289 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1290 return get_head_description();
1291 return show_ref(&atom->u.refname, ref->refname);
1295 * Parse the object referred by ref, and grab needed value.
1297 static void populate_value(struct ref_array_item *ref)
1299 void *buf;
1300 struct object *obj;
1301 int eaten, i;
1302 unsigned long size;
1303 const struct object_id *tagged;
1305 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1307 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1308 struct object_id unused1;
1309 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1310 unused1.hash, NULL);
1311 if (!ref->symref)
1312 ref->symref = "";
1315 /* Fill in specials first */
1316 for (i = 0; i < used_atom_cnt; i++) {
1317 struct used_atom *atom = &used_atom[i];
1318 const char *name = used_atom[i].name;
1319 struct atom_value *v = &ref->value[i];
1320 int deref = 0;
1321 const char *refname;
1322 struct branch *branch = NULL;
1324 v->handler = append_atom;
1325 v->atom = atom;
1327 if (*name == '*') {
1328 deref = 1;
1329 name++;
1332 if (starts_with(name, "refname"))
1333 refname = get_refname(atom, ref);
1334 else if (starts_with(name, "symref"))
1335 refname = get_symref(atom, ref);
1336 else if (starts_with(name, "upstream")) {
1337 const char *branch_name;
1338 /* only local branches may have an upstream */
1339 if (!skip_prefix(ref->refname, "refs/heads/",
1340 &branch_name))
1341 continue;
1342 branch = branch_get(branch_name);
1344 refname = branch_get_upstream(branch, NULL);
1345 if (refname)
1346 fill_remote_ref_details(atom, refname, branch, &v->s);
1347 continue;
1348 } else if (starts_with(name, "push")) {
1349 const char *branch_name;
1350 if (!skip_prefix(ref->refname, "refs/heads/",
1351 &branch_name))
1352 continue;
1353 branch = branch_get(branch_name);
1355 refname = branch_get_push(branch, NULL);
1356 if (!refname)
1357 continue;
1358 fill_remote_ref_details(atom, refname, branch, &v->s);
1359 continue;
1360 } else if (starts_with(name, "color:")) {
1361 v->s = atom->u.color;
1362 continue;
1363 } else if (!strcmp(name, "flag")) {
1364 char buf[256], *cp = buf;
1365 if (ref->flag & REF_ISSYMREF)
1366 cp = copy_advance(cp, ",symref");
1367 if (ref->flag & REF_ISPACKED)
1368 cp = copy_advance(cp, ",packed");
1369 if (cp == buf)
1370 v->s = "";
1371 else {
1372 *cp = '\0';
1373 v->s = xstrdup(buf + 1);
1375 continue;
1376 } else if (!deref && grab_objectname(name, ref->objectname.hash, v, atom)) {
1377 continue;
1378 } else if (!strcmp(name, "HEAD")) {
1379 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1380 v->s = "*";
1381 else
1382 v->s = " ";
1383 continue;
1384 } else if (starts_with(name, "align")) {
1385 v->handler = align_atom_handler;
1386 continue;
1387 } else if (!strcmp(name, "end")) {
1388 v->handler = end_atom_handler;
1389 continue;
1390 } else if (starts_with(name, "if")) {
1391 const char *s;
1393 if (skip_prefix(name, "if:", &s))
1394 v->s = xstrdup(s);
1395 v->handler = if_atom_handler;
1396 continue;
1397 } else if (!strcmp(name, "then")) {
1398 v->handler = then_atom_handler;
1399 continue;
1400 } else if (!strcmp(name, "else")) {
1401 v->handler = else_atom_handler;
1402 continue;
1403 } else
1404 continue;
1406 if (!deref)
1407 v->s = refname;
1408 else
1409 v->s = xstrfmt("%s^{}", refname);
1412 for (i = 0; i < used_atom_cnt; i++) {
1413 struct atom_value *v = &ref->value[i];
1414 if (v->s == NULL)
1415 goto need_obj;
1417 return;
1419 need_obj:
1420 buf = get_obj(&ref->objectname, &obj, &size, &eaten);
1421 if (!buf)
1422 die(_("missing object %s for %s"),
1423 oid_to_hex(&ref->objectname), ref->refname);
1424 if (!obj)
1425 die(_("parse_object_buffer failed on %s for %s"),
1426 oid_to_hex(&ref->objectname), ref->refname);
1428 grab_values(ref->value, 0, obj, buf, size);
1429 if (!eaten)
1430 free(buf);
1433 * If there is no atom that wants to know about tagged
1434 * object, we are done.
1436 if (!need_tagged || (obj->type != OBJ_TAG))
1437 return;
1440 * If it is a tag object, see if we use a value that derefs
1441 * the object, and if we do grab the object it refers to.
1443 tagged = &((struct tag *)obj)->tagged->oid;
1446 * NEEDSWORK: This derefs tag only once, which
1447 * is good to deal with chains of trust, but
1448 * is not consistent with what deref_tag() does
1449 * which peels the onion to the core.
1451 buf = get_obj(tagged, &obj, &size, &eaten);
1452 if (!buf)
1453 die(_("missing object %s for %s"),
1454 oid_to_hex(tagged), ref->refname);
1455 if (!obj)
1456 die(_("parse_object_buffer failed on %s for %s"),
1457 oid_to_hex(tagged), ref->refname);
1458 grab_values(ref->value, 1, obj, buf, size);
1459 if (!eaten)
1460 free(buf);
1464 * Given a ref, return the value for the atom. This lazily gets value
1465 * out of the object by calling populate value.
1467 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1469 if (!ref->value) {
1470 populate_value(ref);
1471 fill_missing_values(ref->value);
1473 *v = &ref->value[atom];
1477 * Unknown has to be "0" here, because that's the default value for
1478 * contains_cache slab entries that have not yet been assigned.
1480 enum contains_result {
1481 CONTAINS_UNKNOWN = 0,
1482 CONTAINS_NO,
1483 CONTAINS_YES
1486 define_commit_slab(contains_cache, enum contains_result);
1488 struct ref_filter_cbdata {
1489 struct ref_array *array;
1490 struct ref_filter *filter;
1491 struct contains_cache contains_cache;
1492 struct contains_cache no_contains_cache;
1496 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1497 * overflows.
1499 * At each recursion step, the stack items points to the commits whose
1500 * ancestors are to be inspected.
1502 struct contains_stack {
1503 int nr, alloc;
1504 struct contains_stack_entry {
1505 struct commit *commit;
1506 struct commit_list *parents;
1507 } *contains_stack;
1510 static int in_commit_list(const struct commit_list *want, struct commit *c)
1512 for (; want; want = want->next)
1513 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1514 return 1;
1515 return 0;
1519 * Test whether the candidate or one of its parents is contained in the list.
1520 * Do not recurse to find out, though, but return -1 if inconclusive.
1522 static enum contains_result contains_test(struct commit *candidate,
1523 const struct commit_list *want,
1524 struct contains_cache *cache)
1526 enum contains_result *cached = contains_cache_at(cache, candidate);
1528 /* If we already have the answer cached, return that. */
1529 if (*cached)
1530 return *cached;
1532 /* or are we it? */
1533 if (in_commit_list(want, candidate)) {
1534 *cached = CONTAINS_YES;
1535 return CONTAINS_YES;
1538 /* Otherwise, we don't know; prepare to recurse */
1539 parse_commit_or_die(candidate);
1540 return CONTAINS_UNKNOWN;
1543 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1545 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1546 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1547 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1550 static enum contains_result contains_tag_algo(struct commit *candidate,
1551 const struct commit_list *want,
1552 struct contains_cache *cache)
1554 struct contains_stack contains_stack = { 0, 0, NULL };
1555 enum contains_result result = contains_test(candidate, want, cache);
1557 if (result != CONTAINS_UNKNOWN)
1558 return result;
1560 push_to_contains_stack(candidate, &contains_stack);
1561 while (contains_stack.nr) {
1562 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1563 struct commit *commit = entry->commit;
1564 struct commit_list *parents = entry->parents;
1566 if (!parents) {
1567 *contains_cache_at(cache, commit) = CONTAINS_NO;
1568 contains_stack.nr--;
1571 * If we just popped the stack, parents->item has been marked,
1572 * therefore contains_test will return a meaningful yes/no.
1574 else switch (contains_test(parents->item, want, cache)) {
1575 case CONTAINS_YES:
1576 *contains_cache_at(cache, commit) = CONTAINS_YES;
1577 contains_stack.nr--;
1578 break;
1579 case CONTAINS_NO:
1580 entry->parents = parents->next;
1581 break;
1582 case CONTAINS_UNKNOWN:
1583 push_to_contains_stack(parents->item, &contains_stack);
1584 break;
1587 free(contains_stack.contains_stack);
1588 return contains_test(candidate, want, cache);
1591 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1592 struct commit_list *list, struct contains_cache *cache)
1594 if (filter->with_commit_tag_algo)
1595 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1596 return is_descendant_of(commit, list);
1600 * Return 1 if the refname matches one of the patterns, otherwise 0.
1601 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1602 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1603 * matches "refs/heads/mas*", too).
1605 static int match_pattern(const struct ref_filter *filter, const char *refname)
1607 const char **patterns = filter->name_patterns;
1608 unsigned flags = 0;
1610 if (filter->ignore_case)
1611 flags |= WM_CASEFOLD;
1614 * When no '--format' option is given we need to skip the prefix
1615 * for matching refs of tags and branches.
1617 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1618 skip_prefix(refname, "refs/heads/", &refname) ||
1619 skip_prefix(refname, "refs/remotes/", &refname) ||
1620 skip_prefix(refname, "refs/", &refname));
1622 for (; *patterns; patterns++) {
1623 if (!wildmatch(*patterns, refname, flags, NULL))
1624 return 1;
1626 return 0;
1630 * Return 1 if the refname matches one of the patterns, otherwise 0.
1631 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1632 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1633 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1635 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1637 const char **pattern = filter->name_patterns;
1638 int namelen = strlen(refname);
1639 unsigned flags = WM_PATHNAME;
1641 if (filter->ignore_case)
1642 flags |= WM_CASEFOLD;
1644 for (; *pattern; pattern++) {
1645 const char *p = *pattern;
1646 int plen = strlen(p);
1648 if ((plen <= namelen) &&
1649 !strncmp(refname, p, plen) &&
1650 (refname[plen] == '\0' ||
1651 refname[plen] == '/' ||
1652 p[plen-1] == '/'))
1653 return 1;
1654 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1655 return 1;
1657 return 0;
1660 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1661 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1663 if (!*filter->name_patterns)
1664 return 1; /* No pattern always matches */
1665 if (filter->match_as_path)
1666 return match_name_as_path(filter, refname);
1667 return match_pattern(filter, refname);
1671 * Given a ref (sha1, refname), check if the ref belongs to the array
1672 * of sha1s. If the given ref is a tag, check if the given tag points
1673 * at one of the sha1s in the given sha1 array.
1674 * the given sha1_array.
1675 * NEEDSWORK:
1676 * 1. Only a single level of inderection is obtained, we might want to
1677 * change this to account for multiple levels (e.g. annotated tags
1678 * pointing to annotated tags pointing to a commit.)
1679 * 2. As the refs are cached we might know what refname peels to without
1680 * the need to parse the object via parse_object(). peel_ref() might be a
1681 * more efficient alternative to obtain the pointee.
1683 static const struct object_id *match_points_at(struct oid_array *points_at,
1684 const struct object_id *oid,
1685 const char *refname)
1687 const struct object_id *tagged_oid = NULL;
1688 struct object *obj;
1690 if (oid_array_lookup(points_at, oid) >= 0)
1691 return oid;
1692 obj = parse_object(oid);
1693 if (!obj)
1694 die(_("malformed object at '%s'"), refname);
1695 if (obj->type == OBJ_TAG)
1696 tagged_oid = &((struct tag *)obj)->tagged->oid;
1697 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1698 return tagged_oid;
1699 return NULL;
1702 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1703 static struct ref_array_item *new_ref_array_item(const char *refname,
1704 const unsigned char *objectname,
1705 int flag)
1707 struct ref_array_item *ref;
1708 FLEX_ALLOC_STR(ref, refname, refname);
1709 hashcpy(ref->objectname.hash, objectname);
1710 ref->flag = flag;
1712 return ref;
1715 static int ref_kind_from_refname(const char *refname)
1717 unsigned int i;
1719 static struct {
1720 const char *prefix;
1721 unsigned int kind;
1722 } ref_kind[] = {
1723 { "refs/heads/" , FILTER_REFS_BRANCHES },
1724 { "refs/remotes/" , FILTER_REFS_REMOTES },
1725 { "refs/tags/", FILTER_REFS_TAGS}
1728 if (!strcmp(refname, "HEAD"))
1729 return FILTER_REFS_DETACHED_HEAD;
1731 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1732 if (starts_with(refname, ref_kind[i].prefix))
1733 return ref_kind[i].kind;
1736 return FILTER_REFS_OTHERS;
1739 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1741 if (filter->kind == FILTER_REFS_BRANCHES ||
1742 filter->kind == FILTER_REFS_REMOTES ||
1743 filter->kind == FILTER_REFS_TAGS)
1744 return filter->kind;
1745 return ref_kind_from_refname(refname);
1749 * A call-back given to for_each_ref(). Filter refs and keep them for
1750 * later object processing.
1752 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1754 struct ref_filter_cbdata *ref_cbdata = cb_data;
1755 struct ref_filter *filter = ref_cbdata->filter;
1756 struct ref_array_item *ref;
1757 struct commit *commit = NULL;
1758 unsigned int kind;
1760 if (flag & REF_BAD_NAME) {
1761 warning(_("ignoring ref with broken name %s"), refname);
1762 return 0;
1765 if (flag & REF_ISBROKEN) {
1766 warning(_("ignoring broken ref %s"), refname);
1767 return 0;
1770 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1771 kind = filter_ref_kind(filter, refname);
1772 if (!(kind & filter->kind))
1773 return 0;
1775 if (!filter_pattern_match(filter, refname))
1776 return 0;
1778 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1779 return 0;
1782 * A merge filter is applied on refs pointing to commits. Hence
1783 * obtain the commit using the 'oid' available and discard all
1784 * non-commits early. The actual filtering is done later.
1786 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1787 commit = lookup_commit_reference_gently(oid, 1);
1788 if (!commit)
1789 return 0;
1790 /* We perform the filtering for the '--contains' option... */
1791 if (filter->with_commit &&
1792 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1793 return 0;
1794 /* ...or for the `--no-contains' option */
1795 if (filter->no_commit &&
1796 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1797 return 0;
1801 * We do not open the object yet; sort may only need refname
1802 * to do its job and the resulting list may yet to be pruned
1803 * by maxcount logic.
1805 ref = new_ref_array_item(refname, oid->hash, flag);
1806 ref->commit = commit;
1808 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1809 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1810 ref->kind = kind;
1811 return 0;
1814 /* Free memory allocated for a ref_array_item */
1815 static void free_array_item(struct ref_array_item *item)
1817 free((char *)item->symref);
1818 free(item);
1821 /* Free all memory allocated for ref_array */
1822 void ref_array_clear(struct ref_array *array)
1824 int i;
1826 for (i = 0; i < array->nr; i++)
1827 free_array_item(array->items[i]);
1828 free(array->items);
1829 array->items = NULL;
1830 array->nr = array->alloc = 0;
1833 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1835 struct rev_info revs;
1836 int i, old_nr;
1837 struct ref_filter *filter = ref_cbdata->filter;
1838 struct ref_array *array = ref_cbdata->array;
1839 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1841 init_revisions(&revs, NULL);
1843 for (i = 0; i < array->nr; i++) {
1844 struct ref_array_item *item = array->items[i];
1845 add_pending_object(&revs, &item->commit->object, item->refname);
1846 to_clear[i] = item->commit;
1849 filter->merge_commit->object.flags |= UNINTERESTING;
1850 add_pending_object(&revs, &filter->merge_commit->object, "");
1852 revs.limited = 1;
1853 if (prepare_revision_walk(&revs))
1854 die(_("revision walk setup failed"));
1856 old_nr = array->nr;
1857 array->nr = 0;
1859 for (i = 0; i < old_nr; i++) {
1860 struct ref_array_item *item = array->items[i];
1861 struct commit *commit = item->commit;
1863 int is_merged = !!(commit->object.flags & UNINTERESTING);
1865 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1866 array->items[array->nr++] = array->items[i];
1867 else
1868 free_array_item(item);
1871 for (i = 0; i < old_nr; i++)
1872 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1873 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1874 free(to_clear);
1878 * API for filtering a set of refs. Based on the type of refs the user
1879 * has requested, we iterate through those refs and apply filters
1880 * as per the given ref_filter structure and finally store the
1881 * filtered refs in the ref_array structure.
1883 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1885 struct ref_filter_cbdata ref_cbdata;
1886 int ret = 0;
1887 unsigned int broken = 0;
1889 ref_cbdata.array = array;
1890 ref_cbdata.filter = filter;
1892 if (type & FILTER_REFS_INCLUDE_BROKEN)
1893 broken = 1;
1894 filter->kind = type & FILTER_REFS_KIND_MASK;
1896 init_contains_cache(&ref_cbdata.contains_cache);
1897 init_contains_cache(&ref_cbdata.no_contains_cache);
1899 /* Simple per-ref filtering */
1900 if (!filter->kind)
1901 die("filter_refs: invalid type");
1902 else {
1904 * For common cases where we need only branches or remotes or tags,
1905 * we only iterate through those refs. If a mix of refs is needed,
1906 * we iterate over all refs and filter out required refs with the help
1907 * of filter_ref_kind().
1909 if (filter->kind == FILTER_REFS_BRANCHES)
1910 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1911 else if (filter->kind == FILTER_REFS_REMOTES)
1912 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1913 else if (filter->kind == FILTER_REFS_TAGS)
1914 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1915 else if (filter->kind & FILTER_REFS_ALL)
1916 ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1917 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1918 head_ref(ref_filter_handler, &ref_cbdata);
1921 clear_contains_cache(&ref_cbdata.contains_cache);
1922 clear_contains_cache(&ref_cbdata.no_contains_cache);
1924 /* Filters that need revision walking */
1925 if (filter->merge_commit)
1926 do_merge_filter(&ref_cbdata);
1928 return ret;
1931 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1933 struct atom_value *va, *vb;
1934 int cmp;
1935 cmp_type cmp_type = used_atom[s->atom].type;
1936 int (*cmp_fn)(const char *, const char *);
1938 get_ref_atom_value(a, s->atom, &va);
1939 get_ref_atom_value(b, s->atom, &vb);
1940 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
1941 if (s->version)
1942 cmp = versioncmp(va->s, vb->s);
1943 else if (cmp_type == FIELD_STR)
1944 cmp = cmp_fn(va->s, vb->s);
1945 else {
1946 if (va->value < vb->value)
1947 cmp = -1;
1948 else if (va->value == vb->value)
1949 cmp = cmp_fn(a->refname, b->refname);
1950 else
1951 cmp = 1;
1954 return (s->reverse) ? -cmp : cmp;
1957 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
1959 struct ref_array_item *a = *((struct ref_array_item **)a_);
1960 struct ref_array_item *b = *((struct ref_array_item **)b_);
1961 struct ref_sorting *s;
1963 for (s = ref_sorting; s; s = s->next) {
1964 int cmp = cmp_ref_sorting(s, a, b);
1965 if (cmp)
1966 return cmp;
1968 return 0;
1971 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1973 QSORT_S(array->items, array->nr, compare_refs, sorting);
1976 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1978 struct strbuf *s = &state->stack->output;
1980 while (*cp && (!ep || cp < ep)) {
1981 if (*cp == '%') {
1982 if (cp[1] == '%')
1983 cp++;
1984 else {
1985 int ch = hex2chr(cp + 1);
1986 if (0 <= ch) {
1987 strbuf_addch(s, ch);
1988 cp += 3;
1989 continue;
1993 strbuf_addch(s, *cp);
1994 cp++;
1998 void format_ref_array_item(struct ref_array_item *info, const char *format,
1999 int quote_style, struct strbuf *final_buf)
2001 const char *cp, *sp, *ep;
2002 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2004 state.quote_style = quote_style;
2005 push_stack_element(&state.stack);
2007 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2008 struct atom_value *atomv;
2010 ep = strchr(sp, ')');
2011 if (cp < sp)
2012 append_literal(cp, sp, &state);
2013 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
2014 atomv->handler(atomv, &state);
2016 if (*cp) {
2017 sp = cp + strlen(cp);
2018 append_literal(cp, sp, &state);
2020 if (need_color_reset_at_eol) {
2021 struct atom_value resetv;
2022 char color[COLOR_MAXLEN] = "";
2024 if (color_parse("reset", color) < 0)
2025 die("BUG: couldn't parse 'reset' as a color");
2026 resetv.s = color;
2027 append_atom(&resetv, &state);
2029 if (state.stack->prev)
2030 die(_("format: %%(end) atom missing"));
2031 strbuf_addbuf(final_buf, &state.stack->output);
2032 pop_stack_element(&state.stack);
2035 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
2037 struct strbuf final_buf = STRBUF_INIT;
2039 format_ref_array_item(info, format, quote_style, &final_buf);
2040 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2041 strbuf_release(&final_buf);
2042 putchar('\n');
2045 void pretty_print_ref(const char *name, const unsigned char *sha1,
2046 const char *format)
2048 struct ref_array_item *ref_item;
2049 ref_item = new_ref_array_item(name, sha1, 0);
2050 ref_item->kind = ref_kind_from_refname(name);
2051 show_ref_array_item(ref_item, format, 0);
2052 free_array_item(ref_item);
2055 /* If no sorting option is given, use refname to sort as default */
2056 struct ref_sorting *ref_default_sorting(void)
2058 static const char cstr_name[] = "refname";
2060 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2062 sorting->next = NULL;
2063 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
2064 return sorting;
2067 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2069 struct ref_sorting **sorting_tail = opt->value;
2070 struct ref_sorting *s;
2071 int len;
2073 if (!arg) /* should --no-sort void the list ? */
2074 return -1;
2076 s = xcalloc(1, sizeof(*s));
2077 s->next = *sorting_tail;
2078 *sorting_tail = s;
2080 if (*arg == '-') {
2081 s->reverse = 1;
2082 arg++;
2084 if (skip_prefix(arg, "version:", &arg) ||
2085 skip_prefix(arg, "v:", &arg))
2086 s->version = 1;
2087 len = strlen(arg);
2088 s->atom = parse_ref_filter_atom(arg, arg+len);
2089 return 0;
2092 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2094 struct ref_filter *rf = opt->value;
2095 struct object_id oid;
2096 int no_merged = starts_with(opt->long_name, "no");
2098 if (rf->merge) {
2099 if (no_merged) {
2100 return opterror(opt, "is incompatible with --merged", 0);
2101 } else {
2102 return opterror(opt, "is incompatible with --no-merged", 0);
2106 rf->merge = no_merged
2107 ? REF_FILTER_MERGED_OMIT
2108 : REF_FILTER_MERGED_INCLUDE;
2110 if (get_oid(arg, &oid))
2111 die(_("malformed object name %s"), arg);
2113 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2114 if (!rf->merge_commit)
2115 return opterror(opt, "must point to a commit", 0);
2117 return 0;