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