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;
20 * An atom is a valid field atom listed below, possibly prefixed with
21 * a "*" to denote deref_tag().
23 * We parse given format string and sort specifiers, and make a list
24 * of properties that we need to extract out of objects. ref_array_item
25 * structure will hold an array of values extracted that can be
26 * indexed with the "atom number", which is an index into this
29 static struct used_atom {
33 char color[COLOR_MAXLEN];
36 static int used_atom_cnt, need_tagged, need_symref;
37 static int need_color_reset_at_eol;
39 static void color_atom_parser(struct used_atom *atom, const char *color_value)
42 die(_("expected format: %%(color:<color>)"));
43 if (color_parse(color_value, atom->u.color) < 0)
44 die(_("unrecognized color: %%(color:%s)"), color_value);
47 static align_type parse_align_position(const char *s)
49 if (!strcmp(s, "right"))
51 else if (!strcmp(s, "middle"))
53 else if (!strcmp(s, "left"))
61 void (*parser)(struct used_atom *atom, const char *arg);
65 { "objectsize", FIELD_ULONG },
69 { "numparent", FIELD_ULONG },
76 { "authordate", FIELD_TIME },
80 { "committerdate", FIELD_TIME },
84 { "taggerdate", FIELD_TIME },
86 { "creatordate", FIELD_TIME },
95 { "color", FIELD_STR, color_atom_parser },
100 #define REF_FORMATTING_STATE_INIT { 0, NULL }
109 struct object_id oid;
112 struct ref_formatting_stack {
113 struct ref_formatting_stack *prev;
114 struct strbuf output;
115 void (*at_end)(struct ref_formatting_stack *stack);
119 struct ref_formatting_state {
121 struct ref_formatting_stack *stack;
128 struct contents contents;
130 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
131 unsigned long ul; /* used for sorting when not FIELD_STR */
135 * Used to parse format string and sort specifiers
137 int parse_ref_filter_atom(const char *atom, const char *ep)
144 if (*sp == '*' && sp < ep)
147 die("malformed field name: %.*s", (int)(ep-atom), atom);
149 /* Do we have the atom already used elsewhere? */
150 for (i = 0; i < used_atom_cnt; i++) {
151 int len = strlen(used_atom[i].name);
152 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
156 /* Is the atom a valid one? */
157 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
158 int len = strlen(valid_atom[i].name);
161 * If the atom name has a colon, strip it and everything after
162 * it off - it specifies the format for this entry, and
163 * shouldn't be used for checking against the valid_atom
166 arg = memchr(sp, ':', ep - sp);
167 if (len == (arg ? arg : ep) - sp &&
168 !memcmp(valid_atom[i].name, sp, len))
172 if (ARRAY_SIZE(valid_atom) <= i)
173 die("unknown field name: %.*s", (int)(ep-atom), atom);
175 /* Add it in, including the deref prefix */
178 REALLOC_ARRAY(used_atom, used_atom_cnt);
179 used_atom[at].name = xmemdupz(atom, ep - atom);
180 used_atom[at].type = valid_atom[i].cmp_type;
182 arg = used_atom[at].name + (arg - atom) + 1;
183 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
184 if (valid_atom[i].parser)
185 valid_atom[i].parser(&used_atom[at], arg);
188 if (!strcmp(used_atom[at].name, "symref"))
193 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
195 switch (quote_style) {
197 strbuf_addstr(s, str);
200 sq_quote_buf(s, str);
203 perl_quote_buf(s, str);
206 python_quote_buf(s, str);
209 tcl_quote_buf(s, str);
214 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
217 * Quote formatting is only done when the stack has a single
218 * element. Otherwise quote formatting is done on the
219 * element's entire output strbuf when the %(end) atom is
222 if (!state->stack->prev)
223 quote_formatting(&state->stack->output, v->s, state->quote_style);
225 strbuf_addstr(&state->stack->output, v->s);
228 static void push_stack_element(struct ref_formatting_stack **stack)
230 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
232 strbuf_init(&s->output, 0);
237 static void pop_stack_element(struct ref_formatting_stack **stack)
239 struct ref_formatting_stack *current = *stack;
240 struct ref_formatting_stack *prev = current->prev;
243 strbuf_addbuf(&prev->output, ¤t->output);
244 strbuf_release(¤t->output);
249 static void end_align_handler(struct ref_formatting_stack *stack)
251 struct align *align = (struct align *)stack->at_end_data;
252 struct strbuf s = STRBUF_INIT;
254 strbuf_utf8_align(&s, align->position, align->width, stack->output.buf);
255 strbuf_swap(&stack->output, &s);
259 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
261 struct ref_formatting_stack *new;
263 push_stack_element(&state->stack);
265 new->at_end = end_align_handler;
266 new->at_end_data = &atomv->u.align;
269 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
271 struct ref_formatting_stack *current = state->stack;
272 struct strbuf s = STRBUF_INIT;
274 if (!current->at_end)
275 die(_("format: %%(end) atom used without corresponding atom"));
276 current->at_end(current);
279 * Perform quote formatting when the stack element is that of
280 * a supporting atom. If nested then perform quote formatting
281 * only on the topmost supporting atom.
283 if (!state->stack->prev->prev) {
284 quote_formatting(&s, current->output.buf, state->quote_style);
285 strbuf_swap(¤t->output, &s);
288 pop_stack_element(&state->stack);
291 static int match_atom_name(const char *name, const char *atom_name, const char **val)
295 if (!skip_prefix(name, atom_name, &body))
296 return 0; /* doesn't even begin with "atom_name" */
298 *val = NULL; /* %(atom_name) and no customization */
302 return 0; /* "atom_namefoo" is not "atom_name" or "atom_name:..." */
303 *val = body + 1; /* "atom_name:val" */
308 * In a format string, find the next occurrence of %(atom).
310 static const char *find_next(const char *cp)
315 * %( is the start of an atom;
316 * %% is a quoted per-cent.
320 else if (cp[1] == '%')
321 cp++; /* skip over two % */
322 /* otherwise this is a singleton, literal % */
330 * Make sure the format string is well formed, and parse out
333 int verify_ref_format(const char *format)
337 need_color_reset_at_eol = 0;
338 for (cp = format; *cp && (sp = find_next(cp)); ) {
339 const char *color, *ep = strchr(sp, ')');
343 return error("malformed format string %s", sp);
344 /* sp points at "%(" and ep points at the closing ")" */
345 at = parse_ref_filter_atom(sp + 2, ep);
348 if (skip_prefix(used_atom[at].name, "color:", &color))
349 need_color_reset_at_eol = !!strcmp(color, "reset");
355 * Given an object name, read the object data and size, and return a
356 * "struct object". If the object data we are returning is also borrowed
357 * by the "struct object" representation, set *eaten as well---it is a
358 * signal from parse_object_buffer to us not to free the buffer.
360 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
362 enum object_type type;
363 void *buf = read_sha1_file(sha1, &type, sz);
366 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
372 static int grab_objectname(const char *name, const unsigned char *sha1,
373 struct atom_value *v)
375 if (!strcmp(name, "objectname")) {
376 v->s = xstrdup(sha1_to_hex(sha1));
379 if (!strcmp(name, "objectname:short")) {
380 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
386 /* See grab_values */
387 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
391 for (i = 0; i < used_atom_cnt; i++) {
392 const char *name = used_atom[i].name;
393 struct atom_value *v = &val[i];
394 if (!!deref != (*name == '*'))
398 if (!strcmp(name, "objecttype"))
399 v->s = typename(obj->type);
400 else if (!strcmp(name, "objectsize")) {
402 v->s = xstrfmt("%lu", sz);
405 grab_objectname(name, obj->oid.hash, v);
409 /* See grab_values */
410 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
413 struct tag *tag = (struct tag *) obj;
415 for (i = 0; i < used_atom_cnt; i++) {
416 const char *name = used_atom[i].name;
417 struct atom_value *v = &val[i];
418 if (!!deref != (*name == '*'))
422 if (!strcmp(name, "tag"))
424 else if (!strcmp(name, "type") && tag->tagged)
425 v->s = typename(tag->tagged->type);
426 else if (!strcmp(name, "object") && tag->tagged)
427 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
431 /* See grab_values */
432 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
435 struct commit *commit = (struct commit *) obj;
437 for (i = 0; i < used_atom_cnt; i++) {
438 const char *name = used_atom[i].name;
439 struct atom_value *v = &val[i];
440 if (!!deref != (*name == '*'))
444 if (!strcmp(name, "tree")) {
445 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
447 else if (!strcmp(name, "numparent")) {
448 v->ul = commit_list_count(commit->parents);
449 v->s = xstrfmt("%lu", v->ul);
451 else if (!strcmp(name, "parent")) {
452 struct commit_list *parents;
453 struct strbuf s = STRBUF_INIT;
454 for (parents = commit->parents; parents; parents = parents->next) {
455 struct commit *parent = parents->item;
456 if (parents != commit->parents)
457 strbuf_addch(&s, ' ');
458 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
460 v->s = strbuf_detach(&s, NULL);
465 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
469 if (!strncmp(buf, who, wholen) &&
471 return buf + wholen + 1;
472 eol = strchr(buf, '\n');
477 return ""; /* end of header */
483 static const char *copy_line(const char *buf)
485 const char *eol = strchrnul(buf, '\n');
486 return xmemdupz(buf, eol - buf);
489 static const char *copy_name(const char *buf)
492 for (cp = buf; *cp && *cp != '\n'; cp++) {
493 if (!strncmp(cp, " <", 2))
494 return xmemdupz(buf, cp - buf);
499 static const char *copy_email(const char *buf)
501 const char *email = strchr(buf, '<');
505 eoemail = strchr(email, '>');
508 return xmemdupz(email, eoemail + 1 - email);
511 static char *copy_subject(const char *buf, unsigned long len)
513 char *r = xmemdupz(buf, len);
516 for (i = 0; i < len; i++)
523 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
525 const char *eoemail = strstr(buf, "> ");
527 unsigned long timestamp;
529 struct date_mode date_mode = { DATE_NORMAL };
533 * We got here because atomname ends in "date" or "date<something>";
534 * it's not possible that <something> is not ":<format>" because
535 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
536 * ":" means no format is specified, and use the default.
538 formatp = strchr(atomname, ':');
539 if (formatp != NULL) {
541 parse_date_format(formatp, &date_mode);
546 timestamp = strtoul(eoemail + 2, &zone, 10);
547 if (timestamp == ULONG_MAX)
549 tz = strtol(zone, NULL, 10);
550 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
552 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
560 /* See grab_values */
561 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
564 int wholen = strlen(who);
565 const char *wholine = NULL;
567 for (i = 0; i < used_atom_cnt; i++) {
568 const char *name = used_atom[i].name;
569 struct atom_value *v = &val[i];
570 if (!!deref != (*name == '*'))
574 if (strncmp(who, name, wholen))
576 if (name[wholen] != 0 &&
577 strcmp(name + wholen, "name") &&
578 strcmp(name + wholen, "email") &&
579 !starts_with(name + wholen, "date"))
582 wholine = find_wholine(who, wholen, buf, sz);
584 return; /* no point looking for it */
585 if (name[wholen] == 0)
586 v->s = copy_line(wholine);
587 else if (!strcmp(name + wholen, "name"))
588 v->s = copy_name(wholine);
589 else if (!strcmp(name + wholen, "email"))
590 v->s = copy_email(wholine);
591 else if (starts_with(name + wholen, "date"))
592 grab_date(wholine, v, name);
596 * For a tag or a commit object, if "creator" or "creatordate" is
597 * requested, do something special.
599 if (strcmp(who, "tagger") && strcmp(who, "committer"))
600 return; /* "author" for commit object is not wanted */
602 wholine = find_wholine(who, wholen, buf, sz);
605 for (i = 0; i < used_atom_cnt; i++) {
606 const char *name = used_atom[i].name;
607 struct atom_value *v = &val[i];
608 if (!!deref != (*name == '*'))
613 if (starts_with(name, "creatordate"))
614 grab_date(wholine, v, name);
615 else if (!strcmp(name, "creator"))
616 v->s = copy_line(wholine);
620 static void find_subpos(const char *buf, unsigned long sz,
621 const char **sub, unsigned long *sublen,
622 const char **body, unsigned long *bodylen,
623 unsigned long *nonsiglen,
624 const char **sig, unsigned long *siglen)
627 /* skip past header until we hit empty line */
628 while (*buf && *buf != '\n') {
629 eol = strchrnul(buf, '\n');
634 /* skip any empty lines */
638 /* parse signature first; we might not even have a subject line */
639 *sig = buf + parse_signature(buf, strlen(buf));
640 *siglen = strlen(*sig);
642 /* subject is first non-empty line */
644 /* subject goes to first empty line */
645 while (buf < *sig && *buf && *buf != '\n') {
646 eol = strchrnul(buf, '\n');
651 *sublen = buf - *sub;
652 /* drop trailing newline, if present */
653 if (*sublen && (*sub)[*sublen - 1] == '\n')
656 /* skip any empty lines */
660 *bodylen = strlen(buf);
661 *nonsiglen = *sig - buf;
665 * If 'lines' is greater than 0, append that many lines from the given
666 * 'buf' of length 'size' to the given strbuf.
668 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
671 const char *sp, *eol;
676 for (i = 0; i < lines && sp < buf + size; i++) {
678 strbuf_addstr(out, "\n ");
679 eol = memchr(sp, '\n', size - (sp - buf));
680 len = eol ? eol - sp : size - (sp - buf);
681 strbuf_add(out, sp, len);
688 /* See grab_values */
689 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
692 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
693 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
695 for (i = 0; i < used_atom_cnt; i++) {
696 const char *name = used_atom[i].name;
697 struct atom_value *v = &val[i];
698 const char *valp = NULL;
699 if (!!deref != (*name == '*'))
703 if (strcmp(name, "subject") &&
704 strcmp(name, "body") &&
705 strcmp(name, "contents") &&
706 strcmp(name, "contents:subject") &&
707 strcmp(name, "contents:body") &&
708 strcmp(name, "contents:signature") &&
709 !starts_with(name, "contents:lines="))
714 &bodypos, &bodylen, &nonsiglen,
717 if (!strcmp(name, "subject"))
718 v->s = copy_subject(subpos, sublen);
719 else if (!strcmp(name, "contents:subject"))
720 v->s = copy_subject(subpos, sublen);
721 else if (!strcmp(name, "body"))
722 v->s = xmemdupz(bodypos, bodylen);
723 else if (!strcmp(name, "contents:body"))
724 v->s = xmemdupz(bodypos, nonsiglen);
725 else if (!strcmp(name, "contents:signature"))
726 v->s = xmemdupz(sigpos, siglen);
727 else if (!strcmp(name, "contents"))
728 v->s = xstrdup(subpos);
729 else if (skip_prefix(name, "contents:lines=", &valp)) {
730 struct strbuf s = STRBUF_INIT;
731 const char *contents_end = bodylen + bodypos - siglen;
733 if (strtoul_ui(valp, 10, &v->u.contents.lines))
734 die(_("positive value expected contents:lines=%s"), valp);
735 /* Size is the length of the message after removing the signature */
736 append_lines(&s, subpos, contents_end - subpos, v->u.contents.lines);
737 v->s = strbuf_detach(&s, NULL);
743 * We want to have empty print-string for field requests
744 * that do not apply (e.g. "authordate" for a tag object)
746 static void fill_missing_values(struct atom_value *val)
749 for (i = 0; i < used_atom_cnt; i++) {
750 struct atom_value *v = &val[i];
757 * val is a list of atom_value to hold returned values. Extract
758 * the values for atoms in used_atom array out of (obj, buf, sz).
759 * when deref is false, (obj, buf, sz) is the object that is
760 * pointed at by the ref itself; otherwise it is the object the
761 * ref (which is a tag) refers to.
763 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
765 grab_common_values(val, deref, obj, buf, sz);
768 grab_tag_values(val, deref, obj, buf, sz);
769 grab_sub_body_contents(val, deref, obj, buf, sz);
770 grab_person("tagger", val, deref, obj, buf, sz);
773 grab_commit_values(val, deref, obj, buf, sz);
774 grab_sub_body_contents(val, deref, obj, buf, sz);
775 grab_person("author", val, deref, obj, buf, sz);
776 grab_person("committer", val, deref, obj, buf, sz);
779 /* grab_tree_values(val, deref, obj, buf, sz); */
782 /* grab_blob_values(val, deref, obj, buf, sz); */
785 die("Eh? Object of type %d?", obj->type);
789 static inline char *copy_advance(char *dst, const char *src)
796 static const char *strip_ref_components(const char *refname, const char *nr_arg)
799 long nr = strtol(nr_arg, &end, 10);
801 const char *start = refname;
803 if (nr < 1 || *end != '\0')
804 die(":strip= requires a positive integer argument");
809 die("ref '%s' does not have %ld components to :strip",
820 * Parse the object referred by ref, and grab needed value.
822 static void populate_value(struct ref_array_item *ref)
828 const unsigned char *tagged;
830 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
832 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
833 unsigned char unused1[20];
834 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
840 /* Fill in specials first */
841 for (i = 0; i < used_atom_cnt; i++) {
842 struct used_atom *atom = &used_atom[i];
843 const char *name = used_atom[i].name;
844 struct atom_value *v = &ref->value[i];
849 struct branch *branch = NULL;
851 v->handler = append_atom;
858 if (starts_with(name, "refname"))
859 refname = ref->refname;
860 else if (starts_with(name, "symref"))
861 refname = ref->symref ? ref->symref : "";
862 else if (starts_with(name, "upstream")) {
863 const char *branch_name;
864 /* only local branches may have an upstream */
865 if (!skip_prefix(ref->refname, "refs/heads/",
868 branch = branch_get(branch_name);
870 refname = branch_get_upstream(branch, NULL);
873 } else if (starts_with(name, "push")) {
874 const char *branch_name;
875 if (!skip_prefix(ref->refname, "refs/heads/",
878 branch = branch_get(branch_name);
880 refname = branch_get_push(branch, NULL);
883 } else if (starts_with(name, "color:")) {
884 v->s = atom->u.color;
886 } else if (!strcmp(name, "flag")) {
887 char buf[256], *cp = buf;
888 if (ref->flag & REF_ISSYMREF)
889 cp = copy_advance(cp, ",symref");
890 if (ref->flag & REF_ISPACKED)
891 cp = copy_advance(cp, ",packed");
896 v->s = xstrdup(buf + 1);
899 } else if (!deref && grab_objectname(name, ref->objectname, v)) {
901 } else if (!strcmp(name, "HEAD")) {
903 unsigned char sha1[20];
905 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
907 if (!strcmp(ref->refname, head))
912 } else if (match_atom_name(name, "align", &valp)) {
913 struct align *align = &v->u.align;
914 struct string_list params = STRING_LIST_INIT_DUP;
919 die(_("expected format: %%(align:<width>,<position>)"));
921 align->position = ALIGN_LEFT;
923 string_list_split(¶ms, valp, ',', -1);
924 for (i = 0; i < params.nr; i++) {
925 const char *s = params.items[i].string;
928 if (!strtoul_ui(s, 10, (unsigned int *)&width))
930 else if ((position = parse_align_position(s)) >= 0)
931 align->position = position;
933 die(_("improper format entered align:%s"), s);
937 die(_("positive width expected with the %%(align) atom"));
938 align->width = width;
939 string_list_clear(¶ms, 0);
940 v->handler = align_atom_handler;
942 } else if (!strcmp(name, "end")) {
943 v->handler = end_atom_handler;
948 formatp = strchr(name, ':');
950 int num_ours, num_theirs;
954 if (!strcmp(formatp, "short"))
955 refname = shorten_unambiguous_ref(refname,
956 warn_ambiguous_refs);
957 else if (skip_prefix(formatp, "strip=", &arg))
958 refname = strip_ref_components(refname, arg);
959 else if (!strcmp(formatp, "track") &&
960 (starts_with(name, "upstream") ||
961 starts_with(name, "push"))) {
963 if (stat_tracking_info(branch, &num_ours,
967 if (!num_ours && !num_theirs)
970 v->s = xstrfmt("[behind %d]", num_theirs);
971 else if (!num_theirs)
972 v->s = xstrfmt("[ahead %d]", num_ours);
974 v->s = xstrfmt("[ahead %d, behind %d]",
975 num_ours, num_theirs);
977 } else if (!strcmp(formatp, "trackshort") &&
978 (starts_with(name, "upstream") ||
979 starts_with(name, "push"))) {
982 if (stat_tracking_info(branch, &num_ours,
986 if (!num_ours && !num_theirs)
990 else if (!num_theirs)
996 die("unknown %.*s format %s",
997 (int)(formatp - name), name, formatp);
1003 v->s = xstrfmt("%s^{}", refname);
1006 for (i = 0; i < used_atom_cnt; i++) {
1007 struct atom_value *v = &ref->value[i];
1014 buf = get_obj(ref->objectname, &obj, &size, &eaten);
1016 die("missing object %s for %s",
1017 sha1_to_hex(ref->objectname), ref->refname);
1019 die("parse_object_buffer failed on %s for %s",
1020 sha1_to_hex(ref->objectname), ref->refname);
1022 grab_values(ref->value, 0, obj, buf, size);
1027 * If there is no atom that wants to know about tagged
1028 * object, we are done.
1030 if (!need_tagged || (obj->type != OBJ_TAG))
1034 * If it is a tag object, see if we use a value that derefs
1035 * the object, and if we do grab the object it refers to.
1037 tagged = ((struct tag *)obj)->tagged->oid.hash;
1040 * NEEDSWORK: This derefs tag only once, which
1041 * is good to deal with chains of trust, but
1042 * is not consistent with what deref_tag() does
1043 * which peels the onion to the core.
1045 buf = get_obj(tagged, &obj, &size, &eaten);
1047 die("missing object %s for %s",
1048 sha1_to_hex(tagged), ref->refname);
1050 die("parse_object_buffer failed on %s for %s",
1051 sha1_to_hex(tagged), ref->refname);
1052 grab_values(ref->value, 1, obj, buf, size);
1058 * Given a ref, return the value for the atom. This lazily gets value
1059 * out of the object by calling populate value.
1061 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1064 populate_value(ref);
1065 fill_missing_values(ref->value);
1067 *v = &ref->value[atom];
1070 enum contains_result {
1071 CONTAINS_UNKNOWN = -1,
1077 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1080 * At each recursion step, the stack items points to the commits whose
1081 * ancestors are to be inspected.
1083 struct contains_stack {
1085 struct contains_stack_entry {
1086 struct commit *commit;
1087 struct commit_list *parents;
1091 static int in_commit_list(const struct commit_list *want, struct commit *c)
1093 for (; want; want = want->next)
1094 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1100 * Test whether the candidate or one of its parents is contained in the list.
1101 * Do not recurse to find out, though, but return -1 if inconclusive.
1103 static enum contains_result contains_test(struct commit *candidate,
1104 const struct commit_list *want)
1106 /* was it previously marked as containing a want commit? */
1107 if (candidate->object.flags & TMP_MARK)
1109 /* or marked as not possibly containing a want commit? */
1110 if (candidate->object.flags & UNINTERESTING)
1113 if (in_commit_list(want, candidate)) {
1114 candidate->object.flags |= TMP_MARK;
1118 if (parse_commit(candidate) < 0)
1124 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1126 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1127 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1128 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1131 static enum contains_result contains_tag_algo(struct commit *candidate,
1132 const struct commit_list *want)
1134 struct contains_stack contains_stack = { 0, 0, NULL };
1135 int result = contains_test(candidate, want);
1137 if (result != CONTAINS_UNKNOWN)
1140 push_to_contains_stack(candidate, &contains_stack);
1141 while (contains_stack.nr) {
1142 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1143 struct commit *commit = entry->commit;
1144 struct commit_list *parents = entry->parents;
1147 commit->object.flags |= UNINTERESTING;
1148 contains_stack.nr--;
1151 * If we just popped the stack, parents->item has been marked,
1152 * therefore contains_test will return a meaningful 0 or 1.
1154 else switch (contains_test(parents->item, want)) {
1156 commit->object.flags |= TMP_MARK;
1157 contains_stack.nr--;
1160 entry->parents = parents->next;
1162 case CONTAINS_UNKNOWN:
1163 push_to_contains_stack(parents->item, &contains_stack);
1167 free(contains_stack.contains_stack);
1168 return contains_test(candidate, want);
1171 static int commit_contains(struct ref_filter *filter, struct commit *commit)
1173 if (filter->with_commit_tag_algo)
1174 return contains_tag_algo(commit, filter->with_commit);
1175 return is_descendant_of(commit, filter->with_commit);
1179 * Return 1 if the refname matches one of the patterns, otherwise 0.
1180 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1181 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1182 * matches "refs/heads/mas*", too).
1184 static int match_pattern(const char **patterns, const char *refname)
1187 * When no '--format' option is given we need to skip the prefix
1188 * for matching refs of tags and branches.
1190 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1191 skip_prefix(refname, "refs/heads/", &refname) ||
1192 skip_prefix(refname, "refs/remotes/", &refname) ||
1193 skip_prefix(refname, "refs/", &refname));
1195 for (; *patterns; patterns++) {
1196 if (!wildmatch(*patterns, refname, 0, NULL))
1203 * Return 1 if the refname matches one of the patterns, otherwise 0.
1204 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1205 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1206 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1208 static int match_name_as_path(const char **pattern, const char *refname)
1210 int namelen = strlen(refname);
1211 for (; *pattern; pattern++) {
1212 const char *p = *pattern;
1213 int plen = strlen(p);
1215 if ((plen <= namelen) &&
1216 !strncmp(refname, p, plen) &&
1217 (refname[plen] == '\0' ||
1218 refname[plen] == '/' ||
1221 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1227 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1228 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1230 if (!*filter->name_patterns)
1231 return 1; /* No pattern always matches */
1232 if (filter->match_as_path)
1233 return match_name_as_path(filter->name_patterns, refname);
1234 return match_pattern(filter->name_patterns, refname);
1238 * Given a ref (sha1, refname), check if the ref belongs to the array
1239 * of sha1s. If the given ref is a tag, check if the given tag points
1240 * at one of the sha1s in the given sha1 array.
1241 * the given sha1_array.
1243 * 1. Only a single level of inderection is obtained, we might want to
1244 * change this to account for multiple levels (e.g. annotated tags
1245 * pointing to annotated tags pointing to a commit.)
1246 * 2. As the refs are cached we might know what refname peels to without
1247 * the need to parse the object via parse_object(). peel_ref() might be a
1248 * more efficient alternative to obtain the pointee.
1250 static const unsigned char *match_points_at(struct sha1_array *points_at,
1251 const unsigned char *sha1,
1252 const char *refname)
1254 const unsigned char *tagged_sha1 = NULL;
1257 if (sha1_array_lookup(points_at, sha1) >= 0)
1259 obj = parse_object(sha1);
1261 die(_("malformed object at '%s'"), refname);
1262 if (obj->type == OBJ_TAG)
1263 tagged_sha1 = ((struct tag *)obj)->tagged->oid.hash;
1264 if (tagged_sha1 && sha1_array_lookup(points_at, tagged_sha1) >= 0)
1269 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1270 static struct ref_array_item *new_ref_array_item(const char *refname,
1271 const unsigned char *objectname,
1274 size_t len = strlen(refname);
1275 struct ref_array_item *ref = xcalloc(1, sizeof(struct ref_array_item) + len + 1);
1276 memcpy(ref->refname, refname, len);
1277 ref->refname[len] = '\0';
1278 hashcpy(ref->objectname, objectname);
1284 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1292 { "refs/heads/" , FILTER_REFS_BRANCHES },
1293 { "refs/remotes/" , FILTER_REFS_REMOTES },
1294 { "refs/tags/", FILTER_REFS_TAGS}
1297 if (filter->kind == FILTER_REFS_BRANCHES ||
1298 filter->kind == FILTER_REFS_REMOTES ||
1299 filter->kind == FILTER_REFS_TAGS)
1300 return filter->kind;
1301 else if (!strcmp(refname, "HEAD"))
1302 return FILTER_REFS_DETACHED_HEAD;
1304 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1305 if (starts_with(refname, ref_kind[i].prefix))
1306 return ref_kind[i].kind;
1309 return FILTER_REFS_OTHERS;
1313 * A call-back given to for_each_ref(). Filter refs and keep them for
1314 * later object processing.
1316 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1318 struct ref_filter_cbdata *ref_cbdata = cb_data;
1319 struct ref_filter *filter = ref_cbdata->filter;
1320 struct ref_array_item *ref;
1321 struct commit *commit = NULL;
1324 if (flag & REF_BAD_NAME) {
1325 warning("ignoring ref with broken name %s", refname);
1329 if (flag & REF_ISBROKEN) {
1330 warning("ignoring broken ref %s", refname);
1334 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1335 kind = filter_ref_kind(filter, refname);
1336 if (!(kind & filter->kind))
1339 if (!filter_pattern_match(filter, refname))
1342 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1346 * A merge filter is applied on refs pointing to commits. Hence
1347 * obtain the commit using the 'oid' available and discard all
1348 * non-commits early. The actual filtering is done later.
1350 if (filter->merge_commit || filter->with_commit || filter->verbose) {
1351 commit = lookup_commit_reference_gently(oid->hash, 1);
1354 /* We perform the filtering for the '--contains' option */
1355 if (filter->with_commit &&
1356 !commit_contains(filter, commit))
1361 * We do not open the object yet; sort may only need refname
1362 * to do its job and the resulting list may yet to be pruned
1363 * by maxcount logic.
1365 ref = new_ref_array_item(refname, oid->hash, flag);
1366 ref->commit = commit;
1368 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1369 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1374 /* Free memory allocated for a ref_array_item */
1375 static void free_array_item(struct ref_array_item *item)
1377 free((char *)item->symref);
1381 /* Free all memory allocated for ref_array */
1382 void ref_array_clear(struct ref_array *array)
1386 for (i = 0; i < array->nr; i++)
1387 free_array_item(array->items[i]);
1389 array->items = NULL;
1390 array->nr = array->alloc = 0;
1393 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1395 struct rev_info revs;
1397 struct ref_filter *filter = ref_cbdata->filter;
1398 struct ref_array *array = ref_cbdata->array;
1399 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1401 init_revisions(&revs, NULL);
1403 for (i = 0; i < array->nr; i++) {
1404 struct ref_array_item *item = array->items[i];
1405 add_pending_object(&revs, &item->commit->object, item->refname);
1406 to_clear[i] = item->commit;
1409 filter->merge_commit->object.flags |= UNINTERESTING;
1410 add_pending_object(&revs, &filter->merge_commit->object, "");
1413 if (prepare_revision_walk(&revs))
1414 die(_("revision walk setup failed"));
1419 for (i = 0; i < old_nr; i++) {
1420 struct ref_array_item *item = array->items[i];
1421 struct commit *commit = item->commit;
1423 int is_merged = !!(commit->object.flags & UNINTERESTING);
1425 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1426 array->items[array->nr++] = array->items[i];
1428 free_array_item(item);
1431 for (i = 0; i < old_nr; i++)
1432 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1433 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1438 * API for filtering a set of refs. Based on the type of refs the user
1439 * has requested, we iterate through those refs and apply filters
1440 * as per the given ref_filter structure and finally store the
1441 * filtered refs in the ref_array structure.
1443 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1445 struct ref_filter_cbdata ref_cbdata;
1447 unsigned int broken = 0;
1449 ref_cbdata.array = array;
1450 ref_cbdata.filter = filter;
1452 if (type & FILTER_REFS_INCLUDE_BROKEN)
1454 filter->kind = type & FILTER_REFS_KIND_MASK;
1456 /* Simple per-ref filtering */
1458 die("filter_refs: invalid type");
1461 * For common cases where we need only branches or remotes or tags,
1462 * we only iterate through those refs. If a mix of refs is needed,
1463 * we iterate over all refs and filter out required refs with the help
1464 * of filter_ref_kind().
1466 if (filter->kind == FILTER_REFS_BRANCHES)
1467 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1468 else if (filter->kind == FILTER_REFS_REMOTES)
1469 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1470 else if (filter->kind == FILTER_REFS_TAGS)
1471 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1472 else if (filter->kind & FILTER_REFS_ALL)
1473 ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1474 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1475 head_ref(ref_filter_handler, &ref_cbdata);
1479 /* Filters that need revision walking */
1480 if (filter->merge_commit)
1481 do_merge_filter(&ref_cbdata);
1486 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1488 struct atom_value *va, *vb;
1490 cmp_type cmp_type = used_atom[s->atom].type;
1492 get_ref_atom_value(a, s->atom, &va);
1493 get_ref_atom_value(b, s->atom, &vb);
1495 cmp = versioncmp(va->s, vb->s);
1496 else if (cmp_type == FIELD_STR)
1497 cmp = strcmp(va->s, vb->s);
1499 if (va->ul < vb->ul)
1501 else if (va->ul == vb->ul)
1502 cmp = strcmp(a->refname, b->refname);
1507 return (s->reverse) ? -cmp : cmp;
1510 static struct ref_sorting *ref_sorting;
1511 static int compare_refs(const void *a_, const void *b_)
1513 struct ref_array_item *a = *((struct ref_array_item **)a_);
1514 struct ref_array_item *b = *((struct ref_array_item **)b_);
1515 struct ref_sorting *s;
1517 for (s = ref_sorting; s; s = s->next) {
1518 int cmp = cmp_ref_sorting(s, a, b);
1525 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1527 ref_sorting = sorting;
1528 qsort(array->items, array->nr, sizeof(struct ref_array_item *), compare_refs);
1531 static int hex1(char ch)
1533 if ('0' <= ch && ch <= '9')
1535 else if ('a' <= ch && ch <= 'f')
1536 return ch - 'a' + 10;
1537 else if ('A' <= ch && ch <= 'F')
1538 return ch - 'A' + 10;
1541 static int hex2(const char *cp)
1544 return (hex1(cp[0]) << 4) | hex1(cp[1]);
1549 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1551 struct strbuf *s = &state->stack->output;
1553 while (*cp && (!ep || cp < ep)) {
1558 int ch = hex2(cp + 1);
1560 strbuf_addch(s, ch);
1566 strbuf_addch(s, *cp);
1571 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
1573 const char *cp, *sp, *ep;
1574 struct strbuf *final_buf;
1575 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1577 state.quote_style = quote_style;
1578 push_stack_element(&state.stack);
1580 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1581 struct atom_value *atomv;
1583 ep = strchr(sp, ')');
1585 append_literal(cp, sp, &state);
1586 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1587 atomv->handler(atomv, &state);
1590 sp = cp + strlen(cp);
1591 append_literal(cp, sp, &state);
1593 if (need_color_reset_at_eol) {
1594 struct atom_value resetv;
1595 char color[COLOR_MAXLEN] = "";
1597 if (color_parse("reset", color) < 0)
1598 die("BUG: couldn't parse 'reset' as a color");
1600 append_atom(&resetv, &state);
1602 if (state.stack->prev)
1603 die(_("format: %%(end) atom missing"));
1604 final_buf = &state.stack->output;
1605 fwrite(final_buf->buf, 1, final_buf->len, stdout);
1606 pop_stack_element(&state.stack);
1610 /* If no sorting option is given, use refname to sort as default */
1611 struct ref_sorting *ref_default_sorting(void)
1613 static const char cstr_name[] = "refname";
1615 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
1617 sorting->next = NULL;
1618 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
1622 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
1624 struct ref_sorting **sorting_tail = opt->value;
1625 struct ref_sorting *s;
1628 if (!arg) /* should --no-sort void the list ? */
1631 s = xcalloc(1, sizeof(*s));
1632 s->next = *sorting_tail;
1639 if (skip_prefix(arg, "version:", &arg) ||
1640 skip_prefix(arg, "v:", &arg))
1643 s->atom = parse_ref_filter_atom(arg, arg+len);
1647 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
1649 struct ref_filter *rf = opt->value;
1650 unsigned char sha1[20];
1652 rf->merge = starts_with(opt->long_name, "no")
1653 ? REF_FILTER_MERGED_OMIT
1654 : REF_FILTER_MERGED_INCLUDE;
1656 if (get_sha1(arg, sha1))
1657 die(_("malformed object name %s"), arg);
1659 rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
1660 if (!rf->merge_commit)
1661 return opterror(opt, "must point to a commit", 0);