doc: describe git svn init --ignore-refs
[git/git-svn.git] / ref-filter.c
blobab32bc9c3145c85c839c660c54b61f13fe9cb51a
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)
1262 * TRANSLATORS: make sure this matches "HEAD
1263 * detached at " in wt-status.c
1265 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1266 state.detached_from);
1267 else
1269 * TRANSLATORS: make sure this matches "HEAD
1270 * detached from " in wt-status.c
1272 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1273 state.detached_from);
1275 else
1276 strbuf_addstr(&desc, _("(no branch)"));
1277 free(state.branch);
1278 free(state.onto);
1279 free(state.detached_from);
1280 return strbuf_detach(&desc, NULL);
1283 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1285 if (!ref->symref)
1286 return "";
1287 else
1288 return show_ref(&atom->u.refname, ref->symref);
1291 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1293 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1294 return get_head_description();
1295 return show_ref(&atom->u.refname, ref->refname);
1299 * Parse the object referred by ref, and grab needed value.
1301 static void populate_value(struct ref_array_item *ref)
1303 void *buf;
1304 struct object *obj;
1305 int eaten, i;
1306 unsigned long size;
1307 const struct object_id *tagged;
1309 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1311 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1312 struct object_id unused1;
1313 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1314 unused1.hash, NULL);
1315 if (!ref->symref)
1316 ref->symref = "";
1319 /* Fill in specials first */
1320 for (i = 0; i < used_atom_cnt; i++) {
1321 struct used_atom *atom = &used_atom[i];
1322 const char *name = used_atom[i].name;
1323 struct atom_value *v = &ref->value[i];
1324 int deref = 0;
1325 const char *refname;
1326 struct branch *branch = NULL;
1328 v->handler = append_atom;
1329 v->atom = atom;
1331 if (*name == '*') {
1332 deref = 1;
1333 name++;
1336 if (starts_with(name, "refname"))
1337 refname = get_refname(atom, ref);
1338 else if (starts_with(name, "symref"))
1339 refname = get_symref(atom, ref);
1340 else if (starts_with(name, "upstream")) {
1341 const char *branch_name;
1342 /* only local branches may have an upstream */
1343 if (!skip_prefix(ref->refname, "refs/heads/",
1344 &branch_name))
1345 continue;
1346 branch = branch_get(branch_name);
1348 refname = branch_get_upstream(branch, NULL);
1349 if (refname)
1350 fill_remote_ref_details(atom, refname, branch, &v->s);
1351 continue;
1352 } else if (starts_with(name, "push")) {
1353 const char *branch_name;
1354 if (!skip_prefix(ref->refname, "refs/heads/",
1355 &branch_name))
1356 continue;
1357 branch = branch_get(branch_name);
1359 refname = branch_get_push(branch, NULL);
1360 if (!refname)
1361 continue;
1362 fill_remote_ref_details(atom, refname, branch, &v->s);
1363 continue;
1364 } else if (starts_with(name, "color:")) {
1365 v->s = atom->u.color;
1366 continue;
1367 } else if (!strcmp(name, "flag")) {
1368 char buf[256], *cp = buf;
1369 if (ref->flag & REF_ISSYMREF)
1370 cp = copy_advance(cp, ",symref");
1371 if (ref->flag & REF_ISPACKED)
1372 cp = copy_advance(cp, ",packed");
1373 if (cp == buf)
1374 v->s = "";
1375 else {
1376 *cp = '\0';
1377 v->s = xstrdup(buf + 1);
1379 continue;
1380 } else if (!deref && grab_objectname(name, ref->objectname.hash, v, atom)) {
1381 continue;
1382 } else if (!strcmp(name, "HEAD")) {
1383 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1384 v->s = "*";
1385 else
1386 v->s = " ";
1387 continue;
1388 } else if (starts_with(name, "align")) {
1389 v->handler = align_atom_handler;
1390 continue;
1391 } else if (!strcmp(name, "end")) {
1392 v->handler = end_atom_handler;
1393 continue;
1394 } else if (starts_with(name, "if")) {
1395 const char *s;
1397 if (skip_prefix(name, "if:", &s))
1398 v->s = xstrdup(s);
1399 v->handler = if_atom_handler;
1400 continue;
1401 } else if (!strcmp(name, "then")) {
1402 v->handler = then_atom_handler;
1403 continue;
1404 } else if (!strcmp(name, "else")) {
1405 v->handler = else_atom_handler;
1406 continue;
1407 } else
1408 continue;
1410 if (!deref)
1411 v->s = refname;
1412 else
1413 v->s = xstrfmt("%s^{}", refname);
1416 for (i = 0; i < used_atom_cnt; i++) {
1417 struct atom_value *v = &ref->value[i];
1418 if (v->s == NULL)
1419 goto need_obj;
1421 return;
1423 need_obj:
1424 buf = get_obj(&ref->objectname, &obj, &size, &eaten);
1425 if (!buf)
1426 die(_("missing object %s for %s"),
1427 oid_to_hex(&ref->objectname), ref->refname);
1428 if (!obj)
1429 die(_("parse_object_buffer failed on %s for %s"),
1430 oid_to_hex(&ref->objectname), ref->refname);
1432 grab_values(ref->value, 0, obj, buf, size);
1433 if (!eaten)
1434 free(buf);
1437 * If there is no atom that wants to know about tagged
1438 * object, we are done.
1440 if (!need_tagged || (obj->type != OBJ_TAG))
1441 return;
1444 * If it is a tag object, see if we use a value that derefs
1445 * the object, and if we do grab the object it refers to.
1447 tagged = &((struct tag *)obj)->tagged->oid;
1450 * NEEDSWORK: This derefs tag only once, which
1451 * is good to deal with chains of trust, but
1452 * is not consistent with what deref_tag() does
1453 * which peels the onion to the core.
1455 buf = get_obj(tagged, &obj, &size, &eaten);
1456 if (!buf)
1457 die(_("missing object %s for %s"),
1458 oid_to_hex(tagged), ref->refname);
1459 if (!obj)
1460 die(_("parse_object_buffer failed on %s for %s"),
1461 oid_to_hex(tagged), ref->refname);
1462 grab_values(ref->value, 1, obj, buf, size);
1463 if (!eaten)
1464 free(buf);
1468 * Given a ref, return the value for the atom. This lazily gets value
1469 * out of the object by calling populate value.
1471 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1473 if (!ref->value) {
1474 populate_value(ref);
1475 fill_missing_values(ref->value);
1477 *v = &ref->value[atom];
1481 * Unknown has to be "0" here, because that's the default value for
1482 * contains_cache slab entries that have not yet been assigned.
1484 enum contains_result {
1485 CONTAINS_UNKNOWN = 0,
1486 CONTAINS_NO,
1487 CONTAINS_YES
1490 define_commit_slab(contains_cache, enum contains_result);
1492 struct ref_filter_cbdata {
1493 struct ref_array *array;
1494 struct ref_filter *filter;
1495 struct contains_cache contains_cache;
1496 struct contains_cache no_contains_cache;
1500 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1501 * overflows.
1503 * At each recursion step, the stack items points to the commits whose
1504 * ancestors are to be inspected.
1506 struct contains_stack {
1507 int nr, alloc;
1508 struct contains_stack_entry {
1509 struct commit *commit;
1510 struct commit_list *parents;
1511 } *contains_stack;
1514 static int in_commit_list(const struct commit_list *want, struct commit *c)
1516 for (; want; want = want->next)
1517 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1518 return 1;
1519 return 0;
1523 * Test whether the candidate or one of its parents is contained in the list.
1524 * Do not recurse to find out, though, but return -1 if inconclusive.
1526 static enum contains_result contains_test(struct commit *candidate,
1527 const struct commit_list *want,
1528 struct contains_cache *cache)
1530 enum contains_result *cached = contains_cache_at(cache, candidate);
1532 /* If we already have the answer cached, return that. */
1533 if (*cached)
1534 return *cached;
1536 /* or are we it? */
1537 if (in_commit_list(want, candidate)) {
1538 *cached = CONTAINS_YES;
1539 return CONTAINS_YES;
1542 /* Otherwise, we don't know; prepare to recurse */
1543 parse_commit_or_die(candidate);
1544 return CONTAINS_UNKNOWN;
1547 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1549 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1550 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1551 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1554 static enum contains_result contains_tag_algo(struct commit *candidate,
1555 const struct commit_list *want,
1556 struct contains_cache *cache)
1558 struct contains_stack contains_stack = { 0, 0, NULL };
1559 enum contains_result result = contains_test(candidate, want, cache);
1561 if (result != CONTAINS_UNKNOWN)
1562 return result;
1564 push_to_contains_stack(candidate, &contains_stack);
1565 while (contains_stack.nr) {
1566 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1567 struct commit *commit = entry->commit;
1568 struct commit_list *parents = entry->parents;
1570 if (!parents) {
1571 *contains_cache_at(cache, commit) = CONTAINS_NO;
1572 contains_stack.nr--;
1575 * If we just popped the stack, parents->item has been marked,
1576 * therefore contains_test will return a meaningful yes/no.
1578 else switch (contains_test(parents->item, want, cache)) {
1579 case CONTAINS_YES:
1580 *contains_cache_at(cache, commit) = CONTAINS_YES;
1581 contains_stack.nr--;
1582 break;
1583 case CONTAINS_NO:
1584 entry->parents = parents->next;
1585 break;
1586 case CONTAINS_UNKNOWN:
1587 push_to_contains_stack(parents->item, &contains_stack);
1588 break;
1591 free(contains_stack.contains_stack);
1592 return contains_test(candidate, want, cache);
1595 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1596 struct commit_list *list, struct contains_cache *cache)
1598 if (filter->with_commit_tag_algo)
1599 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1600 return is_descendant_of(commit, list);
1604 * Return 1 if the refname matches one of the patterns, otherwise 0.
1605 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1606 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1607 * matches "refs/heads/mas*", too).
1609 static int match_pattern(const struct ref_filter *filter, const char *refname)
1611 const char **patterns = filter->name_patterns;
1612 unsigned flags = 0;
1614 if (filter->ignore_case)
1615 flags |= WM_CASEFOLD;
1618 * When no '--format' option is given we need to skip the prefix
1619 * for matching refs of tags and branches.
1621 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1622 skip_prefix(refname, "refs/heads/", &refname) ||
1623 skip_prefix(refname, "refs/remotes/", &refname) ||
1624 skip_prefix(refname, "refs/", &refname));
1626 for (; *patterns; patterns++) {
1627 if (!wildmatch(*patterns, refname, flags, NULL))
1628 return 1;
1630 return 0;
1634 * Return 1 if the refname matches one of the patterns, otherwise 0.
1635 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1636 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1637 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1639 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1641 const char **pattern = filter->name_patterns;
1642 int namelen = strlen(refname);
1643 unsigned flags = WM_PATHNAME;
1645 if (filter->ignore_case)
1646 flags |= WM_CASEFOLD;
1648 for (; *pattern; pattern++) {
1649 const char *p = *pattern;
1650 int plen = strlen(p);
1652 if ((plen <= namelen) &&
1653 !strncmp(refname, p, plen) &&
1654 (refname[plen] == '\0' ||
1655 refname[plen] == '/' ||
1656 p[plen-1] == '/'))
1657 return 1;
1658 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1659 return 1;
1661 return 0;
1664 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1665 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1667 if (!*filter->name_patterns)
1668 return 1; /* No pattern always matches */
1669 if (filter->match_as_path)
1670 return match_name_as_path(filter, refname);
1671 return match_pattern(filter, refname);
1675 * Find the longest prefix of pattern we can pass to
1676 * `for_each_fullref_in()`, namely the part of pattern preceding the
1677 * first glob character. (Note that `for_each_fullref_in()` is
1678 * perfectly happy working with a prefix that doesn't end at a
1679 * pathname component boundary.)
1681 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1683 const char *p;
1685 for (p = pattern; *p && !is_glob_special(*p); p++)
1688 strbuf_add(out, pattern, p - pattern);
1692 * This is the same as for_each_fullref_in(), but it tries to iterate
1693 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1694 * pattern match, so the callback still has to match each ref individually.
1696 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1697 each_ref_fn cb,
1698 void *cb_data,
1699 int broken)
1701 struct strbuf prefix = STRBUF_INIT;
1702 int ret;
1704 if (!filter->match_as_path) {
1706 * in this case, the patterns are applied after
1707 * prefixes like "refs/heads/" etc. are stripped off,
1708 * so we have to look at everything:
1710 return for_each_fullref_in("", cb, cb_data, broken);
1713 if (!filter->name_patterns[0]) {
1714 /* no patterns; we have to look at everything */
1715 return for_each_fullref_in("", cb, cb_data, broken);
1718 if (filter->name_patterns[1]) {
1720 * multiple patterns; in theory this could still work as long
1721 * as the patterns are disjoint. We'd just make multiple calls
1722 * to for_each_ref(). But if they're not disjoint, we'd end up
1723 * reporting the same ref multiple times. So let's punt on that
1724 * for now.
1726 return for_each_fullref_in("", cb, cb_data, broken);
1729 find_longest_prefix(&prefix, filter->name_patterns[0]);
1731 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1732 strbuf_release(&prefix);
1733 return ret;
1737 * Given a ref (sha1, refname), check if the ref belongs to the array
1738 * of sha1s. If the given ref is a tag, check if the given tag points
1739 * at one of the sha1s in the given sha1 array.
1740 * the given sha1_array.
1741 * NEEDSWORK:
1742 * 1. Only a single level of inderection is obtained, we might want to
1743 * change this to account for multiple levels (e.g. annotated tags
1744 * pointing to annotated tags pointing to a commit.)
1745 * 2. As the refs are cached we might know what refname peels to without
1746 * the need to parse the object via parse_object(). peel_ref() might be a
1747 * more efficient alternative to obtain the pointee.
1749 static const struct object_id *match_points_at(struct oid_array *points_at,
1750 const struct object_id *oid,
1751 const char *refname)
1753 const struct object_id *tagged_oid = NULL;
1754 struct object *obj;
1756 if (oid_array_lookup(points_at, oid) >= 0)
1757 return oid;
1758 obj = parse_object(oid);
1759 if (!obj)
1760 die(_("malformed object at '%s'"), refname);
1761 if (obj->type == OBJ_TAG)
1762 tagged_oid = &((struct tag *)obj)->tagged->oid;
1763 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1764 return tagged_oid;
1765 return NULL;
1768 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1769 static struct ref_array_item *new_ref_array_item(const char *refname,
1770 const unsigned char *objectname,
1771 int flag)
1773 struct ref_array_item *ref;
1774 FLEX_ALLOC_STR(ref, refname, refname);
1775 hashcpy(ref->objectname.hash, objectname);
1776 ref->flag = flag;
1778 return ref;
1781 static int ref_kind_from_refname(const char *refname)
1783 unsigned int i;
1785 static struct {
1786 const char *prefix;
1787 unsigned int kind;
1788 } ref_kind[] = {
1789 { "refs/heads/" , FILTER_REFS_BRANCHES },
1790 { "refs/remotes/" , FILTER_REFS_REMOTES },
1791 { "refs/tags/", FILTER_REFS_TAGS}
1794 if (!strcmp(refname, "HEAD"))
1795 return FILTER_REFS_DETACHED_HEAD;
1797 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1798 if (starts_with(refname, ref_kind[i].prefix))
1799 return ref_kind[i].kind;
1802 return FILTER_REFS_OTHERS;
1805 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1807 if (filter->kind == FILTER_REFS_BRANCHES ||
1808 filter->kind == FILTER_REFS_REMOTES ||
1809 filter->kind == FILTER_REFS_TAGS)
1810 return filter->kind;
1811 return ref_kind_from_refname(refname);
1815 * A call-back given to for_each_ref(). Filter refs and keep them for
1816 * later object processing.
1818 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1820 struct ref_filter_cbdata *ref_cbdata = cb_data;
1821 struct ref_filter *filter = ref_cbdata->filter;
1822 struct ref_array_item *ref;
1823 struct commit *commit = NULL;
1824 unsigned int kind;
1826 if (flag & REF_BAD_NAME) {
1827 warning(_("ignoring ref with broken name %s"), refname);
1828 return 0;
1831 if (flag & REF_ISBROKEN) {
1832 warning(_("ignoring broken ref %s"), refname);
1833 return 0;
1836 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1837 kind = filter_ref_kind(filter, refname);
1838 if (!(kind & filter->kind))
1839 return 0;
1841 if (!filter_pattern_match(filter, refname))
1842 return 0;
1844 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1845 return 0;
1848 * A merge filter is applied on refs pointing to commits. Hence
1849 * obtain the commit using the 'oid' available and discard all
1850 * non-commits early. The actual filtering is done later.
1852 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1853 commit = lookup_commit_reference_gently(oid, 1);
1854 if (!commit)
1855 return 0;
1856 /* We perform the filtering for the '--contains' option... */
1857 if (filter->with_commit &&
1858 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1859 return 0;
1860 /* ...or for the `--no-contains' option */
1861 if (filter->no_commit &&
1862 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1863 return 0;
1867 * We do not open the object yet; sort may only need refname
1868 * to do its job and the resulting list may yet to be pruned
1869 * by maxcount logic.
1871 ref = new_ref_array_item(refname, oid->hash, flag);
1872 ref->commit = commit;
1874 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1875 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1876 ref->kind = kind;
1877 return 0;
1880 /* Free memory allocated for a ref_array_item */
1881 static void free_array_item(struct ref_array_item *item)
1883 free((char *)item->symref);
1884 free(item);
1887 /* Free all memory allocated for ref_array */
1888 void ref_array_clear(struct ref_array *array)
1890 int i;
1892 for (i = 0; i < array->nr; i++)
1893 free_array_item(array->items[i]);
1894 free(array->items);
1895 array->items = NULL;
1896 array->nr = array->alloc = 0;
1899 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1901 struct rev_info revs;
1902 int i, old_nr;
1903 struct ref_filter *filter = ref_cbdata->filter;
1904 struct ref_array *array = ref_cbdata->array;
1905 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1907 init_revisions(&revs, NULL);
1909 for (i = 0; i < array->nr; i++) {
1910 struct ref_array_item *item = array->items[i];
1911 add_pending_object(&revs, &item->commit->object, item->refname);
1912 to_clear[i] = item->commit;
1915 filter->merge_commit->object.flags |= UNINTERESTING;
1916 add_pending_object(&revs, &filter->merge_commit->object, "");
1918 revs.limited = 1;
1919 if (prepare_revision_walk(&revs))
1920 die(_("revision walk setup failed"));
1922 old_nr = array->nr;
1923 array->nr = 0;
1925 for (i = 0; i < old_nr; i++) {
1926 struct ref_array_item *item = array->items[i];
1927 struct commit *commit = item->commit;
1929 int is_merged = !!(commit->object.flags & UNINTERESTING);
1931 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1932 array->items[array->nr++] = array->items[i];
1933 else
1934 free_array_item(item);
1937 for (i = 0; i < old_nr; i++)
1938 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1939 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1940 free(to_clear);
1944 * API for filtering a set of refs. Based on the type of refs the user
1945 * has requested, we iterate through those refs and apply filters
1946 * as per the given ref_filter structure and finally store the
1947 * filtered refs in the ref_array structure.
1949 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1951 struct ref_filter_cbdata ref_cbdata;
1952 int ret = 0;
1953 unsigned int broken = 0;
1955 ref_cbdata.array = array;
1956 ref_cbdata.filter = filter;
1958 if (type & FILTER_REFS_INCLUDE_BROKEN)
1959 broken = 1;
1960 filter->kind = type & FILTER_REFS_KIND_MASK;
1962 init_contains_cache(&ref_cbdata.contains_cache);
1963 init_contains_cache(&ref_cbdata.no_contains_cache);
1965 /* Simple per-ref filtering */
1966 if (!filter->kind)
1967 die("filter_refs: invalid type");
1968 else {
1970 * For common cases where we need only branches or remotes or tags,
1971 * we only iterate through those refs. If a mix of refs is needed,
1972 * we iterate over all refs and filter out required refs with the help
1973 * of filter_ref_kind().
1975 if (filter->kind == FILTER_REFS_BRANCHES)
1976 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1977 else if (filter->kind == FILTER_REFS_REMOTES)
1978 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1979 else if (filter->kind == FILTER_REFS_TAGS)
1980 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1981 else if (filter->kind & FILTER_REFS_ALL)
1982 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
1983 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1984 head_ref(ref_filter_handler, &ref_cbdata);
1987 clear_contains_cache(&ref_cbdata.contains_cache);
1988 clear_contains_cache(&ref_cbdata.no_contains_cache);
1990 /* Filters that need revision walking */
1991 if (filter->merge_commit)
1992 do_merge_filter(&ref_cbdata);
1994 return ret;
1997 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1999 struct atom_value *va, *vb;
2000 int cmp;
2001 cmp_type cmp_type = used_atom[s->atom].type;
2002 int (*cmp_fn)(const char *, const char *);
2004 get_ref_atom_value(a, s->atom, &va);
2005 get_ref_atom_value(b, s->atom, &vb);
2006 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2007 if (s->version)
2008 cmp = versioncmp(va->s, vb->s);
2009 else if (cmp_type == FIELD_STR)
2010 cmp = cmp_fn(va->s, vb->s);
2011 else {
2012 if (va->value < vb->value)
2013 cmp = -1;
2014 else if (va->value == vb->value)
2015 cmp = cmp_fn(a->refname, b->refname);
2016 else
2017 cmp = 1;
2020 return (s->reverse) ? -cmp : cmp;
2023 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2025 struct ref_array_item *a = *((struct ref_array_item **)a_);
2026 struct ref_array_item *b = *((struct ref_array_item **)b_);
2027 struct ref_sorting *s;
2029 for (s = ref_sorting; s; s = s->next) {
2030 int cmp = cmp_ref_sorting(s, a, b);
2031 if (cmp)
2032 return cmp;
2034 return 0;
2037 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2039 QSORT_S(array->items, array->nr, compare_refs, sorting);
2042 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2044 struct strbuf *s = &state->stack->output;
2046 while (*cp && (!ep || cp < ep)) {
2047 if (*cp == '%') {
2048 if (cp[1] == '%')
2049 cp++;
2050 else {
2051 int ch = hex2chr(cp + 1);
2052 if (0 <= ch) {
2053 strbuf_addch(s, ch);
2054 cp += 3;
2055 continue;
2059 strbuf_addch(s, *cp);
2060 cp++;
2064 void format_ref_array_item(struct ref_array_item *info, const char *format,
2065 int quote_style, struct strbuf *final_buf)
2067 const char *cp, *sp, *ep;
2068 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2070 state.quote_style = quote_style;
2071 push_stack_element(&state.stack);
2073 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2074 struct atom_value *atomv;
2076 ep = strchr(sp, ')');
2077 if (cp < sp)
2078 append_literal(cp, sp, &state);
2079 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
2080 atomv->handler(atomv, &state);
2082 if (*cp) {
2083 sp = cp + strlen(cp);
2084 append_literal(cp, sp, &state);
2086 if (need_color_reset_at_eol) {
2087 struct atom_value resetv;
2088 char color[COLOR_MAXLEN] = "";
2090 if (color_parse("reset", color) < 0)
2091 die("BUG: couldn't parse 'reset' as a color");
2092 resetv.s = color;
2093 append_atom(&resetv, &state);
2095 if (state.stack->prev)
2096 die(_("format: %%(end) atom missing"));
2097 strbuf_addbuf(final_buf, &state.stack->output);
2098 pop_stack_element(&state.stack);
2101 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
2103 struct strbuf final_buf = STRBUF_INIT;
2105 format_ref_array_item(info, format, quote_style, &final_buf);
2106 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2107 strbuf_release(&final_buf);
2108 putchar('\n');
2111 void pretty_print_ref(const char *name, const unsigned char *sha1,
2112 const char *format)
2114 struct ref_array_item *ref_item;
2115 ref_item = new_ref_array_item(name, sha1, 0);
2116 ref_item->kind = ref_kind_from_refname(name);
2117 show_ref_array_item(ref_item, format, 0);
2118 free_array_item(ref_item);
2121 /* If no sorting option is given, use refname to sort as default */
2122 struct ref_sorting *ref_default_sorting(void)
2124 static const char cstr_name[] = "refname";
2126 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2128 sorting->next = NULL;
2129 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
2130 return sorting;
2133 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2135 struct ref_sorting **sorting_tail = opt->value;
2136 struct ref_sorting *s;
2137 int len;
2139 if (!arg) /* should --no-sort void the list ? */
2140 return -1;
2142 s = xcalloc(1, sizeof(*s));
2143 s->next = *sorting_tail;
2144 *sorting_tail = s;
2146 if (*arg == '-') {
2147 s->reverse = 1;
2148 arg++;
2150 if (skip_prefix(arg, "version:", &arg) ||
2151 skip_prefix(arg, "v:", &arg))
2152 s->version = 1;
2153 len = strlen(arg);
2154 s->atom = parse_ref_filter_atom(arg, arg+len);
2155 return 0;
2158 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2160 struct ref_filter *rf = opt->value;
2161 struct object_id oid;
2162 int no_merged = starts_with(opt->long_name, "no");
2164 if (rf->merge) {
2165 if (no_merged) {
2166 return opterror(opt, "is incompatible with --merged", 0);
2167 } else {
2168 return opterror(opt, "is incompatible with --no-merged", 0);
2172 rf->merge = no_merged
2173 ? REF_FILTER_MERGED_OMIT
2174 : REF_FILTER_MERGED_INCLUDE;
2176 if (get_oid(arg, &oid))
2177 die(_("malformed object name %s"), arg);
2179 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2180 if (!rf->merge_commit)
2181 return opterror(opt, "must point to a commit", 0);
2183 return 0;