]> rtime.felk.cvut.cz Git - git.git/blob - builtin/for-each-ref.c
Update draft release notes to 1.7.2
[git.git] / builtin / for-each-ref.c
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
13 /* Quoting styles */
14 #define QUOTE_NONE 0
15 #define QUOTE_SHELL 1
16 #define QUOTE_PERL 2
17 #define QUOTE_PYTHON 4
18 #define QUOTE_TCL 8
19
20 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
21
22 struct atom_value {
23         const char *s;
24         unsigned long ul; /* used for sorting when not FIELD_STR */
25 };
26
27 struct ref_sort {
28         struct ref_sort *next;
29         int atom; /* index into used_atom array */
30         unsigned reverse : 1;
31 };
32
33 struct refinfo {
34         char *refname;
35         unsigned char objectname[20];
36         int flag;
37         const char *symref;
38         struct atom_value *value;
39 };
40
41 static struct {
42         const char *name;
43         cmp_type cmp_type;
44 } valid_atom[] = {
45         { "refname" },
46         { "objecttype" },
47         { "objectsize", FIELD_ULONG },
48         { "objectname" },
49         { "tree" },
50         { "parent" },
51         { "numparent", FIELD_ULONG },
52         { "object" },
53         { "type" },
54         { "tag" },
55         { "author" },
56         { "authorname" },
57         { "authoremail" },
58         { "authordate", FIELD_TIME },
59         { "committer" },
60         { "committername" },
61         { "committeremail" },
62         { "committerdate", FIELD_TIME },
63         { "tagger" },
64         { "taggername" },
65         { "taggeremail" },
66         { "taggerdate", FIELD_TIME },
67         { "creator" },
68         { "creatordate", FIELD_TIME },
69         { "subject" },
70         { "body" },
71         { "contents" },
72         { "upstream" },
73         { "symref" },
74         { "flag" },
75 };
76
77 /*
78  * An atom is a valid field atom listed above, possibly prefixed with
79  * a "*" to denote deref_tag().
80  *
81  * We parse given format string and sort specifiers, and make a list
82  * of properties that we need to extract out of objects.  refinfo
83  * structure will hold an array of values extracted that can be
84  * indexed with the "atom number", which is an index into this
85  * array.
86  */
87 static const char **used_atom;
88 static cmp_type *used_atom_type;
89 static int used_atom_cnt, sort_atom_limit, need_tagged, need_symref;
90
91 /*
92  * Used to parse format string and sort specifiers
93  */
94 static int parse_atom(const char *atom, const char *ep)
95 {
96         const char *sp;
97         int i, at;
98
99         sp = atom;
100         if (*sp == '*' && sp < ep)
101                 sp++; /* deref */
102         if (ep <= sp)
103                 die("malformed field name: %.*s", (int)(ep-atom), atom);
104
105         /* Do we have the atom already used elsewhere? */
106         for (i = 0; i < used_atom_cnt; i++) {
107                 int len = strlen(used_atom[i]);
108                 if (len == ep - atom && !memcmp(used_atom[i], atom, len))
109                         return i;
110         }
111
112         /* Is the atom a valid one? */
113         for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
114                 int len = strlen(valid_atom[i].name);
115                 /*
116                  * If the atom name has a colon, strip it and everything after
117                  * it off - it specifies the format for this entry, and
118                  * shouldn't be used for checking against the valid_atom
119                  * table.
120                  */
121                 const char *formatp = strchr(sp, ':');
122                 if (!formatp || ep < formatp)
123                         formatp = ep;
124                 if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
125                         break;
126         }
127
128         if (ARRAY_SIZE(valid_atom) <= i)
129                 die("unknown field name: %.*s", (int)(ep-atom), atom);
130
131         /* Add it in, including the deref prefix */
132         at = used_atom_cnt;
133         used_atom_cnt++;
134         used_atom = xrealloc(used_atom,
135                              (sizeof *used_atom) * used_atom_cnt);
136         used_atom_type = xrealloc(used_atom_type,
137                                   (sizeof(*used_atom_type) * used_atom_cnt));
138         used_atom[at] = xmemdupz(atom, ep - atom);
139         used_atom_type[at] = valid_atom[i].cmp_type;
140         if (*atom == '*')
141                 need_tagged = 1;
142         if (!strcmp(used_atom[at], "symref"))
143                 need_symref = 1;
144         return at;
145 }
146
147 /*
148  * In a format string, find the next occurrence of %(atom).
149  */
150 static const char *find_next(const char *cp)
151 {
152         while (*cp) {
153                 if (*cp == '%') {
154                         /*
155                          * %( is the start of an atom;
156                          * %% is a quoted per-cent.
157                          */
158                         if (cp[1] == '(')
159                                 return cp;
160                         else if (cp[1] == '%')
161                                 cp++; /* skip over two % */
162                         /* otherwise this is a singleton, literal % */
163                 }
164                 cp++;
165         }
166         return NULL;
167 }
168
169 /*
170  * Make sure the format string is well formed, and parse out
171  * the used atoms.
172  */
173 static int verify_format(const char *format)
174 {
175         const char *cp, *sp;
176         for (cp = format; *cp && (sp = find_next(cp)); ) {
177                 const char *ep = strchr(sp, ')');
178                 if (!ep)
179                         return error("malformed format string %s", sp);
180                 /* sp points at "%(" and ep points at the closing ")" */
181                 parse_atom(sp + 2, ep);
182                 cp = ep + 1;
183         }
184         return 0;
185 }
186
187 /*
188  * Given an object name, read the object data and size, and return a
189  * "struct object".  If the object data we are returning is also borrowed
190  * by the "struct object" representation, set *eaten as well---it is a
191  * signal from parse_object_buffer to us not to free the buffer.
192  */
193 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
194 {
195         enum object_type type;
196         void *buf = read_sha1_file(sha1, &type, sz);
197
198         if (buf)
199                 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
200         else
201                 *obj = NULL;
202         return buf;
203 }
204
205 /* See grab_values */
206 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
207 {
208         int i;
209
210         for (i = 0; i < used_atom_cnt; i++) {
211                 const char *name = used_atom[i];
212                 struct atom_value *v = &val[i];
213                 if (!!deref != (*name == '*'))
214                         continue;
215                 if (deref)
216                         name++;
217                 if (!strcmp(name, "objecttype"))
218                         v->s = typename(obj->type);
219                 else if (!strcmp(name, "objectsize")) {
220                         char *s = xmalloc(40);
221                         sprintf(s, "%lu", sz);
222                         v->ul = sz;
223                         v->s = s;
224                 }
225                 else if (!strcmp(name, "objectname")) {
226                         char *s = xmalloc(41);
227                         strcpy(s, sha1_to_hex(obj->sha1));
228                         v->s = s;
229                 }
230                 else if (!strcmp(name, "objectname:short")) {
231                         v->s = find_unique_abbrev(obj->sha1, DEFAULT_ABBREV);
232                 }
233         }
234 }
235
236 /* See grab_values */
237 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
238 {
239         int i;
240         struct tag *tag = (struct tag *) obj;
241
242         for (i = 0; i < used_atom_cnt; i++) {
243                 const char *name = used_atom[i];
244                 struct atom_value *v = &val[i];
245                 if (!!deref != (*name == '*'))
246                         continue;
247                 if (deref)
248                         name++;
249                 if (!strcmp(name, "tag"))
250                         v->s = tag->tag;
251                 else if (!strcmp(name, "type") && tag->tagged)
252                         v->s = typename(tag->tagged->type);
253                 else if (!strcmp(name, "object") && tag->tagged) {
254                         char *s = xmalloc(41);
255                         strcpy(s, sha1_to_hex(tag->tagged->sha1));
256                         v->s = s;
257                 }
258         }
259 }
260
261 static int num_parents(struct commit *commit)
262 {
263         struct commit_list *parents;
264         int i;
265
266         for (i = 0, parents = commit->parents;
267              parents;
268              parents = parents->next)
269                 i++;
270         return i;
271 }
272
273 /* See grab_values */
274 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
275 {
276         int i;
277         struct commit *commit = (struct commit *) obj;
278
279         for (i = 0; i < used_atom_cnt; i++) {
280                 const char *name = used_atom[i];
281                 struct atom_value *v = &val[i];
282                 if (!!deref != (*name == '*'))
283                         continue;
284                 if (deref)
285                         name++;
286                 if (!strcmp(name, "tree")) {
287                         char *s = xmalloc(41);
288                         strcpy(s, sha1_to_hex(commit->tree->object.sha1));
289                         v->s = s;
290                 }
291                 if (!strcmp(name, "numparent")) {
292                         char *s = xmalloc(40);
293                         v->ul = num_parents(commit);
294                         sprintf(s, "%lu", v->ul);
295                         v->s = s;
296                 }
297                 else if (!strcmp(name, "parent")) {
298                         int num = num_parents(commit);
299                         int i;
300                         struct commit_list *parents;
301                         char *s = xmalloc(41 * num + 1);
302                         v->s = s;
303                         for (i = 0, parents = commit->parents;
304                              parents;
305                              parents = parents->next, i = i + 41) {
306                                 struct commit *parent = parents->item;
307                                 strcpy(s+i, sha1_to_hex(parent->object.sha1));
308                                 if (parents->next)
309                                         s[i+40] = ' ';
310                         }
311                         if (!i)
312                                 *s = '\0';
313                 }
314         }
315 }
316
317 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
318 {
319         const char *eol;
320         while (*buf) {
321                 if (!strncmp(buf, who, wholen) &&
322                     buf[wholen] == ' ')
323                         return buf + wholen + 1;
324                 eol = strchr(buf, '\n');
325                 if (!eol)
326                         return "";
327                 eol++;
328                 if (*eol == '\n')
329                         return ""; /* end of header */
330                 buf = eol;
331         }
332         return "";
333 }
334
335 static const char *copy_line(const char *buf)
336 {
337         const char *eol = strchrnul(buf, '\n');
338         return xmemdupz(buf, eol - buf);
339 }
340
341 static const char *copy_name(const char *buf)
342 {
343         const char *cp;
344         for (cp = buf; *cp && *cp != '\n'; cp++) {
345                 if (!strncmp(cp, " <", 2))
346                         return xmemdupz(buf, cp - buf);
347         }
348         return "";
349 }
350
351 static const char *copy_email(const char *buf)
352 {
353         const char *email = strchr(buf, '<');
354         const char *eoemail;
355         if (!email)
356                 return "";
357         eoemail = strchr(email, '>');
358         if (!eoemail)
359                 return "";
360         return xmemdupz(email, eoemail + 1 - email);
361 }
362
363 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
364 {
365         const char *eoemail = strstr(buf, "> ");
366         char *zone;
367         unsigned long timestamp;
368         long tz;
369         enum date_mode date_mode = DATE_NORMAL;
370         const char *formatp;
371
372         /*
373          * We got here because atomname ends in "date" or "date<something>";
374          * it's not possible that <something> is not ":<format>" because
375          * parse_atom() wouldn't have allowed it, so we can assume that no
376          * ":" means no format is specified, and use the default.
377          */
378         formatp = strchr(atomname, ':');
379         if (formatp != NULL) {
380                 formatp++;
381                 date_mode = parse_date_format(formatp);
382         }
383
384         if (!eoemail)
385                 goto bad;
386         timestamp = strtoul(eoemail + 2, &zone, 10);
387         if (timestamp == ULONG_MAX)
388                 goto bad;
389         tz = strtol(zone, NULL, 10);
390         if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
391                 goto bad;
392         v->s = xstrdup(show_date(timestamp, tz, date_mode));
393         v->ul = timestamp;
394         return;
395  bad:
396         v->s = "";
397         v->ul = 0;
398 }
399
400 /* See grab_values */
401 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
402 {
403         int i;
404         int wholen = strlen(who);
405         const char *wholine = NULL;
406
407         for (i = 0; i < used_atom_cnt; i++) {
408                 const char *name = used_atom[i];
409                 struct atom_value *v = &val[i];
410                 if (!!deref != (*name == '*'))
411                         continue;
412                 if (deref)
413                         name++;
414                 if (strncmp(who, name, wholen))
415                         continue;
416                 if (name[wholen] != 0 &&
417                     strcmp(name + wholen, "name") &&
418                     strcmp(name + wholen, "email") &&
419                     prefixcmp(name + wholen, "date"))
420                         continue;
421                 if (!wholine)
422                         wholine = find_wholine(who, wholen, buf, sz);
423                 if (!wholine)
424                         return; /* no point looking for it */
425                 if (name[wholen] == 0)
426                         v->s = copy_line(wholine);
427                 else if (!strcmp(name + wholen, "name"))
428                         v->s = copy_name(wholine);
429                 else if (!strcmp(name + wholen, "email"))
430                         v->s = copy_email(wholine);
431                 else if (!prefixcmp(name + wholen, "date"))
432                         grab_date(wholine, v, name);
433         }
434
435         /*
436          * For a tag or a commit object, if "creator" or "creatordate" is
437          * requested, do something special.
438          */
439         if (strcmp(who, "tagger") && strcmp(who, "committer"))
440                 return; /* "author" for commit object is not wanted */
441         if (!wholine)
442                 wholine = find_wholine(who, wholen, buf, sz);
443         if (!wholine)
444                 return;
445         for (i = 0; i < used_atom_cnt; i++) {
446                 const char *name = used_atom[i];
447                 struct atom_value *v = &val[i];
448                 if (!!deref != (*name == '*'))
449                         continue;
450                 if (deref)
451                         name++;
452
453                 if (!prefixcmp(name, "creatordate"))
454                         grab_date(wholine, v, name);
455                 else if (!strcmp(name, "creator"))
456                         v->s = copy_line(wholine);
457         }
458 }
459
460 static void find_subpos(const char *buf, unsigned long sz, const char **sub, const char **body)
461 {
462         while (*buf) {
463                 const char *eol = strchr(buf, '\n');
464                 if (!eol)
465                         return;
466                 if (eol[1] == '\n') {
467                         buf = eol + 1;
468                         break; /* found end of header */
469                 }
470                 buf = eol + 1;
471         }
472         while (*buf == '\n')
473                 buf++;
474         if (!*buf)
475                 return;
476         *sub = buf; /* first non-empty line */
477         buf = strchr(buf, '\n');
478         if (!buf) {
479                 *body = "";
480                 return; /* no body */
481         }
482         while (*buf == '\n')
483                 buf++; /* skip blank between subject and body */
484         *body = buf;
485 }
486
487 /* See grab_values */
488 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
489 {
490         int i;
491         const char *subpos = NULL, *bodypos = NULL;
492
493         for (i = 0; i < used_atom_cnt; i++) {
494                 const char *name = used_atom[i];
495                 struct atom_value *v = &val[i];
496                 if (!!deref != (*name == '*'))
497                         continue;
498                 if (deref)
499                         name++;
500                 if (strcmp(name, "subject") &&
501                     strcmp(name, "body") &&
502                     strcmp(name, "contents"))
503                         continue;
504                 if (!subpos)
505                         find_subpos(buf, sz, &subpos, &bodypos);
506                 if (!subpos)
507                         return;
508
509                 if (!strcmp(name, "subject"))
510                         v->s = copy_line(subpos);
511                 else if (!strcmp(name, "body"))
512                         v->s = xstrdup(bodypos);
513                 else if (!strcmp(name, "contents"))
514                         v->s = xstrdup(subpos);
515         }
516 }
517
518 /*
519  * We want to have empty print-string for field requests
520  * that do not apply (e.g. "authordate" for a tag object)
521  */
522 static void fill_missing_values(struct atom_value *val)
523 {
524         int i;
525         for (i = 0; i < used_atom_cnt; i++) {
526                 struct atom_value *v = &val[i];
527                 if (v->s == NULL)
528                         v->s = "";
529         }
530 }
531
532 /*
533  * val is a list of atom_value to hold returned values.  Extract
534  * the values for atoms in used_atom array out of (obj, buf, sz).
535  * when deref is false, (obj, buf, sz) is the object that is
536  * pointed at by the ref itself; otherwise it is the object the
537  * ref (which is a tag) refers to.
538  */
539 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
540 {
541         grab_common_values(val, deref, obj, buf, sz);
542         switch (obj->type) {
543         case OBJ_TAG:
544                 grab_tag_values(val, deref, obj, buf, sz);
545                 grab_sub_body_contents(val, deref, obj, buf, sz);
546                 grab_person("tagger", val, deref, obj, buf, sz);
547                 break;
548         case OBJ_COMMIT:
549                 grab_commit_values(val, deref, obj, buf, sz);
550                 grab_sub_body_contents(val, deref, obj, buf, sz);
551                 grab_person("author", val, deref, obj, buf, sz);
552                 grab_person("committer", val, deref, obj, buf, sz);
553                 break;
554         case OBJ_TREE:
555                 /* grab_tree_values(val, deref, obj, buf, sz); */
556                 break;
557         case OBJ_BLOB:
558                 /* grab_blob_values(val, deref, obj, buf, sz); */
559                 break;
560         default:
561                 die("Eh?  Object of type %d?", obj->type);
562         }
563 }
564
565 static inline char *copy_advance(char *dst, const char *src)
566 {
567         while (*src)
568                 *dst++ = *src++;
569         return dst;
570 }
571
572 /*
573  * Parse the object referred by ref, and grab needed value.
574  */
575 static void populate_value(struct refinfo *ref)
576 {
577         void *buf;
578         struct object *obj;
579         int eaten, i;
580         unsigned long size;
581         const unsigned char *tagged;
582
583         ref->value = xcalloc(sizeof(struct atom_value), used_atom_cnt);
584
585         if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
586                 unsigned char unused1[20];
587                 const char *symref;
588                 symref = resolve_ref(ref->refname, unused1, 1, NULL);
589                 if (symref)
590                         ref->symref = xstrdup(symref);
591                 else
592                         ref->symref = "";
593         }
594
595         /* Fill in specials first */
596         for (i = 0; i < used_atom_cnt; i++) {
597                 const char *name = used_atom[i];
598                 struct atom_value *v = &ref->value[i];
599                 int deref = 0;
600                 const char *refname;
601                 const char *formatp;
602
603                 if (*name == '*') {
604                         deref = 1;
605                         name++;
606                 }
607
608                 if (!prefixcmp(name, "refname"))
609                         refname = ref->refname;
610                 else if (!prefixcmp(name, "symref"))
611                         refname = ref->symref ? ref->symref : "";
612                 else if (!prefixcmp(name, "upstream")) {
613                         struct branch *branch;
614                         /* only local branches may have an upstream */
615                         if (prefixcmp(ref->refname, "refs/heads/"))
616                                 continue;
617                         branch = branch_get(ref->refname + 11);
618
619                         if (!branch || !branch->merge || !branch->merge[0] ||
620                             !branch->merge[0]->dst)
621                                 continue;
622                         refname = branch->merge[0]->dst;
623                 }
624                 else if (!strcmp(name, "flag")) {
625                         char buf[256], *cp = buf;
626                         if (ref->flag & REF_ISSYMREF)
627                                 cp = copy_advance(cp, ",symref");
628                         if (ref->flag & REF_ISPACKED)
629                                 cp = copy_advance(cp, ",packed");
630                         if (cp == buf)
631                                 v->s = "";
632                         else {
633                                 *cp = '\0';
634                                 v->s = xstrdup(buf + 1);
635                         }
636                         continue;
637                 }
638                 else
639                         continue;
640
641                 formatp = strchr(name, ':');
642                 /* look for "short" refname format */
643                 if (formatp) {
644                         formatp++;
645                         if (!strcmp(formatp, "short"))
646                                 refname = shorten_unambiguous_ref(refname,
647                                                       warn_ambiguous_refs);
648                         else
649                                 die("unknown %.*s format %s",
650                                     (int)(formatp - name), name, formatp);
651                 }
652
653                 if (!deref)
654                         v->s = refname;
655                 else {
656                         int len = strlen(refname);
657                         char *s = xmalloc(len + 4);
658                         sprintf(s, "%s^{}", refname);
659                         v->s = s;
660                 }
661         }
662
663         for (i = 0; i < used_atom_cnt; i++) {
664                 struct atom_value *v = &ref->value[i];
665                 if (v->s == NULL)
666                         goto need_obj;
667         }
668         return;
669
670  need_obj:
671         buf = get_obj(ref->objectname, &obj, &size, &eaten);
672         if (!buf)
673                 die("missing object %s for %s",
674                     sha1_to_hex(ref->objectname), ref->refname);
675         if (!obj)
676                 die("parse_object_buffer failed on %s for %s",
677                     sha1_to_hex(ref->objectname), ref->refname);
678
679         grab_values(ref->value, 0, obj, buf, size);
680         if (!eaten)
681                 free(buf);
682
683         /*
684          * If there is no atom that wants to know about tagged
685          * object, we are done.
686          */
687         if (!need_tagged || (obj->type != OBJ_TAG))
688                 return;
689
690         /*
691          * If it is a tag object, see if we use a value that derefs
692          * the object, and if we do grab the object it refers to.
693          */
694         tagged = ((struct tag *)obj)->tagged->sha1;
695
696         /*
697          * NEEDSWORK: This derefs tag only once, which
698          * is good to deal with chains of trust, but
699          * is not consistent with what deref_tag() does
700          * which peels the onion to the core.
701          */
702         buf = get_obj(tagged, &obj, &size, &eaten);
703         if (!buf)
704                 die("missing object %s for %s",
705                     sha1_to_hex(tagged), ref->refname);
706         if (!obj)
707                 die("parse_object_buffer failed on %s for %s",
708                     sha1_to_hex(tagged), ref->refname);
709         grab_values(ref->value, 1, obj, buf, size);
710         if (!eaten)
711                 free(buf);
712 }
713
714 /*
715  * Given a ref, return the value for the atom.  This lazily gets value
716  * out of the object by calling populate value.
717  */
718 static void get_value(struct refinfo *ref, int atom, struct atom_value **v)
719 {
720         if (!ref->value) {
721                 populate_value(ref);
722                 fill_missing_values(ref->value);
723         }
724         *v = &ref->value[atom];
725 }
726
727 struct grab_ref_cbdata {
728         struct refinfo **grab_array;
729         const char **grab_pattern;
730         int grab_cnt;
731 };
732
733 /*
734  * A call-back given to for_each_ref().  Filter refs and keep them for
735  * later object processing.
736  */
737 static int grab_single_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
738 {
739         struct grab_ref_cbdata *cb = cb_data;
740         struct refinfo *ref;
741         int cnt;
742
743         if (*cb->grab_pattern) {
744                 const char **pattern;
745                 int namelen = strlen(refname);
746                 for (pattern = cb->grab_pattern; *pattern; pattern++) {
747                         const char *p = *pattern;
748                         int plen = strlen(p);
749
750                         if ((plen <= namelen) &&
751                             !strncmp(refname, p, plen) &&
752                             (refname[plen] == '\0' ||
753                              refname[plen] == '/' ||
754                              p[plen-1] == '/'))
755                                 break;
756                         if (!fnmatch(p, refname, FNM_PATHNAME))
757                                 break;
758                 }
759                 if (!*pattern)
760                         return 0;
761         }
762
763         /*
764          * We do not open the object yet; sort may only need refname
765          * to do its job and the resulting list may yet to be pruned
766          * by maxcount logic.
767          */
768         ref = xcalloc(1, sizeof(*ref));
769         ref->refname = xstrdup(refname);
770         hashcpy(ref->objectname, sha1);
771         ref->flag = flag;
772
773         cnt = cb->grab_cnt;
774         cb->grab_array = xrealloc(cb->grab_array,
775                                   sizeof(*cb->grab_array) * (cnt + 1));
776         cb->grab_array[cnt++] = ref;
777         cb->grab_cnt = cnt;
778         return 0;
779 }
780
781 static int cmp_ref_sort(struct ref_sort *s, struct refinfo *a, struct refinfo *b)
782 {
783         struct atom_value *va, *vb;
784         int cmp;
785         cmp_type cmp_type = used_atom_type[s->atom];
786
787         get_value(a, s->atom, &va);
788         get_value(b, s->atom, &vb);
789         switch (cmp_type) {
790         case FIELD_STR:
791                 cmp = strcmp(va->s, vb->s);
792                 break;
793         default:
794                 if (va->ul < vb->ul)
795                         cmp = -1;
796                 else if (va->ul == vb->ul)
797                         cmp = 0;
798                 else
799                         cmp = 1;
800                 break;
801         }
802         return (s->reverse) ? -cmp : cmp;
803 }
804
805 static struct ref_sort *ref_sort;
806 static int compare_refs(const void *a_, const void *b_)
807 {
808         struct refinfo *a = *((struct refinfo **)a_);
809         struct refinfo *b = *((struct refinfo **)b_);
810         struct ref_sort *s;
811
812         for (s = ref_sort; s; s = s->next) {
813                 int cmp = cmp_ref_sort(s, a, b);
814                 if (cmp)
815                         return cmp;
816         }
817         return 0;
818 }
819
820 static void sort_refs(struct ref_sort *sort, struct refinfo **refs, int num_refs)
821 {
822         ref_sort = sort;
823         qsort(refs, num_refs, sizeof(struct refinfo *), compare_refs);
824 }
825
826 static void print_value(struct refinfo *ref, int atom, int quote_style)
827 {
828         struct atom_value *v;
829         get_value(ref, atom, &v);
830         switch (quote_style) {
831         case QUOTE_NONE:
832                 fputs(v->s, stdout);
833                 break;
834         case QUOTE_SHELL:
835                 sq_quote_print(stdout, v->s);
836                 break;
837         case QUOTE_PERL:
838                 perl_quote_print(stdout, v->s);
839                 break;
840         case QUOTE_PYTHON:
841                 python_quote_print(stdout, v->s);
842                 break;
843         case QUOTE_TCL:
844                 tcl_quote_print(stdout, v->s);
845                 break;
846         }
847 }
848
849 static int hex1(char ch)
850 {
851         if ('0' <= ch && ch <= '9')
852                 return ch - '0';
853         else if ('a' <= ch && ch <= 'f')
854                 return ch - 'a' + 10;
855         else if ('A' <= ch && ch <= 'F')
856                 return ch - 'A' + 10;
857         return -1;
858 }
859 static int hex2(const char *cp)
860 {
861         if (cp[0] && cp[1])
862                 return (hex1(cp[0]) << 4) | hex1(cp[1]);
863         else
864                 return -1;
865 }
866
867 static void emit(const char *cp, const char *ep)
868 {
869         while (*cp && (!ep || cp < ep)) {
870                 if (*cp == '%') {
871                         if (cp[1] == '%')
872                                 cp++;
873                         else {
874                                 int ch = hex2(cp + 1);
875                                 if (0 <= ch) {
876                                         putchar(ch);
877                                         cp += 3;
878                                         continue;
879                                 }
880                         }
881                 }
882                 putchar(*cp);
883                 cp++;
884         }
885 }
886
887 static void show_ref(struct refinfo *info, const char *format, int quote_style)
888 {
889         const char *cp, *sp, *ep;
890
891         for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
892                 ep = strchr(sp, ')');
893                 if (cp < sp)
894                         emit(cp, sp);
895                 print_value(info, parse_atom(sp + 2, ep), quote_style);
896         }
897         if (*cp) {
898                 sp = cp + strlen(cp);
899                 emit(cp, sp);
900         }
901         putchar('\n');
902 }
903
904 static struct ref_sort *default_sort(void)
905 {
906         static const char cstr_name[] = "refname";
907
908         struct ref_sort *sort = xcalloc(1, sizeof(*sort));
909
910         sort->next = NULL;
911         sort->atom = parse_atom(cstr_name, cstr_name + strlen(cstr_name));
912         return sort;
913 }
914
915 static int opt_parse_sort(const struct option *opt, const char *arg, int unset)
916 {
917         struct ref_sort **sort_tail = opt->value;
918         struct ref_sort *s;
919         int len;
920
921         if (!arg) /* should --no-sort void the list ? */
922                 return -1;
923
924         *sort_tail = s = xcalloc(1, sizeof(*s));
925
926         if (*arg == '-') {
927                 s->reverse = 1;
928                 arg++;
929         }
930         len = strlen(arg);
931         s->atom = parse_atom(arg, arg+len);
932         return 0;
933 }
934
935 static char const * const for_each_ref_usage[] = {
936         "git for-each-ref [options] [<pattern>]",
937         NULL
938 };
939
940 int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
941 {
942         int i, num_refs;
943         const char *format = "%(objectname) %(objecttype)\t%(refname)";
944         struct ref_sort *sort = NULL, **sort_tail = &sort;
945         int maxcount = 0, quote_style = 0;
946         struct refinfo **refs;
947         struct grab_ref_cbdata cbdata;
948
949         struct option opts[] = {
950                 OPT_BIT('s', "shell", &quote_style,
951                         "quote placeholders suitably for shells", QUOTE_SHELL),
952                 OPT_BIT('p', "perl",  &quote_style,
953                         "quote placeholders suitably for perl", QUOTE_PERL),
954                 OPT_BIT(0 , "python", &quote_style,
955                         "quote placeholders suitably for python", QUOTE_PYTHON),
956                 OPT_BIT(0 , "tcl",  &quote_style,
957                         "quote placeholders suitably for tcl", QUOTE_TCL),
958
959                 OPT_GROUP(""),
960                 OPT_INTEGER( 0 , "count", &maxcount, "show only <n> matched refs"),
961                 OPT_STRING(  0 , "format", &format, "format", "format to use for the output"),
962                 OPT_CALLBACK(0 , "sort", sort_tail, "key",
963                             "field name to sort on", &opt_parse_sort),
964                 OPT_END(),
965         };
966
967         parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
968         if (maxcount < 0) {
969                 error("invalid --count argument: `%d'", maxcount);
970                 usage_with_options(for_each_ref_usage, opts);
971         }
972         if (HAS_MULTI_BITS(quote_style)) {
973                 error("more than one quoting style?");
974                 usage_with_options(for_each_ref_usage, opts);
975         }
976         if (verify_format(format))
977                 usage_with_options(for_each_ref_usage, opts);
978
979         if (!sort)
980                 sort = default_sort();
981         sort_atom_limit = used_atom_cnt;
982
983         /* for warn_ambiguous_refs */
984         git_config(git_default_config, NULL);
985
986         memset(&cbdata, 0, sizeof(cbdata));
987         cbdata.grab_pattern = argv;
988         for_each_rawref(grab_single_ref, &cbdata);
989         refs = cbdata.grab_array;
990         num_refs = cbdata.grab_cnt;
991
992         sort_refs(sort, refs, num_refs);
993
994         if (!maxcount || num_refs < maxcount)
995                 maxcount = num_refs;
996         for (i = 0; i < maxcount; i++)
997                 show_ref(refs[i], format, quote_style);
998         return 0;
999 }