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