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