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