builtin-for-each-ref.con commit core-tutorial.txt: Fix showing the current behaviour. (abea85d)
   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
  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
  18
  19typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
  20
  21struct atom_value {
  22        const char *s;
  23        unsigned long ul; /* used for sorting when not FIELD_STR */
  24};
  25
  26struct ref_sort {
  27        struct ref_sort *next;
  28        int atom; /* index into used_atom array */
  29        unsigned reverse : 1;
  30};
  31
  32struct refinfo {
  33        char *refname;
  34        unsigned char objectname[20];
  35        struct atom_value *value;
  36};
  37
  38static 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};
  70
  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 */
  81static const char **used_atom;
  82static cmp_type *used_atom_type;
  83static int used_atom_cnt, sort_atom_limit, need_tagged;
  84
  85/*
  86 * Used to parse format string and sort specifiers
  87 */
  88static int parse_atom(const char *atom, const char *ep)
  89{
  90        const char *sp;
  91        int i, at;
  92
  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);
  98
  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        }
 105
 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        }
 121
 122        if (ARRAY_SIZE(valid_atom) <= i)
 123                die("unknown field name: %.*s", (int)(ep-atom), atom);
 124
 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;
 135}
 136
 137/*
 138 * In a format string, find the next occurrence of %(atom).
 139 */
 140static const char *find_next(const char *cp)
 141{
 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;
 156}
 157
 158/*
 159 * Make sure the format string is well formed, and parse out
 160 * the used atoms.
 161 */
 162static int verify_format(const char *format)
 163{
 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("malformatted 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;
 174}
 175
 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 */
 182static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
 183{
 184        enum object_type type;
 185        void *buf = read_sha1_file(sha1, &type, sz);
 186
 187        if (buf)
 188                *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
 189        else
 190                *obj = NULL;
 191        return buf;
 192}
 193
 194/* See grab_values */
 195static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 196{
 197        int i;
 198
 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        }
 220}
 221
 222/* See grab_values */
 223static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 224{
 225        int i;
 226        struct tag *tag = (struct tag *) obj;
 227
 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        }
 238}
 239
 240static int num_parents(struct commit *commit)
 241{
 242        struct commit_list *parents;
 243        int i;
 244
 245        for (i = 0, parents = commit->parents;
 246             parents;
 247             parents = parents->next)
 248                i++;
 249        return i;
 250}
 251
 252/* See grab_values */
 253static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 254{
 255        int i;
 256        struct commit *commit = (struct commit *) obj;
 257
 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, "tree")) {
 266                        char *s = xmalloc(41);
 267                        strcpy(s, sha1_to_hex(commit->tree->object.sha1));
 268                        v->s = s;
 269                }
 270                if (!strcmp(name, "numparent")) {
 271                        char *s = xmalloc(40);
 272                        v->ul = num_parents(commit);
 273                        sprintf(s, "%lu", v->ul);
 274                        v->s = s;
 275                }
 276                else if (!strcmp(name, "parent")) {
 277                        int num = num_parents(commit);
 278                        int i;
 279                        struct commit_list *parents;
 280                        char *s = xmalloc(41 * num + 1);
 281                        v->s = s;
 282                        for (i = 0, parents = commit->parents;
 283                             parents;
 284                             parents = parents->next, i = i + 41) {
 285                                struct commit *parent = parents->item;
 286                                strcpy(s+i, sha1_to_hex(parent->object.sha1));
 287                                if (parents->next)
 288                                        s[i+40] = ' ';
 289                        }
 290                        if (!i)
 291                                *s = '\0';
 292                }
 293        }
 294}
 295
 296static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
 297{
 298        const char *eol;
 299        while (*buf) {
 300                if (!strncmp(buf, who, wholen) &&
 301                    buf[wholen] == ' ')
 302                        return buf + wholen + 1;
 303                eol = strchr(buf, '\n');
 304                if (!eol)
 305                        return "";
 306                eol++;
 307                if (*eol == '\n')
 308                        return ""; /* end of header */
 309                buf = eol;
 310        }
 311        return "";
 312}
 313
 314static const char *copy_line(const char *buf)
 315{
 316        const char *eol = strchr(buf, '\n');
 317        if (!eol)
 318                return "";
 319        return xmemdupz(buf, eol - buf);
 320}
 321
 322static const char *copy_name(const char *buf)
 323{
 324        const char *cp;
 325        for (cp = buf; *cp && *cp != '\n'; cp++) {
 326                if (!strncmp(cp, " <", 2))
 327                        return xmemdupz(buf, cp - buf);
 328        }
 329        return "";
 330}
 331
 332static const char *copy_email(const char *buf)
 333{
 334        const char *email = strchr(buf, '<');
 335        const char *eoemail = strchr(email, '>');
 336        if (!email || !eoemail)
 337                return "";
 338        return xmemdupz(email, eoemail + 1 - email);
 339}
 340
 341static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
 342{
 343        const char *eoemail = strstr(buf, "> ");
 344        char *zone;
 345        unsigned long timestamp;
 346        long tz;
 347        enum date_mode date_mode = DATE_NORMAL;
 348        const char *formatp;
 349
 350        /*
 351         * We got here because atomname ends in "date" or "date<something>";
 352         * it's not possible that <something> is not ":<format>" because
 353         * parse_atom() wouldn't have allowed it, so we can assume that no
 354         * ":" means no format is specified, and use the default.
 355         */
 356        formatp = strchr(atomname, ':');
 357        if (formatp != NULL) {
 358                formatp++;
 359                date_mode = parse_date_format(formatp);
 360        }
 361
 362        if (!eoemail)
 363                goto bad;
 364        timestamp = strtoul(eoemail + 2, &zone, 10);
 365        if (timestamp == ULONG_MAX)
 366                goto bad;
 367        tz = strtol(zone, NULL, 10);
 368        if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
 369                goto bad;
 370        v->s = xstrdup(show_date(timestamp, tz, date_mode));
 371        v->ul = timestamp;
 372        return;
 373 bad:
 374        v->s = "";
 375        v->ul = 0;
 376}
 377
 378/* See grab_values */
 379static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 380{
 381        int i;
 382        int wholen = strlen(who);
 383        const char *wholine = NULL;
 384
 385        for (i = 0; i < used_atom_cnt; i++) {
 386                const char *name = used_atom[i];
 387                struct atom_value *v = &val[i];
 388                if (!!deref != (*name == '*'))
 389                        continue;
 390                if (deref)
 391                        name++;
 392                if (strncmp(who, name, wholen))
 393                        continue;
 394                if (name[wholen] != 0 &&
 395                    strcmp(name + wholen, "name") &&
 396                    strcmp(name + wholen, "email") &&
 397                    prefixcmp(name + wholen, "date"))
 398                        continue;
 399                if (!wholine)
 400                        wholine = find_wholine(who, wholen, buf, sz);
 401                if (!wholine)
 402                        return; /* no point looking for it */
 403                if (name[wholen] == 0)
 404                        v->s = copy_line(wholine);
 405                else if (!strcmp(name + wholen, "name"))
 406                        v->s = copy_name(wholine);
 407                else if (!strcmp(name + wholen, "email"))
 408                        v->s = copy_email(wholine);
 409                else if (!prefixcmp(name + wholen, "date"))
 410                        grab_date(wholine, v, name);
 411        }
 412
 413        /* For a tag or a commit object, if "creator" or "creatordate" is
 414         * requested, do something special.
 415         */
 416        if (strcmp(who, "tagger") && strcmp(who, "committer"))
 417                return; /* "author" for commit object is not wanted */
 418        if (!wholine)
 419                wholine = find_wholine(who, wholen, buf, sz);
 420        if (!wholine)
 421                return;
 422        for (i = 0; i < used_atom_cnt; i++) {
 423                const char *name = used_atom[i];
 424                struct atom_value *v = &val[i];
 425                if (!!deref != (*name == '*'))
 426                        continue;
 427                if (deref)
 428                        name++;
 429
 430                if (!prefixcmp(name, "creatordate"))
 431                        grab_date(wholine, v, name);
 432                else if (!strcmp(name, "creator"))
 433                        v->s = copy_line(wholine);
 434        }
 435}
 436
 437static void find_subpos(const char *buf, unsigned long sz, const char **sub, const char **body)
 438{
 439        while (*buf) {
 440                const char *eol = strchr(buf, '\n');
 441                if (!eol)
 442                        return;
 443                if (eol[1] == '\n') {
 444                        buf = eol + 1;
 445                        break; /* found end of header */
 446                }
 447                buf = eol + 1;
 448        }
 449        while (*buf == '\n')
 450                buf++;
 451        if (!*buf)
 452                return;
 453        *sub = buf; /* first non-empty line */
 454        buf = strchr(buf, '\n');
 455        if (!buf)
 456                return; /* no body */
 457        while (*buf == '\n')
 458                buf++; /* skip blank between subject and body */
 459        *body = buf;
 460}
 461
 462/* See grab_values */
 463static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 464{
 465        int i;
 466        const char *subpos = NULL, *bodypos = NULL;
 467
 468        for (i = 0; i < used_atom_cnt; i++) {
 469                const char *name = used_atom[i];
 470                struct atom_value *v = &val[i];
 471                if (!!deref != (*name == '*'))
 472                        continue;
 473                if (deref)
 474                        name++;
 475                if (strcmp(name, "subject") &&
 476                    strcmp(name, "body") &&
 477                    strcmp(name, "contents"))
 478                        continue;
 479                if (!subpos)
 480                        find_subpos(buf, sz, &subpos, &bodypos);
 481                if (!subpos)
 482                        return;
 483
 484                if (!strcmp(name, "subject"))
 485                        v->s = copy_line(subpos);
 486                else if (!strcmp(name, "body"))
 487                        v->s = xstrdup(bodypos);
 488                else if (!strcmp(name, "contents"))
 489                        v->s = xstrdup(subpos);
 490        }
 491}
 492
 493/* We want to have empty print-string for field requests
 494 * that do not apply (e.g. "authordate" for a tag object)
 495 */
 496static void fill_missing_values(struct atom_value *val)
 497{
 498        int i;
 499        for (i = 0; i < used_atom_cnt; i++) {
 500                struct atom_value *v = &val[i];
 501                if (v->s == NULL)
 502                        v->s = "";
 503        }
 504}
 505
 506/*
 507 * val is a list of atom_value to hold returned values.  Extract
 508 * the values for atoms in used_atom array out of (obj, buf, sz).
 509 * when deref is false, (obj, buf, sz) is the object that is
 510 * pointed at by the ref itself; otherwise it is the object the
 511 * ref (which is a tag) refers to.
 512 */
 513static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 514{
 515        grab_common_values(val, deref, obj, buf, sz);
 516        switch (obj->type) {
 517        case OBJ_TAG:
 518                grab_tag_values(val, deref, obj, buf, sz);
 519                grab_sub_body_contents(val, deref, obj, buf, sz);
 520                grab_person("tagger", val, deref, obj, buf, sz);
 521                break;
 522        case OBJ_COMMIT:
 523                grab_commit_values(val, deref, obj, buf, sz);
 524                grab_sub_body_contents(val, deref, obj, buf, sz);
 525                grab_person("author", val, deref, obj, buf, sz);
 526                grab_person("committer", val, deref, obj, buf, sz);
 527                break;
 528        case OBJ_TREE:
 529                // grab_tree_values(val, deref, obj, buf, sz);
 530                break;
 531        case OBJ_BLOB:
 532                // grab_blob_values(val, deref, obj, buf, sz);
 533                break;
 534        default:
 535                die("Eh?  Object of type %d?", obj->type);
 536        }
 537}
 538
 539/*
 540 * Parse the object referred by ref, and grab needed value.
 541 */
 542static void populate_value(struct refinfo *ref)
 543{
 544        void *buf;
 545        struct object *obj;
 546        int eaten, i;
 547        unsigned long size;
 548        const unsigned char *tagged;
 549
 550        ref->value = xcalloc(sizeof(struct atom_value), used_atom_cnt);
 551
 552        buf = get_obj(ref->objectname, &obj, &size, &eaten);
 553        if (!buf)
 554                die("missing object %s for %s",
 555                    sha1_to_hex(ref->objectname), ref->refname);
 556        if (!obj)
 557                die("parse_object_buffer failed on %s for %s",
 558                    sha1_to_hex(ref->objectname), ref->refname);
 559
 560        /* Fill in specials first */
 561        for (i = 0; i < used_atom_cnt; i++) {
 562                const char *name = used_atom[i];
 563                struct atom_value *v = &ref->value[i];
 564                if (!strcmp(name, "refname"))
 565                        v->s = ref->refname;
 566                else if (!strcmp(name, "*refname")) {
 567                        int len = strlen(ref->refname);
 568                        char *s = xmalloc(len + 4);
 569                        sprintf(s, "%s^{}", ref->refname);
 570                        v->s = s;
 571                }
 572        }
 573
 574        grab_values(ref->value, 0, obj, buf, size);
 575        if (!eaten)
 576                free(buf);
 577
 578        /* If there is no atom that wants to know about tagged
 579         * object, we are done.
 580         */
 581        if (!need_tagged || (obj->type != OBJ_TAG))
 582                return;
 583
 584        /* If it is a tag object, see if we use a value that derefs
 585         * the object, and if we do grab the object it refers to.
 586         */
 587        tagged = ((struct tag *)obj)->tagged->sha1;
 588
 589        /* NEEDSWORK: This derefs tag only once, which
 590         * is good to deal with chains of trust, but
 591         * is not consistent with what deref_tag() does
 592         * which peels the onion to the core.
 593         */
 594        buf = get_obj(tagged, &obj, &size, &eaten);
 595        if (!buf)
 596                die("missing object %s for %s",
 597                    sha1_to_hex(tagged), ref->refname);
 598        if (!obj)
 599                die("parse_object_buffer failed on %s for %s",
 600                    sha1_to_hex(tagged), ref->refname);
 601        grab_values(ref->value, 1, obj, buf, size);
 602        if (!eaten)
 603                free(buf);
 604}
 605
 606/*
 607 * Given a ref, return the value for the atom.  This lazily gets value
 608 * out of the object by calling populate value.
 609 */
 610static void get_value(struct refinfo *ref, int atom, struct atom_value **v)
 611{
 612        if (!ref->value) {
 613                populate_value(ref);
 614                fill_missing_values(ref->value);
 615        }
 616        *v = &ref->value[atom];
 617}
 618
 619struct grab_ref_cbdata {
 620        struct refinfo **grab_array;
 621        const char **grab_pattern;
 622        int grab_cnt;
 623};
 624
 625/*
 626 * A call-back given to for_each_ref().  It is unfortunate that we
 627 * need to use global variables to pass extra information to this
 628 * function.
 629 */
 630static int grab_single_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
 631{
 632        struct grab_ref_cbdata *cb = cb_data;
 633        struct refinfo *ref;
 634        int cnt;
 635
 636        if (*cb->grab_pattern) {
 637                const char **pattern;
 638                int namelen = strlen(refname);
 639                for (pattern = cb->grab_pattern; *pattern; pattern++) {
 640                        const char *p = *pattern;
 641                        int plen = strlen(p);
 642
 643                        if ((plen <= namelen) &&
 644                            !strncmp(refname, p, plen) &&
 645                            (refname[plen] == '\0' ||
 646                             refname[plen] == '/'))
 647                                break;
 648                        if (!fnmatch(p, refname, FNM_PATHNAME))
 649                                break;
 650                }
 651                if (!*pattern)
 652                        return 0;
 653        }
 654
 655        /* We do not open the object yet; sort may only need refname
 656         * to do its job and the resulting list may yet to be pruned
 657         * by maxcount logic.
 658         */
 659        ref = xcalloc(1, sizeof(*ref));
 660        ref->refname = xstrdup(refname);
 661        hashcpy(ref->objectname, sha1);
 662
 663        cnt = cb->grab_cnt;
 664        cb->grab_array = xrealloc(cb->grab_array,
 665                                  sizeof(*cb->grab_array) * (cnt + 1));
 666        cb->grab_array[cnt++] = ref;
 667        cb->grab_cnt = cnt;
 668        return 0;
 669}
 670
 671static int cmp_ref_sort(struct ref_sort *s, struct refinfo *a, struct refinfo *b)
 672{
 673        struct atom_value *va, *vb;
 674        int cmp;
 675        cmp_type cmp_type = used_atom_type[s->atom];
 676
 677        get_value(a, s->atom, &va);
 678        get_value(b, s->atom, &vb);
 679        switch (cmp_type) {
 680        case FIELD_STR:
 681                cmp = strcmp(va->s, vb->s);
 682                break;
 683        default:
 684                if (va->ul < vb->ul)
 685                        cmp = -1;
 686                else if (va->ul == vb->ul)
 687                        cmp = 0;
 688                else
 689                        cmp = 1;
 690                break;
 691        }
 692        return (s->reverse) ? -cmp : cmp;
 693}
 694
 695static struct ref_sort *ref_sort;
 696static int compare_refs(const void *a_, const void *b_)
 697{
 698        struct refinfo *a = *((struct refinfo **)a_);
 699        struct refinfo *b = *((struct refinfo **)b_);
 700        struct ref_sort *s;
 701
 702        for (s = ref_sort; s; s = s->next) {
 703                int cmp = cmp_ref_sort(s, a, b);
 704                if (cmp)
 705                        return cmp;
 706        }
 707        return 0;
 708}
 709
 710static void sort_refs(struct ref_sort *sort, struct refinfo **refs, int num_refs)
 711{
 712        ref_sort = sort;
 713        qsort(refs, num_refs, sizeof(struct refinfo *), compare_refs);
 714}
 715
 716static void print_value(struct refinfo *ref, int atom, int quote_style)
 717{
 718        struct atom_value *v;
 719        get_value(ref, atom, &v);
 720        switch (quote_style) {
 721        case QUOTE_NONE:
 722                fputs(v->s, stdout);
 723                break;
 724        case QUOTE_SHELL:
 725                sq_quote_print(stdout, v->s);
 726                break;
 727        case QUOTE_PERL:
 728                perl_quote_print(stdout, v->s);
 729                break;
 730        case QUOTE_PYTHON:
 731                python_quote_print(stdout, v->s);
 732                break;
 733        case QUOTE_TCL:
 734                tcl_quote_print(stdout, v->s);
 735                break;
 736        }
 737}
 738
 739static int hex1(char ch)
 740{
 741        if ('0' <= ch && ch <= '9')
 742                return ch - '0';
 743        else if ('a' <= ch && ch <= 'f')
 744                return ch - 'a' + 10;
 745        else if ('A' <= ch && ch <= 'F')
 746                return ch - 'A' + 10;
 747        return -1;
 748}
 749static int hex2(const char *cp)
 750{
 751        if (cp[0] && cp[1])
 752                return (hex1(cp[0]) << 4) | hex1(cp[1]);
 753        else
 754                return -1;
 755}
 756
 757static void emit(const char *cp, const char *ep)
 758{
 759        while (*cp && (!ep || cp < ep)) {
 760                if (*cp == '%') {
 761                        if (cp[1] == '%')
 762                                cp++;
 763                        else {
 764                                int ch = hex2(cp + 1);
 765                                if (0 <= ch) {
 766                                        putchar(ch);
 767                                        cp += 3;
 768                                        continue;
 769                                }
 770                        }
 771                }
 772                putchar(*cp);
 773                cp++;
 774        }
 775}
 776
 777static void show_ref(struct refinfo *info, const char *format, int quote_style)
 778{
 779        const char *cp, *sp, *ep;
 780
 781        for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
 782                ep = strchr(sp, ')');
 783                if (cp < sp)
 784                        emit(cp, sp);
 785                print_value(info, parse_atom(sp + 2, ep), quote_style);
 786        }
 787        if (*cp) {
 788                sp = cp + strlen(cp);
 789                emit(cp, sp);
 790        }
 791        putchar('\n');
 792}
 793
 794static struct ref_sort *default_sort(void)
 795{
 796        static const char cstr_name[] = "refname";
 797
 798        struct ref_sort *sort = xcalloc(1, sizeof(*sort));
 799
 800        sort->next = NULL;
 801        sort->atom = parse_atom(cstr_name, cstr_name + strlen(cstr_name));
 802        return sort;
 803}
 804
 805int opt_parse_sort(const struct option *opt, const char *arg, int unset)
 806{
 807        struct ref_sort **sort_tail = opt->value;
 808        struct ref_sort *s;
 809        int len;
 810
 811        if (!arg) /* should --no-sort void the list ? */
 812                return -1;
 813
 814        *sort_tail = s = xcalloc(1, sizeof(*s));
 815        sort_tail = &s->next;
 816
 817        if (*arg == '-') {
 818                s->reverse = 1;
 819                arg++;
 820        }
 821        len = strlen(arg);
 822        s->atom = parse_atom(arg, arg+len);
 823        return 0;
 824}
 825
 826static char const * const for_each_ref_usage[] = {
 827        "git-for-each-ref [options] [<pattern>]",
 828        NULL
 829};
 830
 831int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
 832{
 833        int i, num_refs;
 834        const char *format = "%(objectname) %(objecttype)\t%(refname)";
 835        struct ref_sort *sort = NULL, **sort_tail = &sort;
 836        int maxcount = 0, quote_style = 0;
 837        struct refinfo **refs;
 838        struct grab_ref_cbdata cbdata;
 839
 840        struct option opts[] = {
 841                OPT_BIT('s', "shell", &quote_style,
 842                        "quote placeholders suitably for shells", QUOTE_SHELL),
 843                OPT_BIT('p', "perl",  &quote_style,
 844                        "quote placeholders suitably for perl", QUOTE_PERL),
 845                OPT_BIT(0 , "python", &quote_style,
 846                        "quote placeholders suitably for python", QUOTE_PYTHON),
 847                OPT_BIT(0 , "tcl",  &quote_style,
 848                        "quote placeholders suitably for tcl", QUOTE_TCL),
 849
 850                OPT_GROUP(""),
 851                OPT_INTEGER( 0 , "count", &maxcount, "show only <n> matched refs"),
 852                OPT_STRING(  0 , "format", &format, "format", "format to use for the output"),
 853                OPT_CALLBACK(0 , "sort", sort_tail, "key",
 854                            "field name to sort on", &opt_parse_sort),
 855                OPT_END(),
 856        };
 857
 858        parse_options(argc, argv, opts, for_each_ref_usage, 0);
 859        if (maxcount < 0) {
 860                error("invalid --count argument: `%d'", maxcount);
 861                usage_with_options(for_each_ref_usage, opts);
 862        }
 863        if (HAS_MULTI_BITS(quote_style)) {
 864                error("more than one quoting style?");
 865                usage_with_options(for_each_ref_usage, opts);
 866        }
 867        if (verify_format(format))
 868                usage_with_options(for_each_ref_usage, opts);
 869
 870        if (!sort)
 871                sort = default_sort();
 872        sort_atom_limit = used_atom_cnt;
 873
 874        memset(&cbdata, 0, sizeof(cbdata));
 875        cbdata.grab_pattern = argv;
 876        for_each_ref(grab_single_ref, &cbdata);
 877        refs = cbdata.grab_array;
 878        num_refs = cbdata.grab_cnt;
 879
 880        for (i = 0; i < used_atom_cnt; i++) {
 881                if (used_atom[i][0] == '*') {
 882                        need_tagged = 1;
 883                        break;
 884                }
 885        }
 886
 887        sort_refs(sort, refs, num_refs);
 888
 889        if (!maxcount || num_refs < maxcount)
 890                maxcount = num_refs;
 891        for (i = 0; i < maxcount; i++)
 892                show_ref(refs[i], format, quote_style);
 893        return 0;
 894}