branch: only perform HEAD check for local branches
[git.git] / ref-filter.c
blobf4c68237275d49af3f1665f40788bc8287e3f879
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 char *head;
96 } u;
97 } *used_atom;
98 static int used_atom_cnt, need_tagged, need_symref;
99 static int need_color_reset_at_eol;
101 static void color_atom_parser(struct used_atom *atom, const char *color_value)
103 if (!color_value)
104 die(_("expected format: %%(color:<color>)"));
105 if (color_parse(color_value, atom->u.color) < 0)
106 die(_("unrecognized color: %%(color:%s)"), color_value);
109 static void refname_atom_parser_internal(struct refname_atom *atom,
110 const char *arg, const char *name)
112 if (!arg)
113 atom->option = R_NORMAL;
114 else if (!strcmp(arg, "short"))
115 atom->option = R_SHORT;
116 else if (skip_prefix(arg, "lstrip=", &arg) ||
117 skip_prefix(arg, "strip=", &arg)) {
118 atom->option = R_LSTRIP;
119 if (strtol_i(arg, 10, &atom->lstrip))
120 die(_("Integer value expected refname:lstrip=%s"), arg);
121 } else if (skip_prefix(arg, "rstrip=", &arg)) {
122 atom->option = R_RSTRIP;
123 if (strtol_i(arg, 10, &atom->rstrip))
124 die(_("Integer value expected refname:rstrip=%s"), arg);
125 } else
126 die(_("unrecognized %%(%s) argument: %s"), name, arg);
129 static void remote_ref_atom_parser(struct used_atom *atom, const char *arg)
131 struct string_list params = STRING_LIST_INIT_DUP;
132 int i;
134 if (!arg) {
135 atom->u.remote_ref.option = RR_REF;
136 refname_atom_parser_internal(&atom->u.remote_ref.refname,
137 arg, atom->name);
138 return;
141 atom->u.remote_ref.nobracket = 0;
142 string_list_split(&params, arg, ',', -1);
144 for (i = 0; i < params.nr; i++) {
145 const char *s = params.items[i].string;
147 if (!strcmp(s, "track"))
148 atom->u.remote_ref.option = RR_TRACK;
149 else if (!strcmp(s, "trackshort"))
150 atom->u.remote_ref.option = RR_TRACKSHORT;
151 else if (!strcmp(s, "nobracket"))
152 atom->u.remote_ref.nobracket = 1;
153 else {
154 atom->u.remote_ref.option = RR_REF;
155 refname_atom_parser_internal(&atom->u.remote_ref.refname,
156 arg, atom->name);
160 string_list_clear(&params, 0);
163 static void body_atom_parser(struct used_atom *atom, const char *arg)
165 if (arg)
166 die(_("%%(body) does not take arguments"));
167 atom->u.contents.option = C_BODY_DEP;
170 static void subject_atom_parser(struct used_atom *atom, const char *arg)
172 if (arg)
173 die(_("%%(subject) does not take arguments"));
174 atom->u.contents.option = C_SUB;
177 static void trailers_atom_parser(struct used_atom *atom, const char *arg)
179 if (arg)
180 die(_("%%(trailers) does not take arguments"));
181 atom->u.contents.option = C_TRAILERS;
184 static void contents_atom_parser(struct used_atom *atom, const char *arg)
186 if (!arg)
187 atom->u.contents.option = C_BARE;
188 else if (!strcmp(arg, "body"))
189 atom->u.contents.option = C_BODY;
190 else if (!strcmp(arg, "signature"))
191 atom->u.contents.option = C_SIG;
192 else if (!strcmp(arg, "subject"))
193 atom->u.contents.option = C_SUB;
194 else if (!strcmp(arg, "trailers"))
195 atom->u.contents.option = C_TRAILERS;
196 else if (skip_prefix(arg, "lines=", &arg)) {
197 atom->u.contents.option = C_LINES;
198 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
199 die(_("positive value expected contents:lines=%s"), arg);
200 } else
201 die(_("unrecognized %%(contents) argument: %s"), arg);
204 static void objectname_atom_parser(struct used_atom *atom, const char *arg)
206 if (!arg)
207 atom->u.objectname.option = O_FULL;
208 else if (!strcmp(arg, "short"))
209 atom->u.objectname.option = O_SHORT;
210 else if (skip_prefix(arg, "short=", &arg)) {
211 atom->u.objectname.option = O_LENGTH;
212 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
213 atom->u.objectname.length == 0)
214 die(_("positive value expected objectname:short=%s"), arg);
215 if (atom->u.objectname.length < MINIMUM_ABBREV)
216 atom->u.objectname.length = MINIMUM_ABBREV;
217 } else
218 die(_("unrecognized %%(objectname) argument: %s"), arg);
221 static void refname_atom_parser(struct used_atom *atom, const char *arg)
223 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
226 static align_type parse_align_position(const char *s)
228 if (!strcmp(s, "right"))
229 return ALIGN_RIGHT;
230 else if (!strcmp(s, "middle"))
231 return ALIGN_MIDDLE;
232 else if (!strcmp(s, "left"))
233 return ALIGN_LEFT;
234 return -1;
237 static void align_atom_parser(struct used_atom *atom, const char *arg)
239 struct align *align = &atom->u.align;
240 struct string_list params = STRING_LIST_INIT_DUP;
241 int i;
242 unsigned int width = ~0U;
244 if (!arg)
245 die(_("expected format: %%(align:<width>,<position>)"));
247 align->position = ALIGN_LEFT;
249 string_list_split(&params, arg, ',', -1);
250 for (i = 0; i < params.nr; i++) {
251 const char *s = params.items[i].string;
252 int position;
254 if (skip_prefix(s, "position=", &s)) {
255 position = parse_align_position(s);
256 if (position < 0)
257 die(_("unrecognized position:%s"), s);
258 align->position = position;
259 } else if (skip_prefix(s, "width=", &s)) {
260 if (strtoul_ui(s, 10, &width))
261 die(_("unrecognized width:%s"), s);
262 } else if (!strtoul_ui(s, 10, &width))
264 else if ((position = parse_align_position(s)) >= 0)
265 align->position = position;
266 else
267 die(_("unrecognized %%(align) argument: %s"), s);
270 if (width == ~0U)
271 die(_("positive width expected with the %%(align) atom"));
272 align->width = width;
273 string_list_clear(&params, 0);
276 static void if_atom_parser(struct used_atom *atom, const char *arg)
278 if (!arg) {
279 atom->u.if_then_else.cmp_status = COMPARE_NONE;
280 return;
281 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
282 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
283 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
284 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
285 } else {
286 die(_("unrecognized %%(if) argument: %s"), arg);
290 static void head_atom_parser(struct used_atom *atom, const char *arg)
292 unsigned char unused[GIT_SHA1_RAWSZ];
294 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, unused, NULL);
297 static struct {
298 const char *name;
299 cmp_type cmp_type;
300 void (*parser)(struct used_atom *atom, const char *arg);
301 } valid_atom[] = {
302 { "refname" , FIELD_STR, refname_atom_parser },
303 { "objecttype" },
304 { "objectsize", FIELD_ULONG },
305 { "objectname", FIELD_STR, objectname_atom_parser },
306 { "tree" },
307 { "parent" },
308 { "numparent", FIELD_ULONG },
309 { "object" },
310 { "type" },
311 { "tag" },
312 { "author" },
313 { "authorname" },
314 { "authoremail" },
315 { "authordate", FIELD_TIME },
316 { "committer" },
317 { "committername" },
318 { "committeremail" },
319 { "committerdate", FIELD_TIME },
320 { "tagger" },
321 { "taggername" },
322 { "taggeremail" },
323 { "taggerdate", FIELD_TIME },
324 { "creator" },
325 { "creatordate", FIELD_TIME },
326 { "subject", FIELD_STR, subject_atom_parser },
327 { "body", FIELD_STR, body_atom_parser },
328 { "trailers", FIELD_STR, trailers_atom_parser },
329 { "contents", FIELD_STR, contents_atom_parser },
330 { "upstream", FIELD_STR, remote_ref_atom_parser },
331 { "push", FIELD_STR, remote_ref_atom_parser },
332 { "symref", FIELD_STR, refname_atom_parser },
333 { "flag" },
334 { "HEAD", FIELD_STR, head_atom_parser },
335 { "color", FIELD_STR, color_atom_parser },
336 { "align", FIELD_STR, align_atom_parser },
337 { "end" },
338 { "if", FIELD_STR, if_atom_parser },
339 { "then" },
340 { "else" },
343 #define REF_FORMATTING_STATE_INIT { 0, NULL }
345 struct ref_formatting_stack {
346 struct ref_formatting_stack *prev;
347 struct strbuf output;
348 void (*at_end)(struct ref_formatting_stack **stack);
349 void *at_end_data;
352 struct ref_formatting_state {
353 int quote_style;
354 struct ref_formatting_stack *stack;
357 struct atom_value {
358 const char *s;
359 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
360 unsigned long ul; /* used for sorting when not FIELD_STR */
361 struct used_atom *atom;
365 * Used to parse format string and sort specifiers
367 int parse_ref_filter_atom(const char *atom, const char *ep)
369 const char *sp;
370 const char *arg;
371 int i, at, atom_len;
373 sp = atom;
374 if (*sp == '*' && sp < ep)
375 sp++; /* deref */
376 if (ep <= sp)
377 die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
379 /* Do we have the atom already used elsewhere? */
380 for (i = 0; i < used_atom_cnt; i++) {
381 int len = strlen(used_atom[i].name);
382 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
383 return i;
387 * If the atom name has a colon, strip it and everything after
388 * it off - it specifies the format for this entry, and
389 * shouldn't be used for checking against the valid_atom
390 * table.
392 arg = memchr(sp, ':', ep - sp);
393 atom_len = (arg ? arg : ep) - sp;
395 /* Is the atom a valid one? */
396 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
397 int len = strlen(valid_atom[i].name);
398 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
399 break;
402 if (ARRAY_SIZE(valid_atom) <= i)
403 die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
405 /* Add it in, including the deref prefix */
406 at = used_atom_cnt;
407 used_atom_cnt++;
408 REALLOC_ARRAY(used_atom, used_atom_cnt);
409 used_atom[at].name = xmemdupz(atom, ep - atom);
410 used_atom[at].type = valid_atom[i].cmp_type;
411 if (arg)
412 arg = used_atom[at].name + (arg - atom) + 1;
413 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
414 if (valid_atom[i].parser)
415 valid_atom[i].parser(&used_atom[at], arg);
416 if (*atom == '*')
417 need_tagged = 1;
418 if (!strcmp(valid_atom[i].name, "symref"))
419 need_symref = 1;
420 return at;
423 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
425 switch (quote_style) {
426 case QUOTE_NONE:
427 strbuf_addstr(s, str);
428 break;
429 case QUOTE_SHELL:
430 sq_quote_buf(s, str);
431 break;
432 case QUOTE_PERL:
433 perl_quote_buf(s, str);
434 break;
435 case QUOTE_PYTHON:
436 python_quote_buf(s, str);
437 break;
438 case QUOTE_TCL:
439 tcl_quote_buf(s, str);
440 break;
444 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
447 * Quote formatting is only done when the stack has a single
448 * element. Otherwise quote formatting is done on the
449 * element's entire output strbuf when the %(end) atom is
450 * encountered.
452 if (!state->stack->prev)
453 quote_formatting(&state->stack->output, v->s, state->quote_style);
454 else
455 strbuf_addstr(&state->stack->output, v->s);
458 static void push_stack_element(struct ref_formatting_stack **stack)
460 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
462 strbuf_init(&s->output, 0);
463 s->prev = *stack;
464 *stack = s;
467 static void pop_stack_element(struct ref_formatting_stack **stack)
469 struct ref_formatting_stack *current = *stack;
470 struct ref_formatting_stack *prev = current->prev;
472 if (prev)
473 strbuf_addbuf(&prev->output, &current->output);
474 strbuf_release(&current->output);
475 free(current);
476 *stack = prev;
479 static void end_align_handler(struct ref_formatting_stack **stack)
481 struct ref_formatting_stack *cur = *stack;
482 struct align *align = (struct align *)cur->at_end_data;
483 struct strbuf s = STRBUF_INIT;
485 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
486 strbuf_swap(&cur->output, &s);
487 strbuf_release(&s);
490 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
492 struct ref_formatting_stack *new;
494 push_stack_element(&state->stack);
495 new = state->stack;
496 new->at_end = end_align_handler;
497 new->at_end_data = &atomv->atom->u.align;
500 static void if_then_else_handler(struct ref_formatting_stack **stack)
502 struct ref_formatting_stack *cur = *stack;
503 struct ref_formatting_stack *prev = cur->prev;
504 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
506 if (!if_then_else->then_atom_seen)
507 die(_("format: %%(if) atom used without a %%(then) atom"));
509 if (if_then_else->else_atom_seen) {
511 * There is an %(else) atom: we need to drop one state from the
512 * stack, either the %(else) branch if the condition is satisfied, or
513 * the %(then) branch if it isn't.
515 if (if_then_else->condition_satisfied) {
516 strbuf_reset(&cur->output);
517 pop_stack_element(&cur);
518 } else {
519 strbuf_swap(&cur->output, &prev->output);
520 strbuf_reset(&cur->output);
521 pop_stack_element(&cur);
523 } else if (!if_then_else->condition_satisfied) {
525 * No %(else) atom: just drop the %(then) branch if the
526 * condition is not satisfied.
528 strbuf_reset(&cur->output);
531 *stack = cur;
532 free(if_then_else);
535 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
537 struct ref_formatting_stack *new;
538 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
540 if_then_else->str = atomv->atom->u.if_then_else.str;
541 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
543 push_stack_element(&state->stack);
544 new = state->stack;
545 new->at_end = if_then_else_handler;
546 new->at_end_data = if_then_else;
549 static int is_empty(const char *s)
551 while (*s != '\0') {
552 if (!isspace(*s))
553 return 0;
554 s++;
556 return 1;
559 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
561 struct ref_formatting_stack *cur = state->stack;
562 struct if_then_else *if_then_else = NULL;
564 if (cur->at_end == if_then_else_handler)
565 if_then_else = (struct if_then_else *)cur->at_end_data;
566 if (!if_then_else)
567 die(_("format: %%(then) atom used without an %%(if) atom"));
568 if (if_then_else->then_atom_seen)
569 die(_("format: %%(then) atom used more than once"));
570 if (if_then_else->else_atom_seen)
571 die(_("format: %%(then) atom used after %%(else)"));
572 if_then_else->then_atom_seen = 1;
574 * If the 'equals' or 'notequals' attribute is used then
575 * perform the required comparison. If not, only non-empty
576 * strings satisfy the 'if' condition.
578 if (if_then_else->cmp_status == COMPARE_EQUAL) {
579 if (!strcmp(if_then_else->str, cur->output.buf))
580 if_then_else->condition_satisfied = 1;
581 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
582 if (strcmp(if_then_else->str, cur->output.buf))
583 if_then_else->condition_satisfied = 1;
584 } else if (cur->output.len && !is_empty(cur->output.buf))
585 if_then_else->condition_satisfied = 1;
586 strbuf_reset(&cur->output);
589 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
591 struct ref_formatting_stack *prev = state->stack;
592 struct if_then_else *if_then_else = NULL;
594 if (prev->at_end == if_then_else_handler)
595 if_then_else = (struct if_then_else *)prev->at_end_data;
596 if (!if_then_else)
597 die(_("format: %%(else) atom used without an %%(if) atom"));
598 if (!if_then_else->then_atom_seen)
599 die(_("format: %%(else) atom used without a %%(then) atom"));
600 if (if_then_else->else_atom_seen)
601 die(_("format: %%(else) atom used more than once"));
602 if_then_else->else_atom_seen = 1;
603 push_stack_element(&state->stack);
604 state->stack->at_end_data = prev->at_end_data;
605 state->stack->at_end = prev->at_end;
608 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
610 struct ref_formatting_stack *current = state->stack;
611 struct strbuf s = STRBUF_INIT;
613 if (!current->at_end)
614 die(_("format: %%(end) atom used without corresponding atom"));
615 current->at_end(&state->stack);
617 /* Stack may have been popped within at_end(), hence reset the current pointer */
618 current = state->stack;
621 * Perform quote formatting when the stack element is that of
622 * a supporting atom. If nested then perform quote formatting
623 * only on the topmost supporting atom.
625 if (!current->prev->prev) {
626 quote_formatting(&s, current->output.buf, state->quote_style);
627 strbuf_swap(&current->output, &s);
629 strbuf_release(&s);
630 pop_stack_element(&state->stack);
634 * In a format string, find the next occurrence of %(atom).
636 static const char *find_next(const char *cp)
638 while (*cp) {
639 if (*cp == '%') {
641 * %( is the start of an atom;
642 * %% is a quoted per-cent.
644 if (cp[1] == '(')
645 return cp;
646 else if (cp[1] == '%')
647 cp++; /* skip over two % */
648 /* otherwise this is a singleton, literal % */
650 cp++;
652 return NULL;
656 * Make sure the format string is well formed, and parse out
657 * the used atoms.
659 int verify_ref_format(const char *format)
661 const char *cp, *sp;
663 need_color_reset_at_eol = 0;
664 for (cp = format; *cp && (sp = find_next(cp)); ) {
665 const char *color, *ep = strchr(sp, ')');
666 int at;
668 if (!ep)
669 return error(_("malformed format string %s"), sp);
670 /* sp points at "%(" and ep points at the closing ")" */
671 at = parse_ref_filter_atom(sp + 2, ep);
672 cp = ep + 1;
674 if (skip_prefix(used_atom[at].name, "color:", &color))
675 need_color_reset_at_eol = !!strcmp(color, "reset");
677 return 0;
681 * Given an object name, read the object data and size, and return a
682 * "struct object". If the object data we are returning is also borrowed
683 * by the "struct object" representation, set *eaten as well---it is a
684 * signal from parse_object_buffer to us not to free the buffer.
686 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
688 enum object_type type;
689 void *buf = read_sha1_file(sha1, &type, sz);
691 if (buf)
692 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
693 else
694 *obj = NULL;
695 return buf;
698 static int grab_objectname(const char *name, const unsigned char *sha1,
699 struct atom_value *v, struct used_atom *atom)
701 if (starts_with(name, "objectname")) {
702 if (atom->u.objectname.option == O_SHORT) {
703 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
704 return 1;
705 } else if (atom->u.objectname.option == O_FULL) {
706 v->s = xstrdup(sha1_to_hex(sha1));
707 return 1;
708 } else if (atom->u.objectname.option == O_LENGTH) {
709 v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
710 return 1;
711 } else
712 die("BUG: unknown %%(objectname) option");
714 return 0;
717 /* See grab_values */
718 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
720 int i;
722 for (i = 0; i < used_atom_cnt; i++) {
723 const char *name = used_atom[i].name;
724 struct atom_value *v = &val[i];
725 if (!!deref != (*name == '*'))
726 continue;
727 if (deref)
728 name++;
729 if (!strcmp(name, "objecttype"))
730 v->s = typename(obj->type);
731 else if (!strcmp(name, "objectsize")) {
732 v->ul = sz;
733 v->s = xstrfmt("%lu", sz);
735 else if (deref)
736 grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
740 /* See grab_values */
741 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
743 int i;
744 struct tag *tag = (struct tag *) obj;
746 for (i = 0; i < used_atom_cnt; i++) {
747 const char *name = used_atom[i].name;
748 struct atom_value *v = &val[i];
749 if (!!deref != (*name == '*'))
750 continue;
751 if (deref)
752 name++;
753 if (!strcmp(name, "tag"))
754 v->s = tag->tag;
755 else if (!strcmp(name, "type") && tag->tagged)
756 v->s = typename(tag->tagged->type);
757 else if (!strcmp(name, "object") && tag->tagged)
758 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
762 /* See grab_values */
763 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
765 int i;
766 struct commit *commit = (struct commit *) obj;
768 for (i = 0; i < used_atom_cnt; i++) {
769 const char *name = used_atom[i].name;
770 struct atom_value *v = &val[i];
771 if (!!deref != (*name == '*'))
772 continue;
773 if (deref)
774 name++;
775 if (!strcmp(name, "tree")) {
776 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
778 else if (!strcmp(name, "numparent")) {
779 v->ul = commit_list_count(commit->parents);
780 v->s = xstrfmt("%lu", v->ul);
782 else if (!strcmp(name, "parent")) {
783 struct commit_list *parents;
784 struct strbuf s = STRBUF_INIT;
785 for (parents = commit->parents; parents; parents = parents->next) {
786 struct commit *parent = parents->item;
787 if (parents != commit->parents)
788 strbuf_addch(&s, ' ');
789 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
791 v->s = strbuf_detach(&s, NULL);
796 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
798 const char *eol;
799 while (*buf) {
800 if (!strncmp(buf, who, wholen) &&
801 buf[wholen] == ' ')
802 return buf + wholen + 1;
803 eol = strchr(buf, '\n');
804 if (!eol)
805 return "";
806 eol++;
807 if (*eol == '\n')
808 return ""; /* end of header */
809 buf = eol;
811 return "";
814 static const char *copy_line(const char *buf)
816 const char *eol = strchrnul(buf, '\n');
817 return xmemdupz(buf, eol - buf);
820 static const char *copy_name(const char *buf)
822 const char *cp;
823 for (cp = buf; *cp && *cp != '\n'; cp++) {
824 if (!strncmp(cp, " <", 2))
825 return xmemdupz(buf, cp - buf);
827 return "";
830 static const char *copy_email(const char *buf)
832 const char *email = strchr(buf, '<');
833 const char *eoemail;
834 if (!email)
835 return "";
836 eoemail = strchr(email, '>');
837 if (!eoemail)
838 return "";
839 return xmemdupz(email, eoemail + 1 - email);
842 static char *copy_subject(const char *buf, unsigned long len)
844 char *r = xmemdupz(buf, len);
845 int i;
847 for (i = 0; i < len; i++)
848 if (r[i] == '\n')
849 r[i] = ' ';
851 return r;
854 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
856 const char *eoemail = strstr(buf, "> ");
857 char *zone;
858 unsigned long timestamp;
859 long tz;
860 struct date_mode date_mode = { DATE_NORMAL };
861 const char *formatp;
864 * We got here because atomname ends in "date" or "date<something>";
865 * it's not possible that <something> is not ":<format>" because
866 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
867 * ":" means no format is specified, and use the default.
869 formatp = strchr(atomname, ':');
870 if (formatp != NULL) {
871 formatp++;
872 parse_date_format(formatp, &date_mode);
875 if (!eoemail)
876 goto bad;
877 timestamp = strtoul(eoemail + 2, &zone, 10);
878 if (timestamp == ULONG_MAX)
879 goto bad;
880 tz = strtol(zone, NULL, 10);
881 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
882 goto bad;
883 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
884 v->ul = timestamp;
885 return;
886 bad:
887 v->s = "";
888 v->ul = 0;
891 /* See grab_values */
892 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
894 int i;
895 int wholen = strlen(who);
896 const char *wholine = NULL;
898 for (i = 0; i < used_atom_cnt; i++) {
899 const char *name = used_atom[i].name;
900 struct atom_value *v = &val[i];
901 if (!!deref != (*name == '*'))
902 continue;
903 if (deref)
904 name++;
905 if (strncmp(who, name, wholen))
906 continue;
907 if (name[wholen] != 0 &&
908 strcmp(name + wholen, "name") &&
909 strcmp(name + wholen, "email") &&
910 !starts_with(name + wholen, "date"))
911 continue;
912 if (!wholine)
913 wholine = find_wholine(who, wholen, buf, sz);
914 if (!wholine)
915 return; /* no point looking for it */
916 if (name[wholen] == 0)
917 v->s = copy_line(wholine);
918 else if (!strcmp(name + wholen, "name"))
919 v->s = copy_name(wholine);
920 else if (!strcmp(name + wholen, "email"))
921 v->s = copy_email(wholine);
922 else if (starts_with(name + wholen, "date"))
923 grab_date(wholine, v, name);
927 * For a tag or a commit object, if "creator" or "creatordate" is
928 * requested, do something special.
930 if (strcmp(who, "tagger") && strcmp(who, "committer"))
931 return; /* "author" for commit object is not wanted */
932 if (!wholine)
933 wholine = find_wholine(who, wholen, buf, sz);
934 if (!wholine)
935 return;
936 for (i = 0; i < used_atom_cnt; i++) {
937 const char *name = used_atom[i].name;
938 struct atom_value *v = &val[i];
939 if (!!deref != (*name == '*'))
940 continue;
941 if (deref)
942 name++;
944 if (starts_with(name, "creatordate"))
945 grab_date(wholine, v, name);
946 else if (!strcmp(name, "creator"))
947 v->s = copy_line(wholine);
951 static void find_subpos(const char *buf, unsigned long sz,
952 const char **sub, unsigned long *sublen,
953 const char **body, unsigned long *bodylen,
954 unsigned long *nonsiglen,
955 const char **sig, unsigned long *siglen)
957 const char *eol;
958 /* skip past header until we hit empty line */
959 while (*buf && *buf != '\n') {
960 eol = strchrnul(buf, '\n');
961 if (*eol)
962 eol++;
963 buf = eol;
965 /* skip any empty lines */
966 while (*buf == '\n')
967 buf++;
969 /* parse signature first; we might not even have a subject line */
970 *sig = buf + parse_signature(buf, strlen(buf));
971 *siglen = strlen(*sig);
973 /* subject is first non-empty line */
974 *sub = buf;
975 /* subject goes to first empty line */
976 while (buf < *sig && *buf && *buf != '\n') {
977 eol = strchrnul(buf, '\n');
978 if (*eol)
979 eol++;
980 buf = eol;
982 *sublen = buf - *sub;
983 /* drop trailing newline, if present */
984 if (*sublen && (*sub)[*sublen - 1] == '\n')
985 *sublen -= 1;
987 /* skip any empty lines */
988 while (*buf == '\n')
989 buf++;
990 *body = buf;
991 *bodylen = strlen(buf);
992 *nonsiglen = *sig - buf;
996 * If 'lines' is greater than 0, append that many lines from the given
997 * 'buf' of length 'size' to the given strbuf.
999 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1001 int i;
1002 const char *sp, *eol;
1003 size_t len;
1005 sp = buf;
1007 for (i = 0; i < lines && sp < buf + size; i++) {
1008 if (i)
1009 strbuf_addstr(out, "\n ");
1010 eol = memchr(sp, '\n', size - (sp - buf));
1011 len = eol ? eol - sp : size - (sp - buf);
1012 strbuf_add(out, sp, len);
1013 if (!eol)
1014 break;
1015 sp = eol + 1;
1019 /* See grab_values */
1020 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1022 int i;
1023 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1024 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1026 for (i = 0; i < used_atom_cnt; i++) {
1027 struct used_atom *atom = &used_atom[i];
1028 const char *name = atom->name;
1029 struct atom_value *v = &val[i];
1030 if (!!deref != (*name == '*'))
1031 continue;
1032 if (deref)
1033 name++;
1034 if (strcmp(name, "subject") &&
1035 strcmp(name, "body") &&
1036 strcmp(name, "trailers") &&
1037 !starts_with(name, "contents"))
1038 continue;
1039 if (!subpos)
1040 find_subpos(buf, sz,
1041 &subpos, &sublen,
1042 &bodypos, &bodylen, &nonsiglen,
1043 &sigpos, &siglen);
1045 if (atom->u.contents.option == C_SUB)
1046 v->s = copy_subject(subpos, sublen);
1047 else if (atom->u.contents.option == C_BODY_DEP)
1048 v->s = xmemdupz(bodypos, bodylen);
1049 else if (atom->u.contents.option == C_BODY)
1050 v->s = xmemdupz(bodypos, nonsiglen);
1051 else if (atom->u.contents.option == C_SIG)
1052 v->s = xmemdupz(sigpos, siglen);
1053 else if (atom->u.contents.option == C_LINES) {
1054 struct strbuf s = STRBUF_INIT;
1055 const char *contents_end = bodylen + bodypos - siglen;
1057 /* Size is the length of the message after removing the signature */
1058 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1059 v->s = strbuf_detach(&s, NULL);
1060 } else if (atom->u.contents.option == C_TRAILERS) {
1061 struct trailer_info info;
1063 /* Search for trailer info */
1064 trailer_info_get(&info, subpos);
1065 v->s = xmemdupz(info.trailer_start,
1066 info.trailer_end - info.trailer_start);
1067 trailer_info_release(&info);
1068 } else if (atom->u.contents.option == C_BARE)
1069 v->s = xstrdup(subpos);
1074 * We want to have empty print-string for field requests
1075 * that do not apply (e.g. "authordate" for a tag object)
1077 static void fill_missing_values(struct atom_value *val)
1079 int i;
1080 for (i = 0; i < used_atom_cnt; i++) {
1081 struct atom_value *v = &val[i];
1082 if (v->s == NULL)
1083 v->s = "";
1088 * val is a list of atom_value to hold returned values. Extract
1089 * the values for atoms in used_atom array out of (obj, buf, sz).
1090 * when deref is false, (obj, buf, sz) is the object that is
1091 * pointed at by the ref itself; otherwise it is the object the
1092 * ref (which is a tag) refers to.
1094 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1096 grab_common_values(val, deref, obj, buf, sz);
1097 switch (obj->type) {
1098 case OBJ_TAG:
1099 grab_tag_values(val, deref, obj, buf, sz);
1100 grab_sub_body_contents(val, deref, obj, buf, sz);
1101 grab_person("tagger", val, deref, obj, buf, sz);
1102 break;
1103 case OBJ_COMMIT:
1104 grab_commit_values(val, deref, obj, buf, sz);
1105 grab_sub_body_contents(val, deref, obj, buf, sz);
1106 grab_person("author", val, deref, obj, buf, sz);
1107 grab_person("committer", val, deref, obj, buf, sz);
1108 break;
1109 case OBJ_TREE:
1110 /* grab_tree_values(val, deref, obj, buf, sz); */
1111 break;
1112 case OBJ_BLOB:
1113 /* grab_blob_values(val, deref, obj, buf, sz); */
1114 break;
1115 default:
1116 die("Eh? Object of type %d?", obj->type);
1120 static inline char *copy_advance(char *dst, const char *src)
1122 while (*src)
1123 *dst++ = *src++;
1124 return dst;
1127 static const char *lstrip_ref_components(const char *refname, int len)
1129 long remaining = len;
1130 const char *start = refname;
1132 if (len < 0) {
1133 int i;
1134 const char *p = refname;
1136 /* Find total no of '/' separated path-components */
1137 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1140 * The number of components we need to strip is now
1141 * the total minus the components to be left (Plus one
1142 * because we count the number of '/', but the number
1143 * of components is one more than the no of '/').
1145 remaining = i + len + 1;
1148 while (remaining > 0) {
1149 switch (*start++) {
1150 case '\0':
1151 return "";
1152 case '/':
1153 remaining--;
1154 break;
1158 return start;
1161 static const char *rstrip_ref_components(const char *refname, int len)
1163 long remaining = len;
1164 char *start = xstrdup(refname);
1166 if (len < 0) {
1167 int i;
1168 const char *p = refname;
1170 /* Find total no of '/' separated path-components */
1171 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1174 * The number of components we need to strip is now
1175 * the total minus the components to be left (Plus one
1176 * because we count the number of '/', but the number
1177 * of components is one more than the no of '/').
1179 remaining = i + len + 1;
1182 while (remaining-- > 0) {
1183 char *p = strrchr(start, '/');
1184 if (p == NULL)
1185 return "";
1186 else
1187 p[0] = '\0';
1189 return start;
1192 static const char *show_ref(struct refname_atom *atom, const char *refname)
1194 if (atom->option == R_SHORT)
1195 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1196 else if (atom->option == R_LSTRIP)
1197 return lstrip_ref_components(refname, atom->lstrip);
1198 else if (atom->option == R_RSTRIP)
1199 return rstrip_ref_components(refname, atom->rstrip);
1200 else
1201 return refname;
1204 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1205 struct branch *branch, const char **s)
1207 int num_ours, num_theirs;
1208 if (atom->u.remote_ref.option == RR_REF)
1209 *s = show_ref(&atom->u.remote_ref.refname, refname);
1210 else if (atom->u.remote_ref.option == RR_TRACK) {
1211 if (stat_tracking_info(branch, &num_ours,
1212 &num_theirs, NULL)) {
1213 *s = xstrdup(msgs.gone);
1214 } else if (!num_ours && !num_theirs)
1215 *s = "";
1216 else if (!num_ours)
1217 *s = xstrfmt(msgs.behind, num_theirs);
1218 else if (!num_theirs)
1219 *s = xstrfmt(msgs.ahead, num_ours);
1220 else
1221 *s = xstrfmt(msgs.ahead_behind,
1222 num_ours, num_theirs);
1223 if (!atom->u.remote_ref.nobracket && *s[0]) {
1224 const char *to_free = *s;
1225 *s = xstrfmt("[%s]", *s);
1226 free((void *)to_free);
1228 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1229 if (stat_tracking_info(branch, &num_ours,
1230 &num_theirs, NULL))
1231 return;
1233 if (!num_ours && !num_theirs)
1234 *s = "=";
1235 else if (!num_ours)
1236 *s = "<";
1237 else if (!num_theirs)
1238 *s = ">";
1239 else
1240 *s = "<>";
1241 } else
1242 die("BUG: unhandled RR_* enum");
1245 char *get_head_description(void)
1247 struct strbuf desc = STRBUF_INIT;
1248 struct wt_status_state state;
1249 memset(&state, 0, sizeof(state));
1250 wt_status_get_state(&state, 1);
1251 if (state.rebase_in_progress ||
1252 state.rebase_interactive_in_progress)
1253 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1254 state.branch);
1255 else if (state.bisect_in_progress)
1256 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1257 state.branch);
1258 else if (state.detached_from) {
1259 /* TRANSLATORS: make sure these match _("HEAD detached at ")
1260 and _("HEAD detached from ") in wt-status.c */
1261 if (state.detached_at)
1262 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1263 state.detached_from);
1264 else
1265 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1266 state.detached_from);
1268 else
1269 strbuf_addstr(&desc, _("(no branch)"));
1270 free(state.branch);
1271 free(state.onto);
1272 free(state.detached_from);
1273 return strbuf_detach(&desc, NULL);
1276 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1278 if (!ref->symref)
1279 return "";
1280 else
1281 return show_ref(&atom->u.refname, ref->symref);
1284 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1286 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1287 return get_head_description();
1288 return show_ref(&atom->u.refname, ref->refname);
1292 * Parse the object referred by ref, and grab needed value.
1294 static void populate_value(struct ref_array_item *ref)
1296 void *buf;
1297 struct object *obj;
1298 int eaten, i;
1299 unsigned long size;
1300 const unsigned char *tagged;
1302 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1304 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1305 unsigned char unused1[20];
1306 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1307 unused1, NULL);
1308 if (!ref->symref)
1309 ref->symref = "";
1312 /* Fill in specials first */
1313 for (i = 0; i < used_atom_cnt; i++) {
1314 struct used_atom *atom = &used_atom[i];
1315 const char *name = used_atom[i].name;
1316 struct atom_value *v = &ref->value[i];
1317 int deref = 0;
1318 const char *refname;
1319 struct branch *branch = NULL;
1321 v->handler = append_atom;
1322 v->atom = atom;
1324 if (*name == '*') {
1325 deref = 1;
1326 name++;
1329 if (starts_with(name, "refname"))
1330 refname = get_refname(atom, ref);
1331 else if (starts_with(name, "symref"))
1332 refname = get_symref(atom, ref);
1333 else if (starts_with(name, "upstream")) {
1334 const char *branch_name;
1335 /* only local branches may have an upstream */
1336 if (!skip_prefix(ref->refname, "refs/heads/",
1337 &branch_name))
1338 continue;
1339 branch = branch_get(branch_name);
1341 refname = branch_get_upstream(branch, NULL);
1342 if (refname)
1343 fill_remote_ref_details(atom, refname, branch, &v->s);
1344 continue;
1345 } else if (starts_with(name, "push")) {
1346 const char *branch_name;
1347 if (!skip_prefix(ref->refname, "refs/heads/",
1348 &branch_name))
1349 continue;
1350 branch = branch_get(branch_name);
1352 refname = branch_get_push(branch, NULL);
1353 if (!refname)
1354 continue;
1355 fill_remote_ref_details(atom, refname, branch, &v->s);
1356 continue;
1357 } else if (starts_with(name, "color:")) {
1358 v->s = atom->u.color;
1359 continue;
1360 } else if (!strcmp(name, "flag")) {
1361 char buf[256], *cp = buf;
1362 if (ref->flag & REF_ISSYMREF)
1363 cp = copy_advance(cp, ",symref");
1364 if (ref->flag & REF_ISPACKED)
1365 cp = copy_advance(cp, ",packed");
1366 if (cp == buf)
1367 v->s = "";
1368 else {
1369 *cp = '\0';
1370 v->s = xstrdup(buf + 1);
1372 continue;
1373 } else if (!deref && grab_objectname(name, ref->objectname, v, atom)) {
1374 continue;
1375 } else if (!strcmp(name, "HEAD")) {
1376 if (atom->u.head && !strcmp(ref->refname, atom->u.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 filter_ref_kind(struct ref_filter *filter, 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 (filter->kind == FILTER_REFS_BRANCHES ||
1711 filter->kind == FILTER_REFS_REMOTES ||
1712 filter->kind == FILTER_REFS_TAGS)
1713 return filter->kind;
1714 else if (!strcmp(refname, "HEAD"))
1715 return FILTER_REFS_DETACHED_HEAD;
1717 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1718 if (starts_with(refname, ref_kind[i].prefix))
1719 return ref_kind[i].kind;
1722 return FILTER_REFS_OTHERS;
1726 * A call-back given to for_each_ref(). Filter refs and keep them for
1727 * later object processing.
1729 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1731 struct ref_filter_cbdata *ref_cbdata = cb_data;
1732 struct ref_filter *filter = ref_cbdata->filter;
1733 struct ref_array_item *ref;
1734 struct commit *commit = NULL;
1735 unsigned int kind;
1737 if (flag & REF_BAD_NAME) {
1738 warning(_("ignoring ref with broken name %s"), refname);
1739 return 0;
1742 if (flag & REF_ISBROKEN) {
1743 warning(_("ignoring broken ref %s"), refname);
1744 return 0;
1747 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1748 kind = filter_ref_kind(filter, refname);
1749 if (!(kind & filter->kind))
1750 return 0;
1752 if (!filter_pattern_match(filter, refname))
1753 return 0;
1755 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1756 return 0;
1759 * A merge filter is applied on refs pointing to commits. Hence
1760 * obtain the commit using the 'oid' available and discard all
1761 * non-commits early. The actual filtering is done later.
1763 if (filter->merge_commit || filter->with_commit || filter->verbose) {
1764 commit = lookup_commit_reference_gently(oid->hash, 1);
1765 if (!commit)
1766 return 0;
1767 /* We perform the filtering for the '--contains' option */
1768 if (filter->with_commit &&
1769 !commit_contains(filter, commit))
1770 return 0;
1774 * We do not open the object yet; sort may only need refname
1775 * to do its job and the resulting list may yet to be pruned
1776 * by maxcount logic.
1778 ref = new_ref_array_item(refname, oid->hash, flag);
1779 ref->commit = commit;
1781 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1782 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1783 ref->kind = kind;
1784 return 0;
1787 /* Free memory allocated for a ref_array_item */
1788 static void free_array_item(struct ref_array_item *item)
1790 free((char *)item->symref);
1791 free(item);
1794 /* Free all memory allocated for ref_array */
1795 void ref_array_clear(struct ref_array *array)
1797 int i;
1799 for (i = 0; i < array->nr; i++)
1800 free_array_item(array->items[i]);
1801 free(array->items);
1802 array->items = NULL;
1803 array->nr = array->alloc = 0;
1806 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1808 struct rev_info revs;
1809 int i, old_nr;
1810 struct ref_filter *filter = ref_cbdata->filter;
1811 struct ref_array *array = ref_cbdata->array;
1812 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1814 init_revisions(&revs, NULL);
1816 for (i = 0; i < array->nr; i++) {
1817 struct ref_array_item *item = array->items[i];
1818 add_pending_object(&revs, &item->commit->object, item->refname);
1819 to_clear[i] = item->commit;
1822 filter->merge_commit->object.flags |= UNINTERESTING;
1823 add_pending_object(&revs, &filter->merge_commit->object, "");
1825 revs.limited = 1;
1826 if (prepare_revision_walk(&revs))
1827 die(_("revision walk setup failed"));
1829 old_nr = array->nr;
1830 array->nr = 0;
1832 for (i = 0; i < old_nr; i++) {
1833 struct ref_array_item *item = array->items[i];
1834 struct commit *commit = item->commit;
1836 int is_merged = !!(commit->object.flags & UNINTERESTING);
1838 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1839 array->items[array->nr++] = array->items[i];
1840 else
1841 free_array_item(item);
1844 for (i = 0; i < old_nr; i++)
1845 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1846 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1847 free(to_clear);
1851 * API for filtering a set of refs. Based on the type of refs the user
1852 * has requested, we iterate through those refs and apply filters
1853 * as per the given ref_filter structure and finally store the
1854 * filtered refs in the ref_array structure.
1856 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1858 struct ref_filter_cbdata ref_cbdata;
1859 int ret = 0;
1860 unsigned int broken = 0;
1862 ref_cbdata.array = array;
1863 ref_cbdata.filter = filter;
1865 if (type & FILTER_REFS_INCLUDE_BROKEN)
1866 broken = 1;
1867 filter->kind = type & FILTER_REFS_KIND_MASK;
1869 /* Simple per-ref filtering */
1870 if (!filter->kind)
1871 die("filter_refs: invalid type");
1872 else {
1874 * For common cases where we need only branches or remotes or tags,
1875 * we only iterate through those refs. If a mix of refs is needed,
1876 * we iterate over all refs and filter out required refs with the help
1877 * of filter_ref_kind().
1879 if (filter->kind == FILTER_REFS_BRANCHES)
1880 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1881 else if (filter->kind == FILTER_REFS_REMOTES)
1882 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1883 else if (filter->kind == FILTER_REFS_TAGS)
1884 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1885 else if (filter->kind & FILTER_REFS_ALL)
1886 ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1887 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1888 head_ref(ref_filter_handler, &ref_cbdata);
1892 /* Filters that need revision walking */
1893 if (filter->merge_commit)
1894 do_merge_filter(&ref_cbdata);
1896 return ret;
1899 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1901 struct atom_value *va, *vb;
1902 int cmp;
1903 cmp_type cmp_type = used_atom[s->atom].type;
1904 int (*cmp_fn)(const char *, const char *);
1906 get_ref_atom_value(a, s->atom, &va);
1907 get_ref_atom_value(b, s->atom, &vb);
1908 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
1909 if (s->version)
1910 cmp = versioncmp(va->s, vb->s);
1911 else if (cmp_type == FIELD_STR)
1912 cmp = cmp_fn(va->s, vb->s);
1913 else {
1914 if (va->ul < vb->ul)
1915 cmp = -1;
1916 else if (va->ul == vb->ul)
1917 cmp = cmp_fn(a->refname, b->refname);
1918 else
1919 cmp = 1;
1922 return (s->reverse) ? -cmp : cmp;
1925 static struct ref_sorting *ref_sorting;
1926 static int compare_refs(const void *a_, const void *b_)
1928 struct ref_array_item *a = *((struct ref_array_item **)a_);
1929 struct ref_array_item *b = *((struct ref_array_item **)b_);
1930 struct ref_sorting *s;
1932 for (s = ref_sorting; s; s = s->next) {
1933 int cmp = cmp_ref_sorting(s, a, b);
1934 if (cmp)
1935 return cmp;
1937 return 0;
1940 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1942 ref_sorting = sorting;
1943 QSORT(array->items, array->nr, compare_refs);
1946 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1948 struct strbuf *s = &state->stack->output;
1950 while (*cp && (!ep || cp < ep)) {
1951 if (*cp == '%') {
1952 if (cp[1] == '%')
1953 cp++;
1954 else {
1955 int ch = hex2chr(cp + 1);
1956 if (0 <= ch) {
1957 strbuf_addch(s, ch);
1958 cp += 3;
1959 continue;
1963 strbuf_addch(s, *cp);
1964 cp++;
1968 void format_ref_array_item(struct ref_array_item *info, const char *format,
1969 int quote_style, struct strbuf *final_buf)
1971 const char *cp, *sp, *ep;
1972 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1974 state.quote_style = quote_style;
1975 push_stack_element(&state.stack);
1977 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1978 struct atom_value *atomv;
1980 ep = strchr(sp, ')');
1981 if (cp < sp)
1982 append_literal(cp, sp, &state);
1983 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1984 atomv->handler(atomv, &state);
1986 if (*cp) {
1987 sp = cp + strlen(cp);
1988 append_literal(cp, sp, &state);
1990 if (need_color_reset_at_eol) {
1991 struct atom_value resetv;
1992 char color[COLOR_MAXLEN] = "";
1994 if (color_parse("reset", color) < 0)
1995 die("BUG: couldn't parse 'reset' as a color");
1996 resetv.s = color;
1997 append_atom(&resetv, &state);
1999 if (state.stack->prev)
2000 die(_("format: %%(end) atom missing"));
2001 strbuf_addbuf(final_buf, &state.stack->output);
2002 pop_stack_element(&state.stack);
2005 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
2007 struct strbuf final_buf = STRBUF_INIT;
2009 format_ref_array_item(info, format, quote_style, &final_buf);
2010 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2011 strbuf_release(&final_buf);
2012 putchar('\n');
2015 /* If no sorting option is given, use refname to sort as default */
2016 struct ref_sorting *ref_default_sorting(void)
2018 static const char cstr_name[] = "refname";
2020 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2022 sorting->next = NULL;
2023 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
2024 return sorting;
2027 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2029 struct ref_sorting **sorting_tail = opt->value;
2030 struct ref_sorting *s;
2031 int len;
2033 if (!arg) /* should --no-sort void the list ? */
2034 return -1;
2036 s = xcalloc(1, sizeof(*s));
2037 s->next = *sorting_tail;
2038 *sorting_tail = s;
2040 if (*arg == '-') {
2041 s->reverse = 1;
2042 arg++;
2044 if (skip_prefix(arg, "version:", &arg) ||
2045 skip_prefix(arg, "v:", &arg))
2046 s->version = 1;
2047 len = strlen(arg);
2048 s->atom = parse_ref_filter_atom(arg, arg+len);
2049 return 0;
2052 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2054 struct ref_filter *rf = opt->value;
2055 unsigned char sha1[20];
2057 rf->merge = starts_with(opt->long_name, "no")
2058 ? REF_FILTER_MERGED_OMIT
2059 : REF_FILTER_MERGED_INCLUDE;
2061 if (get_sha1(arg, sha1))
2062 die(_("malformed object name %s"), arg);
2064 rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
2065 if (!rf->merge_commit)
2066 return opterror(opt, "must point to a commit", 0);
2068 return 0;