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