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