252daf2812480d61efe2669c3be3d9dcc134cfdc
   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
1491        if (oi->info.contentp) {
1492                *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
1493                if (!obj) {
1494                        if (!eaten)
1495                                free(oi->content);
1496                        return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1497                                               oid_to_hex(&oi->oid), ref->refname);
1498                }
1499                grab_values(ref->value, deref, *obj, oi->content, oi->size);
1500        }
1501
1502        grab_common_values(ref->value, deref, oi);
1503        if (!eaten)
1504                free(oi->content);
1505        return 0;
1506}
1507
1508/*
1509 * Parse the object referred by ref, and grab needed value.
1510 */
1511static int populate_value(struct ref_array_item *ref, struct strbuf *err)
1512{
1513        struct object *obj;
1514        int i;
1515        struct object_info empty = OBJECT_INFO_INIT;
1516
1517        ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1518
1519        if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
1520                ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
1521                                             NULL, NULL);
1522                if (!ref->symref)
1523                        ref->symref = xstrdup("");
1524        }
1525
1526        /* Fill in specials first */
1527        for (i = 0; i < used_atom_cnt; i++) {
1528                struct used_atom *atom = &used_atom[i];
1529                const char *name = used_atom[i].name;
1530                struct atom_value *v = &ref->value[i];
1531                int deref = 0;
1532                const char *refname;
1533                struct branch *branch = NULL;
1534
1535                v->handler = append_atom;
1536                v->atom = atom;
1537
1538                if (*name == '*') {
1539                        deref = 1;
1540                        name++;
1541                }
1542
1543                if (starts_with(name, "refname"))
1544                        refname = get_refname(atom, ref);
1545                else if (starts_with(name, "symref"))
1546                        refname = get_symref(atom, ref);
1547                else if (starts_with(name, "upstream")) {
1548                        const char *branch_name;
1549                        /* only local branches may have an upstream */
1550                        if (!skip_prefix(ref->refname, "refs/heads/",
1551                                         &branch_name)) {
1552                                v->s = xstrdup("");
1553                                continue;
1554                        }
1555                        branch = branch_get(branch_name);
1556
1557                        refname = branch_get_upstream(branch, NULL);
1558                        if (refname)
1559                                fill_remote_ref_details(atom, refname, branch, &v->s);
1560                        else
1561                                v->s = xstrdup("");
1562                        continue;
1563                } else if (atom->u.remote_ref.push) {
1564                        const char *branch_name;
1565                        v->s = xstrdup("");
1566                        if (!skip_prefix(ref->refname, "refs/heads/",
1567                                         &branch_name))
1568                                continue;
1569                        branch = branch_get(branch_name);
1570
1571                        if (atom->u.remote_ref.push_remote)
1572                                refname = NULL;
1573                        else {
1574                                refname = branch_get_push(branch, NULL);
1575                                if (!refname)
1576                                        continue;
1577                        }
1578                        /* We will definitely re-init v->s on the next line. */
1579                        free((char *)v->s);
1580                        fill_remote_ref_details(atom, refname, branch, &v->s);
1581                        continue;
1582                } else if (starts_with(name, "color:")) {
1583                        v->s = xstrdup(atom->u.color);
1584                        continue;
1585                } else if (!strcmp(name, "flag")) {
1586                        char buf[256], *cp = buf;
1587                        if (ref->flag & REF_ISSYMREF)
1588                                cp = copy_advance(cp, ",symref");
1589                        if (ref->flag & REF_ISPACKED)
1590                                cp = copy_advance(cp, ",packed");
1591                        if (cp == buf)
1592                                v->s = xstrdup("");
1593                        else {
1594                                *cp = '\0';
1595                                v->s = xstrdup(buf + 1);
1596                        }
1597                        continue;
1598                } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
1599                        continue;
1600                } else if (!strcmp(name, "HEAD")) {
1601                        if (atom->u.head && !strcmp(ref->refname, atom->u.head))
1602                                v->s = xstrdup("*");
1603                        else
1604                                v->s = xstrdup(" ");
1605                        continue;
1606                } else if (starts_with(name, "align")) {
1607                        v->handler = align_atom_handler;
1608                        v->s = xstrdup("");
1609                        continue;
1610                } else if (!strcmp(name, "end")) {
1611                        v->handler = end_atom_handler;
1612                        v->s = xstrdup("");
1613                        continue;
1614                } else if (starts_with(name, "if")) {
1615                        const char *s;
1616                        if (skip_prefix(name, "if:", &s))
1617                                v->s = xstrdup(s);
1618                        else
1619                                v->s = xstrdup("");
1620                        v->handler = if_atom_handler;
1621                        continue;
1622                } else if (!strcmp(name, "then")) {
1623                        v->handler = then_atom_handler;
1624                        v->s = xstrdup("");
1625                        continue;
1626                } else if (!strcmp(name, "else")) {
1627                        v->handler = else_atom_handler;
1628                        v->s = xstrdup("");
1629                        continue;
1630                } else
1631                        continue;
1632
1633                if (!deref)
1634                        v->s = xstrdup(refname);
1635                else
1636                        v->s = xstrfmt("%s^{}", refname);
1637                free((char *)refname);
1638        }
1639
1640        for (i = 0; i < used_atom_cnt; i++) {
1641                struct atom_value *v = &ref->value[i];
1642                if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1643                        return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1644                                               oid_to_hex(&ref->objectname), ref->refname);
1645        }
1646
1647        if (need_tagged)
1648                oi.info.contentp = &oi.content;
1649        if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1650            !memcmp(&oi_deref.info, &empty, sizeof(empty)))
1651                return 0;
1652
1653
1654        oi.oid = ref->objectname;
1655        if (get_object(ref, 0, &obj, &oi, err))
1656                return -1;
1657
1658        /*
1659         * If there is no atom that wants to know about tagged
1660         * object, we are done.
1661         */
1662        if (!need_tagged || (obj->type != OBJ_TAG))
1663                return 0;
1664
1665        /*
1666         * If it is a tag object, see if we use a value that derefs
1667         * the object, and if we do grab the object it refers to.
1668         */
1669        oi_deref.oid = ((struct tag *)obj)->tagged->oid;
1670
1671        /*
1672         * NEEDSWORK: This derefs tag only once, which
1673         * is good to deal with chains of trust, but
1674         * is not consistent with what deref_tag() does
1675         * which peels the onion to the core.
1676         */
1677        return get_object(ref, 1, &obj, &oi_deref, err);
1678}
1679
1680/*
1681 * Given a ref, return the value for the atom.  This lazily gets value
1682 * out of the object by calling populate value.
1683 */
1684static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1685                              struct atom_value **v, struct strbuf *err)
1686{
1687        if (!ref->value) {
1688                if (populate_value(ref, err))
1689                        return -1;
1690                fill_missing_values(ref->value);
1691        }
1692        *v = &ref->value[atom];
1693        return 0;
1694}
1695
1696/*
1697 * Return 1 if the refname matches one of the patterns, otherwise 0.
1698 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1699 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1700 * matches "refs/heads/mas*", too).
1701 */
1702static int match_pattern(const struct ref_filter *filter, const char *refname)
1703{
1704        const char **patterns = filter->name_patterns;
1705        unsigned flags = 0;
1706
1707        if (filter->ignore_case)
1708                flags |= WM_CASEFOLD;
1709
1710        /*
1711         * When no '--format' option is given we need to skip the prefix
1712         * for matching refs of tags and branches.
1713         */
1714        (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1715               skip_prefix(refname, "refs/heads/", &refname) ||
1716               skip_prefix(refname, "refs/remotes/", &refname) ||
1717               skip_prefix(refname, "refs/", &refname));
1718
1719        for (; *patterns; patterns++) {
1720                if (!wildmatch(*patterns, refname, flags))
1721                        return 1;
1722        }
1723        return 0;
1724}
1725
1726/*
1727 * Return 1 if the refname matches one of the patterns, otherwise 0.
1728 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
1729 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1730 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
1731 */
1732static int match_name_as_path(const struct ref_filter *filter, const char *refname)
1733{
1734        const char **pattern = filter->name_patterns;
1735        int namelen = strlen(refname);
1736        unsigned flags = WM_PATHNAME;
1737
1738        if (filter->ignore_case)
1739                flags |= WM_CASEFOLD;
1740
1741        for (; *pattern; pattern++) {
1742                const char *p = *pattern;
1743                int plen = strlen(p);
1744
1745                if ((plen <= namelen) &&
1746                    !strncmp(refname, p, plen) &&
1747                    (refname[plen] == '\0' ||
1748                     refname[plen] == '/' ||
1749                     p[plen-1] == '/'))
1750                        return 1;
1751                if (!wildmatch(p, refname, flags))
1752                        return 1;
1753        }
1754        return 0;
1755}
1756
1757/* Return 1 if the refname matches one of the patterns, otherwise 0. */
1758static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1759{
1760        if (!*filter->name_patterns)
1761                return 1; /* No pattern always matches */
1762        if (filter->match_as_path)
1763                return match_name_as_path(filter, refname);
1764        return match_pattern(filter, refname);
1765}
1766
1767/*
1768 * Find the longest prefix of pattern we can pass to
1769 * `for_each_fullref_in()`, namely the part of pattern preceding the
1770 * first glob character. (Note that `for_each_fullref_in()` is
1771 * perfectly happy working with a prefix that doesn't end at a
1772 * pathname component boundary.)
1773 */
1774static void find_longest_prefix(struct strbuf *out, const char *pattern)
1775{
1776        const char *p;
1777
1778        for (p = pattern; *p && !is_glob_special(*p); p++)
1779                ;
1780
1781        strbuf_add(out, pattern, p - pattern);
1782}
1783
1784/*
1785 * This is the same as for_each_fullref_in(), but it tries to iterate
1786 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1787 * pattern match, so the callback still has to match each ref individually.
1788 */
1789static int for_each_fullref_in_pattern(struct ref_filter *filter,
1790                                       each_ref_fn cb,
1791                                       void *cb_data,
1792                                       int broken)
1793{
1794        struct strbuf prefix = STRBUF_INIT;
1795        int ret;
1796
1797        if (!filter->match_as_path) {
1798                /*
1799                 * in this case, the patterns are applied after
1800                 * prefixes like "refs/heads/" etc. are stripped off,
1801                 * so we have to look at everything:
1802                 */
1803                return for_each_fullref_in("", cb, cb_data, broken);
1804        }
1805
1806        if (filter->ignore_case) {
1807                /*
1808                 * we can't handle case-insensitive comparisons,
1809                 * so just return everything and let the caller
1810                 * sort it out.
1811                 */
1812                return for_each_fullref_in("", cb, cb_data, broken);
1813        }
1814
1815        if (!filter->name_patterns[0]) {
1816                /* no patterns; we have to look at everything */
1817                return for_each_fullref_in("", cb, cb_data, broken);
1818        }
1819
1820        if (filter->name_patterns[1]) {
1821                /*
1822                 * multiple patterns; in theory this could still work as long
1823                 * as the patterns are disjoint. We'd just make multiple calls
1824                 * to for_each_ref(). But if they're not disjoint, we'd end up
1825                 * reporting the same ref multiple times. So let's punt on that
1826                 * for now.
1827                 */
1828                return for_each_fullref_in("", cb, cb_data, broken);
1829        }
1830
1831        find_longest_prefix(&prefix, filter->name_patterns[0]);
1832
1833        ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1834        strbuf_release(&prefix);
1835        return ret;
1836}
1837
1838/*
1839 * Given a ref (sha1, refname), check if the ref belongs to the array
1840 * of sha1s. If the given ref is a tag, check if the given tag points
1841 * at one of the sha1s in the given sha1 array.
1842 * the given sha1_array.
1843 * NEEDSWORK:
1844 * 1. Only a single level of inderection is obtained, we might want to
1845 * change this to account for multiple levels (e.g. annotated tags
1846 * pointing to annotated tags pointing to a commit.)
1847 * 2. As the refs are cached we might know what refname peels to without
1848 * the need to parse the object via parse_object(). peel_ref() might be a
1849 * more efficient alternative to obtain the pointee.
1850 */
1851static const struct object_id *match_points_at(struct oid_array *points_at,
1852                                               const struct object_id *oid,
1853                                               const char *refname)
1854{
1855        const struct object_id *tagged_oid = NULL;
1856        struct object *obj;
1857
1858        if (oid_array_lookup(points_at, oid) >= 0)
1859                return oid;
1860        obj = parse_object(the_repository, oid);
1861        if (!obj)
1862                die(_("malformed object at '%s'"), refname);
1863        if (obj->type == OBJ_TAG)
1864                tagged_oid = &((struct tag *)obj)->tagged->oid;
1865        if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
1866                return tagged_oid;
1867        return NULL;
1868}
1869
1870/*
1871 * Allocate space for a new ref_array_item and copy the name and oid to it.
1872 *
1873 * Callers can then fill in other struct members at their leisure.
1874 */
1875static struct ref_array_item *new_ref_array_item(const char *refname,
1876                                                 const struct object_id *oid)
1877{
1878        struct ref_array_item *ref;
1879
1880        FLEX_ALLOC_STR(ref, refname, refname);
1881        oidcpy(&ref->objectname, oid);
1882
1883        return ref;
1884}
1885
1886struct ref_array_item *ref_array_push(struct ref_array *array,
1887                                      const char *refname,
1888                                      const struct object_id *oid)
1889{
1890        struct ref_array_item *ref = new_ref_array_item(refname, oid);
1891
1892        ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1893        array->items[array->nr++] = ref;
1894
1895        return ref;
1896}
1897
1898static int ref_kind_from_refname(const char *refname)
1899{
1900        unsigned int i;
1901
1902        static struct {
1903                const char *prefix;
1904                unsigned int kind;
1905        } ref_kind[] = {
1906                { "refs/heads/" , FILTER_REFS_BRANCHES },
1907                { "refs/remotes/" , FILTER_REFS_REMOTES },
1908                { "refs/tags/", FILTER_REFS_TAGS}
1909        };
1910
1911        if (!strcmp(refname, "HEAD"))
1912                return FILTER_REFS_DETACHED_HEAD;
1913
1914        for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1915                if (starts_with(refname, ref_kind[i].prefix))
1916                        return ref_kind[i].kind;
1917        }
1918
1919        return FILTER_REFS_OTHERS;
1920}
1921
1922static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1923{
1924        if (filter->kind == FILTER_REFS_BRANCHES ||
1925            filter->kind == FILTER_REFS_REMOTES ||
1926            filter->kind == FILTER_REFS_TAGS)
1927                return filter->kind;
1928        return ref_kind_from_refname(refname);
1929}
1930
1931struct ref_filter_cbdata {
1932        struct ref_array *array;
1933        struct ref_filter *filter;
1934        struct contains_cache contains_cache;
1935        struct contains_cache no_contains_cache;
1936};
1937
1938/*
1939 * A call-back given to for_each_ref().  Filter refs and keep them for
1940 * later object processing.
1941 */
1942static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
1943{
1944        struct ref_filter_cbdata *ref_cbdata = cb_data;
1945        struct ref_filter *filter = ref_cbdata->filter;
1946        struct ref_array_item *ref;
1947        struct commit *commit = NULL;
1948        unsigned int kind;
1949
1950        if (flag & REF_BAD_NAME) {
1951                warning(_("ignoring ref with broken name %s"), refname);
1952                return 0;
1953        }
1954
1955        if (flag & REF_ISBROKEN) {
1956                warning(_("ignoring broken ref %s"), refname);
1957                return 0;
1958        }
1959
1960        /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1961        kind = filter_ref_kind(filter, refname);
1962        if (!(kind & filter->kind))
1963                return 0;
1964
1965        if (!filter_pattern_match(filter, refname))
1966                return 0;
1967
1968        if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
1969                return 0;
1970
1971        /*
1972         * A merge filter is applied on refs pointing to commits. Hence
1973         * obtain the commit using the 'oid' available and discard all
1974         * non-commits early. The actual filtering is done later.
1975         */
1976        if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
1977                commit = lookup_commit_reference_gently(the_repository, oid,
1978                                                        1);
1979                if (!commit)
1980                        return 0;
1981                /* We perform the filtering for the '--contains' option... */
1982                if (filter->with_commit &&
1983                    !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1984                        return 0;
1985                /* ...or for the `--no-contains' option */
1986                if (filter->no_commit &&
1987                    commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
1988                        return 0;
1989        }
1990
1991        /*
1992         * We do not open the object yet; sort may only need refname
1993         * to do its job and the resulting list may yet to be pruned
1994         * by maxcount logic.
1995         */
1996        ref = ref_array_push(ref_cbdata->array, refname, oid);
1997        ref->commit = commit;
1998        ref->flag = flag;
1999        ref->kind = kind;
2000
2001        return 0;
2002}
2003
2004/*  Free memory allocated for a ref_array_item */
2005static void free_array_item(struct ref_array_item *item)
2006{
2007        free((char *)item->symref);
2008        if (item->value) {
2009                free((char *)item->value->s);
2010                free(item->value);
2011        }
2012        free(item);
2013}
2014
2015/* Free all memory allocated for ref_array */
2016void ref_array_clear(struct ref_array *array)
2017{
2018        int i;
2019
2020        for (i = 0; i < used_atom_cnt; i++)
2021                free((char *)used_atom[i].name);
2022        FREE_AND_NULL(used_atom);
2023        used_atom_cnt = 0;
2024        for (i = 0; i < array->nr; i++)
2025                free_array_item(array->items[i]);
2026        FREE_AND_NULL(array->items);
2027        array->nr = array->alloc = 0;
2028}
2029
2030static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2031{
2032        struct rev_info revs;
2033        int i, old_nr;
2034        struct ref_filter *filter = ref_cbdata->filter;
2035        struct ref_array *array = ref_cbdata->array;
2036        struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2037
2038        repo_init_revisions(the_repository, &revs, NULL);
2039
2040        for (i = 0; i < array->nr; i++) {
2041                struct ref_array_item *item = array->items[i];
2042                add_pending_object(&revs, &item->commit->object, item->refname);
2043                to_clear[i] = item->commit;
2044        }
2045
2046        filter->merge_commit->object.flags |= UNINTERESTING;
2047        add_pending_object(&revs, &filter->merge_commit->object, "");
2048
2049        revs.limited = 1;
2050        if (prepare_revision_walk(&revs))
2051                die(_("revision walk setup failed"));
2052
2053        old_nr = array->nr;
2054        array->nr = 0;
2055
2056        for (i = 0; i < old_nr; i++) {
2057                struct ref_array_item *item = array->items[i];
2058                struct commit *commit = item->commit;
2059
2060                int is_merged = !!(commit->object.flags & UNINTERESTING);
2061
2062                if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2063                        array->items[array->nr++] = array->items[i];
2064                else
2065                        free_array_item(item);
2066        }
2067
2068        clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
2069        clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2070        free(to_clear);
2071}
2072
2073/*
2074 * API for filtering a set of refs. Based on the type of refs the user
2075 * has requested, we iterate through those refs and apply filters
2076 * as per the given ref_filter structure and finally store the
2077 * filtered refs in the ref_array structure.
2078 */
2079int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2080{
2081        struct ref_filter_cbdata ref_cbdata;
2082        int ret = 0;
2083        unsigned int broken = 0;
2084
2085        ref_cbdata.array = array;
2086        ref_cbdata.filter = filter;
2087
2088        if (type & FILTER_REFS_INCLUDE_BROKEN)
2089                broken = 1;
2090        filter->kind = type & FILTER_REFS_KIND_MASK;
2091
2092        init_contains_cache(&ref_cbdata.contains_cache);
2093        init_contains_cache(&ref_cbdata.no_contains_cache);
2094
2095        /*  Simple per-ref filtering */
2096        if (!filter->kind)
2097                die("filter_refs: invalid type");
2098        else {
2099                /*
2100                 * For common cases where we need only branches or remotes or tags,
2101                 * we only iterate through those refs. If a mix of refs is needed,
2102                 * we iterate over all refs and filter out required refs with the help
2103                 * of filter_ref_kind().
2104                 */
2105                if (filter->kind == FILTER_REFS_BRANCHES)
2106                        ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2107                else if (filter->kind == FILTER_REFS_REMOTES)
2108                        ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2109                else if (filter->kind == FILTER_REFS_TAGS)
2110                        ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2111                else if (filter->kind & FILTER_REFS_ALL)
2112                        ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
2113                if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2114                        head_ref(ref_filter_handler, &ref_cbdata);
2115        }
2116
2117        clear_contains_cache(&ref_cbdata.contains_cache);
2118        clear_contains_cache(&ref_cbdata.no_contains_cache);
2119
2120        /*  Filters that need revision walking */
2121        if (filter->merge_commit)
2122                do_merge_filter(&ref_cbdata);
2123
2124        return ret;
2125}
2126
2127static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2128{
2129        struct atom_value *va, *vb;
2130        int cmp;
2131        cmp_type cmp_type = used_atom[s->atom].type;
2132        int (*cmp_fn)(const char *, const char *);
2133        struct strbuf err = STRBUF_INIT;
2134
2135        if (get_ref_atom_value(a, s->atom, &va, &err))
2136                die("%s", err.buf);
2137        if (get_ref_atom_value(b, s->atom, &vb, &err))
2138                die("%s", err.buf);
2139        strbuf_release(&err);
2140        cmp_fn = s->ignore_case ? strcasecmp : strcmp;
2141        if (s->version)
2142                cmp = versioncmp(va->s, vb->s);
2143        else if (cmp_type == FIELD_STR)
2144                cmp = cmp_fn(va->s, vb->s);
2145        else {
2146                if (va->value < vb->value)
2147                        cmp = -1;
2148                else if (va->value == vb->value)
2149                        cmp = cmp_fn(a->refname, b->refname);
2150                else
2151                        cmp = 1;
2152        }
2153
2154        return (s->reverse) ? -cmp : cmp;
2155}
2156
2157static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
2158{
2159        struct ref_array_item *a = *((struct ref_array_item **)a_);
2160        struct ref_array_item *b = *((struct ref_array_item **)b_);
2161        struct ref_sorting *s;
2162
2163        for (s = ref_sorting; s; s = s->next) {
2164                int cmp = cmp_ref_sorting(s, a, b);
2165                if (cmp)
2166                        return cmp;
2167        }
2168        return 0;
2169}
2170
2171void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2172{
2173        QSORT_S(array->items, array->nr, compare_refs, sorting);
2174}
2175
2176static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
2177{
2178        struct strbuf *s = &state->stack->output;
2179
2180        while (*cp && (!ep || cp < ep)) {
2181                if (*cp == '%') {
2182                        if (cp[1] == '%')
2183                                cp++;
2184                        else {
2185                                int ch = hex2chr(cp + 1);
2186                                if (0 <= ch) {
2187                                        strbuf_addch(s, ch);
2188                                        cp += 3;
2189                                        continue;
2190                                }
2191                        }
2192                }
2193                strbuf_addch(s, *cp);
2194                cp++;
2195        }
2196}
2197
2198int format_ref_array_item(struct ref_array_item *info,
2199                           const struct ref_format *format,
2200                           struct strbuf *final_buf,
2201                           struct strbuf *error_buf)
2202{
2203        const char *cp, *sp, *ep;
2204        struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2205
2206        state.quote_style = format->quote_style;
2207        push_stack_element(&state.stack);
2208
2209        for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
2210                struct atom_value *atomv;
2211                int pos;
2212
2213                ep = strchr(sp, ')');
2214                if (cp < sp)
2215                        append_literal(cp, sp, &state);
2216                pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
2217                if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2218                    atomv->handler(atomv, &state, error_buf)) {
2219                        pop_stack_element(&state.stack);
2220                        return -1;
2221                }
2222        }
2223        if (*cp) {
2224                sp = cp + strlen(cp);
2225                append_literal(cp, sp, &state);
2226        }
2227        if (format->need_color_reset_at_eol) {
2228                struct atom_value resetv;
2229                resetv.s = GIT_COLOR_RESET;
2230                if (append_atom(&resetv, &state, error_buf)) {
2231                        pop_stack_element(&state.stack);
2232                        return -1;
2233                }
2234        }
2235        if (state.stack->prev) {
2236                pop_stack_element(&state.stack);
2237                return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
2238        }
2239        strbuf_addbuf(final_buf, &state.stack->output);
2240        pop_stack_element(&state.stack);
2241        return 0;
2242}
2243
2244void show_ref_array_item(struct ref_array_item *info,
2245                         const struct ref_format *format)
2246{
2247        struct strbuf final_buf = STRBUF_INIT;
2248        struct strbuf error_buf = STRBUF_INIT;
2249
2250        if (format_ref_array_item(info, format, &final_buf, &error_buf))
2251                die("%s", error_buf.buf);
2252        fwrite(final_buf.buf, 1, final_buf.len, stdout);
2253        strbuf_release(&error_buf);
2254        strbuf_release(&final_buf);
2255        putchar('\n');
2256}
2257
2258void pretty_print_ref(const char *name, const struct object_id *oid,
2259                      const struct ref_format *format)
2260{
2261        struct ref_array_item *ref_item;
2262        ref_item = new_ref_array_item(name, oid);
2263        ref_item->kind = ref_kind_from_refname(name);
2264        show_ref_array_item(ref_item, format);
2265        free_array_item(ref_item);
2266}
2267
2268static int parse_sorting_atom(const char *atom)
2269{
2270        /*
2271         * This parses an atom using a dummy ref_format, since we don't
2272         * actually care about the formatting details.
2273         */
2274        struct ref_format dummy = REF_FORMAT_INIT;
2275        const char *end = atom + strlen(atom);
2276        struct strbuf err = STRBUF_INIT;
2277        int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2278        if (res < 0)
2279                die("%s", err.buf);
2280        strbuf_release(&err);
2281        return res;
2282}
2283
2284/*  If no sorting option is given, use refname to sort as default */
2285struct ref_sorting *ref_default_sorting(void)
2286{
2287        static const char cstr_name[] = "refname";
2288
2289        struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2290
2291        sorting->next = NULL;
2292        sorting->atom = parse_sorting_atom(cstr_name);
2293        return sorting;
2294}
2295
2296void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
2297{
2298        struct ref_sorting *s;
2299
2300        s = xcalloc(1, sizeof(*s));
2301        s->next = *sorting_tail;
2302        *sorting_tail = s;
2303
2304        if (*arg == '-') {
2305                s->reverse = 1;
2306                arg++;
2307        }
2308        if (skip_prefix(arg, "version:", &arg) ||
2309            skip_prefix(arg, "v:", &arg))
2310                s->version = 1;
2311        s->atom = parse_sorting_atom(arg);
2312}
2313
2314int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2315{
2316        if (!arg) /* should --no-sort void the list ? */
2317                return -1;
2318        parse_ref_sorting(opt->value, arg);
2319        return 0;
2320}
2321
2322int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2323{
2324        struct ref_filter *rf = opt->value;
2325        struct object_id oid;
2326        int no_merged = starts_with(opt->long_name, "no");
2327
2328        if (rf->merge) {
2329                if (no_merged) {
2330                        return opterror(opt, "is incompatible with --merged", 0);
2331                } else {
2332                        return opterror(opt, "is incompatible with --no-merged", 0);
2333                }
2334        }
2335
2336        rf->merge = no_merged
2337                ? REF_FILTER_MERGED_OMIT
2338                : REF_FILTER_MERGED_INCLUDE;
2339
2340        if (get_oid(arg, &oid))
2341                die(_("malformed object name %s"), arg);
2342
2343        rf->merge_commit = lookup_commit_reference_gently(the_repository,
2344                                                          &oid, 0);
2345        if (!rf->merge_commit)
2346                return opterror(opt, "must point to a commit", 0);
2347
2348        return 0;
2349}