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