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