Code

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