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