3 #include "parse-options.h"
11 #include "ref-filter.h"
14 #include "git-compat-util.h"
17 typedef enum { FIELD_STR
, FIELD_ULONG
, FIELD_TIME
} cmp_type
;
20 * An atom is a valid field atom listed below, possibly prefixed with
21 * a "*" to denote deref_tag().
23 * We parse given format string and sort specifiers, and make a list
24 * of properties that we need to extract out of objects. ref_array_item
25 * structure will hold an array of values extracted that can be
26 * indexed with the "atom number", which is an index into this
29 static struct used_atom
{
33 char color
[COLOR_MAXLEN
];
36 static int used_atom_cnt
, need_tagged
, need_symref
;
37 static int need_color_reset_at_eol
;
39 static void color_atom_parser(struct used_atom
*atom
, const char *color_value
)
42 die(_("expected format: %%(color:<color>)"));
43 if (color_parse(color_value
, atom
->u
.color
) < 0)
44 die(_("unrecognized color: %%(color:%s)"), color_value
);
50 void (*parser
)(struct used_atom
*atom
, const char *arg
);
54 { "objectsize", FIELD_ULONG
},
58 { "numparent", FIELD_ULONG
},
65 { "authordate", FIELD_TIME
},
69 { "committerdate", FIELD_TIME
},
73 { "taggerdate", FIELD_TIME
},
75 { "creatordate", FIELD_TIME
},
84 { "color", FIELD_STR
, color_atom_parser
},
89 #define REF_FORMATTING_STATE_INIT { 0, NULL }
101 struct ref_formatting_stack
{
102 struct ref_formatting_stack
*prev
;
103 struct strbuf output
;
104 void (*at_end
)(struct ref_formatting_stack
*stack
);
108 struct ref_formatting_state
{
110 struct ref_formatting_stack
*stack
;
117 struct contents contents
;
119 void (*handler
)(struct atom_value
*atomv
, struct ref_formatting_state
*state
);
120 unsigned long ul
; /* used for sorting when not FIELD_STR */
124 * Used to parse format string and sort specifiers
126 int parse_ref_filter_atom(const char *atom
, const char *ep
)
133 if (*sp
== '*' && sp
< ep
)
136 die("malformed field name: %.*s", (int)(ep
-atom
), atom
);
138 /* Do we have the atom already used elsewhere? */
139 for (i
= 0; i
< used_atom_cnt
; i
++) {
140 int len
= strlen(used_atom
[i
].name
);
141 if (len
== ep
- atom
&& !memcmp(used_atom
[i
].name
, atom
, len
))
145 /* Is the atom a valid one? */
146 for (i
= 0; i
< ARRAY_SIZE(valid_atom
); i
++) {
147 int len
= strlen(valid_atom
[i
].name
);
150 * If the atom name has a colon, strip it and everything after
151 * it off - it specifies the format for this entry, and
152 * shouldn't be used for checking against the valid_atom
155 arg
= memchr(sp
, ':', ep
- sp
);
156 if (len
== (arg
? arg
: ep
) - sp
&&
157 !memcmp(valid_atom
[i
].name
, sp
, len
))
161 if (ARRAY_SIZE(valid_atom
) <= i
)
162 die("unknown field name: %.*s", (int)(ep
-atom
), atom
);
164 /* Add it in, including the deref prefix */
167 REALLOC_ARRAY(used_atom
, used_atom_cnt
);
168 used_atom
[at
].name
= xmemdupz(atom
, ep
- atom
);
169 used_atom
[at
].type
= valid_atom
[i
].cmp_type
;
171 arg
= used_atom
[at
].name
+ (arg
- atom
) + 1;
172 memset(&used_atom
[at
].u
, 0, sizeof(used_atom
[at
].u
));
173 if (valid_atom
[i
].parser
)
174 valid_atom
[i
].parser(&used_atom
[at
], arg
);
177 if (!strcmp(used_atom
[at
].name
, "symref"))
182 static void quote_formatting(struct strbuf
*s
, const char *str
, int quote_style
)
184 switch (quote_style
) {
186 strbuf_addstr(s
, str
);
189 sq_quote_buf(s
, str
);
192 perl_quote_buf(s
, str
);
195 python_quote_buf(s
, str
);
198 tcl_quote_buf(s
, str
);
203 static void append_atom(struct atom_value
*v
, struct ref_formatting_state
*state
)
206 * Quote formatting is only done when the stack has a single
207 * element. Otherwise quote formatting is done on the
208 * element's entire output strbuf when the %(end) atom is
211 if (!state
->stack
->prev
)
212 quote_formatting(&state
->stack
->output
, v
->s
, state
->quote_style
);
214 strbuf_addstr(&state
->stack
->output
, v
->s
);
217 static void push_stack_element(struct ref_formatting_stack
**stack
)
219 struct ref_formatting_stack
*s
= xcalloc(1, sizeof(struct ref_formatting_stack
));
221 strbuf_init(&s
->output
, 0);
226 static void pop_stack_element(struct ref_formatting_stack
**stack
)
228 struct ref_formatting_stack
*current
= *stack
;
229 struct ref_formatting_stack
*prev
= current
->prev
;
232 strbuf_addbuf(&prev
->output
, ¤t
->output
);
233 strbuf_release(¤t
->output
);
238 static void end_align_handler(struct ref_formatting_stack
*stack
)
240 struct align
*align
= (struct align
*)stack
->at_end_data
;
241 struct strbuf s
= STRBUF_INIT
;
243 strbuf_utf8_align(&s
, align
->position
, align
->width
, stack
->output
.buf
);
244 strbuf_swap(&stack
->output
, &s
);
248 static void align_atom_handler(struct atom_value
*atomv
, struct ref_formatting_state
*state
)
250 struct ref_formatting_stack
*new;
252 push_stack_element(&state
->stack
);
254 new->at_end
= end_align_handler
;
255 new->at_end_data
= &atomv
->u
.align
;
258 static void end_atom_handler(struct atom_value
*atomv
, struct ref_formatting_state
*state
)
260 struct ref_formatting_stack
*current
= state
->stack
;
261 struct strbuf s
= STRBUF_INIT
;
263 if (!current
->at_end
)
264 die(_("format: %%(end) atom used without corresponding atom"));
265 current
->at_end(current
);
268 * Perform quote formatting when the stack element is that of
269 * a supporting atom. If nested then perform quote formatting
270 * only on the topmost supporting atom.
272 if (!state
->stack
->prev
->prev
) {
273 quote_formatting(&s
, current
->output
.buf
, state
->quote_style
);
274 strbuf_swap(¤t
->output
, &s
);
277 pop_stack_element(&state
->stack
);
280 static int match_atom_name(const char *name
, const char *atom_name
, const char **val
)
284 if (!skip_prefix(name
, atom_name
, &body
))
285 return 0; /* doesn't even begin with "atom_name" */
287 *val
= NULL
; /* %(atom_name) and no customization */
291 return 0; /* "atom_namefoo" is not "atom_name" or "atom_name:..." */
292 *val
= body
+ 1; /* "atom_name:val" */
297 * In a format string, find the next occurrence of %(atom).
299 static const char *find_next(const char *cp
)
304 * %( is the start of an atom;
305 * %% is a quoted per-cent.
309 else if (cp
[1] == '%')
310 cp
++; /* skip over two % */
311 /* otherwise this is a singleton, literal % */
319 * Make sure the format string is well formed, and parse out
322 int verify_ref_format(const char *format
)
326 need_color_reset_at_eol
= 0;
327 for (cp
= format
; *cp
&& (sp
= find_next(cp
)); ) {
328 const char *color
, *ep
= strchr(sp
, ')');
332 return error("malformed format string %s", sp
);
333 /* sp points at "%(" and ep points at the closing ")" */
334 at
= parse_ref_filter_atom(sp
+ 2, ep
);
337 if (skip_prefix(used_atom
[at
].name
, "color:", &color
))
338 need_color_reset_at_eol
= !!strcmp(color
, "reset");
344 * Given an object name, read the object data and size, and return a
345 * "struct object". If the object data we are returning is also borrowed
346 * by the "struct object" representation, set *eaten as well---it is a
347 * signal from parse_object_buffer to us not to free the buffer.
349 static void *get_obj(const unsigned char *sha1
, struct object
**obj
, unsigned long *sz
, int *eaten
)
351 enum object_type type
;
352 void *buf
= read_sha1_file(sha1
, &type
, sz
);
355 *obj
= parse_object_buffer(sha1
, type
, *sz
, buf
, eaten
);
361 static int grab_objectname(const char *name
, const unsigned char *sha1
,
362 struct atom_value
*v
)
364 if (!strcmp(name
, "objectname")) {
365 v
->s
= xstrdup(sha1_to_hex(sha1
));
368 if (!strcmp(name
, "objectname:short")) {
369 v
->s
= xstrdup(find_unique_abbrev(sha1
, DEFAULT_ABBREV
));
375 /* See grab_values */
376 static void grab_common_values(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
380 for (i
= 0; i
< used_atom_cnt
; i
++) {
381 const char *name
= used_atom
[i
].name
;
382 struct atom_value
*v
= &val
[i
];
383 if (!!deref
!= (*name
== '*'))
387 if (!strcmp(name
, "objecttype"))
388 v
->s
= typename(obj
->type
);
389 else if (!strcmp(name
, "objectsize")) {
391 v
->s
= xstrfmt("%lu", sz
);
394 grab_objectname(name
, obj
->oid
.hash
, v
);
398 /* See grab_values */
399 static void grab_tag_values(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
402 struct tag
*tag
= (struct tag
*) obj
;
404 for (i
= 0; i
< used_atom_cnt
; i
++) {
405 const char *name
= used_atom
[i
].name
;
406 struct atom_value
*v
= &val
[i
];
407 if (!!deref
!= (*name
== '*'))
411 if (!strcmp(name
, "tag"))
413 else if (!strcmp(name
, "type") && tag
->tagged
)
414 v
->s
= typename(tag
->tagged
->type
);
415 else if (!strcmp(name
, "object") && tag
->tagged
)
416 v
->s
= xstrdup(oid_to_hex(&tag
->tagged
->oid
));
420 /* See grab_values */
421 static void grab_commit_values(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
424 struct commit
*commit
= (struct commit
*) obj
;
426 for (i
= 0; i
< used_atom_cnt
; i
++) {
427 const char *name
= used_atom
[i
].name
;
428 struct atom_value
*v
= &val
[i
];
429 if (!!deref
!= (*name
== '*'))
433 if (!strcmp(name
, "tree")) {
434 v
->s
= xstrdup(oid_to_hex(&commit
->tree
->object
.oid
));
436 else if (!strcmp(name
, "numparent")) {
437 v
->ul
= commit_list_count(commit
->parents
);
438 v
->s
= xstrfmt("%lu", v
->ul
);
440 else if (!strcmp(name
, "parent")) {
441 struct commit_list
*parents
;
442 struct strbuf s
= STRBUF_INIT
;
443 for (parents
= commit
->parents
; parents
; parents
= parents
->next
) {
444 struct commit
*parent
= parents
->item
;
445 if (parents
!= commit
->parents
)
446 strbuf_addch(&s
, ' ');
447 strbuf_addstr(&s
, oid_to_hex(&parent
->object
.oid
));
449 v
->s
= strbuf_detach(&s
, NULL
);
454 static const char *find_wholine(const char *who
, int wholen
, const char *buf
, unsigned long sz
)
458 if (!strncmp(buf
, who
, wholen
) &&
460 return buf
+ wholen
+ 1;
461 eol
= strchr(buf
, '\n');
466 return ""; /* end of header */
472 static const char *copy_line(const char *buf
)
474 const char *eol
= strchrnul(buf
, '\n');
475 return xmemdupz(buf
, eol
- buf
);
478 static const char *copy_name(const char *buf
)
481 for (cp
= buf
; *cp
&& *cp
!= '\n'; cp
++) {
482 if (!strncmp(cp
, " <", 2))
483 return xmemdupz(buf
, cp
- buf
);
488 static const char *copy_email(const char *buf
)
490 const char *email
= strchr(buf
, '<');
494 eoemail
= strchr(email
, '>');
497 return xmemdupz(email
, eoemail
+ 1 - email
);
500 static char *copy_subject(const char *buf
, unsigned long len
)
502 char *r
= xmemdupz(buf
, len
);
505 for (i
= 0; i
< len
; i
++)
512 static void grab_date(const char *buf
, struct atom_value
*v
, const char *atomname
)
514 const char *eoemail
= strstr(buf
, "> ");
516 unsigned long timestamp
;
518 struct date_mode date_mode
= { DATE_NORMAL
};
522 * We got here because atomname ends in "date" or "date<something>";
523 * it's not possible that <something> is not ":<format>" because
524 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
525 * ":" means no format is specified, and use the default.
527 formatp
= strchr(atomname
, ':');
528 if (formatp
!= NULL
) {
530 parse_date_format(formatp
, &date_mode
);
535 timestamp
= strtoul(eoemail
+ 2, &zone
, 10);
536 if (timestamp
== ULONG_MAX
)
538 tz
= strtol(zone
, NULL
, 10);
539 if ((tz
== LONG_MIN
|| tz
== LONG_MAX
) && errno
== ERANGE
)
541 v
->s
= xstrdup(show_date(timestamp
, tz
, &date_mode
));
549 /* See grab_values */
550 static void grab_person(const char *who
, struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
553 int wholen
= strlen(who
);
554 const char *wholine
= NULL
;
556 for (i
= 0; i
< used_atom_cnt
; i
++) {
557 const char *name
= used_atom
[i
].name
;
558 struct atom_value
*v
= &val
[i
];
559 if (!!deref
!= (*name
== '*'))
563 if (strncmp(who
, name
, wholen
))
565 if (name
[wholen
] != 0 &&
566 strcmp(name
+ wholen
, "name") &&
567 strcmp(name
+ wholen
, "email") &&
568 !starts_with(name
+ wholen
, "date"))
571 wholine
= find_wholine(who
, wholen
, buf
, sz
);
573 return; /* no point looking for it */
574 if (name
[wholen
] == 0)
575 v
->s
= copy_line(wholine
);
576 else if (!strcmp(name
+ wholen
, "name"))
577 v
->s
= copy_name(wholine
);
578 else if (!strcmp(name
+ wholen
, "email"))
579 v
->s
= copy_email(wholine
);
580 else if (starts_with(name
+ wholen
, "date"))
581 grab_date(wholine
, v
, name
);
585 * For a tag or a commit object, if "creator" or "creatordate" is
586 * requested, do something special.
588 if (strcmp(who
, "tagger") && strcmp(who
, "committer"))
589 return; /* "author" for commit object is not wanted */
591 wholine
= find_wholine(who
, wholen
, buf
, sz
);
594 for (i
= 0; i
< used_atom_cnt
; i
++) {
595 const char *name
= used_atom
[i
].name
;
596 struct atom_value
*v
= &val
[i
];
597 if (!!deref
!= (*name
== '*'))
602 if (starts_with(name
, "creatordate"))
603 grab_date(wholine
, v
, name
);
604 else if (!strcmp(name
, "creator"))
605 v
->s
= copy_line(wholine
);
609 static void find_subpos(const char *buf
, unsigned long sz
,
610 const char **sub
, unsigned long *sublen
,
611 const char **body
, unsigned long *bodylen
,
612 unsigned long *nonsiglen
,
613 const char **sig
, unsigned long *siglen
)
616 /* skip past header until we hit empty line */
617 while (*buf
&& *buf
!= '\n') {
618 eol
= strchrnul(buf
, '\n');
623 /* skip any empty lines */
627 /* parse signature first; we might not even have a subject line */
628 *sig
= buf
+ parse_signature(buf
, strlen(buf
));
629 *siglen
= strlen(*sig
);
631 /* subject is first non-empty line */
633 /* subject goes to first empty line */
634 while (buf
< *sig
&& *buf
&& *buf
!= '\n') {
635 eol
= strchrnul(buf
, '\n');
640 *sublen
= buf
- *sub
;
641 /* drop trailing newline, if present */
642 if (*sublen
&& (*sub
)[*sublen
- 1] == '\n')
645 /* skip any empty lines */
649 *bodylen
= strlen(buf
);
650 *nonsiglen
= *sig
- buf
;
654 * If 'lines' is greater than 0, append that many lines from the given
655 * 'buf' of length 'size' to the given strbuf.
657 static void append_lines(struct strbuf
*out
, const char *buf
, unsigned long size
, int lines
)
660 const char *sp
, *eol
;
665 for (i
= 0; i
< lines
&& sp
< buf
+ size
; i
++) {
667 strbuf_addstr(out
, "\n ");
668 eol
= memchr(sp
, '\n', size
- (sp
- buf
));
669 len
= eol
? eol
- sp
: size
- (sp
- buf
);
670 strbuf_add(out
, sp
, len
);
677 /* See grab_values */
678 static void grab_sub_body_contents(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
681 const char *subpos
= NULL
, *bodypos
= NULL
, *sigpos
= NULL
;
682 unsigned long sublen
= 0, bodylen
= 0, nonsiglen
= 0, siglen
= 0;
684 for (i
= 0; i
< used_atom_cnt
; i
++) {
685 const char *name
= used_atom
[i
].name
;
686 struct atom_value
*v
= &val
[i
];
687 const char *valp
= NULL
;
688 if (!!deref
!= (*name
== '*'))
692 if (strcmp(name
, "subject") &&
693 strcmp(name
, "body") &&
694 strcmp(name
, "contents") &&
695 strcmp(name
, "contents:subject") &&
696 strcmp(name
, "contents:body") &&
697 strcmp(name
, "contents:signature") &&
698 !starts_with(name
, "contents:lines="))
703 &bodypos
, &bodylen
, &nonsiglen
,
706 if (!strcmp(name
, "subject"))
707 v
->s
= copy_subject(subpos
, sublen
);
708 else if (!strcmp(name
, "contents:subject"))
709 v
->s
= copy_subject(subpos
, sublen
);
710 else if (!strcmp(name
, "body"))
711 v
->s
= xmemdupz(bodypos
, bodylen
);
712 else if (!strcmp(name
, "contents:body"))
713 v
->s
= xmemdupz(bodypos
, nonsiglen
);
714 else if (!strcmp(name
, "contents:signature"))
715 v
->s
= xmemdupz(sigpos
, siglen
);
716 else if (!strcmp(name
, "contents"))
717 v
->s
= xstrdup(subpos
);
718 else if (skip_prefix(name
, "contents:lines=", &valp
)) {
719 struct strbuf s
= STRBUF_INIT
;
720 const char *contents_end
= bodylen
+ bodypos
- siglen
;
722 if (strtoul_ui(valp
, 10, &v
->u
.contents
.lines
))
723 die(_("positive value expected contents:lines=%s"), valp
);
724 /* Size is the length of the message after removing the signature */
725 append_lines(&s
, subpos
, contents_end
- subpos
, v
->u
.contents
.lines
);
726 v
->s
= strbuf_detach(&s
, NULL
);
732 * We want to have empty print-string for field requests
733 * that do not apply (e.g. "authordate" for a tag object)
735 static void fill_missing_values(struct atom_value
*val
)
738 for (i
= 0; i
< used_atom_cnt
; i
++) {
739 struct atom_value
*v
= &val
[i
];
746 * val is a list of atom_value to hold returned values. Extract
747 * the values for atoms in used_atom array out of (obj, buf, sz).
748 * when deref is false, (obj, buf, sz) is the object that is
749 * pointed at by the ref itself; otherwise it is the object the
750 * ref (which is a tag) refers to.
752 static void grab_values(struct atom_value
*val
, int deref
, struct object
*obj
, void *buf
, unsigned long sz
)
754 grab_common_values(val
, deref
, obj
, buf
, sz
);
757 grab_tag_values(val
, deref
, obj
, buf
, sz
);
758 grab_sub_body_contents(val
, deref
, obj
, buf
, sz
);
759 grab_person("tagger", val
, deref
, obj
, buf
, sz
);
762 grab_commit_values(val
, deref
, obj
, buf
, sz
);
763 grab_sub_body_contents(val
, deref
, obj
, buf
, sz
);
764 grab_person("author", val
, deref
, obj
, buf
, sz
);
765 grab_person("committer", val
, deref
, obj
, buf
, sz
);
768 /* grab_tree_values(val, deref, obj, buf, sz); */
771 /* grab_blob_values(val, deref, obj, buf, sz); */
774 die("Eh? Object of type %d?", obj
->type
);
778 static inline char *copy_advance(char *dst
, const char *src
)
785 static const char *strip_ref_components(const char *refname
, const char *nr_arg
)
788 long nr
= strtol(nr_arg
, &end
, 10);
790 const char *start
= refname
;
792 if (nr
< 1 || *end
!= '\0')
793 die(":strip= requires a positive integer argument");
798 die("ref '%s' does not have %ld components to :strip",
809 * Parse the object referred by ref, and grab needed value.
811 static void populate_value(struct ref_array_item
*ref
)
817 const unsigned char *tagged
;
819 ref
->value
= xcalloc(used_atom_cnt
, sizeof(struct atom_value
));
821 if (need_symref
&& (ref
->flag
& REF_ISSYMREF
) && !ref
->symref
) {
822 unsigned char unused1
[20];
823 ref
->symref
= resolve_refdup(ref
->refname
, RESOLVE_REF_READING
,
829 /* Fill in specials first */
830 for (i
= 0; i
< used_atom_cnt
; i
++) {
831 struct used_atom
*atom
= &used_atom
[i
];
832 const char *name
= used_atom
[i
].name
;
833 struct atom_value
*v
= &ref
->value
[i
];
838 struct branch
*branch
= NULL
;
840 v
->handler
= append_atom
;
847 if (starts_with(name
, "refname"))
848 refname
= ref
->refname
;
849 else if (starts_with(name
, "symref"))
850 refname
= ref
->symref
? ref
->symref
: "";
851 else if (starts_with(name
, "upstream")) {
852 const char *branch_name
;
853 /* only local branches may have an upstream */
854 if (!skip_prefix(ref
->refname
, "refs/heads/",
857 branch
= branch_get(branch_name
);
859 refname
= branch_get_upstream(branch
, NULL
);
862 } else if (starts_with(name
, "push")) {
863 const char *branch_name
;
864 if (!skip_prefix(ref
->refname
, "refs/heads/",
867 branch
= branch_get(branch_name
);
869 refname
= branch_get_push(branch
, NULL
);
872 } else if (starts_with(name
, "color:")) {
873 v
->s
= atom
->u
.color
;
875 } else if (!strcmp(name
, "flag")) {
876 char buf
[256], *cp
= buf
;
877 if (ref
->flag
& REF_ISSYMREF
)
878 cp
= copy_advance(cp
, ",symref");
879 if (ref
->flag
& REF_ISPACKED
)
880 cp
= copy_advance(cp
, ",packed");
885 v
->s
= xstrdup(buf
+ 1);
888 } else if (!deref
&& grab_objectname(name
, ref
->objectname
, v
)) {
890 } else if (!strcmp(name
, "HEAD")) {
892 unsigned char sha1
[20];
894 head
= resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
,
896 if (!strcmp(ref
->refname
, head
))
901 } else if (match_atom_name(name
, "align", &valp
)) {
902 struct align
*align
= &v
->u
.align
;
903 struct string_list params
= STRING_LIST_INIT_DUP
;
908 die(_("expected format: %%(align:<width>,<position>)"));
910 align
->position
= ALIGN_LEFT
;
912 string_list_split(¶ms
, valp
, ',', -1);
913 for (i
= 0; i
< params
.nr
; i
++) {
914 const char *s
= params
.items
[i
].string
;
915 if (!strtoul_ui(s
, 10, (unsigned int *)&width
))
917 else if (!strcmp(s
, "left"))
918 align
->position
= ALIGN_LEFT
;
919 else if (!strcmp(s
, "right"))
920 align
->position
= ALIGN_RIGHT
;
921 else if (!strcmp(s
, "middle"))
922 align
->position
= ALIGN_MIDDLE
;
924 die(_("improper format entered align:%s"), s
);
928 die(_("positive width expected with the %%(align) atom"));
929 align
->width
= width
;
930 string_list_clear(¶ms
, 0);
931 v
->handler
= align_atom_handler
;
933 } else if (!strcmp(name
, "end")) {
934 v
->handler
= end_atom_handler
;
939 formatp
= strchr(name
, ':');
941 int num_ours
, num_theirs
;
945 if (!strcmp(formatp
, "short"))
946 refname
= shorten_unambiguous_ref(refname
,
947 warn_ambiguous_refs
);
948 else if (skip_prefix(formatp
, "strip=", &arg
))
949 refname
= strip_ref_components(refname
, arg
);
950 else if (!strcmp(formatp
, "track") &&
951 (starts_with(name
, "upstream") ||
952 starts_with(name
, "push"))) {
954 if (stat_tracking_info(branch
, &num_ours
,
958 if (!num_ours
&& !num_theirs
)
961 v
->s
= xstrfmt("[behind %d]", num_theirs
);
962 else if (!num_theirs
)
963 v
->s
= xstrfmt("[ahead %d]", num_ours
);
965 v
->s
= xstrfmt("[ahead %d, behind %d]",
966 num_ours
, num_theirs
);
968 } else if (!strcmp(formatp
, "trackshort") &&
969 (starts_with(name
, "upstream") ||
970 starts_with(name
, "push"))) {
973 if (stat_tracking_info(branch
, &num_ours
,
977 if (!num_ours
&& !num_theirs
)
981 else if (!num_theirs
)
987 die("unknown %.*s format %s",
988 (int)(formatp
- name
), name
, formatp
);
994 v
->s
= xstrfmt("%s^{}", refname
);
997 for (i
= 0; i
< used_atom_cnt
; i
++) {
998 struct atom_value
*v
= &ref
->value
[i
];
1005 buf
= get_obj(ref
->objectname
, &obj
, &size
, &eaten
);
1007 die("missing object %s for %s",
1008 sha1_to_hex(ref
->objectname
), ref
->refname
);
1010 die("parse_object_buffer failed on %s for %s",
1011 sha1_to_hex(ref
->objectname
), ref
->refname
);
1013 grab_values(ref
->value
, 0, obj
, buf
, size
);
1018 * If there is no atom that wants to know about tagged
1019 * object, we are done.
1021 if (!need_tagged
|| (obj
->type
!= OBJ_TAG
))
1025 * If it is a tag object, see if we use a value that derefs
1026 * the object, and if we do grab the object it refers to.
1028 tagged
= ((struct tag
*)obj
)->tagged
->oid
.hash
;
1031 * NEEDSWORK: This derefs tag only once, which
1032 * is good to deal with chains of trust, but
1033 * is not consistent with what deref_tag() does
1034 * which peels the onion to the core.
1036 buf
= get_obj(tagged
, &obj
, &size
, &eaten
);
1038 die("missing object %s for %s",
1039 sha1_to_hex(tagged
), ref
->refname
);
1041 die("parse_object_buffer failed on %s for %s",
1042 sha1_to_hex(tagged
), ref
->refname
);
1043 grab_values(ref
->value
, 1, obj
, buf
, size
);
1049 * Given a ref, return the value for the atom. This lazily gets value
1050 * out of the object by calling populate value.
1052 static void get_ref_atom_value(struct ref_array_item
*ref
, int atom
, struct atom_value
**v
)
1055 populate_value(ref
);
1056 fill_missing_values(ref
->value
);
1058 *v
= &ref
->value
[atom
];
1061 enum contains_result
{
1062 CONTAINS_UNKNOWN
= -1,
1068 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1071 * At each recursion step, the stack items points to the commits whose
1072 * ancestors are to be inspected.
1074 struct contains_stack
{
1076 struct contains_stack_entry
{
1077 struct commit
*commit
;
1078 struct commit_list
*parents
;
1082 static int in_commit_list(const struct commit_list
*want
, struct commit
*c
)
1084 for (; want
; want
= want
->next
)
1085 if (!oidcmp(&want
->item
->object
.oid
, &c
->object
.oid
))
1091 * Test whether the candidate or one of its parents is contained in the list.
1092 * Do not recurse to find out, though, but return -1 if inconclusive.
1094 static enum contains_result
contains_test(struct commit
*candidate
,
1095 const struct commit_list
*want
)
1097 /* was it previously marked as containing a want commit? */
1098 if (candidate
->object
.flags
& TMP_MARK
)
1100 /* or marked as not possibly containing a want commit? */
1101 if (candidate
->object
.flags
& UNINTERESTING
)
1104 if (in_commit_list(want
, candidate
)) {
1105 candidate
->object
.flags
|= TMP_MARK
;
1109 if (parse_commit(candidate
) < 0)
1115 static void push_to_contains_stack(struct commit
*candidate
, struct contains_stack
*contains_stack
)
1117 ALLOC_GROW(contains_stack
->contains_stack
, contains_stack
->nr
+ 1, contains_stack
->alloc
);
1118 contains_stack
->contains_stack
[contains_stack
->nr
].commit
= candidate
;
1119 contains_stack
->contains_stack
[contains_stack
->nr
++].parents
= candidate
->parents
;
1122 static enum contains_result
contains_tag_algo(struct commit
*candidate
,
1123 const struct commit_list
*want
)
1125 struct contains_stack contains_stack
= { 0, 0, NULL
};
1126 int result
= contains_test(candidate
, want
);
1128 if (result
!= CONTAINS_UNKNOWN
)
1131 push_to_contains_stack(candidate
, &contains_stack
);
1132 while (contains_stack
.nr
) {
1133 struct contains_stack_entry
*entry
= &contains_stack
.contains_stack
[contains_stack
.nr
- 1];
1134 struct commit
*commit
= entry
->commit
;
1135 struct commit_list
*parents
= entry
->parents
;
1138 commit
->object
.flags
|= UNINTERESTING
;
1139 contains_stack
.nr
--;
1142 * If we just popped the stack, parents->item has been marked,
1143 * therefore contains_test will return a meaningful 0 or 1.
1145 else switch (contains_test(parents
->item
, want
)) {
1147 commit
->object
.flags
|= TMP_MARK
;
1148 contains_stack
.nr
--;
1151 entry
->parents
= parents
->next
;
1153 case CONTAINS_UNKNOWN
:
1154 push_to_contains_stack(parents
->item
, &contains_stack
);
1158 free(contains_stack
.contains_stack
);
1159 return contains_test(candidate
, want
);
1162 static int commit_contains(struct ref_filter
*filter
, struct commit
*commit
)
1164 if (filter
->with_commit_tag_algo
)
1165 return contains_tag_algo(commit
, filter
->with_commit
);
1166 return is_descendant_of(commit
, filter
->with_commit
);
1170 * Return 1 if the refname matches one of the patterns, otherwise 0.
1171 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1172 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1173 * matches "refs/heads/mas*", too).
1175 static int match_pattern(const char **patterns
, const char *refname
)
1178 * When no '--format' option is given we need to skip the prefix
1179 * for matching refs of tags and branches.
1181 (void)(skip_prefix(refname
, "refs/tags/", &refname
) ||
1182 skip_prefix(refname
, "refs/heads/", &refname
) ||
1183 skip_prefix(refname
, "refs/remotes/", &refname
) ||
1184 skip_prefix(refname
, "refs/", &refname
));
1186 for (; *patterns
; patterns
++) {
1187 if (!wildmatch(*patterns
, refname
, 0, NULL
))
1194 * Return 1 if the refname matches one of the patterns, otherwise 0.
1195 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1196 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1197 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1199 static int match_name_as_path(const char **pattern
, const char *refname
)
1201 int namelen
= strlen(refname
);
1202 for (; *pattern
; pattern
++) {
1203 const char *p
= *pattern
;
1204 int plen
= strlen(p
);
1206 if ((plen
<= namelen
) &&
1207 !strncmp(refname
, p
, plen
) &&
1208 (refname
[plen
] == '\0' ||
1209 refname
[plen
] == '/' ||
1212 if (!wildmatch(p
, refname
, WM_PATHNAME
, NULL
))
1218 /* Return 1 if the refname matches one of the patterns, otherwise 0. */
1219 static int filter_pattern_match(struct ref_filter
*filter
, const char *refname
)
1221 if (!*filter
->name_patterns
)
1222 return 1; /* No pattern always matches */
1223 if (filter
->match_as_path
)
1224 return match_name_as_path(filter
->name_patterns
, refname
);
1225 return match_pattern(filter
->name_patterns
, refname
);
1229 * Given a ref (sha1, refname), check if the ref belongs to the array
1230 * of sha1s. If the given ref is a tag, check if the given tag points
1231 * at one of the sha1s in the given sha1 array.
1232 * the given sha1_array.
1234 * 1. Only a single level of inderection is obtained, we might want to
1235 * change this to account for multiple levels (e.g. annotated tags
1236 * pointing to annotated tags pointing to a commit.)
1237 * 2. As the refs are cached we might know what refname peels to without
1238 * the need to parse the object via parse_object(). peel_ref() might be a
1239 * more efficient alternative to obtain the pointee.
1241 static const unsigned char *match_points_at(struct sha1_array
*points_at
,
1242 const unsigned char *sha1
,
1243 const char *refname
)
1245 const unsigned char *tagged_sha1
= NULL
;
1248 if (sha1_array_lookup(points_at
, sha1
) >= 0)
1250 obj
= parse_object(sha1
);
1252 die(_("malformed object at '%s'"), refname
);
1253 if (obj
->type
== OBJ_TAG
)
1254 tagged_sha1
= ((struct tag
*)obj
)->tagged
->oid
.hash
;
1255 if (tagged_sha1
&& sha1_array_lookup(points_at
, tagged_sha1
) >= 0)
1260 /* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1261 static struct ref_array_item
*new_ref_array_item(const char *refname
,
1262 const unsigned char *objectname
,
1265 size_t len
= strlen(refname
);
1266 struct ref_array_item
*ref
= xcalloc(1, sizeof(struct ref_array_item
) + len
+ 1);
1267 memcpy(ref
->refname
, refname
, len
);
1268 ref
->refname
[len
] = '\0';
1269 hashcpy(ref
->objectname
, objectname
);
1275 static int filter_ref_kind(struct ref_filter
*filter
, const char *refname
)
1283 { "refs/heads/" , FILTER_REFS_BRANCHES
},
1284 { "refs/remotes/" , FILTER_REFS_REMOTES
},
1285 { "refs/tags/", FILTER_REFS_TAGS
}
1288 if (filter
->kind
== FILTER_REFS_BRANCHES
||
1289 filter
->kind
== FILTER_REFS_REMOTES
||
1290 filter
->kind
== FILTER_REFS_TAGS
)
1291 return filter
->kind
;
1292 else if (!strcmp(refname
, "HEAD"))
1293 return FILTER_REFS_DETACHED_HEAD
;
1295 for (i
= 0; i
< ARRAY_SIZE(ref_kind
); i
++) {
1296 if (starts_with(refname
, ref_kind
[i
].prefix
))
1297 return ref_kind
[i
].kind
;
1300 return FILTER_REFS_OTHERS
;
1304 * A call-back given to for_each_ref(). Filter refs and keep them for
1305 * later object processing.
1307 static int ref_filter_handler(const char *refname
, const struct object_id
*oid
, int flag
, void *cb_data
)
1309 struct ref_filter_cbdata
*ref_cbdata
= cb_data
;
1310 struct ref_filter
*filter
= ref_cbdata
->filter
;
1311 struct ref_array_item
*ref
;
1312 struct commit
*commit
= NULL
;
1315 if (flag
& REF_BAD_NAME
) {
1316 warning("ignoring ref with broken name %s", refname
);
1320 if (flag
& REF_ISBROKEN
) {
1321 warning("ignoring broken ref %s", refname
);
1325 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1326 kind
= filter_ref_kind(filter
, refname
);
1327 if (!(kind
& filter
->kind
))
1330 if (!filter_pattern_match(filter
, refname
))
1333 if (filter
->points_at
.nr
&& !match_points_at(&filter
->points_at
, oid
->hash
, refname
))
1337 * A merge filter is applied on refs pointing to commits. Hence
1338 * obtain the commit using the 'oid' available and discard all
1339 * non-commits early. The actual filtering is done later.
1341 if (filter
->merge_commit
|| filter
->with_commit
|| filter
->verbose
) {
1342 commit
= lookup_commit_reference_gently(oid
->hash
, 1);
1345 /* We perform the filtering for the '--contains' option */
1346 if (filter
->with_commit
&&
1347 !commit_contains(filter
, commit
))
1352 * We do not open the object yet; sort may only need refname
1353 * to do its job and the resulting list may yet to be pruned
1354 * by maxcount logic.
1356 ref
= new_ref_array_item(refname
, oid
->hash
, flag
);
1357 ref
->commit
= commit
;
1359 REALLOC_ARRAY(ref_cbdata
->array
->items
, ref_cbdata
->array
->nr
+ 1);
1360 ref_cbdata
->array
->items
[ref_cbdata
->array
->nr
++] = ref
;
1365 /* Free memory allocated for a ref_array_item */
1366 static void free_array_item(struct ref_array_item
*item
)
1368 free((char *)item
->symref
);
1372 /* Free all memory allocated for ref_array */
1373 void ref_array_clear(struct ref_array
*array
)
1377 for (i
= 0; i
< array
->nr
; i
++)
1378 free_array_item(array
->items
[i
]);
1380 array
->items
= NULL
;
1381 array
->nr
= array
->alloc
= 0;
1384 static void do_merge_filter(struct ref_filter_cbdata
*ref_cbdata
)
1386 struct rev_info revs
;
1388 struct ref_filter
*filter
= ref_cbdata
->filter
;
1389 struct ref_array
*array
= ref_cbdata
->array
;
1390 struct commit
**to_clear
= xcalloc(sizeof(struct commit
*), array
->nr
);
1392 init_revisions(&revs
, NULL
);
1394 for (i
= 0; i
< array
->nr
; i
++) {
1395 struct ref_array_item
*item
= array
->items
[i
];
1396 add_pending_object(&revs
, &item
->commit
->object
, item
->refname
);
1397 to_clear
[i
] = item
->commit
;
1400 filter
->merge_commit
->object
.flags
|= UNINTERESTING
;
1401 add_pending_object(&revs
, &filter
->merge_commit
->object
, "");
1404 if (prepare_revision_walk(&revs
))
1405 die(_("revision walk setup failed"));
1410 for (i
= 0; i
< old_nr
; i
++) {
1411 struct ref_array_item
*item
= array
->items
[i
];
1412 struct commit
*commit
= item
->commit
;
1414 int is_merged
= !!(commit
->object
.flags
& UNINTERESTING
);
1416 if (is_merged
== (filter
->merge
== REF_FILTER_MERGED_INCLUDE
))
1417 array
->items
[array
->nr
++] = array
->items
[i
];
1419 free_array_item(item
);
1422 for (i
= 0; i
< old_nr
; i
++)
1423 clear_commit_marks(to_clear
[i
], ALL_REV_FLAGS
);
1424 clear_commit_marks(filter
->merge_commit
, ALL_REV_FLAGS
);
1429 * API for filtering a set of refs. Based on the type of refs the user
1430 * has requested, we iterate through those refs and apply filters
1431 * as per the given ref_filter structure and finally store the
1432 * filtered refs in the ref_array structure.
1434 int filter_refs(struct ref_array
*array
, struct ref_filter
*filter
, unsigned int type
)
1436 struct ref_filter_cbdata ref_cbdata
;
1438 unsigned int broken
= 0;
1440 ref_cbdata
.array
= array
;
1441 ref_cbdata
.filter
= filter
;
1443 if (type
& FILTER_REFS_INCLUDE_BROKEN
)
1445 filter
->kind
= type
& FILTER_REFS_KIND_MASK
;
1447 /* Simple per-ref filtering */
1449 die("filter_refs: invalid type");
1452 * For common cases where we need only branches or remotes or tags,
1453 * we only iterate through those refs. If a mix of refs is needed,
1454 * we iterate over all refs and filter out required refs with the help
1455 * of filter_ref_kind().
1457 if (filter
->kind
== FILTER_REFS_BRANCHES
)
1458 ret
= for_each_fullref_in("refs/heads/", ref_filter_handler
, &ref_cbdata
, broken
);
1459 else if (filter
->kind
== FILTER_REFS_REMOTES
)
1460 ret
= for_each_fullref_in("refs/remotes/", ref_filter_handler
, &ref_cbdata
, broken
);
1461 else if (filter
->kind
== FILTER_REFS_TAGS
)
1462 ret
= for_each_fullref_in("refs/tags/", ref_filter_handler
, &ref_cbdata
, broken
);
1463 else if (filter
->kind
& FILTER_REFS_ALL
)
1464 ret
= for_each_fullref_in("", ref_filter_handler
, &ref_cbdata
, broken
);
1465 if (!ret
&& (filter
->kind
& FILTER_REFS_DETACHED_HEAD
))
1466 head_ref(ref_filter_handler
, &ref_cbdata
);
1470 /* Filters that need revision walking */
1471 if (filter
->merge_commit
)
1472 do_merge_filter(&ref_cbdata
);
1477 static int cmp_ref_sorting(struct ref_sorting
*s
, struct ref_array_item
*a
, struct ref_array_item
*b
)
1479 struct atom_value
*va
, *vb
;
1481 cmp_type cmp_type
= used_atom
[s
->atom
].type
;
1483 get_ref_atom_value(a
, s
->atom
, &va
);
1484 get_ref_atom_value(b
, s
->atom
, &vb
);
1486 cmp
= versioncmp(va
->s
, vb
->s
);
1487 else if (cmp_type
== FIELD_STR
)
1488 cmp
= strcmp(va
->s
, vb
->s
);
1490 if (va
->ul
< vb
->ul
)
1492 else if (va
->ul
== vb
->ul
)
1493 cmp
= strcmp(a
->refname
, b
->refname
);
1498 return (s
->reverse
) ? -cmp
: cmp
;
1501 static struct ref_sorting
*ref_sorting
;
1502 static int compare_refs(const void *a_
, const void *b_
)
1504 struct ref_array_item
*a
= *((struct ref_array_item
**)a_
);
1505 struct ref_array_item
*b
= *((struct ref_array_item
**)b_
);
1506 struct ref_sorting
*s
;
1508 for (s
= ref_sorting
; s
; s
= s
->next
) {
1509 int cmp
= cmp_ref_sorting(s
, a
, b
);
1516 void ref_array_sort(struct ref_sorting
*sorting
, struct ref_array
*array
)
1518 ref_sorting
= sorting
;
1519 qsort(array
->items
, array
->nr
, sizeof(struct ref_array_item
*), compare_refs
);
1522 static int hex1(char ch
)
1524 if ('0' <= ch
&& ch
<= '9')
1526 else if ('a' <= ch
&& ch
<= 'f')
1527 return ch
- 'a' + 10;
1528 else if ('A' <= ch
&& ch
<= 'F')
1529 return ch
- 'A' + 10;
1532 static int hex2(const char *cp
)
1535 return (hex1(cp
[0]) << 4) | hex1(cp
[1]);
1540 static void append_literal(const char *cp
, const char *ep
, struct ref_formatting_state
*state
)
1542 struct strbuf
*s
= &state
->stack
->output
;
1544 while (*cp
&& (!ep
|| cp
< ep
)) {
1549 int ch
= hex2(cp
+ 1);
1551 strbuf_addch(s
, ch
);
1557 strbuf_addch(s
, *cp
);
1562 void show_ref_array_item(struct ref_array_item
*info
, const char *format
, int quote_style
)
1564 const char *cp
, *sp
, *ep
;
1565 struct strbuf
*final_buf
;
1566 struct ref_formatting_state state
= REF_FORMATTING_STATE_INIT
;
1568 state
.quote_style
= quote_style
;
1569 push_stack_element(&state
.stack
);
1571 for (cp
= format
; *cp
&& (sp
= find_next(cp
)); cp
= ep
+ 1) {
1572 struct atom_value
*atomv
;
1574 ep
= strchr(sp
, ')');
1576 append_literal(cp
, sp
, &state
);
1577 get_ref_atom_value(info
, parse_ref_filter_atom(sp
+ 2, ep
), &atomv
);
1578 atomv
->handler(atomv
, &state
);
1581 sp
= cp
+ strlen(cp
);
1582 append_literal(cp
, sp
, &state
);
1584 if (need_color_reset_at_eol
) {
1585 struct atom_value resetv
;
1586 char color
[COLOR_MAXLEN
] = "";
1588 if (color_parse("reset", color
) < 0)
1589 die("BUG: couldn't parse 'reset' as a color");
1591 append_atom(&resetv
, &state
);
1593 if (state
.stack
->prev
)
1594 die(_("format: %%(end) atom missing"));
1595 final_buf
= &state
.stack
->output
;
1596 fwrite(final_buf
->buf
, 1, final_buf
->len
, stdout
);
1597 pop_stack_element(&state
.stack
);
1601 /* If no sorting option is given, use refname to sort as default */
1602 struct ref_sorting
*ref_default_sorting(void)
1604 static const char cstr_name
[] = "refname";
1606 struct ref_sorting
*sorting
= xcalloc(1, sizeof(*sorting
));
1608 sorting
->next
= NULL
;
1609 sorting
->atom
= parse_ref_filter_atom(cstr_name
, cstr_name
+ strlen(cstr_name
));
1613 int parse_opt_ref_sorting(const struct option
*opt
, const char *arg
, int unset
)
1615 struct ref_sorting
**sorting_tail
= opt
->value
;
1616 struct ref_sorting
*s
;
1619 if (!arg
) /* should --no-sort void the list ? */
1622 s
= xcalloc(1, sizeof(*s
));
1623 s
->next
= *sorting_tail
;
1630 if (skip_prefix(arg
, "version:", &arg
) ||
1631 skip_prefix(arg
, "v:", &arg
))
1634 s
->atom
= parse_ref_filter_atom(arg
, arg
+len
);
1638 int parse_opt_merge_filter(const struct option
*opt
, const char *arg
, int unset
)
1640 struct ref_filter
*rf
= opt
->value
;
1641 unsigned char sha1
[20];
1643 rf
->merge
= starts_with(opt
->long_name
, "no")
1644 ? REF_FILTER_MERGED_OMIT
1645 : REF_FILTER_MERGED_INCLUDE
;
1647 if (get_sha1(arg
, sha1
))
1648 die(_("malformed object name %s"), arg
);
1650 rf
->merge_commit
= lookup_commit_reference_gently(sha1
, 0);
1651 if (!rf
->merge_commit
)
1652 return opterror(opt
, "must point to a commit", 0);