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