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