3 #include "parse-options.h"
11 #include "ref-filter.h"
15 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
23 { "objectsize", FIELD_ULONG },
27 { "numparent", FIELD_ULONG },
34 { "authordate", FIELD_TIME },
38 { "committerdate", FIELD_TIME },
42 { "taggerdate", FIELD_TIME },
44 { "creatordate", FIELD_TIME },
48 { "contents:subject" },
50 { "contents:signature" },
61 #define REF_FORMATTING_STATE_INIT { 0, NULL }
68 struct ref_formatting_stack {
69 struct ref_formatting_stack *prev;
71 void (*at_end)(struct ref_formatting_stack *stack);
75 struct ref_formatting_state {
77 struct ref_formatting_stack *stack;
85 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
86 unsigned long ul; /* used for sorting when not FIELD_STR */
90 * An atom is a valid field atom listed above, possibly prefixed with
91 * a "*" to denote deref_tag().
93 * We parse given format string and sort specifiers, and make a list
94 * of properties that we need to extract out of objects. ref_array_item
95 * structure will hold an array of values extracted that can be
96 * indexed with the "atom number", which is an index into this
99 static const char **used_atom;
100 static cmp_type *used_atom_type;
101 static int used_atom_cnt, need_tagged, need_symref;
102 static int need_color_reset_at_eol;
105 * Used to parse format string and sort specifiers
107 int parse_ref_filter_atom(const char *atom, const char *ep)
113 if (*sp == '*' && sp < ep)
116 die("malformed field name: %.*s", (int)(ep-atom), atom);
118 /* Do we have the atom already used elsewhere? */
119 for (i = 0; i < used_atom_cnt; i++) {
120 int len = strlen(used_atom[i]);
121 if (len == ep - atom && !memcmp(used_atom[i], atom, len))
125 /* Is the atom a valid one? */
126 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
127 int len = strlen(valid_atom[i].name);
129 * If the atom name has a colon, strip it and everything after
130 * it off - it specifies the format for this entry, and
131 * shouldn't be used for checking against the valid_atom
134 const char *formatp = strchr(sp, ':');
135 if (!formatp || ep < formatp)
137 if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
141 if (ARRAY_SIZE(valid_atom) <= i)
142 die("unknown field name: %.*s", (int)(ep-atom), atom);
144 /* Add it in, including the deref prefix */
147 REALLOC_ARRAY(used_atom, used_atom_cnt);
148 REALLOC_ARRAY(used_atom_type, used_atom_cnt);
149 used_atom[at] = xmemdupz(atom, ep - atom);
150 used_atom_type[at] = valid_atom[i].cmp_type;
153 if (!strcmp(used_atom[at], "symref"))
158 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
160 switch (quote_style) {
162 strbuf_addstr(s, str);
165 sq_quote_buf(s, str);
168 perl_quote_buf(s, str);
171 python_quote_buf(s, str);
174 tcl_quote_buf(s, str);
179 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
182 * Quote formatting is only done when the stack has a single
183 * element. Otherwise quote formatting is done on the
184 * element's entire output strbuf when the %(end) atom is
187 if (!state->stack->prev)
188 quote_formatting(&state->stack->output, v->s, state->quote_style);
190 strbuf_addstr(&state->stack->output, v->s);
193 static void push_stack_element(struct ref_formatting_stack **stack)
195 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
197 strbuf_init(&s->output, 0);
202 static void pop_stack_element(struct ref_formatting_stack **stack)
204 struct ref_formatting_stack *current = *stack;
205 struct ref_formatting_stack *prev = current->prev;
208 strbuf_addbuf(&prev->output, ¤t->output);
209 strbuf_release(¤t->output);
214 static void end_align_handler(struct ref_formatting_stack *stack)
216 struct align *align = (struct align *)stack->at_end_data;
217 struct strbuf s = STRBUF_INIT;
219 strbuf_utf8_align(&s, align->position, align->width, stack->output.buf);
220 strbuf_swap(&stack->output, &s);
224 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
226 struct ref_formatting_stack *new;
228 push_stack_element(&state->stack);
230 new->at_end = end_align_handler;
231 new->at_end_data = &atomv->u.align;
234 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
236 struct ref_formatting_stack *current = state->stack;
237 struct strbuf s = STRBUF_INIT;
239 if (!current->at_end)
240 die(_("format: %%(end) atom used without corresponding atom"));
241 current->at_end(current);
244 * Perform quote formatting when the stack element is that of
245 * a supporting atom. If nested then perform quote formatting
246 * only on the topmost supporting atom.
248 if (!state->stack->prev->prev) {
249 quote_formatting(&s, current->output.buf, state->quote_style);
250 strbuf_swap(¤t->output, &s);
253 pop_stack_element(&state->stack);
256 static int match_atom_name(const char *name, const char *atom_name, const char **val)
260 if (!skip_prefix(name, atom_name, &body))
261 return 0; /* doesn't even begin with "atom_name" */
263 *val = NULL; /* %(atom_name) and no customization */
267 return 0; /* "atom_namefoo" is not "atom_name" or "atom_name:..." */
268 *val = body + 1; /* "atom_name:val" */
273 * In a format string, find the next occurrence of %(atom).
275 static const char *find_next(const char *cp)
280 * %( is the start of an atom;
281 * %% is a quoted per-cent.
285 else if (cp[1] == '%')
286 cp++; /* skip over two % */
287 /* otherwise this is a singleton, literal % */
295 * Make sure the format string is well formed, and parse out
298 int verify_ref_format(const char *format)
302 need_color_reset_at_eol = 0;
303 for (cp = format; *cp && (sp = find_next(cp)); ) {
304 const char *color, *ep = strchr(sp, ')');
308 return error("malformed format string %s", sp);
309 /* sp points at "%(" and ep points at the closing ")" */
310 at = parse_ref_filter_atom(sp + 2, ep);
313 if (skip_prefix(used_atom[at], "color:", &color))
314 need_color_reset_at_eol = !!strcmp(color, "reset");
320 * Given an object name, read the object data and size, and return a
321 * "struct object". If the object data we are returning is also borrowed
322 * by the "struct object" representation, set *eaten as well---it is a
323 * signal from parse_object_buffer to us not to free the buffer.
325 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
327 enum object_type type;
328 void *buf = read_sha1_file(sha1, &type, sz);
331 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
337 static int grab_objectname(const char *name, const unsigned char *sha1,
338 struct atom_value *v)
340 if (!strcmp(name, "objectname")) {
341 char *s = xmalloc(41);
342 strcpy(s, sha1_to_hex(sha1));
346 if (!strcmp(name, "objectname:short")) {
347 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
353 /* See grab_values */
354 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
358 for (i = 0; i < used_atom_cnt; i++) {
359 const char *name = used_atom[i];
360 struct atom_value *v = &val[i];
361 if (!!deref != (*name == '*'))
365 if (!strcmp(name, "objecttype"))
366 v->s = typename(obj->type);
367 else if (!strcmp(name, "objectsize")) {
368 char *s = xmalloc(40);
369 sprintf(s, "%lu", sz);
374 grab_objectname(name, obj->sha1, v);
378 /* See grab_values */
379 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
382 struct tag *tag = (struct tag *) obj;
384 for (i = 0; i < used_atom_cnt; i++) {
385 const char *name = used_atom[i];
386 struct atom_value *v = &val[i];
387 if (!!deref != (*name == '*'))
391 if (!strcmp(name, "tag"))
393 else if (!strcmp(name, "type") && tag->tagged)
394 v->s = typename(tag->tagged->type);
395 else if (!strcmp(name, "object") && tag->tagged) {
396 char *s = xmalloc(41);
397 strcpy(s, sha1_to_hex(tag->tagged->sha1));
403 /* See grab_values */
404 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
407 struct commit *commit = (struct commit *) obj;
409 for (i = 0; i < used_atom_cnt; i++) {
410 const char *name = used_atom[i];
411 struct atom_value *v = &val[i];
412 if (!!deref != (*name == '*'))
416 if (!strcmp(name, "tree")) {
417 char *s = xmalloc(41);
418 strcpy(s, sha1_to_hex(commit->tree->object.sha1));
421 if (!strcmp(name, "numparent")) {
422 char *s = xmalloc(40);
423 v->ul = commit_list_count(commit->parents);
424 sprintf(s, "%lu", v->ul);
427 else if (!strcmp(name, "parent")) {
428 int num = commit_list_count(commit->parents);
430 struct commit_list *parents;
431 char *s = xmalloc(41 * num + 1);
433 for (i = 0, parents = commit->parents;
435 parents = parents->next, i = i + 41) {
436 struct commit *parent = parents->item;
437 strcpy(s+i, sha1_to_hex(parent->object.sha1));
447 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
451 if (!strncmp(buf, who, wholen) &&
453 return buf + wholen + 1;
454 eol = strchr(buf, '\n');
459 return ""; /* end of header */
465 static const char *copy_line(const char *buf)
467 const char *eol = strchrnul(buf, '\n');
468 return xmemdupz(buf, eol - buf);
471 static const char *copy_name(const char *buf)
474 for (cp = buf; *cp && *cp != '\n'; cp++) {
475 if (!strncmp(cp, " <", 2))
476 return xmemdupz(buf, cp - buf);
481 static const char *copy_email(const char *buf)
483 const char *email = strchr(buf, '<');
487 eoemail = strchr(email, '>');
490 return xmemdupz(email, eoemail + 1 - email);
493 static char *copy_subject(const char *buf, unsigned long len)
495 char *r = xmemdupz(buf, len);
498 for (i = 0; i < len; i++)
505 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
507 const char *eoemail = strstr(buf, "> ");
509 unsigned long timestamp;
511 struct date_mode date_mode = { DATE_NORMAL };
515 * We got here because atomname ends in "date" or "date<something>";
516 * it's not possible that <something> is not ":<format>" because
517 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
518 * ":" means no format is specified, and use the default.
520 formatp = strchr(atomname, ':');
521 if (formatp != NULL) {
523 parse_date_format(formatp, &date_mode);
528 timestamp = strtoul(eoemail + 2, &zone, 10);
529 if (timestamp == ULONG_MAX)
531 tz = strtol(zone, NULL, 10);
532 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
534 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
542 /* See grab_values */
543 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
546 int wholen = strlen(who);
547 const char *wholine = NULL;
549 for (i = 0; i < used_atom_cnt; i++) {
550 const char *name = used_atom[i];
551 struct atom_value *v = &val[i];
552 if (!!deref != (*name == '*'))
556 if (strncmp(who, name, wholen))
558 if (name[wholen] != 0 &&
559 strcmp(name + wholen, "name") &&
560 strcmp(name + wholen, "email") &&
561 !starts_with(name + wholen, "date"))
564 wholine = find_wholine(who, wholen, buf, sz);
566 return; /* no point looking for it */
567 if (name[wholen] == 0)
568 v->s = copy_line(wholine);
569 else if (!strcmp(name + wholen, "name"))
570 v->s = copy_name(wholine);
571 else if (!strcmp(name + wholen, "email"))
572 v->s = copy_email(wholine);
573 else if (starts_with(name + wholen, "date"))
574 grab_date(wholine, v, name);
578 * For a tag or a commit object, if "creator" or "creatordate" is
579 * requested, do something special.
581 if (strcmp(who, "tagger") && strcmp(who, "committer"))
582 return; /* "author" for commit object is not wanted */
584 wholine = find_wholine(who, wholen, buf, sz);
587 for (i = 0; i < used_atom_cnt; i++) {
588 const char *name = used_atom[i];
589 struct atom_value *v = &val[i];
590 if (!!deref != (*name == '*'))
595 if (starts_with(name, "creatordate"))
596 grab_date(wholine, v, name);
597 else if (!strcmp(name, "creator"))
598 v->s = copy_line(wholine);
602 static void find_subpos(const char *buf, unsigned long sz,
603 const char **sub, unsigned long *sublen,
604 const char **body, unsigned long *bodylen,
605 unsigned long *nonsiglen,
606 const char **sig, unsigned long *siglen)
609 /* skip past header until we hit empty line */
610 while (*buf && *buf != '\n') {
611 eol = strchrnul(buf, '\n');
616 /* skip any empty lines */
620 /* parse signature first; we might not even have a subject line */
621 *sig = buf + parse_signature(buf, strlen(buf));
622 *siglen = strlen(*sig);
624 /* subject is first non-empty line */
626 /* subject goes to first empty line */
627 while (buf < *sig && *buf && *buf != '\n') {
628 eol = strchrnul(buf, '\n');
633 *sublen = buf - *sub;
634 /* drop trailing newline, if present */
635 if (*sublen && (*sub)[*sublen - 1] == '\n')
638 /* skip any empty lines */
642 *bodylen = strlen(buf);
643 *nonsiglen = *sig - buf;
646 /* See grab_values */
647 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
650 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
651 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
653 for (i = 0; i < used_atom_cnt; i++) {
654 const char *name = used_atom[i];
655 struct atom_value *v = &val[i];
656 if (!!deref != (*name == '*'))
660 if (strcmp(name, "subject") &&
661 strcmp(name, "body") &&
662 strcmp(name, "contents") &&
663 strcmp(name, "contents:subject") &&
664 strcmp(name, "contents:body") &&
665 strcmp(name, "contents:signature"))
670 &bodypos, &bodylen, &nonsiglen,
673 if (!strcmp(name, "subject"))
674 v->s = copy_subject(subpos, sublen);
675 else if (!strcmp(name, "contents:subject"))
676 v->s = copy_subject(subpos, sublen);
677 else if (!strcmp(name, "body"))
678 v->s = xmemdupz(bodypos, bodylen);
679 else if (!strcmp(name, "contents:body"))
680 v->s = xmemdupz(bodypos, nonsiglen);
681 else if (!strcmp(name, "contents:signature"))
682 v->s = xmemdupz(sigpos, siglen);
683 else if (!strcmp(name, "contents"))
684 v->s = xstrdup(subpos);
689 * We want to have empty print-string for field requests
690 * that do not apply (e.g. "authordate" for a tag object)
692 static void fill_missing_values(struct atom_value *val)
695 for (i = 0; i < used_atom_cnt; i++) {
696 struct atom_value *v = &val[i];
703 * val is a list of atom_value to hold returned values. Extract
704 * the values for atoms in used_atom array out of (obj, buf, sz).
705 * when deref is false, (obj, buf, sz) is the object that is
706 * pointed at by the ref itself; otherwise it is the object the
707 * ref (which is a tag) refers to.
709 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
711 grab_common_values(val, deref, obj, buf, sz);
714 grab_tag_values(val, deref, obj, buf, sz);
715 grab_sub_body_contents(val, deref, obj, buf, sz);
716 grab_person("tagger", val, deref, obj, buf, sz);
719 grab_commit_values(val, deref, obj, buf, sz);
720 grab_sub_body_contents(val, deref, obj, buf, sz);
721 grab_person("author", val, deref, obj, buf, sz);
722 grab_person("committer", val, deref, obj, buf, sz);
725 /* grab_tree_values(val, deref, obj, buf, sz); */
728 /* grab_blob_values(val, deref, obj, buf, sz); */
731 die("Eh? Object of type %d?", obj->type);
735 static inline char *copy_advance(char *dst, const char *src)
743 * Parse the object referred by ref, and grab needed value.
745 static void populate_value(struct ref_array_item *ref)
751 const unsigned char *tagged;
753 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
755 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
756 unsigned char unused1[20];
757 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
763 /* Fill in specials first */
764 for (i = 0; i < used_atom_cnt; i++) {
765 const char *name = used_atom[i];
766 struct atom_value *v = &ref->value[i];
771 struct branch *branch = NULL;
773 v->handler = append_atom;
780 if (starts_with(name, "refname"))
781 refname = ref->refname;
782 else if (starts_with(name, "symref"))
783 refname = ref->symref ? ref->symref : "";
784 else if (starts_with(name, "upstream")) {
785 const char *branch_name;
786 /* only local branches may have an upstream */
787 if (!skip_prefix(ref->refname, "refs/heads/",
790 branch = branch_get(branch_name);
792 refname = branch_get_upstream(branch, NULL);
795 } else if (starts_with(name, "push")) {
796 const char *branch_name;
797 if (!skip_prefix(ref->refname, "refs/heads/",
800 branch = branch_get(branch_name);
802 refname = branch_get_push(branch, NULL);
805 } else if (match_atom_name(name, "color", &valp)) {
806 char color[COLOR_MAXLEN] = "";
809 die(_("expected format: %%(color:<color>)"));
810 if (color_parse(valp, color) < 0)
811 die(_("unable to parse format"));
812 v->s = xstrdup(color);
814 } else if (!strcmp(name, "flag")) {
815 char buf[256], *cp = buf;
816 if (ref->flag & REF_ISSYMREF)
817 cp = copy_advance(cp, ",symref");
818 if (ref->flag & REF_ISPACKED)
819 cp = copy_advance(cp, ",packed");
824 v->s = xstrdup(buf + 1);
827 } else if (!deref && grab_objectname(name, ref->objectname, v)) {
829 } else if (!strcmp(name, "HEAD")) {
831 unsigned char sha1[20];
833 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
835 if (!strcmp(ref->refname, head))
840 } else if (match_atom_name(name, "align", &valp)) {
841 struct align *align = &v->u.align;
842 struct strbuf **s, **to_free;
846 die(_("expected format: %%(align:<width>,<position>)"));
849 * TODO: Implement a function similar to strbuf_split_str()
850 * which would omit the separator from the end of each value.
852 s = to_free = strbuf_split_str(valp, ',', 0);
854 align->position = ALIGN_LEFT;
857 /* Strip trailing comma */
859 strbuf_setlen(s[0], s[0]->len - 1);
860 if (!strtoul_ui(s[0]->buf, 10, (unsigned int *)&width))
862 else if (!strcmp(s[0]->buf, "left"))
863 align->position = ALIGN_LEFT;
864 else if (!strcmp(s[0]->buf, "right"))
865 align->position = ALIGN_RIGHT;
866 else if (!strcmp(s[0]->buf, "middle"))
867 align->position = ALIGN_MIDDLE;
869 die(_("improper format entered align:%s"), s[0]->buf);
874 die(_("positive width expected with the %%(align) atom"));
875 align->width = width;
876 strbuf_list_free(to_free);
877 v->handler = align_atom_handler;
879 } else if (!strcmp(name, "end")) {
880 v->handler = end_atom_handler;
885 formatp = strchr(name, ':');
887 int num_ours, num_theirs;
890 if (!strcmp(formatp, "short"))
891 refname = shorten_unambiguous_ref(refname,
892 warn_ambiguous_refs);
893 else if (!strcmp(formatp, "track") &&
894 (starts_with(name, "upstream") ||
895 starts_with(name, "push"))) {
898 if (stat_tracking_info(branch, &num_ours,
902 if (!num_ours && !num_theirs)
904 else if (!num_ours) {
905 sprintf(buf, "[behind %d]", num_theirs);
907 } else if (!num_theirs) {
908 sprintf(buf, "[ahead %d]", num_ours);
911 sprintf(buf, "[ahead %d, behind %d]",
912 num_ours, num_theirs);
916 } else if (!strcmp(formatp, "trackshort") &&
917 (starts_with(name, "upstream") ||
918 starts_with(name, "push"))) {
921 if (stat_tracking_info(branch, &num_ours,
925 if (!num_ours && !num_theirs)
929 else if (!num_theirs)
935 die("unknown %.*s format %s",
936 (int)(formatp - name), name, formatp);
942 int len = strlen(refname);
943 char *s = xmalloc(len + 4);
944 sprintf(s, "%s^{}", refname);
949 for (i = 0; i < used_atom_cnt; i++) {
950 struct atom_value *v = &ref->value[i];
957 buf = get_obj(ref->objectname, &obj, &size, &eaten);
959 die("missing object %s for %s",
960 sha1_to_hex(ref->objectname), ref->refname);
962 die("parse_object_buffer failed on %s for %s",
963 sha1_to_hex(ref->objectname), ref->refname);
965 grab_values(ref->value, 0, obj, buf, size);
970 * If there is no atom that wants to know about tagged
971 * object, we are done.
973 if (!need_tagged || (obj->type != OBJ_TAG))
977 * If it is a tag object, see if we use a value that derefs
978 * the object, and if we do grab the object it refers to.
980 tagged = ((struct tag *)obj)->tagged->sha1;
983 * NEEDSWORK: This derefs tag only once, which
984 * is good to deal with chains of trust, but
985 * is not consistent with what deref_tag() does
986 * which peels the onion to the core.
988 buf = get_obj(tagged, &obj, &size, &eaten);
990 die("missing object %s for %s",
991 sha1_to_hex(tagged), ref->refname);
993 die("parse_object_buffer failed on %s for %s",
994 sha1_to_hex(tagged), ref->refname);
995 grab_values(ref->value, 1, obj, buf, size);
1001 * Given a ref, return the value for the atom. This lazily gets value
1002 * out of the object by calling populate value.
1004 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1007 populate_value(ref);
1008 fill_missing_values(ref->value);
1010 *v = &ref->value[atom];
1013 enum contains_result {
1014 CONTAINS_UNKNOWN = -1,
1020 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1023 * At each recursion step, the stack items points to the commits whose
1024 * ancestors are to be inspected.
1026 struct contains_stack {
1028 struct contains_stack_entry {
1029 struct commit *commit;
1030 struct commit_list *parents;
1034 static int in_commit_list(const struct commit_list *want, struct commit *c)
1036 for (; want; want = want->next)
1037 if (!hashcmp(want->item->object.sha1, c->object.sha1))
1043 * Test whether the candidate or one of its parents is contained in the list.
1044 * Do not recurse to find out, though, but return -1 if inconclusive.
1046 static enum contains_result contains_test(struct commit *candidate,
1047 const struct commit_list *want)
1049 /* was it previously marked as containing a want commit? */
1050 if (candidate->object.flags & TMP_MARK)
1052 /* or marked as not possibly containing a want commit? */
1053 if (candidate->object.flags & UNINTERESTING)
1056 if (in_commit_list(want, candidate)) {
1057 candidate->object.flags |= TMP_MARK;
1061 if (parse_commit(candidate) < 0)
1067 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1069 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1070 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1071 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1074 static enum contains_result contains_tag_algo(struct commit *candidate,
1075 const struct commit_list *want)
1077 struct contains_stack contains_stack = { 0, 0, NULL };
1078 int result = contains_test(candidate, want);
1080 if (result != CONTAINS_UNKNOWN)
1083 push_to_contains_stack(candidate, &contains_stack);
1084 while (contains_stack.nr) {
1085 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1086 struct commit *commit = entry->commit;
1087 struct commit_list *parents = entry->parents;
1090 commit->object.flags |= UNINTERESTING;
1091 contains_stack.nr--;
1094 * If we just popped the stack, parents->item has been marked,
1095 * therefore contains_test will return a meaningful 0 or 1.
1097 else switch (contains_test(parents->item, want)) {
1099 commit->object.flags |= TMP_MARK;
1100 contains_stack.nr--;
1103 entry->parents = parents->next;
1105 case CONTAINS_UNKNOWN:
1106 push_to_contains_stack(parents->item, &contains_stack);
1110 free(contains_stack.contains_stack);
1111 return contains_test(candidate, want);
1114 static int commit_contains(struct ref_filter *filter, struct commit *commit)
1116 if (filter->with_commit_tag_algo)
1117 return contains_tag_algo(commit, filter->with_commit);
1118 return is_descendant_of(commit, filter->with_commit);
1122 * Return 1 if the refname matches one of the patterns, otherwise 0.
1123 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1124 * matches a pattern "refs/heads/") or a wildcard (e.g. the same ref
1125 * matches "refs/heads/m*",too).
1127 static int match_name_as_path(const char **pattern, const char *refname)
1129 int namelen = strlen(refname);
1130 for (; *pattern; pattern++) {
1131 const char *p = *pattern;
1132 int plen = strlen(p);
1134 if ((plen <= namelen) &&
1135 !strncmp(refname, p, plen) &&
1136 (refname[plen] == '\0' ||
1137 refname[plen] == '/' ||
1140 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1147 * Given a ref (sha1, refname), check if the ref belongs to the array
1148 * of sha1s. If the given ref is a tag, check if the given tag points
1149 * at one of the sha1s in the given sha1 array.
1150 * the given sha1_array.
1152 * 1. Only a single level of inderection is obtained, we might want to
1153 * change this to account for multiple levels (e.g. annotated tags
1154 * pointing to annotated tags pointing to a commit.)
1155 * 2. As the refs are cached we might know what refname peels to without
1156 * the need to parse the object via parse_object(). peel_ref() might be a
1157 * more efficient alternative to obtain the pointee.
1159 static const unsigned char *match_points_at(struct sha1_array *points_at,
1160 const unsigned char *sha1,
1161 const char *refname)
1163 const unsigned char *tagged_sha1 = NULL;
1166 if (sha1_array_lookup(points_at, sha1) >= 0)
1168 obj = parse_object(sha1);
1170 die(_("malformed object at '%s'"), refname);
1171 if (obj->type == OBJ_TAG)
1172 tagged_sha1 = ((struct tag *)obj)->tagged->sha1;
1173 if (tagged_sha1 && sha1_array_lookup(points_at, tagged_sha1) >= 0)
1178 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1179 static struct ref_array_item *new_ref_array_item(const char *refname,
1180 const unsigned char *objectname,
1183 size_t len = strlen(refname);
1184 struct ref_array_item *ref = xcalloc(1, sizeof(struct ref_array_item) + len + 1);
1185 memcpy(ref->refname, refname, len);
1186 ref->refname[len] = '\0';
1187 hashcpy(ref->objectname, objectname);
1193 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1201 { "refs/heads/" , FILTER_REFS_BRANCHES },
1202 { "refs/remotes/" , FILTER_REFS_REMOTES },
1203 { "refs/tags/", FILTER_REFS_TAGS}
1206 if (filter->kind == FILTER_REFS_BRANCHES ||
1207 filter->kind == FILTER_REFS_REMOTES ||
1208 filter->kind == FILTER_REFS_TAGS)
1209 return filter->kind;
1210 else if (!strcmp(refname, "HEAD"))
1211 return FILTER_REFS_DETACHED_HEAD;
1213 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1214 if (starts_with(refname, ref_kind[i].prefix))
1215 return ref_kind[i].kind;
1218 return FILTER_REFS_OTHERS;
1222 * A call-back given to for_each_ref(). Filter refs and keep them for
1223 * later object processing.
1225 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1227 struct ref_filter_cbdata *ref_cbdata = cb_data;
1228 struct ref_filter *filter = ref_cbdata->filter;
1229 struct ref_array_item *ref;
1230 struct commit *commit = NULL;
1233 if (flag & REF_BAD_NAME) {
1234 warning("ignoring ref with broken name %s", refname);
1238 if (flag & REF_ISBROKEN) {
1239 warning("ignoring broken ref %s", refname);
1243 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1244 kind = filter_ref_kind(filter, refname);
1245 if (!(kind & filter->kind))
1248 if (*filter->name_patterns && !match_name_as_path(filter->name_patterns, refname))
1251 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1255 * A merge filter is applied on refs pointing to commits. Hence
1256 * obtain the commit using the 'oid' available and discard all
1257 * non-commits early. The actual filtering is done later.
1259 if (filter->merge_commit || filter->with_commit) {
1260 commit = lookup_commit_reference_gently(oid->hash, 1);
1263 /* We perform the filtering for the '--contains' option */
1264 if (filter->with_commit &&
1265 !commit_contains(filter, commit))
1270 * We do not open the object yet; sort may only need refname
1271 * to do its job and the resulting list may yet to be pruned
1272 * by maxcount logic.
1274 ref = new_ref_array_item(refname, oid->hash, flag);
1275 ref->commit = commit;
1277 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1278 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1283 /* Free memory allocated for a ref_array_item */
1284 static void free_array_item(struct ref_array_item *item)
1286 free((char *)item->symref);
1290 /* Free all memory allocated for ref_array */
1291 void ref_array_clear(struct ref_array *array)
1295 for (i = 0; i < array->nr; i++)
1296 free_array_item(array->items[i]);
1298 array->items = NULL;
1299 array->nr = array->alloc = 0;
1302 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1304 struct rev_info revs;
1306 struct ref_filter *filter = ref_cbdata->filter;
1307 struct ref_array *array = ref_cbdata->array;
1308 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1310 init_revisions(&revs, NULL);
1312 for (i = 0; i < array->nr; i++) {
1313 struct ref_array_item *item = array->items[i];
1314 add_pending_object(&revs, &item->commit->object, item->refname);
1315 to_clear[i] = item->commit;
1318 filter->merge_commit->object.flags |= UNINTERESTING;
1319 add_pending_object(&revs, &filter->merge_commit->object, "");
1322 if (prepare_revision_walk(&revs))
1323 die(_("revision walk setup failed"));
1328 for (i = 0; i < old_nr; i++) {
1329 struct ref_array_item *item = array->items[i];
1330 struct commit *commit = item->commit;
1332 int is_merged = !!(commit->object.flags & UNINTERESTING);
1334 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1335 array->items[array->nr++] = array->items[i];
1337 free_array_item(item);
1340 for (i = 0; i < old_nr; i++)
1341 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1342 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1347 * API for filtering a set of refs. Based on the type of refs the user
1348 * has requested, we iterate through those refs and apply filters
1349 * as per the given ref_filter structure and finally store the
1350 * filtered refs in the ref_array structure.
1352 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1354 struct ref_filter_cbdata ref_cbdata;
1356 unsigned int broken = 0;
1358 ref_cbdata.array = array;
1359 ref_cbdata.filter = filter;
1361 if (type & FILTER_REFS_INCLUDE_BROKEN)
1363 filter->kind = type & FILTER_REFS_KIND_MASK;
1365 /* Simple per-ref filtering */
1367 die("filter_refs: invalid type");
1370 * For common cases where we need only branches or remotes or tags,
1371 * we only iterate through those refs. If a mix of refs is needed,
1372 * we iterate over all refs and filter out required refs with the help
1373 * of filter_ref_kind().
1375 if (filter->kind == FILTER_REFS_BRANCHES)
1376 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1377 else if (filter->kind == FILTER_REFS_REMOTES)
1378 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1379 else if (filter->kind == FILTER_REFS_TAGS)
1380 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1381 else if (filter->kind & FILTER_REFS_ALL)
1382 ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1383 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1384 head_ref(ref_filter_handler, &ref_cbdata);
1388 /* Filters that need revision walking */
1389 if (filter->merge_commit)
1390 do_merge_filter(&ref_cbdata);
1395 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1397 struct atom_value *va, *vb;
1399 cmp_type cmp_type = used_atom_type[s->atom];
1401 get_ref_atom_value(a, s->atom, &va);
1402 get_ref_atom_value(b, s->atom, &vb);
1405 cmp = strcmp(va->s, vb->s);
1408 if (va->ul < vb->ul)
1410 else if (va->ul == vb->ul)
1416 return (s->reverse) ? -cmp : cmp;
1419 static struct ref_sorting *ref_sorting;
1420 static int compare_refs(const void *a_, const void *b_)
1422 struct ref_array_item *a = *((struct ref_array_item **)a_);
1423 struct ref_array_item *b = *((struct ref_array_item **)b_);
1424 struct ref_sorting *s;
1426 for (s = ref_sorting; s; s = s->next) {
1427 int cmp = cmp_ref_sorting(s, a, b);
1434 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1436 ref_sorting = sorting;
1437 qsort(array->items, array->nr, sizeof(struct ref_array_item *), compare_refs);
1440 static int hex1(char ch)
1442 if ('0' <= ch && ch <= '9')
1444 else if ('a' <= ch && ch <= 'f')
1445 return ch - 'a' + 10;
1446 else if ('A' <= ch && ch <= 'F')
1447 return ch - 'A' + 10;
1450 static int hex2(const char *cp)
1453 return (hex1(cp[0]) << 4) | hex1(cp[1]);
1458 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1460 struct strbuf *s = &state->stack->output;
1462 while (*cp && (!ep || cp < ep)) {
1467 int ch = hex2(cp + 1);
1469 strbuf_addch(s, ch);
1475 strbuf_addch(s, *cp);
1480 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
1482 const char *cp, *sp, *ep;
1483 struct strbuf *final_buf;
1484 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1486 state.quote_style = quote_style;
1487 push_stack_element(&state.stack);
1489 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1490 struct atom_value *atomv;
1492 ep = strchr(sp, ')');
1494 append_literal(cp, sp, &state);
1495 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1496 atomv->handler(atomv, &state);
1499 sp = cp + strlen(cp);
1500 append_literal(cp, sp, &state);
1502 if (need_color_reset_at_eol) {
1503 struct atom_value resetv;
1504 char color[COLOR_MAXLEN] = "";
1506 if (color_parse("reset", color) < 0)
1507 die("BUG: couldn't parse 'reset' as a color");
1509 append_atom(&resetv, &state);
1511 if (state.stack->prev)
1512 die(_("format: %%(end) atom missing"));
1513 final_buf = &state.stack->output;
1514 fwrite(final_buf->buf, 1, final_buf->len, stdout);
1515 pop_stack_element(&state.stack);
1519 /* If no sorting option is given, use refname to sort as default */
1520 struct ref_sorting *ref_default_sorting(void)
1522 static const char cstr_name[] = "refname";
1524 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
1526 sorting->next = NULL;
1527 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
1531 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
1533 struct ref_sorting **sorting_tail = opt->value;
1534 struct ref_sorting *s;
1537 if (!arg) /* should --no-sort void the list ? */
1540 s = xcalloc(1, sizeof(*s));
1541 s->next = *sorting_tail;
1549 s->atom = parse_ref_filter_atom(arg, arg+len);
1553 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
1555 struct ref_filter *rf = opt->value;
1556 unsigned char sha1[20];
1558 rf->merge = starts_with(opt->long_name, "no")
1559 ? REF_FILTER_MERGED_OMIT
1560 : REF_FILTER_MERGED_INCLUDE;
1562 if (get_sha1(arg, sha1))
1563 die(_("malformed object name %s"), arg);
1565 rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
1566 if (!rf->merge_commit)
1567 return opterror(opt, "must point to a commit", 0);