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