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