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