ref-filter.con commit ref-filter: add support to sort by version (90c0040)
   1#include "builtin.h"
   2#include "cache.h"
   3#include "parse-options.h"
   4#include "refs.h"
   5#include "wildmatch.h"
   6#include "commit.h"
   7#include "remote.h"
   8#include "color.h"
   9#include "tag.h"
  10#include "quote.h"
  11#include "ref-filter.h"
  12#include "revision.h"
  13#include "utf8.h"
  14#include "git-compat-util.h"
  15#include "version.h"
  16
  17typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
  18
  19static struct {
  20        const char *name;
  21        cmp_type cmp_type;
  22} valid_atom[] = {
  23        { "refname" },
  24        { "objecttype" },
  25        { "objectsize", FIELD_ULONG },
  26        { "objectname" },
  27        { "tree" },
  28        { "parent" },
  29        { "numparent", FIELD_ULONG },
  30        { "object" },
  31        { "type" },
  32        { "tag" },
  33        { "author" },
  34        { "authorname" },
  35        { "authoremail" },
  36        { "authordate", FIELD_TIME },
  37        { "committer" },
  38        { "committername" },
  39        { "committeremail" },
  40        { "committerdate", FIELD_TIME },
  41        { "tagger" },
  42        { "taggername" },
  43        { "taggeremail" },
  44        { "taggerdate", FIELD_TIME },
  45        { "creator" },
  46        { "creatordate", FIELD_TIME },
  47        { "subject" },
  48        { "body" },
  49        { "contents" },
  50        { "upstream" },
  51        { "push" },
  52        { "symref" },
  53        { "flag" },
  54        { "HEAD" },
  55        { "color" },
  56        { "align" },
  57        { "end" },
  58};
  59
  60#define REF_FORMATTING_STATE_INIT  { 0, NULL }
  61
  62struct align {
  63        align_type position;
  64        unsigned int width;
  65};
  66
  67struct contents {
  68        unsigned int lines;
  69        struct object_id oid;
  70};
  71
  72struct ref_formatting_stack {
  73        struct ref_formatting_stack *prev;
  74        struct strbuf output;
  75        void (*at_end)(struct ref_formatting_stack *stack);
  76        void *at_end_data;
  77};
  78
  79struct ref_formatting_state {
  80        int quote_style;
  81        struct ref_formatting_stack *stack;
  82};
  83
  84struct atom_value {
  85        const char *s;
  86        union {
  87                struct align align;
  88                struct contents contents;
  89        } u;
  90        void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
  91        unsigned long ul; /* used for sorting when not FIELD_STR */
  92};
  93
  94/*
  95 * An atom is a valid field atom listed above, possibly prefixed with
  96 * a "*" to denote deref_tag().
  97 *
  98 * We parse given format string and sort specifiers, and make a list
  99 * of properties that we need to extract out of objects.  ref_array_item
 100 * structure will hold an array of values extracted that can be
 101 * indexed with the "atom number", which is an index into this
 102 * array.
 103 */
 104static const char **used_atom;
 105static cmp_type *used_atom_type;
 106static int used_atom_cnt, need_tagged, need_symref;
 107static int need_color_reset_at_eol;
 108
 109/*
 110 * Used to parse format string and sort specifiers
 111 */
 112int parse_ref_filter_atom(const char *atom, const char *ep)
 113{
 114        const char *sp;
 115        int i, at;
 116
 117        sp = atom;
 118        if (*sp == '*' && sp < ep)
 119                sp++; /* deref */
 120        if (ep <= sp)
 121                die("malformed field name: %.*s", (int)(ep-atom), atom);
 122
 123        /* Do we have the atom already used elsewhere? */
 124        for (i = 0; i < used_atom_cnt; i++) {
 125                int len = strlen(used_atom[i]);
 126                if (len == ep - atom && !memcmp(used_atom[i], atom, len))
 127                        return i;
 128        }
 129
 130        /* Is the atom a valid one? */
 131        for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
 132                int len = strlen(valid_atom[i].name);
 133                /*
 134                 * If the atom name has a colon, strip it and everything after
 135                 * it off - it specifies the format for this entry, and
 136                 * shouldn't be used for checking against the valid_atom
 137                 * table.
 138                 */
 139                const char *formatp = strchr(sp, ':');
 140                if (!formatp || ep < formatp)
 141                        formatp = ep;
 142                if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
 143                        break;
 144        }
 145
 146        if (ARRAY_SIZE(valid_atom) <= i)
 147                die("unknown field name: %.*s", (int)(ep-atom), atom);
 148
 149        /* Add it in, including the deref prefix */
 150        at = used_atom_cnt;
 151        used_atom_cnt++;
 152        REALLOC_ARRAY(used_atom, used_atom_cnt);
 153        REALLOC_ARRAY(used_atom_type, used_atom_cnt);
 154        used_atom[at] = xmemdupz(atom, ep - atom);
 155        used_atom_type[at] = valid_atom[i].cmp_type;
 156        if (*atom == '*')
 157                need_tagged = 1;
 158        if (!strcmp(used_atom[at], "symref"))
 159                need_symref = 1;
 160        return at;
 161}
 162
 163static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
 164{
 165        switch (quote_style) {
 166        case QUOTE_NONE:
 167                strbuf_addstr(s, str);
 168                break;
 169        case QUOTE_SHELL:
 170                sq_quote_buf(s, str);
 171                break;
 172        case QUOTE_PERL:
 173                perl_quote_buf(s, str);
 174                break;
 175        case QUOTE_PYTHON:
 176                python_quote_buf(s, str);
 177                break;
 178        case QUOTE_TCL:
 179                tcl_quote_buf(s, str);
 180                break;
 181        }
 182}
 183
 184static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
 185{
 186        /*
 187         * Quote formatting is only done when the stack has a single
 188         * element. Otherwise quote formatting is done on the
 189         * element's entire output strbuf when the %(end) atom is
 190         * encountered.
 191         */
 192        if (!state->stack->prev)
 193                quote_formatting(&state->stack->output, v->s, state->quote_style);
 194        else
 195                strbuf_addstr(&state->stack->output, v->s);
 196}
 197
 198static void push_stack_element(struct ref_formatting_stack **stack)
 199{
 200        struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
 201
 202        strbuf_init(&s->output, 0);
 203        s->prev = *stack;
 204        *stack = s;
 205}
 206
 207static void pop_stack_element(struct ref_formatting_stack **stack)
 208{
 209        struct ref_formatting_stack *current = *stack;
 210        struct ref_formatting_stack *prev = current->prev;
 211
 212        if (prev)
 213                strbuf_addbuf(&prev->output, &current->output);
 214        strbuf_release(&current->output);
 215        free(current);
 216        *stack = prev;
 217}
 218
 219static void end_align_handler(struct ref_formatting_stack *stack)
 220{
 221        struct align *align = (struct align *)stack->at_end_data;
 222        struct strbuf s = STRBUF_INIT;
 223
 224        strbuf_utf8_align(&s, align->position, align->width, stack->output.buf);
 225        strbuf_swap(&stack->output, &s);
 226        strbuf_release(&s);
 227}
 228
 229static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
 230{
 231        struct ref_formatting_stack *new;
 232
 233        push_stack_element(&state->stack);
 234        new = state->stack;
 235        new->at_end = end_align_handler;
 236        new->at_end_data = &atomv->u.align;
 237}
 238
 239static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
 240{
 241        struct ref_formatting_stack *current = state->stack;
 242        struct strbuf s = STRBUF_INIT;
 243
 244        if (!current->at_end)
 245                die(_("format: %%(end) atom used without corresponding atom"));
 246        current->at_end(current);
 247
 248        /*
 249         * Perform quote formatting when the stack element is that of
 250         * a supporting atom. If nested then perform quote formatting
 251         * only on the topmost supporting atom.
 252         */
 253        if (!state->stack->prev->prev) {
 254                quote_formatting(&s, current->output.buf, state->quote_style);
 255                strbuf_swap(&current->output, &s);
 256        }
 257        strbuf_release(&s);
 258        pop_stack_element(&state->stack);
 259}
 260
 261static int match_atom_name(const char *name, const char *atom_name, const char **val)
 262{
 263        const char *body;
 264
 265        if (!skip_prefix(name, atom_name, &body))
 266                return 0; /* doesn't even begin with "atom_name" */
 267        if (!body[0]) {
 268                *val = NULL; /* %(atom_name) and no customization */
 269                return 1;
 270        }
 271        if (body[0] != ':')
 272                return 0; /* "atom_namefoo" is not "atom_name" or "atom_name:..." */
 273        *val = body + 1; /* "atom_name:val" */
 274        return 1;
 275}
 276
 277/*
 278 * In a format string, find the next occurrence of %(atom).
 279 */
 280static const char *find_next(const char *cp)
 281{
 282        while (*cp) {
 283                if (*cp == '%') {
 284                        /*
 285                         * %( is the start of an atom;
 286                         * %% is a quoted per-cent.
 287                         */
 288                        if (cp[1] == '(')
 289                                return cp;
 290                        else if (cp[1] == '%')
 291                                cp++; /* skip over two % */
 292                        /* otherwise this is a singleton, literal % */
 293                }
 294                cp++;
 295        }
 296        return NULL;
 297}
 298
 299/*
 300 * Make sure the format string is well formed, and parse out
 301 * the used atoms.
 302 */
 303int verify_ref_format(const char *format)
 304{
 305        const char *cp, *sp;
 306
 307        need_color_reset_at_eol = 0;
 308        for (cp = format; *cp && (sp = find_next(cp)); ) {
 309                const char *color, *ep = strchr(sp, ')');
 310                int at;
 311
 312                if (!ep)
 313                        return error("malformed format string %s", sp);
 314                /* sp points at "%(" and ep points at the closing ")" */
 315                at = parse_ref_filter_atom(sp + 2, ep);
 316                cp = ep + 1;
 317
 318                if (skip_prefix(used_atom[at], "color:", &color))
 319                        need_color_reset_at_eol = !!strcmp(color, "reset");
 320        }
 321        return 0;
 322}
 323
 324/*
 325 * Given an object name, read the object data and size, and return a
 326 * "struct object".  If the object data we are returning is also borrowed
 327 * by the "struct object" representation, set *eaten as well---it is a
 328 * signal from parse_object_buffer to us not to free the buffer.
 329 */
 330static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
 331{
 332        enum object_type type;
 333        void *buf = read_sha1_file(sha1, &type, sz);
 334
 335        if (buf)
 336                *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
 337        else
 338                *obj = NULL;
 339        return buf;
 340}
 341
 342static int grab_objectname(const char *name, const unsigned char *sha1,
 343                            struct atom_value *v)
 344{
 345        if (!strcmp(name, "objectname")) {
 346                char *s = xmalloc(41);
 347                strcpy(s, sha1_to_hex(sha1));
 348                v->s = s;
 349                return 1;
 350        }
 351        if (!strcmp(name, "objectname:short")) {
 352                v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
 353                return 1;
 354        }
 355        return 0;
 356}
 357
 358/* See grab_values */
 359static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 360{
 361        int i;
 362
 363        for (i = 0; i < used_atom_cnt; i++) {
 364                const char *name = used_atom[i];
 365                struct atom_value *v = &val[i];
 366                if (!!deref != (*name == '*'))
 367                        continue;
 368                if (deref)
 369                        name++;
 370                if (!strcmp(name, "objecttype"))
 371                        v->s = typename(obj->type);
 372                else if (!strcmp(name, "objectsize")) {
 373                        char *s = xmalloc(40);
 374                        sprintf(s, "%lu", sz);
 375                        v->ul = sz;
 376                        v->s = s;
 377                }
 378                else if (deref)
 379                        grab_objectname(name, obj->sha1, v);
 380        }
 381}
 382
 383/* See grab_values */
 384static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 385{
 386        int i;
 387        struct tag *tag = (struct tag *) obj;
 388
 389        for (i = 0; i < used_atom_cnt; i++) {
 390                const char *name = used_atom[i];
 391                struct atom_value *v = &val[i];
 392                if (!!deref != (*name == '*'))
 393                        continue;
 394                if (deref)
 395                        name++;
 396                if (!strcmp(name, "tag"))
 397                        v->s = tag->tag;
 398                else if (!strcmp(name, "type") && tag->tagged)
 399                        v->s = typename(tag->tagged->type);
 400                else if (!strcmp(name, "object") && tag->tagged) {
 401                        char *s = xmalloc(41);
 402                        strcpy(s, sha1_to_hex(tag->tagged->sha1));
 403                        v->s = s;
 404                }
 405        }
 406}
 407
 408/* See grab_values */
 409static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 410{
 411        int i;
 412        struct commit *commit = (struct commit *) obj;
 413
 414        for (i = 0; i < used_atom_cnt; i++) {
 415                const char *name = used_atom[i];
 416                struct atom_value *v = &val[i];
 417                if (!!deref != (*name == '*'))
 418                        continue;
 419                if (deref)
 420                        name++;
 421                if (!strcmp(name, "tree")) {
 422                        char *s = xmalloc(41);
 423                        strcpy(s, sha1_to_hex(commit->tree->object.sha1));
 424                        v->s = s;
 425                }
 426                if (!strcmp(name, "numparent")) {
 427                        char *s = xmalloc(40);
 428                        v->ul = commit_list_count(commit->parents);
 429                        sprintf(s, "%lu", v->ul);
 430                        v->s = s;
 431                }
 432                else if (!strcmp(name, "parent")) {
 433                        int num = commit_list_count(commit->parents);
 434                        int i;
 435                        struct commit_list *parents;
 436                        char *s = xmalloc(41 * num + 1);
 437                        v->s = s;
 438                        for (i = 0, parents = commit->parents;
 439                             parents;
 440                             parents = parents->next, i = i + 41) {
 441                                struct commit *parent = parents->item;
 442                                strcpy(s+i, sha1_to_hex(parent->object.sha1));
 443                                if (parents->next)
 444                                        s[i+40] = ' ';
 445                        }
 446                        if (!i)
 447                                *s = '\0';
 448                }
 449        }
 450}
 451
 452static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
 453{
 454        const char *eol;
 455        while (*buf) {
 456                if (!strncmp(buf, who, wholen) &&
 457                    buf[wholen] == ' ')
 458                        return buf + wholen + 1;
 459                eol = strchr(buf, '\n');
 460                if (!eol)
 461                        return "";
 462                eol++;
 463                if (*eol == '\n')
 464                        return ""; /* end of header */
 465                buf = eol;
 466        }
 467        return "";
 468}
 469
 470static const char *copy_line(const char *buf)
 471{
 472        const char *eol = strchrnul(buf, '\n');
 473        return xmemdupz(buf, eol - buf);
 474}
 475
 476static const char *copy_name(const char *buf)
 477{
 478        const char *cp;
 479        for (cp = buf; *cp && *cp != '\n'; cp++) {
 480                if (!strncmp(cp, " <", 2))
 481                        return xmemdupz(buf, cp - buf);
 482        }
 483        return "";
 484}
 485
 486static const char *copy_email(const char *buf)
 487{
 488        const char *email = strchr(buf, '<');
 489        const char *eoemail;
 490        if (!email)
 491                return "";
 492        eoemail = strchr(email, '>');
 493        if (!eoemail)
 494                return "";
 495        return xmemdupz(email, eoemail + 1 - email);
 496}
 497
 498static char *copy_subject(const char *buf, unsigned long len)
 499{
 500        char *r = xmemdupz(buf, len);
 501        int i;
 502
 503        for (i = 0; i < len; i++)
 504                if (r[i] == '\n')
 505                        r[i] = ' ';
 506
 507        return r;
 508}
 509
 510static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
 511{
 512        const char *eoemail = strstr(buf, "> ");
 513        char *zone;
 514        unsigned long timestamp;
 515        long tz;
 516        struct date_mode date_mode = { DATE_NORMAL };
 517        const char *formatp;
 518
 519        /*
 520         * We got here because atomname ends in "date" or "date<something>";
 521         * it's not possible that <something> is not ":<format>" because
 522         * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
 523         * ":" means no format is specified, and use the default.
 524         */
 525        formatp = strchr(atomname, ':');
 526        if (formatp != NULL) {
 527                formatp++;
 528                parse_date_format(formatp, &date_mode);
 529        }
 530
 531        if (!eoemail)
 532                goto bad;
 533        timestamp = strtoul(eoemail + 2, &zone, 10);
 534        if (timestamp == ULONG_MAX)
 535                goto bad;
 536        tz = strtol(zone, NULL, 10);
 537        if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
 538                goto bad;
 539        v->s = xstrdup(show_date(timestamp, tz, &date_mode));
 540        v->ul = timestamp;
 541        return;
 542 bad:
 543        v->s = "";
 544        v->ul = 0;
 545}
 546
 547/* See grab_values */
 548static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 549{
 550        int i;
 551        int wholen = strlen(who);
 552        const char *wholine = NULL;
 553
 554        for (i = 0; i < used_atom_cnt; i++) {
 555                const char *name = used_atom[i];
 556                struct atom_value *v = &val[i];
 557                if (!!deref != (*name == '*'))
 558                        continue;
 559                if (deref)
 560                        name++;
 561                if (strncmp(who, name, wholen))
 562                        continue;
 563                if (name[wholen] != 0 &&
 564                    strcmp(name + wholen, "name") &&
 565                    strcmp(name + wholen, "email") &&
 566                    !starts_with(name + wholen, "date"))
 567                        continue;
 568                if (!wholine)
 569                        wholine = find_wholine(who, wholen, buf, sz);
 570                if (!wholine)
 571                        return; /* no point looking for it */
 572                if (name[wholen] == 0)
 573                        v->s = copy_line(wholine);
 574                else if (!strcmp(name + wholen, "name"))
 575                        v->s = copy_name(wholine);
 576                else if (!strcmp(name + wholen, "email"))
 577                        v->s = copy_email(wholine);
 578                else if (starts_with(name + wholen, "date"))
 579                        grab_date(wholine, v, name);
 580        }
 581
 582        /*
 583         * For a tag or a commit object, if "creator" or "creatordate" is
 584         * requested, do something special.
 585         */
 586        if (strcmp(who, "tagger") && strcmp(who, "committer"))
 587                return; /* "author" for commit object is not wanted */
 588        if (!wholine)
 589                wholine = find_wholine(who, wholen, buf, sz);
 590        if (!wholine)
 591                return;
 592        for (i = 0; i < used_atom_cnt; i++) {
 593                const char *name = used_atom[i];
 594                struct atom_value *v = &val[i];
 595                if (!!deref != (*name == '*'))
 596                        continue;
 597                if (deref)
 598                        name++;
 599
 600                if (starts_with(name, "creatordate"))
 601                        grab_date(wholine, v, name);
 602                else if (!strcmp(name, "creator"))
 603                        v->s = copy_line(wholine);
 604        }
 605}
 606
 607static void find_subpos(const char *buf, unsigned long sz,
 608                        const char **sub, unsigned long *sublen,
 609                        const char **body, unsigned long *bodylen,
 610                        unsigned long *nonsiglen,
 611                        const char **sig, unsigned long *siglen)
 612{
 613        const char *eol;
 614        /* skip past header until we hit empty line */
 615        while (*buf && *buf != '\n') {
 616                eol = strchrnul(buf, '\n');
 617                if (*eol)
 618                        eol++;
 619                buf = eol;
 620        }
 621        /* skip any empty lines */
 622        while (*buf == '\n')
 623                buf++;
 624
 625        /* parse signature first; we might not even have a subject line */
 626        *sig = buf + parse_signature(buf, strlen(buf));
 627        *siglen = strlen(*sig);
 628
 629        /* subject is first non-empty line */
 630        *sub = buf;
 631        /* subject goes to first empty line */
 632        while (buf < *sig && *buf && *buf != '\n') {
 633                eol = strchrnul(buf, '\n');
 634                if (*eol)
 635                        eol++;
 636                buf = eol;
 637        }
 638        *sublen = buf - *sub;
 639        /* drop trailing newline, if present */
 640        if (*sublen && (*sub)[*sublen - 1] == '\n')
 641                *sublen -= 1;
 642
 643        /* skip any empty lines */
 644        while (*buf == '\n')
 645                buf++;
 646        *body = buf;
 647        *bodylen = strlen(buf);
 648        *nonsiglen = *sig - buf;
 649}
 650
 651/*
 652 * If 'lines' is greater than 0, append that many lines from the given
 653 * 'buf' of length 'size' to the given strbuf.
 654 */
 655static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
 656{
 657        int i;
 658        const char *sp, *eol;
 659        size_t len;
 660
 661        sp = buf;
 662
 663        for (i = 0; i < lines && sp < buf + size; i++) {
 664                if (i)
 665                        strbuf_addstr(out, "\n    ");
 666                eol = memchr(sp, '\n', size - (sp - buf));
 667                len = eol ? eol - sp : size - (sp - buf);
 668                strbuf_add(out, sp, len);
 669                if (!eol)
 670                        break;
 671                sp = eol + 1;
 672        }
 673}
 674
 675/* See grab_values */
 676static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 677{
 678        int i;
 679        const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
 680        unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
 681
 682        for (i = 0; i < used_atom_cnt; i++) {
 683                const char *name = used_atom[i];
 684                struct atom_value *v = &val[i];
 685                const char *valp = NULL;
 686                if (!!deref != (*name == '*'))
 687                        continue;
 688                if (deref)
 689                        name++;
 690                if (strcmp(name, "subject") &&
 691                    strcmp(name, "body") &&
 692                    strcmp(name, "contents") &&
 693                    strcmp(name, "contents:subject") &&
 694                    strcmp(name, "contents:body") &&
 695                    strcmp(name, "contents:signature") &&
 696                    !starts_with(name, "contents:lines="))
 697                        continue;
 698                if (!subpos)
 699                        find_subpos(buf, sz,
 700                                    &subpos, &sublen,
 701                                    &bodypos, &bodylen, &nonsiglen,
 702                                    &sigpos, &siglen);
 703
 704                if (!strcmp(name, "subject"))
 705                        v->s = copy_subject(subpos, sublen);
 706                else if (!strcmp(name, "contents:subject"))
 707                        v->s = copy_subject(subpos, sublen);
 708                else if (!strcmp(name, "body"))
 709                        v->s = xmemdupz(bodypos, bodylen);
 710                else if (!strcmp(name, "contents:body"))
 711                        v->s = xmemdupz(bodypos, nonsiglen);
 712                else if (!strcmp(name, "contents:signature"))
 713                        v->s = xmemdupz(sigpos, siglen);
 714                else if (!strcmp(name, "contents"))
 715                        v->s = xstrdup(subpos);
 716                else if (skip_prefix(name, "contents:lines=", &valp)) {
 717                        struct strbuf s = STRBUF_INIT;
 718                        const char *contents_end = bodylen + bodypos - siglen;
 719
 720                        if (strtoul_ui(valp, 10, &v->u.contents.lines))
 721                                die(_("positive value expected contents:lines=%s"), valp);
 722                        /*  Size is the length of the message after removing the signature */
 723                        append_lines(&s, subpos, contents_end - subpos, v->u.contents.lines);
 724                        v->s = strbuf_detach(&s, NULL);
 725                }
 726        }
 727}
 728
 729/*
 730 * We want to have empty print-string for field requests
 731 * that do not apply (e.g. "authordate" for a tag object)
 732 */
 733static void fill_missing_values(struct atom_value *val)
 734{
 735        int i;
 736        for (i = 0; i < used_atom_cnt; i++) {
 737                struct atom_value *v = &val[i];
 738                if (v->s == NULL)
 739                        v->s = "";
 740        }
 741}
 742
 743/*
 744 * val is a list of atom_value to hold returned values.  Extract
 745 * the values for atoms in used_atom array out of (obj, buf, sz).
 746 * when deref is false, (obj, buf, sz) is the object that is
 747 * pointed at by the ref itself; otherwise it is the object the
 748 * ref (which is a tag) refers to.
 749 */
 750static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
 751{
 752        grab_common_values(val, deref, obj, buf, sz);
 753        switch (obj->type) {
 754        case OBJ_TAG:
 755                grab_tag_values(val, deref, obj, buf, sz);
 756                grab_sub_body_contents(val, deref, obj, buf, sz);
 757                grab_person("tagger", val, deref, obj, buf, sz);
 758                break;
 759        case OBJ_COMMIT:
 760                grab_commit_values(val, deref, obj, buf, sz);
 761                grab_sub_body_contents(val, deref, obj, buf, sz);
 762                grab_person("author", val, deref, obj, buf, sz);
 763                grab_person("committer", val, deref, obj, buf, sz);
 764                break;
 765        case OBJ_TREE:
 766                /* grab_tree_values(val, deref, obj, buf, sz); */
 767                break;
 768        case OBJ_BLOB:
 769                /* grab_blob_values(val, deref, obj, buf, sz); */
 770                break;
 771        default:
 772                die("Eh?  Object of type %d?", obj->type);
 773        }
 774}
 775
 776static inline char *copy_advance(char *dst, const char *src)
 777{
 778        while (*src)
 779                *dst++ = *src++;
 780        return dst;
 781}
 782
 783/*
 784 * Parse the object referred by ref, and grab needed value.
 785 */
 786static void populate_value(struct ref_array_item *ref)
 787{
 788        void *buf;
 789        struct object *obj;
 790        int eaten, i;
 791        unsigned long size;
 792        const unsigned char *tagged;
 793
 794        ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
 795
 796        if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
 797                unsigned char unused1[20];
 798                ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
 799                                             unused1, NULL);
 800                if (!ref->symref)
 801                        ref->symref = "";
 802        }
 803
 804        /* Fill in specials first */
 805        for (i = 0; i < used_atom_cnt; i++) {
 806                const char *name = used_atom[i];
 807                struct atom_value *v = &ref->value[i];
 808                int deref = 0;
 809                const char *refname;
 810                const char *formatp;
 811                const char *valp;
 812                struct branch *branch = NULL;
 813
 814                v->handler = append_atom;
 815
 816                if (*name == '*') {
 817                        deref = 1;
 818                        name++;
 819                }
 820
 821                if (starts_with(name, "refname"))
 822                        refname = ref->refname;
 823                else if (starts_with(name, "symref"))
 824                        refname = ref->symref ? ref->symref : "";
 825                else if (starts_with(name, "upstream")) {
 826                        const char *branch_name;
 827                        /* only local branches may have an upstream */
 828                        if (!skip_prefix(ref->refname, "refs/heads/",
 829                                         &branch_name))
 830                                continue;
 831                        branch = branch_get(branch_name);
 832
 833                        refname = branch_get_upstream(branch, NULL);
 834                        if (!refname)
 835                                continue;
 836                } else if (starts_with(name, "push")) {
 837                        const char *branch_name;
 838                        if (!skip_prefix(ref->refname, "refs/heads/",
 839                                         &branch_name))
 840                                continue;
 841                        branch = branch_get(branch_name);
 842
 843                        refname = branch_get_push(branch, NULL);
 844                        if (!refname)
 845                                continue;
 846                } else if (match_atom_name(name, "color", &valp)) {
 847                        char color[COLOR_MAXLEN] = "";
 848
 849                        if (!valp)
 850                                die(_("expected format: %%(color:<color>)"));
 851                        if (color_parse(valp, color) < 0)
 852                                die(_("unable to parse format"));
 853                        v->s = xstrdup(color);
 854                        continue;
 855                } else if (!strcmp(name, "flag")) {
 856                        char buf[256], *cp = buf;
 857                        if (ref->flag & REF_ISSYMREF)
 858                                cp = copy_advance(cp, ",symref");
 859                        if (ref->flag & REF_ISPACKED)
 860                                cp = copy_advance(cp, ",packed");
 861                        if (cp == buf)
 862                                v->s = "";
 863                        else {
 864                                *cp = '\0';
 865                                v->s = xstrdup(buf + 1);
 866                        }
 867                        continue;
 868                } else if (!deref && grab_objectname(name, ref->objectname, v)) {
 869                        continue;
 870                } else if (!strcmp(name, "HEAD")) {
 871                        const char *head;
 872                        unsigned char sha1[20];
 873
 874                        head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
 875                                                  sha1, NULL);
 876                        if (!strcmp(ref->refname, head))
 877                                v->s = "*";
 878                        else
 879                                v->s = " ";
 880                        continue;
 881                } else if (match_atom_name(name, "align", &valp)) {
 882                        struct align *align = &v->u.align;
 883                        struct strbuf **s, **to_free;
 884                        int width = -1;
 885
 886                        if (!valp)
 887                                die(_("expected format: %%(align:<width>,<position>)"));
 888
 889                        /*
 890                         * TODO: Implement a function similar to strbuf_split_str()
 891                         * which would omit the separator from the end of each value.
 892                         */
 893                        s = to_free = strbuf_split_str(valp, ',', 0);
 894
 895                        align->position = ALIGN_LEFT;
 896
 897                        while (*s) {
 898                                /*  Strip trailing comma */
 899                                if (s[1])
 900                                        strbuf_setlen(s[0], s[0]->len - 1);
 901                                if (!strtoul_ui(s[0]->buf, 10, (unsigned int *)&width))
 902                                        ;
 903                                else if (!strcmp(s[0]->buf, "left"))
 904                                        align->position = ALIGN_LEFT;
 905                                else if (!strcmp(s[0]->buf, "right"))
 906                                        align->position = ALIGN_RIGHT;
 907                                else if (!strcmp(s[0]->buf, "middle"))
 908                                        align->position = ALIGN_MIDDLE;
 909                                else
 910                                        die(_("improper format entered align:%s"), s[0]->buf);
 911                                s++;
 912                        }
 913
 914                        if (width < 0)
 915                                die(_("positive width expected with the %%(align) atom"));
 916                        align->width = width;
 917                        strbuf_list_free(to_free);
 918                        v->handler = align_atom_handler;
 919                        continue;
 920                } else if (!strcmp(name, "end")) {
 921                        v->handler = end_atom_handler;
 922                        continue;
 923                } else
 924                        continue;
 925
 926                formatp = strchr(name, ':');
 927                if (formatp) {
 928                        int num_ours, num_theirs;
 929
 930                        formatp++;
 931                        if (!strcmp(formatp, "short"))
 932                                refname = shorten_unambiguous_ref(refname,
 933                                                      warn_ambiguous_refs);
 934                        else if (!strcmp(formatp, "track") &&
 935                                 (starts_with(name, "upstream") ||
 936                                  starts_with(name, "push"))) {
 937                                char buf[40];
 938
 939                                if (stat_tracking_info(branch, &num_ours,
 940                                                       &num_theirs, NULL))
 941                                        continue;
 942
 943                                if (!num_ours && !num_theirs)
 944                                        v->s = "";
 945                                else if (!num_ours) {
 946                                        sprintf(buf, "[behind %d]", num_theirs);
 947                                        v->s = xstrdup(buf);
 948                                } else if (!num_theirs) {
 949                                        sprintf(buf, "[ahead %d]", num_ours);
 950                                        v->s = xstrdup(buf);
 951                                } else {
 952                                        sprintf(buf, "[ahead %d, behind %d]",
 953                                                num_ours, num_theirs);
 954                                        v->s = xstrdup(buf);
 955                                }
 956                                continue;
 957                        } else if (!strcmp(formatp, "trackshort") &&
 958                                   (starts_with(name, "upstream") ||
 959                                    starts_with(name, "push"))) {
 960                                assert(branch);
 961
 962                                if (stat_tracking_info(branch, &num_ours,
 963                                                        &num_theirs, NULL))
 964                                        continue;
 965
 966                                if (!num_ours && !num_theirs)
 967                                        v->s = "=";
 968                                else if (!num_ours)
 969                                        v->s = "<";
 970                                else if (!num_theirs)
 971                                        v->s = ">";
 972                                else
 973                                        v->s = "<>";
 974                                continue;
 975                        } else
 976                                die("unknown %.*s format %s",
 977                                    (int)(formatp - name), name, formatp);
 978                }
 979
 980                if (!deref)
 981                        v->s = refname;
 982                else {
 983                        int len = strlen(refname);
 984                        char *s = xmalloc(len + 4);
 985                        sprintf(s, "%s^{}", refname);
 986                        v->s = s;
 987                }
 988        }
 989
 990        for (i = 0; i < used_atom_cnt; i++) {
 991                struct atom_value *v = &ref->value[i];
 992                if (v->s == NULL)
 993                        goto need_obj;
 994        }
 995        return;
 996
 997 need_obj:
 998        buf = get_obj(ref->objectname, &obj, &size, &eaten);
 999        if (!buf)
1000                die("missing object %s for %s",
1001                    sha1_to_hex(ref->objectname), ref->refname);
1002        if (!obj)
1003                die("parse_object_buffer failed on %s for %s",
1004                    sha1_to_hex(ref->objectname), ref->refname);
1005
1006        grab_values(ref->value, 0, obj, buf, size);
1007        if (!eaten)
1008                free(buf);
1009
1010        /*
1011         * If there is no atom that wants to know about tagged
1012         * object, we are done.
1013         */
1014        if (!need_tagged || (obj->type != OBJ_TAG))
1015                return;
1016
1017        /*
1018         * If it is a tag object, see if we use a value that derefs
1019         * the object, and if we do grab the object it refers to.
1020         */
1021        tagged = ((struct tag *)obj)->tagged->sha1;
1022
1023        /*
1024         * NEEDSWORK: This derefs tag only once, which
1025         * is good to deal with chains of trust, but
1026         * is not consistent with what deref_tag() does
1027         * which peels the onion to the core.
1028         */
1029        buf = get_obj(tagged, &obj, &size, &eaten);
1030        if (!buf)
1031                die("missing object %s for %s",
1032                    sha1_to_hex(tagged), ref->refname);
1033        if (!obj)
1034                die("parse_object_buffer failed on %s for %s",
1035                    sha1_to_hex(tagged), ref->refname);
1036        grab_values(ref->value, 1, obj, buf, size);
1037        if (!eaten)
1038                free(buf);
1039}
1040
1041/*
1042 * Given a ref, return the value for the atom.  This lazily gets value
1043 * out of the object by calling populate value.
1044 */
1045static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
1046{
1047        if (!ref->value) {
1048                populate_value(ref);
1049                fill_missing_values(ref->value);
1050        }
1051        *v = &ref->value[atom];
1052}
1053
1054enum contains_result {
1055        CONTAINS_UNKNOWN = -1,
1056        CONTAINS_NO = 0,
1057        CONTAINS_YES = 1
1058};
1059
1060/*
1061 * Mimicking the real stack, this stack lives on the heap, avoiding stack
1062 * overflows.
1063 *
1064 * At each recursion step, the stack items points to the commits whose
1065 * ancestors are to be inspected.
1066 */
1067struct contains_stack {
1068        int nr, alloc;
1069        struct contains_stack_entry {
1070                struct commit *commit;
1071                struct commit_list *parents;
1072        } *contains_stack;
1073};
1074
1075static int in_commit_list(const struct commit_list *want, struct commit *c)
1076{
1077        for (; want; want = want->next)
1078                if (!hashcmp(want->item->object.sha1, c->object.sha1))
1079                        return 1;
1080        return 0;
1081}
1082
1083/*
1084 * Test whether the candidate or one of its parents is contained in the list.
1085 * Do not recurse to find out, though, but return -1 if inconclusive.
1086 */
1087static enum contains_result contains_test(struct commit *candidate,
1088                            const struct commit_list *want)
1089{
1090        /* was it previously marked as containing a want commit? */
1091        if (candidate->object.flags & TMP_MARK)
1092                return 1;
1093        /* or marked as not possibly containing a want commit? */
1094        if (candidate->object.flags & UNINTERESTING)
1095                return 0;
1096        /* or are we it? */
1097        if (in_commit_list(want, candidate)) {
1098                candidate->object.flags |= TMP_MARK;
1099                return 1;
1100        }
1101
1102        if (parse_commit(candidate) < 0)
1103                return 0;
1104
1105        return -1;
1106}
1107
1108static void push_to_contains_stack(struct commit *candidate, struct contains_stack *contains_stack)
1109{
1110        ALLOC_GROW(contains_stack->contains_stack, contains_stack->nr + 1, contains_stack->alloc);
1111        contains_stack->contains_stack[contains_stack->nr].commit = candidate;
1112        contains_stack->contains_stack[contains_stack->nr++].parents = candidate->parents;
1113}
1114
1115static enum contains_result contains_tag_algo(struct commit *candidate,
1116                const struct commit_list *want)
1117{
1118        struct contains_stack contains_stack = { 0, 0, NULL };
1119        int result = contains_test(candidate, want);
1120
1121        if (result != CONTAINS_UNKNOWN)
1122                return result;
1123
1124        push_to_contains_stack(candidate, &contains_stack);
1125        while (contains_stack.nr) {
1126                struct contains_stack_entry *entry = &contains_stack.contains_stack[contains_stack.nr - 1];
1127                struct commit *commit = entry->commit;
1128                struct commit_list *parents = entry->parents;
1129
1130                if (!parents) {
1131                        commit->object.flags |= UNINTERESTING;
1132                        contains_stack.nr--;
1133                }
1134                /*
1135                 * If we just popped the stack, parents->item has been marked,
1136                 * therefore contains_test will return a meaningful 0 or 1.
1137                 */
1138                else switch (contains_test(parents->item, want)) {
1139                case CONTAINS_YES:
1140                        commit->object.flags |= TMP_MARK;
1141                        contains_stack.nr--;
1142                        break;
1143                case CONTAINS_NO:
1144                        entry->parents = parents->next;
1145                        break;
1146                case CONTAINS_UNKNOWN:
1147                        push_to_contains_stack(parents->item, &contains_stack);
1148                        break;
1149                }
1150        }
1151        free(contains_stack.contains_stack);
1152        return contains_test(candidate, want);
1153}
1154
1155static int commit_contains(struct ref_filter *filter, struct commit *commit)
1156{
1157        if (filter->with_commit_tag_algo)
1158                return contains_tag_algo(commit, filter->with_commit);
1159        return is_descendant_of(commit, filter->with_commit);
1160}
1161
1162/*
1163 * Return 1 if the refname matches one of the patterns, otherwise 0.
1164 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1165 * matches a pattern "refs/heads/") or a wildcard (e.g. the same ref
1166 * matches "refs/heads/m*",too).
1167 */
1168static int match_name_as_path(const char **pattern, const char *refname)
1169{
1170        int namelen = strlen(refname);
1171        for (; *pattern; pattern++) {
1172                const char *p = *pattern;
1173                int plen = strlen(p);
1174
1175                if ((plen <= namelen) &&
1176                    !strncmp(refname, p, plen) &&
1177                    (refname[plen] == '\0' ||
1178                     refname[plen] == '/' ||
1179                     p[plen-1] == '/'))
1180                        return 1;
1181                if (!wildmatch(p, refname, WM_PATHNAME, NULL))
1182                        return 1;
1183        }
1184        return 0;
1185}
1186
1187/*
1188 * Given a ref (sha1, refname), check if the ref belongs to the array
1189 * of sha1s. If the given ref is a tag, check if the given tag points
1190 * at one of the sha1s in the given sha1 array.
1191 * the given sha1_array.
1192 * NEEDSWORK:
1193 * 1. Only a single level of inderection is obtained, we might want to
1194 * change this to account for multiple levels (e.g. annotated tags
1195 * pointing to annotated tags pointing to a commit.)
1196 * 2. As the refs are cached we might know what refname peels to without
1197 * the need to parse the object via parse_object(). peel_ref() might be a
1198 * more efficient alternative to obtain the pointee.
1199 */
1200static const unsigned char *match_points_at(struct sha1_array *points_at,
1201                                            const unsigned char *sha1,
1202                                            const char *refname)
1203{
1204        const unsigned char *tagged_sha1 = NULL;
1205        struct object *obj;
1206
1207        if (sha1_array_lookup(points_at, sha1) >= 0)
1208                return sha1;
1209        obj = parse_object(sha1);
1210        if (!obj)
1211                die(_("malformed object at '%s'"), refname);
1212        if (obj->type == OBJ_TAG)
1213                tagged_sha1 = ((struct tag *)obj)->tagged->sha1;
1214        if (tagged_sha1 && sha1_array_lookup(points_at, tagged_sha1) >= 0)
1215                return tagged_sha1;
1216        return NULL;
1217}
1218
1219/* Allocate space for a new ref_array_item and copy the objectname and flag to it */
1220static struct ref_array_item *new_ref_array_item(const char *refname,
1221                                                 const unsigned char *objectname,
1222                                                 int flag)
1223{
1224        size_t len = strlen(refname);
1225        struct ref_array_item *ref = xcalloc(1, sizeof(struct ref_array_item) + len + 1);
1226        memcpy(ref->refname, refname, len);
1227        ref->refname[len] = '\0';
1228        hashcpy(ref->objectname, objectname);
1229        ref->flag = flag;
1230
1231        return ref;
1232}
1233
1234static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1235{
1236        unsigned int i;
1237
1238        static struct {
1239                const char *prefix;
1240                unsigned int kind;
1241        } ref_kind[] = {
1242                { "refs/heads/" , FILTER_REFS_BRANCHES },
1243                { "refs/remotes/" , FILTER_REFS_REMOTES },
1244                { "refs/tags/", FILTER_REFS_TAGS}
1245        };
1246
1247        if (filter->kind == FILTER_REFS_BRANCHES ||
1248            filter->kind == FILTER_REFS_REMOTES ||
1249            filter->kind == FILTER_REFS_TAGS)
1250                return filter->kind;
1251        else if (!strcmp(refname, "HEAD"))
1252                return FILTER_REFS_DETACHED_HEAD;
1253
1254        for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1255                if (starts_with(refname, ref_kind[i].prefix))
1256                        return ref_kind[i].kind;
1257        }
1258
1259        return FILTER_REFS_OTHERS;
1260}
1261
1262/*
1263 * A call-back given to for_each_ref().  Filter refs and keep them for
1264 * later object processing.
1265 */
1266static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1267{
1268        struct ref_filter_cbdata *ref_cbdata = cb_data;
1269        struct ref_filter *filter = ref_cbdata->filter;
1270        struct ref_array_item *ref;
1271        struct commit *commit = NULL;
1272        unsigned int kind;
1273
1274        if (flag & REF_BAD_NAME) {
1275                warning("ignoring ref with broken name %s", refname);
1276                return 0;
1277        }
1278
1279        if (flag & REF_ISBROKEN) {
1280                warning("ignoring broken ref %s", refname);
1281                return 0;
1282        }
1283
1284        /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1285        kind = filter_ref_kind(filter, refname);
1286        if (!(kind & filter->kind))
1287                return 0;
1288
1289        if (*filter->name_patterns && !match_name_as_path(filter->name_patterns, refname))
1290                return 0;
1291
1292        if (filter->points_at.nr && !match_points_at(&filter->points_at, oid->hash, refname))
1293                return 0;
1294
1295        /*
1296         * A merge filter is applied on refs pointing to commits. Hence
1297         * obtain the commit using the 'oid' available and discard all
1298         * non-commits early. The actual filtering is done later.
1299         */
1300        if (filter->merge_commit || filter->with_commit) {
1301                commit = lookup_commit_reference_gently(oid->hash, 1);
1302                if (!commit)
1303                        return 0;
1304                /* We perform the filtering for the '--contains' option */
1305                if (filter->with_commit &&
1306                    !commit_contains(filter, commit))
1307                        return 0;
1308        }
1309
1310        /*
1311         * We do not open the object yet; sort may only need refname
1312         * to do its job and the resulting list may yet to be pruned
1313         * by maxcount logic.
1314         */
1315        ref = new_ref_array_item(refname, oid->hash, flag);
1316        ref->commit = commit;
1317
1318        REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
1319        ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
1320        ref->kind = kind;
1321        return 0;
1322}
1323
1324/*  Free memory allocated for a ref_array_item */
1325static void free_array_item(struct ref_array_item *item)
1326{
1327        free((char *)item->symref);
1328        free(item);
1329}
1330
1331/* Free all memory allocated for ref_array */
1332void ref_array_clear(struct ref_array *array)
1333{
1334        int i;
1335
1336        for (i = 0; i < array->nr; i++)
1337                free_array_item(array->items[i]);
1338        free(array->items);
1339        array->items = NULL;
1340        array->nr = array->alloc = 0;
1341}
1342
1343static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
1344{
1345        struct rev_info revs;
1346        int i, old_nr;
1347        struct ref_filter *filter = ref_cbdata->filter;
1348        struct ref_array *array = ref_cbdata->array;
1349        struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
1350
1351        init_revisions(&revs, NULL);
1352
1353        for (i = 0; i < array->nr; i++) {
1354                struct ref_array_item *item = array->items[i];
1355                add_pending_object(&revs, &item->commit->object, item->refname);
1356                to_clear[i] = item->commit;
1357        }
1358
1359        filter->merge_commit->object.flags |= UNINTERESTING;
1360        add_pending_object(&revs, &filter->merge_commit->object, "");
1361
1362        revs.limited = 1;
1363        if (prepare_revision_walk(&revs))
1364                die(_("revision walk setup failed"));
1365
1366        old_nr = array->nr;
1367        array->nr = 0;
1368
1369        for (i = 0; i < old_nr; i++) {
1370                struct ref_array_item *item = array->items[i];
1371                struct commit *commit = item->commit;
1372
1373                int is_merged = !!(commit->object.flags & UNINTERESTING);
1374
1375                if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
1376                        array->items[array->nr++] = array->items[i];
1377                else
1378                        free_array_item(item);
1379        }
1380
1381        for (i = 0; i < old_nr; i++)
1382                clear_commit_marks(to_clear[i], ALL_REV_FLAGS);
1383        clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
1384        free(to_clear);
1385}
1386
1387/*
1388 * API for filtering a set of refs. Based on the type of refs the user
1389 * has requested, we iterate through those refs and apply filters
1390 * as per the given ref_filter structure and finally store the
1391 * filtered refs in the ref_array structure.
1392 */
1393int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
1394{
1395        struct ref_filter_cbdata ref_cbdata;
1396        int ret = 0;
1397        unsigned int broken = 0;
1398
1399        ref_cbdata.array = array;
1400        ref_cbdata.filter = filter;
1401
1402        if (type & FILTER_REFS_INCLUDE_BROKEN)
1403                broken = 1;
1404        filter->kind = type & FILTER_REFS_KIND_MASK;
1405
1406        /*  Simple per-ref filtering */
1407        if (!filter->kind)
1408                die("filter_refs: invalid type");
1409        else {
1410                /*
1411                 * For common cases where we need only branches or remotes or tags,
1412                 * we only iterate through those refs. If a mix of refs is needed,
1413                 * we iterate over all refs and filter out required refs with the help
1414                 * of filter_ref_kind().
1415                 */
1416                if (filter->kind == FILTER_REFS_BRANCHES)
1417                        ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
1418                else if (filter->kind == FILTER_REFS_REMOTES)
1419                        ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
1420                else if (filter->kind == FILTER_REFS_TAGS)
1421                        ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
1422                else if (filter->kind & FILTER_REFS_ALL)
1423                        ret = for_each_fullref_in("", ref_filter_handler, &ref_cbdata, broken);
1424                if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
1425                        head_ref(ref_filter_handler, &ref_cbdata);
1426        }
1427
1428
1429        /*  Filters that need revision walking */
1430        if (filter->merge_commit)
1431                do_merge_filter(&ref_cbdata);
1432
1433        return ret;
1434}
1435
1436static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
1437{
1438        struct atom_value *va, *vb;
1439        int cmp;
1440        cmp_type cmp_type = used_atom_type[s->atom];
1441
1442        get_ref_atom_value(a, s->atom, &va);
1443        get_ref_atom_value(b, s->atom, &vb);
1444        if (s->version)
1445                cmp = versioncmp(va->s, vb->s);
1446        else if (cmp_type == FIELD_STR)
1447                cmp = strcmp(va->s, vb->s);
1448        else {
1449                if (va->ul < vb->ul)
1450                        cmp = -1;
1451                else if (va->ul == vb->ul)
1452                        cmp = 0;
1453                else
1454                        cmp = 1;
1455        }
1456
1457        return (s->reverse) ? -cmp : cmp;
1458}
1459
1460static struct ref_sorting *ref_sorting;
1461static int compare_refs(const void *a_, const void *b_)
1462{
1463        struct ref_array_item *a = *((struct ref_array_item **)a_);
1464        struct ref_array_item *b = *((struct ref_array_item **)b_);
1465        struct ref_sorting *s;
1466
1467        for (s = ref_sorting; s; s = s->next) {
1468                int cmp = cmp_ref_sorting(s, a, b);
1469                if (cmp)
1470                        return cmp;
1471        }
1472        return 0;
1473}
1474
1475void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
1476{
1477        ref_sorting = sorting;
1478        qsort(array->items, array->nr, sizeof(struct ref_array_item *), compare_refs);
1479}
1480
1481static int hex1(char ch)
1482{
1483        if ('0' <= ch && ch <= '9')
1484                return ch - '0';
1485        else if ('a' <= ch && ch <= 'f')
1486                return ch - 'a' + 10;
1487        else if ('A' <= ch && ch <= 'F')
1488                return ch - 'A' + 10;
1489        return -1;
1490}
1491static int hex2(const char *cp)
1492{
1493        if (cp[0] && cp[1])
1494                return (hex1(cp[0]) << 4) | hex1(cp[1]);
1495        else
1496                return -1;
1497}
1498
1499static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
1500{
1501        struct strbuf *s = &state->stack->output;
1502
1503        while (*cp && (!ep || cp < ep)) {
1504                if (*cp == '%') {
1505                        if (cp[1] == '%')
1506                                cp++;
1507                        else {
1508                                int ch = hex2(cp + 1);
1509                                if (0 <= ch) {
1510                                        strbuf_addch(s, ch);
1511                                        cp += 3;
1512                                        continue;
1513                                }
1514                        }
1515                }
1516                strbuf_addch(s, *cp);
1517                cp++;
1518        }
1519}
1520
1521void show_ref_array_item(struct ref_array_item *info, const char *format, int quote_style)
1522{
1523        const char *cp, *sp, *ep;
1524        struct strbuf *final_buf;
1525        struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
1526
1527        state.quote_style = quote_style;
1528        push_stack_element(&state.stack);
1529
1530        for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1531                struct atom_value *atomv;
1532
1533                ep = strchr(sp, ')');
1534                if (cp < sp)
1535                        append_literal(cp, sp, &state);
1536                get_ref_atom_value(info, parse_ref_filter_atom(sp + 2, ep), &atomv);
1537                atomv->handler(atomv, &state);
1538        }
1539        if (*cp) {
1540                sp = cp + strlen(cp);
1541                append_literal(cp, sp, &state);
1542        }
1543        if (need_color_reset_at_eol) {
1544                struct atom_value resetv;
1545                char color[COLOR_MAXLEN] = "";
1546
1547                if (color_parse("reset", color) < 0)
1548                        die("BUG: couldn't parse 'reset' as a color");
1549                resetv.s = color;
1550                append_atom(&resetv, &state);
1551        }
1552        if (state.stack->prev)
1553                die(_("format: %%(end) atom missing"));
1554        final_buf = &state.stack->output;
1555        fwrite(final_buf->buf, 1, final_buf->len, stdout);
1556        pop_stack_element(&state.stack);
1557        putchar('\n');
1558}
1559
1560/*  If no sorting option is given, use refname to sort as default */
1561struct ref_sorting *ref_default_sorting(void)
1562{
1563        static const char cstr_name[] = "refname";
1564
1565        struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
1566
1567        sorting->next = NULL;
1568        sorting->atom = parse_ref_filter_atom(cstr_name, cstr_name + strlen(cstr_name));
1569        return sorting;
1570}
1571
1572int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
1573{
1574        struct ref_sorting **sorting_tail = opt->value;
1575        struct ref_sorting *s;
1576        int len;
1577
1578        if (!arg) /* should --no-sort void the list ? */
1579                return -1;
1580
1581        s = xcalloc(1, sizeof(*s));
1582        s->next = *sorting_tail;
1583        *sorting_tail = s;
1584
1585        if (*arg == '-') {
1586                s->reverse = 1;
1587                arg++;
1588        }
1589        if (skip_prefix(arg, "version:", &arg) ||
1590            skip_prefix(arg, "v:", &arg))
1591                s->version = 1;
1592        len = strlen(arg);
1593        s->atom = parse_ref_filter_atom(arg, arg+len);
1594        return 0;
1595}
1596
1597int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
1598{
1599        struct ref_filter *rf = opt->value;
1600        unsigned char sha1[20];
1601
1602        rf->merge = starts_with(opt->long_name, "no")
1603                ? REF_FILTER_MERGED_OMIT
1604                : REF_FILTER_MERGED_INCLUDE;
1605
1606        if (get_sha1(arg, sha1))
1607                die(_("malformed object name %s"), arg);
1608
1609        rf->merge_commit = lookup_commit_reference_gently(sha1, 0);
1610        if (!rf->merge_commit)
1611                return opterror(opt, "must point to a commit", 0);
1612
1613        return 0;
1614}