for-each-ref: avoid color leakage
[alt-git.git] / builtin / for-each-ref.c
blob5ff51d1d322c554fc906a78b7b88130d7a8dd60e
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, sort_atom_limit, 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;
183 static const char color_reset[] = "color:reset";
185 need_color_reset_at_eol = 0;
186 for (cp = format; *cp && (sp = find_next(cp)); ) {
187 const char *ep = strchr(sp, ')');
188 int at;
190 if (!ep)
191 return error("malformed format string %s", sp);
192 /* sp points at "%(" and ep points at the closing ")" */
193 at = parse_atom(sp + 2, ep);
194 cp = ep + 1;
196 if (!memcmp(used_atom[at], "color:", 6))
197 need_color_reset_at_eol = !!strcmp(used_atom[at], color_reset);
199 return 0;
203 * Given an object name, read the object data and size, and return a
204 * "struct object". If the object data we are returning is also borrowed
205 * by the "struct object" representation, set *eaten as well---it is a
206 * signal from parse_object_buffer to us not to free the buffer.
208 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
210 enum object_type type;
211 void *buf = read_sha1_file(sha1, &type, sz);
213 if (buf)
214 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
215 else
216 *obj = NULL;
217 return buf;
220 /* See grab_values */
221 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
223 int i;
225 for (i = 0; i < used_atom_cnt; i++) {
226 const char *name = used_atom[i];
227 struct atom_value *v = &val[i];
228 if (!!deref != (*name == '*'))
229 continue;
230 if (deref)
231 name++;
232 if (!strcmp(name, "objecttype"))
233 v->s = typename(obj->type);
234 else if (!strcmp(name, "objectsize")) {
235 char *s = xmalloc(40);
236 sprintf(s, "%lu", sz);
237 v->ul = sz;
238 v->s = s;
240 else if (!strcmp(name, "objectname")) {
241 char *s = xmalloc(41);
242 strcpy(s, sha1_to_hex(obj->sha1));
243 v->s = s;
245 else if (!strcmp(name, "objectname:short")) {
246 v->s = xstrdup(find_unique_abbrev(obj->sha1,
247 DEFAULT_ABBREV));
252 /* See grab_values */
253 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
255 int i;
256 struct tag *tag = (struct tag *) obj;
258 for (i = 0; i < used_atom_cnt; i++) {
259 const char *name = used_atom[i];
260 struct atom_value *v = &val[i];
261 if (!!deref != (*name == '*'))
262 continue;
263 if (deref)
264 name++;
265 if (!strcmp(name, "tag"))
266 v->s = tag->tag;
267 else if (!strcmp(name, "type") && tag->tagged)
268 v->s = typename(tag->tagged->type);
269 else if (!strcmp(name, "object") && tag->tagged) {
270 char *s = xmalloc(41);
271 strcpy(s, sha1_to_hex(tag->tagged->sha1));
272 v->s = s;
277 static int num_parents(struct commit *commit)
279 struct commit_list *parents;
280 int i;
282 for (i = 0, parents = commit->parents;
283 parents;
284 parents = parents->next)
285 i++;
286 return i;
289 /* See grab_values */
290 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
292 int i;
293 struct commit *commit = (struct commit *) obj;
295 for (i = 0; i < used_atom_cnt; i++) {
296 const char *name = used_atom[i];
297 struct atom_value *v = &val[i];
298 if (!!deref != (*name == '*'))
299 continue;
300 if (deref)
301 name++;
302 if (!strcmp(name, "tree")) {
303 char *s = xmalloc(41);
304 strcpy(s, sha1_to_hex(commit->tree->object.sha1));
305 v->s = s;
307 if (!strcmp(name, "numparent")) {
308 char *s = xmalloc(40);
309 v->ul = num_parents(commit);
310 sprintf(s, "%lu", v->ul);
311 v->s = s;
313 else if (!strcmp(name, "parent")) {
314 int num = num_parents(commit);
315 int i;
316 struct commit_list *parents;
317 char *s = xmalloc(41 * num + 1);
318 v->s = s;
319 for (i = 0, parents = commit->parents;
320 parents;
321 parents = parents->next, i = i + 41) {
322 struct commit *parent = parents->item;
323 strcpy(s+i, sha1_to_hex(parent->object.sha1));
324 if (parents->next)
325 s[i+40] = ' ';
327 if (!i)
328 *s = '\0';
333 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
335 const char *eol;
336 while (*buf) {
337 if (!strncmp(buf, who, wholen) &&
338 buf[wholen] == ' ')
339 return buf + wholen + 1;
340 eol = strchr(buf, '\n');
341 if (!eol)
342 return "";
343 eol++;
344 if (*eol == '\n')
345 return ""; /* end of header */
346 buf = eol;
348 return "";
351 static const char *copy_line(const char *buf)
353 const char *eol = strchrnul(buf, '\n');
354 return xmemdupz(buf, eol - buf);
357 static const char *copy_name(const char *buf)
359 const char *cp;
360 for (cp = buf; *cp && *cp != '\n'; cp++) {
361 if (!strncmp(cp, " <", 2))
362 return xmemdupz(buf, cp - buf);
364 return "";
367 static const char *copy_email(const char *buf)
369 const char *email = strchr(buf, '<');
370 const char *eoemail;
371 if (!email)
372 return "";
373 eoemail = strchr(email, '>');
374 if (!eoemail)
375 return "";
376 return xmemdupz(email, eoemail + 1 - email);
379 static char *copy_subject(const char *buf, unsigned long len)
381 char *r = xmemdupz(buf, len);
382 int i;
384 for (i = 0; i < len; i++)
385 if (r[i] == '\n')
386 r[i] = ' ';
388 return r;
391 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
393 const char *eoemail = strstr(buf, "> ");
394 char *zone;
395 unsigned long timestamp;
396 long tz;
397 enum date_mode date_mode = DATE_NORMAL;
398 const char *formatp;
401 * We got here because atomname ends in "date" or "date<something>";
402 * it's not possible that <something> is not ":<format>" because
403 * parse_atom() wouldn't have allowed it, so we can assume that no
404 * ":" means no format is specified, and use the default.
406 formatp = strchr(atomname, ':');
407 if (formatp != NULL) {
408 formatp++;
409 date_mode = parse_date_format(formatp);
412 if (!eoemail)
413 goto bad;
414 timestamp = strtoul(eoemail + 2, &zone, 10);
415 if (timestamp == ULONG_MAX)
416 goto bad;
417 tz = strtol(zone, NULL, 10);
418 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
419 goto bad;
420 v->s = xstrdup(show_date(timestamp, tz, date_mode));
421 v->ul = timestamp;
422 return;
423 bad:
424 v->s = "";
425 v->ul = 0;
428 /* See grab_values */
429 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
431 int i;
432 int wholen = strlen(who);
433 const char *wholine = NULL;
435 for (i = 0; i < used_atom_cnt; i++) {
436 const char *name = used_atom[i];
437 struct atom_value *v = &val[i];
438 if (!!deref != (*name == '*'))
439 continue;
440 if (deref)
441 name++;
442 if (strncmp(who, name, wholen))
443 continue;
444 if (name[wholen] != 0 &&
445 strcmp(name + wholen, "name") &&
446 strcmp(name + wholen, "email") &&
447 prefixcmp(name + wholen, "date"))
448 continue;
449 if (!wholine)
450 wholine = find_wholine(who, wholen, buf, sz);
451 if (!wholine)
452 return; /* no point looking for it */
453 if (name[wholen] == 0)
454 v->s = copy_line(wholine);
455 else if (!strcmp(name + wholen, "name"))
456 v->s = copy_name(wholine);
457 else if (!strcmp(name + wholen, "email"))
458 v->s = copy_email(wholine);
459 else if (!prefixcmp(name + wholen, "date"))
460 grab_date(wholine, v, name);
464 * For a tag or a commit object, if "creator" or "creatordate" is
465 * requested, do something special.
467 if (strcmp(who, "tagger") && strcmp(who, "committer"))
468 return; /* "author" for commit object is not wanted */
469 if (!wholine)
470 wholine = find_wholine(who, wholen, buf, sz);
471 if (!wholine)
472 return;
473 for (i = 0; i < used_atom_cnt; i++) {
474 const char *name = used_atom[i];
475 struct atom_value *v = &val[i];
476 if (!!deref != (*name == '*'))
477 continue;
478 if (deref)
479 name++;
481 if (!prefixcmp(name, "creatordate"))
482 grab_date(wholine, v, name);
483 else if (!strcmp(name, "creator"))
484 v->s = copy_line(wholine);
488 static void find_subpos(const char *buf, unsigned long sz,
489 const char **sub, unsigned long *sublen,
490 const char **body, unsigned long *bodylen,
491 unsigned long *nonsiglen,
492 const char **sig, unsigned long *siglen)
494 const char *eol;
495 /* skip past header until we hit empty line */
496 while (*buf && *buf != '\n') {
497 eol = strchrnul(buf, '\n');
498 if (*eol)
499 eol++;
500 buf = eol;
502 /* skip any empty lines */
503 while (*buf == '\n')
504 buf++;
506 /* parse signature first; we might not even have a subject line */
507 *sig = buf + parse_signature(buf, strlen(buf));
508 *siglen = strlen(*sig);
510 /* subject is first non-empty line */
511 *sub = buf;
512 /* subject goes to first empty line */
513 while (buf < *sig && *buf && *buf != '\n') {
514 eol = strchrnul(buf, '\n');
515 if (*eol)
516 eol++;
517 buf = eol;
519 *sublen = buf - *sub;
520 /* drop trailing newline, if present */
521 if (*sublen && (*sub)[*sublen - 1] == '\n')
522 *sublen -= 1;
524 /* skip any empty lines */
525 while (*buf == '\n')
526 buf++;
527 *body = buf;
528 *bodylen = strlen(buf);
529 *nonsiglen = *sig - buf;
532 /* See grab_values */
533 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
535 int i;
536 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
537 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
539 for (i = 0; i < used_atom_cnt; i++) {
540 const char *name = used_atom[i];
541 struct atom_value *v = &val[i];
542 if (!!deref != (*name == '*'))
543 continue;
544 if (deref)
545 name++;
546 if (strcmp(name, "subject") &&
547 strcmp(name, "body") &&
548 strcmp(name, "contents") &&
549 strcmp(name, "contents:subject") &&
550 strcmp(name, "contents:body") &&
551 strcmp(name, "contents:signature"))
552 continue;
553 if (!subpos)
554 find_subpos(buf, sz,
555 &subpos, &sublen,
556 &bodypos, &bodylen, &nonsiglen,
557 &sigpos, &siglen);
559 if (!strcmp(name, "subject"))
560 v->s = copy_subject(subpos, sublen);
561 else if (!strcmp(name, "contents:subject"))
562 v->s = copy_subject(subpos, sublen);
563 else if (!strcmp(name, "body"))
564 v->s = xmemdupz(bodypos, bodylen);
565 else if (!strcmp(name, "contents:body"))
566 v->s = xmemdupz(bodypos, nonsiglen);
567 else if (!strcmp(name, "contents:signature"))
568 v->s = xmemdupz(sigpos, siglen);
569 else if (!strcmp(name, "contents"))
570 v->s = xstrdup(subpos);
575 * We want to have empty print-string for field requests
576 * that do not apply (e.g. "authordate" for a tag object)
578 static void fill_missing_values(struct atom_value *val)
580 int i;
581 for (i = 0; i < used_atom_cnt; i++) {
582 struct atom_value *v = &val[i];
583 if (v->s == NULL)
584 v->s = "";
589 * val is a list of atom_value to hold returned values. Extract
590 * the values for atoms in used_atom array out of (obj, buf, sz).
591 * when deref is false, (obj, buf, sz) is the object that is
592 * pointed at by the ref itself; otherwise it is the object the
593 * ref (which is a tag) refers to.
595 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
597 grab_common_values(val, deref, obj, buf, sz);
598 switch (obj->type) {
599 case OBJ_TAG:
600 grab_tag_values(val, deref, obj, buf, sz);
601 grab_sub_body_contents(val, deref, obj, buf, sz);
602 grab_person("tagger", val, deref, obj, buf, sz);
603 break;
604 case OBJ_COMMIT:
605 grab_commit_values(val, deref, obj, buf, sz);
606 grab_sub_body_contents(val, deref, obj, buf, sz);
607 grab_person("author", val, deref, obj, buf, sz);
608 grab_person("committer", val, deref, obj, buf, sz);
609 break;
610 case OBJ_TREE:
611 /* grab_tree_values(val, deref, obj, buf, sz); */
612 break;
613 case OBJ_BLOB:
614 /* grab_blob_values(val, deref, obj, buf, sz); */
615 break;
616 default:
617 die("Eh? Object of type %d?", obj->type);
621 static inline char *copy_advance(char *dst, const char *src)
623 while (*src)
624 *dst++ = *src++;
625 return dst;
629 * Parse the object referred by ref, and grab needed value.
631 static void populate_value(struct refinfo *ref)
633 void *buf;
634 struct object *obj;
635 int eaten, i;
636 unsigned long size;
637 const unsigned char *tagged;
639 ref->value = xcalloc(sizeof(struct atom_value), used_atom_cnt);
641 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
642 unsigned char unused1[20];
643 ref->symref = resolve_refdup(ref->refname, unused1, 1, NULL);
644 if (!ref->symref)
645 ref->symref = "";
648 /* Fill in specials first */
649 for (i = 0; i < used_atom_cnt; i++) {
650 const char *name = used_atom[i];
651 struct atom_value *v = &ref->value[i];
652 int deref = 0;
653 const char *refname;
654 const char *formatp;
655 struct branch *branch = NULL;
657 if (*name == '*') {
658 deref = 1;
659 name++;
662 if (!prefixcmp(name, "refname"))
663 refname = ref->refname;
664 else if (!prefixcmp(name, "symref"))
665 refname = ref->symref ? ref->symref : "";
666 else if (!prefixcmp(name, "upstream")) {
667 /* only local branches may have an upstream */
668 if (prefixcmp(ref->refname, "refs/heads/"))
669 continue;
670 branch = branch_get(ref->refname + 11);
672 if (!branch || !branch->merge || !branch->merge[0] ||
673 !branch->merge[0]->dst)
674 continue;
675 refname = branch->merge[0]->dst;
676 } else if (!prefixcmp(name, "color:")) {
677 char color[COLOR_MAXLEN] = "";
679 color_parse(name + 6, "--format", color);
680 v->s = xstrdup(color);
681 continue;
682 } else if (!strcmp(name, "flag")) {
683 char buf[256], *cp = buf;
684 if (ref->flag & REF_ISSYMREF)
685 cp = copy_advance(cp, ",symref");
686 if (ref->flag & REF_ISPACKED)
687 cp = copy_advance(cp, ",packed");
688 if (cp == buf)
689 v->s = "";
690 else {
691 *cp = '\0';
692 v->s = xstrdup(buf + 1);
694 continue;
695 } else if (!strcmp(name, "HEAD")) {
696 const char *head;
697 unsigned char sha1[20];
699 head = resolve_ref_unsafe("HEAD", sha1, 1, NULL);
700 if (!strcmp(ref->refname, head))
701 v->s = "*";
702 else
703 v->s = " ";
704 continue;
705 } else
706 continue;
708 formatp = strchr(name, ':');
709 if (formatp) {
710 int num_ours, num_theirs;
712 formatp++;
713 if (!strcmp(formatp, "short"))
714 refname = shorten_unambiguous_ref(refname,
715 warn_ambiguous_refs);
716 else if (!strcmp(formatp, "track") &&
717 !prefixcmp(name, "upstream")) {
718 char buf[40];
720 stat_tracking_info(branch, &num_ours, &num_theirs);
721 if (!num_ours && !num_theirs)
722 v->s = "";
723 else if (!num_ours) {
724 sprintf(buf, "[behind %d]", num_theirs);
725 v->s = xstrdup(buf);
726 } else if (!num_theirs) {
727 sprintf(buf, "[ahead %d]", num_ours);
728 v->s = xstrdup(buf);
729 } else {
730 sprintf(buf, "[ahead %d, behind %d]",
731 num_ours, num_theirs);
732 v->s = xstrdup(buf);
734 continue;
735 } else if (!strcmp(formatp, "trackshort") &&
736 !prefixcmp(name, "upstream")) {
737 assert(branch);
738 stat_tracking_info(branch, &num_ours, &num_theirs);
739 if (!num_ours && !num_theirs)
740 v->s = "=";
741 else if (!num_ours)
742 v->s = "<";
743 else if (!num_theirs)
744 v->s = ">";
745 else
746 v->s = "<>";
747 continue;
748 } else
749 die("unknown %.*s format %s",
750 (int)(formatp - name), name, formatp);
753 if (!deref)
754 v->s = refname;
755 else {
756 int len = strlen(refname);
757 char *s = xmalloc(len + 4);
758 sprintf(s, "%s^{}", refname);
759 v->s = s;
763 for (i = 0; i < used_atom_cnt; i++) {
764 struct atom_value *v = &ref->value[i];
765 if (v->s == NULL)
766 goto need_obj;
768 return;
770 need_obj:
771 buf = get_obj(ref->objectname, &obj, &size, &eaten);
772 if (!buf)
773 die("missing object %s for %s",
774 sha1_to_hex(ref->objectname), ref->refname);
775 if (!obj)
776 die("parse_object_buffer failed on %s for %s",
777 sha1_to_hex(ref->objectname), ref->refname);
779 grab_values(ref->value, 0, obj, buf, size);
780 if (!eaten)
781 free(buf);
784 * If there is no atom that wants to know about tagged
785 * object, we are done.
787 if (!need_tagged || (obj->type != OBJ_TAG))
788 return;
791 * If it is a tag object, see if we use a value that derefs
792 * the object, and if we do grab the object it refers to.
794 tagged = ((struct tag *)obj)->tagged->sha1;
797 * NEEDSWORK: This derefs tag only once, which
798 * is good to deal with chains of trust, but
799 * is not consistent with what deref_tag() does
800 * which peels the onion to the core.
802 buf = get_obj(tagged, &obj, &size, &eaten);
803 if (!buf)
804 die("missing object %s for %s",
805 sha1_to_hex(tagged), ref->refname);
806 if (!obj)
807 die("parse_object_buffer failed on %s for %s",
808 sha1_to_hex(tagged), ref->refname);
809 grab_values(ref->value, 1, obj, buf, size);
810 if (!eaten)
811 free(buf);
815 * Given a ref, return the value for the atom. This lazily gets value
816 * out of the object by calling populate value.
818 static void get_value(struct refinfo *ref, int atom, struct atom_value **v)
820 if (!ref->value) {
821 populate_value(ref);
822 fill_missing_values(ref->value);
824 *v = &ref->value[atom];
827 struct grab_ref_cbdata {
828 struct refinfo **grab_array;
829 const char **grab_pattern;
830 int grab_cnt;
834 * A call-back given to for_each_ref(). Filter refs and keep them for
835 * later object processing.
837 static int grab_single_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
839 struct grab_ref_cbdata *cb = cb_data;
840 struct refinfo *ref;
841 int cnt;
843 if (*cb->grab_pattern) {
844 const char **pattern;
845 int namelen = strlen(refname);
846 for (pattern = cb->grab_pattern; *pattern; pattern++) {
847 const char *p = *pattern;
848 int plen = strlen(p);
850 if ((plen <= namelen) &&
851 !strncmp(refname, p, plen) &&
852 (refname[plen] == '\0' ||
853 refname[plen] == '/' ||
854 p[plen-1] == '/'))
855 break;
856 if (!fnmatch(p, refname, FNM_PATHNAME))
857 break;
859 if (!*pattern)
860 return 0;
864 * We do not open the object yet; sort may only need refname
865 * to do its job and the resulting list may yet to be pruned
866 * by maxcount logic.
868 ref = xcalloc(1, sizeof(*ref));
869 ref->refname = xstrdup(refname);
870 hashcpy(ref->objectname, sha1);
871 ref->flag = flag;
873 cnt = cb->grab_cnt;
874 cb->grab_array = xrealloc(cb->grab_array,
875 sizeof(*cb->grab_array) * (cnt + 1));
876 cb->grab_array[cnt++] = ref;
877 cb->grab_cnt = cnt;
878 return 0;
881 static int cmp_ref_sort(struct ref_sort *s, struct refinfo *a, struct refinfo *b)
883 struct atom_value *va, *vb;
884 int cmp;
885 cmp_type cmp_type = used_atom_type[s->atom];
887 get_value(a, s->atom, &va);
888 get_value(b, s->atom, &vb);
889 switch (cmp_type) {
890 case FIELD_STR:
891 cmp = strcmp(va->s, vb->s);
892 break;
893 default:
894 if (va->ul < vb->ul)
895 cmp = -1;
896 else if (va->ul == vb->ul)
897 cmp = 0;
898 else
899 cmp = 1;
900 break;
902 return (s->reverse) ? -cmp : cmp;
905 static struct ref_sort *ref_sort;
906 static int compare_refs(const void *a_, const void *b_)
908 struct refinfo *a = *((struct refinfo **)a_);
909 struct refinfo *b = *((struct refinfo **)b_);
910 struct ref_sort *s;
912 for (s = ref_sort; s; s = s->next) {
913 int cmp = cmp_ref_sort(s, a, b);
914 if (cmp)
915 return cmp;
917 return 0;
920 static void sort_refs(struct ref_sort *sort, struct refinfo **refs, int num_refs)
922 ref_sort = sort;
923 qsort(refs, num_refs, sizeof(struct refinfo *), compare_refs);
926 static void print_value(struct atom_value *v, int quote_style)
928 struct strbuf sb = STRBUF_INIT;
929 switch (quote_style) {
930 case QUOTE_NONE:
931 fputs(v->s, stdout);
932 break;
933 case QUOTE_SHELL:
934 sq_quote_buf(&sb, v->s);
935 break;
936 case QUOTE_PERL:
937 perl_quote_buf(&sb, v->s);
938 break;
939 case QUOTE_PYTHON:
940 python_quote_buf(&sb, v->s);
941 break;
942 case QUOTE_TCL:
943 tcl_quote_buf(&sb, v->s);
944 break;
946 if (quote_style != QUOTE_NONE) {
947 fputs(sb.buf, stdout);
948 strbuf_release(&sb);
952 static int hex1(char ch)
954 if ('0' <= ch && ch <= '9')
955 return ch - '0';
956 else if ('a' <= ch && ch <= 'f')
957 return ch - 'a' + 10;
958 else if ('A' <= ch && ch <= 'F')
959 return ch - 'A' + 10;
960 return -1;
962 static int hex2(const char *cp)
964 if (cp[0] && cp[1])
965 return (hex1(cp[0]) << 4) | hex1(cp[1]);
966 else
967 return -1;
970 static void emit(const char *cp, const char *ep)
972 while (*cp && (!ep || cp < ep)) {
973 if (*cp == '%') {
974 if (cp[1] == '%')
975 cp++;
976 else {
977 int ch = hex2(cp + 1);
978 if (0 <= ch) {
979 putchar(ch);
980 cp += 3;
981 continue;
985 putchar(*cp);
986 cp++;
990 static void show_ref(struct refinfo *info, const char *format, int quote_style)
992 const char *cp, *sp, *ep;
994 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
995 struct atom_value *atomv;
997 ep = strchr(sp, ')');
998 if (cp < sp)
999 emit(cp, sp);
1000 get_value(info, parse_atom(sp + 2, ep), &atomv);
1001 print_value(atomv, quote_style);
1003 if (*cp) {
1004 sp = cp + strlen(cp);
1005 emit(cp, sp);
1007 if (need_color_reset_at_eol) {
1008 struct atom_value resetv;
1009 char color[COLOR_MAXLEN] = "";
1011 color_parse("reset", "--format", color);
1012 resetv.s = color;
1013 print_value(&resetv, quote_style);
1015 putchar('\n');
1018 static struct ref_sort *default_sort(void)
1020 static const char cstr_name[] = "refname";
1022 struct ref_sort *sort = xcalloc(1, sizeof(*sort));
1024 sort->next = NULL;
1025 sort->atom = parse_atom(cstr_name, cstr_name + strlen(cstr_name));
1026 return sort;
1029 static int opt_parse_sort(const struct option *opt, const char *arg, int unset)
1031 struct ref_sort **sort_tail = opt->value;
1032 struct ref_sort *s;
1033 int len;
1035 if (!arg) /* should --no-sort void the list ? */
1036 return -1;
1038 s = xcalloc(1, sizeof(*s));
1039 s->next = *sort_tail;
1040 *sort_tail = s;
1042 if (*arg == '-') {
1043 s->reverse = 1;
1044 arg++;
1046 len = strlen(arg);
1047 s->atom = parse_atom(arg, arg+len);
1048 return 0;
1051 static char const * const for_each_ref_usage[] = {
1052 N_("git for-each-ref [options] [<pattern>]"),
1053 NULL
1056 int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
1058 int i, num_refs;
1059 const char *format = "%(objectname) %(objecttype)\t%(refname)";
1060 struct ref_sort *sort = NULL, **sort_tail = &sort;
1061 int maxcount = 0, quote_style = 0;
1062 struct refinfo **refs;
1063 struct grab_ref_cbdata cbdata;
1065 struct option opts[] = {
1066 OPT_BIT('s', "shell", &quote_style,
1067 N_("quote placeholders suitably for shells"), QUOTE_SHELL),
1068 OPT_BIT('p', "perl", &quote_style,
1069 N_("quote placeholders suitably for perl"), QUOTE_PERL),
1070 OPT_BIT(0 , "python", &quote_style,
1071 N_("quote placeholders suitably for python"), QUOTE_PYTHON),
1072 OPT_BIT(0 , "tcl", &quote_style,
1073 N_("quote placeholders suitably for tcl"), QUOTE_TCL),
1075 OPT_GROUP(""),
1076 OPT_INTEGER( 0 , "count", &maxcount, N_("show only <n> matched refs")),
1077 OPT_STRING( 0 , "format", &format, N_("format"), N_("format to use for the output")),
1078 OPT_CALLBACK(0 , "sort", sort_tail, N_("key"),
1079 N_("field name to sort on"), &opt_parse_sort),
1080 OPT_END(),
1083 parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
1084 if (maxcount < 0) {
1085 error("invalid --count argument: `%d'", maxcount);
1086 usage_with_options(for_each_ref_usage, opts);
1088 if (HAS_MULTI_BITS(quote_style)) {
1089 error("more than one quoting style?");
1090 usage_with_options(for_each_ref_usage, opts);
1092 if (verify_format(format))
1093 usage_with_options(for_each_ref_usage, opts);
1095 if (!sort)
1096 sort = default_sort();
1097 sort_atom_limit = used_atom_cnt;
1099 /* for warn_ambiguous_refs */
1100 git_config(git_default_config, NULL);
1102 memset(&cbdata, 0, sizeof(cbdata));
1103 cbdata.grab_pattern = argv;
1104 for_each_rawref(grab_single_ref, &cbdata);
1105 refs = cbdata.grab_array;
1106 num_refs = cbdata.grab_cnt;
1108 sort_refs(sort, refs, num_refs);
1110 if (!maxcount || num_refs < maxcount)
1111 maxcount = num_refs;
1112 for (i = 0; i < maxcount; i++)
1113 show_ref(refs[i], format, quote_style);
1114 return 0;