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