10 #include "parse-options.h"
16 #define QUOTE_PYTHON 4
19 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
23 unsigned long ul; /* used for sorting when not FIELD_STR */
27 struct ref_sort *next;
28 int atom; /* index into used_atom array */
34 unsigned char objectname[20];
35 struct atom_value *value;
44 { "objectsize", FIELD_ULONG },
48 { "numparent", FIELD_ULONG },
55 { "authordate", FIELD_TIME },
59 { "committerdate", FIELD_TIME },
63 { "taggerdate", FIELD_TIME },
65 { "creatordate", FIELD_TIME },
72 * An atom is a valid field atom listed above, possibly prefixed with
73 * a "*" to denote deref_tag().
75 * We parse given format string and sort specifiers, and make a list
76 * of properties that we need to extract out of objects. refinfo
77 * structure will hold an array of values extracted that can be
78 * indexed with the "atom number", which is an index into this
81 static const char **used_atom;
82 static cmp_type *used_atom_type;
83 static int used_atom_cnt, sort_atom_limit, need_tagged;
86 * Used to parse format string and sort specifiers
88 static int parse_atom(const char *atom, const char *ep)
94 if (*sp == '*' && sp < ep)
97 die("malformed field name: %.*s", (int)(ep-atom), atom);
99 /* Do we have the atom already used elsewhere? */
100 for (i = 0; i < used_atom_cnt; i++) {
101 int len = strlen(used_atom[i]);
102 if (len == ep - atom && !memcmp(used_atom[i], atom, len))
106 /* Is the atom a valid one? */
107 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
108 int len = strlen(valid_atom[i].name);
110 * If the atom name has a colon, strip it and everything after
111 * it off - it specifies the format for this entry, and
112 * shouldn't be used for checking against the valid_atom
115 const char *formatp = strchr(sp, ':');
116 if (!formatp || ep < formatp)
118 if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
122 if (ARRAY_SIZE(valid_atom) <= i)
123 die("unknown field name: %.*s", (int)(ep-atom), atom);
125 /* Add it in, including the deref prefix */
128 used_atom = xrealloc(used_atom,
129 (sizeof *used_atom) * used_atom_cnt);
130 used_atom_type = xrealloc(used_atom_type,
131 (sizeof(*used_atom_type) * used_atom_cnt));
132 used_atom[at] = xmemdupz(atom, ep - atom);
133 used_atom_type[at] = valid_atom[i].cmp_type;
138 * In a format string, find the next occurrence of %(atom).
140 static const char *find_next(const char *cp)
144 /* %( is the start of an atom;
145 * %% is a quoted per-cent.
149 else if (cp[1] == '%')
150 cp++; /* skip over two % */
151 /* otherwise this is a singleton, literal % */
159 * Make sure the format string is well formed, and parse out
162 static int verify_format(const char *format)
165 for (cp = format; *cp && (sp = find_next(cp)); ) {
166 const char *ep = strchr(sp, ')');
168 return error("malformed format string %s", sp);
169 /* sp points at "%(" and ep points at the closing ")" */
170 parse_atom(sp + 2, ep);
177 * Given an object name, read the object data and size, and return a
178 * "struct object". If the object data we are returning is also borrowed
179 * by the "struct object" representation, set *eaten as well---it is a
180 * signal from parse_object_buffer to us not to free the buffer.
182 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
184 enum object_type type;
185 void *buf = read_sha1_file(sha1, &type, sz);
188 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
194 /* See grab_values */
195 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
199 for (i = 0; i < used_atom_cnt; i++) {
200 const char *name = used_atom[i];
201 struct atom_value *v = &val[i];
202 if (!!deref != (*name == '*'))
206 if (!strcmp(name, "objecttype"))
207 v->s = typename(obj->type);
208 else if (!strcmp(name, "objectsize")) {
209 char *s = xmalloc(40);
210 sprintf(s, "%lu", sz);
214 else if (!strcmp(name, "objectname")) {
215 char *s = xmalloc(41);
216 strcpy(s, sha1_to_hex(obj->sha1));
222 /* See grab_values */
223 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
226 struct tag *tag = (struct tag *) obj;
228 for (i = 0; i < used_atom_cnt; i++) {
229 const char *name = used_atom[i];
230 struct atom_value *v = &val[i];
231 if (!!deref != (*name == '*'))
235 if (!strcmp(name, "tag"))
237 else if (!strcmp(name, "type") && tag->tagged)
238 v->s = typename(tag->tagged->type);
239 else if (!strcmp(name, "object") && tag->tagged) {
240 char *s = xmalloc(41);
241 strcpy(s, sha1_to_hex(tag->tagged->sha1));
247 static int num_parents(struct commit *commit)
249 struct commit_list *parents;
252 for (i = 0, parents = commit->parents;
254 parents = parents->next)
259 /* See grab_values */
260 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
263 struct commit *commit = (struct commit *) obj;
265 for (i = 0; i < used_atom_cnt; i++) {
266 const char *name = used_atom[i];
267 struct atom_value *v = &val[i];
268 if (!!deref != (*name == '*'))
272 if (!strcmp(name, "tree")) {
273 char *s = xmalloc(41);
274 strcpy(s, sha1_to_hex(commit->tree->object.sha1));
277 if (!strcmp(name, "numparent")) {
278 char *s = xmalloc(40);
279 v->ul = num_parents(commit);
280 sprintf(s, "%lu", v->ul);
283 else if (!strcmp(name, "parent")) {
284 int num = num_parents(commit);
286 struct commit_list *parents;
287 char *s = xmalloc(41 * num + 1);
289 for (i = 0, parents = commit->parents;
291 parents = parents->next, i = i + 41) {
292 struct commit *parent = parents->item;
293 strcpy(s+i, sha1_to_hex(parent->object.sha1));
303 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
307 if (!strncmp(buf, who, wholen) &&
309 return buf + wholen + 1;
310 eol = strchr(buf, '\n');
315 return ""; /* end of header */
321 static const char *copy_line(const char *buf)
323 const char *eol = strchrnul(buf, '\n');
324 return xmemdupz(buf, eol - buf);
327 static const char *copy_name(const char *buf)
330 for (cp = buf; *cp && *cp != '\n'; cp++) {
331 if (!strncmp(cp, " <", 2))
332 return xmemdupz(buf, cp - buf);
337 static const char *copy_email(const char *buf)
339 const char *email = strchr(buf, '<');
340 const char *eoemail = strchr(email, '>');
341 if (!email || !eoemail)
343 return xmemdupz(email, eoemail + 1 - email);
346 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
348 const char *eoemail = strstr(buf, "> ");
350 unsigned long timestamp;
352 enum date_mode date_mode = DATE_NORMAL;
356 * We got here because atomname ends in "date" or "date<something>";
357 * it's not possible that <something> is not ":<format>" because
358 * parse_atom() wouldn't have allowed it, so we can assume that no
359 * ":" means no format is specified, and use the default.
361 formatp = strchr(atomname, ':');
362 if (formatp != NULL) {
364 date_mode = parse_date_format(formatp);
369 timestamp = strtoul(eoemail + 2, &zone, 10);
370 if (timestamp == ULONG_MAX)
372 tz = strtol(zone, NULL, 10);
373 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
375 v->s = xstrdup(show_date(timestamp, tz, date_mode));
383 /* See grab_values */
384 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
387 int wholen = strlen(who);
388 const char *wholine = NULL;
390 for (i = 0; i < used_atom_cnt; i++) {
391 const char *name = used_atom[i];
392 struct atom_value *v = &val[i];
393 if (!!deref != (*name == '*'))
397 if (strncmp(who, name, wholen))
399 if (name[wholen] != 0 &&
400 strcmp(name + wholen, "name") &&
401 strcmp(name + wholen, "email") &&
402 prefixcmp(name + wholen, "date"))
405 wholine = find_wholine(who, wholen, buf, sz);
407 return; /* no point looking for it */
408 if (name[wholen] == 0)
409 v->s = copy_line(wholine);
410 else if (!strcmp(name + wholen, "name"))
411 v->s = copy_name(wholine);
412 else if (!strcmp(name + wholen, "email"))
413 v->s = copy_email(wholine);
414 else if (!prefixcmp(name + wholen, "date"))
415 grab_date(wholine, v, name);
418 /* For a tag or a commit object, if "creator" or "creatordate" is
419 * requested, do something special.
421 if (strcmp(who, "tagger") && strcmp(who, "committer"))
422 return; /* "author" for commit object is not wanted */
424 wholine = find_wholine(who, wholen, buf, sz);
427 for (i = 0; i < used_atom_cnt; i++) {
428 const char *name = used_atom[i];
429 struct atom_value *v = &val[i];
430 if (!!deref != (*name == '*'))
435 if (!prefixcmp(name, "creatordate"))
436 grab_date(wholine, v, name);
437 else if (!strcmp(name, "creator"))
438 v->s = copy_line(wholine);
442 static void find_subpos(const char *buf, unsigned long sz, const char **sub, const char **body)
445 const char *eol = strchr(buf, '\n');
448 if (eol[1] == '\n') {
450 break; /* found end of header */
458 *sub = buf; /* first non-empty line */
459 buf = strchr(buf, '\n');
462 return; /* no body */
465 buf++; /* skip blank between subject and body */
469 /* See grab_values */
470 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
473 const char *subpos = NULL, *bodypos = NULL;
475 for (i = 0; i < used_atom_cnt; i++) {
476 const char *name = used_atom[i];
477 struct atom_value *v = &val[i];
478 if (!!deref != (*name == '*'))
482 if (strcmp(name, "subject") &&
483 strcmp(name, "body") &&
484 strcmp(name, "contents"))
487 find_subpos(buf, sz, &subpos, &bodypos);
491 if (!strcmp(name, "subject"))
492 v->s = copy_line(subpos);
493 else if (!strcmp(name, "body"))
494 v->s = xstrdup(bodypos);
495 else if (!strcmp(name, "contents"))
496 v->s = xstrdup(subpos);
500 /* We want to have empty print-string for field requests
501 * that do not apply (e.g. "authordate" for a tag object)
503 static void fill_missing_values(struct atom_value *val)
506 for (i = 0; i < used_atom_cnt; i++) {
507 struct atom_value *v = &val[i];
514 * val is a list of atom_value to hold returned values. Extract
515 * the values for atoms in used_atom array out of (obj, buf, sz).
516 * when deref is false, (obj, buf, sz) is the object that is
517 * pointed at by the ref itself; otherwise it is the object the
518 * ref (which is a tag) refers to.
520 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
522 grab_common_values(val, deref, obj, buf, sz);
525 grab_tag_values(val, deref, obj, buf, sz);
526 grab_sub_body_contents(val, deref, obj, buf, sz);
527 grab_person("tagger", val, deref, obj, buf, sz);
530 grab_commit_values(val, deref, obj, buf, sz);
531 grab_sub_body_contents(val, deref, obj, buf, sz);
532 grab_person("author", val, deref, obj, buf, sz);
533 grab_person("committer", val, deref, obj, buf, sz);
536 // grab_tree_values(val, deref, obj, buf, sz);
539 // grab_blob_values(val, deref, obj, buf, sz);
542 die("Eh? Object of type %d?", obj->type);
547 * Parse the object referred by ref, and grab needed value.
549 static void populate_value(struct refinfo *ref)
555 const unsigned char *tagged;
557 ref->value = xcalloc(sizeof(struct atom_value), used_atom_cnt);
559 buf = get_obj(ref->objectname, &obj, &size, &eaten);
561 die("missing object %s for %s",
562 sha1_to_hex(ref->objectname), ref->refname);
564 die("parse_object_buffer failed on %s for %s",
565 sha1_to_hex(ref->objectname), ref->refname);
567 /* Fill in specials first */
568 for (i = 0; i < used_atom_cnt; i++) {
569 const char *name = used_atom[i];
570 struct atom_value *v = &ref->value[i];
571 if (!strcmp(name, "refname"))
573 else if (!strcmp(name, "*refname")) {
574 int len = strlen(ref->refname);
575 char *s = xmalloc(len + 4);
576 sprintf(s, "%s^{}", ref->refname);
581 grab_values(ref->value, 0, obj, buf, size);
585 /* If there is no atom that wants to know about tagged
586 * object, we are done.
588 if (!need_tagged || (obj->type != OBJ_TAG))
591 /* If it is a tag object, see if we use a value that derefs
592 * the object, and if we do grab the object it refers to.
594 tagged = ((struct tag *)obj)->tagged->sha1;
596 /* NEEDSWORK: This derefs tag only once, which
597 * is good to deal with chains of trust, but
598 * is not consistent with what deref_tag() does
599 * which peels the onion to the core.
601 buf = get_obj(tagged, &obj, &size, &eaten);
603 die("missing object %s for %s",
604 sha1_to_hex(tagged), ref->refname);
606 die("parse_object_buffer failed on %s for %s",
607 sha1_to_hex(tagged), ref->refname);
608 grab_values(ref->value, 1, obj, buf, size);
614 * Given a ref, return the value for the atom. This lazily gets value
615 * out of the object by calling populate value.
617 static void get_value(struct refinfo *ref, int atom, struct atom_value **v)
621 fill_missing_values(ref->value);
623 *v = &ref->value[atom];
626 struct grab_ref_cbdata {
627 struct refinfo **grab_array;
628 const char **grab_pattern;
633 * A call-back given to for_each_ref(). It is unfortunate that we
634 * need to use global variables to pass extra information to this
637 static int grab_single_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
639 struct grab_ref_cbdata *cb = cb_data;
643 if (*cb->grab_pattern) {
644 const char **pattern;
645 int namelen = strlen(refname);
646 for (pattern = cb->grab_pattern; *pattern; pattern++) {
647 const char *p = *pattern;
648 int plen = strlen(p);
650 if ((plen <= namelen) &&
651 !strncmp(refname, p, plen) &&
652 (refname[plen] == '\0' ||
653 refname[plen] == '/' ||
656 if (!fnmatch(p, refname, FNM_PATHNAME))
663 /* We do not open the object yet; sort may only need refname
664 * to do its job and the resulting list may yet to be pruned
667 ref = xcalloc(1, sizeof(*ref));
668 ref->refname = xstrdup(refname);
669 hashcpy(ref->objectname, sha1);
672 cb->grab_array = xrealloc(cb->grab_array,
673 sizeof(*cb->grab_array) * (cnt + 1));
674 cb->grab_array[cnt++] = ref;
679 static int cmp_ref_sort(struct ref_sort *s, struct refinfo *a, struct refinfo *b)
681 struct atom_value *va, *vb;
683 cmp_type cmp_type = used_atom_type[s->atom];
685 get_value(a, s->atom, &va);
686 get_value(b, s->atom, &vb);
689 cmp = strcmp(va->s, vb->s);
694 else if (va->ul == vb->ul)
700 return (s->reverse) ? -cmp : cmp;
703 static struct ref_sort *ref_sort;
704 static int compare_refs(const void *a_, const void *b_)
706 struct refinfo *a = *((struct refinfo **)a_);
707 struct refinfo *b = *((struct refinfo **)b_);
710 for (s = ref_sort; s; s = s->next) {
711 int cmp = cmp_ref_sort(s, a, b);
718 static void sort_refs(struct ref_sort *sort, struct refinfo **refs, int num_refs)
721 qsort(refs, num_refs, sizeof(struct refinfo *), compare_refs);
724 static void print_value(struct refinfo *ref, int atom, int quote_style)
726 struct atom_value *v;
727 get_value(ref, atom, &v);
728 switch (quote_style) {
733 sq_quote_print(stdout, v->s);
736 perl_quote_print(stdout, v->s);
739 python_quote_print(stdout, v->s);
742 tcl_quote_print(stdout, v->s);
747 static int hex1(char ch)
749 if ('0' <= ch && ch <= '9')
751 else if ('a' <= ch && ch <= 'f')
752 return ch - 'a' + 10;
753 else if ('A' <= ch && ch <= 'F')
754 return ch - 'A' + 10;
757 static int hex2(const char *cp)
760 return (hex1(cp[0]) << 4) | hex1(cp[1]);
765 static void emit(const char *cp, const char *ep)
767 while (*cp && (!ep || cp < ep)) {
772 int ch = hex2(cp + 1);
785 static void show_ref(struct refinfo *info, const char *format, int quote_style)
787 const char *cp, *sp, *ep;
789 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
790 ep = strchr(sp, ')');
793 print_value(info, parse_atom(sp + 2, ep), quote_style);
796 sp = cp + strlen(cp);
802 static struct ref_sort *default_sort(void)
804 static const char cstr_name[] = "refname";
806 struct ref_sort *sort = xcalloc(1, sizeof(*sort));
809 sort->atom = parse_atom(cstr_name, cstr_name + strlen(cstr_name));
813 static int opt_parse_sort(const struct option *opt, const char *arg, int unset)
815 struct ref_sort **sort_tail = opt->value;
819 if (!arg) /* should --no-sort void the list ? */
822 *sort_tail = s = xcalloc(1, sizeof(*s));
823 sort_tail = &s->next;
830 s->atom = parse_atom(arg, arg+len);
834 static char const * const for_each_ref_usage[] = {
835 "git for-each-ref [options] [<pattern>]",
839 int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
842 const char *format = "%(objectname) %(objecttype)\t%(refname)";
843 struct ref_sort *sort = NULL, **sort_tail = &sort;
844 int maxcount = 0, quote_style = 0;
845 struct refinfo **refs;
846 struct grab_ref_cbdata cbdata;
848 struct option opts[] = {
849 OPT_BIT('s', "shell", "e_style,
850 "quote placeholders suitably for shells", QUOTE_SHELL),
851 OPT_BIT('p', "perl", "e_style,
852 "quote placeholders suitably for perl", QUOTE_PERL),
853 OPT_BIT(0 , "python", "e_style,
854 "quote placeholders suitably for python", QUOTE_PYTHON),
855 OPT_BIT(0 , "tcl", "e_style,
856 "quote placeholders suitably for tcl", QUOTE_TCL),
859 OPT_INTEGER( 0 , "count", &maxcount, "show only <n> matched refs"),
860 OPT_STRING( 0 , "format", &format, "format", "format to use for the output"),
861 OPT_CALLBACK(0 , "sort", sort_tail, "key",
862 "field name to sort on", &opt_parse_sort),
866 parse_options(argc, argv, opts, for_each_ref_usage, 0);
868 error("invalid --count argument: `%d'", maxcount);
869 usage_with_options(for_each_ref_usage, opts);
871 if (HAS_MULTI_BITS(quote_style)) {
872 error("more than one quoting style?");
873 usage_with_options(for_each_ref_usage, opts);
875 if (verify_format(format))
876 usage_with_options(for_each_ref_usage, opts);
879 sort = default_sort();
880 sort_atom_limit = used_atom_cnt;
882 memset(&cbdata, 0, sizeof(cbdata));
883 cbdata.grab_pattern = argv;
884 for_each_ref(grab_single_ref, &cbdata);
885 refs = cbdata.grab_array;
886 num_refs = cbdata.grab_cnt;
888 for (i = 0; i < used_atom_cnt; i++) {
889 if (used_atom[i][0] == '*') {
895 sort_refs(sort, refs, num_refs);
897 if (!maxcount || num_refs < maxcount)
899 for (i = 0; i < maxcount; i++)
900 show_ref(refs[i], format, quote_style);