for-each-ref: use skip_prefix() to avoid duplicate string comparison
[git/gitweb.git] / builtin / for-each-ref.c
blob9463dca196787b62aa1e5aeda89d15869ec2b349
1 #include "builtin.h"
2 #include "cache.h"
3 #include "refs.h"
4 #include "object.h"
5 #include "tag.h"
6 #include "commit.h"
7 #include "tree.h"
8 #include "blob.h"
9 #include "quote.h"
10 #include "parse-options.h"
11 #include "remote.h"
12 #include "color.h"
14 /* Quoting styles */
15 #define QUOTE_NONE 0
16 #define QUOTE_SHELL 1
17 #define QUOTE_PERL 2
18 #define QUOTE_PYTHON 4
19 #define QUOTE_TCL 8
21 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
23 struct atom_value {
24 const char *s;
25 unsigned long ul; /* used for sorting when not FIELD_STR */
28 struct ref_sort {
29 struct ref_sort *next;
30 int atom; /* index into used_atom array */
31 unsigned reverse : 1;
34 struct refinfo {
35 char *refname;
36 unsigned char objectname[20];
37 int flag;
38 const char *symref;
39 struct atom_value *value;
42 static struct {
43 const char *name;
44 cmp_type cmp_type;
45 } valid_atom[] = {
46 { "refname" },
47 { "objecttype" },
48 { "objectsize", FIELD_ULONG },
49 { "objectname" },
50 { "tree" },
51 { "parent" },
52 { "numparent", FIELD_ULONG },
53 { "object" },
54 { "type" },
55 { "tag" },
56 { "author" },
57 { "authorname" },
58 { "authoremail" },
59 { "authordate", FIELD_TIME },
60 { "committer" },
61 { "committername" },
62 { "committeremail" },
63 { "committerdate", FIELD_TIME },
64 { "tagger" },
65 { "taggername" },
66 { "taggeremail" },
67 { "taggerdate", FIELD_TIME },
68 { "creator" },
69 { "creatordate", FIELD_TIME },
70 { "subject" },
71 { "body" },
72 { "contents" },
73 { "contents:subject" },
74 { "contents:body" },
75 { "contents:signature" },
76 { "upstream" },
77 { "symref" },
78 { "flag" },
79 { "HEAD" },
80 { "color" },
84 * An atom is a valid field atom listed above, possibly prefixed with
85 * a "*" to denote deref_tag().
87 * We parse given format string and sort specifiers, and make a list
88 * of properties that we need to extract out of objects. refinfo
89 * structure will hold an array of values extracted that can be
90 * indexed with the "atom number", which is an index into this
91 * array.
93 static const char **used_atom;
94 static cmp_type *used_atom_type;
95 static int used_atom_cnt, need_tagged, need_symref;
96 static int need_color_reset_at_eol;
99 * Used to parse format string and sort specifiers
101 static int parse_atom(const char *atom, const char *ep)
103 const char *sp;
104 int i, at;
106 sp = atom;
107 if (*sp == '*' && sp < ep)
108 sp++; /* deref */
109 if (ep <= sp)
110 die("malformed field name: %.*s", (int)(ep-atom), atom);
112 /* Do we have the atom already used elsewhere? */
113 for (i = 0; i < used_atom_cnt; i++) {
114 int len = strlen(used_atom[i]);
115 if (len == ep - atom && !memcmp(used_atom[i], atom, len))
116 return i;
119 /* Is the atom a valid one? */
120 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
121 int len = strlen(valid_atom[i].name);
123 * If the atom name has a colon, strip it and everything after
124 * it off - it specifies the format for this entry, and
125 * shouldn't be used for checking against the valid_atom
126 * table.
128 const char *formatp = strchr(sp, ':');
129 if (!formatp || ep < formatp)
130 formatp = ep;
131 if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
132 break;
135 if (ARRAY_SIZE(valid_atom) <= i)
136 die("unknown field name: %.*s", (int)(ep-atom), atom);
138 /* Add it in, including the deref prefix */
139 at = used_atom_cnt;
140 used_atom_cnt++;
141 used_atom = xrealloc(used_atom,
142 (sizeof *used_atom) * used_atom_cnt);
143 used_atom_type = xrealloc(used_atom_type,
144 (sizeof(*used_atom_type) * used_atom_cnt));
145 used_atom[at] = xmemdupz(atom, ep - atom);
146 used_atom_type[at] = valid_atom[i].cmp_type;
147 if (*atom == '*')
148 need_tagged = 1;
149 if (!strcmp(used_atom[at], "symref"))
150 need_symref = 1;
151 return at;
155 * In a format string, find the next occurrence of %(atom).
157 static const char *find_next(const char *cp)
159 while (*cp) {
160 if (*cp == '%') {
162 * %( is the start of an atom;
163 * %% is a quoted per-cent.
165 if (cp[1] == '(')
166 return cp;
167 else if (cp[1] == '%')
168 cp++; /* skip over two % */
169 /* otherwise this is a singleton, literal % */
171 cp++;
173 return NULL;
177 * Make sure the format string is well formed, and parse out
178 * the used atoms.
180 static int verify_format(const char *format)
182 const char *cp, *sp;
184 need_color_reset_at_eol = 0;
185 for (cp = format; *cp && (sp = find_next(cp)); ) {
186 const char *color, *ep = strchr(sp, ')');
187 int at;
189 if (!ep)
190 return error("malformed format string %s", sp);
191 /* sp points at "%(" and ep points at the closing ")" */
192 at = parse_atom(sp + 2, ep);
193 cp = ep + 1;
195 if (skip_prefix(used_atom[at], "color:", &color))
196 need_color_reset_at_eol = !!strcmp(color, "reset");
198 return 0;
202 * Given an object name, read the object data and size, and return a
203 * "struct object". If the object data we are returning is also borrowed
204 * by the "struct object" representation, set *eaten as well---it is a
205 * signal from parse_object_buffer to us not to free the buffer.
207 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
209 enum object_type type;
210 void *buf = read_sha1_file(sha1, &type, sz);
212 if (buf)
213 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
214 else
215 *obj = NULL;
216 return buf;
219 static int grab_objectname(const char *name, const unsigned char *sha1,
220 struct atom_value *v)
222 if (!strcmp(name, "objectname")) {
223 char *s = xmalloc(41);
224 strcpy(s, sha1_to_hex(sha1));
225 v->s = s;
226 return 1;
228 if (!strcmp(name, "objectname:short")) {
229 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
230 return 1;
232 return 0;
235 /* See grab_values */
236 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
238 int i;
240 for (i = 0; i < used_atom_cnt; i++) {
241 const char *name = used_atom[i];
242 struct atom_value *v = &val[i];
243 if (!!deref != (*name == '*'))
244 continue;
245 if (deref)
246 name++;
247 if (!strcmp(name, "objecttype"))
248 v->s = typename(obj->type);
249 else if (!strcmp(name, "objectsize")) {
250 char *s = xmalloc(40);
251 sprintf(s, "%lu", sz);
252 v->ul = sz;
253 v->s = s;
255 else if (deref)
256 grab_objectname(name, obj->sha1, v);
260 /* See grab_values */
261 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
263 int i;
264 struct tag *tag = (struct tag *) obj;
266 for (i = 0; i < used_atom_cnt; i++) {
267 const char *name = used_atom[i];
268 struct atom_value *v = &val[i];
269 if (!!deref != (*name == '*'))
270 continue;
271 if (deref)
272 name++;
273 if (!strcmp(name, "tag"))
274 v->s = tag->tag;
275 else if (!strcmp(name, "type") && tag->tagged)
276 v->s = typename(tag->tagged->type);
277 else if (!strcmp(name, "object") && tag->tagged) {
278 char *s = xmalloc(41);
279 strcpy(s, sha1_to_hex(tag->tagged->sha1));
280 v->s = s;
285 /* See grab_values */
286 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
288 int i;
289 struct commit *commit = (struct commit *) obj;
291 for (i = 0; i < used_atom_cnt; i++) {
292 const char *name = used_atom[i];
293 struct atom_value *v = &val[i];
294 if (!!deref != (*name == '*'))
295 continue;
296 if (deref)
297 name++;
298 if (!strcmp(name, "tree")) {
299 char *s = xmalloc(41);
300 strcpy(s, sha1_to_hex(commit->tree->object.sha1));
301 v->s = s;
303 if (!strcmp(name, "numparent")) {
304 char *s = xmalloc(40);
305 v->ul = commit_list_count(commit->parents);
306 sprintf(s, "%lu", v->ul);
307 v->s = s;
309 else if (!strcmp(name, "parent")) {
310 int num = commit_list_count(commit->parents);
311 int i;
312 struct commit_list *parents;
313 char *s = xmalloc(41 * num + 1);
314 v->s = s;
315 for (i = 0, parents = commit->parents;
316 parents;
317 parents = parents->next, i = i + 41) {
318 struct commit *parent = parents->item;
319 strcpy(s+i, sha1_to_hex(parent->object.sha1));
320 if (parents->next)
321 s[i+40] = ' ';
323 if (!i)
324 *s = '\0';
329 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
331 const char *eol;
332 while (*buf) {
333 if (!strncmp(buf, who, wholen) &&
334 buf[wholen] == ' ')
335 return buf + wholen + 1;
336 eol = strchr(buf, '\n');
337 if (!eol)
338 return "";
339 eol++;
340 if (*eol == '\n')
341 return ""; /* end of header */
342 buf = eol;
344 return "";
347 static const char *copy_line(const char *buf)
349 const char *eol = strchrnul(buf, '\n');
350 return xmemdupz(buf, eol - buf);
353 static const char *copy_name(const char *buf)
355 const char *cp;
356 for (cp = buf; *cp && *cp != '\n'; cp++) {
357 if (!strncmp(cp, " <", 2))
358 return xmemdupz(buf, cp - buf);
360 return "";
363 static const char *copy_email(const char *buf)
365 const char *email = strchr(buf, '<');
366 const char *eoemail;
367 if (!email)
368 return "";
369 eoemail = strchr(email, '>');
370 if (!eoemail)
371 return "";
372 return xmemdupz(email, eoemail + 1 - email);
375 static char *copy_subject(const char *buf, unsigned long len)
377 char *r = xmemdupz(buf, len);
378 int i;
380 for (i = 0; i < len; i++)
381 if (r[i] == '\n')
382 r[i] = ' ';
384 return r;
387 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
389 const char *eoemail = strstr(buf, "> ");
390 char *zone;
391 unsigned long timestamp;
392 long tz;
393 enum date_mode date_mode = DATE_NORMAL;
394 const char *formatp;
397 * We got here because atomname ends in "date" or "date<something>";
398 * it's not possible that <something> is not ":<format>" because
399 * parse_atom() wouldn't have allowed it, so we can assume that no
400 * ":" means no format is specified, and use the default.
402 formatp = strchr(atomname, ':');
403 if (formatp != NULL) {
404 formatp++;
405 date_mode = parse_date_format(formatp);
408 if (!eoemail)
409 goto bad;
410 timestamp = strtoul(eoemail + 2, &zone, 10);
411 if (timestamp == ULONG_MAX)
412 goto bad;
413 tz = strtol(zone, NULL, 10);
414 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
415 goto bad;
416 v->s = xstrdup(show_date(timestamp, tz, date_mode));
417 v->ul = timestamp;
418 return;
419 bad:
420 v->s = "";
421 v->ul = 0;
424 /* See grab_values */
425 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
427 int i;
428 int wholen = strlen(who);
429 const char *wholine = NULL;
431 for (i = 0; i < used_atom_cnt; i++) {
432 const char *name = used_atom[i];
433 struct atom_value *v = &val[i];
434 if (!!deref != (*name == '*'))
435 continue;
436 if (deref)
437 name++;
438 if (strncmp(who, name, wholen))
439 continue;
440 if (name[wholen] != 0 &&
441 strcmp(name + wholen, "name") &&
442 strcmp(name + wholen, "email") &&
443 !starts_with(name + wholen, "date"))
444 continue;
445 if (!wholine)
446 wholine = find_wholine(who, wholen, buf, sz);
447 if (!wholine)
448 return; /* no point looking for it */
449 if (name[wholen] == 0)
450 v->s = copy_line(wholine);
451 else if (!strcmp(name + wholen, "name"))
452 v->s = copy_name(wholine);
453 else if (!strcmp(name + wholen, "email"))
454 v->s = copy_email(wholine);
455 else if (starts_with(name + wholen, "date"))
456 grab_date(wholine, v, name);
460 * For a tag or a commit object, if "creator" or "creatordate" is
461 * requested, do something special.
463 if (strcmp(who, "tagger") && strcmp(who, "committer"))
464 return; /* "author" for commit object is not wanted */
465 if (!wholine)
466 wholine = find_wholine(who, wholen, buf, sz);
467 if (!wholine)
468 return;
469 for (i = 0; i < used_atom_cnt; i++) {
470 const char *name = used_atom[i];
471 struct atom_value *v = &val[i];
472 if (!!deref != (*name == '*'))
473 continue;
474 if (deref)
475 name++;
477 if (starts_with(name, "creatordate"))
478 grab_date(wholine, v, name);
479 else if (!strcmp(name, "creator"))
480 v->s = copy_line(wholine);
484 static void find_subpos(const char *buf, unsigned long sz,
485 const char **sub, unsigned long *sublen,
486 const char **body, unsigned long *bodylen,
487 unsigned long *nonsiglen,
488 const char **sig, unsigned long *siglen)
490 const char *eol;
491 /* skip past header until we hit empty line */
492 while (*buf && *buf != '\n') {
493 eol = strchrnul(buf, '\n');
494 if (*eol)
495 eol++;
496 buf = eol;
498 /* skip any empty lines */
499 while (*buf == '\n')
500 buf++;
502 /* parse signature first; we might not even have a subject line */
503 *sig = buf + parse_signature(buf, strlen(buf));
504 *siglen = strlen(*sig);
506 /* subject is first non-empty line */
507 *sub = buf;
508 /* subject goes to first empty line */
509 while (buf < *sig && *buf && *buf != '\n') {
510 eol = strchrnul(buf, '\n');
511 if (*eol)
512 eol++;
513 buf = eol;
515 *sublen = buf - *sub;
516 /* drop trailing newline, if present */
517 if (*sublen && (*sub)[*sublen - 1] == '\n')
518 *sublen -= 1;
520 /* skip any empty lines */
521 while (*buf == '\n')
522 buf++;
523 *body = buf;
524 *bodylen = strlen(buf);
525 *nonsiglen = *sig - buf;
528 /* See grab_values */
529 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
531 int i;
532 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
533 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
535 for (i = 0; i < used_atom_cnt; i++) {
536 const char *name = used_atom[i];
537 struct atom_value *v = &val[i];
538 if (!!deref != (*name == '*'))
539 continue;
540 if (deref)
541 name++;
542 if (strcmp(name, "subject") &&
543 strcmp(name, "body") &&
544 strcmp(name, "contents") &&
545 strcmp(name, "contents:subject") &&
546 strcmp(name, "contents:body") &&
547 strcmp(name, "contents:signature"))
548 continue;
549 if (!subpos)
550 find_subpos(buf, sz,
551 &subpos, &sublen,
552 &bodypos, &bodylen, &nonsiglen,
553 &sigpos, &siglen);
555 if (!strcmp(name, "subject"))
556 v->s = copy_subject(subpos, sublen);
557 else if (!strcmp(name, "contents:subject"))
558 v->s = copy_subject(subpos, sublen);
559 else if (!strcmp(name, "body"))
560 v->s = xmemdupz(bodypos, bodylen);
561 else if (!strcmp(name, "contents:body"))
562 v->s = xmemdupz(bodypos, nonsiglen);
563 else if (!strcmp(name, "contents:signature"))
564 v->s = xmemdupz(sigpos, siglen);
565 else if (!strcmp(name, "contents"))
566 v->s = xstrdup(subpos);
571 * We want to have empty print-string for field requests
572 * that do not apply (e.g. "authordate" for a tag object)
574 static void fill_missing_values(struct atom_value *val)
576 int i;
577 for (i = 0; i < used_atom_cnt; i++) {
578 struct atom_value *v = &val[i];
579 if (v->s == NULL)
580 v->s = "";
585 * val is a list of atom_value to hold returned values. Extract
586 * the values for atoms in used_atom array out of (obj, buf, sz).
587 * when deref is false, (obj, buf, sz) is the object that is
588 * pointed at by the ref itself; otherwise it is the object the
589 * ref (which is a tag) refers to.
591 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
593 grab_common_values(val, deref, obj, buf, sz);
594 switch (obj->type) {
595 case OBJ_TAG:
596 grab_tag_values(val, deref, obj, buf, sz);
597 grab_sub_body_contents(val, deref, obj, buf, sz);
598 grab_person("tagger", val, deref, obj, buf, sz);
599 break;
600 case OBJ_COMMIT:
601 grab_commit_values(val, deref, obj, buf, sz);
602 grab_sub_body_contents(val, deref, obj, buf, sz);
603 grab_person("author", val, deref, obj, buf, sz);
604 grab_person("committer", val, deref, obj, buf, sz);
605 break;
606 case OBJ_TREE:
607 /* grab_tree_values(val, deref, obj, buf, sz); */
608 break;
609 case OBJ_BLOB:
610 /* grab_blob_values(val, deref, obj, buf, sz); */
611 break;
612 default:
613 die("Eh? Object of type %d?", obj->type);
617 static inline char *copy_advance(char *dst, const char *src)
619 while (*src)
620 *dst++ = *src++;
621 return dst;
625 * Parse the object referred by ref, and grab needed value.
627 static void populate_value(struct refinfo *ref)
629 void *buf;
630 struct object *obj;
631 int eaten, i;
632 unsigned long size;
633 const unsigned char *tagged;
635 ref->value = xcalloc(sizeof(struct atom_value), used_atom_cnt);
637 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
638 unsigned char unused1[20];
639 ref->symref = resolve_refdup(ref->refname, unused1, 1, NULL);
640 if (!ref->symref)
641 ref->symref = "";
644 /* Fill in specials first */
645 for (i = 0; i < used_atom_cnt; i++) {
646 const char *name = used_atom[i];
647 struct atom_value *v = &ref->value[i];
648 int deref = 0;
649 const char *refname;
650 const char *formatp;
651 struct branch *branch = NULL;
653 if (*name == '*') {
654 deref = 1;
655 name++;
658 if (starts_with(name, "refname"))
659 refname = ref->refname;
660 else if (starts_with(name, "symref"))
661 refname = ref->symref ? ref->symref : "";
662 else if (starts_with(name, "upstream")) {
663 /* only local branches may have an upstream */
664 if (!starts_with(ref->refname, "refs/heads/"))
665 continue;
666 branch = branch_get(ref->refname + 11);
668 if (!branch || !branch->merge || !branch->merge[0] ||
669 !branch->merge[0]->dst)
670 continue;
671 refname = branch->merge[0]->dst;
672 } else if (starts_with(name, "color:")) {
673 char color[COLOR_MAXLEN] = "";
675 color_parse(name + 6, "--format", color);
676 v->s = xstrdup(color);
677 continue;
678 } else if (!strcmp(name, "flag")) {
679 char buf[256], *cp = buf;
680 if (ref->flag & REF_ISSYMREF)
681 cp = copy_advance(cp, ",symref");
682 if (ref->flag & REF_ISPACKED)
683 cp = copy_advance(cp, ",packed");
684 if (cp == buf)
685 v->s = "";
686 else {
687 *cp = '\0';
688 v->s = xstrdup(buf + 1);
690 continue;
691 } else if (!deref && grab_objectname(name, ref->objectname, v)) {
692 continue;
693 } else if (!strcmp(name, "HEAD")) {
694 const char *head;
695 unsigned char sha1[20];
697 head = resolve_ref_unsafe("HEAD", sha1, 1, NULL);
698 if (!strcmp(ref->refname, head))
699 v->s = "*";
700 else
701 v->s = " ";
702 continue;
703 } else
704 continue;
706 formatp = strchr(name, ':');
707 if (formatp) {
708 int num_ours, num_theirs;
710 formatp++;
711 if (!strcmp(formatp, "short"))
712 refname = shorten_unambiguous_ref(refname,
713 warn_ambiguous_refs);
714 else if (!strcmp(formatp, "track") &&
715 starts_with(name, "upstream")) {
716 char buf[40];
718 stat_tracking_info(branch, &num_ours, &num_theirs);
719 if (!num_ours && !num_theirs)
720 v->s = "";
721 else if (!num_ours) {
722 sprintf(buf, "[behind %d]", num_theirs);
723 v->s = xstrdup(buf);
724 } else if (!num_theirs) {
725 sprintf(buf, "[ahead %d]", num_ours);
726 v->s = xstrdup(buf);
727 } else {
728 sprintf(buf, "[ahead %d, behind %d]",
729 num_ours, num_theirs);
730 v->s = xstrdup(buf);
732 continue;
733 } else if (!strcmp(formatp, "trackshort") &&
734 starts_with(name, "upstream")) {
735 assert(branch);
736 stat_tracking_info(branch, &num_ours, &num_theirs);
737 if (!num_ours && !num_theirs)
738 v->s = "=";
739 else if (!num_ours)
740 v->s = "<";
741 else if (!num_theirs)
742 v->s = ">";
743 else
744 v->s = "<>";
745 continue;
746 } else
747 die("unknown %.*s format %s",
748 (int)(formatp - name), name, formatp);
751 if (!deref)
752 v->s = refname;
753 else {
754 int len = strlen(refname);
755 char *s = xmalloc(len + 4);
756 sprintf(s, "%s^{}", refname);
757 v->s = s;
761 for (i = 0; i < used_atom_cnt; i++) {
762 struct atom_value *v = &ref->value[i];
763 if (v->s == NULL)
764 goto need_obj;
766 return;
768 need_obj:
769 buf = get_obj(ref->objectname, &obj, &size, &eaten);
770 if (!buf)
771 die("missing object %s for %s",
772 sha1_to_hex(ref->objectname), ref->refname);
773 if (!obj)
774 die("parse_object_buffer failed on %s for %s",
775 sha1_to_hex(ref->objectname), ref->refname);
777 grab_values(ref->value, 0, obj, buf, size);
778 if (!eaten)
779 free(buf);
782 * If there is no atom that wants to know about tagged
783 * object, we are done.
785 if (!need_tagged || (obj->type != OBJ_TAG))
786 return;
789 * If it is a tag object, see if we use a value that derefs
790 * the object, and if we do grab the object it refers to.
792 tagged = ((struct tag *)obj)->tagged->sha1;
795 * NEEDSWORK: This derefs tag only once, which
796 * is good to deal with chains of trust, but
797 * is not consistent with what deref_tag() does
798 * which peels the onion to the core.
800 buf = get_obj(tagged, &obj, &size, &eaten);
801 if (!buf)
802 die("missing object %s for %s",
803 sha1_to_hex(tagged), ref->refname);
804 if (!obj)
805 die("parse_object_buffer failed on %s for %s",
806 sha1_to_hex(tagged), ref->refname);
807 grab_values(ref->value, 1, obj, buf, size);
808 if (!eaten)
809 free(buf);
813 * Given a ref, return the value for the atom. This lazily gets value
814 * out of the object by calling populate value.
816 static void get_value(struct refinfo *ref, int atom, struct atom_value **v)
818 if (!ref->value) {
819 populate_value(ref);
820 fill_missing_values(ref->value);
822 *v = &ref->value[atom];
825 struct grab_ref_cbdata {
826 struct refinfo **grab_array;
827 const char **grab_pattern;
828 int grab_cnt;
832 * A call-back given to for_each_ref(). Filter refs and keep them for
833 * later object processing.
835 static int grab_single_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
837 struct grab_ref_cbdata *cb = cb_data;
838 struct refinfo *ref;
839 int cnt;
841 if (*cb->grab_pattern) {
842 const char **pattern;
843 int namelen = strlen(refname);
844 for (pattern = cb->grab_pattern; *pattern; pattern++) {
845 const char *p = *pattern;
846 int plen = strlen(p);
848 if ((plen <= namelen) &&
849 !strncmp(refname, p, plen) &&
850 (refname[plen] == '\0' ||
851 refname[plen] == '/' ||
852 p[plen-1] == '/'))
853 break;
854 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
855 break;
857 if (!*pattern)
858 return 0;
862 * We do not open the object yet; sort may only need refname
863 * to do its job and the resulting list may yet to be pruned
864 * by maxcount logic.
866 ref = xcalloc(1, sizeof(*ref));
867 ref->refname = xstrdup(refname);
868 hashcpy(ref->objectname, sha1);
869 ref->flag = flag;
871 cnt = cb->grab_cnt;
872 cb->grab_array = xrealloc(cb->grab_array,
873 sizeof(*cb->grab_array) * (cnt + 1));
874 cb->grab_array[cnt++] = ref;
875 cb->grab_cnt = cnt;
876 return 0;
879 static int cmp_ref_sort(struct ref_sort *s, struct refinfo *a, struct refinfo *b)
881 struct atom_value *va, *vb;
882 int cmp;
883 cmp_type cmp_type = used_atom_type[s->atom];
885 get_value(a, s->atom, &va);
886 get_value(b, s->atom, &vb);
887 switch (cmp_type) {
888 case FIELD_STR:
889 cmp = strcmp(va->s, vb->s);
890 break;
891 default:
892 if (va->ul < vb->ul)
893 cmp = -1;
894 else if (va->ul == vb->ul)
895 cmp = 0;
896 else
897 cmp = 1;
898 break;
900 return (s->reverse) ? -cmp : cmp;
903 static struct ref_sort *ref_sort;
904 static int compare_refs(const void *a_, const void *b_)
906 struct refinfo *a = *((struct refinfo **)a_);
907 struct refinfo *b = *((struct refinfo **)b_);
908 struct ref_sort *s;
910 for (s = ref_sort; s; s = s->next) {
911 int cmp = cmp_ref_sort(s, a, b);
912 if (cmp)
913 return cmp;
915 return 0;
918 static void sort_refs(struct ref_sort *sort, struct refinfo **refs, int num_refs)
920 ref_sort = sort;
921 qsort(refs, num_refs, sizeof(struct refinfo *), compare_refs);
924 static void print_value(struct atom_value *v, int quote_style)
926 struct strbuf sb = STRBUF_INIT;
927 switch (quote_style) {
928 case QUOTE_NONE:
929 fputs(v->s, stdout);
930 break;
931 case QUOTE_SHELL:
932 sq_quote_buf(&sb, v->s);
933 break;
934 case QUOTE_PERL:
935 perl_quote_buf(&sb, v->s);
936 break;
937 case QUOTE_PYTHON:
938 python_quote_buf(&sb, v->s);
939 break;
940 case QUOTE_TCL:
941 tcl_quote_buf(&sb, v->s);
942 break;
944 if (quote_style != QUOTE_NONE) {
945 fputs(sb.buf, stdout);
946 strbuf_release(&sb);
950 static int hex1(char ch)
952 if ('0' <= ch && ch <= '9')
953 return ch - '0';
954 else if ('a' <= ch && ch <= 'f')
955 return ch - 'a' + 10;
956 else if ('A' <= ch && ch <= 'F')
957 return ch - 'A' + 10;
958 return -1;
960 static int hex2(const char *cp)
962 if (cp[0] && cp[1])
963 return (hex1(cp[0]) << 4) | hex1(cp[1]);
964 else
965 return -1;
968 static void emit(const char *cp, const char *ep)
970 while (*cp && (!ep || cp < ep)) {
971 if (*cp == '%') {
972 if (cp[1] == '%')
973 cp++;
974 else {
975 int ch = hex2(cp + 1);
976 if (0 <= ch) {
977 putchar(ch);
978 cp += 3;
979 continue;
983 putchar(*cp);
984 cp++;
988 static void show_ref(struct refinfo *info, const char *format, int quote_style)
990 const char *cp, *sp, *ep;
992 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
993 struct atom_value *atomv;
995 ep = strchr(sp, ')');
996 if (cp < sp)
997 emit(cp, sp);
998 get_value(info, parse_atom(sp + 2, ep), &atomv);
999 print_value(atomv, quote_style);
1001 if (*cp) {
1002 sp = cp + strlen(cp);
1003 emit(cp, sp);
1005 if (need_color_reset_at_eol) {
1006 struct atom_value resetv;
1007 char color[COLOR_MAXLEN] = "";
1009 color_parse("reset", "--format", color);
1010 resetv.s = color;
1011 print_value(&resetv, quote_style);
1013 putchar('\n');
1016 static struct ref_sort *default_sort(void)
1018 static const char cstr_name[] = "refname";
1020 struct ref_sort *sort = xcalloc(1, sizeof(*sort));
1022 sort->next = NULL;
1023 sort->atom = parse_atom(cstr_name, cstr_name + strlen(cstr_name));
1024 return sort;
1027 static int opt_parse_sort(const struct option *opt, const char *arg, int unset)
1029 struct ref_sort **sort_tail = opt->value;
1030 struct ref_sort *s;
1031 int len;
1033 if (!arg) /* should --no-sort void the list ? */
1034 return -1;
1036 s = xcalloc(1, sizeof(*s));
1037 s->next = *sort_tail;
1038 *sort_tail = s;
1040 if (*arg == '-') {
1041 s->reverse = 1;
1042 arg++;
1044 len = strlen(arg);
1045 s->atom = parse_atom(arg, arg+len);
1046 return 0;
1049 static char const * const for_each_ref_usage[] = {
1050 N_("git for-each-ref [options] [<pattern>]"),
1051 NULL
1054 int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
1056 int i, num_refs;
1057 const char *format = "%(objectname) %(objecttype)\t%(refname)";
1058 struct ref_sort *sort = NULL, **sort_tail = &sort;
1059 int maxcount = 0, quote_style = 0;
1060 struct refinfo **refs;
1061 struct grab_ref_cbdata cbdata;
1063 struct option opts[] = {
1064 OPT_BIT('s', "shell", &quote_style,
1065 N_("quote placeholders suitably for shells"), QUOTE_SHELL),
1066 OPT_BIT('p', "perl", &quote_style,
1067 N_("quote placeholders suitably for perl"), QUOTE_PERL),
1068 OPT_BIT(0 , "python", &quote_style,
1069 N_("quote placeholders suitably for python"), QUOTE_PYTHON),
1070 OPT_BIT(0 , "tcl", &quote_style,
1071 N_("quote placeholders suitably for tcl"), QUOTE_TCL),
1073 OPT_GROUP(""),
1074 OPT_INTEGER( 0 , "count", &maxcount, N_("show only <n> matched refs")),
1075 OPT_STRING( 0 , "format", &format, N_("format"), N_("format to use for the output")),
1076 OPT_CALLBACK(0 , "sort", sort_tail, N_("key"),
1077 N_("field name to sort on"), &opt_parse_sort),
1078 OPT_END(),
1081 parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
1082 if (maxcount < 0) {
1083 error("invalid --count argument: `%d'", maxcount);
1084 usage_with_options(for_each_ref_usage, opts);
1086 if (HAS_MULTI_BITS(quote_style)) {
1087 error("more than one quoting style?");
1088 usage_with_options(for_each_ref_usage, opts);
1090 if (verify_format(format))
1091 usage_with_options(for_each_ref_usage, opts);
1093 if (!sort)
1094 sort = default_sort();
1096 /* for warn_ambiguous_refs */
1097 git_config(git_default_config, NULL);
1099 memset(&cbdata, 0, sizeof(cbdata));
1100 cbdata.grab_pattern = argv;
1101 for_each_rawref(grab_single_ref, &cbdata);
1102 refs = cbdata.grab_array;
1103 num_refs = cbdata.grab_cnt;
1105 sort_refs(sort, refs, num_refs);
1107 if (!maxcount || num_refs < maxcount)
1108 maxcount = num_refs;
1109 for (i = 0; i < maxcount; i++)
1110 show_ref(refs[i], format, quote_style);
1111 return 0;