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