ref-filter: introduce align_atom_parser()
[git/git-svn.git] / ref-filter.c
blob797f9fe2d883d9568259507e394cfe290fc4adde
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "refs.h"
5 #include "wildmatch.h"
6 #include "commit.h"
7 #include "remote.h"
8 #include "color.h"
9 #include "tag.h"
10 #include "quote.h"
11 #include "ref-filter.h"
12 #include "revision.h"
13 #include "utf8.h"
14 #include "git-compat-util.h"
15 #include "version.h"
17 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
19 struct align {
20 align_type position;
21 unsigned int width;
25 * An atom is a valid field atom listed below, possibly prefixed with
26 * a "*" to denote deref_tag().
28 * We parse given format string and sort specifiers, and make a list
29 * of properties that we need to extract out of objects. ref_array_item
30 * structure will hold an array of values extracted that can be
31 * indexed with the "atom number", which is an index into this
32 * array.
34 static struct used_atom {
35 const char *name;
36 cmp_type type;
37 union {
38 char color[COLOR_MAXLEN];
39 struct align align;
40 } u;
41 } *used_atom;
42 static int used_atom_cnt, need_tagged, need_symref;
43 static int need_color_reset_at_eol;
45 static void color_atom_parser(struct used_atom *atom, const char *color_value)
47 if (!color_value)
48 die(_("expected format: %%(color:<color>)"));
49 if (color_parse(color_value, atom->u.color) < 0)
50 die(_("unrecognized color: %%(color:%s)"), color_value);
53 static align_type parse_align_position(const char *s)
55 if (!strcmp(s, "right"))
56 return ALIGN_RIGHT;
57 else if (!strcmp(s, "middle"))
58 return ALIGN_MIDDLE;
59 else if (!strcmp(s, "left"))
60 return ALIGN_LEFT;
61 return -1;
64 static void align_atom_parser(struct used_atom *atom, const char *arg)
66 struct align *align = &atom->u.align;
67 struct string_list params = STRING_LIST_INIT_DUP;
68 int i;
69 unsigned int width = ~0U;
71 if (!arg)
72 die(_("expected format: %%(align:<width>,<position>)"));
74 align->position = ALIGN_LEFT;
76 string_list_split(&params, arg, ',', -1);
77 for (i = 0; i < params.nr; i++) {
78 const char *s = params.items[i].string;
79 int position;
81 if (!strtoul_ui(s, 10, &width))
83 else if ((position = parse_align_position(s)) >= 0)
84 align->position = position;
85 else
86 die(_("unrecognized %%(align) argument: %s"), s);
89 if (width == ~0U)
90 die(_("positive width expected with the %%(align) atom"));
91 align->width = width;
92 string_list_clear(&params, 0);
95 static struct {
96 const char *name;
97 cmp_type cmp_type;
98 void (*parser)(struct used_atom *atom, const char *arg);
99 } valid_atom[] = {
100 { "refname" },
101 { "objecttype" },
102 { "objectsize", FIELD_ULONG },
103 { "objectname" },
104 { "tree" },
105 { "parent" },
106 { "numparent", FIELD_ULONG },
107 { "object" },
108 { "type" },
109 { "tag" },
110 { "author" },
111 { "authorname" },
112 { "authoremail" },
113 { "authordate", FIELD_TIME },
114 { "committer" },
115 { "committername" },
116 { "committeremail" },
117 { "committerdate", FIELD_TIME },
118 { "tagger" },
119 { "taggername" },
120 { "taggeremail" },
121 { "taggerdate", FIELD_TIME },
122 { "creator" },
123 { "creatordate", FIELD_TIME },
124 { "subject" },
125 { "body" },
126 { "contents" },
127 { "upstream" },
128 { "push" },
129 { "symref" },
130 { "flag" },
131 { "HEAD" },
132 { "color", FIELD_STR, color_atom_parser },
133 { "align", FIELD_STR, align_atom_parser },
134 { "end" },
137 #define REF_FORMATTING_STATE_INIT { 0, NULL }
139 struct contents {
140 unsigned int lines;
141 struct object_id oid;
144 struct ref_formatting_stack {
145 struct ref_formatting_stack *prev;
146 struct strbuf output;
147 void (*at_end)(struct ref_formatting_stack *stack);
148 void *at_end_data;
151 struct ref_formatting_state {
152 int quote_style;
153 struct ref_formatting_stack *stack;
156 struct atom_value {
157 const char *s;
158 union {
159 struct align align;
160 struct contents contents;
161 } u;
162 void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
163 unsigned long ul; /* used for sorting when not FIELD_STR */
167 * Used to parse format string and sort specifiers
169 int parse_ref_filter_atom(const char *atom, const char *ep)
171 const char *sp;
172 const char *arg;
173 int i, at;
175 sp = atom;
176 if (*sp == '*' && sp < ep)
177 sp++; /* deref */
178 if (ep <= sp)
179 die("malformed field name: %.*s", (int)(ep-atom), atom);
181 /* Do we have the atom already used elsewhere? */
182 for (i = 0; i < used_atom_cnt; i++) {
183 int len = strlen(used_atom[i].name);
184 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
185 return i;
188 /* Is the atom a valid one? */
189 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
190 int len = strlen(valid_atom[i].name);
193 * If the atom name has a colon, strip it and everything after
194 * it off - it specifies the format for this entry, and
195 * shouldn't be used for checking against the valid_atom
196 * table.
198 arg = memchr(sp, ':', ep - sp);
199 if (len == (arg ? arg : ep) - sp &&
200 !memcmp(valid_atom[i].name, sp, len))
201 break;
204 if (ARRAY_SIZE(valid_atom) <= i)
205 die("unknown field name: %.*s", (int)(ep-atom), atom);
207 /* Add it in, including the deref prefix */
208 at = used_atom_cnt;
209 used_atom_cnt++;
210 REALLOC_ARRAY(used_atom, used_atom_cnt);
211 used_atom[at].name = xmemdupz(atom, ep - atom);
212 used_atom[at].type = valid_atom[i].cmp_type;
213 if (arg)
214 arg = used_atom[at].name + (arg - atom) + 1;
215 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
216 if (valid_atom[i].parser)
217 valid_atom[i].parser(&used_atom[at], arg);
218 if (*atom == '*')
219 need_tagged = 1;
220 if (!strcmp(used_atom[at].name, "symref"))
221 need_symref = 1;
222 return at;
225 static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
227 switch (quote_style) {
228 case QUOTE_NONE:
229 strbuf_addstr(s, str);
230 break;
231 case QUOTE_SHELL:
232 sq_quote_buf(s, str);
233 break;
234 case QUOTE_PERL:
235 perl_quote_buf(s, str);
236 break;
237 case QUOTE_PYTHON:
238 python_quote_buf(s, str);
239 break;
240 case QUOTE_TCL:
241 tcl_quote_buf(s, str);
242 break;
246 static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
249 * Quote formatting is only done when the stack has a single
250 * element. Otherwise quote formatting is done on the
251 * element's entire output strbuf when the %(end) atom is
252 * encountered.
254 if (!state->stack->prev)
255 quote_formatting(&state->stack->output, v->s, state->quote_style);
256 else
257 strbuf_addstr(&state->stack->output, v->s);
260 static void push_stack_element(struct ref_formatting_stack **stack)
262 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
264 strbuf_init(&s->output, 0);
265 s->prev = *stack;
266 *stack = s;
269 static void pop_stack_element(struct ref_formatting_stack **stack)
271 struct ref_formatting_stack *current = *stack;
272 struct ref_formatting_stack *prev = current->prev;
274 if (prev)
275 strbuf_addbuf(&prev->output, &current->output);
276 strbuf_release(&current->output);
277 free(current);
278 *stack = prev;
281 static void end_align_handler(struct ref_formatting_stack *stack)
283 struct align *align = (struct align *)stack->at_end_data;
284 struct strbuf s = STRBUF_INIT;
286 strbuf_utf8_align(&s, align->position, align->width, stack->output.buf);
287 strbuf_swap(&stack->output, &s);
288 strbuf_release(&s);
291 static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
293 struct ref_formatting_stack *new;
295 push_stack_element(&state->stack);
296 new = state->stack;
297 new->at_end = end_align_handler;
298 new->at_end_data = &atomv->u.align;
301 static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
303 struct ref_formatting_stack *current = state->stack;
304 struct strbuf s = STRBUF_INIT;
306 if (!current->at_end)
307 die(_("format: %%(end) atom used without corresponding atom"));
308 current->at_end(current);
311 * Perform quote formatting when the stack element is that of
312 * a supporting atom. If nested then perform quote formatting
313 * only on the topmost supporting atom.
315 if (!state->stack->prev->prev) {
316 quote_formatting(&s, current->output.buf, state->quote_style);
317 strbuf_swap(&current->output, &s);
319 strbuf_release(&s);
320 pop_stack_element(&state->stack);
324 * In a format string, find the next occurrence of %(atom).
326 static const char *find_next(const char *cp)
328 while (*cp) {
329 if (*cp == '%') {
331 * %( is the start of an atom;
332 * %% is a quoted per-cent.
334 if (cp[1] == '(')
335 return cp;
336 else if (cp[1] == '%')
337 cp++; /* skip over two % */
338 /* otherwise this is a singleton, literal % */
340 cp++;
342 return NULL;
346 * Make sure the format string is well formed, and parse out
347 * the used atoms.
349 int verify_ref_format(const char *format)
351 const char *cp, *sp;
353 need_color_reset_at_eol = 0;
354 for (cp = format; *cp && (sp = find_next(cp)); ) {
355 const char *color, *ep = strchr(sp, ')');
356 int at;
358 if (!ep)
359 return error("malformed format string %s", sp);
360 /* sp points at "%(" and ep points at the closing ")" */
361 at = parse_ref_filter_atom(sp + 2, ep);
362 cp = ep + 1;
364 if (skip_prefix(used_atom[at].name, "color:", &color))
365 need_color_reset_at_eol = !!strcmp(color, "reset");
367 return 0;
371 * Given an object name, read the object data and size, and return a
372 * "struct object". If the object data we are returning is also borrowed
373 * by the "struct object" representation, set *eaten as well---it is a
374 * signal from parse_object_buffer to us not to free the buffer.
376 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
378 enum object_type type;
379 void *buf = read_sha1_file(sha1, &type, sz);
381 if (buf)
382 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
383 else
384 *obj = NULL;
385 return buf;
388 static int grab_objectname(const char *name, const unsigned char *sha1,
389 struct atom_value *v)
391 if (!strcmp(name, "objectname")) {
392 v->s = xstrdup(sha1_to_hex(sha1));
393 return 1;
395 if (!strcmp(name, "objectname:short")) {
396 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
397 return 1;
399 return 0;
402 /* See grab_values */
403 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
405 int i;
407 for (i = 0; i < used_atom_cnt; i++) {
408 const char *name = used_atom[i].name;
409 struct atom_value *v = &val[i];
410 if (!!deref != (*name == '*'))
411 continue;
412 if (deref)
413 name++;
414 if (!strcmp(name, "objecttype"))
415 v->s = typename(obj->type);
416 else if (!strcmp(name, "objectsize")) {
417 v->ul = sz;
418 v->s = xstrfmt("%lu", sz);
420 else if (deref)
421 grab_objectname(name, obj->oid.hash, v);
425 /* See grab_values */
426 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
428 int i;
429 struct tag *tag = (struct tag *) obj;
431 for (i = 0; i < used_atom_cnt; i++) {
432 const char *name = used_atom[i].name;
433 struct atom_value *v = &val[i];
434 if (!!deref != (*name == '*'))
435 continue;
436 if (deref)
437 name++;
438 if (!strcmp(name, "tag"))
439 v->s = tag->tag;
440 else if (!strcmp(name, "type") && tag->tagged)
441 v->s = typename(tag->tagged->type);
442 else if (!strcmp(name, "object") && tag->tagged)
443 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
447 /* See grab_values */
448 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
450 int i;
451 struct commit *commit = (struct commit *) obj;
453 for (i = 0; i < used_atom_cnt; i++) {
454 const char *name = used_atom[i].name;
455 struct atom_value *v = &val[i];
456 if (!!deref != (*name == '*'))
457 continue;
458 if (deref)
459 name++;
460 if (!strcmp(name, "tree")) {
461 v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
463 else if (!strcmp(name, "numparent")) {
464 v->ul = commit_list_count(commit->parents);
465 v->s = xstrfmt("%lu", v->ul);
467 else if (!strcmp(name, "parent")) {
468 struct commit_list *parents;
469 struct strbuf s = STRBUF_INIT;
470 for (parents = commit->parents; parents; parents = parents->next) {
471 struct commit *parent = parents->item;
472 if (parents != commit->parents)
473 strbuf_addch(&s, ' ');
474 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
476 v->s = strbuf_detach(&s, NULL);
481 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
483 const char *eol;
484 while (*buf) {
485 if (!strncmp(buf, who, wholen) &&
486 buf[wholen] == ' ')
487 return buf + wholen + 1;
488 eol = strchr(buf, '\n');
489 if (!eol)
490 return "";
491 eol++;
492 if (*eol == '\n')
493 return ""; /* end of header */
494 buf = eol;
496 return "";
499 static const char *copy_line(const char *buf)
501 const char *eol = strchrnul(buf, '\n');
502 return xmemdupz(buf, eol - buf);
505 static const char *copy_name(const char *buf)
507 const char *cp;
508 for (cp = buf; *cp && *cp != '\n'; cp++) {
509 if (!strncmp(cp, " <", 2))
510 return xmemdupz(buf, cp - buf);
512 return "";
515 static const char *copy_email(const char *buf)
517 const char *email = strchr(buf, '<');
518 const char *eoemail;
519 if (!email)
520 return "";
521 eoemail = strchr(email, '>');
522 if (!eoemail)
523 return "";
524 return xmemdupz(email, eoemail + 1 - email);
527 static char *copy_subject(const char *buf, unsigned long len)
529 char *r = xmemdupz(buf, len);
530 int i;
532 for (i = 0; i < len; i++)
533 if (r[i] == '\n')
534 r[i] = ' ';
536 return r;
539 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
541 const char *eoemail = strstr(buf, "> ");
542 char *zone;
543 unsigned long timestamp;
544 long tz;
545 struct date_mode date_mode = { DATE_NORMAL };
546 const char *formatp;
549 * We got here because atomname ends in "date" or "date<something>";
550 * it's not possible that <something> is not ":<format>" because
551 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
552 * ":" means no format is specified, and use the default.
554 formatp = strchr(atomname, ':');
555 if (formatp != NULL) {
556 formatp++;
557 parse_date_format(formatp, &date_mode);
560 if (!eoemail)
561 goto bad;
562 timestamp = strtoul(eoemail + 2, &zone, 10);
563 if (timestamp == ULONG_MAX)
564 goto bad;
565 tz = strtol(zone, NULL, 10);
566 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
567 goto bad;
568 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
569 v->ul = timestamp;
570 return;
571 bad:
572 v->s = "";
573 v->ul = 0;
576 /* See grab_values */
577 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
579 int i;
580 int wholen = strlen(who);
581 const char *wholine = NULL;
583 for (i = 0; i < used_atom_cnt; i++) {
584 const char *name = used_atom[i].name;
585 struct atom_value *v = &val[i];
586 if (!!deref != (*name == '*'))
587 continue;
588 if (deref)
589 name++;
590 if (strncmp(who, name, wholen))
591 continue;
592 if (name[wholen] != 0 &&
593 strcmp(name + wholen, "name") &&
594 strcmp(name + wholen, "email") &&
595 !starts_with(name + wholen, "date"))
596 continue;
597 if (!wholine)
598 wholine = find_wholine(who, wholen, buf, sz);
599 if (!wholine)
600 return; /* no point looking for it */
601 if (name[wholen] == 0)
602 v->s = copy_line(wholine);
603 else if (!strcmp(name + wholen, "name"))
604 v->s = copy_name(wholine);
605 else if (!strcmp(name + wholen, "email"))
606 v->s = copy_email(wholine);
607 else if (starts_with(name + wholen, "date"))
608 grab_date(wholine, v, name);
612 * For a tag or a commit object, if "creator" or "creatordate" is
613 * requested, do something special.
615 if (strcmp(who, "tagger") && strcmp(who, "committer"))
616 return; /* "author" for commit object is not wanted */
617 if (!wholine)
618 wholine = find_wholine(who, wholen, buf, sz);
619 if (!wholine)
620 return;
621 for (i = 0; i < used_atom_cnt; i++) {
622 const char *name = used_atom[i].name;
623 struct atom_value *v = &val[i];
624 if (!!deref != (*name == '*'))
625 continue;
626 if (deref)
627 name++;
629 if (starts_with(name, "creatordate"))
630 grab_date(wholine, v, name);
631 else if (!strcmp(name, "creator"))
632 v->s = copy_line(wholine);
636 static void find_subpos(const char *buf, unsigned long sz,
637 const char **sub, unsigned long *sublen,
638 const char **body, unsigned long *bodylen,
639 unsigned long *nonsiglen,
640 const char **sig, unsigned long *siglen)
642 const char *eol;
643 /* skip past header until we hit empty line */
644 while (*buf && *buf != '\n') {
645 eol = strchrnul(buf, '\n');
646 if (*eol)
647 eol++;
648 buf = eol;
650 /* skip any empty lines */
651 while (*buf == '\n')
652 buf++;
654 /* parse signature first; we might not even have a subject line */
655 *sig = buf + parse_signature(buf, strlen(buf));
656 *siglen = strlen(*sig);
658 /* subject is first non-empty line */
659 *sub = buf;
660 /* subject goes to first empty line */
661 while (buf < *sig && *buf && *buf != '\n') {
662 eol = strchrnul(buf, '\n');
663 if (*eol)
664 eol++;
665 buf = eol;
667 *sublen = buf - *sub;
668 /* drop trailing newline, if present */
669 if (*sublen && (*sub)[*sublen - 1] == '\n')
670 *sublen -= 1;
672 /* skip any empty lines */
673 while (*buf == '\n')
674 buf++;
675 *body = buf;
676 *bodylen = strlen(buf);
677 *nonsiglen = *sig - buf;
681 * If 'lines' is greater than 0, append that many lines from the given
682 * 'buf' of length 'size' to the given strbuf.
684 static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
686 int i;
687 const char *sp, *eol;
688 size_t len;
690 sp = buf;
692 for (i = 0; i < lines && sp < buf + size; i++) {
693 if (i)
694 strbuf_addstr(out, "\n ");
695 eol = memchr(sp, '\n', size - (sp - buf));
696 len = eol ? eol - sp : size - (sp - buf);
697 strbuf_add(out, sp, len);
698 if (!eol)
699 break;
700 sp = eol + 1;
704 /* See grab_values */
705 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
707 int i;
708 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
709 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
711 for (i = 0; i < used_atom_cnt; i++) {
712 const char *name = used_atom[i].name;
713 struct atom_value *v = &val[i];
714 const char *valp = NULL;
715 if (!!deref != (*name == '*'))
716 continue;
717 if (deref)
718 name++;
719 if (strcmp(name, "subject") &&
720 strcmp(name, "body") &&
721 strcmp(name, "contents") &&
722 strcmp(name, "contents:subject") &&
723 strcmp(name, "contents:body") &&
724 strcmp(name, "contents:signature") &&
725 !starts_with(name, "contents:lines="))
726 continue;
727 if (!subpos)
728 find_subpos(buf, sz,
729 &subpos, &sublen,
730 &bodypos, &bodylen, &nonsiglen,
731 &sigpos, &siglen);
733 if (!strcmp(name, "subject"))
734 v->s = copy_subject(subpos, sublen);
735 else if (!strcmp(name, "contents:subject"))
736 v->s = copy_subject(subpos, sublen);
737 else if (!strcmp(name, "body"))
738 v->s = xmemdupz(bodypos, bodylen);
739 else if (!strcmp(name, "contents:body"))
740 v->s = xmemdupz(bodypos, nonsiglen);
741 else if (!strcmp(name, "contents:signature"))
742 v->s = xmemdupz(sigpos, siglen);
743 else if (!strcmp(name, "contents"))
744 v->s = xstrdup(subpos);
745 else if (skip_prefix(name, "contents:lines=", &valp)) {
746 struct strbuf s = STRBUF_INIT;
747 const char *contents_end = bodylen + bodypos - siglen;
749 if (strtoul_ui(valp, 10, &v->u.contents.lines))
750 die(_("positive value expected contents:lines=%s"), valp);
751 /* Size is the length of the message after removing the signature */
752 append_lines(&s, subpos, contents_end - subpos, v->u.contents.lines);
753 v->s = strbuf_detach(&s, NULL);
759 * We want to have empty print-string for field requests
760 * that do not apply (e.g. "authordate" for a tag object)
762 static void fill_missing_values(struct atom_value *val)
764 int i;
765 for (i = 0; i < used_atom_cnt; i++) {
766 struct atom_value *v = &val[i];
767 if (v->s == NULL)
768 v->s = "";
773 * val is a list of atom_value to hold returned values. Extract
774 * the values for atoms in used_atom array out of (obj, buf, sz).
775 * when deref is false, (obj, buf, sz) is the object that is
776 * pointed at by the ref itself; otherwise it is the object the
777 * ref (which is a tag) refers to.
779 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
781 grab_common_values(val, deref, obj, buf, sz);
782 switch (obj->type) {
783 case OBJ_TAG:
784 grab_tag_values(val, deref, obj, buf, sz);
785 grab_sub_body_contents(val, deref, obj, buf, sz);
786 grab_person("tagger", val, deref, obj, buf, sz);
787 break;
788 case OBJ_COMMIT:
789 grab_commit_values(val, deref, obj, buf, sz);
790 grab_sub_body_contents(val, deref, obj, buf, sz);
791 grab_person("author", val, deref, obj, buf, sz);
792 grab_person("committer", val, deref, obj, buf, sz);
793 break;
794 case OBJ_TREE:
795 /* grab_tree_values(val, deref, obj, buf, sz); */
796 break;
797 case OBJ_BLOB:
798 /* grab_blob_values(val, deref, obj, buf, sz); */
799 break;
800 default:
801 die("Eh? Object of type %d?", obj->type);
805 static inline char *copy_advance(char *dst, const char *src)
807 while (*src)
808 *dst++ = *src++;
809 return dst;
812 static const char *strip_ref_components(const char *refname, const char *nr_arg)
814 char *end;
815 long nr = strtol(nr_arg, &end, 10);
816 long remaining = nr;
817 const char *start = refname;
819 if (nr < 1 || *end != '\0')
820 die(":strip= requires a positive integer argument");
822 while (remaining) {
823 switch (*start++) {
824 case '\0':
825 die("ref '%s' does not have %ld components to :strip",
826 refname, nr);
827 case '/':
828 remaining--;
829 break;
832 return start;
836 * Parse the object referred by ref, and grab needed value.
838 static void populate_value(struct ref_array_item *ref)
840 void *buf;
841 struct object *obj;
842 int eaten, i;
843 unsigned long size;
844 const unsigned char *tagged;
846 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
848 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
849 unsigned char unused1[20];
850 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
851 unused1, NULL);
852 if (!ref->symref)
853 ref->symref = "";
856 /* Fill in specials first */
857 for (i = 0; i < used_atom_cnt; i++) {
858 struct used_atom *atom = &used_atom[i];
859 const char *name = used_atom[i].name;
860 struct atom_value *v = &ref->value[i];
861 int deref = 0;
862 const char *refname;
863 const char *formatp;
864 struct branch *branch = NULL;
866 v->handler = append_atom;
868 if (*name == '*') {
869 deref = 1;
870 name++;
873 if (starts_with(name, "refname"))
874 refname = ref->refname;
875 else if (starts_with(name, "symref"))
876 refname = ref->symref ? ref->symref : "";
877 else if (starts_with(name, "upstream")) {
878 const char *branch_name;
879 /* only local branches may have an upstream */
880 if (!skip_prefix(ref->refname, "refs/heads/",
881 &branch_name))
882 continue;
883 branch = branch_get(branch_name);
885 refname = branch_get_upstream(branch, NULL);
886 if (!refname)
887 continue;
888 } else if (starts_with(name, "push")) {
889 const char *branch_name;
890 if (!skip_prefix(ref->refname, "refs/heads/",
891 &branch_name))
892 continue;
893 branch = branch_get(branch_name);
895 refname = branch_get_push(branch, NULL);
896 if (!refname)
897 continue;
898 } else if (starts_with(name, "color:")) {
899 v->s = atom->u.color;
900 continue;
901 } else if (!strcmp(name, "flag")) {
902 char buf[256], *cp = buf;
903 if (ref->flag & REF_ISSYMREF)
904 cp = copy_advance(cp, ",symref");
905 if (ref->flag & REF_ISPACKED)
906 cp = copy_advance(cp, ",packed");
907 if (cp == buf)
908 v->s = "";
909 else {
910 *cp = '\0';
911 v->s = xstrdup(buf + 1);
913 continue;
914 } else if (!deref && grab_objectname(name, ref->objectname, v)) {
915 continue;
916 } else if (!strcmp(name, "HEAD")) {
917 const char *head;
918 unsigned char sha1[20];
920 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
921 sha1, NULL);
922 if (!strcmp(ref->refname, head))
923 v->s = "*";
924 else
925 v->s = " ";
926 continue;
927 } else if (starts_with(name, "align")) {
928 v->u.align = atom->u.align;
929 v->handler = align_atom_handler;
930 continue;
931 } else if (!strcmp(name, "end")) {
932 v->handler = end_atom_handler;
933 continue;
934 } else
935 continue;
937 formatp = strchr(name, ':');
938 if (formatp) {
939 int num_ours, num_theirs;
940 const char *arg;
942 formatp++;
943 if (!strcmp(formatp, "short"))
944 refname = shorten_unambiguous_ref(refname,
945 warn_ambiguous_refs);
946 else if (skip_prefix(formatp, "strip=", &arg))
947 refname = strip_ref_components(refname, arg);
948 else if (!strcmp(formatp, "track") &&
949 (starts_with(name, "upstream") ||
950 starts_with(name, "push"))) {
952 if (stat_tracking_info(branch, &num_ours,
953 &num_theirs, NULL))
954 continue;
956 if (!num_ours && !num_theirs)
957 v->s = "";
958 else if (!num_ours)
959 v->s = xstrfmt("[behind %d]", num_theirs);
960 else if (!num_theirs)
961 v->s = xstrfmt("[ahead %d]", num_ours);
962 else
963 v->s = xstrfmt("[ahead %d, behind %d]",
964 num_ours, num_theirs);
965 continue;
966 } else if (!strcmp(formatp, "trackshort") &&
967 (starts_with(name, "upstream") ||
968 starts_with(name, "push"))) {
969 assert(branch);
971 if (stat_tracking_info(branch, &num_ours,
972 &num_theirs, NULL))
973 continue;
975 if (!num_ours && !num_theirs)
976 v->s = "=";
977 else if (!num_ours)
978 v->s = "<";
979 else if (!num_theirs)
980 v->s = ">";
981 else
982 v->s = "<>";
983 continue;
984 } else
985 die("unknown %.*s format %s",
986 (int)(formatp - name), name, formatp);
989 if (!deref)
990 v->s = refname;
991 else
992 v->s = xstrfmt("%s^{}", refname);
995 for (i = 0; i < used_atom_cnt; i++) {
996 struct atom_value *v = &ref->value[i];
997 if (v->s == NULL)
998 goto need_obj;
1000 return;
1002 need_obj:
1003 buf = get_obj(ref->objectname, &obj, &size, &eaten);
1004 if (!buf)
1005 die("missing object %s for %s",
1006 sha1_to_hex(ref->objectname), ref->refname);
1007 if (!obj)
1008 die("parse_object_buffer failed on %s for %s",
1009 sha1_to_hex(ref->objectname), ref->refname);
1011 grab_values(ref->value, 0, obj, buf, size);
1012 if (!eaten)
1013 free(buf);
1016 * If there is no atom that wants to know about tagged
1017 * object, we are done.
1019 if (!need_tagged || (obj->type != OBJ_TAG))
1020 return;
1023 * If it is a tag object, see if we use a value that derefs
1024 * the object, and if we do grab the object it refers to.
1026 tagged = ((struct tag *)obj)->tagged->oid.hash;
1029 * NEEDSWORK: This derefs tag only once, which
1030 * is good to deal with chains of trust, but
1031 * is not consistent with what deref_tag() does
1032 * which peels the onion to the core.
1034 buf = get_obj(tagged, &obj, &size, &eaten);
1035 if (!buf)
1036 die("missing object %s for %s",
1037 sha1_to_hex(tagged), ref->refname);
1038 if (!obj)
1039 die("parse_object_buffer failed on %s for %s",
1040 sha1_to_hex(tagged), ref->refname);
1041 grab_values(ref->value, 1, obj, buf, size);
1042 if (!eaten)
1043 free(buf);
1047 * Given a ref, return the value for the atom. This lazily gets value
1048 * out of the object by calling populate value.
1050 static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1052 if (!ref->value) {
1053 populate_value(ref);
1054 fill_missing_values(ref->value);
1056 *v = &ref->value[atom];
1059 enum contains_result {
1060 CONTAINS_UNKNOWN = -1,
1061 CONTAINS_NO = 0,
1062 CONTAINS_YES = 1
1066 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1067 * overflows.
1069 * At each recursion step, the stack items points to the commits whose
1070 * ancestors are to be inspected.
1072 struct contains_stack {
1073 int nr, alloc;
1074 struct contains_stack_entry {
1075 struct commit *commit;
1076 struct commit_list *parents;
1077 } *contains_stack;
1080 static int in_commit_list(const struct commit_list *want, struct commit *c)
1082 for (; want; want = want->next)
1083 if (!oidcmp(&want->item->object.oid, &c->object.oid))
1084 return 1;
1085 return 0;
1089 * Test whether the candidate or one of its parents is contained in the list.
1090 * Do not recurse to find out, though, but return -1 if inconclusive.
1092 static enum contains_result contains_test(struct commit *candidate,
1093 const struct commit_list *want)
1095 /* was it previously marked as containing a want commit? */
1096 if (candidate->object.flags & TMP_MARK)
1097 return 1;
1098 /* or marked as not possibly containing a want commit? */
1099 if (candidate->object.flags & UNINTERESTING)
1100 return 0;
1101 /* or are we it? */
1102 if (in_commit_list(want, candidate)) {
1103 candidate->object.flags |= TMP_MARK;
1104 return 1;
1107 if (parse_commit(candidate) < 0)
1108 return 0;
1110 return -1;
1113 static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1115 ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1116 contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1117 contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1120 static enum contains_result contains_tag_algo(struct commit *candidate,
1121 const struct commit_list *want)
1123 struct contains_stack contains_stack = { 0, 0, NULL };
1124 int result = contains_test(candidate, want);
1126 if (result != CONTAINS_UNKNOWN)
1127 return result;
1129 push_to_contains_stack(candidate, &contains_stack);
1130 while (contains_stack.nr) {
1131 struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1132 struct commit *commit = entry->commit;
1133 struct commit_list *parents = entry->parents;
1135 if (!parents) {
1136 commit->object.flags |= UNINTERESTING;
1137 contains_stack.nr--;
1140 * If we just popped the stack, parents->item has been marked,
1141 * therefore contains_test will return a meaningful 0 or 1.
1143 else switch (contains_test(parents->item, want)) {
1144 case CONTAINS_YES:
1145 commit->object.flags |= TMP_MARK;
1146 contains_stack.nr--;
1147 break;
1148 case CONTAINS_NO:
1149 entry->parents = parents->next;
1150 break;
1151 case CONTAINS_UNKNOWN:
1152 push_to_contains_stack(parents->item, &contains_stack);
1153 break;
1156 free(contains_stack.contains_stack);
1157 return contains_test(candidate, want);
1160 static int commit_contains(struct ref_filter *filter, struct commit *commit)
1162 if (filter->with_commit_tag_algo)
1163 return contains_tag_algo(commit, filter->with_commit);
1164 return is_descendant_of(commit, filter->with_commit);
1168 * Return 1 if the refname matches one of the patterns, otherwise 0.
1169 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1170 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1171 * matches "refs/heads/mas*", too).
1173 static int match_pattern(const char **patterns, const char *refname)
1176 * When no '--format' option is given we need to skip the prefix
1177 * for matching refs of tags and branches.
1179 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1180 skip_prefix(refname, "refs/heads/", &refname) ||
1181 skip_prefix(refname, "refs/remotes/", &refname) ||
1182 skip_prefix(refname, "refs/", &refname));
1184 for (; *patterns; patterns++) {
1185 if (!wildmatch(*patterns, refname, 0, NULL))
1186 return 1;
1188 return 0;
1192 * Return 1 if the refname matches one of the patterns, otherwise 0.
1193 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1194 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1195 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1197 static int match_name_as_path(const char **pattern, const char *refname)
1199 int namelen = strlen(refname);
1200 for (; *pattern; pattern++) {
1201 const char *p = *pattern;
1202 int plen = strlen(p);
1204 if ((plen <= namelen) &&
1205 !strncmp(refname, p, plen) &&
1206 (refname[plen] == '\0' ||
1207 refname[plen] == '/' ||
1208 p[plen-1] == '/'))
1209 return 1;
1210 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1211 return 1;
1213 return 0;
1216 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1217 static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1219 if (!*filter->name_patterns)
1220 return 1; /* No pattern always matches */
1221 if (filter->match_as_path)
1222 return match_name_as_path(filter->name_patterns, refname);
1223 return match_pattern(filter->name_patterns, refname);
1227 * Given a ref (sha1, refname), check if the ref belongs to the array
1228 * of sha1s. If the given ref is a tag, check if the given tag points
1229 * at one of the sha1s in the given sha1 array.
1230 * the given sha1_array.
1231 * NEEDSWORK:
1232 * 1. Only a single level of inderection is obtained, we might want to
1233 * change this to account for multiple levels (e.g. annotated tags
1234 * pointing to annotated tags pointing to a commit.)
1235 * 2. As the refs are cached we might know what refname peels to without
1236 * the need to parse the object via parse_object(). peel_ref() might be a
1237 * more efficient alternative to obtain the pointee.
1239 static const unsigned char *match_points_at(struct sha1_array *points_at,
1240 const unsigned char *sha1,
1241 const char *refname)
1243 const unsigned char *tagged_sha1 = NULL;
1244 struct object *obj;
1246 if (sha1_array_lookup(points_at, sha1) >= 0)
1247 return sha1;
1248 obj = parse_object(sha1);
1249 if (!obj)
1250 die(_("malformed object at '%s'"), refname);
1251 if (obj->type == OBJ_TAG)
1252 tagged_sha1 = ((struct tag *)obj)->tagged->oid.hash;
1253 if (tagged_sha1 && sha1_array_lookup(points_at, tagged_sha1) >= 0)
1254 return tagged_sha1;
1255 return NULL;
1258 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1259 static struct ref_array_item *new_ref_array_item(const char *refname,
1260 const unsigned char *objectname,
1261 int flag)
1263 size_t len = strlen(refname);
1264 struct ref_array_item *ref = xcalloc(1, sizeof(struct ref_array_item) + len + 1);
1265 memcpy(ref->refname, refname, len);
1266 ref->refname[len] = '\0';
1267 hashcpy(ref->objectname, objectname);
1268 ref->flag = flag;
1270 return ref;
1273 static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1275 unsigned int i;
1277 static struct {
1278 const char *prefix;
1279 unsigned int kind;
1280 } ref_kind[] = {
1281 { "refs/heads/" , FILTER_REFS_BRANCHES },
1282 { "refs/remotes/" , FILTER_REFS_REMOTES },
1283 { "refs/tags/", FILTER_REFS_TAGS}
1286 if (filter->kind == FILTER_REFS_BRANCHES ||
1287 filter->kind == FILTER_REFS_REMOTES ||
1288 filter->kind == FILTER_REFS_TAGS)
1289 return filter->kind;
1290 else if (!strcmp(refname, "HEAD"))
1291 return FILTER_REFS_DETACHED_HEAD;
1293 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1294 if (starts_with(refname, ref_kind[i].prefix))
1295 return ref_kind[i].kind;
1298 return FILTER_REFS_OTHERS;
1302 * A call-back given to for_each_ref(). Filter refs and keep them for
1303 * later object processing.
1305 static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1307 struct ref_filter_cbdata *ref_cbdata = cb_data;
1308 struct ref_filter *filter = ref_cbdata->filter;
1309 struct ref_array_item *ref;
1310 struct commit *commit = NULL;
1311 unsigned int kind;
1313 if (flag & REF_BAD_NAME) {
1314 warning("ignoring ref with broken name %s", refname);
1315 return 0;
1318 if (flag & REF_ISBROKEN) {
1319 warning("ignoring broken ref %s", refname);
1320 return 0;
1323 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1324 kind = filter_ref_kind(filter, refname);
1325 if (!(kind & filter->kind))
1326 return 0;
1328 if (!filter_pattern_match(filter, refname))
1329 return 0;
1331 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1332 return 0;
1335 * A merge filter is applied on refs pointing to commits. Hence
1336 * obtain the commit using the 'oid' available and discard all
1337 * non-commits early. The actual filtering is done later.
1339 if (filter->merge_commit || filter->with_commit || filter->verbose) {
1340 commit = lookup_commit_reference_gently(oid->hash, 1);
1341 if (!commit)
1342 return 0;
1343 /* We perform the filtering for the '--contains' option */
1344 if (filter->with_commit &&
1345 !commit_contains(filter, commit))
1346 return 0;
1350 * We do not open the object yet; sort may only need refname
1351 * to do its job and the resulting list may yet to be pruned
1352 * by maxcount logic.
1354 ref = new_ref_array_item(refname, oid->hash, flag);
1355 ref->commit = commit;
1357 REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1358 ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1359 ref->kind = kind;
1360 return 0;
1363 /* Free memory allocated for a ref_array_item */
1364 static void free_array_item(struct ref_array_item *item)
1366 free((char *)item->symref);
1367 free(item);
1370 /* Free all memory allocated for ref_array */
1371 void ref_array_clear(struct ref_array *array)
1373 int i;
1375 for (i = 0; i < array->nr; i++)
1376 free_array_item(array->items[i]);
1377 free(array->items);
1378 array->items = NULL;
1379 array->nr = array->alloc = 0;
1382 static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1384 struct rev_info revs;
1385 int i, old_nr;
1386 struct ref_filter *filter = ref_cbdata->filter;
1387 struct ref_array *array = ref_cbdata->array;
1388 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1390 init_revisions(&revs, NULL);
1392 for (i = 0; i < array->nr; i++) {
1393 struct ref_array_item *item = array->items[i];
1394 add_pending_object(&revs, &item->commit->object, item->refname);
1395 to_clear[i] = item->commit;
1398 filter->merge_commit->object.flags |= UNINTERESTING;
1399 add_pending_object(&revs, &filter->merge_commit->object, "");
1401 revs.limited = 1;
1402 if (prepare_revision_walk(&revs))
1403 die(_("revision walk setup failed"));
1405 old_nr = array->nr;
1406 array->nr = 0;
1408 for (i = 0; i < old_nr; i++) {
1409 struct ref_array_item *item = array->items[i];
1410 struct commit *commit = item->commit;
1412 int is_merged = !!(commit->object.flags & UNINTERESTING);
1414 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1415 array->items[array->nr++] = array->items[i];
1416 else
1417 free_array_item(item);
1420 for (i = 0; i < old_nr; i++)
1421 clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1422 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1423 free(to_clear);
1427 * API for filtering a set of refs. Based on the type of refs the user
1428 * has requested, we iterate through those refs and apply filters
1429 * as per the given ref_filter structure and finally store the
1430 * filtered refs in the ref_array structure.
1432 int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1434 struct ref_filter_cbdata ref_cbdata;
1435 int ret = 0;
1436 unsigned int broken = 0;
1438 ref_cbdata.array = array;
1439 ref_cbdata.filter = filter;
1441 if (type & FILTER_REFS_INCLUDE_BROKEN)
1442 broken = 1;
1443 filter->kind = type & FILTER_REFS_KIND_MASK;
1445 /* Simple per-ref filtering */
1446 if (!filter->kind)
1447 die("filter_refs: invalid type");
1448 else {
1450 * For common cases where we need only branches or remotes or tags,
1451 * we only iterate through those refs. If a mix of refs is needed,
1452 * we iterate over all refs and filter out required refs with the help
1453 * of filter_ref_kind().
1455 if (filter->kind == FILTER_REFS_BRANCHES)
1456 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1457 else if (filter->kind == FILTER_REFS_REMOTES)
1458 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1459 else if (filter->kind == FILTER_REFS_TAGS)
1460 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1461 else if (filter->kind & FILTER_REFS_ALL)
1462 ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1463 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1464 head_ref(ref_filter_handler, &ref_cbdata);
1468 /* Filters that need revision walking */
1469 if (filter->merge_commit)
1470 do_merge_filter(&ref_cbdata);
1472 return ret;
1475 static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1477 struct atom_value *va, *vb;
1478 int cmp;
1479 cmp_type cmp_type = used_atom[s->atom].type;
1481 get_ref_atom_value(a, s->atom, &va);
1482 get_ref_atom_value(b, s->atom, &vb);
1483 if (s->version)
1484 cmp = versioncmp(va->s, vb->s);
1485 else if (cmp_type == FIELD_STR)
1486 cmp = strcmp(va->s, vb->s);
1487 else {
1488 if (va->ul < vb->ul)
1489 cmp = -1;
1490 else if (va->ul == vb->ul)
1491 cmp = strcmp(a->refname, b->refname);
1492 else
1493 cmp = 1;
1496 return (s->reverse) ? -cmp : cmp;
1499 static struct ref_sorting *ref_sorting;
1500 static int compare_refs(const void *a_, const void *b_)
1502 struct ref_array_item *a = *((struct ref_array_item **)a_);
1503 struct ref_array_item *b = *((struct ref_array_item **)b_);
1504 struct ref_sorting *s;
1506 for (s = ref_sorting; s; s = s->next) {
1507 int cmp = cmp_ref_sorting(s, a, b);
1508 if (cmp)
1509 return cmp;
1511 return 0;
1514 void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1516 ref_sorting = sorting;
1517 qsort(array->items, array->nr, sizeof(struct ref_array_item *), compare_refs);
1520 static int hex1(char ch)
1522 if ('0' <= ch && ch <= '9')
1523 return ch - '0';
1524 else if ('a' <= ch && ch <= 'f')
1525 return ch - 'a' + 10;
1526 else if ('A' <= ch && ch <= 'F')
1527 return ch - 'A' + 10;
1528 return -1;
1530 static int hex2(const char *cp)
1532 if (cp[0] && cp[1])
1533 return (hex1(cp[0]) << 4) | hex1(cp[1]);
1534 else
1535 return -1;
1538 static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1540 struct strbuf *s = &state->stack->output;
1542 while (*cp && (!ep || cp < ep)) {
1543 if (*cp == '%') {
1544 if (cp[1] == '%')
1545 cp++;
1546 else {
1547 int ch = hex2(cp + 1);
1548 if (0 <= ch) {
1549 strbuf_addch(s, ch);
1550 cp += 3;
1551 continue;
1555 strbuf_addch(s, *cp);
1556 cp++;
1560 void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
1562 const char *cp, *sp, *ep;
1563 struct strbuf *final_buf;
1564 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1566 state.quote_style = quote_style;
1567 push_stack_element(&state.stack);
1569 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1570 struct atom_value *atomv;
1572 ep = strchr(sp, ')');
1573 if (cp < sp)
1574 append_literal(cp, sp, &state);
1575 get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1576 atomv->handler(atomv, &state);
1578 if (*cp) {
1579 sp = cp + strlen(cp);
1580 append_literal(cp, sp, &state);
1582 if (need_color_reset_at_eol) {
1583 struct atom_value resetv;
1584 char color[COLOR_MAXLEN] = "";
1586 if (color_parse("reset", color) < 0)
1587 die("BUG: couldn't parse 'reset' as a color");
1588 resetv.s = color;
1589 append_atom(&resetv, &state);
1591 if (state.stack->prev)
1592 die(_("format: %%(end) atom missing"));
1593 final_buf = &state.stack->output;
1594 fwrite(final_buf->buf, 1, final_buf->len, stdout);
1595 pop_stack_element(&state.stack);
1596 putchar('\n');
1599 /* If no sorting option is given, use refname to sort as default */
1600 struct ref_sorting *ref_default_sorting(void)
1602 static const char cstr_name[] = "refname";
1604 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
1606 sorting->next = NULL;
1607 sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
1608 return sorting;
1611 int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
1613 struct ref_sorting **sorting_tail = opt->value;
1614 struct ref_sorting *s;
1615 int len;
1617 if (!arg) /* should --no-sort void the list ? */
1618 return -1;
1620 s = xcalloc(1, sizeof(*s));
1621 s->next = *sorting_tail;
1622 *sorting_tail = s;
1624 if (*arg == '-') {
1625 s->reverse = 1;
1626 arg++;
1628 if (skip_prefix(arg, "version:", &arg) ||
1629 skip_prefix(arg, "v:", &arg))
1630 s->version = 1;
1631 len = strlen(arg);
1632 s->atom = parse_ref_filter_atom(arg, arg+len);
1633 return 0;
1636 int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
1638 struct ref_filter *rf = opt->value;
1639 unsigned char sha1[20];
1641 rf->merge = starts_with(opt->long_name, "no")
1642 ? REF_FILTER_MERGED_OMIT
1643 : REF_FILTER_MERGED_INCLUDE;
1645 if (get_sha1(arg, sha1))
1646 die(_("malformed object name %s"), arg);
1648 rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
1649 if (!rf->merge_commit)
1650 return opterror(opt, "must point to a commit", 0);
1652 return 0;