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