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