3 #include "parse-options.h"
11 #include "ref-filter.h"
14 #include "git-compat-util.h"
17 typedef enum { FIELD_STR
, FIELD_ULONG
, FIELD_TIME
} cmp_type
;
25 * An atom is a valid field atom listed below, possibly prefixed with
26 * a "*" to denote deref_tag().
28 * We parse given format string and sort specifiers, and make a list
29 * of properties that we need to extract out of objects. ref_array_item
30 * structure will hold an array of values extracted that can be
31 * indexed with the "atom number", which is an index into this
34 static struct used_atom
{
38 char color
[COLOR_MAXLEN
];
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
)
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"))
57 else if (!strcmp(s
, "middle"))
59 else if (!strcmp(s
, "left"))
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
;
69 unsigned int width
= ~0U;
72 die(_("expected format: %%(align:<width>,<position>)"));
74 align
->position
= ALIGN_LEFT
;
76 string_list_split(¶ms
, arg
, ',', -1);
77 for (i
= 0; i
< params
.nr
; i
++) {
78 const char *s
= params
.items
[i
].string
;
81 if (skip_prefix(s
, "position=", &s
)) {
82 position
= parse_align_position(s
);
84 die(_("unrecognized position:%s"), s
);
85 align
->position
= position
;
86 } else if (skip_prefix(s
, "width=", &s
)) {
87 if (strtoul_ui(s
, 10, &width
))
88 die(_("unrecognized width:%s"), s
);
89 } else if (!strtoul_ui(s
, 10, &width
))
91 else if ((position
= parse_align_position(s
)) >= 0)
92 align
->position
= position
;
94 die(_("unrecognized %%(align) argument: %s"), s
);
98 die(_("positive width expected with the %%(align) atom"));
100 string_list_clear(¶ms
, 0);
106 void (*parser
)(struct used_atom
*atom
, const char *arg
);
110 { "objectsize", FIELD_ULONG
},
114 { "numparent", FIELD_ULONG
},
121 { "authordate", FIELD_TIME
},
124 { "committeremail" },
125 { "committerdate", FIELD_TIME
},
129 { "taggerdate", FIELD_TIME
},
131 { "creatordate", FIELD_TIME
},
140 { "color", FIELD_STR
, color_atom_parser
},
141 { "align", FIELD_STR
, align_atom_parser
},
145 #define REF_FORMATTING_STATE_INIT { 0, NULL }
149 struct object_id oid
;
152 struct ref_formatting_stack
{
153 struct ref_formatting_stack
*prev
;
154 struct strbuf output
;
155 void (*at_end
)(struct ref_formatting_stack
*stack
);
159 struct ref_formatting_state
{
161 struct ref_formatting_stack
*stack
;
168 struct contents contents
;
170 void (*handler
)(struct atom_value
*atomv
, struct ref_formatting_state
*state
);
171 unsigned long ul
; /* used for sorting when not FIELD_STR */
175 * Used to parse format string and sort specifiers
177 int parse_ref_filter_atom(const char *atom
, const char *ep
)
184 if (*sp
== '*' && sp
< ep
)
187 die("malformed field name: %.*s", (int)(ep
-atom
), atom
);
189 /* Do we have the atom already used elsewhere? */
190 for (i
= 0; i
< used_atom_cnt
; i
++) {
191 int len
= strlen(used_atom
[i
].name
);
192 if (len
== ep
- atom
&& !memcmp(used_atom
[i
].name
, atom
, len
))
196 /* Is the atom a valid one? */
197 for (i
= 0; i
< ARRAY_SIZE(valid_atom
); i
++) {
198 int len
= strlen(valid_atom
[i
].name
);
201 * If the atom name has a colon, strip it and everything after
202 * it off - it specifies the format for this entry, and
203 * shouldn't be used for checking against the valid_atom
206 arg
= memchr(sp
, ':', ep
- sp
);
207 if (len
== (arg
? arg
: ep
) - sp
&&
208 !memcmp(valid_atom
[i
].name
, sp
, len
))
212 if (ARRAY_SIZE(valid_atom
) <= i
)
213 die("unknown field name: %.*s", (int)(ep
-atom
), atom
);
215 /* Add it in, including the deref prefix */
218 REALLOC_ARRAY(used_atom
, used_atom_cnt
);
219 used_atom
[at
].name
= xmemdupz(atom
, ep
- atom
);
220 used_atom
[at
].type
= valid_atom
[i
].cmp_type
;
222 arg
= used_atom
[at
].name
+ (arg
- atom
) + 1;
223 memset(&used_atom
[at
].u
, 0, sizeof(used_atom
[at
].u
));
224 if (valid_atom
[i
].parser
)
225 valid_atom
[i
].parser(&used_atom
[at
], arg
);
228 if (!strcmp(used_atom
[at
].name
, "symref"))
233 static void quote_formatting(struct strbuf
*s
, const char *str
, int quote_style
)
235 switch (quote_style
) {
237 strbuf_addstr(s
, str
);
240 sq_quote_buf(s
, str
);
243 perl_quote_buf(s
, str
);
246 python_quote_buf(s
, str
);
249 tcl_quote_buf(s
, str
);
254 static void append_atom(struct atom_value
*v
, struct ref_formatting_state
*state
)
257 * Quote formatting is only done when the stack has a single
258 * element. Otherwise quote formatting is done on the
259 * element's entire output strbuf when the %(end) atom is
262 if (!state
->stack
->prev
)
263 quote_formatting(&state
->stack
->output
, v
->s
, state
->quote_style
);
265 strbuf_addstr(&state
->stack
->output
, v
->s
);
268 static void push_stack_element(struct ref_formatting_stack
**stack
)
270 struct ref_formatting_stack
*s
= xcalloc(1, sizeof(struct ref_formatting_stack
));
272 strbuf_init(&s
->output
, 0);
277 static void pop_stack_element(struct ref_formatting_stack
**stack
)
279 struct ref_formatting_stack
*current
= *stack
;
280 struct ref_formatting_stack
*prev
= current
->prev
;
283 strbuf_addbuf(&prev
->output
, ¤t
->output
);
284 strbuf_release(¤t
->output
);
289 static void end_align_handler(struct ref_formatting_stack
*stack
)
291 struct align
*align
= (struct align
*)stack
->at_end_data
;
292 struct strbuf s
= STRBUF_INIT
;
294 strbuf_utf8_align(&s
, align
->position
, align
->width
, stack
->output
.buf
);
295 strbuf_swap(&stack
->output
, &s
);
299 static void align_atom_handler(struct atom_value
*atomv
, struct ref_formatting_state
*state
)
301 struct ref_formatting_stack
*new;
303 push_stack_element(&state
->stack
);
305 new->at_end
= end_align_handler
;
306 new->at_end_data
= &atomv
->u
.align
;
309 static void end_atom_handler(struct atom_value
*atomv
, struct ref_formatting_state
*state
)
311 struct ref_formatting_stack
*current
= state
->stack
;
312 struct strbuf s
= STRBUF_INIT
;
314 if (!current
->at_end
)
315 die(_("format: %%(end) atom used without corresponding atom"));
316 current
->at_end(current
);
319 * Perform quote formatting when the stack element is that of
320 * a supporting atom. If nested then perform quote formatting
321 * only on the topmost supporting atom.
323 if (!state
->stack
->prev
->prev
) {
324 quote_formatting(&s
, current
->output
.buf
, state
->quote_style
);
325 strbuf_swap(¤t
->output
, &s
);
328 pop_stack_element(&state
->stack
);
332 * In a format string, find the next occurrence of %(atom).
334 static const char *find_next(const char *cp
)
339 * %( is the start of an atom;
340 * %% is a quoted per-cent.
344 else if (cp
[1] == '%')
345 cp
++; /* skip over two % */
346 /* otherwise this is a singleton, literal % */
354 * Make sure the format string is well formed, and parse out
357 int verify_ref_format(const char *format
)
361 need_color_reset_at_eol
= 0;
362 for (cp
= format
; *cp
&& (sp
= find_next(cp
)); ) {
363 const char *color
, *ep
= strchr(sp
, ')');
367 return error("malformed format string %s", sp
);
368 /* sp points at "%(" and ep points at the closing ")" */
369 at
= parse_ref_filter_atom(sp
+ 2, ep
);
372 if (skip_prefix(used_atom
[at
].name
, "color:", &color
))
373 need_color_reset_at_eol
= !!strcmp(color
, "reset");
379 * Given an object name, read the object data and size, and return a
380 * "struct object". If the object data we are returning is also borrowed
381 * by the "struct object" representation, set *eaten as well---it is a
382 * signal from parse_object_buffer to us not to free the buffer.
384 static void *get_obj(const unsigned char *sha1
, struct object
**obj
, unsigned long *sz
, int *eaten
)
386 enum object_type type
;
387 void *buf
= read_sha1_file(sha1
, &type
, sz
);
390 *obj
= parse_object_buffer(sha1
, type
, *sz
, buf
, eaten
);
396 static int grab_objectname(const char *name
, const unsigned char *sha1
,
397 struct atom_value
*v
)
399 if (!strcmp(name
, "objectname")) {
400 v
->s
= xstrdup(sha1_to_hex(sha1
));
403 if (!strcmp(name
, "objectname:short")) {
404 v
->s
= xstrdup(find_unique_abbrev(sha1
, DEFAULT_ABBREV
));
410 /* See grab_values */
411 static void grab_common_values(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
415 for (i
= 0; i
< used_atom_cnt
; i
++) {
416 const char *name
= used_atom
[i
].name
;
417 struct atom_value
*v
= &val
[i
];
418 if (!!deref
!= (*name
== '*'))
422 if (!strcmp(name
, "objecttype"))
423 v
->s
= typename(obj
->type
);
424 else if (!strcmp(name
, "objectsize")) {
426 v
->s
= xstrfmt("%lu", sz
);
429 grab_objectname(name
, obj
->oid
.hash
, v
);
433 /* See grab_values */
434 static void grab_tag_values(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
437 struct tag
*tag
= (struct tag
*) obj
;
439 for (i
= 0; i
< used_atom_cnt
; i
++) {
440 const char *name
= used_atom
[i
].name
;
441 struct atom_value
*v
= &val
[i
];
442 if (!!deref
!= (*name
== '*'))
446 if (!strcmp(name
, "tag"))
448 else if (!strcmp(name
, "type") && tag
->tagged
)
449 v
->s
= typename(tag
->tagged
->type
);
450 else if (!strcmp(name
, "object") && tag
->tagged
)
451 v
->s
= xstrdup(oid_to_hex(&tag
->tagged
->oid
));
455 /* See grab_values */
456 static void grab_commit_values(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
459 struct commit
*commit
= (struct commit
*) obj
;
461 for (i
= 0; i
< used_atom_cnt
; i
++) {
462 const char *name
= used_atom
[i
].name
;
463 struct atom_value
*v
= &val
[i
];
464 if (!!deref
!= (*name
== '*'))
468 if (!strcmp(name
, "tree")) {
469 v
->s
= xstrdup(oid_to_hex(&commit
->tree
->object
.oid
));
471 else if (!strcmp(name
, "numparent")) {
472 v
->ul
= commit_list_count(commit
->parents
);
473 v
->s
= xstrfmt("%lu", v
->ul
);
475 else if (!strcmp(name
, "parent")) {
476 struct commit_list
*parents
;
477 struct strbuf s
= STRBUF_INIT
;
478 for (parents
= commit
->parents
; parents
; parents
= parents
->next
) {
479 struct commit
*parent
= parents
->item
;
480 if (parents
!= commit
->parents
)
481 strbuf_addch(&s
, ' ');
482 strbuf_addstr(&s
, oid_to_hex(&parent
->object
.oid
));
484 v
->s
= strbuf_detach(&s
, NULL
);
489 static const char *find_wholine(const char *who
, int wholen
, const char *buf
, unsigned long sz
)
493 if (!strncmp(buf
, who
, wholen
) &&
495 return buf
+ wholen
+ 1;
496 eol
= strchr(buf
, '\n');
501 return ""; /* end of header */
507 static const char *copy_line(const char *buf
)
509 const char *eol
= strchrnul(buf
, '\n');
510 return xmemdupz(buf
, eol
- buf
);
513 static const char *copy_name(const char *buf
)
516 for (cp
= buf
; *cp
&& *cp
!= '\n'; cp
++) {
517 if (!strncmp(cp
, " <", 2))
518 return xmemdupz(buf
, cp
- buf
);
523 static const char *copy_email(const char *buf
)
525 const char *email
= strchr(buf
, '<');
529 eoemail
= strchr(email
, '>');
532 return xmemdupz(email
, eoemail
+ 1 - email
);
535 static char *copy_subject(const char *buf
, unsigned long len
)
537 char *r
= xmemdupz(buf
, len
);
540 for (i
= 0; i
< len
; i
++)
547 static void grab_date(const char *buf
, struct atom_value
*v
, const char *atomname
)
549 const char *eoemail
= strstr(buf
, "> ");
551 unsigned long timestamp
;
553 struct date_mode date_mode
= { DATE_NORMAL
};
557 * We got here because atomname ends in "date" or "date<something>";
558 * it's not possible that <something> is not ":<format>" because
559 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
560 * ":" means no format is specified, and use the default.
562 formatp
= strchr(atomname
, ':');
563 if (formatp
!= NULL
) {
565 parse_date_format(formatp
, &date_mode
);
570 timestamp
= strtoul(eoemail
+ 2, &zone
, 10);
571 if (timestamp
== ULONG_MAX
)
573 tz
= strtol(zone
, NULL
, 10);
574 if ((tz
== LONG_MIN
|| tz
== LONG_MAX
) && errno
== ERANGE
)
576 v
->s
= xstrdup(show_date(timestamp
, tz
, &date_mode
));
584 /* See grab_values */
585 static void grab_person(const char *who
, struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
588 int wholen
= strlen(who
);
589 const char *wholine
= NULL
;
591 for (i
= 0; i
< used_atom_cnt
; i
++) {
592 const char *name
= used_atom
[i
].name
;
593 struct atom_value
*v
= &val
[i
];
594 if (!!deref
!= (*name
== '*'))
598 if (strncmp(who
, name
, wholen
))
600 if (name
[wholen
] != 0 &&
601 strcmp(name
+ wholen
, "name") &&
602 strcmp(name
+ wholen
, "email") &&
603 !starts_with(name
+ wholen
, "date"))
606 wholine
= find_wholine(who
, wholen
, buf
, sz
);
608 return; /* no point looking for it */
609 if (name
[wholen
] == 0)
610 v
->s
= copy_line(wholine
);
611 else if (!strcmp(name
+ wholen
, "name"))
612 v
->s
= copy_name(wholine
);
613 else if (!strcmp(name
+ wholen
, "email"))
614 v
->s
= copy_email(wholine
);
615 else if (starts_with(name
+ wholen
, "date"))
616 grab_date(wholine
, v
, name
);
620 * For a tag or a commit object, if "creator" or "creatordate" is
621 * requested, do something special.
623 if (strcmp(who
, "tagger") && strcmp(who
, "committer"))
624 return; /* "author" for commit object is not wanted */
626 wholine
= find_wholine(who
, wholen
, buf
, sz
);
629 for (i
= 0; i
< used_atom_cnt
; i
++) {
630 const char *name
= used_atom
[i
].name
;
631 struct atom_value
*v
= &val
[i
];
632 if (!!deref
!= (*name
== '*'))
637 if (starts_with(name
, "creatordate"))
638 grab_date(wholine
, v
, name
);
639 else if (!strcmp(name
, "creator"))
640 v
->s
= copy_line(wholine
);
644 static void find_subpos(const char *buf
, unsigned long sz
,
645 const char **sub
, unsigned long *sublen
,
646 const char **body
, unsigned long *bodylen
,
647 unsigned long *nonsiglen
,
648 const char **sig
, unsigned long *siglen
)
651 /* skip past header until we hit empty line */
652 while (*buf
&& *buf
!= '\n') {
653 eol
= strchrnul(buf
, '\n');
658 /* skip any empty lines */
662 /* parse signature first; we might not even have a subject line */
663 *sig
= buf
+ parse_signature(buf
, strlen(buf
));
664 *siglen
= strlen(*sig
);
666 /* subject is first non-empty line */
668 /* subject goes to first empty line */
669 while (buf
< *sig
&& *buf
&& *buf
!= '\n') {
670 eol
= strchrnul(buf
, '\n');
675 *sublen
= buf
- *sub
;
676 /* drop trailing newline, if present */
677 if (*sublen
&& (*sub
)[*sublen
- 1] == '\n')
680 /* skip any empty lines */
684 *bodylen
= strlen(buf
);
685 *nonsiglen
= *sig
- buf
;
689 * If 'lines' is greater than 0, append that many lines from the given
690 * 'buf' of length 'size' to the given strbuf.
692 static void append_lines(struct strbuf
*out
, const char *buf
, unsigned long size
, int lines
)
695 const char *sp
, *eol
;
700 for (i
= 0; i
< lines
&& sp
< buf
+ size
; i
++) {
702 strbuf_addstr(out
, "\n ");
703 eol
= memchr(sp
, '\n', size
- (sp
- buf
));
704 len
= eol
? eol
- sp
: size
- (sp
- buf
);
705 strbuf_add(out
, sp
, len
);
712 /* See grab_values */
713 static void grab_sub_body_contents(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
716 const char *subpos
= NULL
, *bodypos
= NULL
, *sigpos
= NULL
;
717 unsigned long sublen
= 0, bodylen
= 0, nonsiglen
= 0, siglen
= 0;
719 for (i
= 0; i
< used_atom_cnt
; i
++) {
720 const char *name
= used_atom
[i
].name
;
721 struct atom_value
*v
= &val
[i
];
722 const char *valp
= NULL
;
723 if (!!deref
!= (*name
== '*'))
727 if (strcmp(name
, "subject") &&
728 strcmp(name
, "body") &&
729 strcmp(name
, "contents") &&
730 strcmp(name
, "contents:subject") &&
731 strcmp(name
, "contents:body") &&
732 strcmp(name
, "contents:signature") &&
733 !starts_with(name
, "contents:lines="))
738 &bodypos
, &bodylen
, &nonsiglen
,
741 if (!strcmp(name
, "subject"))
742 v
->s
= copy_subject(subpos
, sublen
);
743 else if (!strcmp(name
, "contents:subject"))
744 v
->s
= copy_subject(subpos
, sublen
);
745 else if (!strcmp(name
, "body"))
746 v
->s
= xmemdupz(bodypos
, bodylen
);
747 else if (!strcmp(name
, "contents:body"))
748 v
->s
= xmemdupz(bodypos
, nonsiglen
);
749 else if (!strcmp(name
, "contents:signature"))
750 v
->s
= xmemdupz(sigpos
, siglen
);
751 else if (!strcmp(name
, "contents"))
752 v
->s
= xstrdup(subpos
);
753 else if (skip_prefix(name
, "contents:lines=", &valp
)) {
754 struct strbuf s
= STRBUF_INIT
;
755 const char *contents_end
= bodylen
+ bodypos
- siglen
;
757 if (strtoul_ui(valp
, 10, &v
->u
.contents
.lines
))
758 die(_("positive value expected contents:lines=%s"), valp
);
759 /* Size is the length of the message after removing the signature */
760 append_lines(&s
, subpos
, contents_end
- subpos
, v
->u
.contents
.lines
);
761 v
->s
= strbuf_detach(&s
, NULL
);
767 * We want to have empty print-string for field requests
768 * that do not apply (e.g. "authordate" for a tag object)
770 static void fill_missing_values(struct atom_value
*val
)
773 for (i
= 0; i
< used_atom_cnt
; i
++) {
774 struct atom_value
*v
= &val
[i
];
781 * val is a list of atom_value to hold returned values. Extract
782 * the values for atoms in used_atom array out of (obj, buf, sz).
783 * when deref is false, (obj, buf, sz) is the object that is
784 * pointed at by the ref itself; otherwise it is the object the
785 * ref (which is a tag) refers to.
787 static void grab_values(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
789 grab_common_values(val
, deref
, obj
, buf
, sz
);
792 grab_tag_values(val
, deref
, obj
, buf
, sz
);
793 grab_sub_body_contents(val
, deref
, obj
, buf
, sz
);
794 grab_person("tagger", val
, deref
, obj
, buf
, sz
);
797 grab_commit_values(val
, deref
, obj
, buf
, sz
);
798 grab_sub_body_contents(val
, deref
, obj
, buf
, sz
);
799 grab_person("author", val
, deref
, obj
, buf
, sz
);
800 grab_person("committer", val
, deref
, obj
, buf
, sz
);
803 /* grab_tree_values(val, deref, obj, buf, sz); */
806 /* grab_blob_values(val, deref, obj, buf, sz); */
809 die("Eh? Object of type %d?", obj
->type
);
813 static inline char *copy_advance(char *dst
, const char *src
)
820 static const char *strip_ref_components(const char *refname
, const char *nr_arg
)
823 long nr
= strtol(nr_arg
, &end
, 10);
825 const char *start
= refname
;
827 if (nr
< 1 || *end
!= '\0')
828 die(":strip= requires a positive integer argument");
833 die("ref '%s' does not have %ld components to :strip",
844 * Parse the object referred by ref, and grab needed value.
846 static void populate_value(struct ref_array_item
*ref
)
852 const unsigned char *tagged
;
854 ref
->value
= xcalloc(used_atom_cnt
, sizeof(struct atom_value
));
856 if (need_symref
&& (ref
->flag
& REF_ISSYMREF
) && !ref
->symref
) {
857 unsigned char unused1
[20];
858 ref
->symref
= resolve_refdup(ref
->refname
, RESOLVE_REF_READING
,
864 /* Fill in specials first */
865 for (i
= 0; i
< used_atom_cnt
; i
++) {
866 struct used_atom
*atom
= &used_atom
[i
];
867 const char *name
= used_atom
[i
].name
;
868 struct atom_value
*v
= &ref
->value
[i
];
872 struct branch
*branch
= NULL
;
874 v
->handler
= append_atom
;
881 if (starts_with(name
, "refname"))
882 refname
= ref
->refname
;
883 else if (starts_with(name
, "symref"))
884 refname
= ref
->symref
? ref
->symref
: "";
885 else if (starts_with(name
, "upstream")) {
886 const char *branch_name
;
887 /* only local branches may have an upstream */
888 if (!skip_prefix(ref
->refname
, "refs/heads/",
891 branch
= branch_get(branch_name
);
893 refname
= branch_get_upstream(branch
, NULL
);
896 } else if (starts_with(name
, "push")) {
897 const char *branch_name
;
898 if (!skip_prefix(ref
->refname
, "refs/heads/",
901 branch
= branch_get(branch_name
);
903 refname
= branch_get_push(branch
, NULL
);
906 } else if (starts_with(name
, "color:")) {
907 v
->s
= atom
->u
.color
;
909 } else if (!strcmp(name
, "flag")) {
910 char buf
[256], *cp
= buf
;
911 if (ref
->flag
& REF_ISSYMREF
)
912 cp
= copy_advance(cp
, ",symref");
913 if (ref
->flag
& REF_ISPACKED
)
914 cp
= copy_advance(cp
, ",packed");
919 v
->s
= xstrdup(buf
+ 1);
922 } else if (!deref
&& grab_objectname(name
, ref
->objectname
, v
)) {
924 } else if (!strcmp(name
, "HEAD")) {
926 unsigned char sha1
[20];
928 head
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
930 if (!strcmp(ref
->refname
, head
))
935 } else if (starts_with(name
, "align")) {
936 v
->u
.align
= atom
->u
.align
;
937 v
->handler
= align_atom_handler
;
939 } else if (!strcmp(name
, "end")) {
940 v
->handler
= end_atom_handler
;
945 formatp
= strchr(name
, ':');
947 int num_ours
, num_theirs
;
951 if (!strcmp(formatp
, "short"))
952 refname
= shorten_unambiguous_ref(refname
,
953 warn_ambiguous_refs
);
954 else if (skip_prefix(formatp
, "strip=", &arg
))
955 refname
= strip_ref_components(refname
, arg
);
956 else if (!strcmp(formatp
, "track") &&
957 (starts_with(name
, "upstream") ||
958 starts_with(name
, "push"))) {
960 if (stat_tracking_info(branch
, &num_ours
,
964 if (!num_ours
&& !num_theirs
)
967 v
->s
= xstrfmt("[behind %d]", num_theirs
);
968 else if (!num_theirs
)
969 v
->s
= xstrfmt("[ahead %d]", num_ours
);
971 v
->s
= xstrfmt("[ahead %d, behind %d]",
972 num_ours
, num_theirs
);
974 } else if (!strcmp(formatp
, "trackshort") &&
975 (starts_with(name
, "upstream") ||
976 starts_with(name
, "push"))) {
979 if (stat_tracking_info(branch
, &num_ours
,
983 if (!num_ours
&& !num_theirs
)
987 else if (!num_theirs
)
993 die("unknown %.*s format %s",
994 (int)(formatp
- name
), name
, formatp
);
1000 v
->s
= xstrfmt("%s^{}", refname
);
1003 for (i
= 0; i
< used_atom_cnt
; i
++) {
1004 struct atom_value
*v
= &ref
->value
[i
];
1011 buf
= get_obj(ref
->objectname
, &obj
, &size
, &eaten
);
1013 die("missing object %s for %s",
1014 sha1_to_hex(ref
->objectname
), ref
->refname
);
1016 die("parse_object_buffer failed on %s for %s",
1017 sha1_to_hex(ref
->objectname
), ref
->refname
);
1019 grab_values(ref
->value
, 0, obj
, buf
, size
);
1024 * If there is no atom that wants to know about tagged
1025 * object, we are done.
1027 if (!need_tagged
|| (obj
->type
!= OBJ_TAG
))
1031 * If it is a tag object, see if we use a value that derefs
1032 * the object, and if we do grab the object it refers to.
1034 tagged
= ((struct tag
*)obj
)->tagged
->oid
.hash
;
1037 * NEEDSWORK: This derefs tag only once, which
1038 * is good to deal with chains of trust, but
1039 * is not consistent with what deref_tag() does
1040 * which peels the onion to the core.
1042 buf
= get_obj(tagged
, &obj
, &size
, &eaten
);
1044 die("missing object %s for %s",
1045 sha1_to_hex(tagged
), ref
->refname
);
1047 die("parse_object_buffer failed on %s for %s",
1048 sha1_to_hex(tagged
), ref
->refname
);
1049 grab_values(ref
->value
, 1, obj
, buf
, size
);
1055 * Given a ref, return the value for the atom. This lazily gets value
1056 * out of the object by calling populate value.
1058 static void get_ref_atom_value(struct ref_array_item
*ref
, int atom
, struct atom_value
**v
)
1061 populate_value(ref
);
1062 fill_missing_values(ref
->value
);
1064 *v
= &ref
->value
[atom
];
1067 enum contains_result
{
1068 CONTAINS_UNKNOWN
= -1,
1074 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1077 * At each recursion step, the stack items points to the commits whose
1078 * ancestors are to be inspected.
1080 struct contains_stack
{
1082 struct contains_stack_entry
{
1083 struct commit
*commit
;
1084 struct commit_list
*parents
;
1088 static int in_commit_list(const struct commit_list
*want
, struct commit
*c
)
1090 for (; want
; want
= want
->next
)
1091 if (!oidcmp(&want
->item
->object
.oid
, &c
->object
.oid
))
1097 * Test whether the candidate or one of its parents is contained in the list.
1098 * Do not recurse to find out, though, but return -1 if inconclusive.
1100 static enum contains_result
contains_test(struct commit
*candidate
,
1101 const struct commit_list
*want
)
1103 /* was it previously marked as containing a want commit? */
1104 if (candidate
->object
.flags
& TMP_MARK
)
1106 /* or marked as not possibly containing a want commit? */
1107 if (candidate
->object
.flags
& UNINTERESTING
)
1110 if (in_commit_list(want
, candidate
)) {
1111 candidate
->object
.flags
|= TMP_MARK
;
1115 if (parse_commit(candidate
) < 0)
1121 static void push_to_contains_stack(struct commit
*candidate
, struct contains_stack
*contains_stack
)
1123 ALLOC_GROW(contains_stack
->contains_stack
, contains_stack
->nr
+ 1, contains_stack
->alloc
);
1124 contains_stack
->contains_stack
[contains_stack
->nr
].commit
= candidate
;
1125 contains_stack
->contains_stack
[contains_stack
->nr
++].parents
= candidate
->parents
;
1128 static enum contains_result
contains_tag_algo(struct commit
*candidate
,
1129 const struct commit_list
*want
)
1131 struct contains_stack contains_stack
= { 0, 0, NULL
};
1132 int result
= contains_test(candidate
, want
);
1134 if (result
!= CONTAINS_UNKNOWN
)
1137 push_to_contains_stack(candidate
, &contains_stack
);
1138 while (contains_stack
.nr
) {
1139 struct contains_stack_entry
*entry
= &contains_stack
.contains_stack
[contains_stack
.nr
- 1];
1140 struct commit
*commit
= entry
->commit
;
1141 struct commit_list
*parents
= entry
->parents
;
1144 commit
->object
.flags
|= UNINTERESTING
;
1145 contains_stack
.nr
--;
1148 * If we just popped the stack, parents->item has been marked,
1149 * therefore contains_test will return a meaningful 0 or 1.
1151 else switch (contains_test(parents
->item
, want
)) {
1153 commit
->object
.flags
|= TMP_MARK
;
1154 contains_stack
.nr
--;
1157 entry
->parents
= parents
->next
;
1159 case CONTAINS_UNKNOWN
:
1160 push_to_contains_stack(parents
->item
, &contains_stack
);
1164 free(contains_stack
.contains_stack
);
1165 return contains_test(candidate
, want
);
1168 static int commit_contains(struct ref_filter
*filter
, struct commit
*commit
)
1170 if (filter
->with_commit_tag_algo
)
1171 return contains_tag_algo(commit
, filter
->with_commit
);
1172 return is_descendant_of(commit
, filter
->with_commit
);
1176 * Return 1 if the refname matches one of the patterns, otherwise 0.
1177 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1178 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1179 * matches "refs/heads/mas*", too).
1181 static int match_pattern(const char **patterns
, const char *refname
)
1184 * When no '--format' option is given we need to skip the prefix
1185 * for matching refs of tags and branches.
1187 (void)(skip_prefix(refname
, "refs/tags/", &refname
) ||
1188 skip_prefix(refname
, "refs/heads/", &refname
) ||
1189 skip_prefix(refname
, "refs/remotes/", &refname
) ||
1190 skip_prefix(refname
, "refs/", &refname
));
1192 for (; *patterns
; patterns
++) {
1193 if (!wildmatch(*patterns
, refname
, 0, NULL
))
1200 * Return 1 if the refname matches one of the patterns, otherwise 0.
1201 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1202 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1203 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1205 static int match_name_as_path(const char **pattern
, const char *refname
)
1207 int namelen
= strlen(refname
);
1208 for (; *pattern
; pattern
++) {
1209 const char *p
= *pattern
;
1210 int plen
= strlen(p
);
1212 if ((plen
<= namelen
) &&
1213 !strncmp(refname
, p
, plen
) &&
1214 (refname
[plen
] == '\0' ||
1215 refname
[plen
] == '/' ||
1218 if (!wildmatch(p
, refname
, WM_PATHNAME
, NULL
))
1224 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1225 static int filter_pattern_match(struct ref_filter
*filter
, const char *refname
)
1227 if (!*filter
->name_patterns
)
1228 return 1; /* No pattern always matches */
1229 if (filter
->match_as_path
)
1230 return match_name_as_path(filter
->name_patterns
, refname
);
1231 return match_pattern(filter
->name_patterns
, refname
);
1235 * Given a ref (sha1, refname), check if the ref belongs to the array
1236 * of sha1s. If the given ref is a tag, check if the given tag points
1237 * at one of the sha1s in the given sha1 array.
1238 * the given sha1_array.
1240 * 1. Only a single level of inderection is obtained, we might want to
1241 * change this to account for multiple levels (e.g. annotated tags
1242 * pointing to annotated tags pointing to a commit.)
1243 * 2. As the refs are cached we might know what refname peels to without
1244 * the need to parse the object via parse_object(). peel_ref() might be a
1245 * more efficient alternative to obtain the pointee.
1247 static const unsigned char *match_points_at(struct sha1_array
*points_at
,
1248 const unsigned char *sha1
,
1249 const char *refname
)
1251 const unsigned char *tagged_sha1
= NULL
;
1254 if (sha1_array_lookup(points_at
, sha1
) >= 0)
1256 obj
= parse_object(sha1
);
1258 die(_("malformed object at '%s'"), refname
);
1259 if (obj
->type
== OBJ_TAG
)
1260 tagged_sha1
= ((struct tag
*)obj
)->tagged
->oid
.hash
;
1261 if (tagged_sha1
&& sha1_array_lookup(points_at
, tagged_sha1
) >= 0)
1266 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1267 static struct ref_array_item
*new_ref_array_item(const char *refname
,
1268 const unsigned char *objectname
,
1271 size_t len
= strlen(refname
);
1272 struct ref_array_item
*ref
= xcalloc(1, sizeof(struct ref_array_item
) + len
+ 1);
1273 memcpy(ref
->refname
, refname
, len
);
1274 ref
->refname
[len
] = '\0';
1275 hashcpy(ref
->objectname
, objectname
);
1281 static int filter_ref_kind(struct ref_filter
*filter
, const char *refname
)
1289 { "refs/heads/" , FILTER_REFS_BRANCHES
},
1290 { "refs/remotes/" , FILTER_REFS_REMOTES
},
1291 { "refs/tags/", FILTER_REFS_TAGS
}
1294 if (filter
->kind
== FILTER_REFS_BRANCHES
||
1295 filter
->kind
== FILTER_REFS_REMOTES
||
1296 filter
->kind
== FILTER_REFS_TAGS
)
1297 return filter
->kind
;
1298 else if (!strcmp(refname
, "HEAD"))
1299 return FILTER_REFS_DETACHED_HEAD
;
1301 for (i
= 0; i
< ARRAY_SIZE(ref_kind
); i
++) {
1302 if (starts_with(refname
, ref_kind
[i
].prefix
))
1303 return ref_kind
[i
].kind
;
1306 return FILTER_REFS_OTHERS
;
1310 * A call-back given to for_each_ref(). Filter refs and keep them for
1311 * later object processing.
1313 static int ref_filter_handler(const char *refname
, const struct object_id
*oid
, int flag
, void *cb_data
)
1315 struct ref_filter_cbdata
*ref_cbdata
= cb_data
;
1316 struct ref_filter
*filter
= ref_cbdata
->filter
;
1317 struct ref_array_item
*ref
;
1318 struct commit
*commit
= NULL
;
1321 if (flag
& REF_BAD_NAME
) {
1322 warning("ignoring ref with broken name %s", refname
);
1326 if (flag
& REF_ISBROKEN
) {
1327 warning("ignoring broken ref %s", refname
);
1331 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1332 kind
= filter_ref_kind(filter
, refname
);
1333 if (!(kind
& filter
->kind
))
1336 if (!filter_pattern_match(filter
, refname
))
1339 if (filter
->points_at
.nr
&& !match_points_at(&filter
->points_at
, oid
->hash
, refname
))
1343 * A merge filter is applied on refs pointing to commits. Hence
1344 * obtain the commit using the 'oid' available and discard all
1345 * non-commits early. The actual filtering is done later.
1347 if (filter
->merge_commit
|| filter
->with_commit
|| filter
->verbose
) {
1348 commit
= lookup_commit_reference_gently(oid
->hash
, 1);
1351 /* We perform the filtering for the '--contains' option */
1352 if (filter
->with_commit
&&
1353 !commit_contains(filter
, commit
))
1358 * We do not open the object yet; sort may only need refname
1359 * to do its job and the resulting list may yet to be pruned
1360 * by maxcount logic.
1362 ref
= new_ref_array_item(refname
, oid
->hash
, flag
);
1363 ref
->commit
= commit
;
1365 REALLOC_ARRAY(ref_cbdata
->array
->items
, ref_cbdata
->array
->nr
+ 1);
1366 ref_cbdata
->array
->items
[ref_cbdata
->array
->nr
++] = ref
;
1371 /* Free memory allocated for a ref_array_item */
1372 static void free_array_item(struct ref_array_item
*item
)
1374 free((char *)item
->symref
);
1378 /* Free all memory allocated for ref_array */
1379 void ref_array_clear(struct ref_array
*array
)
1383 for (i
= 0; i
< array
->nr
; i
++)
1384 free_array_item(array
->items
[i
]);
1386 array
->items
= NULL
;
1387 array
->nr
= array
->alloc
= 0;
1390 static void do_merge_filter(struct ref_filter_cbdata
*ref_cbdata
)
1392 struct rev_info revs
;
1394 struct ref_filter
*filter
= ref_cbdata
->filter
;
1395 struct ref_array
*array
= ref_cbdata
->array
;
1396 struct commit
**to_clear
= xcalloc(sizeof(struct commit
*), array
->nr
);
1398 init_revisions(&revs
, NULL
);
1400 for (i
= 0; i
< array
->nr
; i
++) {
1401 struct ref_array_item
*item
= array
->items
[i
];
1402 add_pending_object(&revs
, &item
->commit
->object
, item
->refname
);
1403 to_clear
[i
] = item
->commit
;
1406 filter
->merge_commit
->object
.flags
|= UNINTERESTING
;
1407 add_pending_object(&revs
, &filter
->merge_commit
->object
, "");
1410 if (prepare_revision_walk(&revs
))
1411 die(_("revision walk setup failed"));
1416 for (i
= 0; i
< old_nr
; i
++) {
1417 struct ref_array_item
*item
= array
->items
[i
];
1418 struct commit
*commit
= item
->commit
;
1420 int is_merged
= !!(commit
->object
.flags
& UNINTERESTING
);
1422 if (is_merged
== (filter
->merge
== REF_FILTER_MERGED_INCLUDE
))
1423 array
->items
[array
->nr
++] = array
->items
[i
];
1425 free_array_item(item
);
1428 for (i
= 0; i
< old_nr
; i
++)
1429 clear_commit_marks(to_clear
[i
], ALL_REV_FLAGS
);
1430 clear_commit_marks(filter
->merge_commit
, ALL_REV_FLAGS
);
1435 * API for filtering a set of refs. Based on the type of refs the user
1436 * has requested, we iterate through those refs and apply filters
1437 * as per the given ref_filter structure and finally store the
1438 * filtered refs in the ref_array structure.
1440 int filter_refs(struct ref_array
*array
, struct ref_filter
*filter
, unsigned int type
)
1442 struct ref_filter_cbdata ref_cbdata
;
1444 unsigned int broken
= 0;
1446 ref_cbdata
.array
= array
;
1447 ref_cbdata
.filter
= filter
;
1449 if (type
& FILTER_REFS_INCLUDE_BROKEN
)
1451 filter
->kind
= type
& FILTER_REFS_KIND_MASK
;
1453 /* Simple per-ref filtering */
1455 die("filter_refs: invalid type");
1458 * For common cases where we need only branches or remotes or tags,
1459 * we only iterate through those refs. If a mix of refs is needed,
1460 * we iterate over all refs and filter out required refs with the help
1461 * of filter_ref_kind().
1463 if (filter
->kind
== FILTER_REFS_BRANCHES
)
1464 ret
= for_each_fullref_in("refs/heads/", ref_filter_handler
, &ref_cbdata
, broken
);
1465 else if (filter
->kind
== FILTER_REFS_REMOTES
)
1466 ret
= for_each_fullref_in("refs/remotes/", ref_filter_handler
, &ref_cbdata
, broken
);
1467 else if (filter
->kind
== FILTER_REFS_TAGS
)
1468 ret
= for_each_fullref_in("refs/tags/", ref_filter_handler
, &ref_cbdata
, broken
);
1469 else if (filter
->kind
& FILTER_REFS_ALL
)
1470 ret
= for_each_fullref_in("", ref_filter_handler
, &ref_cbdata
, broken
);
1471 if (!ret
&& (filter
->kind
& FILTER_REFS_DETACHED_HEAD
))
1472 head_ref(ref_filter_handler
, &ref_cbdata
);
1476 /* Filters that need revision walking */
1477 if (filter
->merge_commit
)
1478 do_merge_filter(&ref_cbdata
);
1483 static int cmp_ref_sorting(struct ref_sorting
*s
, struct ref_array_item
*a
, struct ref_array_item
*b
)
1485 struct atom_value
*va
, *vb
;
1487 cmp_type cmp_type
= used_atom
[s
->atom
].type
;
1489 get_ref_atom_value(a
, s
->atom
, &va
);
1490 get_ref_atom_value(b
, s
->atom
, &vb
);
1492 cmp
= versioncmp(va
->s
, vb
->s
);
1493 else if (cmp_type
== FIELD_STR
)
1494 cmp
= strcmp(va
->s
, vb
->s
);
1496 if (va
->ul
< vb
->ul
)
1498 else if (va
->ul
== vb
->ul
)
1499 cmp
= strcmp(a
->refname
, b
->refname
);
1504 return (s
->reverse
) ? -cmp
: cmp
;
1507 static struct ref_sorting
*ref_sorting
;
1508 static int compare_refs(const void *a_
, const void *b_
)
1510 struct ref_array_item
*a
= *((struct ref_array_item
**)a_
);
1511 struct ref_array_item
*b
= *((struct ref_array_item
**)b_
);
1512 struct ref_sorting
*s
;
1514 for (s
= ref_sorting
; s
; s
= s
->next
) {
1515 int cmp
= cmp_ref_sorting(s
, a
, b
);
1522 void ref_array_sort(struct ref_sorting
*sorting
, struct ref_array
*array
)
1524 ref_sorting
= sorting
;
1525 qsort(array
->items
, array
->nr
, sizeof(struct ref_array_item
*), compare_refs
);
1528 static int hex1(char ch
)
1530 if ('0' <= ch
&& ch
<= '9')
1532 else if ('a' <= ch
&& ch
<= 'f')
1533 return ch
- 'a' + 10;
1534 else if ('A' <= ch
&& ch
<= 'F')
1535 return ch
- 'A' + 10;
1538 static int hex2(const char *cp
)
1541 return (hex1(cp
[0]) << 4) | hex1(cp
[1]);
1546 static void append_literal(const char *cp
, const char *ep
, struct ref_formatting_state
*state
)
1548 struct strbuf
*s
= &state
->stack
->output
;
1550 while (*cp
&& (!ep
|| cp
< ep
)) {
1555 int ch
= hex2(cp
+ 1);
1557 strbuf_addch(s
, ch
);
1563 strbuf_addch(s
, *cp
);
1568 void show_ref_array_item(struct ref_array_item
*info
, const char *format
, int quote_style
)
1570 const char *cp
, *sp
, *ep
;
1571 struct strbuf
*final_buf
;
1572 struct ref_formatting_state state
= REF_FORMATTING_STATE_INIT
;
1574 state
.quote_style
= quote_style
;
1575 push_stack_element(&state
.stack
);
1577 for (cp
= format
; *cp
&& (sp
= find_next(cp
)); cp
= ep
+ 1) {
1578 struct atom_value
*atomv
;
1580 ep
= strchr(sp
, ')');
1582 append_literal(cp
, sp
, &state
);
1583 get_ref_atom_value(info
, parse_ref_filter_atom(sp
+ 2, ep
), &atomv
);
1584 atomv
->handler(atomv
, &state
);
1587 sp
= cp
+ strlen(cp
);
1588 append_literal(cp
, sp
, &state
);
1590 if (need_color_reset_at_eol
) {
1591 struct atom_value resetv
;
1592 char color
[COLOR_MAXLEN
] = "";
1594 if (color_parse("reset", color
) < 0)
1595 die("BUG: couldn't parse 'reset' as a color");
1597 append_atom(&resetv
, &state
);
1599 if (state
.stack
->prev
)
1600 die(_("format: %%(end) atom missing"));
1601 final_buf
= &state
.stack
->output
;
1602 fwrite(final_buf
->buf
, 1, final_buf
->len
, stdout
);
1603 pop_stack_element(&state
.stack
);
1607 /* If no sorting option is given, use refname to sort as default */
1608 struct ref_sorting
*ref_default_sorting(void)
1610 static const char cstr_name
[] = "refname";
1612 struct ref_sorting
*sorting
= xcalloc(1, sizeof(*sorting
));
1614 sorting
->next
= NULL
;
1615 sorting
->atom
= parse_ref_filter_atom(cstr_name
, cstr_name
+ strlen(cstr_name
));
1619 int parse_opt_ref_sorting(const struct option
*opt
, const char *arg
, int unset
)
1621 struct ref_sorting
**sorting_tail
= opt
->value
;
1622 struct ref_sorting
*s
;
1625 if (!arg
) /* should --no-sort void the list ? */
1628 s
= xcalloc(1, sizeof(*s
));
1629 s
->next
= *sorting_tail
;
1636 if (skip_prefix(arg
, "version:", &arg
) ||
1637 skip_prefix(arg
, "v:", &arg
))
1640 s
->atom
= parse_ref_filter_atom(arg
, arg
+len
);
1644 int parse_opt_merge_filter(const struct option
*opt
, const char *arg
, int unset
)
1646 struct ref_filter
*rf
= opt
->value
;
1647 unsigned char sha1
[20];
1649 rf
->merge
= starts_with(opt
->long_name
, "no")
1650 ? REF_FILTER_MERGED_OMIT
1651 : REF_FILTER_MERGED_INCLUDE
;
1653 if (get_sha1(arg
, sha1
))
1654 die(_("malformed object name %s"), arg
);
1656 rf
->merge_commit
= lookup_commit_reference_gently(sha1
, 0);
1657 if (!rf
->merge_commit
)
1658 return opterror(opt
, "must point to a commit", 0);