3 #include "parse-options.h"
11 #include "ref-filter.h"
14 #include "git-compat-util.h"
17 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
25 * An atom is a valid field atom listed below, possibly prefixed with
26 * a "*" to denote deref_tag().
28 * We parse given format string and sort specifiers, and make a list
29 * of properties that we need to extract out of objects. ref_array_item
30 * structure will hold an array of values extracted that can be
31 * indexed with the "atom number", which is an index into this
34 static struct used_atom {
38 char color[COLOR_MAXLEN];
40 enum { RR_NORMAL, RR_SHORTEN, RR_TRACK, RR_TRACKSHORT }
44 static int used_atom_cnt, need_tagged, need_symref;
45 static int need_color_reset_at_eol;
47 static void color_atom_parser(struct used_atom *atom, const char *color_value)
50 die(_("expected format: %%(color:<color>)"));
51 if (color_parse(color_value, atom->u.color) < 0)
52 die(_("unrecognized color: %%(color:%s)"), color_value);
55 static void remote_ref_atom_parser(struct used_atom *atom, const char *arg)
58 atom->u.remote_ref = RR_NORMAL;
59 else if (!strcmp(arg, "short"))
60 atom->u.remote_ref = RR_SHORTEN;
61 else if (!strcmp(arg, "track"))
62 atom->u.remote_ref = RR_TRACK;
63 else if (!strcmp(arg, "trackshort"))
64 atom->u.remote_ref = RR_TRACKSHORT;
66 die(_("unrecognized format: %%(%s)"), atom->name);
69 static align_type parse_align_position(const char *s)
71 if (!strcmp(s, "right"))
73 else if (!strcmp(s, "middle"))
75 else if (!strcmp(s, "left"))
80 static void align_atom_parser(struct used_atom *atom, const char *arg)
82 struct align *align = &atom->u.align;
83 struct string_list params = STRING_LIST_INIT_DUP;
85 unsigned int width = ~0U;
88 die(_("expected format: %%(align:<width>,<position>)"));
90 align->position = ALIGN_LEFT;
92 string_list_split(¶ms, arg, ',', -1);
93 for (i = 0; i < params.nr; i++) {
94 const char *s = params.items[i].string;
97 if (skip_prefix(s, "position=", &s)) {
98 position = parse_align_position(s);
100 die(_("unrecognized position:%s"), s);
101 align->position = position;
102 } else if (skip_prefix(s, "width=", &s)) {
103 if (strtoul_ui(s, 10, &width))
104 die(_("unrecognized width:%s"), s);
105 } else if (!strtoul_ui(s, 10, &width))
107 else if ((position = parse_align_position(s)) >= 0)
108 align->position = position;
110 die(_("unrecognized %%(align) argument: %s"), s);
114 die(_("positive width expected with the %%(align) atom"));
115 align->width = width;
116 string_list_clear(¶ms, 0);
122 void (*parser)(struct used_atom *atom, const char *arg);
126 { "objectsize", FIELD_ULONG },
130 { "numparent", FIELD_ULONG },
137 { "authordate", FIELD_TIME },
140 { "committeremail" },
141 { "committerdate", FIELD_TIME },
145 { "taggerdate", FIELD_TIME },
147 { "creatordate", FIELD_TIME },
151 { "upstream", FIELD_STR, remote_ref_atom_parser },
152 { "push", FIELD_STR, remote_ref_atom_parser },
156 { "color", FIELD_STR, color_atom_parser },
157 { "align", FIELD_STR, align_atom_parser },
161 #define REF_FORMATTING_STATE_INIT { 0, NULL }
165 struct object_id oid;
168 struct ref_formatting_stack {
169 struct ref_formatting_stack *prev;
170 struct strbuf output;
171 void (*at_end)(struct ref_formatting_stack *stack);
175 struct ref_formatting_state {
177 struct ref_formatting_stack *stack;
184 struct contents contents;
186 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
187 unsigned long ul; /* used for sorting when not FIELD_STR */
191 * Used to parse format string and sort specifiers
193 int parse_ref_filter_atom(const char *atom, const char *ep)
200 if (*sp == '*' && sp < ep)
203 die("malformed field name: %.*s", (int)(ep-atom), atom);
205 /* Do we have the atom already used elsewhere? */
206 for (i = 0; i < used_atom_cnt; i++) {
207 int len = strlen(used_atom[i].name);
208 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
212 /* Is the atom a valid one? */
213 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
214 int len = strlen(valid_atom[i].name);
217 * If the atom name has a colon, strip it and everything after
218 * it off - it specifies the format for this entry, and
219 * shouldn't be used for checking against the valid_atom
222 arg = memchr(sp, ':', ep - sp);
223 if (len == (arg ? arg : ep) - sp &&
224 !memcmp(valid_atom[i].name, sp, len))
228 if (ARRAY_SIZE(valid_atom) <= i)
229 die("unknown field name: %.*s", (int)(ep-atom), atom);
231 /* Add it in, including the deref prefix */
234 REALLOC_ARRAY(used_atom, used_atom_cnt);
235 used_atom[at].name = xmemdupz(atom, ep - atom);
236 used_atom[at].type = valid_atom[i].cmp_type;
238 arg = used_atom[at].name + (arg - atom) + 1;
239 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
240 if (valid_atom[i].parser)
241 valid_atom[i].parser(&used_atom[at], arg);
244 if (!strcmp(used_atom[at].name, "symref"))
249 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
251 switch (quote_style) {
253 strbuf_addstr(s, str);
256 sq_quote_buf(s, str);
259 perl_quote_buf(s, str);
262 python_quote_buf(s, str);
265 tcl_quote_buf(s, str);
270 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
273 * Quote formatting is only done when the stack has a single
274 * element. Otherwise quote formatting is done on the
275 * element's entire output strbuf when the %(end) atom is
278 if (!state->stack->prev)
279 quote_formatting(&state->stack->output, v->s, state->quote_style);
281 strbuf_addstr(&state->stack->output, v->s);
284 static void push_stack_element(struct ref_formatting_stack **stack)
286 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
288 strbuf_init(&s->output, 0);
293 static void pop_stack_element(struct ref_formatting_stack **stack)
295 struct ref_formatting_stack *current = *stack;
296 struct ref_formatting_stack *prev = current->prev;
299 strbuf_addbuf(&prev->output, ¤t->output);
300 strbuf_release(¤t->output);
305 static void end_align_handler(struct ref_formatting_stack *stack)
307 struct align *align = (struct align *)stack->at_end_data;
308 struct strbuf s = STRBUF_INIT;
310 strbuf_utf8_align(&s, align->position, align->width, stack->output.buf);
311 strbuf_swap(&stack->output, &s);
315 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
317 struct ref_formatting_stack *new;
319 push_stack_element(&state->stack);
321 new->at_end = end_align_handler;
322 new->at_end_data = &atomv->u.align;
325 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
327 struct ref_formatting_stack *current = state->stack;
328 struct strbuf s = STRBUF_INIT;
330 if (!current->at_end)
331 die(_("format: %%(end) atom used without corresponding atom"));
332 current->at_end(current);
335 * Perform quote formatting when the stack element is that of
336 * a supporting atom. If nested then perform quote formatting
337 * only on the topmost supporting atom.
339 if (!state->stack->prev->prev) {
340 quote_formatting(&s, current->output.buf, state->quote_style);
341 strbuf_swap(¤t->output, &s);
344 pop_stack_element(&state->stack);
348 * In a format string, find the next occurrence of %(atom).
350 static const char *find_next(const char *cp)
355 * %( is the start of an atom;
356 * %% is a quoted per-cent.
360 else if (cp[1] == '%')
361 cp++; /* skip over two % */
362 /* otherwise this is a singleton, literal % */
370 * Make sure the format string is well formed, and parse out
373 int verify_ref_format(const char *format)
377 need_color_reset_at_eol = 0;
378 for (cp = format; *cp && (sp = find_next(cp)); ) {
379 const char *color, *ep = strchr(sp, ')');
383 return error("malformed format string %s", sp);
384 /* sp points at "%(" and ep points at the closing ")" */
385 at = parse_ref_filter_atom(sp + 2, ep);
388 if (skip_prefix(used_atom[at].name, "color:", &color))
389 need_color_reset_at_eol = !!strcmp(color, "reset");
395 * Given an object name, read the object data and size, and return a
396 * "struct object". If the object data we are returning is also borrowed
397 * by the "struct object" representation, set *eaten as well---it is a
398 * signal from parse_object_buffer to us not to free the buffer.
400 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
402 enum object_type type;
403 void *buf = read_sha1_file(sha1, &type, sz);
406 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
412 static int grab_objectname(const char *name, const unsigned char *sha1,
413 struct atom_value *v)
415 if (!strcmp(name, "objectname")) {
416 v->s = xstrdup(sha1_to_hex(sha1));
419 if (!strcmp(name, "objectname:short")) {
420 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
426 /* See grab_values */
427 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
431 for (i = 0; i < used_atom_cnt; i++) {
432 const char *name = used_atom[i].name;
433 struct atom_value *v = &val[i];
434 if (!!deref != (*name == '*'))
438 if (!strcmp(name, "objecttype"))
439 v->s = typename(obj->type);
440 else if (!strcmp(name, "objectsize")) {
442 v->s = xstrfmt("%lu", sz);
445 grab_objectname(name, obj->oid.hash, v);
449 /* See grab_values */
450 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
453 struct tag *tag = (struct tag *) obj;
455 for (i = 0; i < used_atom_cnt; i++) {
456 const char *name = used_atom[i].name;
457 struct atom_value *v = &val[i];
458 if (!!deref != (*name == '*'))
462 if (!strcmp(name, "tag"))
464 else if (!strcmp(name, "type") && tag->tagged)
465 v->s = typename(tag->tagged->type);
466 else if (!strcmp(name, "object") && tag->tagged)
467 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
471 /* See grab_values */
472 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
475 struct commit *commit = (struct commit *) obj;
477 for (i = 0; i < used_atom_cnt; i++) {
478 const char *name = used_atom[i].name;
479 struct atom_value *v = &val[i];
480 if (!!deref != (*name == '*'))
484 if (!strcmp(name, "tree")) {
485 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
487 else if (!strcmp(name, "numparent")) {
488 v->ul = commit_list_count(commit->parents);
489 v->s = xstrfmt("%lu", v->ul);
491 else if (!strcmp(name, "parent")) {
492 struct commit_list *parents;
493 struct strbuf s = STRBUF_INIT;
494 for (parents = commit->parents; parents; parents = parents->next) {
495 struct commit *parent = parents->item;
496 if (parents != commit->parents)
497 strbuf_addch(&s, ' ');
498 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
500 v->s = strbuf_detach(&s, NULL);
505 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
509 if (!strncmp(buf, who, wholen) &&
511 return buf + wholen + 1;
512 eol = strchr(buf, '\n');
517 return ""; /* end of header */
523 static const char *copy_line(const char *buf)
525 const char *eol = strchrnul(buf, '\n');
526 return xmemdupz(buf, eol - buf);
529 static const char *copy_name(const char *buf)
532 for (cp = buf; *cp && *cp != '\n'; cp++) {
533 if (!strncmp(cp, " <", 2))
534 return xmemdupz(buf, cp - buf);
539 static const char *copy_email(const char *buf)
541 const char *email = strchr(buf, '<');
545 eoemail = strchr(email, '>');
548 return xmemdupz(email, eoemail + 1 - email);
551 static char *copy_subject(const char *buf, unsigned long len)
553 char *r = xmemdupz(buf, len);
556 for (i = 0; i < len; i++)
563 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
565 const char *eoemail = strstr(buf, "> ");
567 unsigned long timestamp;
569 struct date_mode date_mode = { DATE_NORMAL };
573 * We got here because atomname ends in "date" or "date<something>";
574 * it's not possible that <something> is not ":<format>" because
575 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
576 * ":" means no format is specified, and use the default.
578 formatp = strchr(atomname, ':');
579 if (formatp != NULL) {
581 parse_date_format(formatp, &date_mode);
586 timestamp = strtoul(eoemail + 2, &zone, 10);
587 if (timestamp == ULONG_MAX)
589 tz = strtol(zone, NULL, 10);
590 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
592 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
600 /* See grab_values */
601 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
604 int wholen = strlen(who);
605 const char *wholine = NULL;
607 for (i = 0; i < used_atom_cnt; i++) {
608 const char *name = used_atom[i].name;
609 struct atom_value *v = &val[i];
610 if (!!deref != (*name == '*'))
614 if (strncmp(who, name, wholen))
616 if (name[wholen] != 0 &&
617 strcmp(name + wholen, "name") &&
618 strcmp(name + wholen, "email") &&
619 !starts_with(name + wholen, "date"))
622 wholine = find_wholine(who, wholen, buf, sz);
624 return; /* no point looking for it */
625 if (name[wholen] == 0)
626 v->s = copy_line(wholine);
627 else if (!strcmp(name + wholen, "name"))
628 v->s = copy_name(wholine);
629 else if (!strcmp(name + wholen, "email"))
630 v->s = copy_email(wholine);
631 else if (starts_with(name + wholen, "date"))
632 grab_date(wholine, v, name);
636 * For a tag or a commit object, if "creator" or "creatordate" is
637 * requested, do something special.
639 if (strcmp(who, "tagger") && strcmp(who, "committer"))
640 return; /* "author" for commit object is not wanted */
642 wholine = find_wholine(who, wholen, buf, sz);
645 for (i = 0; i < used_atom_cnt; i++) {
646 const char *name = used_atom[i].name;
647 struct atom_value *v = &val[i];
648 if (!!deref != (*name == '*'))
653 if (starts_with(name, "creatordate"))
654 grab_date(wholine, v, name);
655 else if (!strcmp(name, "creator"))
656 v->s = copy_line(wholine);
660 static void find_subpos(const char *buf, unsigned long sz,
661 const char **sub, unsigned long *sublen,
662 const char **body, unsigned long *bodylen,
663 unsigned long *nonsiglen,
664 const char **sig, unsigned long *siglen)
667 /* skip past header until we hit empty line */
668 while (*buf && *buf != '\n') {
669 eol = strchrnul(buf, '\n');
674 /* skip any empty lines */
678 /* parse signature first; we might not even have a subject line */
679 *sig = buf + parse_signature(buf, strlen(buf));
680 *siglen = strlen(*sig);
682 /* subject is first non-empty line */
684 /* subject goes to first empty line */
685 while (buf < *sig && *buf && *buf != '\n') {
686 eol = strchrnul(buf, '\n');
691 *sublen = buf - *sub;
692 /* drop trailing newline, if present */
693 if (*sublen && (*sub)[*sublen - 1] == '\n')
696 /* skip any empty lines */
700 *bodylen = strlen(buf);
701 *nonsiglen = *sig - buf;
705 * If 'lines' is greater than 0, append that many lines from the given
706 * 'buf' of length 'size' to the given strbuf.
708 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
711 const char *sp, *eol;
716 for (i = 0; i < lines && sp < buf + size; i++) {
718 strbuf_addstr(out, "\n ");
719 eol = memchr(sp, '\n', size - (sp - buf));
720 len = eol ? eol - sp : size - (sp - buf);
721 strbuf_add(out, sp, len);
728 /* See grab_values */
729 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
732 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
733 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
735 for (i = 0; i < used_atom_cnt; i++) {
736 const char *name = used_atom[i].name;
737 struct atom_value *v = &val[i];
738 const char *valp = NULL;
739 if (!!deref != (*name == '*'))
743 if (strcmp(name, "subject") &&
744 strcmp(name, "body") &&
745 strcmp(name, "contents") &&
746 strcmp(name, "contents:subject") &&
747 strcmp(name, "contents:body") &&
748 strcmp(name, "contents:signature") &&
749 !starts_with(name, "contents:lines="))
754 &bodypos, &bodylen, &nonsiglen,
757 if (!strcmp(name, "subject"))
758 v->s = copy_subject(subpos, sublen);
759 else if (!strcmp(name, "contents:subject"))
760 v->s = copy_subject(subpos, sublen);
761 else if (!strcmp(name, "body"))
762 v->s = xmemdupz(bodypos, bodylen);
763 else if (!strcmp(name, "contents:body"))
764 v->s = xmemdupz(bodypos, nonsiglen);
765 else if (!strcmp(name, "contents:signature"))
766 v->s = xmemdupz(sigpos, siglen);
767 else if (!strcmp(name, "contents"))
768 v->s = xstrdup(subpos);
769 else if (skip_prefix(name, "contents:lines=", &valp)) {
770 struct strbuf s = STRBUF_INIT;
771 const char *contents_end = bodylen + bodypos - siglen;
773 if (strtoul_ui(valp, 10, &v->u.contents.lines))
774 die(_("positive value expected contents:lines=%s"), valp);
775 /* Size is the length of the message after removing the signature */
776 append_lines(&s, subpos, contents_end - subpos, v->u.contents.lines);
777 v->s = strbuf_detach(&s, NULL);
783 * We want to have empty print-string for field requests
784 * that do not apply (e.g. "authordate" for a tag object)
786 static void fill_missing_values(struct atom_value *val)
789 for (i = 0; i < used_atom_cnt; i++) {
790 struct atom_value *v = &val[i];
797 * val is a list of atom_value to hold returned values. Extract
798 * the values for atoms in used_atom array out of (obj, buf, sz).
799 * when deref is false, (obj, buf, sz) is the object that is
800 * pointed at by the ref itself; otherwise it is the object the
801 * ref (which is a tag) refers to.
803 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
805 grab_common_values(val, deref, obj, buf, sz);
808 grab_tag_values(val, deref, obj, buf, sz);
809 grab_sub_body_contents(val, deref, obj, buf, sz);
810 grab_person("tagger", val, deref, obj, buf, sz);
813 grab_commit_values(val, deref, obj, buf, sz);
814 grab_sub_body_contents(val, deref, obj, buf, sz);
815 grab_person("author", val, deref, obj, buf, sz);
816 grab_person("committer", val, deref, obj, buf, sz);
819 /* grab_tree_values(val, deref, obj, buf, sz); */
822 /* grab_blob_values(val, deref, obj, buf, sz); */
825 die("Eh? Object of type %d?", obj->type);
829 static inline char *copy_advance(char *dst, const char *src)
836 static const char *strip_ref_components(const char *refname, const char *nr_arg)
839 long nr = strtol(nr_arg, &end, 10);
841 const char *start = refname;
843 if (nr < 1 || *end != '\0')
844 die(":strip= requires a positive integer argument");
849 die("ref '%s' does not have %ld components to :strip",
859 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
860 struct branch *branch, const char **s)
862 int num_ours, num_theirs;
863 if (atom->u.remote_ref == RR_SHORTEN)
864 *s = shorten_unambiguous_ref(refname, warn_ambiguous_refs);
865 else if (atom->u.remote_ref == RR_TRACK) {
866 if (stat_tracking_info(branch, &num_ours,
870 if (!num_ours && !num_theirs)
873 *s = xstrfmt("[behind %d]", num_theirs);
874 else if (!num_theirs)
875 *s = xstrfmt("[ahead %d]", num_ours);
877 *s = xstrfmt("[ahead %d, behind %d]",
878 num_ours, num_theirs);
879 } else if (atom->u.remote_ref == RR_TRACKSHORT) {
880 if (stat_tracking_info(branch, &num_ours,
884 if (!num_ours && !num_theirs)
888 else if (!num_theirs)
892 } else /* RR_NORMAL */
897 * Parse the object referred by ref, and grab needed value.
899 static void populate_value(struct ref_array_item *ref)
905 const unsigned char *tagged;
907 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
909 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
910 unsigned char unused1[20];
911 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
917 /* Fill in specials first */
918 for (i = 0; i < used_atom_cnt; i++) {
919 struct used_atom *atom = &used_atom[i];
920 const char *name = used_atom[i].name;
921 struct atom_value *v = &ref->value[i];
925 struct branch *branch = NULL;
927 v->handler = append_atom;
934 if (starts_with(name, "refname"))
935 refname = ref->refname;
936 else if (starts_with(name, "symref"))
937 refname = ref->symref ? ref->symref : "";
938 else if (starts_with(name, "upstream")) {
939 const char *branch_name;
940 /* only local branches may have an upstream */
941 if (!skip_prefix(ref->refname, "refs/heads/",
944 branch = branch_get(branch_name);
946 refname = branch_get_upstream(branch, NULL);
948 fill_remote_ref_details(atom, refname, branch, &v->s);
950 } else if (starts_with(name, "push")) {
951 const char *branch_name;
952 if (!skip_prefix(ref->refname, "refs/heads/",
955 branch = branch_get(branch_name);
957 refname = branch_get_push(branch, NULL);
960 fill_remote_ref_details(atom, refname, branch, &v->s);
962 } else if (starts_with(name, "color:")) {
963 v->s = atom->u.color;
965 } else if (!strcmp(name, "flag")) {
966 char buf[256], *cp = buf;
967 if (ref->flag & REF_ISSYMREF)
968 cp = copy_advance(cp, ",symref");
969 if (ref->flag & REF_ISPACKED)
970 cp = copy_advance(cp, ",packed");
975 v->s = xstrdup(buf + 1);
978 } else if (!deref && grab_objectname(name, ref->objectname, v)) {
980 } else if (!strcmp(name, "HEAD")) {
982 unsigned char sha1[20];
984 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
986 if (!strcmp(ref->refname, head))
991 } else if (starts_with(name, "align")) {
992 v->u.align = atom->u.align;
993 v->handler = align_atom_handler;
995 } else if (!strcmp(name, "end")) {
996 v->handler = end_atom_handler;
1001 formatp = strchr(name, ':');
1006 if (!strcmp(formatp, "short"))
1007 refname = shorten_unambiguous_ref(refname,
1008 warn_ambiguous_refs);
1009 else if (skip_prefix(formatp, "strip=", &arg))
1010 refname = strip_ref_components(refname, arg);
1012 die("unknown %.*s format %s",
1013 (int)(formatp - name), name, formatp);
1019 v->s = xstrfmt("%s^{}", refname);
1022 for (i = 0; i < used_atom_cnt; i++) {
1023 struct atom_value *v = &ref->value[i];
1030 buf = get_obj(ref->objectname, &obj, &size, &eaten);
1032 die("missing object %s for %s",
1033 sha1_to_hex(ref->objectname), ref->refname);
1035 die("parse_object_buffer failed on %s for %s",
1036 sha1_to_hex(ref->objectname), ref->refname);
1038 grab_values(ref->value, 0, obj, buf, size);
1043 * If there is no atom that wants to know about tagged
1044 * object, we are done.
1046 if (!need_tagged || (obj->type != OBJ_TAG))
1050 * If it is a tag object, see if we use a value that derefs
1051 * the object, and if we do grab the object it refers to.
1053 tagged = ((struct tag *)obj)->tagged->oid.hash;
1056 * NEEDSWORK: This derefs tag only once, which
1057 * is good to deal with chains of trust, but
1058 * is not consistent with what deref_tag() does
1059 * which peels the onion to the core.
1061 buf = get_obj(tagged, &obj, &size, &eaten);
1063 die("missing object %s for %s",
1064 sha1_to_hex(tagged), ref->refname);
1066 die("parse_object_buffer failed on %s for %s",
1067 sha1_to_hex(tagged), ref->refname);
1068 grab_values(ref->value, 1, obj, buf, size);
1074 * Given a ref, return the value for the atom. This lazily gets value
1075 * out of the object by calling populate value.
1077 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1080 populate_value(ref);
1081 fill_missing_values(ref->value);
1083 *v = &ref->value[atom];
1086 enum contains_result {
1087 CONTAINS_UNKNOWN = -1,
1093 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1096 * At each recursion step, the stack items points to the commits whose
1097 * ancestors are to be inspected.
1099 struct contains_stack {
1101 struct contains_stack_entry {
1102 struct commit *commit;
1103 struct commit_list *parents;
1107 static int in_commit_list(const struct commit_list *want, struct commit *c)
1109 for (; want; want = want->next)
1110 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1116 * Test whether the candidate or one of its parents is contained in the list.
1117 * Do not recurse to find out, though, but return -1 if inconclusive.
1119 static enum contains_result contains_test(struct commit *candidate,
1120 const struct commit_list *want)
1122 /* was it previously marked as containing a want commit? */
1123 if (candidate->object.flags & TMP_MARK)
1125 /* or marked as not possibly containing a want commit? */
1126 if (candidate->object.flags & UNINTERESTING)
1129 if (in_commit_list(want, candidate)) {
1130 candidate->object.flags |= TMP_MARK;
1134 if (parse_commit(candidate) < 0)
1140 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1142 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1143 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1144 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1147 static enum contains_result contains_tag_algo(struct commit *candidate,
1148 const struct commit_list *want)
1150 struct contains_stack contains_stack = { 0, 0, NULL };
1151 int result = contains_test(candidate, want);
1153 if (result != CONTAINS_UNKNOWN)
1156 push_to_contains_stack(candidate, &contains_stack);
1157 while (contains_stack.nr) {
1158 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1159 struct commit *commit = entry->commit;
1160 struct commit_list *parents = entry->parents;
1163 commit->object.flags |= UNINTERESTING;
1164 contains_stack.nr--;
1167 * If we just popped the stack, parents->item has been marked,
1168 * therefore contains_test will return a meaningful 0 or 1.
1170 else switch (contains_test(parents->item, want)) {
1172 commit->object.flags |= TMP_MARK;
1173 contains_stack.nr--;
1176 entry->parents = parents->next;
1178 case CONTAINS_UNKNOWN:
1179 push_to_contains_stack(parents->item, &contains_stack);
1183 free(contains_stack.contains_stack);
1184 return contains_test(candidate, want);
1187 static int commit_contains(struct ref_filter *filter, struct commit *commit)
1189 if (filter->with_commit_tag_algo)
1190 return contains_tag_algo(commit, filter->with_commit);
1191 return is_descendant_of(commit, filter->with_commit);
1195 * Return 1 if the refname matches one of the patterns, otherwise 0.
1196 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1197 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1198 * matches "refs/heads/mas*", too).
1200 static int match_pattern(const char **patterns, const char *refname)
1203 * When no '--format' option is given we need to skip the prefix
1204 * for matching refs of tags and branches.
1206 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1207 skip_prefix(refname, "refs/heads/", &refname) ||
1208 skip_prefix(refname, "refs/remotes/", &refname) ||
1209 skip_prefix(refname, "refs/", &refname));
1211 for (; *patterns; patterns++) {
1212 if (!wildmatch(*patterns, refname, 0, NULL))
1219 * Return 1 if the refname matches one of the patterns, otherwise 0.
1220 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1221 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1222 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1224 static int match_name_as_path(const char **pattern, const char *refname)
1226 int namelen = strlen(refname);
1227 for (; *pattern; pattern++) {
1228 const char *p = *pattern;
1229 int plen = strlen(p);
1231 if ((plen <= namelen) &&
1232 !strncmp(refname, p, plen) &&
1233 (refname[plen] == '\0' ||
1234 refname[plen] == '/' ||
1237 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1243 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1244 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1246 if (!*filter->name_patterns)
1247 return 1; /* No pattern always matches */
1248 if (filter->match_as_path)
1249 return match_name_as_path(filter->name_patterns, refname);
1250 return match_pattern(filter->name_patterns, refname);
1254 * Given a ref (sha1, refname), check if the ref belongs to the array
1255 * of sha1s. If the given ref is a tag, check if the given tag points
1256 * at one of the sha1s in the given sha1 array.
1257 * the given sha1_array.
1259 * 1. Only a single level of inderection is obtained, we might want to
1260 * change this to account for multiple levels (e.g. annotated tags
1261 * pointing to annotated tags pointing to a commit.)
1262 * 2. As the refs are cached we might know what refname peels to without
1263 * the need to parse the object via parse_object(). peel_ref() might be a
1264 * more efficient alternative to obtain the pointee.
1266 static const unsigned char *match_points_at(struct sha1_array *points_at,
1267 const unsigned char *sha1,
1268 const char *refname)
1270 const unsigned char *tagged_sha1 = NULL;
1273 if (sha1_array_lookup(points_at, sha1) >= 0)
1275 obj = parse_object(sha1);
1277 die(_("malformed object at '%s'"), refname);
1278 if (obj->type == OBJ_TAG)
1279 tagged_sha1 = ((struct tag *)obj)->tagged->oid.hash;
1280 if (tagged_sha1 && sha1_array_lookup(points_at, tagged_sha1) >= 0)
1285 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1286 static struct ref_array_item *new_ref_array_item(const char *refname,
1287 const unsigned char *objectname,
1290 size_t len = strlen(refname);
1291 struct ref_array_item *ref = xcalloc(1, sizeof(struct ref_array_item) + len + 1);
1292 memcpy(ref->refname, refname, len);
1293 ref->refname[len] = '\0';
1294 hashcpy(ref->objectname, objectname);
1300 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1308 { "refs/heads/" , FILTER_REFS_BRANCHES },
1309 { "refs/remotes/" , FILTER_REFS_REMOTES },
1310 { "refs/tags/", FILTER_REFS_TAGS}
1313 if (filter->kind == FILTER_REFS_BRANCHES ||
1314 filter->kind == FILTER_REFS_REMOTES ||
1315 filter->kind == FILTER_REFS_TAGS)
1316 return filter->kind;
1317 else if (!strcmp(refname, "HEAD"))
1318 return FILTER_REFS_DETACHED_HEAD;
1320 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1321 if (starts_with(refname, ref_kind[i].prefix))
1322 return ref_kind[i].kind;
1325 return FILTER_REFS_OTHERS;
1329 * A call-back given to for_each_ref(). Filter refs and keep them for
1330 * later object processing.
1332 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1334 struct ref_filter_cbdata *ref_cbdata = cb_data;
1335 struct ref_filter *filter = ref_cbdata->filter;
1336 struct ref_array_item *ref;
1337 struct commit *commit = NULL;
1340 if (flag & REF_BAD_NAME) {
1341 warning("ignoring ref with broken name %s", refname);
1345 if (flag & REF_ISBROKEN) {
1346 warning("ignoring broken ref %s", refname);
1350 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1351 kind = filter_ref_kind(filter, refname);
1352 if (!(kind & filter->kind))
1355 if (!filter_pattern_match(filter, refname))
1358 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1362 * A merge filter is applied on refs pointing to commits. Hence
1363 * obtain the commit using the 'oid' available and discard all
1364 * non-commits early. The actual filtering is done later.
1366 if (filter->merge_commit || filter->with_commit || filter->verbose) {
1367 commit = lookup_commit_reference_gently(oid->hash, 1);
1370 /* We perform the filtering for the '--contains' option */
1371 if (filter->with_commit &&
1372 !commit_contains(filter, commit))
1377 * We do not open the object yet; sort may only need refname
1378 * to do its job and the resulting list may yet to be pruned
1379 * by maxcount logic.
1381 ref = new_ref_array_item(refname, oid->hash, flag);
1382 ref->commit = commit;
1384 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1385 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1390 /* Free memory allocated for a ref_array_item */
1391 static void free_array_item(struct ref_array_item *item)
1393 free((char *)item->symref);
1397 /* Free all memory allocated for ref_array */
1398 void ref_array_clear(struct ref_array *array)
1402 for (i = 0; i < array->nr; i++)
1403 free_array_item(array->items[i]);
1405 array->items = NULL;
1406 array->nr = array->alloc = 0;
1409 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1411 struct rev_info revs;
1413 struct ref_filter *filter = ref_cbdata->filter;
1414 struct ref_array *array = ref_cbdata->array;
1415 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1417 init_revisions(&revs, NULL);
1419 for (i = 0; i < array->nr; i++) {
1420 struct ref_array_item *item = array->items[i];
1421 add_pending_object(&revs, &item->commit->object, item->refname);
1422 to_clear[i] = item->commit;
1425 filter->merge_commit->object.flags |= UNINTERESTING;
1426 add_pending_object(&revs, &filter->merge_commit->object, "");
1429 if (prepare_revision_walk(&revs))
1430 die(_("revision walk setup failed"));
1435 for (i = 0; i < old_nr; i++) {
1436 struct ref_array_item *item = array->items[i];
1437 struct commit *commit = item->commit;
1439 int is_merged = !!(commit->object.flags & UNINTERESTING);
1441 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1442 array->items[array->nr++] = array->items[i];
1444 free_array_item(item);
1447 for (i = 0; i < old_nr; i++)
1448 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1449 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1454 * API for filtering a set of refs. Based on the type of refs the user
1455 * has requested, we iterate through those refs and apply filters
1456 * as per the given ref_filter structure and finally store the
1457 * filtered refs in the ref_array structure.
1459 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1461 struct ref_filter_cbdata ref_cbdata;
1463 unsigned int broken = 0;
1465 ref_cbdata.array = array;
1466 ref_cbdata.filter = filter;
1468 if (type & FILTER_REFS_INCLUDE_BROKEN)
1470 filter->kind = type & FILTER_REFS_KIND_MASK;
1472 /* Simple per-ref filtering */
1474 die("filter_refs: invalid type");
1477 * For common cases where we need only branches or remotes or tags,
1478 * we only iterate through those refs. If a mix of refs is needed,
1479 * we iterate over all refs and filter out required refs with the help
1480 * of filter_ref_kind().
1482 if (filter->kind == FILTER_REFS_BRANCHES)
1483 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1484 else if (filter->kind == FILTER_REFS_REMOTES)
1485 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1486 else if (filter->kind == FILTER_REFS_TAGS)
1487 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1488 else if (filter->kind & FILTER_REFS_ALL)
1489 ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1490 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1491 head_ref(ref_filter_handler, &ref_cbdata);
1495 /* Filters that need revision walking */
1496 if (filter->merge_commit)
1497 do_merge_filter(&ref_cbdata);
1502 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1504 struct atom_value *va, *vb;
1506 cmp_type cmp_type = used_atom[s->atom].type;
1508 get_ref_atom_value(a, s->atom, &va);
1509 get_ref_atom_value(b, s->atom, &vb);
1511 cmp = versioncmp(va->s, vb->s);
1512 else if (cmp_type == FIELD_STR)
1513 cmp = strcmp(va->s, vb->s);
1515 if (va->ul < vb->ul)
1517 else if (va->ul == vb->ul)
1518 cmp = strcmp(a->refname, b->refname);
1523 return (s->reverse) ? -cmp : cmp;
1526 static struct ref_sorting *ref_sorting;
1527 static int compare_refs(const void *a_, const void *b_)
1529 struct ref_array_item *a = *((struct ref_array_item **)a_);
1530 struct ref_array_item *b = *((struct ref_array_item **)b_);
1531 struct ref_sorting *s;
1533 for (s = ref_sorting; s; s = s->next) {
1534 int cmp = cmp_ref_sorting(s, a, b);
1541 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1543 ref_sorting = sorting;
1544 qsort(array->items, array->nr, sizeof(struct ref_array_item *), compare_refs);
1547 static int hex1(char ch)
1549 if ('0' <= ch && ch <= '9')
1551 else if ('a' <= ch && ch <= 'f')
1552 return ch - 'a' + 10;
1553 else if ('A' <= ch && ch <= 'F')
1554 return ch - 'A' + 10;
1557 static int hex2(const char *cp)
1560 return (hex1(cp[0]) << 4) | hex1(cp[1]);
1565 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1567 struct strbuf *s = &state->stack->output;
1569 while (*cp && (!ep || cp < ep)) {
1574 int ch = hex2(cp + 1);
1576 strbuf_addch(s, ch);
1582 strbuf_addch(s, *cp);
1587 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
1589 const char *cp, *sp, *ep;
1590 struct strbuf *final_buf;
1591 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1593 state.quote_style = quote_style;
1594 push_stack_element(&state.stack);
1596 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1597 struct atom_value *atomv;
1599 ep = strchr(sp, ')');
1601 append_literal(cp, sp, &state);
1602 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1603 atomv->handler(atomv, &state);
1606 sp = cp + strlen(cp);
1607 append_literal(cp, sp, &state);
1609 if (need_color_reset_at_eol) {
1610 struct atom_value resetv;
1611 char color[COLOR_MAXLEN] = "";
1613 if (color_parse("reset", color) < 0)
1614 die("BUG: couldn't parse 'reset' as a color");
1616 append_atom(&resetv, &state);
1618 if (state.stack->prev)
1619 die(_("format: %%(end) atom missing"));
1620 final_buf = &state.stack->output;
1621 fwrite(final_buf->buf, 1, final_buf->len, stdout);
1622 pop_stack_element(&state.stack);
1626 /* If no sorting option is given, use refname to sort as default */
1627 struct ref_sorting *ref_default_sorting(void)
1629 static const char cstr_name[] = "refname";
1631 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
1633 sorting->next = NULL;
1634 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
1638 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
1640 struct ref_sorting **sorting_tail = opt->value;
1641 struct ref_sorting *s;
1644 if (!arg) /* should --no-sort void the list ? */
1647 s = xcalloc(1, sizeof(*s));
1648 s->next = *sorting_tail;
1655 if (skip_prefix(arg, "version:", &arg) ||
1656 skip_prefix(arg, "v:", &arg))
1659 s->atom = parse_ref_filter_atom(arg, arg+len);
1663 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
1665 struct ref_filter *rf = opt->value;
1666 unsigned char sha1[20];
1668 rf->merge = starts_with(opt->long_name, "no")
1669 ? REF_FILTER_MERGED_OMIT
1670 : REF_FILTER_MERGED_INCLUDE;
1672 if (get_sha1(arg, sha1))
1673 die(_("malformed object name %s"), arg);
1675 rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
1676 if (!rf->merge_commit)
1677 return opterror(opt, "must point to a commit", 0);