Merge branch 'jk/grep-no-index-fix'
[git/git-svn.git] / ref-filter.c
blob1ec0fb8391ba6be716e76c688a0f9e2f0208adc2
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"
19 static struct ref_msg {
20 const char *gone;
21 const char *ahead;
22 const char *behind;
23 const char *ahead_behind;
24 } msgs = {
25 /* Untranslated plumbing messages: */
26 "gone",
27 "ahead %d",
28 "behind %d",
29 "ahead %d, behind %d"
32 void setup_ref_filter_porcelain_msg(void)
34 msgs.gone = _("gone");
35 msgs.ahead = _("ahead %d");
36 msgs.behind = _("behind %d");
37 msgs.ahead_behind = _("ahead %d, behind %d");
40 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
41 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
43 struct align {
44 align_type position;
45 unsigned int width;
48 struct if_then_else {
49 cmp_status cmp_status;
50 const char *str;
51 unsigned int then_atom_seen : 1,
52 else_atom_seen : 1,
53 condition_satisfied : 1;
56 struct refname_atom {
57 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
58 int lstrip, rstrip;
62 * An atom is a valid field atom listed below, possibly prefixed with
63 * a "*" to denote deref_tag().
65 * We parse given format string and sort specifiers, and make a list
66 * of properties that we need to extract out of objects. ref_array_item
67 * structure will hold an array of values extracted that can be
68 * indexed with the "atom number", which is an index into this
69 * array.
71 static struct used_atom {
72 const char *name;
73 cmp_type type;
74 union {
75 char color[COLOR_MAXLEN];
76 struct align align;
77 struct {
78 enum { RR_REF, RR_TRACK, RR_TRACKSHORT } option;
79 struct refname_atom refname;
80 unsigned int nobracket : 1;
81 } remote_ref;
82 struct {
83 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
84 unsigned int nlines;
85 } contents;
86 struct {
87 cmp_status cmp_status;
88 const char *str;
89 } if_then_else;
90 struct {
91 enum { O_FULL, O_LENGTH, O_SHORT } option;
92 unsigned int length;
93 } objectname;
94 struct refname_atom refname;
95 } u;
96 } *used_atom;
97 static int used_atom_cnt, need_tagged, need_symref;
98 static int need_color_reset_at_eol;
100 static void color_atom_parser(struct used_atom *atom, const char *color_value)
102 if (!color_value)
103 die(_("expected format: %%(color:<color>)"));
104 if (color_parse(color_value, atom->u.color) < 0)
105 die(_("unrecognized color: %%(color:%s)"), color_value);
108 static void refname_atom_parser_internal(struct refname_atom *atom,
109 const char *arg, const char *name)
111 if (!arg)
112 atom->option = R_NORMAL;
113 else if (!strcmp(arg, "short"))
114 atom->option = R_SHORT;
115 else if (skip_prefix(arg, "lstrip=", &arg) ||
116 skip_prefix(arg, "strip=", &arg)) {
117 atom->option = R_LSTRIP;
118 if (strtol_i(arg, 10, &atom->lstrip))
119 die(_("Integer value expected refname:lstrip=%s"), arg);
120 } else if (skip_prefix(arg, "rstrip=", &arg)) {
121 atom->option = R_RSTRIP;
122 if (strtol_i(arg, 10, &atom->rstrip))
123 die(_("Integer value expected refname:rstrip=%s"), arg);
124 } else
125 die(_("unrecognized %%(%s) argument: %s"), name, arg);
128 static void remote_ref_atom_parser(struct used_atom *atom, const char *arg)
130 struct string_list params = STRING_LIST_INIT_DUP;
131 int i;
133 if (!arg) {
134 atom->u.remote_ref.option = RR_REF;
135 refname_atom_parser_internal(&atom->u.remote_ref.refname,
136 arg, atom->name);
137 return;
140 atom->u.remote_ref.nobracket = 0;
141 string_list_split(&params, arg, ',', -1);
143 for (i = 0; i < params.nr; i++) {
144 const char *s = params.items[i].string;
146 if (!strcmp(s, "track"))
147 atom->u.remote_ref.option = RR_TRACK;
148 else if (!strcmp(s, "trackshort"))
149 atom->u.remote_ref.option = RR_TRACKSHORT;
150 else if (!strcmp(s, "nobracket"))
151 atom->u.remote_ref.nobracket = 1;
152 else {
153 atom->u.remote_ref.option = RR_REF;
154 refname_atom_parser_internal(&atom->u.remote_ref.refname,
155 arg, atom->name);
159 string_list_clear(&params, 0);
162 static void body_atom_parser(struct used_atom *atom, const char *arg)
164 if (arg)
165 die(_("%%(body) does not take arguments"));
166 atom->u.contents.option = C_BODY_DEP;
169 static void subject_atom_parser(struct used_atom *atom, const char *arg)
171 if (arg)
172 die(_("%%(subject) does not take arguments"));
173 atom->u.contents.option = C_SUB;
176 static void trailers_atom_parser(struct used_atom *atom, const char *arg)
178 if (arg)
179 die(_("%%(trailers) does not take arguments"));
180 atom->u.contents.option = C_TRAILERS;
183 static void contents_atom_parser(struct used_atom *atom, const char *arg)
185 if (!arg)
186 atom->u.contents.option = C_BARE;
187 else if (!strcmp(arg, "body"))
188 atom->u.contents.option = C_BODY;
189 else if (!strcmp(arg, "signature"))
190 atom->u.contents.option = C_SIG;
191 else if (!strcmp(arg, "subject"))
192 atom->u.contents.option = C_SUB;
193 else if (!strcmp(arg, "trailers"))
194 atom->u.contents.option = C_TRAILERS;
195 else if (skip_prefix(arg, "lines=", &arg)) {
196 atom->u.contents.option = C_LINES;
197 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
198 die(_("positive value expected contents:lines=%s"), arg);
199 } else
200 die(_("unrecognized %%(contents) argument: %s"), arg);
203 static void objectname_atom_parser(struct used_atom *atom, const char *arg)
205 if (!arg)
206 atom->u.objectname.option = O_FULL;
207 else if (!strcmp(arg, "short"))
208 atom->u.objectname.option = O_SHORT;
209 else if (skip_prefix(arg, "short=", &arg)) {
210 atom->u.objectname.option = O_LENGTH;
211 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
212 atom->u.objectname.length == 0)
213 die(_("positive value expected objectname:short=%s"), arg);
214 if (atom->u.objectname.length < MINIMUM_ABBREV)
215 atom->u.objectname.length = MINIMUM_ABBREV;
216 } else
217 die(_("unrecognized %%(objectname) argument: %s"), arg);
220 static void refname_atom_parser(struct used_atom *atom, const char *arg)
222 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
225 static align_type parse_align_position(const char *s)
227 if (!strcmp(s, "right"))
228 return ALIGN_RIGHT;
229 else if (!strcmp(s, "middle"))
230 return ALIGN_MIDDLE;
231 else if (!strcmp(s, "left"))
232 return ALIGN_LEFT;
233 return -1;
236 static void align_atom_parser(struct used_atom *atom, const char *arg)
238 struct align *align = &atom->u.align;
239 struct string_list params = STRING_LIST_INIT_DUP;
240 int i;
241 unsigned int width = ~0U;
243 if (!arg)
244 die(_("expected format: %%(align:<width>,<position>)"));
246 align->position = ALIGN_LEFT;
248 string_list_split(&params, arg, ',', -1);
249 for (i = 0; i < params.nr; i++) {
250 const char *s = params.items[i].string;
251 int position;
253 if (skip_prefix(s, "position=", &s)) {
254 position = parse_align_position(s);
255 if (position < 0)
256 die(_("unrecognized position:%s"), s);
257 align->position = position;
258 } else if (skip_prefix(s, "width=", &s)) {
259 if (strtoul_ui(s, 10, &width))
260 die(_("unrecognized width:%s"), s);
261 } else if (!strtoul_ui(s, 10, &width))
263 else if ((position = parse_align_position(s)) >= 0)
264 align->position = position;
265 else
266 die(_("unrecognized %%(align) argument: %s"), s);
269 if (width == ~0U)
270 die(_("positive width expected with the %%(align) atom"));
271 align->width = width;
272 string_list_clear(&params, 0);
275 static void if_atom_parser(struct used_atom *atom, const char *arg)
277 if (!arg) {
278 atom->u.if_then_else.cmp_status = COMPARE_NONE;
279 return;
280 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
281 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
282 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
283 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
284 } else {
285 die(_("unrecognized %%(if) argument: %s"), arg);
290 static struct {
291 const char *name;
292 cmp_type cmp_type;
293 void (*parser)(struct used_atom *atom, const char *arg);
294 } valid_atom[] = {
295 { "refname" , FIELD_STR, refname_atom_parser },
296 { "objecttype" },
297 { "objectsize", FIELD_ULONG },
298 { "objectname", FIELD_STR, objectname_atom_parser },
299 { "tree" },
300 { "parent" },
301 { "numparent", FIELD_ULONG },
302 { "object" },
303 { "type" },
304 { "tag" },
305 { "author" },
306 { "authorname" },
307 { "authoremail" },
308 { "authordate", FIELD_TIME },
309 { "committer" },
310 { "committername" },
311 { "committeremail" },
312 { "committerdate", FIELD_TIME },
313 { "tagger" },
314 { "taggername" },
315 { "taggeremail" },
316 { "taggerdate", FIELD_TIME },
317 { "creator" },
318 { "creatordate", FIELD_TIME },
319 { "subject", FIELD_STR, subject_atom_parser },
320 { "body", FIELD_STR, body_atom_parser },
321 { "trailers", FIELD_STR, trailers_atom_parser },
322 { "contents", FIELD_STR, contents_atom_parser },
323 { "upstream", FIELD_STR, remote_ref_atom_parser },
324 { "push", FIELD_STR, remote_ref_atom_parser },
325 { "symref", FIELD_STR, refname_atom_parser },
326 { "flag" },
327 { "HEAD" },
328 { "color", FIELD_STR, color_atom_parser },
329 { "align", FIELD_STR, align_atom_parser },
330 { "end" },
331 { "if", FIELD_STR, if_atom_parser },
332 { "then" },
333 { "else" },
336 #define REF_FORMATTING_STATE_INIT { 0, NULL }
338 struct ref_formatting_stack {
339 struct ref_formatting_stack *prev;
340 struct strbuf output;
341 void (*at_end)(struct ref_formatting_stack **stack);
342 void *at_end_data;
345 struct ref_formatting_state {
346 int quote_style;
347 struct ref_formatting_stack *stack;
350 struct atom_value {
351 const char *s;
352 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
353 unsigned long ul; /* used for sorting when not FIELD_STR */
354 struct used_atom *atom;
358 * Used to parse format string and sort specifiers
360 int parse_ref_filter_atom(const char *atom, const char *ep)
362 const char *sp;
363 const char *arg;
364 int i, at, atom_len;
366 sp = atom;
367 if (*sp == '*' && sp < ep)
368 sp++; /* deref */
369 if (ep <= sp)
370 die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
372 /* Do we have the atom already used elsewhere? */
373 for (i = 0; i < used_atom_cnt; i++) {
374 int len = strlen(used_atom[i].name);
375 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
376 return i;
380 * If the atom name has a colon, strip it and everything after
381 * it off - it specifies the format for this entry, and
382 * shouldn't be used for checking against the valid_atom
383 * table.
385 arg = memchr(sp, ':', ep - sp);
386 atom_len = (arg ? arg : ep) - sp;
388 /* Is the atom a valid one? */
389 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
390 int len = strlen(valid_atom[i].name);
391 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
392 break;
395 if (ARRAY_SIZE(valid_atom) <= i)
396 die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
398 /* Add it in, including the deref prefix */
399 at = used_atom_cnt;
400 used_atom_cnt++;
401 REALLOC_ARRAY(used_atom, used_atom_cnt);
402 used_atom[at].name = xmemdupz(atom, ep - atom);
403 used_atom[at].type = valid_atom[i].cmp_type;
404 if (arg)
405 arg = used_atom[at].name + (arg - atom) + 1;
406 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
407 if (valid_atom[i].parser)
408 valid_atom[i].parser(&used_atom[at], arg);
409 if (*atom == '*')
410 need_tagged = 1;
411 if (!strcmp(valid_atom[i].name, "symref"))
412 need_symref = 1;
413 return at;
416 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
418 switch (quote_style) {
419 case QUOTE_NONE:
420 strbuf_addstr(s, str);
421 break;
422 case QUOTE_SHELL:
423 sq_quote_buf(s, str);
424 break;
425 case QUOTE_PERL:
426 perl_quote_buf(s, str);
427 break;
428 case QUOTE_PYTHON:
429 python_quote_buf(s, str);
430 break;
431 case QUOTE_TCL:
432 tcl_quote_buf(s, str);
433 break;
437 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
440 * Quote formatting is only done when the stack has a single
441 * element. Otherwise quote formatting is done on the
442 * element's entire output strbuf when the %(end) atom is
443 * encountered.
445 if (!state->stack->prev)
446 quote_formatting(&state->stack->output, v->s, state->quote_style);
447 else
448 strbuf_addstr(&state->stack->output, v->s);
451 static void push_stack_element(struct ref_formatting_stack **stack)
453 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
455 strbuf_init(&s->output, 0);
456 s->prev = *stack;
457 *stack = s;
460 static void pop_stack_element(struct ref_formatting_stack **stack)
462 struct ref_formatting_stack *current = *stack;
463 struct ref_formatting_stack *prev = current->prev;
465 if (prev)
466 strbuf_addbuf(&prev->output, &current->output);
467 strbuf_release(&current->output);
468 free(current);
469 *stack = prev;
472 static void end_align_handler(struct ref_formatting_stack **stack)
474 struct ref_formatting_stack *cur = *stack;
475 struct align *align = (struct align *)cur->at_end_data;
476 struct strbuf s = STRBUF_INIT;
478 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
479 strbuf_swap(&cur->output, &s);
480 strbuf_release(&s);
483 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
485 struct ref_formatting_stack *new;
487 push_stack_element(&state->stack);
488 new = state->stack;
489 new->at_end = end_align_handler;
490 new->at_end_data = &atomv->atom->u.align;
493 static void if_then_else_handler(struct ref_formatting_stack **stack)
495 struct ref_formatting_stack *cur = *stack;
496 struct ref_formatting_stack *prev = cur->prev;
497 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
499 if (!if_then_else->then_atom_seen)
500 die(_("format: %%(if) atom used without a %%(then) atom"));
502 if (if_then_else->else_atom_seen) {
504 * There is an %(else) atom: we need to drop one state from the
505 * stack, either the %(else) branch if the condition is satisfied, or
506 * the %(then) branch if it isn't.
508 if (if_then_else->condition_satisfied) {
509 strbuf_reset(&cur->output);
510 pop_stack_element(&cur);
511 } else {
512 strbuf_swap(&cur->output, &prev->output);
513 strbuf_reset(&cur->output);
514 pop_stack_element(&cur);
516 } else if (!if_then_else->condition_satisfied) {
518 * No %(else) atom: just drop the %(then) branch if the
519 * condition is not satisfied.
521 strbuf_reset(&cur->output);
524 *stack = cur;
525 free(if_then_else);
528 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
530 struct ref_formatting_stack *new;
531 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
533 if_then_else->str = atomv->atom->u.if_then_else.str;
534 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
536 push_stack_element(&state->stack);
537 new = state->stack;
538 new->at_end = if_then_else_handler;
539 new->at_end_data = if_then_else;
542 static int is_empty(const char *s)
544 while (*s != '\0') {
545 if (!isspace(*s))
546 return 0;
547 s++;
549 return 1;
552 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
554 struct ref_formatting_stack *cur = state->stack;
555 struct if_then_else *if_then_else = NULL;
557 if (cur->at_end == if_then_else_handler)
558 if_then_else = (struct if_then_else *)cur->at_end_data;
559 if (!if_then_else)
560 die(_("format: %%(then) atom used without an %%(if) atom"));
561 if (if_then_else->then_atom_seen)
562 die(_("format: %%(then) atom used more than once"));
563 if (if_then_else->else_atom_seen)
564 die(_("format: %%(then) atom used after %%(else)"));
565 if_then_else->then_atom_seen = 1;
567 * If the 'equals' or 'notequals' attribute is used then
568 * perform the required comparison. If not, only non-empty
569 * strings satisfy the 'if' condition.
571 if (if_then_else->cmp_status == COMPARE_EQUAL) {
572 if (!strcmp(if_then_else->str, cur->output.buf))
573 if_then_else->condition_satisfied = 1;
574 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
575 if (strcmp(if_then_else->str, cur->output.buf))
576 if_then_else->condition_satisfied = 1;
577 } else if (cur->output.len && !is_empty(cur->output.buf))
578 if_then_else->condition_satisfied = 1;
579 strbuf_reset(&cur->output);
582 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
584 struct ref_formatting_stack *prev = state->stack;
585 struct if_then_else *if_then_else = NULL;
587 if (prev->at_end == if_then_else_handler)
588 if_then_else = (struct if_then_else *)prev->at_end_data;
589 if (!if_then_else)
590 die(_("format: %%(else) atom used without an %%(if) atom"));
591 if (!if_then_else->then_atom_seen)
592 die(_("format: %%(else) atom used without a %%(then) atom"));
593 if (if_then_else->else_atom_seen)
594 die(_("format: %%(else) atom used more than once"));
595 if_then_else->else_atom_seen = 1;
596 push_stack_element(&state->stack);
597 state->stack->at_end_data = prev->at_end_data;
598 state->stack->at_end = prev->at_end;
601 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
603 struct ref_formatting_stack *current = state->stack;
604 struct strbuf s = STRBUF_INIT;
606 if (!current->at_end)
607 die(_("format: %%(end) atom used without corresponding atom"));
608 current->at_end(&state->stack);
610 /* Stack may have been popped within at_end(), hence reset the current pointer */
611 current = state->stack;
614 * Perform quote formatting when the stack element is that of
615 * a supporting atom. If nested then perform quote formatting
616 * only on the topmost supporting atom.
618 if (!current->prev->prev) {
619 quote_formatting(&s, current->output.buf, state->quote_style);
620 strbuf_swap(&current->output, &s);
622 strbuf_release(&s);
623 pop_stack_element(&state->stack);
627 * In a format string, find the next occurrence of %(atom).
629 static const char *find_next(const char *cp)
631 while (*cp) {
632 if (*cp == '%') {
634 * %( is the start of an atom;
635 * %% is a quoted per-cent.
637 if (cp[1] == '(')
638 return cp;
639 else if (cp[1] == '%')
640 cp++; /* skip over two % */
641 /* otherwise this is a singleton, literal % */
643 cp++;
645 return NULL;
649 * Make sure the format string is well formed, and parse out
650 * the used atoms.
652 int verify_ref_format(const char *format)
654 const char *cp, *sp;
656 need_color_reset_at_eol = 0;
657 for (cp = format; *cp && (sp = find_next(cp)); ) {
658 const char *color, *ep = strchr(sp, ')');
659 int at;
661 if (!ep)
662 return error(_("malformed format string %s"), sp);
663 /* sp points at "%(" and ep points at the closing ")" */
664 at = parse_ref_filter_atom(sp + 2, ep);
665 cp = ep + 1;
667 if (skip_prefix(used_atom[at].name, "color:", &color))
668 need_color_reset_at_eol = !!strcmp(color, "reset");
670 return 0;
674 * Given an object name, read the object data and size, and return a
675 * "struct object". If the object data we are returning is also borrowed
676 * by the "struct object" representation, set *eaten as well---it is a
677 * signal from parse_object_buffer to us not to free the buffer.
679 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
681 enum object_type type;
682 void *buf = read_sha1_file(sha1, &type, sz);
684 if (buf)
685 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
686 else
687 *obj = NULL;
688 return buf;
691 static int grab_objectname(const char *name, const unsigned char *sha1,
692 struct atom_value *v, struct used_atom *atom)
694 if (starts_with(name, "objectname")) {
695 if (atom->u.objectname.option == O_SHORT) {
696 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
697 return 1;
698 } else if (atom->u.objectname.option == O_FULL) {
699 v->s = xstrdup(sha1_to_hex(sha1));
700 return 1;
701 } else if (atom->u.objectname.option == O_LENGTH) {
702 v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
703 return 1;
704 } else
705 die("BUG: unknown %%(objectname) option");
707 return 0;
710 /* See grab_values */
711 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
713 int i;
715 for (i = 0; i < used_atom_cnt; i++) {
716 const char *name = used_atom[i].name;
717 struct atom_value *v = &val[i];
718 if (!!deref != (*name == '*'))
719 continue;
720 if (deref)
721 name++;
722 if (!strcmp(name, "objecttype"))
723 v->s = typename(obj->type);
724 else if (!strcmp(name, "objectsize")) {
725 v->ul = sz;
726 v->s = xstrfmt("%lu", sz);
728 else if (deref)
729 grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
733 /* See grab_values */
734 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
736 int i;
737 struct tag *tag = (struct tag *) obj;
739 for (i = 0; i < used_atom_cnt; i++) {
740 const char *name = used_atom[i].name;
741 struct atom_value *v = &val[i];
742 if (!!deref != (*name == '*'))
743 continue;
744 if (deref)
745 name++;
746 if (!strcmp(name, "tag"))
747 v->s = tag->tag;
748 else if (!strcmp(name, "type") && tag->tagged)
749 v->s = typename(tag->tagged->type);
750 else if (!strcmp(name, "object") && tag->tagged)
751 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
755 /* See grab_values */
756 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
758 int i;
759 struct commit *commit = (struct commit *) obj;
761 for (i = 0; i < used_atom_cnt; i++) {
762 const char *name = used_atom[i].name;
763 struct atom_value *v = &val[i];
764 if (!!deref != (*name == '*'))
765 continue;
766 if (deref)
767 name++;
768 if (!strcmp(name, "tree")) {
769 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
771 else if (!strcmp(name, "numparent")) {
772 v->ul = commit_list_count(commit->parents);
773 v->s = xstrfmt("%lu", v->ul);
775 else if (!strcmp(name, "parent")) {
776 struct commit_list *parents;
777 struct strbuf s = STRBUF_INIT;
778 for (parents = commit->parents; parents; parents = parents->next) {
779 struct commit *parent = parents->item;
780 if (parents != commit->parents)
781 strbuf_addch(&s, ' ');
782 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
784 v->s = strbuf_detach(&s, NULL);
789 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
791 const char *eol;
792 while (*buf) {
793 if (!strncmp(buf, who, wholen) &&
794 buf[wholen] == ' ')
795 return buf + wholen + 1;
796 eol = strchr(buf, '\n');
797 if (!eol)
798 return "";
799 eol++;
800 if (*eol == '\n')
801 return ""; /* end of header */
802 buf = eol;
804 return "";
807 static const char *copy_line(const char *buf)
809 const char *eol = strchrnul(buf, '\n');
810 return xmemdupz(buf, eol - buf);
813 static const char *copy_name(const char *buf)
815 const char *cp;
816 for (cp = buf; *cp && *cp != '\n'; cp++) {
817 if (!strncmp(cp, " <", 2))
818 return xmemdupz(buf, cp - buf);
820 return "";
823 static const char *copy_email(const char *buf)
825 const char *email = strchr(buf, '<');
826 const char *eoemail;
827 if (!email)
828 return "";
829 eoemail = strchr(email, '>');
830 if (!eoemail)
831 return "";
832 return xmemdupz(email, eoemail + 1 - email);
835 static char *copy_subject(const char *buf, unsigned long len)
837 char *r = xmemdupz(buf, len);
838 int i;
840 for (i = 0; i < len; i++)
841 if (r[i] == '\n')
842 r[i] = ' ';
844 return r;
847 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
849 const char *eoemail = strstr(buf, "> ");
850 char *zone;
851 unsigned long timestamp;
852 long tz;
853 struct date_mode date_mode = { DATE_NORMAL };
854 const char *formatp;
857 * We got here because atomname ends in "date" or "date<something>";
858 * it's not possible that <something> is not ":<format>" because
859 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
860 * ":" means no format is specified, and use the default.
862 formatp = strchr(atomname, ':');
863 if (formatp != NULL) {
864 formatp++;
865 parse_date_format(formatp, &date_mode);
868 if (!eoemail)
869 goto bad;
870 timestamp = strtoul(eoemail + 2, &zone, 10);
871 if (timestamp == ULONG_MAX)
872 goto bad;
873 tz = strtol(zone, NULL, 10);
874 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
875 goto bad;
876 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
877 v->ul = timestamp;
878 return;
879 bad:
880 v->s = "";
881 v->ul = 0;
884 /* See grab_values */
885 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
887 int i;
888 int wholen = strlen(who);
889 const char *wholine = NULL;
891 for (i = 0; i < used_atom_cnt; i++) {
892 const char *name = used_atom[i].name;
893 struct atom_value *v = &val[i];
894 if (!!deref != (*name == '*'))
895 continue;
896 if (deref)
897 name++;
898 if (strncmp(who, name, wholen))
899 continue;
900 if (name[wholen] != 0 &&
901 strcmp(name + wholen, "name") &&
902 strcmp(name + wholen, "email") &&
903 !starts_with(name + wholen, "date"))
904 continue;
905 if (!wholine)
906 wholine = find_wholine(who, wholen, buf, sz);
907 if (!wholine)
908 return; /* no point looking for it */
909 if (name[wholen] == 0)
910 v->s = copy_line(wholine);
911 else if (!strcmp(name + wholen, "name"))
912 v->s = copy_name(wholine);
913 else if (!strcmp(name + wholen, "email"))
914 v->s = copy_email(wholine);
915 else if (starts_with(name + wholen, "date"))
916 grab_date(wholine, v, name);
920 * For a tag or a commit object, if "creator" or "creatordate" is
921 * requested, do something special.
923 if (strcmp(who, "tagger") && strcmp(who, "committer"))
924 return; /* "author" for commit object is not wanted */
925 if (!wholine)
926 wholine = find_wholine(who, wholen, buf, sz);
927 if (!wholine)
928 return;
929 for (i = 0; i < used_atom_cnt; i++) {
930 const char *name = used_atom[i].name;
931 struct atom_value *v = &val[i];
932 if (!!deref != (*name == '*'))
933 continue;
934 if (deref)
935 name++;
937 if (starts_with(name, "creatordate"))
938 grab_date(wholine, v, name);
939 else if (!strcmp(name, "creator"))
940 v->s = copy_line(wholine);
944 static void find_subpos(const char *buf, unsigned long sz,
945 const char **sub, unsigned long *sublen,
946 const char **body, unsigned long *bodylen,
947 unsigned long *nonsiglen,
948 const char **sig, unsigned long *siglen)
950 const char *eol;
951 /* skip past header until we hit empty line */
952 while (*buf && *buf != '\n') {
953 eol = strchrnul(buf, '\n');
954 if (*eol)
955 eol++;
956 buf = eol;
958 /* skip any empty lines */
959 while (*buf == '\n')
960 buf++;
962 /* parse signature first; we might not even have a subject line */
963 *sig = buf + parse_signature(buf, strlen(buf));
964 *siglen = strlen(*sig);
966 /* subject is first non-empty line */
967 *sub = buf;
968 /* subject goes to first empty line */
969 while (buf < *sig && *buf && *buf != '\n') {
970 eol = strchrnul(buf, '\n');
971 if (*eol)
972 eol++;
973 buf = eol;
975 *sublen = buf - *sub;
976 /* drop trailing newline, if present */
977 if (*sublen && (*sub)[*sublen - 1] == '\n')
978 *sublen -= 1;
980 /* skip any empty lines */
981 while (*buf == '\n')
982 buf++;
983 *body = buf;
984 *bodylen = strlen(buf);
985 *nonsiglen = *sig - buf;
989 * If 'lines' is greater than 0, append that many lines from the given
990 * 'buf' of length 'size' to the given strbuf.
992 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
994 int i;
995 const char *sp, *eol;
996 size_t len;
998 sp = buf;
1000 for (i = 0; i < lines && sp < buf + size; i++) {
1001 if (i)
1002 strbuf_addstr(out, "\n ");
1003 eol = memchr(sp, '\n', size - (sp - buf));
1004 len = eol ? eol - sp : size - (sp - buf);
1005 strbuf_add(out, sp, len);
1006 if (!eol)
1007 break;
1008 sp = eol + 1;
1012 /* See grab_values */
1013 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1015 int i;
1016 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1017 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1019 for (i = 0; i < used_atom_cnt; i++) {
1020 struct used_atom *atom = &used_atom[i];
1021 const char *name = atom->name;
1022 struct atom_value *v = &val[i];
1023 if (!!deref != (*name == '*'))
1024 continue;
1025 if (deref)
1026 name++;
1027 if (strcmp(name, "subject") &&
1028 strcmp(name, "body") &&
1029 strcmp(name, "trailers") &&
1030 !starts_with(name, "contents"))
1031 continue;
1032 if (!subpos)
1033 find_subpos(buf, sz,
1034 &subpos, &sublen,
1035 &bodypos, &bodylen, &nonsiglen,
1036 &sigpos, &siglen);
1038 if (atom->u.contents.option == C_SUB)
1039 v->s = copy_subject(subpos, sublen);
1040 else if (atom->u.contents.option == C_BODY_DEP)
1041 v->s = xmemdupz(bodypos, bodylen);
1042 else if (atom->u.contents.option == C_BODY)
1043 v->s = xmemdupz(bodypos, nonsiglen);
1044 else if (atom->u.contents.option == C_SIG)
1045 v->s = xmemdupz(sigpos, siglen);
1046 else if (atom->u.contents.option == C_LINES) {
1047 struct strbuf s = STRBUF_INIT;
1048 const char *contents_end = bodylen + bodypos - siglen;
1050 /* Size is the length of the message after removing the signature */
1051 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1052 v->s = strbuf_detach(&s, NULL);
1053 } else if (atom->u.contents.option == C_TRAILERS) {
1054 struct trailer_info info;
1056 /* Search for trailer info */
1057 trailer_info_get(&info, subpos);
1058 v->s = xmemdupz(info.trailer_start,
1059 info.trailer_end - info.trailer_start);
1060 trailer_info_release(&info);
1061 } else if (atom->u.contents.option == C_BARE)
1062 v->s = xstrdup(subpos);
1067 * We want to have empty print-string for field requests
1068 * that do not apply (e.g. "authordate" for a tag object)
1070 static void fill_missing_values(struct atom_value *val)
1072 int i;
1073 for (i = 0; i < used_atom_cnt; i++) {
1074 struct atom_value *v = &val[i];
1075 if (v->s == NULL)
1076 v->s = "";
1081 * val is a list of atom_value to hold returned values. Extract
1082 * the values for atoms in used_atom array out of (obj, buf, sz).
1083 * when deref is false, (obj, buf, sz) is the object that is
1084 * pointed at by the ref itself; otherwise it is the object the
1085 * ref (which is a tag) refers to.
1087 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1089 grab_common_values(val, deref, obj, buf, sz);
1090 switch (obj->type) {
1091 case OBJ_TAG:
1092 grab_tag_values(val, deref, obj, buf, sz);
1093 grab_sub_body_contents(val, deref, obj, buf, sz);
1094 grab_person("tagger", val, deref, obj, buf, sz);
1095 break;
1096 case OBJ_COMMIT:
1097 grab_commit_values(val, deref, obj, buf, sz);
1098 grab_sub_body_contents(val, deref, obj, buf, sz);
1099 grab_person("author", val, deref, obj, buf, sz);
1100 grab_person("committer", val, deref, obj, buf, sz);
1101 break;
1102 case OBJ_TREE:
1103 /* grab_tree_values(val, deref, obj, buf, sz); */
1104 break;
1105 case OBJ_BLOB:
1106 /* grab_blob_values(val, deref, obj, buf, sz); */
1107 break;
1108 default:
1109 die("Eh? Object of type %d?", obj->type);
1113 static inline char *copy_advance(char *dst, const char *src)
1115 while (*src)
1116 *dst++ = *src++;
1117 return dst;
1120 static const char *lstrip_ref_components(const char *refname, int len)
1122 long remaining = len;
1123 const char *start = refname;
1125 if (len < 0) {
1126 int i;
1127 const char *p = refname;
1129 /* Find total no of '/' separated path-components */
1130 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1133 * The number of components we need to strip is now
1134 * the total minus the components to be left (Plus one
1135 * because we count the number of '/', but the number
1136 * of components is one more than the no of '/').
1138 remaining = i + len + 1;
1141 while (remaining > 0) {
1142 switch (*start++) {
1143 case '\0':
1144 return "";
1145 case '/':
1146 remaining--;
1147 break;
1151 return start;
1154 static const char *rstrip_ref_components(const char *refname, int len)
1156 long remaining = len;
1157 char *start = xstrdup(refname);
1159 if (len < 0) {
1160 int i;
1161 const char *p = refname;
1163 /* Find total no of '/' separated path-components */
1164 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1167 * The number of components we need to strip is now
1168 * the total minus the components to be left (Plus one
1169 * because we count the number of '/', but the number
1170 * of components is one more than the no of '/').
1172 remaining = i + len + 1;
1175 while (remaining-- > 0) {
1176 char *p = strrchr(start, '/');
1177 if (p == NULL)
1178 return "";
1179 else
1180 p[0] = '\0';
1182 return start;
1185 static const char *show_ref(struct refname_atom *atom, const char *refname)
1187 if (atom->option == R_SHORT)
1188 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1189 else if (atom->option == R_LSTRIP)
1190 return lstrip_ref_components(refname, atom->lstrip);
1191 else if (atom->option == R_RSTRIP)
1192 return rstrip_ref_components(refname, atom->rstrip);
1193 else
1194 return refname;
1197 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1198 struct branch *branch, const char **s)
1200 int num_ours, num_theirs;
1201 if (atom->u.remote_ref.option == RR_REF)
1202 *s = show_ref(&atom->u.remote_ref.refname, refname);
1203 else if (atom->u.remote_ref.option == RR_TRACK) {
1204 if (stat_tracking_info(branch, &num_ours,
1205 &num_theirs, NULL)) {
1206 *s = xstrdup(msgs.gone);
1207 } else if (!num_ours && !num_theirs)
1208 *s = "";
1209 else if (!num_ours)
1210 *s = xstrfmt(msgs.behind, num_theirs);
1211 else if (!num_theirs)
1212 *s = xstrfmt(msgs.ahead, num_ours);
1213 else
1214 *s = xstrfmt(msgs.ahead_behind,
1215 num_ours, num_theirs);
1216 if (!atom->u.remote_ref.nobracket && *s[0]) {
1217 const char *to_free = *s;
1218 *s = xstrfmt("[%s]", *s);
1219 free((void *)to_free);
1221 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1222 if (stat_tracking_info(branch, &num_ours,
1223 &num_theirs, NULL))
1224 return;
1226 if (!num_ours && !num_theirs)
1227 *s = "=";
1228 else if (!num_ours)
1229 *s = "<";
1230 else if (!num_theirs)
1231 *s = ">";
1232 else
1233 *s = "<>";
1234 } else
1235 die("BUG: unhandled RR_* enum");
1238 char *get_head_description(void)
1240 struct strbuf desc = STRBUF_INIT;
1241 struct wt_status_state state;
1242 memset(&state, 0, sizeof(state));
1243 wt_status_get_state(&state, 1);
1244 if (state.rebase_in_progress ||
1245 state.rebase_interactive_in_progress)
1246 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1247 state.branch);
1248 else if (state.bisect_in_progress)
1249 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1250 state.branch);
1251 else if (state.detached_from) {
1252 if (state.detached_at)
1253 /* TRANSLATORS: make sure this matches
1254 "HEAD detached at " in wt-status.c */
1255 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1256 state.detached_from);
1257 else
1258 /* TRANSLATORS: make sure this matches
1259 "HEAD detached from " in wt-status.c */
1260 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1261 state.detached_from);
1263 else
1264 strbuf_addstr(&desc, _("(no branch)"));
1265 free(state.branch);
1266 free(state.onto);
1267 free(state.detached_from);
1268 return strbuf_detach(&desc, NULL);
1271 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1273 if (!ref->symref)
1274 return "";
1275 else
1276 return show_ref(&atom->u.refname, ref->symref);
1279 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1281 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1282 return get_head_description();
1283 return show_ref(&atom->u.refname, ref->refname);
1287 * Parse the object referred by ref, and grab needed value.
1289 static void populate_value(struct ref_array_item *ref)
1291 void *buf;
1292 struct object *obj;
1293 int eaten, i;
1294 unsigned long size;
1295 const unsigned char *tagged;
1297 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1299 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1300 unsigned char unused1[20];
1301 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1302 unused1, NULL);
1303 if (!ref->symref)
1304 ref->symref = "";
1307 /* Fill in specials first */
1308 for (i = 0; i < used_atom_cnt; i++) {
1309 struct used_atom *atom = &used_atom[i];
1310 const char *name = used_atom[i].name;
1311 struct atom_value *v = &ref->value[i];
1312 int deref = 0;
1313 const char *refname;
1314 struct branch *branch = NULL;
1316 v->handler = append_atom;
1317 v->atom = atom;
1319 if (*name == '*') {
1320 deref = 1;
1321 name++;
1324 if (starts_with(name, "refname"))
1325 refname = get_refname(atom, ref);
1326 else if (starts_with(name, "symref"))
1327 refname = get_symref(atom, ref);
1328 else if (starts_with(name, "upstream")) {
1329 const char *branch_name;
1330 /* only local branches may have an upstream */
1331 if (!skip_prefix(ref->refname, "refs/heads/",
1332 &branch_name))
1333 continue;
1334 branch = branch_get(branch_name);
1336 refname = branch_get_upstream(branch, NULL);
1337 if (refname)
1338 fill_remote_ref_details(atom, refname, branch, &v->s);
1339 continue;
1340 } else if (starts_with(name, "push")) {
1341 const char *branch_name;
1342 if (!skip_prefix(ref->refname, "refs/heads/",
1343 &branch_name))
1344 continue;
1345 branch = branch_get(branch_name);
1347 refname = branch_get_push(branch, NULL);
1348 if (!refname)
1349 continue;
1350 fill_remote_ref_details(atom, refname, branch, &v->s);
1351 continue;
1352 } else if (starts_with(name, "color:")) {
1353 v->s = atom->u.color;
1354 continue;
1355 } else if (!strcmp(name, "flag")) {
1356 char buf[256], *cp = buf;
1357 if (ref->flag & REF_ISSYMREF)
1358 cp = copy_advance(cp, ",symref");
1359 if (ref->flag & REF_ISPACKED)
1360 cp = copy_advance(cp, ",packed");
1361 if (cp == buf)
1362 v->s = "";
1363 else {
1364 *cp = '\0';
1365 v->s = xstrdup(buf + 1);
1367 continue;
1368 } else if (!deref && grab_objectname(name, ref->objectname, v, atom)) {
1369 continue;
1370 } else if (!strcmp(name, "HEAD")) {
1371 const char *head;
1372 unsigned char sha1[20];
1374 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1375 sha1, NULL);
1376 if (head && !strcmp(ref->refname, head))
1377 v->s = "*";
1378 else
1379 v->s = " ";
1380 continue;
1381 } else if (starts_with(name, "align")) {
1382 v->handler = align_atom_handler;
1383 continue;
1384 } else if (!strcmp(name, "end")) {
1385 v->handler = end_atom_handler;
1386 continue;
1387 } else if (starts_with(name, "if")) {
1388 const char *s;
1390 if (skip_prefix(name, "if:", &s))
1391 v->s = xstrdup(s);
1392 v->handler = if_atom_handler;
1393 continue;
1394 } else if (!strcmp(name, "then")) {
1395 v->handler = then_atom_handler;
1396 continue;
1397 } else if (!strcmp(name, "else")) {
1398 v->handler = else_atom_handler;
1399 continue;
1400 } else
1401 continue;
1403 if (!deref)
1404 v->s = refname;
1405 else
1406 v->s = xstrfmt("%s^{}", refname);
1409 for (i = 0; i < used_atom_cnt; i++) {
1410 struct atom_value *v = &ref->value[i];
1411 if (v->s == NULL)
1412 goto need_obj;
1414 return;
1416 need_obj:
1417 buf = get_obj(ref->objectname, &obj, &size, &eaten);
1418 if (!buf)
1419 die(_("missing object %s for %s"),
1420 sha1_to_hex(ref->objectname), ref->refname);
1421 if (!obj)
1422 die(_("parse_object_buffer failed on %s for %s"),
1423 sha1_to_hex(ref->objectname), ref->refname);
1425 grab_values(ref->value, 0, obj, buf, size);
1426 if (!eaten)
1427 free(buf);
1430 * If there is no atom that wants to know about tagged
1431 * object, we are done.
1433 if (!need_tagged || (obj->type != OBJ_TAG))
1434 return;
1437 * If it is a tag object, see if we use a value that derefs
1438 * the object, and if we do grab the object it refers to.
1440 tagged = ((struct tag *)obj)->tagged->oid.hash;
1443 * NEEDSWORK: This derefs tag only once, which
1444 * is good to deal with chains of trust, but
1445 * is not consistent with what deref_tag() does
1446 * which peels the onion to the core.
1448 buf = get_obj(tagged, &obj, &size, &eaten);
1449 if (!buf)
1450 die(_("missing object %s for %s"),
1451 sha1_to_hex(tagged), ref->refname);
1452 if (!obj)
1453 die(_("parse_object_buffer failed on %s for %s"),
1454 sha1_to_hex(tagged), ref->refname);
1455 grab_values(ref->value, 1, obj, buf, size);
1456 if (!eaten)
1457 free(buf);
1461 * Given a ref, return the value for the atom. This lazily gets value
1462 * out of the object by calling populate value.
1464 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1466 if (!ref->value) {
1467 populate_value(ref);
1468 fill_missing_values(ref->value);
1470 *v = &ref->value[atom];
1473 enum contains_result {
1474 CONTAINS_UNKNOWN = -1,
1475 CONTAINS_NO = 0,
1476 CONTAINS_YES = 1
1480 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1481 * overflows.
1483 * At each recursion step, the stack items points to the commits whose
1484 * ancestors are to be inspected.
1486 struct contains_stack {
1487 int nr, alloc;
1488 struct contains_stack_entry {
1489 struct commit *commit;
1490 struct commit_list *parents;
1491 } *contains_stack;
1494 static int in_commit_list(const struct commit_list *want, struct commit *c)
1496 for (; want; want = want->next)
1497 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1498 return 1;
1499 return 0;
1503 * Test whether the candidate or one of its parents is contained in the list.
1504 * Do not recurse to find out, though, but return -1 if inconclusive.
1506 static enum contains_result contains_test(struct commit *candidate,
1507 const struct commit_list *want)
1509 /* was it previously marked as containing a want commit? */
1510 if (candidate->object.flags & TMP_MARK)
1511 return 1;
1512 /* or marked as not possibly containing a want commit? */
1513 if (candidate->object.flags & UNINTERESTING)
1514 return 0;
1515 /* or are we it? */
1516 if (in_commit_list(want, candidate)) {
1517 candidate->object.flags |= TMP_MARK;
1518 return 1;
1521 if (parse_commit(candidate) < 0)
1522 return 0;
1524 return -1;
1527 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1529 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1530 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1531 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1534 static enum contains_result contains_tag_algo(struct commit *candidate,
1535 const struct commit_list *want)
1537 struct contains_stack contains_stack = { 0, 0, NULL };
1538 int result = contains_test(candidate, want);
1540 if (result != CONTAINS_UNKNOWN)
1541 return result;
1543 push_to_contains_stack(candidate, &contains_stack);
1544 while (contains_stack.nr) {
1545 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1546 struct commit *commit = entry->commit;
1547 struct commit_list *parents = entry->parents;
1549 if (!parents) {
1550 commit->object.flags |= UNINTERESTING;
1551 contains_stack.nr--;
1554 * If we just popped the stack, parents->item has been marked,
1555 * therefore contains_test will return a meaningful 0 or 1.
1557 else switch (contains_test(parents->item, want)) {
1558 case CONTAINS_YES:
1559 commit->object.flags |= TMP_MARK;
1560 contains_stack.nr--;
1561 break;
1562 case CONTAINS_NO:
1563 entry->parents = parents->next;
1564 break;
1565 case CONTAINS_UNKNOWN:
1566 push_to_contains_stack(parents->item, &contains_stack);
1567 break;
1570 free(contains_stack.contains_stack);
1571 return contains_test(candidate, want);
1574 static int commit_contains(struct ref_filter *filter, struct commit *commit)
1576 if (filter->with_commit_tag_algo)
1577 return contains_tag_algo(commit, filter->with_commit);
1578 return is_descendant_of(commit, filter->with_commit);
1582 * Return 1 if the refname matches one of the patterns, otherwise 0.
1583 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1584 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1585 * matches "refs/heads/mas*", too).
1587 static int match_pattern(const struct ref_filter *filter, const char *refname)
1589 const char **patterns = filter->name_patterns;
1590 unsigned flags = 0;
1592 if (filter->ignore_case)
1593 flags |= WM_CASEFOLD;
1596 * When no '--format' option is given we need to skip the prefix
1597 * for matching refs of tags and branches.
1599 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1600 skip_prefix(refname, "refs/heads/", &refname) ||
1601 skip_prefix(refname, "refs/remotes/", &refname) ||
1602 skip_prefix(refname, "refs/", &refname));
1604 for (; *patterns; patterns++) {
1605 if (!wildmatch(*patterns, refname, flags, NULL))
1606 return 1;
1608 return 0;
1612 * Return 1 if the refname matches one of the patterns, otherwise 0.
1613 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1614 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1615 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1617 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1619 const char **pattern = filter->name_patterns;
1620 int namelen = strlen(refname);
1621 unsigned flags = WM_PATHNAME;
1623 if (filter->ignore_case)
1624 flags |= WM_CASEFOLD;
1626 for (; *pattern; pattern++) {
1627 const char *p = *pattern;
1628 int plen = strlen(p);
1630 if ((plen <= namelen) &&
1631 !strncmp(refname, p, plen) &&
1632 (refname[plen] == '\0' ||
1633 refname[plen] == '/' ||
1634 p[plen-1] == '/'))
1635 return 1;
1636 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1637 return 1;
1639 return 0;
1642 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1643 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1645 if (!*filter->name_patterns)
1646 return 1; /* No pattern always matches */
1647 if (filter->match_as_path)
1648 return match_name_as_path(filter, refname);
1649 return match_pattern(filter, refname);
1653 * Given a ref (sha1, refname), check if the ref belongs to the array
1654 * of sha1s. If the given ref is a tag, check if the given tag points
1655 * at one of the sha1s in the given sha1 array.
1656 * the given sha1_array.
1657 * NEEDSWORK:
1658 * 1. Only a single level of inderection is obtained, we might want to
1659 * change this to account for multiple levels (e.g. annotated tags
1660 * pointing to annotated tags pointing to a commit.)
1661 * 2. As the refs are cached we might know what refname peels to without
1662 * the need to parse the object via parse_object(). peel_ref() might be a
1663 * more efficient alternative to obtain the pointee.
1665 static const unsigned char *match_points_at(struct sha1_array *points_at,
1666 const unsigned char *sha1,
1667 const char *refname)
1669 const unsigned char *tagged_sha1 = NULL;
1670 struct object *obj;
1672 if (sha1_array_lookup(points_at, sha1) >= 0)
1673 return sha1;
1674 obj = parse_object(sha1);
1675 if (!obj)
1676 die(_("malformed object at '%s'"), refname);
1677 if (obj->type == OBJ_TAG)
1678 tagged_sha1 = ((struct tag *)obj)->tagged->oid.hash;
1679 if (tagged_sha1 && sha1_array_lookup(points_at, tagged_sha1) >= 0)
1680 return tagged_sha1;
1681 return NULL;
1684 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1685 static struct ref_array_item *new_ref_array_item(const char *refname,
1686 const unsigned char *objectname,
1687 int flag)
1689 struct ref_array_item *ref;
1690 FLEX_ALLOC_STR(ref, refname, refname);
1691 hashcpy(ref->objectname, objectname);
1692 ref->flag = flag;
1694 return ref;
1697 static int ref_kind_from_refname(const char *refname)
1699 unsigned int i;
1701 static struct {
1702 const char *prefix;
1703 unsigned int kind;
1704 } ref_kind[] = {
1705 { "refs/heads/" , FILTER_REFS_BRANCHES },
1706 { "refs/remotes/" , FILTER_REFS_REMOTES },
1707 { "refs/tags/", FILTER_REFS_TAGS}
1710 if (!strcmp(refname, "HEAD"))
1711 return FILTER_REFS_DETACHED_HEAD;
1713 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1714 if (starts_with(refname, ref_kind[i].prefix))
1715 return ref_kind[i].kind;
1718 return FILTER_REFS_OTHERS;
1721 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1723 if (filter->kind == FILTER_REFS_BRANCHES ||
1724 filter->kind == FILTER_REFS_REMOTES ||
1725 filter->kind == FILTER_REFS_TAGS)
1726 return filter->kind;
1727 return ref_kind_from_refname(refname);
1731 * A call-back given to for_each_ref(). Filter refs and keep them for
1732 * later object processing.
1734 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1736 struct ref_filter_cbdata *ref_cbdata = cb_data;
1737 struct ref_filter *filter = ref_cbdata->filter;
1738 struct ref_array_item *ref;
1739 struct commit *commit = NULL;
1740 unsigned int kind;
1742 if (flag & REF_BAD_NAME) {
1743 warning(_("ignoring ref with broken name %s"), refname);
1744 return 0;
1747 if (flag & REF_ISBROKEN) {
1748 warning(_("ignoring broken ref %s"), refname);
1749 return 0;
1752 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1753 kind = filter_ref_kind(filter, refname);
1754 if (!(kind & filter->kind))
1755 return 0;
1757 if (!filter_pattern_match(filter, refname))
1758 return 0;
1760 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1761 return 0;
1764 * A merge filter is applied on refs pointing to commits. Hence
1765 * obtain the commit using the 'oid' available and discard all
1766 * non-commits early. The actual filtering is done later.
1768 if (filter->merge_commit || filter->with_commit || filter->verbose) {
1769 commit = lookup_commit_reference_gently(oid->hash, 1);
1770 if (!commit)
1771 return 0;
1772 /* We perform the filtering for the '--contains' option */
1773 if (filter->with_commit &&
1774 !commit_contains(filter, commit))
1775 return 0;
1779 * We do not open the object yet; sort may only need refname
1780 * to do its job and the resulting list may yet to be pruned
1781 * by maxcount logic.
1783 ref = new_ref_array_item(refname, oid->hash, flag);
1784 ref->commit = commit;
1786 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1787 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1788 ref->kind = kind;
1789 return 0;
1792 /* Free memory allocated for a ref_array_item */
1793 static void free_array_item(struct ref_array_item *item)
1795 free((char *)item->symref);
1796 free(item);
1799 /* Free all memory allocated for ref_array */
1800 void ref_array_clear(struct ref_array *array)
1802 int i;
1804 for (i = 0; i < array->nr; i++)
1805 free_array_item(array->items[i]);
1806 free(array->items);
1807 array->items = NULL;
1808 array->nr = array->alloc = 0;
1811 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1813 struct rev_info revs;
1814 int i, old_nr;
1815 struct ref_filter *filter = ref_cbdata->filter;
1816 struct ref_array *array = ref_cbdata->array;
1817 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1819 init_revisions(&revs, NULL);
1821 for (i = 0; i < array->nr; i++) {
1822 struct ref_array_item *item = array->items[i];
1823 add_pending_object(&revs, &item->commit->object, item->refname);
1824 to_clear[i] = item->commit;
1827 filter->merge_commit->object.flags |= UNINTERESTING;
1828 add_pending_object(&revs, &filter->merge_commit->object, "");
1830 revs.limited = 1;
1831 if (prepare_revision_walk(&revs))
1832 die(_("revision walk setup failed"));
1834 old_nr = array->nr;
1835 array->nr = 0;
1837 for (i = 0; i < old_nr; i++) {
1838 struct ref_array_item *item = array->items[i];
1839 struct commit *commit = item->commit;
1841 int is_merged = !!(commit->object.flags & UNINTERESTING);
1843 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1844 array->items[array->nr++] = array->items[i];
1845 else
1846 free_array_item(item);
1849 for (i = 0; i < old_nr; i++)
1850 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1851 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1852 free(to_clear);
1856 * API for filtering a set of refs. Based on the type of refs the user
1857 * has requested, we iterate through those refs and apply filters
1858 * as per the given ref_filter structure and finally store the
1859 * filtered refs in the ref_array structure.
1861 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1863 struct ref_filter_cbdata ref_cbdata;
1864 int ret = 0;
1865 unsigned int broken = 0;
1867 ref_cbdata.array = array;
1868 ref_cbdata.filter = filter;
1870 if (type & FILTER_REFS_INCLUDE_BROKEN)
1871 broken = 1;
1872 filter->kind = type & FILTER_REFS_KIND_MASK;
1874 /* Simple per-ref filtering */
1875 if (!filter->kind)
1876 die("filter_refs: invalid type");
1877 else {
1879 * For common cases where we need only branches or remotes or tags,
1880 * we only iterate through those refs. If a mix of refs is needed,
1881 * we iterate over all refs and filter out required refs with the help
1882 * of filter_ref_kind().
1884 if (filter->kind == FILTER_REFS_BRANCHES)
1885 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1886 else if (filter->kind == FILTER_REFS_REMOTES)
1887 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1888 else if (filter->kind == FILTER_REFS_TAGS)
1889 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1890 else if (filter->kind & FILTER_REFS_ALL)
1891 ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1892 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1893 head_ref(ref_filter_handler, &ref_cbdata);
1897 /* Filters that need revision walking */
1898 if (filter->merge_commit)
1899 do_merge_filter(&ref_cbdata);
1901 return ret;
1904 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1906 struct atom_value *va, *vb;
1907 int cmp;
1908 cmp_type cmp_type = used_atom[s->atom].type;
1909 int (*cmp_fn)(const char *, const char *);
1911 get_ref_atom_value(a, s->atom, &va);
1912 get_ref_atom_value(b, s->atom, &vb);
1913 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
1914 if (s->version)
1915 cmp = versioncmp(va->s, vb->s);
1916 else if (cmp_type == FIELD_STR)
1917 cmp = cmp_fn(va->s, vb->s);
1918 else {
1919 if (va->ul < vb->ul)
1920 cmp = -1;
1921 else if (va->ul == vb->ul)
1922 cmp = cmp_fn(a->refname, b->refname);
1923 else
1924 cmp = 1;
1927 return (s->reverse) ? -cmp : cmp;
1930 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
1932 struct ref_array_item *a = *((struct ref_array_item **)a_);
1933 struct ref_array_item *b = *((struct ref_array_item **)b_);
1934 struct ref_sorting *s;
1936 for (s = ref_sorting; s; s = s->next) {
1937 int cmp = cmp_ref_sorting(s, a, b);
1938 if (cmp)
1939 return cmp;
1941 return 0;
1944 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1946 QSORT_S(array->items, array->nr, compare_refs, sorting);
1949 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1951 struct strbuf *s = &state->stack->output;
1953 while (*cp && (!ep || cp < ep)) {
1954 if (*cp == '%') {
1955 if (cp[1] == '%')
1956 cp++;
1957 else {
1958 int ch = hex2chr(cp + 1);
1959 if (0 <= ch) {
1960 strbuf_addch(s, ch);
1961 cp += 3;
1962 continue;
1966 strbuf_addch(s, *cp);
1967 cp++;
1971 void format_ref_array_item(struct ref_array_item *info, const char *format,
1972 int quote_style, struct strbuf *final_buf)
1974 const char *cp, *sp, *ep;
1975 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1977 state.quote_style = quote_style;
1978 push_stack_element(&state.stack);
1980 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1981 struct atom_value *atomv;
1983 ep = strchr(sp, ')');
1984 if (cp < sp)
1985 append_literal(cp, sp, &state);
1986 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1987 atomv->handler(atomv, &state);
1989 if (*cp) {
1990 sp = cp + strlen(cp);
1991 append_literal(cp, sp, &state);
1993 if (need_color_reset_at_eol) {
1994 struct atom_value resetv;
1995 char color[COLOR_MAXLEN] = "";
1997 if (color_parse("reset", color) < 0)
1998 die("BUG: couldn't parse 'reset' as a color");
1999 resetv.s = color;
2000 append_atom(&resetv, &state);
2002 if (state.stack->prev)
2003 die(_("format: %%(end) atom missing"));
2004 strbuf_addbuf(final_buf, &state.stack->output);
2005 pop_stack_element(&state.stack);
2008 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
2010 struct strbuf final_buf = STRBUF_INIT;
2012 format_ref_array_item(info, format, quote_style, &final_buf);
2013 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2014 strbuf_release(&final_buf);
2015 putchar('\n');
2018 void pretty_print_ref(const char *name, const unsigned char *sha1,
2019 const char *format)
2021 struct ref_array_item *ref_item;
2022 ref_item = new_ref_array_item(name, sha1, 0);
2023 ref_item->kind = ref_kind_from_refname(name);
2024 show_ref_array_item(ref_item, format, 0);
2025 free_array_item(ref_item);
2028 /* If no sorting option is given, use refname to sort as default */
2029 struct ref_sorting *ref_default_sorting(void)
2031 static const char cstr_name[] = "refname";
2033 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2035 sorting->next = NULL;
2036 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
2037 return sorting;
2040 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2042 struct ref_sorting **sorting_tail = opt->value;
2043 struct ref_sorting *s;
2044 int len;
2046 if (!arg) /* should --no-sort void the list ? */
2047 return -1;
2049 s = xcalloc(1, sizeof(*s));
2050 s->next = *sorting_tail;
2051 *sorting_tail = s;
2053 if (*arg == '-') {
2054 s->reverse = 1;
2055 arg++;
2057 if (skip_prefix(arg, "version:", &arg) ||
2058 skip_prefix(arg, "v:", &arg))
2059 s->version = 1;
2060 len = strlen(arg);
2061 s->atom = parse_ref_filter_atom(arg, arg+len);
2062 return 0;
2065 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2067 struct ref_filter *rf = opt->value;
2068 unsigned char sha1[20];
2070 rf->merge = starts_with(opt->long_name, "no")
2071 ? REF_FILTER_MERGED_OMIT
2072 : REF_FILTER_MERGED_INCLUDE;
2074 if (get_sha1(arg, sha1))
2075 die(_("malformed object name %s"), arg);
2077 rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
2078 if (!rf->merge_commit)
2079 return opterror(opt, "must point to a commit", 0);
2081 return 0;