3 #include "parse-options.h"
11 #include "ref-filter.h"
14 #include "git-compat-util.h"
17 #include "wt-status.h"
18 #include "commit-slab.h"
20 static struct ref_msg {
24 const char *ahead_behind;
26 /* Untranslated plumbing messages: */
33 void setup_ref_filter_porcelain_msg(void)
35 msgs.gone = _("gone");
36 msgs.ahead = _("ahead %d");
37 msgs.behind = _("behind %d");
38 msgs.ahead_behind = _("ahead %d, behind %d");
41 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
42 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
50 cmp_status cmp_status;
52 unsigned int then_atom_seen : 1,
54 condition_satisfied : 1;
58 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
63 * An atom is a valid field atom listed below, possibly prefixed with
64 * a "*" to denote deref_tag().
66 * We parse given format string and sort specifiers, and make a list
67 * of properties that we need to extract out of objects. ref_array_item
68 * structure will hold an array of values extracted that can be
69 * indexed with the "atom number", which is an index into this
72 static struct used_atom {
76 char color[COLOR_MAXLEN];
80 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
82 struct refname_atom refname;
83 unsigned int nobracket : 1, push : 1, push_remote : 1;
86 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
90 cmp_status cmp_status;
94 enum { O_FULL, O_LENGTH, O_SHORT } option;
97 struct refname_atom refname;
101 static int used_atom_cnt, need_tagged, need_symref;
103 static void color_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *color_value)
106 die(_("expected format: %%(color:<color>)"));
107 if (color_parse(color_value, atom->u.color) < 0)
108 die(_("unrecognized color: %%(color:%s)"), color_value);
110 * We check this after we've parsed the color, which lets us complain
111 * about syntactically bogus color names even if they won't be used.
113 if (!want_color(format->use_color))
114 color_parse("", atom->u.color);
117 static void refname_atom_parser_internal(struct refname_atom *atom,
118 const char *arg, const char *name)
121 atom->option = R_NORMAL;
122 else if (!strcmp(arg, "short"))
123 atom->option = R_SHORT;
124 else if (skip_prefix(arg, "lstrip=", &arg) ||
125 skip_prefix(arg, "strip=", &arg)) {
126 atom->option = R_LSTRIP;
127 if (strtol_i(arg, 10, &atom->lstrip))
128 die(_("Integer value expected refname:lstrip=%s"), arg);
129 } else if (skip_prefix(arg, "rstrip=", &arg)) {
130 atom->option = R_RSTRIP;
131 if (strtol_i(arg, 10, &atom->rstrip))
132 die(_("Integer value expected refname:rstrip=%s"), arg);
134 die(_("unrecognized %%(%s) argument: %s"), name, arg);
137 static void remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
139 struct string_list params = STRING_LIST_INIT_DUP;
142 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
143 atom->u.remote_ref.push = 1;
146 atom->u.remote_ref.option = RR_REF;
147 refname_atom_parser_internal(&atom->u.remote_ref.refname,
152 atom->u.remote_ref.nobracket = 0;
153 string_list_split(¶ms, arg, ',', -1);
155 for (i = 0; i < params.nr; i++) {
156 const char *s = params.items[i].string;
158 if (!strcmp(s, "track"))
159 atom->u.remote_ref.option = RR_TRACK;
160 else if (!strcmp(s, "trackshort"))
161 atom->u.remote_ref.option = RR_TRACKSHORT;
162 else if (!strcmp(s, "nobracket"))
163 atom->u.remote_ref.nobracket = 1;
164 else if (!strcmp(s, "remotename")) {
165 atom->u.remote_ref.option = RR_REMOTE_NAME;
166 atom->u.remote_ref.push_remote = 1;
167 } else if (!strcmp(s, "remoteref")) {
168 atom->u.remote_ref.option = RR_REMOTE_REF;
169 atom->u.remote_ref.push_remote = 1;
171 atom->u.remote_ref.option = RR_REF;
172 refname_atom_parser_internal(&atom->u.remote_ref.refname,
177 string_list_clear(¶ms, 0);
180 static void body_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
183 die(_("%%(body) does not take arguments"));
184 atom->u.contents.option = C_BODY_DEP;
187 static void subject_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
190 die(_("%%(subject) does not take arguments"));
191 atom->u.contents.option = C_SUB;
194 static void trailers_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
197 die(_("%%(trailers) does not take arguments"));
198 atom->u.contents.option = C_TRAILERS;
201 static void contents_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
204 atom->u.contents.option = C_BARE;
205 else if (!strcmp(arg, "body"))
206 atom->u.contents.option = C_BODY;
207 else if (!strcmp(arg, "signature"))
208 atom->u.contents.option = C_SIG;
209 else if (!strcmp(arg, "subject"))
210 atom->u.contents.option = C_SUB;
211 else if (!strcmp(arg, "trailers"))
212 atom->u.contents.option = C_TRAILERS;
213 else if (skip_prefix(arg, "lines=", &arg)) {
214 atom->u.contents.option = C_LINES;
215 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
216 die(_("positive value expected contents:lines=%s"), arg);
218 die(_("unrecognized %%(contents) argument: %s"), arg);
221 static void objectname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
224 atom->u.objectname.option = O_FULL;
225 else if (!strcmp(arg, "short"))
226 atom->u.objectname.option = O_SHORT;
227 else if (skip_prefix(arg, "short=", &arg)) {
228 atom->u.objectname.option = O_LENGTH;
229 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
230 atom->u.objectname.length == 0)
231 die(_("positive value expected objectname:short=%s"), arg);
232 if (atom->u.objectname.length < MINIMUM_ABBREV)
233 atom->u.objectname.length = MINIMUM_ABBREV;
235 die(_("unrecognized %%(objectname) argument: %s"), arg);
238 static void refname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
240 refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
243 static align_type parse_align_position(const char *s)
245 if (!strcmp(s, "right"))
247 else if (!strcmp(s, "middle"))
249 else if (!strcmp(s, "left"))
254 static void align_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
256 struct align *align = &atom->u.align;
257 struct string_list params = STRING_LIST_INIT_DUP;
259 unsigned int width = ~0U;
262 die(_("expected format: %%(align:<width>,<position>)"));
264 align->position = ALIGN_LEFT;
266 string_list_split(¶ms, arg, ',', -1);
267 for (i = 0; i < params.nr; i++) {
268 const char *s = params.items[i].string;
271 if (skip_prefix(s, "position=", &s)) {
272 position = parse_align_position(s);
274 die(_("unrecognized position:%s"), s);
275 align->position = position;
276 } else if (skip_prefix(s, "width=", &s)) {
277 if (strtoul_ui(s, 10, &width))
278 die(_("unrecognized width:%s"), s);
279 } else if (!strtoul_ui(s, 10, &width))
281 else if ((position = parse_align_position(s)) >= 0)
282 align->position = position;
284 die(_("unrecognized %%(align) argument: %s"), s);
288 die(_("positive width expected with the %%(align) atom"));
289 align->width = width;
290 string_list_clear(¶ms, 0);
293 static void if_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
296 atom->u.if_then_else.cmp_status = COMPARE_NONE;
298 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
299 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
300 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
301 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
303 die(_("unrecognized %%(if) argument: %s"), arg);
307 static void head_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
309 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
315 void (*parser)(const struct ref_format *format, struct used_atom *atom, const char *arg);
317 { "refname" , FIELD_STR, refname_atom_parser },
319 { "objectsize", FIELD_ULONG },
320 { "objectname", FIELD_STR, objectname_atom_parser },
323 { "numparent", FIELD_ULONG },
330 { "authordate", FIELD_TIME },
333 { "committeremail" },
334 { "committerdate", FIELD_TIME },
338 { "taggerdate", FIELD_TIME },
340 { "creatordate", FIELD_TIME },
341 { "subject", FIELD_STR, subject_atom_parser },
342 { "body", FIELD_STR, body_atom_parser },
343 { "trailers", FIELD_STR, trailers_atom_parser },
344 { "contents", FIELD_STR, contents_atom_parser },
345 { "upstream", FIELD_STR, remote_ref_atom_parser },
346 { "push", FIELD_STR, remote_ref_atom_parser },
347 { "symref", FIELD_STR, refname_atom_parser },
349 { "HEAD", FIELD_STR, head_atom_parser },
350 { "color", FIELD_STR, color_atom_parser },
351 { "align", FIELD_STR, align_atom_parser },
353 { "if", FIELD_STR, if_atom_parser },
358 #define REF_FORMATTING_STATE_INIT { 0, NULL }
360 struct ref_formatting_stack {
361 struct ref_formatting_stack *prev;
362 struct strbuf output;
363 void (*at_end)(struct ref_formatting_stack **stack);
367 struct ref_formatting_state {
369 struct ref_formatting_stack *stack;
374 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
375 uintmax_t value; /* used for sorting when not FIELD_STR */
376 struct used_atom *atom;
380 * Used to parse format string and sort specifiers
382 static int parse_ref_filter_atom(const struct ref_format *format,
383 const char *atom, const char *ep)
390 if (*sp == '*' && sp < ep)
393 die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
395 /* Do we have the atom already used elsewhere? */
396 for (i = 0; i < used_atom_cnt; i++) {
397 int len = strlen(used_atom[i].name);
398 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
403 * If the atom name has a colon, strip it and everything after
404 * it off - it specifies the format for this entry, and
405 * shouldn't be used for checking against the valid_atom
408 arg = memchr(sp, ':', ep - sp);
409 atom_len = (arg ? arg : ep) - sp;
411 /* Is the atom a valid one? */
412 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
413 int len = strlen(valid_atom[i].name);
414 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
418 if (ARRAY_SIZE(valid_atom) <= i)
419 die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
421 /* Add it in, including the deref prefix */
424 REALLOC_ARRAY(used_atom, used_atom_cnt);
425 used_atom[at].name = xmemdupz(atom, ep - atom);
426 used_atom[at].type = valid_atom[i].cmp_type;
428 arg = used_atom[at].name + (arg - atom) + 1;
429 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
430 if (valid_atom[i].parser)
431 valid_atom[i].parser(format, &used_atom[at], arg);
434 if (!strcmp(valid_atom[i].name, "symref"))
439 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
441 switch (quote_style) {
443 strbuf_addstr(s, str);
446 sq_quote_buf(s, str);
449 perl_quote_buf(s, str);
452 python_quote_buf(s, str);
455 tcl_quote_buf(s, str);
460 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
463 * Quote formatting is only done when the stack has a single
464 * element. Otherwise quote formatting is done on the
465 * element's entire output strbuf when the %(end) atom is
468 if (!state->stack->prev)
469 quote_formatting(&state->stack->output, v->s, state->quote_style);
471 strbuf_addstr(&state->stack->output, v->s);
474 static void push_stack_element(struct ref_formatting_stack **stack)
476 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
478 strbuf_init(&s->output, 0);
483 static void pop_stack_element(struct ref_formatting_stack **stack)
485 struct ref_formatting_stack *current = *stack;
486 struct ref_formatting_stack *prev = current->prev;
489 strbuf_addbuf(&prev->output, ¤t->output);
490 strbuf_release(¤t->output);
495 static void end_align_handler(struct ref_formatting_stack **stack)
497 struct ref_formatting_stack *cur = *stack;
498 struct align *align = (struct align *)cur->at_end_data;
499 struct strbuf s = STRBUF_INIT;
501 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
502 strbuf_swap(&cur->output, &s);
506 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
508 struct ref_formatting_stack *new;
510 push_stack_element(&state->stack);
512 new->at_end = end_align_handler;
513 new->at_end_data = &atomv->atom->u.align;
516 static void if_then_else_handler(struct ref_formatting_stack **stack)
518 struct ref_formatting_stack *cur = *stack;
519 struct ref_formatting_stack *prev = cur->prev;
520 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
522 if (!if_then_else->then_atom_seen)
523 die(_("format: %%(if) atom used without a %%(then) atom"));
525 if (if_then_else->else_atom_seen) {
527 * There is an %(else) atom: we need to drop one state from the
528 * stack, either the %(else) branch if the condition is satisfied, or
529 * the %(then) branch if it isn't.
531 if (if_then_else->condition_satisfied) {
532 strbuf_reset(&cur->output);
533 pop_stack_element(&cur);
535 strbuf_swap(&cur->output, &prev->output);
536 strbuf_reset(&cur->output);
537 pop_stack_element(&cur);
539 } else if (!if_then_else->condition_satisfied) {
541 * No %(else) atom: just drop the %(then) branch if the
542 * condition is not satisfied.
544 strbuf_reset(&cur->output);
551 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
553 struct ref_formatting_stack *new;
554 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
556 if_then_else->str = atomv->atom->u.if_then_else.str;
557 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
559 push_stack_element(&state->stack);
561 new->at_end = if_then_else_handler;
562 new->at_end_data = if_then_else;
565 static int is_empty(const char *s)
575 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
577 struct ref_formatting_stack *cur = state->stack;
578 struct if_then_else *if_then_else = NULL;
580 if (cur->at_end == if_then_else_handler)
581 if_then_else = (struct if_then_else *)cur->at_end_data;
583 die(_("format: %%(then) atom used without an %%(if) atom"));
584 if (if_then_else->then_atom_seen)
585 die(_("format: %%(then) atom used more than once"));
586 if (if_then_else->else_atom_seen)
587 die(_("format: %%(then) atom used after %%(else)"));
588 if_then_else->then_atom_seen = 1;
590 * If the 'equals' or 'notequals' attribute is used then
591 * perform the required comparison. If not, only non-empty
592 * strings satisfy the 'if' condition.
594 if (if_then_else->cmp_status == COMPARE_EQUAL) {
595 if (!strcmp(if_then_else->str, cur->output.buf))
596 if_then_else->condition_satisfied = 1;
597 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
598 if (strcmp(if_then_else->str, cur->output.buf))
599 if_then_else->condition_satisfied = 1;
600 } else if (cur->output.len && !is_empty(cur->output.buf))
601 if_then_else->condition_satisfied = 1;
602 strbuf_reset(&cur->output);
605 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
607 struct ref_formatting_stack *prev = state->stack;
608 struct if_then_else *if_then_else = NULL;
610 if (prev->at_end == if_then_else_handler)
611 if_then_else = (struct if_then_else *)prev->at_end_data;
613 die(_("format: %%(else) atom used without an %%(if) atom"));
614 if (!if_then_else->then_atom_seen)
615 die(_("format: %%(else) atom used without a %%(then) atom"));
616 if (if_then_else->else_atom_seen)
617 die(_("format: %%(else) atom used more than once"));
618 if_then_else->else_atom_seen = 1;
619 push_stack_element(&state->stack);
620 state->stack->at_end_data = prev->at_end_data;
621 state->stack->at_end = prev->at_end;
624 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
626 struct ref_formatting_stack *current = state->stack;
627 struct strbuf s = STRBUF_INIT;
629 if (!current->at_end)
630 die(_("format: %%(end) atom used without corresponding atom"));
631 current->at_end(&state->stack);
633 /* Stack may have been popped within at_end(), hence reset the current pointer */
634 current = state->stack;
637 * Perform quote formatting when the stack element is that of
638 * a supporting atom. If nested then perform quote formatting
639 * only on the topmost supporting atom.
641 if (!current->prev->prev) {
642 quote_formatting(&s, current->output.buf, state->quote_style);
643 strbuf_swap(¤t->output, &s);
646 pop_stack_element(&state->stack);
650 * In a format string, find the next occurrence of %(atom).
652 static const char *find_next(const char *cp)
657 * %( is the start of an atom;
658 * %% is a quoted per-cent.
662 else if (cp[1] == '%')
663 cp++; /* skip over two % */
664 /* otherwise this is a singleton, literal % */
672 * Make sure the format string is well formed, and parse out
675 int verify_ref_format(struct ref_format *format)
679 format->need_color_reset_at_eol = 0;
680 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
681 const char *color, *ep = strchr(sp, ')');
685 return error(_("malformed format string %s"), sp);
686 /* sp points at "%(" and ep points at the closing ")" */
687 at = parse_ref_filter_atom(format, sp + 2, ep);
690 if (skip_prefix(used_atom[at].name, "color:", &color))
691 format->need_color_reset_at_eol = !!strcmp(color, "reset");
693 if (format->need_color_reset_at_eol && !want_color(format->use_color))
694 format->need_color_reset_at_eol = 0;
699 * Given an object name, read the object data and size, and return a
700 * "struct object". If the object data we are returning is also borrowed
701 * by the "struct object" representation, set *eaten as well---it is a
702 * signal from parse_object_buffer to us not to free the buffer.
704 static void *get_obj(const struct object_id *oid, struct object **obj, unsigned long *sz, int *eaten)
706 enum object_type type;
707 void *buf = read_sha1_file(oid->hash, &type, sz);
710 *obj = parse_object_buffer(oid, type, *sz, buf, eaten);
716 static int grab_objectname(const char *name, const unsigned char *sha1,
717 struct atom_value *v, struct used_atom *atom)
719 if (starts_with(name, "objectname")) {
720 if (atom->u.objectname.option == O_SHORT) {
721 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
723 } else if (atom->u.objectname.option == O_FULL) {
724 v->s = xstrdup(sha1_to_hex(sha1));
726 } else if (atom->u.objectname.option == O_LENGTH) {
727 v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
730 die("BUG: unknown %%(objectname) option");
735 /* See grab_values */
736 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
740 for (i = 0; i < used_atom_cnt; i++) {
741 const char *name = used_atom[i].name;
742 struct atom_value *v = &val[i];
743 if (!!deref != (*name == '*'))
747 if (!strcmp(name, "objecttype"))
748 v->s = typename(obj->type);
749 else if (!strcmp(name, "objectsize")) {
751 v->s = xstrfmt("%lu", sz);
754 grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
758 /* See grab_values */
759 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
762 struct tag *tag = (struct tag *) obj;
764 for (i = 0; i < used_atom_cnt; i++) {
765 const char *name = used_atom[i].name;
766 struct atom_value *v = &val[i];
767 if (!!deref != (*name == '*'))
771 if (!strcmp(name, "tag"))
773 else if (!strcmp(name, "type") && tag->tagged)
774 v->s = typename(tag->tagged->type);
775 else if (!strcmp(name, "object") && tag->tagged)
776 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
780 /* See grab_values */
781 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
784 struct commit *commit = (struct commit *) obj;
786 for (i = 0; i < used_atom_cnt; i++) {
787 const char *name = used_atom[i].name;
788 struct atom_value *v = &val[i];
789 if (!!deref != (*name == '*'))
793 if (!strcmp(name, "tree")) {
794 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
796 else if (!strcmp(name, "numparent")) {
797 v->value = commit_list_count(commit->parents);
798 v->s = xstrfmt("%lu", (unsigned long)v->value);
800 else if (!strcmp(name, "parent")) {
801 struct commit_list *parents;
802 struct strbuf s = STRBUF_INIT;
803 for (parents = commit->parents; parents; parents = parents->next) {
804 struct commit *parent = parents->item;
805 if (parents != commit->parents)
806 strbuf_addch(&s, ' ');
807 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
809 v->s = strbuf_detach(&s, NULL);
814 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
818 if (!strncmp(buf, who, wholen) &&
820 return buf + wholen + 1;
821 eol = strchr(buf, '\n');
826 return ""; /* end of header */
832 static const char *copy_line(const char *buf)
834 const char *eol = strchrnul(buf, '\n');
835 return xmemdupz(buf, eol - buf);
838 static const char *copy_name(const char *buf)
841 for (cp = buf; *cp && *cp != '\n'; cp++) {
842 if (!strncmp(cp, " <", 2))
843 return xmemdupz(buf, cp - buf);
848 static const char *copy_email(const char *buf)
850 const char *email = strchr(buf, '<');
854 eoemail = strchr(email, '>');
857 return xmemdupz(email, eoemail + 1 - email);
860 static char *copy_subject(const char *buf, unsigned long len)
862 char *r = xmemdupz(buf, len);
865 for (i = 0; i < len; i++)
872 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
874 const char *eoemail = strstr(buf, "> ");
876 timestamp_t timestamp;
878 struct date_mode date_mode = { DATE_NORMAL };
882 * We got here because atomname ends in "date" or "date<something>";
883 * it's not possible that <something> is not ":<format>" because
884 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
885 * ":" means no format is specified, and use the default.
887 formatp = strchr(atomname, ':');
888 if (formatp != NULL) {
890 parse_date_format(formatp, &date_mode);
895 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
896 if (timestamp == TIME_MAX)
898 tz = strtol(zone, NULL, 10);
899 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
901 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
902 v->value = timestamp;
909 /* See grab_values */
910 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
913 int wholen = strlen(who);
914 const char *wholine = NULL;
916 for (i = 0; i < used_atom_cnt; i++) {
917 const char *name = used_atom[i].name;
918 struct atom_value *v = &val[i];
919 if (!!deref != (*name == '*'))
923 if (strncmp(who, name, wholen))
925 if (name[wholen] != 0 &&
926 strcmp(name + wholen, "name") &&
927 strcmp(name + wholen, "email") &&
928 !starts_with(name + wholen, "date"))
931 wholine = find_wholine(who, wholen, buf, sz);
933 return; /* no point looking for it */
934 if (name[wholen] == 0)
935 v->s = copy_line(wholine);
936 else if (!strcmp(name + wholen, "name"))
937 v->s = copy_name(wholine);
938 else if (!strcmp(name + wholen, "email"))
939 v->s = copy_email(wholine);
940 else if (starts_with(name + wholen, "date"))
941 grab_date(wholine, v, name);
945 * For a tag or a commit object, if "creator" or "creatordate" is
946 * requested, do something special.
948 if (strcmp(who, "tagger") && strcmp(who, "committer"))
949 return; /* "author" for commit object is not wanted */
951 wholine = find_wholine(who, wholen, buf, sz);
954 for (i = 0; i < used_atom_cnt; i++) {
955 const char *name = used_atom[i].name;
956 struct atom_value *v = &val[i];
957 if (!!deref != (*name == '*'))
962 if (starts_with(name, "creatordate"))
963 grab_date(wholine, v, name);
964 else if (!strcmp(name, "creator"))
965 v->s = copy_line(wholine);
969 static void find_subpos(const char *buf, unsigned long sz,
970 const char **sub, unsigned long *sublen,
971 const char **body, unsigned long *bodylen,
972 unsigned long *nonsiglen,
973 const char **sig, unsigned long *siglen)
976 /* skip past header until we hit empty line */
977 while (*buf && *buf != '\n') {
978 eol = strchrnul(buf, '\n');
983 /* skip any empty lines */
987 /* parse signature first; we might not even have a subject line */
988 *sig = buf + parse_signature(buf, strlen(buf));
989 *siglen = strlen(*sig);
991 /* subject is first non-empty line */
993 /* subject goes to first empty line */
994 while (buf < *sig && *buf && *buf != '\n') {
995 eol = strchrnul(buf, '\n');
1000 *sublen = buf - *sub;
1001 /* drop trailing newline, if present */
1002 if (*sublen && (*sub)[*sublen - 1] == '\n')
1005 /* skip any empty lines */
1006 while (*buf == '\n')
1009 *bodylen = strlen(buf);
1010 *nonsiglen = *sig - buf;
1014 * If 'lines' is greater than 0, append that many lines from the given
1015 * 'buf' of length 'size' to the given strbuf.
1017 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1020 const char *sp, *eol;
1025 for (i = 0; i < lines && sp < buf + size; i++) {
1027 strbuf_addstr(out, "\n ");
1028 eol = memchr(sp, '\n', size - (sp - buf));
1029 len = eol ? eol - sp : size - (sp - buf);
1030 strbuf_add(out, sp, len);
1037 /* See grab_values */
1038 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1041 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1042 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1044 for (i = 0; i < used_atom_cnt; i++) {
1045 struct used_atom *atom = &used_atom[i];
1046 const char *name = atom->name;
1047 struct atom_value *v = &val[i];
1048 if (!!deref != (*name == '*'))
1052 if (strcmp(name, "subject") &&
1053 strcmp(name, "body") &&
1054 strcmp(name, "trailers") &&
1055 !starts_with(name, "contents"))
1058 find_subpos(buf, sz,
1060 &bodypos, &bodylen, &nonsiglen,
1063 if (atom->u.contents.option == C_SUB)
1064 v->s = copy_subject(subpos, sublen);
1065 else if (atom->u.contents.option == C_BODY_DEP)
1066 v->s = xmemdupz(bodypos, bodylen);
1067 else if (atom->u.contents.option == C_BODY)
1068 v->s = xmemdupz(bodypos, nonsiglen);
1069 else if (atom->u.contents.option == C_SIG)
1070 v->s = xmemdupz(sigpos, siglen);
1071 else if (atom->u.contents.option == C_LINES) {
1072 struct strbuf s = STRBUF_INIT;
1073 const char *contents_end = bodylen + bodypos - siglen;
1075 /* Size is the length of the message after removing the signature */
1076 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1077 v->s = strbuf_detach(&s, NULL);
1078 } else if (atom->u.contents.option == C_TRAILERS) {
1079 struct trailer_info info;
1081 /* Search for trailer info */
1082 trailer_info_get(&info, subpos);
1083 v->s = xmemdupz(info.trailer_start,
1084 info.trailer_end - info.trailer_start);
1085 trailer_info_release(&info);
1086 } else if (atom->u.contents.option == C_BARE)
1087 v->s = xstrdup(subpos);
1092 * We want to have empty print-string for field requests
1093 * that do not apply (e.g. "authordate" for a tag object)
1095 static void fill_missing_values(struct atom_value *val)
1098 for (i = 0; i < used_atom_cnt; i++) {
1099 struct atom_value *v = &val[i];
1106 * val is a list of atom_value to hold returned values. Extract
1107 * the values for atoms in used_atom array out of (obj, buf, sz).
1108 * when deref is false, (obj, buf, sz) is the object that is
1109 * pointed at by the ref itself; otherwise it is the object the
1110 * ref (which is a tag) refers to.
1112 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1114 grab_common_values(val, deref, obj, buf, sz);
1115 switch (obj->type) {
1117 grab_tag_values(val, deref, obj, buf, sz);
1118 grab_sub_body_contents(val, deref, obj, buf, sz);
1119 grab_person("tagger", val, deref, obj, buf, sz);
1122 grab_commit_values(val, deref, obj, buf, sz);
1123 grab_sub_body_contents(val, deref, obj, buf, sz);
1124 grab_person("author", val, deref, obj, buf, sz);
1125 grab_person("committer", val, deref, obj, buf, sz);
1128 /* grab_tree_values(val, deref, obj, buf, sz); */
1131 /* grab_blob_values(val, deref, obj, buf, sz); */
1134 die("Eh? Object of type %d?", obj->type);
1138 static inline char *copy_advance(char *dst, const char *src)
1145 static const char *lstrip_ref_components(const char *refname, int len)
1147 long remaining = len;
1148 const char *start = refname;
1152 const char *p = refname;
1154 /* Find total no of '/' separated path-components */
1155 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1158 * The number of components we need to strip is now
1159 * the total minus the components to be left (Plus one
1160 * because we count the number of '/', but the number
1161 * of components is one more than the no of '/').
1163 remaining = i + len + 1;
1166 while (remaining > 0) {
1179 static const char *rstrip_ref_components(const char *refname, int len)
1181 long remaining = len;
1182 char *start = xstrdup(refname);
1186 const char *p = refname;
1188 /* Find total no of '/' separated path-components */
1189 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1192 * The number of components we need to strip is now
1193 * the total minus the components to be left (Plus one
1194 * because we count the number of '/', but the number
1195 * of components is one more than the no of '/').
1197 remaining = i + len + 1;
1200 while (remaining-- > 0) {
1201 char *p = strrchr(start, '/');
1210 static const char *show_ref(struct refname_atom *atom, const char *refname)
1212 if (atom->option == R_SHORT)
1213 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1214 else if (atom->option == R_LSTRIP)
1215 return lstrip_ref_components(refname, atom->lstrip);
1216 else if (atom->option == R_RSTRIP)
1217 return rstrip_ref_components(refname, atom->rstrip);
1222 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1223 struct branch *branch, const char **s)
1225 int num_ours, num_theirs;
1226 if (atom->u.remote_ref.option == RR_REF)
1227 *s = show_ref(&atom->u.remote_ref.refname, refname);
1228 else if (atom->u.remote_ref.option == RR_TRACK) {
1229 if (stat_tracking_info(branch, &num_ours,
1230 &num_theirs, NULL)) {
1231 *s = xstrdup(msgs.gone);
1232 } else if (!num_ours && !num_theirs)
1235 *s = xstrfmt(msgs.behind, num_theirs);
1236 else if (!num_theirs)
1237 *s = xstrfmt(msgs.ahead, num_ours);
1239 *s = xstrfmt(msgs.ahead_behind,
1240 num_ours, num_theirs);
1241 if (!atom->u.remote_ref.nobracket && *s[0]) {
1242 const char *to_free = *s;
1243 *s = xstrfmt("[%s]", *s);
1244 free((void *)to_free);
1246 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1247 if (stat_tracking_info(branch, &num_ours,
1251 if (!num_ours && !num_theirs)
1255 else if (!num_theirs)
1259 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1261 const char *remote = atom->u.remote_ref.push ?
1262 pushremote_for_branch(branch, &explicit) :
1263 remote_for_branch(branch, &explicit);
1265 *s = xstrdup(remote);
1268 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1272 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1275 *s = xstrdup(merge);
1279 die("BUG: unhandled RR_* enum");
1282 char *get_head_description(void)
1284 struct strbuf desc = STRBUF_INIT;
1285 struct wt_status_state state;
1286 memset(&state, 0, sizeof(state));
1287 wt_status_get_state(&state, 1);
1288 if (state.rebase_in_progress ||
1289 state.rebase_interactive_in_progress)
1290 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1292 else if (state.bisect_in_progress)
1293 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1295 else if (state.detached_from) {
1296 if (state.detached_at)
1298 * TRANSLATORS: make sure this matches "HEAD
1299 * detached at " in wt-status.c
1301 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1302 state.detached_from);
1305 * TRANSLATORS: make sure this matches "HEAD
1306 * detached from " in wt-status.c
1308 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1309 state.detached_from);
1312 strbuf_addstr(&desc, _("(no branch)"));
1315 free(state.detached_from);
1316 return strbuf_detach(&desc, NULL);
1319 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1324 return show_ref(&atom->u.refname, ref->symref);
1327 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1329 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1330 return get_head_description();
1331 return show_ref(&atom->u.refname, ref->refname);
1335 * Parse the object referred by ref, and grab needed value.
1337 static void populate_value(struct ref_array_item *ref)
1343 const struct object_id *tagged;
1345 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1347 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1348 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1354 /* Fill in specials first */
1355 for (i = 0; i < used_atom_cnt; i++) {
1356 struct used_atom *atom = &used_atom[i];
1357 const char *name = used_atom[i].name;
1358 struct atom_value *v = &ref->value[i];
1360 const char *refname;
1361 struct branch *branch = NULL;
1363 v->handler = append_atom;
1371 if (starts_with(name, "refname"))
1372 refname = get_refname(atom, ref);
1373 else if (starts_with(name, "symref"))
1374 refname = get_symref(atom, ref);
1375 else if (starts_with(name, "upstream")) {
1376 const char *branch_name;
1377 /* only local branches may have an upstream */
1378 if (!skip_prefix(ref->refname, "refs/heads/",
1381 branch = branch_get(branch_name);
1383 refname = branch_get_upstream(branch, NULL);
1385 fill_remote_ref_details(atom, refname, branch, &v->s);
1387 } else if (atom->u.remote_ref.push) {
1388 const char *branch_name;
1389 if (!skip_prefix(ref->refname, "refs/heads/",
1392 branch = branch_get(branch_name);
1394 if (atom->u.remote_ref.push_remote)
1397 refname = branch_get_push(branch, NULL);
1401 fill_remote_ref_details(atom, refname, branch, &v->s);
1403 } else if (starts_with(name, "color:")) {
1404 v->s = atom->u.color;
1406 } else if (!strcmp(name, "flag")) {
1407 char buf[256], *cp = buf;
1408 if (ref->flag & REF_ISSYMREF)
1409 cp = copy_advance(cp, ",symref");
1410 if (ref->flag & REF_ISPACKED)
1411 cp = copy_advance(cp, ",packed");
1416 v->s = xstrdup(buf + 1);
1419 } else if (!deref && grab_objectname(name, ref->objectname.hash, v, atom)) {
1421 } else if (!strcmp(name, "HEAD")) {
1422 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1427 } else if (starts_with(name, "align")) {
1428 v->handler = align_atom_handler;
1430 } else if (!strcmp(name, "end")) {
1431 v->handler = end_atom_handler;
1433 } else if (starts_with(name, "if")) {
1436 if (skip_prefix(name, "if:", &s))
1438 v->handler = if_atom_handler;
1440 } else if (!strcmp(name, "then")) {
1441 v->handler = then_atom_handler;
1443 } else if (!strcmp(name, "else")) {
1444 v->handler = else_atom_handler;
1452 v->s = xstrfmt("%s^{}", refname);
1455 for (i = 0; i < used_atom_cnt; i++) {
1456 struct atom_value *v = &ref->value[i];
1463 buf = get_obj(&ref->objectname, &obj, &size, &eaten);
1465 die(_("missing object %s for %s"),
1466 oid_to_hex(&ref->objectname), ref->refname);
1468 die(_("parse_object_buffer failed on %s for %s"),
1469 oid_to_hex(&ref->objectname), ref->refname);
1471 grab_values(ref->value, 0, obj, buf, size);
1476 * If there is no atom that wants to know about tagged
1477 * object, we are done.
1479 if (!need_tagged || (obj->type != OBJ_TAG))
1483 * If it is a tag object, see if we use a value that derefs
1484 * the object, and if we do grab the object it refers to.
1486 tagged = &((struct tag *)obj)->tagged->oid;
1489 * NEEDSWORK: This derefs tag only once, which
1490 * is good to deal with chains of trust, but
1491 * is not consistent with what deref_tag() does
1492 * which peels the onion to the core.
1494 buf = get_obj(tagged, &obj, &size, &eaten);
1496 die(_("missing object %s for %s"),
1497 oid_to_hex(tagged), ref->refname);
1499 die(_("parse_object_buffer failed on %s for %s"),
1500 oid_to_hex(tagged), ref->refname);
1501 grab_values(ref->value, 1, obj, buf, size);
1507 * Given a ref, return the value for the atom. This lazily gets value
1508 * out of the object by calling populate value.
1510 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1513 populate_value(ref);
1514 fill_missing_values(ref->value);
1516 *v = &ref->value[atom];
1520 * Unknown has to be "0" here, because that's the default value for
1521 * contains_cache slab entries that have not yet been assigned.
1523 enum contains_result {
1524 CONTAINS_UNKNOWN = 0,
1529 define_commit_slab(contains_cache, enum contains_result);
1531 struct ref_filter_cbdata {
1532 struct ref_array *array;
1533 struct ref_filter *filter;
1534 struct contains_cache contains_cache;
1535 struct contains_cache no_contains_cache;
1539 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1542 * At each recursion step, the stack items points to the commits whose
1543 * ancestors are to be inspected.
1545 struct contains_stack {
1547 struct contains_stack_entry {
1548 struct commit *commit;
1549 struct commit_list *parents;
1553 static int in_commit_list(const struct commit_list *want, struct commit *c)
1555 for (; want; want = want->next)
1556 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1562 * Test whether the candidate or one of its parents is contained in the list.
1563 * Do not recurse to find out, though, but return -1 if inconclusive.
1565 static enum contains_result contains_test(struct commit *candidate,
1566 const struct commit_list *want,
1567 struct contains_cache *cache)
1569 enum contains_result *cached = contains_cache_at(cache, candidate);
1571 /* If we already have the answer cached, return that. */
1576 if (in_commit_list(want, candidate)) {
1577 *cached = CONTAINS_YES;
1578 return CONTAINS_YES;
1581 /* Otherwise, we don't know; prepare to recurse */
1582 parse_commit_or_die(candidate);
1583 return CONTAINS_UNKNOWN;
1586 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1588 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1589 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1590 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1593 static enum contains_result contains_tag_algo(struct commit *candidate,
1594 const struct commit_list *want,
1595 struct contains_cache *cache)
1597 struct contains_stack contains_stack = { 0, 0, NULL };
1598 enum contains_result result = contains_test(candidate, want, cache);
1600 if (result != CONTAINS_UNKNOWN)
1603 push_to_contains_stack(candidate, &contains_stack);
1604 while (contains_stack.nr) {
1605 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1606 struct commit *commit = entry->commit;
1607 struct commit_list *parents = entry->parents;
1610 *contains_cache_at(cache, commit) = CONTAINS_NO;
1611 contains_stack.nr--;
1614 * If we just popped the stack, parents->item has been marked,
1615 * therefore contains_test will return a meaningful yes/no.
1617 else switch (contains_test(parents->item, want, cache)) {
1619 *contains_cache_at(cache, commit) = CONTAINS_YES;
1620 contains_stack.nr--;
1623 entry->parents = parents->next;
1625 case CONTAINS_UNKNOWN:
1626 push_to_contains_stack(parents->item, &contains_stack);
1630 free(contains_stack.contains_stack);
1631 return contains_test(candidate, want, cache);
1634 static int commit_contains(struct ref_filter *filter, struct commit *commit,
1635 struct commit_list *list, struct contains_cache *cache)
1637 if (filter->with_commit_tag_algo)
1638 return contains_tag_algo(commit, list, cache) == CONTAINS_YES;
1639 return is_descendant_of(commit, list);
1643 * Return 1 if the refname matches one of the patterns, otherwise 0.
1644 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1645 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1646 * matches "refs/heads/mas*", too).
1648 static int match_pattern(const struct ref_filter *filter, const char *refname)
1650 const char **patterns = filter->name_patterns;
1653 if (filter->ignore_case)
1654 flags |= WM_CASEFOLD;
1657 * When no '--format' option is given we need to skip the prefix
1658 * for matching refs of tags and branches.
1660 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1661 skip_prefix(refname, "refs/heads/", &refname) ||
1662 skip_prefix(refname, "refs/remotes/", &refname) ||
1663 skip_prefix(refname, "refs/", &refname));
1665 for (; *patterns; patterns++) {
1666 if (!wildmatch(*patterns, refname, flags))
1673 * Return 1 if the refname matches one of the patterns, otherwise 0.
1674 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1675 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1676 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1678 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1680 const char **pattern = filter->name_patterns;
1681 int namelen = strlen(refname);
1682 unsigned flags = WM_PATHNAME;
1684 if (filter->ignore_case)
1685 flags |= WM_CASEFOLD;
1687 for (; *pattern; pattern++) {
1688 const char *p = *pattern;
1689 int plen = strlen(p);
1691 if ((plen <= namelen) &&
1692 !strncmp(refname, p, plen) &&
1693 (refname[plen] == '\0' ||
1694 refname[plen] == '/' ||
1697 if (!wildmatch(p, refname, WM_PATHNAME))
1703 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1704 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1706 if (!*filter->name_patterns)
1707 return 1; /* No pattern always matches */
1708 if (filter->match_as_path)
1709 return match_name_as_path(filter, refname);
1710 return match_pattern(filter, refname);
1714 * Find the longest prefix of pattern we can pass to
1715 * `for_each_fullref_in()`, namely the part of pattern preceding the
1716 * first glob character. (Note that `for_each_fullref_in()` is
1717 * perfectly happy working with a prefix that doesn't end at a
1718 * pathname component boundary.)
1720 static void find_longest_prefix(struct strbuf *out, const char *pattern)
1724 for (p = pattern; *p && !is_glob_special(*p); p++)
1727 strbuf_add(out, pattern, p - pattern);
1731 * This is the same as for_each_fullref_in(), but it tries to iterate
1732 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1733 * pattern match, so the callback still has to match each ref individually.
1735 static int for_each_fullref_in_pattern(struct ref_filter *filter,
1740 struct strbuf prefix = STRBUF_INIT;
1743 if (!filter->match_as_path) {
1745 * in this case, the patterns are applied after
1746 * prefixes like "refs/heads/" etc. are stripped off,
1747 * so we have to look at everything:
1749 return for_each_fullref_in("", cb, cb_data, broken);
1752 if (!filter->name_patterns[0]) {
1753 /* no patterns; we have to look at everything */
1754 return for_each_fullref_in("", cb, cb_data, broken);
1757 if (filter->name_patterns[1]) {
1759 * multiple patterns; in theory this could still work as long
1760 * as the patterns are disjoint. We'd just make multiple calls
1761 * to for_each_ref(). But if they're not disjoint, we'd end up
1762 * reporting the same ref multiple times. So let's punt on that
1765 return for_each_fullref_in("", cb, cb_data, broken);
1768 find_longest_prefix(&prefix, filter->name_patterns[0]);
1770 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1771 strbuf_release(&prefix);
1776 * Given a ref (sha1, refname), check if the ref belongs to the array
1777 * of sha1s. If the given ref is a tag, check if the given tag points
1778 * at one of the sha1s in the given sha1 array.
1779 * the given sha1_array.
1781 * 1. Only a single level of inderection is obtained, we might want to
1782 * change this to account for multiple levels (e.g. annotated tags
1783 * pointing to annotated tags pointing to a commit.)
1784 * 2. As the refs are cached we might know what refname peels to without
1785 * the need to parse the object via parse_object(). peel_ref() might be a
1786 * more efficient alternative to obtain the pointee.
1788 static const struct object_id *match_points_at(struct oid_array *points_at,
1789 const struct object_id *oid,
1790 const char *refname)
1792 const struct object_id *tagged_oid = NULL;
1795 if (oid_array_lookup(points_at, oid) >= 0)
1797 obj = parse_object(oid);
1799 die(_("malformed object at '%s'"), refname);
1800 if (obj->type == OBJ_TAG)
1801 tagged_oid = &((struct tag *)obj)->tagged->oid;
1802 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1807 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1808 static struct ref_array_item *new_ref_array_item(const char *refname,
1809 const unsigned char *objectname,
1812 struct ref_array_item *ref;
1813 FLEX_ALLOC_STR(ref, refname, refname);
1814 hashcpy(ref->objectname.hash, objectname);
1820 static int ref_kind_from_refname(const char *refname)
1828 { "refs/heads/" , FILTER_REFS_BRANCHES },
1829 { "refs/remotes/" , FILTER_REFS_REMOTES },
1830 { "refs/tags/", FILTER_REFS_TAGS}
1833 if (!strcmp(refname, "HEAD"))
1834 return FILTER_REFS_DETACHED_HEAD;
1836 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1837 if (starts_with(refname, ref_kind[i].prefix))
1838 return ref_kind[i].kind;
1841 return FILTER_REFS_OTHERS;
1844 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1846 if (filter->kind == FILTER_REFS_BRANCHES ||
1847 filter->kind == FILTER_REFS_REMOTES ||
1848 filter->kind == FILTER_REFS_TAGS)
1849 return filter->kind;
1850 return ref_kind_from_refname(refname);
1854 * A call-back given to for_each_ref(). Filter refs and keep them for
1855 * later object processing.
1857 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1859 struct ref_filter_cbdata *ref_cbdata = cb_data;
1860 struct ref_filter *filter = ref_cbdata->filter;
1861 struct ref_array_item *ref;
1862 struct commit *commit = NULL;
1865 if (flag & REF_BAD_NAME) {
1866 warning(_("ignoring ref with broken name %s"), refname);
1870 if (flag & REF_ISBROKEN) {
1871 warning(_("ignoring broken ref %s"), refname);
1875 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1876 kind = filter_ref_kind(filter, refname);
1877 if (!(kind & filter->kind))
1880 if (!filter_pattern_match(filter, refname))
1883 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1887 * A merge filter is applied on refs pointing to commits. Hence
1888 * obtain the commit using the 'oid' available and discard all
1889 * non-commits early. The actual filtering is done later.
1891 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1892 commit = lookup_commit_reference_gently(oid, 1);
1895 /* We perform the filtering for the '--contains' option... */
1896 if (filter->with_commit &&
1897 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1899 /* ...or for the `--no-contains' option */
1900 if (filter->no_commit &&
1901 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1906 * We do not open the object yet; sort may only need refname
1907 * to do its job and the resulting list may yet to be pruned
1908 * by maxcount logic.
1910 ref = new_ref_array_item(refname, oid->hash, flag);
1911 ref->commit = commit;
1913 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1914 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1919 /* Free memory allocated for a ref_array_item */
1920 static void free_array_item(struct ref_array_item *item)
1922 free((char *)item->symref);
1926 /* Free all memory allocated for ref_array */
1927 void ref_array_clear(struct ref_array *array)
1931 for (i = 0; i < array->nr; i++)
1932 free_array_item(array->items[i]);
1933 FREE_AND_NULL(array->items);
1934 array->nr = array->alloc = 0;
1937 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1939 struct rev_info revs;
1941 struct ref_filter *filter = ref_cbdata->filter;
1942 struct ref_array *array = ref_cbdata->array;
1943 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1945 init_revisions(&revs, NULL);
1947 for (i = 0; i < array->nr; i++) {
1948 struct ref_array_item *item = array->items[i];
1949 add_pending_object(&revs, &item->commit->object, item->refname);
1950 to_clear[i] = item->commit;
1953 filter->merge_commit->object.flags |= UNINTERESTING;
1954 add_pending_object(&revs, &filter->merge_commit->object, "");
1957 if (prepare_revision_walk(&revs))
1958 die(_("revision walk setup failed"));
1963 for (i = 0; i < old_nr; i++) {
1964 struct ref_array_item *item = array->items[i];
1965 struct commit *commit = item->commit;
1967 int is_merged = !!(commit->object.flags & UNINTERESTING);
1969 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1970 array->items[array->nr++] = array->items[i];
1972 free_array_item(item);
1975 for (i = 0; i < old_nr; i++)
1976 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1977 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1982 * API for filtering a set of refs. Based on the type of refs the user
1983 * has requested, we iterate through those refs and apply filters
1984 * as per the given ref_filter structure and finally store the
1985 * filtered refs in the ref_array structure.
1987 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1989 struct ref_filter_cbdata ref_cbdata;
1991 unsigned int broken = 0;
1993 ref_cbdata.array = array;
1994 ref_cbdata.filter = filter;
1996 if (type & FILTER_REFS_INCLUDE_BROKEN)
1998 filter->kind = type & FILTER_REFS_KIND_MASK;
2000 init_contains_cache(&ref_cbdata.contains_cache);
2001 init_contains_cache(&ref_cbdata.no_contains_cache);
2003 /* Simple per-ref filtering */
2005 die("filter_refs: invalid type");
2008 * For common cases where we need only branches or remotes or tags,
2009 * we only iterate through those refs. If a mix of refs is needed,
2010 * we iterate over all refs and filter out required refs with the help
2011 * of filter_ref_kind().
2013 if (filter->kind == FILTER_REFS_BRANCHES)
2014 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2015 else if (filter->kind == FILTER_REFS_REMOTES)
2016 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2017 else if (filter->kind == FILTER_REFS_TAGS)
2018 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2019 else if (filter->kind & FILTER_REFS_ALL)
2020 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2021 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2022 head_ref(ref_filter_handler, &ref_cbdata);
2025 clear_contains_cache(&ref_cbdata.contains_cache);
2026 clear_contains_cache(&ref_cbdata.no_contains_cache);
2028 /* Filters that need revision walking */
2029 if (filter->merge_commit)
2030 do_merge_filter(&ref_cbdata);
2035 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2037 struct atom_value *va, *vb;
2039 cmp_type cmp_type = used_atom[s->atom].type;
2040 int (*cmp_fn)(const char *, const char *);
2042 get_ref_atom_value(a, s->atom, &va);
2043 get_ref_atom_value(b, s->atom, &vb);
2044 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2046 cmp = versioncmp(va->s, vb->s);
2047 else if (cmp_type == FIELD_STR)
2048 cmp = cmp_fn(va->s, vb->s);
2050 if (va->value < vb->value)
2052 else if (va->value == vb->value)
2053 cmp = cmp_fn(a->refname, b->refname);
2058 return (s->reverse) ? -cmp : cmp;
2061 static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2063 struct ref_array_item *a = *((struct ref_array_item **)a_);
2064 struct ref_array_item *b = *((struct ref_array_item **)b_);
2065 struct ref_sorting *s;
2067 for (s = ref_sorting; s; s = s->next) {
2068 int cmp = cmp_ref_sorting(s, a, b);
2075 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2077 QSORT_S(array->items, array->nr, compare_refs, sorting);
2080 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2082 struct strbuf *s = &state->stack->output;
2084 while (*cp && (!ep || cp < ep)) {
2089 int ch = hex2chr(cp + 1);
2091 strbuf_addch(s, ch);
2097 strbuf_addch(s, *cp);
2102 void format_ref_array_item(struct ref_array_item *info,
2103 const struct ref_format *format,
2104 struct strbuf *final_buf)
2106 const char *cp, *sp, *ep;
2107 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2109 state.quote_style = format->quote_style;
2110 push_stack_element(&state.stack);
2112 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2113 struct atom_value *atomv;
2115 ep = strchr(sp, ')');
2117 append_literal(cp, sp, &state);
2118 get_ref_atom_value(info,
2119 parse_ref_filter_atom(format, sp + 2, ep),
2121 atomv->handler(atomv, &state);
2124 sp = cp + strlen(cp);
2125 append_literal(cp, sp, &state);
2127 if (format->need_color_reset_at_eol) {
2128 struct atom_value resetv;
2129 resetv.s = GIT_COLOR_RESET;
2130 append_atom(&resetv, &state);
2132 if (state.stack->prev)
2133 die(_("format: %%(end) atom missing"));
2134 strbuf_addbuf(final_buf, &state.stack->output);
2135 pop_stack_element(&state.stack);
2138 void show_ref_array_item(struct ref_array_item *info,
2139 const struct ref_format *format)
2141 struct strbuf final_buf = STRBUF_INIT;
2143 format_ref_array_item(info, format, &final_buf);
2144 fwrite(final_buf.buf, 1, final_buf.len, stdout);
2145 strbuf_release(&final_buf);
2149 void pretty_print_ref(const char *name, const unsigned char *sha1,
2150 const struct ref_format *format)
2152 struct ref_array_item *ref_item;
2153 ref_item = new_ref_array_item(name, sha1, 0);
2154 ref_item->kind = ref_kind_from_refname(name);
2155 show_ref_array_item(ref_item, format);
2156 free_array_item(ref_item);
2159 static int parse_sorting_atom(const char *atom)
2162 * This parses an atom using a dummy ref_format, since we don't
2163 * actually care about the formatting details.
2165 struct ref_format dummy = REF_FORMAT_INIT;
2166 const char *end = atom + strlen(atom);
2167 return parse_ref_filter_atom(&dummy, atom, end);
2170 /* If no sorting option is given, use refname to sort as default */
2171 struct ref_sorting *ref_default_sorting(void)
2173 static const char cstr_name[] = "refname";
2175 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2177 sorting->next = NULL;
2178 sorting->atom = parse_sorting_atom(cstr_name);
2182 void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2184 struct ref_sorting *s;
2186 s = xcalloc(1, sizeof(*s));
2187 s->next = *sorting_tail;
2194 if (skip_prefix(arg, "version:", &arg) ||
2195 skip_prefix(arg, "v:", &arg))
2197 s->atom = parse_sorting_atom(arg);
2200 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2202 if (!arg) /* should --no-sort void the list ? */
2204 parse_ref_sorting(opt->value, arg);
2208 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2210 struct ref_filter *rf = opt->value;
2211 struct object_id oid;
2212 int no_merged = starts_with(opt->long_name, "no");
2216 return opterror(opt, "is incompatible with --merged", 0);
2218 return opterror(opt, "is incompatible with --no-merged", 0);
2222 rf->merge = no_merged
2223 ? REF_FILTER_MERGED_OMIT
2224 : REF_FILTER_MERGED_INCLUDE;
2226 if (get_oid(arg, &oid))
2227 die(_("malformed object name %s"), arg);
2229 rf->merge_commit = lookup_commit_reference_gently(&oid, 0);
2230 if (!rf->merge_commit)
2231 return opterror(opt, "must point to a commit", 0);