3 #include "parse-options.h"
11 #include "ref-filter.h"
14 #include "git-compat-util.h"
17 #include "wt-status.h"
19 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
20 typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
28 cmp_status cmp_status;
30 unsigned int then_atom_seen : 1,
32 condition_satisfied : 1;
36 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
41 * An atom is a valid field atom listed below, possibly prefixed with
42 * a "*" to denote deref_tag().
44 * We parse given format string and sort specifiers, and make a list
45 * of properties that we need to extract out of objects. ref_array_item
46 * structure will hold an array of values extracted that can be
47 * indexed with the "atom number", which is an index into this
50 static struct used_atom {
54 char color[COLOR_MAXLEN];
57 enum { RR_REF, RR_TRACK, RR_TRACKSHORT } option;
58 struct refname_atom refname;
59 unsigned int nobracket : 1;
62 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
66 cmp_status cmp_status;
70 enum { O_FULL, O_LENGTH, O_SHORT } option;
73 struct refname_atom refname;
76 static int used_atom_cnt, need_tagged, need_symref;
77 static int need_color_reset_at_eol;
79 static void color_atom_parser(struct used_atom *atom, const char *color_value)
82 die(_("expected format: %%(color:<color>)"));
83 if (color_parse(color_value, atom->u.color) < 0)
84 die(_("unrecognized color: %%(color:%s)"), color_value);
87 static void refname_atom_parser_internal(struct refname_atom *atom,
88 const char *arg, const char *name)
91 atom->option = R_NORMAL;
92 else if (!strcmp(arg, "short"))
93 atom->option = R_SHORT;
94 else if (skip_prefix(arg, "lstrip=", &arg)) {
95 atom->option = R_LSTRIP;
96 if (strtol_i(arg, 10, &atom->lstrip))
97 die(_("Integer value expected refname:lstrip=%s"), arg);
98 } else if (skip_prefix(arg, "rstrip=", &arg)) {
99 atom->option = R_RSTRIP;
100 if (strtol_i(arg, 10, &atom->rstrip))
101 die(_("Integer value expected refname:rstrip=%s"), arg);
103 die(_("unrecognized %%(%s) argument: %s"), name, arg);
106 static void remote_ref_atom_parser(struct used_atom *atom, const char *arg)
108 struct string_list params = STRING_LIST_INIT_DUP;
112 atom->u.remote_ref.option = RR_REF;
113 refname_atom_parser_internal(&atom->u.remote_ref.refname,
118 atom->u.remote_ref.nobracket = 0;
119 string_list_split(¶ms, arg, ',', -1);
121 for (i = 0; i < params.nr; i++) {
122 const char *s = params.items[i].string;
124 if (!strcmp(s, "track"))
125 atom->u.remote_ref.option = RR_TRACK;
126 else if (!strcmp(s, "trackshort"))
127 atom->u.remote_ref.option = RR_TRACKSHORT;
128 else if (!strcmp(s, "nobracket"))
129 atom->u.remote_ref.nobracket = 1;
131 atom->u.remote_ref.option = RR_REF;
132 refname_atom_parser_internal(&atom->u.remote_ref.refname,
137 string_list_clear(¶ms, 0);
140 static void body_atom_parser(struct used_atom *atom, const char *arg)
143 die(_("%%(body) does not take arguments"));
144 atom->u.contents.option = C_BODY_DEP;
147 static void subject_atom_parser(struct used_atom *atom, const char *arg)
150 die(_("%%(subject) does not take arguments"));
151 atom->u.contents.option = C_SUB;
154 static void trailers_atom_parser(struct used_atom *atom, const char *arg)
157 die(_("%%(trailers) does not take arguments"));
158 atom->u.contents.option = C_TRAILERS;
161 static void contents_atom_parser(struct used_atom *atom, const char *arg)
164 atom->u.contents.option = C_BARE;
165 else if (!strcmp(arg, "body"))
166 atom->u.contents.option = C_BODY;
167 else if (!strcmp(arg, "signature"))
168 atom->u.contents.option = C_SIG;
169 else if (!strcmp(arg, "subject"))
170 atom->u.contents.option = C_SUB;
171 else if (!strcmp(arg, "trailers"))
172 atom->u.contents.option = C_TRAILERS;
173 else if (skip_prefix(arg, "lines=", &arg)) {
174 atom->u.contents.option = C_LINES;
175 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
176 die(_("positive value expected contents:lines=%s"), arg);
178 die(_("unrecognized %%(contents) argument: %s"), arg);
181 static void objectname_atom_parser(struct used_atom *atom, const char *arg)
184 atom->u.objectname.option = O_FULL;
185 else if (!strcmp(arg, "short"))
186 atom->u.objectname.option = O_SHORT;
187 else if (skip_prefix(arg, "short=", &arg)) {
188 atom->u.objectname.option = O_LENGTH;
189 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
190 atom->u.objectname.length == 0)
191 die(_("positive value expected objectname:short=%s"), arg);
192 if (atom->u.objectname.length < MINIMUM_ABBREV)
193 atom->u.objectname.length = MINIMUM_ABBREV;
195 die(_("unrecognized %%(objectname) argument: %s"), arg);
198 static void refname_atom_parser(struct used_atom *atom, const char *arg)
200 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
203 static align_type parse_align_position(const char *s)
205 if (!strcmp(s, "right"))
207 else if (!strcmp(s, "middle"))
209 else if (!strcmp(s, "left"))
214 static void align_atom_parser(struct used_atom *atom, const char *arg)
216 struct align *align = &atom->u.align;
217 struct string_list params = STRING_LIST_INIT_DUP;
219 unsigned int width = ~0U;
222 die(_("expected format: %%(align:<width>,<position>)"));
224 align->position = ALIGN_LEFT;
226 string_list_split(¶ms, arg, ',', -1);
227 for (i = 0; i < params.nr; i++) {
228 const char *s = params.items[i].string;
231 if (skip_prefix(s, "position=", &s)) {
232 position = parse_align_position(s);
234 die(_("unrecognized position:%s"), s);
235 align->position = position;
236 } else if (skip_prefix(s, "width=", &s)) {
237 if (strtoul_ui(s, 10, &width))
238 die(_("unrecognized width:%s"), s);
239 } else if (!strtoul_ui(s, 10, &width))
241 else if ((position = parse_align_position(s)) >= 0)
242 align->position = position;
244 die(_("unrecognized %%(align) argument: %s"), s);
248 die(_("positive width expected with the %%(align) atom"));
249 align->width = width;
250 string_list_clear(¶ms, 0);
253 static void if_atom_parser(struct used_atom *atom, const char *arg)
256 atom->u.if_then_else.cmp_status = COMPARE_NONE;
258 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
259 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
260 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
261 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
263 die(_("unrecognized %%(if) argument: %s"), arg);
271 void (*parser)(struct used_atom *atom, const char *arg);
273 { "refname" , FIELD_STR, refname_atom_parser },
275 { "objectsize", FIELD_ULONG },
276 { "objectname", FIELD_STR, objectname_atom_parser },
279 { "numparent", FIELD_ULONG },
286 { "authordate", FIELD_TIME },
289 { "committeremail" },
290 { "committerdate", FIELD_TIME },
294 { "taggerdate", FIELD_TIME },
296 { "creatordate", FIELD_TIME },
297 { "subject", FIELD_STR, subject_atom_parser },
298 { "body", FIELD_STR, body_atom_parser },
299 { "trailers", FIELD_STR, trailers_atom_parser },
300 { "contents", FIELD_STR, contents_atom_parser },
301 { "upstream", FIELD_STR, remote_ref_atom_parser },
302 { "push", FIELD_STR, remote_ref_atom_parser },
303 { "symref", FIELD_STR, refname_atom_parser },
306 { "color", FIELD_STR, color_atom_parser },
307 { "align", FIELD_STR, align_atom_parser },
309 { "if", FIELD_STR, if_atom_parser },
314 #define REF_FORMATTING_STATE_INIT { 0, NULL }
316 struct ref_formatting_stack {
317 struct ref_formatting_stack *prev;
318 struct strbuf output;
319 void (*at_end)(struct ref_formatting_stack **stack);
323 struct ref_formatting_state {
325 struct ref_formatting_stack *stack;
330 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
331 unsigned long ul; /* used for sorting when not FIELD_STR */
332 struct used_atom *atom;
336 * Used to parse format string and sort specifiers
338 int parse_ref_filter_atom(const char *atom, const char *ep)
345 if (*sp == '*' && sp < ep)
348 die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
350 /* Do we have the atom already used elsewhere? */
351 for (i = 0; i < used_atom_cnt; i++) {
352 int len = strlen(used_atom[i].name);
353 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
358 * If the atom name has a colon, strip it and everything after
359 * it off - it specifies the format for this entry, and
360 * shouldn't be used for checking against the valid_atom
363 arg = memchr(sp, ':', ep - sp);
364 atom_len = (arg ? arg : ep) - sp;
366 /* Is the atom a valid one? */
367 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
368 int len = strlen(valid_atom[i].name);
369 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
373 if (ARRAY_SIZE(valid_atom) <= i)
374 die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
376 /* Add it in, including the deref prefix */
379 REALLOC_ARRAY(used_atom, used_atom_cnt);
380 used_atom[at].name = xmemdupz(atom, ep - atom);
381 used_atom[at].type = valid_atom[i].cmp_type;
383 arg = used_atom[at].name + (arg - atom) + 1;
384 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
385 if (valid_atom[i].parser)
386 valid_atom[i].parser(&used_atom[at], arg);
389 if (!strcmp(valid_atom[i].name, "symref"))
394 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
396 switch (quote_style) {
398 strbuf_addstr(s, str);
401 sq_quote_buf(s, str);
404 perl_quote_buf(s, str);
407 python_quote_buf(s, str);
410 tcl_quote_buf(s, str);
415 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
418 * Quote formatting is only done when the stack has a single
419 * element. Otherwise quote formatting is done on the
420 * element's entire output strbuf when the %(end) atom is
423 if (!state->stack->prev)
424 quote_formatting(&state->stack->output, v->s, state->quote_style);
426 strbuf_addstr(&state->stack->output, v->s);
429 static void push_stack_element(struct ref_formatting_stack **stack)
431 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
433 strbuf_init(&s->output, 0);
438 static void pop_stack_element(struct ref_formatting_stack **stack)
440 struct ref_formatting_stack *current = *stack;
441 struct ref_formatting_stack *prev = current->prev;
444 strbuf_addbuf(&prev->output, ¤t->output);
445 strbuf_release(¤t->output);
450 static void end_align_handler(struct ref_formatting_stack **stack)
452 struct ref_formatting_stack *cur = *stack;
453 struct align *align = (struct align *)cur->at_end_data;
454 struct strbuf s = STRBUF_INIT;
456 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
457 strbuf_swap(&cur->output, &s);
461 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
463 struct ref_formatting_stack *new;
465 push_stack_element(&state->stack);
467 new->at_end = end_align_handler;
468 new->at_end_data = &atomv->atom->u.align;
471 static void if_then_else_handler(struct ref_formatting_stack **stack)
473 struct ref_formatting_stack *cur = *stack;
474 struct ref_formatting_stack *prev = cur->prev;
475 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
477 if (!if_then_else->then_atom_seen)
478 die(_("format: %%(if) atom used without a %%(then) atom"));
480 if (if_then_else->else_atom_seen) {
482 * There is an %(else) atom: we need to drop one state from the
483 * stack, either the %(else) branch if the condition is satisfied, or
484 * the %(then) branch if it isn't.
486 if (if_then_else->condition_satisfied) {
487 strbuf_reset(&cur->output);
488 pop_stack_element(&cur);
490 strbuf_swap(&cur->output, &prev->output);
491 strbuf_reset(&cur->output);
492 pop_stack_element(&cur);
494 } else if (!if_then_else->condition_satisfied) {
496 * No %(else) atom: just drop the %(then) branch if the
497 * condition is not satisfied.
499 strbuf_reset(&cur->output);
506 static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
508 struct ref_formatting_stack *new;
509 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
511 if_then_else->str = atomv->atom->u.if_then_else.str;
512 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
514 push_stack_element(&state->stack);
516 new->at_end = if_then_else_handler;
517 new->at_end_data = if_then_else;
520 static int is_empty(const char *s)
530 static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
532 struct ref_formatting_stack *cur = state->stack;
533 struct if_then_else *if_then_else = NULL;
535 if (cur->at_end == if_then_else_handler)
536 if_then_else = (struct if_then_else *)cur->at_end_data;
538 die(_("format: %%(then) atom used without an %%(if) atom"));
539 if (if_then_else->then_atom_seen)
540 die(_("format: %%(then) atom used more than once"));
541 if (if_then_else->else_atom_seen)
542 die(_("format: %%(then) atom used after %%(else)"));
543 if_then_else->then_atom_seen = 1;
545 * If the 'equals' or 'notequals' attribute is used then
546 * perform the required comparison. If not, only non-empty
547 * strings satisfy the 'if' condition.
549 if (if_then_else->cmp_status == COMPARE_EQUAL) {
550 if (!strcmp(if_then_else->str, cur->output.buf))
551 if_then_else->condition_satisfied = 1;
552 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
553 if (strcmp(if_then_else->str, cur->output.buf))
554 if_then_else->condition_satisfied = 1;
555 } else if (cur->output.len && !is_empty(cur->output.buf))
556 if_then_else->condition_satisfied = 1;
557 strbuf_reset(&cur->output);
560 static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
562 struct ref_formatting_stack *prev = state->stack;
563 struct if_then_else *if_then_else = NULL;
565 if (prev->at_end == if_then_else_handler)
566 if_then_else = (struct if_then_else *)prev->at_end_data;
568 die(_("format: %%(else) atom used without an %%(if) atom"));
569 if (!if_then_else->then_atom_seen)
570 die(_("format: %%(else) atom used without a %%(then) atom"));
571 if (if_then_else->else_atom_seen)
572 die(_("format: %%(else) atom used more than once"));
573 if_then_else->else_atom_seen = 1;
574 push_stack_element(&state->stack);
575 state->stack->at_end_data = prev->at_end_data;
576 state->stack->at_end = prev->at_end;
579 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
581 struct ref_formatting_stack *current = state->stack;
582 struct strbuf s = STRBUF_INIT;
584 if (!current->at_end)
585 die(_("format: %%(end) atom used without corresponding atom"));
586 current->at_end(&state->stack);
588 /* Stack may have been popped within at_end(), hence reset the current pointer */
589 current = state->stack;
592 * Perform quote formatting when the stack element is that of
593 * a supporting atom. If nested then perform quote formatting
594 * only on the topmost supporting atom.
596 if (!current->prev->prev) {
597 quote_formatting(&s, current->output.buf, state->quote_style);
598 strbuf_swap(¤t->output, &s);
601 pop_stack_element(&state->stack);
605 * In a format string, find the next occurrence of %(atom).
607 static const char *find_next(const char *cp)
612 * %( is the start of an atom;
613 * %% is a quoted per-cent.
617 else if (cp[1] == '%')
618 cp++; /* skip over two % */
619 /* otherwise this is a singleton, literal % */
627 * Make sure the format string is well formed, and parse out
630 int verify_ref_format(const char *format)
634 need_color_reset_at_eol = 0;
635 for (cp = format; *cp && (sp = find_next(cp)); ) {
636 const char *color, *ep = strchr(sp, ')');
640 return error(_("malformed format string %s"), sp);
641 /* sp points at "%(" and ep points at the closing ")" */
642 at = parse_ref_filter_atom(sp + 2, ep);
645 if (skip_prefix(used_atom[at].name, "color:", &color))
646 need_color_reset_at_eol = !!strcmp(color, "reset");
652 * Given an object name, read the object data and size, and return a
653 * "struct object". If the object data we are returning is also borrowed
654 * by the "struct object" representation, set *eaten as well---it is a
655 * signal from parse_object_buffer to us not to free the buffer.
657 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
659 enum object_type type;
660 void *buf = read_sha1_file(sha1, &type, sz);
663 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
669 static int grab_objectname(const char *name, const unsigned char *sha1,
670 struct atom_value *v, struct used_atom *atom)
672 if (starts_with(name, "objectname")) {
673 if (atom->u.objectname.option == O_SHORT) {
674 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
676 } else if (atom->u.objectname.option == O_FULL) {
677 v->s = xstrdup(sha1_to_hex(sha1));
679 } else if (atom->u.objectname.option == O_LENGTH) {
680 v->s = xstrdup(find_unique_abbrev(sha1, atom->u.objectname.length));
683 die("BUG: unknown %%(objectname) option");
688 /* See grab_values */
689 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
693 for (i = 0; i < used_atom_cnt; i++) {
694 const char *name = used_atom[i].name;
695 struct atom_value *v = &val[i];
696 if (!!deref != (*name == '*'))
700 if (!strcmp(name, "objecttype"))
701 v->s = typename(obj->type);
702 else if (!strcmp(name, "objectsize")) {
704 v->s = xstrfmt("%lu", sz);
707 grab_objectname(name, obj->oid.hash, v, &used_atom[i]);
711 /* See grab_values */
712 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
715 struct tag *tag = (struct tag *) obj;
717 for (i = 0; i < used_atom_cnt; i++) {
718 const char *name = used_atom[i].name;
719 struct atom_value *v = &val[i];
720 if (!!deref != (*name == '*'))
724 if (!strcmp(name, "tag"))
726 else if (!strcmp(name, "type") && tag->tagged)
727 v->s = typename(tag->tagged->type);
728 else if (!strcmp(name, "object") && tag->tagged)
729 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
733 /* See grab_values */
734 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
737 struct commit *commit = (struct commit *) obj;
739 for (i = 0; i < used_atom_cnt; i++) {
740 const char *name = used_atom[i].name;
741 struct atom_value *v = &val[i];
742 if (!!deref != (*name == '*'))
746 if (!strcmp(name, "tree")) {
747 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
749 else if (!strcmp(name, "numparent")) {
750 v->ul = commit_list_count(commit->parents);
751 v->s = xstrfmt("%lu", v->ul);
753 else if (!strcmp(name, "parent")) {
754 struct commit_list *parents;
755 struct strbuf s = STRBUF_INIT;
756 for (parents = commit->parents; parents; parents = parents->next) {
757 struct commit *parent = parents->item;
758 if (parents != commit->parents)
759 strbuf_addch(&s, ' ');
760 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
762 v->s = strbuf_detach(&s, NULL);
767 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
771 if (!strncmp(buf, who, wholen) &&
773 return buf + wholen + 1;
774 eol = strchr(buf, '\n');
779 return ""; /* end of header */
785 static const char *copy_line(const char *buf)
787 const char *eol = strchrnul(buf, '\n');
788 return xmemdupz(buf, eol - buf);
791 static const char *copy_name(const char *buf)
794 for (cp = buf; *cp && *cp != '\n'; cp++) {
795 if (!strncmp(cp, " <", 2))
796 return xmemdupz(buf, cp - buf);
801 static const char *copy_email(const char *buf)
803 const char *email = strchr(buf, '<');
807 eoemail = strchr(email, '>');
810 return xmemdupz(email, eoemail + 1 - email);
813 static char *copy_subject(const char *buf, unsigned long len)
815 char *r = xmemdupz(buf, len);
818 for (i = 0; i < len; i++)
825 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
827 const char *eoemail = strstr(buf, "> ");
829 unsigned long timestamp;
831 struct date_mode date_mode = { DATE_NORMAL };
835 * We got here because atomname ends in "date" or "date<something>";
836 * it's not possible that <something> is not ":<format>" because
837 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
838 * ":" means no format is specified, and use the default.
840 formatp = strchr(atomname, ':');
841 if (formatp != NULL) {
843 parse_date_format(formatp, &date_mode);
848 timestamp = strtoul(eoemail + 2, &zone, 10);
849 if (timestamp == ULONG_MAX)
851 tz = strtol(zone, NULL, 10);
852 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
854 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
862 /* See grab_values */
863 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
866 int wholen = strlen(who);
867 const char *wholine = NULL;
869 for (i = 0; i < used_atom_cnt; i++) {
870 const char *name = used_atom[i].name;
871 struct atom_value *v = &val[i];
872 if (!!deref != (*name == '*'))
876 if (strncmp(who, name, wholen))
878 if (name[wholen] != 0 &&
879 strcmp(name + wholen, "name") &&
880 strcmp(name + wholen, "email") &&
881 !starts_with(name + wholen, "date"))
884 wholine = find_wholine(who, wholen, buf, sz);
886 return; /* no point looking for it */
887 if (name[wholen] == 0)
888 v->s = copy_line(wholine);
889 else if (!strcmp(name + wholen, "name"))
890 v->s = copy_name(wholine);
891 else if (!strcmp(name + wholen, "email"))
892 v->s = copy_email(wholine);
893 else if (starts_with(name + wholen, "date"))
894 grab_date(wholine, v, name);
898 * For a tag or a commit object, if "creator" or "creatordate" is
899 * requested, do something special.
901 if (strcmp(who, "tagger") && strcmp(who, "committer"))
902 return; /* "author" for commit object is not wanted */
904 wholine = find_wholine(who, wholen, buf, sz);
907 for (i = 0; i < used_atom_cnt; i++) {
908 const char *name = used_atom[i].name;
909 struct atom_value *v = &val[i];
910 if (!!deref != (*name == '*'))
915 if (starts_with(name, "creatordate"))
916 grab_date(wholine, v, name);
917 else if (!strcmp(name, "creator"))
918 v->s = copy_line(wholine);
922 static void find_subpos(const char *buf, unsigned long sz,
923 const char **sub, unsigned long *sublen,
924 const char **body, unsigned long *bodylen,
925 unsigned long *nonsiglen,
926 const char **sig, unsigned long *siglen)
929 /* skip past header until we hit empty line */
930 while (*buf && *buf != '\n') {
931 eol = strchrnul(buf, '\n');
936 /* skip any empty lines */
940 /* parse signature first; we might not even have a subject line */
941 *sig = buf + parse_signature(buf, strlen(buf));
942 *siglen = strlen(*sig);
944 /* subject is first non-empty line */
946 /* subject goes to first empty line */
947 while (buf < *sig && *buf && *buf != '\n') {
948 eol = strchrnul(buf, '\n');
953 *sublen = buf - *sub;
954 /* drop trailing newline, if present */
955 if (*sublen && (*sub)[*sublen - 1] == '\n')
958 /* skip any empty lines */
962 *bodylen = strlen(buf);
963 *nonsiglen = *sig - buf;
967 * If 'lines' is greater than 0, append that many lines from the given
968 * 'buf' of length 'size' to the given strbuf.
970 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
973 const char *sp, *eol;
978 for (i = 0; i < lines && sp < buf + size; i++) {
980 strbuf_addstr(out, "\n ");
981 eol = memchr(sp, '\n', size - (sp - buf));
982 len = eol ? eol - sp : size - (sp - buf);
983 strbuf_add(out, sp, len);
990 /* See grab_values */
991 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
994 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
995 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
997 for (i = 0; i < used_atom_cnt; i++) {
998 struct used_atom *atom = &used_atom[i];
999 const char *name = atom->name;
1000 struct atom_value *v = &val[i];
1001 if (!!deref != (*name == '*'))
1005 if (strcmp(name, "subject") &&
1006 strcmp(name, "body") &&
1007 strcmp(name, "trailers") &&
1008 !starts_with(name, "contents"))
1011 find_subpos(buf, sz,
1013 &bodypos, &bodylen, &nonsiglen,
1016 if (atom->u.contents.option == C_SUB)
1017 v->s = copy_subject(subpos, sublen);
1018 else if (atom->u.contents.option == C_BODY_DEP)
1019 v->s = xmemdupz(bodypos, bodylen);
1020 else if (atom->u.contents.option == C_BODY)
1021 v->s = xmemdupz(bodypos, nonsiglen);
1022 else if (atom->u.contents.option == C_SIG)
1023 v->s = xmemdupz(sigpos, siglen);
1024 else if (atom->u.contents.option == C_LINES) {
1025 struct strbuf s = STRBUF_INIT;
1026 const char *contents_end = bodylen + bodypos - siglen;
1028 /* Size is the length of the message after removing the signature */
1029 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1030 v->s = strbuf_detach(&s, NULL);
1031 } else if (atom->u.contents.option == C_TRAILERS) {
1032 struct trailer_info info;
1034 /* Search for trailer info */
1035 trailer_info_get(&info, subpos);
1036 v->s = xmemdupz(info.trailer_start,
1037 info.trailer_end - info.trailer_start);
1038 trailer_info_release(&info);
1039 } else if (atom->u.contents.option == C_BARE)
1040 v->s = xstrdup(subpos);
1045 * We want to have empty print-string for field requests
1046 * that do not apply (e.g. "authordate" for a tag object)
1048 static void fill_missing_values(struct atom_value *val)
1051 for (i = 0; i < used_atom_cnt; i++) {
1052 struct atom_value *v = &val[i];
1059 * val is a list of atom_value to hold returned values. Extract
1060 * the values for atoms in used_atom array out of (obj, buf, sz).
1061 * when deref is false, (obj, buf, sz) is the object that is
1062 * pointed at by the ref itself; otherwise it is the object the
1063 * ref (which is a tag) refers to.
1065 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1067 grab_common_values(val, deref, obj, buf, sz);
1068 switch (obj->type) {
1070 grab_tag_values(val, deref, obj, buf, sz);
1071 grab_sub_body_contents(val, deref, obj, buf, sz);
1072 grab_person("tagger", val, deref, obj, buf, sz);
1075 grab_commit_values(val, deref, obj, buf, sz);
1076 grab_sub_body_contents(val, deref, obj, buf, sz);
1077 grab_person("author", val, deref, obj, buf, sz);
1078 grab_person("committer", val, deref, obj, buf, sz);
1081 /* grab_tree_values(val, deref, obj, buf, sz); */
1084 /* grab_blob_values(val, deref, obj, buf, sz); */
1087 die("Eh? Object of type %d?", obj->type);
1091 static inline char *copy_advance(char *dst, const char *src)
1098 static const char *lstrip_ref_components(const char *refname, int len)
1100 long remaining = len;
1101 const char *start = refname;
1105 const char *p = refname;
1107 /* Find total no of '/' separated path-components */
1108 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1111 * The number of components we need to strip is now
1112 * the total minus the components to be left (Plus one
1113 * because we count the number of '/', but the number
1114 * of components is one more than the no of '/').
1116 remaining = i + len + 1;
1119 while (remaining > 0) {
1132 static const char *rstrip_ref_components(const char *refname, int len)
1134 long remaining = len;
1135 char *start = xstrdup(refname);
1139 const char *p = refname;
1141 /* Find total no of '/' separated path-components */
1142 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1145 * The number of components we need to strip is now
1146 * the total minus the components to be left (Plus one
1147 * because we count the number of '/', but the number
1148 * of components is one more than the no of '/').
1150 remaining = i + len + 1;
1153 while (remaining-- > 0) {
1154 char *p = strrchr(start, '/');
1163 static const char *show_ref(struct refname_atom *atom, const char *refname)
1165 if (atom->option == R_SHORT)
1166 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
1167 else if (atom->option == R_LSTRIP)
1168 return lstrip_ref_components(refname, atom->lstrip);
1169 else if (atom->option == R_RSTRIP)
1170 return rstrip_ref_components(refname, atom->rstrip);
1175 static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1176 struct branch *branch, const char **s)
1178 int num_ours, num_theirs;
1179 if (atom->u.remote_ref.option == RR_REF)
1180 *s = show_ref(&atom->u.remote_ref.refname, refname);
1181 else if (atom->u.remote_ref.option == RR_TRACK) {
1182 if (stat_tracking_info(branch, &num_ours,
1183 &num_theirs, NULL)) {
1184 *s = xstrdup("gone");
1185 } else if (!num_ours && !num_theirs)
1188 *s = xstrfmt("behind %d", num_theirs);
1189 else if (!num_theirs)
1190 *s = xstrfmt("ahead %d", num_ours);
1192 *s = xstrfmt("ahead %d, behind %d",
1193 num_ours, num_theirs);
1194 if (!atom->u.remote_ref.nobracket && *s[0]) {
1195 const char *to_free = *s;
1196 *s = xstrfmt("[%s]", *s);
1197 free((void *)to_free);
1199 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
1200 if (stat_tracking_info(branch, &num_ours,
1204 if (!num_ours && !num_theirs)
1208 else if (!num_theirs)
1213 die("BUG: unhandled RR_* enum");
1216 char *get_head_description(void)
1218 struct strbuf desc = STRBUF_INIT;
1219 struct wt_status_state state;
1220 memset(&state, 0, sizeof(state));
1221 wt_status_get_state(&state, 1);
1222 if (state.rebase_in_progress ||
1223 state.rebase_interactive_in_progress)
1224 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1226 else if (state.bisect_in_progress)
1227 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1229 else if (state.detached_from) {
1230 /* TRANSLATORS: make sure these match _("HEAD detached at ")
1231 and _("HEAD detached from ") in wt-status.c */
1232 if (state.detached_at)
1233 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1234 state.detached_from);
1236 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1237 state.detached_from);
1240 strbuf_addstr(&desc, _("(no branch)"));
1243 free(state.detached_from);
1244 return strbuf_detach(&desc, NULL);
1247 static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1252 return show_ref(&atom->u.refname, ref->symref);
1255 static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1257 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1258 return get_head_description();
1259 return show_ref(&atom->u.refname, ref->refname);
1263 * Parse the object referred by ref, and grab needed value.
1265 static void populate_value(struct ref_array_item *ref)
1271 const unsigned char *tagged;
1273 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1275 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1276 unsigned char unused1[20];
1277 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1283 /* Fill in specials first */
1284 for (i = 0; i < used_atom_cnt; i++) {
1285 struct used_atom *atom = &used_atom[i];
1286 const char *name = used_atom[i].name;
1287 struct atom_value *v = &ref->value[i];
1289 const char *refname;
1290 struct branch *branch = NULL;
1292 v->handler = append_atom;
1300 if (starts_with(name, "refname"))
1301 refname = get_refname(atom, ref);
1302 else if (starts_with(name, "symref"))
1303 refname = get_symref(atom, ref);
1304 else if (starts_with(name, "upstream")) {
1305 const char *branch_name;
1306 /* only local branches may have an upstream */
1307 if (!skip_prefix(ref->refname, "refs/heads/",
1310 branch = branch_get(branch_name);
1312 refname = branch_get_upstream(branch, NULL);
1314 fill_remote_ref_details(atom, refname, branch, &v->s);
1316 } else if (starts_with(name, "push")) {
1317 const char *branch_name;
1318 if (!skip_prefix(ref->refname, "refs/heads/",
1321 branch = branch_get(branch_name);
1323 refname = branch_get_push(branch, NULL);
1326 fill_remote_ref_details(atom, refname, branch, &v->s);
1328 } else if (starts_with(name, "color:")) {
1329 v->s = atom->u.color;
1331 } else if (!strcmp(name, "flag")) {
1332 char buf[256], *cp = buf;
1333 if (ref->flag & REF_ISSYMREF)
1334 cp = copy_advance(cp, ",symref");
1335 if (ref->flag & REF_ISPACKED)
1336 cp = copy_advance(cp, ",packed");
1341 v->s = xstrdup(buf + 1);
1344 } else if (!deref && grab_objectname(name, ref->objectname, v, atom)) {
1346 } else if (!strcmp(name, "HEAD")) {
1348 unsigned char sha1[20];
1350 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1352 if (head && !strcmp(ref->refname, head))
1357 } else if (starts_with(name, "align")) {
1358 v->handler = align_atom_handler;
1360 } else if (!strcmp(name, "end")) {
1361 v->handler = end_atom_handler;
1363 } else if (starts_with(name, "if")) {
1366 if (skip_prefix(name, "if:", &s))
1368 v->handler = if_atom_handler;
1370 } else if (!strcmp(name, "then")) {
1371 v->handler = then_atom_handler;
1373 } else if (!strcmp(name, "else")) {
1374 v->handler = else_atom_handler;
1382 v->s = xstrfmt("%s^{}", refname);
1385 for (i = 0; i < used_atom_cnt; i++) {
1386 struct atom_value *v = &ref->value[i];
1393 buf = get_obj(ref->objectname, &obj, &size, &eaten);
1395 die(_("missing object %s for %s"),
1396 sha1_to_hex(ref->objectname), ref->refname);
1398 die(_("parse_object_buffer failed on %s for %s"),
1399 sha1_to_hex(ref->objectname), ref->refname);
1401 grab_values(ref->value, 0, obj, buf, size);
1406 * If there is no atom that wants to know about tagged
1407 * object, we are done.
1409 if (!need_tagged || (obj->type != OBJ_TAG))
1413 * If it is a tag object, see if we use a value that derefs
1414 * the object, and if we do grab the object it refers to.
1416 tagged = ((struct tag *)obj)->tagged->oid.hash;
1419 * NEEDSWORK: This derefs tag only once, which
1420 * is good to deal with chains of trust, but
1421 * is not consistent with what deref_tag() does
1422 * which peels the onion to the core.
1424 buf = get_obj(tagged, &obj, &size, &eaten);
1426 die(_("missing object %s for %s"),
1427 sha1_to_hex(tagged), ref->refname);
1429 die(_("parse_object_buffer failed on %s for %s"),
1430 sha1_to_hex(tagged), ref->refname);
1431 grab_values(ref->value, 1, obj, buf, size);
1437 * Given a ref, return the value for the atom. This lazily gets value
1438 * out of the object by calling populate value.
1440 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1443 populate_value(ref);
1444 fill_missing_values(ref->value);
1446 *v = &ref->value[atom];
1449 enum contains_result {
1450 CONTAINS_UNKNOWN = -1,
1456 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1459 * At each recursion step, the stack items points to the commits whose
1460 * ancestors are to be inspected.
1462 struct contains_stack {
1464 struct contains_stack_entry {
1465 struct commit *commit;
1466 struct commit_list *parents;
1470 static int in_commit_list(const struct commit_list *want, struct commit *c)
1472 for (; want; want = want->next)
1473 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1479 * Test whether the candidate or one of its parents is contained in the list.
1480 * Do not recurse to find out, though, but return -1 if inconclusive.
1482 static enum contains_result contains_test(struct commit *candidate,
1483 const struct commit_list *want)
1485 /* was it previously marked as containing a want commit? */
1486 if (candidate->object.flags & TMP_MARK)
1488 /* or marked as not possibly containing a want commit? */
1489 if (candidate->object.flags & UNINTERESTING)
1492 if (in_commit_list(want, candidate)) {
1493 candidate->object.flags |= TMP_MARK;
1497 if (parse_commit(candidate) < 0)
1503 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1505 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1506 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1507 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1510 static enum contains_result contains_tag_algo(struct commit *candidate,
1511 const struct commit_list *want)
1513 struct contains_stack contains_stack = { 0, 0, NULL };
1514 int result = contains_test(candidate, want);
1516 if (result != CONTAINS_UNKNOWN)
1519 push_to_contains_stack(candidate, &contains_stack);
1520 while (contains_stack.nr) {
1521 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1522 struct commit *commit = entry->commit;
1523 struct commit_list *parents = entry->parents;
1526 commit->object.flags |= UNINTERESTING;
1527 contains_stack.nr--;
1530 * If we just popped the stack, parents->item has been marked,
1531 * therefore contains_test will return a meaningful 0 or 1.
1533 else switch (contains_test(parents->item, want)) {
1535 commit->object.flags |= TMP_MARK;
1536 contains_stack.nr--;
1539 entry->parents = parents->next;
1541 case CONTAINS_UNKNOWN:
1542 push_to_contains_stack(parents->item, &contains_stack);
1546 free(contains_stack.contains_stack);
1547 return contains_test(candidate, want);
1550 static int commit_contains(struct ref_filter *filter, struct commit *commit)
1552 if (filter->with_commit_tag_algo)
1553 return contains_tag_algo(commit, filter->with_commit);
1554 return is_descendant_of(commit, filter->with_commit);
1558 * Return 1 if the refname matches one of the patterns, otherwise 0.
1559 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1560 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1561 * matches "refs/heads/mas*", too).
1563 static int match_pattern(const struct ref_filter *filter, const char *refname)
1565 const char **patterns = filter->name_patterns;
1568 if (filter->ignore_case)
1569 flags |= WM_CASEFOLD;
1572 * When no '--format' option is given we need to skip the prefix
1573 * for matching refs of tags and branches.
1575 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1576 skip_prefix(refname, "refs/heads/", &refname) ||
1577 skip_prefix(refname, "refs/remotes/", &refname) ||
1578 skip_prefix(refname, "refs/", &refname));
1580 for (; *patterns; patterns++) {
1581 if (!wildmatch(*patterns, refname, flags, NULL))
1588 * Return 1 if the refname matches one of the patterns, otherwise 0.
1589 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1590 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1591 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1593 static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1595 const char **pattern = filter->name_patterns;
1596 int namelen = strlen(refname);
1597 unsigned flags = WM_PATHNAME;
1599 if (filter->ignore_case)
1600 flags |= WM_CASEFOLD;
1602 for (; *pattern; pattern++) {
1603 const char *p = *pattern;
1604 int plen = strlen(p);
1606 if ((plen <= namelen) &&
1607 !strncmp(refname, p, plen) &&
1608 (refname[plen] == '\0' ||
1609 refname[plen] == '/' ||
1612 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1618 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1619 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1621 if (!*filter->name_patterns)
1622 return 1; /* No pattern always matches */
1623 if (filter->match_as_path)
1624 return match_name_as_path(filter, refname);
1625 return match_pattern(filter, refname);
1629 * Given a ref (sha1, refname), check if the ref belongs to the array
1630 * of sha1s. If the given ref is a tag, check if the given tag points
1631 * at one of the sha1s in the given sha1 array.
1632 * the given sha1_array.
1634 * 1. Only a single level of inderection is obtained, we might want to
1635 * change this to account for multiple levels (e.g. annotated tags
1636 * pointing to annotated tags pointing to a commit.)
1637 * 2. As the refs are cached we might know what refname peels to without
1638 * the need to parse the object via parse_object(). peel_ref() might be a
1639 * more efficient alternative to obtain the pointee.
1641 static const unsigned char *match_points_at(struct sha1_array *points_at,
1642 const unsigned char *sha1,
1643 const char *refname)
1645 const unsigned char *tagged_sha1 = NULL;
1648 if (sha1_array_lookup(points_at, sha1) >= 0)
1650 obj = parse_object(sha1);
1652 die(_("malformed object at '%s'"), refname);
1653 if (obj->type == OBJ_TAG)
1654 tagged_sha1 = ((struct tag *)obj)->tagged->oid.hash;
1655 if (tagged_sha1 && sha1_array_lookup(points_at, tagged_sha1) >= 0)
1660 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1661 static struct ref_array_item *new_ref_array_item(const char *refname,
1662 const unsigned char *objectname,
1665 struct ref_array_item *ref;
1666 FLEX_ALLOC_STR(ref, refname, refname);
1667 hashcpy(ref->objectname, objectname);
1673 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1681 { "refs/heads/" , FILTER_REFS_BRANCHES },
1682 { "refs/remotes/" , FILTER_REFS_REMOTES },
1683 { "refs/tags/", FILTER_REFS_TAGS}
1686 if (filter->kind == FILTER_REFS_BRANCHES ||
1687 filter->kind == FILTER_REFS_REMOTES ||
1688 filter->kind == FILTER_REFS_TAGS)
1689 return filter->kind;
1690 else if (!strcmp(refname, "HEAD"))
1691 return FILTER_REFS_DETACHED_HEAD;
1693 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1694 if (starts_with(refname, ref_kind[i].prefix))
1695 return ref_kind[i].kind;
1698 return FILTER_REFS_OTHERS;
1702 * A call-back given to for_each_ref(). Filter refs and keep them for
1703 * later object processing.
1705 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1707 struct ref_filter_cbdata *ref_cbdata = cb_data;
1708 struct ref_filter *filter = ref_cbdata->filter;
1709 struct ref_array_item *ref;
1710 struct commit *commit = NULL;
1713 if (flag & REF_BAD_NAME) {
1714 warning(_("ignoring ref with broken name %s"), refname);
1718 if (flag & REF_ISBROKEN) {
1719 warning(_("ignoring broken ref %s"), refname);
1723 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1724 kind = filter_ref_kind(filter, refname);
1725 if (!(kind & filter->kind))
1728 if (!filter_pattern_match(filter, refname))
1731 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1735 * A merge filter is applied on refs pointing to commits. Hence
1736 * obtain the commit using the 'oid' available and discard all
1737 * non-commits early. The actual filtering is done later.
1739 if (filter->merge_commit || filter->with_commit || filter->verbose) {
1740 commit = lookup_commit_reference_gently(oid->hash, 1);
1743 /* We perform the filtering for the '--contains' option */
1744 if (filter->with_commit &&
1745 !commit_contains(filter, commit))
1750 * We do not open the object yet; sort may only need refname
1751 * to do its job and the resulting list may yet to be pruned
1752 * by maxcount logic.
1754 ref = new_ref_array_item(refname, oid->hash, flag);
1755 ref->commit = commit;
1757 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1758 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1763 /* Free memory allocated for a ref_array_item */
1764 static void free_array_item(struct ref_array_item *item)
1766 free((char *)item->symref);
1770 /* Free all memory allocated for ref_array */
1771 void ref_array_clear(struct ref_array *array)
1775 for (i = 0; i < array->nr; i++)
1776 free_array_item(array->items[i]);
1778 array->items = NULL;
1779 array->nr = array->alloc = 0;
1782 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1784 struct rev_info revs;
1786 struct ref_filter *filter = ref_cbdata->filter;
1787 struct ref_array *array = ref_cbdata->array;
1788 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1790 init_revisions(&revs, NULL);
1792 for (i = 0; i < array->nr; i++) {
1793 struct ref_array_item *item = array->items[i];
1794 add_pending_object(&revs, &item->commit->object, item->refname);
1795 to_clear[i] = item->commit;
1798 filter->merge_commit->object.flags |= UNINTERESTING;
1799 add_pending_object(&revs, &filter->merge_commit->object, "");
1802 if (prepare_revision_walk(&revs))
1803 die(_("revision walk setup failed"));
1808 for (i = 0; i < old_nr; i++) {
1809 struct ref_array_item *item = array->items[i];
1810 struct commit *commit = item->commit;
1812 int is_merged = !!(commit->object.flags & UNINTERESTING);
1814 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1815 array->items[array->nr++] = array->items[i];
1817 free_array_item(item);
1820 for (i = 0; i < old_nr; i++)
1821 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1822 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1827 * API for filtering a set of refs. Based on the type of refs the user
1828 * has requested, we iterate through those refs and apply filters
1829 * as per the given ref_filter structure and finally store the
1830 * filtered refs in the ref_array structure.
1832 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1834 struct ref_filter_cbdata ref_cbdata;
1836 unsigned int broken = 0;
1838 ref_cbdata.array = array;
1839 ref_cbdata.filter = filter;
1841 if (type & FILTER_REFS_INCLUDE_BROKEN)
1843 filter->kind = type & FILTER_REFS_KIND_MASK;
1845 /* Simple per-ref filtering */
1847 die("filter_refs: invalid type");
1850 * For common cases where we need only branches or remotes or tags,
1851 * we only iterate through those refs. If a mix of refs is needed,
1852 * we iterate over all refs and filter out required refs with the help
1853 * of filter_ref_kind().
1855 if (filter->kind == FILTER_REFS_BRANCHES)
1856 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1857 else if (filter->kind == FILTER_REFS_REMOTES)
1858 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1859 else if (filter->kind == FILTER_REFS_TAGS)
1860 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1861 else if (filter->kind & FILTER_REFS_ALL)
1862 ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1863 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1864 head_ref(ref_filter_handler, &ref_cbdata);
1868 /* Filters that need revision walking */
1869 if (filter->merge_commit)
1870 do_merge_filter(&ref_cbdata);
1875 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1877 struct atom_value *va, *vb;
1879 cmp_type cmp_type = used_atom[s->atom].type;
1880 int (*cmp_fn)(const char *, const char *);
1882 get_ref_atom_value(a, s->atom, &va);
1883 get_ref_atom_value(b, s->atom, &vb);
1884 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
1886 cmp = versioncmp(va->s, vb->s);
1887 else if (cmp_type == FIELD_STR)
1888 cmp = cmp_fn(va->s, vb->s);
1890 if (va->ul < vb->ul)
1892 else if (va->ul == vb->ul)
1893 cmp = cmp_fn(a->refname, b->refname);
1898 return (s->reverse) ? -cmp : cmp;
1901 static struct ref_sorting *ref_sorting;
1902 static int compare_refs(const void *a_, const void *b_)
1904 struct ref_array_item *a = *((struct ref_array_item **)a_);
1905 struct ref_array_item *b = *((struct ref_array_item **)b_);
1906 struct ref_sorting *s;
1908 for (s = ref_sorting; s; s = s->next) {
1909 int cmp = cmp_ref_sorting(s, a, b);
1916 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1918 ref_sorting = sorting;
1919 QSORT(array->items, array->nr, compare_refs);
1922 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1924 struct strbuf *s = &state->stack->output;
1926 while (*cp && (!ep || cp < ep)) {
1931 int ch = hex2chr(cp + 1);
1933 strbuf_addch(s, ch);
1939 strbuf_addch(s, *cp);
1944 void format_ref_array_item(struct ref_array_item *info, const char *format,
1945 int quote_style, struct strbuf *final_buf)
1947 const char *cp, *sp, *ep;
1948 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1950 state.quote_style = quote_style;
1951 push_stack_element(&state.stack);
1953 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1954 struct atom_value *atomv;
1956 ep = strchr(sp, ')');
1958 append_literal(cp, sp, &state);
1959 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1960 atomv->handler(atomv, &state);
1963 sp = cp + strlen(cp);
1964 append_literal(cp, sp, &state);
1966 if (need_color_reset_at_eol) {
1967 struct atom_value resetv;
1968 char color[COLOR_MAXLEN] = "";
1970 if (color_parse("reset", color) < 0)
1971 die("BUG: couldn't parse 'reset' as a color");
1973 append_atom(&resetv, &state);
1975 if (state.stack->prev)
1976 die(_("format: %%(end) atom missing"));
1977 strbuf_addbuf(final_buf, &state.stack->output);
1978 pop_stack_element(&state.stack);
1981 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
1983 struct strbuf final_buf = STRBUF_INIT;
1985 format_ref_array_item(info, format, quote_style, &final_buf);
1986 fwrite(final_buf.buf, 1, final_buf.len, stdout);
1987 strbuf_release(&final_buf);
1991 /* If no sorting option is given, use refname to sort as default */
1992 struct ref_sorting *ref_default_sorting(void)
1994 static const char cstr_name[] = "refname";
1996 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
1998 sorting->next = NULL;
1999 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
2003 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2005 struct ref_sorting **sorting_tail = opt->value;
2006 struct ref_sorting *s;
2009 if (!arg) /* should --no-sort void the list ? */
2012 s = xcalloc(1, sizeof(*s));
2013 s->next = *sorting_tail;
2020 if (skip_prefix(arg, "version:", &arg) ||
2021 skip_prefix(arg, "v:", &arg))
2024 s->atom = parse_ref_filter_atom(arg, arg+len);
2028 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2030 struct ref_filter *rf = opt->value;
2031 unsigned char sha1[20];
2033 rf->merge = starts_with(opt->long_name, "no")
2034 ? REF_FILTER_MERGED_OMIT
2035 : REF_FILTER_MERGED_INCLUDE;
2037 if (get_sha1(arg, sha1))
2038 die(_("malformed object name %s"), arg);
2040 rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
2041 if (!rf->merge_commit)
2042 return opterror(opt, "must point to a commit", 0);