git
/
ref-filter.c
3592 строки · 96.4 Кб
1#define USE_THE_REPOSITORY_VARIABLE2
3#include "git-compat-util.h"4#include "environment.h"5#include "gettext.h"6#include "config.h"7#include "gpg-interface.h"8#include "hex.h"9#include "parse-options.h"10#include "run-command.h"11#include "refs.h"12#include "wildmatch.h"13#include "object-name.h"14#include "object-store-ll.h"15#include "oid-array.h"16#include "repository.h"17#include "commit.h"18#include "mailmap.h"19#include "ident.h"20#include "remote.h"21#include "color.h"22#include "tag.h"23#include "quote.h"24#include "ref-filter.h"25#include "revision.h"26#include "utf8.h"27#include "versioncmp.h"28#include "trailer.h"29#include "wt-status.h"30#include "commit-slab.h"31#include "commit-reach.h"32#include "worktree.h"33#include "hashmap.h"34
35static struct ref_msg {36const char *gone;37const char *ahead;38const char *behind;39const char *ahead_behind;40} msgs = {41/* Untranslated plumbing messages: */42"gone",43"ahead %d",44"behind %d",45"ahead %d, behind %d"46};47
48void setup_ref_filter_porcelain_msg(void)49{
50msgs.gone = _("gone");51msgs.ahead = _("ahead %d");52msgs.behind = _("behind %d");53msgs.ahead_behind = _("ahead %d, behind %d");54}
55
56typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;57typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;58typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;59
60struct align {61align_type position;62unsigned int width;63};64
65struct if_then_else {66cmp_status cmp_status;67const char *str;68unsigned int then_atom_seen : 1,69else_atom_seen : 1,70condition_satisfied : 1;71};72
73struct refname_atom {74enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;75int lstrip, rstrip;76};77
78static struct ref_trailer_buf {79struct string_list filter_list;80struct strbuf sepbuf;81struct strbuf kvsepbuf;82} ref_trailer_buf = {STRING_LIST_INIT_NODUP, STRBUF_INIT, STRBUF_INIT};83
84static struct expand_data {85struct object_id oid;86enum object_type type;87unsigned long size;88off_t disk_size;89struct object_id delta_base_oid;90void *content;91
92struct object_info info;93} oi, oi_deref;94
95struct ref_to_worktree_entry {96struct hashmap_entry ent;97struct worktree *wt; /* key is wt->head_ref */98};99
100static int ref_to_worktree_map_cmpfnc(const void *lookupdata UNUSED,101const struct hashmap_entry *eptr,102const struct hashmap_entry *kptr,103const void *keydata_aka_refname)104{
105const struct ref_to_worktree_entry *e, *k;106
107e = container_of(eptr, const struct ref_to_worktree_entry, ent);108k = container_of(kptr, const struct ref_to_worktree_entry, ent);109
110return strcmp(e->wt->head_ref,111keydata_aka_refname ? keydata_aka_refname : k->wt->head_ref);112}
113
114static struct ref_to_worktree_map {115struct hashmap map;116struct worktree **worktrees;117} ref_to_worktree_map;118
119/*
120* The enum atom_type is used as the index of valid_atom array.
121* In the atom parsing stage, it will be passed to used_atom.atom_type
122* as the identifier of the atom type. We can check the type of used_atom
123* entry by `if (used_atom[i].atom_type == ATOM_*)`.
124*/
125enum atom_type {126ATOM_REFNAME,127ATOM_OBJECTTYPE,128ATOM_OBJECTSIZE,129ATOM_OBJECTNAME,130ATOM_DELTABASE,131ATOM_TREE,132ATOM_PARENT,133ATOM_NUMPARENT,134ATOM_OBJECT,135ATOM_TYPE,136ATOM_TAG,137ATOM_AUTHOR,138ATOM_AUTHORNAME,139ATOM_AUTHOREMAIL,140ATOM_AUTHORDATE,141ATOM_COMMITTER,142ATOM_COMMITTERNAME,143ATOM_COMMITTEREMAIL,144ATOM_COMMITTERDATE,145ATOM_TAGGER,146ATOM_TAGGERNAME,147ATOM_TAGGEREMAIL,148ATOM_TAGGERDATE,149ATOM_CREATOR,150ATOM_CREATORDATE,151ATOM_DESCRIBE,152ATOM_SUBJECT,153ATOM_BODY,154ATOM_TRAILERS,155ATOM_CONTENTS,156ATOM_SIGNATURE,157ATOM_RAW,158ATOM_UPSTREAM,159ATOM_PUSH,160ATOM_SYMREF,161ATOM_FLAG,162ATOM_HEAD,163ATOM_COLOR,164ATOM_WORKTREEPATH,165ATOM_ALIGN,166ATOM_END,167ATOM_IF,168ATOM_THEN,169ATOM_ELSE,170ATOM_REST,171ATOM_AHEADBEHIND,172ATOM_ISBASE,173};174
175/*
176* An atom is a valid field atom listed below, possibly prefixed with
177* a "*" to denote deref_tag().
178*
179* We parse given format string and sort specifiers, and make a list
180* of properties that we need to extract out of objects. ref_array_item
181* structure will hold an array of values extracted that can be
182* indexed with the "atom number", which is an index into this
183* array.
184*/
185static struct used_atom {186enum atom_type atom_type;187const char *name;188cmp_type type;189info_source source;190union {191char color[COLOR_MAXLEN];192struct align align;193struct {194enum {195RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF196} option;197struct refname_atom refname;198unsigned int nobracket : 1, push : 1, push_remote : 1;199} remote_ref;200struct {201enum { C_BARE, C_BODY, C_BODY_DEP, C_LENGTH, C_LINES,202C_SIG, C_SUB, C_SUB_SANITIZE, C_TRAILERS } option;203struct process_trailer_options trailer_opts;204unsigned int nlines;205} contents;206struct {207enum { RAW_BARE, RAW_LENGTH } option;208} raw_data;209struct {210cmp_status cmp_status;211const char *str;212} if_then_else;213struct {214enum { O_FULL, O_LENGTH, O_SHORT } option;215unsigned int length;216} oid;217struct {218enum { O_SIZE, O_SIZE_DISK } option;219} objectsize;220struct {221enum { N_RAW, N_MAILMAP } option;222} name_option;223struct {224enum {225EO_RAW = 0,226EO_TRIM = 1<<0,227EO_LOCALPART = 1<<1,228EO_MAILMAP = 1<<2,229} option;230} email_option;231struct {232enum { S_BARE, S_GRADE, S_SIGNER, S_KEY,233S_FINGERPRINT, S_PRI_KEY_FP, S_TRUST_LEVEL } option;234} signature;235const char **describe_args;236struct refname_atom refname;237char *head;238} u;239} *used_atom;240static int used_atom_cnt, need_tagged, need_symref;241
242/*
243* Expand string, append it to strbuf *sb, then return error code ret.
244* Allow to save few lines of code.
245*/
246__attribute__((format (printf, 3, 4)))247static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)248{
249va_list ap;250va_start(ap, fmt);251strbuf_vaddf(sb, fmt, ap);252va_end(ap);253return ret;254}
255
256static int err_no_arg(struct strbuf *sb, const char *name)257{
258size_t namelen = strchrnul(name, ':') - name;259strbuf_addf(sb, _("%%(%.*s) does not take arguments"),260(int)namelen, name);261return -1;262}
263
264static int err_bad_arg(struct strbuf *sb, const char *name, const char *arg)265{
266size_t namelen = strchrnul(name, ':') - name;267strbuf_addf(sb, _("unrecognized %%(%.*s) argument: %s"),268(int)namelen, name, arg);269return -1;270}
271
272/*
273* Parse option of name "candidate" in the option string "to_parse" of
274* the form
275*
276* "candidate1[=val1],candidate2[=val2],candidate3[=val3],..."
277*
278* The remaining part of "to_parse" is stored in "end" (if we are
279* parsing the last candidate, then this is NULL) and the value of
280* the candidate is stored in "valuestart" and its length in "valuelen",
281* that is the portion after "=". Since it is possible for a "candidate"
282* to not have a value, in such cases, "valuestart" is set to point to
283* NULL and "valuelen" to 0.
284*
285* The function returns 1 on success. It returns 0 if we don't find
286* "candidate" in "to_parse" or we find "candidate" but it is followed
287* by more chars (for example, "candidatefoo"), that is, we don't find
288* an exact match.
289*
290* This function only does the above for one "candidate" at a time. So
291* it has to be called each time trying to parse a "candidate" in the
292* option string "to_parse".
293*/
294static int match_atom_arg_value(const char *to_parse, const char *candidate,295const char **end, const char **valuestart,296size_t *valuelen)297{
298const char *atom;299
300if (!skip_prefix(to_parse, candidate, &atom))301return 0; /* definitely not "candidate" */302
303if (*atom == '=') {304/* we just saw "candidate=" */305*valuestart = atom + 1;306atom = strchrnul(*valuestart, ',');307*valuelen = atom - *valuestart;308} else if (*atom != ',' && *atom != '\0') {309/* key begins with "candidate" but has more chars */310return 0;311} else {312/* just "candidate" without "=val" */313*valuestart = NULL;314*valuelen = 0;315}316
317/* atom points at either the ',' or NUL after this key[=val] */318if (*atom == ',')319atom++;320else if (*atom)321BUG("Why is *atom not NULL yet?");322
323*end = atom;324return 1;325}
326
327/*
328* Parse boolean option of name "candidate" in the option list "to_parse"
329* of the form
330*
331* "candidate1[=bool1],candidate2[=bool2],candidate3[=bool3],..."
332*
333* The remaining part of "to_parse" is stored in "end" (if we are parsing
334* the last candidate, then this is NULL) and the value (if given) is
335* parsed and stored in "val", so "val" always points to either 0 or 1.
336* If the value is not given, then "val" is set to point to 1.
337*
338* The boolean value is parsed using "git_parse_maybe_bool()", so the
339* accepted values are
340*
341* to set true - "1", "yes", "true"
342* to set false - "0", "no", "false"
343*
344* This function returns 1 on success. It returns 0 when we don't find
345* an exact match for "candidate" or when the boolean value given is
346* not valid.
347*/
348static int match_atom_bool_arg(const char *to_parse, const char *candidate,349const char **end, int *val)350{
351const char *argval;352char *strval;353size_t arglen;354int v;355
356if (!match_atom_arg_value(to_parse, candidate, end, &argval, &arglen))357return 0;358
359if (!argval) {360*val = 1;361return 1;362}363
364strval = xstrndup(argval, arglen);365v = git_parse_maybe_bool(strval);366free(strval);367
368if (v == -1)369return 0;370
371*val = v;372
373return 1;374}
375
376static int color_atom_parser(struct ref_format *format, struct used_atom *atom,377const char *color_value, struct strbuf *err)378{
379if (!color_value)380return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));381if (color_parse(color_value, atom->u.color) < 0)382return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),383color_value);384/*385* We check this after we've parsed the color, which lets us complain
386* about syntactically bogus color names even if they won't be used.
387*/
388if (!want_color(format->use_color))389color_parse("", atom->u.color);390return 0;391}
392
393static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,394const char *name, struct strbuf *err)395{
396if (!arg)397atom->option = R_NORMAL;398else if (!strcmp(arg, "short"))399atom->option = R_SHORT;400else if (skip_prefix(arg, "lstrip=", &arg) ||401skip_prefix(arg, "strip=", &arg)) {402atom->option = R_LSTRIP;403if (strtol_i(arg, 10, &atom->lstrip))404return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);405} else if (skip_prefix(arg, "rstrip=", &arg)) {406atom->option = R_RSTRIP;407if (strtol_i(arg, 10, &atom->rstrip))408return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);409} else410return err_bad_arg(err, name, arg);411return 0;412}
413
414static int remote_ref_atom_parser(struct ref_format *format UNUSED,415struct used_atom *atom,416const char *arg, struct strbuf *err)417{
418struct string_list params = STRING_LIST_INIT_DUP;419int i;420
421if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))422atom->u.remote_ref.push = 1;423
424if (!arg) {425atom->u.remote_ref.option = RR_REF;426return refname_atom_parser_internal(&atom->u.remote_ref.refname,427arg, atom->name, err);428}429
430atom->u.remote_ref.nobracket = 0;431string_list_split(¶ms, arg, ',', -1);432
433for (i = 0; i < params.nr; i++) {434const char *s = params.items[i].string;435
436if (!strcmp(s, "track"))437atom->u.remote_ref.option = RR_TRACK;438else if (!strcmp(s, "trackshort"))439atom->u.remote_ref.option = RR_TRACKSHORT;440else if (!strcmp(s, "nobracket"))441atom->u.remote_ref.nobracket = 1;442else if (!strcmp(s, "remotename")) {443atom->u.remote_ref.option = RR_REMOTE_NAME;444atom->u.remote_ref.push_remote = 1;445} else if (!strcmp(s, "remoteref")) {446atom->u.remote_ref.option = RR_REMOTE_REF;447atom->u.remote_ref.push_remote = 1;448} else {449atom->u.remote_ref.option = RR_REF;450if (refname_atom_parser_internal(&atom->u.remote_ref.refname,451arg, atom->name, err)) {452string_list_clear(¶ms, 0);453return -1;454}455}456}457
458string_list_clear(¶ms, 0);459return 0;460}
461
462static int objecttype_atom_parser(struct ref_format *format UNUSED,463struct used_atom *atom,464const char *arg, struct strbuf *err)465{
466if (arg)467return err_no_arg(err, "objecttype");468if (*atom->name == '*')469oi_deref.info.typep = &oi_deref.type;470else471oi.info.typep = &oi.type;472return 0;473}
474
475static int objectsize_atom_parser(struct ref_format *format UNUSED,476struct used_atom *atom,477const char *arg, struct strbuf *err)478{
479if (!arg) {480atom->u.objectsize.option = O_SIZE;481if (*atom->name == '*')482oi_deref.info.sizep = &oi_deref.size;483else484oi.info.sizep = &oi.size;485} else if (!strcmp(arg, "disk")) {486atom->u.objectsize.option = O_SIZE_DISK;487if (*atom->name == '*')488oi_deref.info.disk_sizep = &oi_deref.disk_size;489else490oi.info.disk_sizep = &oi.disk_size;491} else492return err_bad_arg(err, "objectsize", arg);493return 0;494}
495
496static int deltabase_atom_parser(struct ref_format *format UNUSED,497struct used_atom *atom,498const char *arg, struct strbuf *err)499{
500if (arg)501return err_no_arg(err, "deltabase");502if (*atom->name == '*')503oi_deref.info.delta_base_oid = &oi_deref.delta_base_oid;504else505oi.info.delta_base_oid = &oi.delta_base_oid;506return 0;507}
508
509static int body_atom_parser(struct ref_format *format UNUSED,510struct used_atom *atom,511const char *arg, struct strbuf *err)512{
513if (arg)514return err_no_arg(err, "body");515atom->u.contents.option = C_BODY_DEP;516return 0;517}
518
519static int subject_atom_parser(struct ref_format *format UNUSED,520struct used_atom *atom,521const char *arg, struct strbuf *err)522{
523if (!arg)524atom->u.contents.option = C_SUB;525else if (!strcmp(arg, "sanitize"))526atom->u.contents.option = C_SUB_SANITIZE;527else528return err_bad_arg(err, "subject", arg);529return 0;530}
531
532static int parse_signature_option(const char *arg)533{
534if (!arg)535return S_BARE;536else if (!strcmp(arg, "signer"))537return S_SIGNER;538else if (!strcmp(arg, "grade"))539return S_GRADE;540else if (!strcmp(arg, "key"))541return S_KEY;542else if (!strcmp(arg, "fingerprint"))543return S_FINGERPRINT;544else if (!strcmp(arg, "primarykeyfingerprint"))545return S_PRI_KEY_FP;546else if (!strcmp(arg, "trustlevel"))547return S_TRUST_LEVEL;548return -1;549}
550
551static int signature_atom_parser(struct ref_format *format UNUSED,552struct used_atom *atom,553const char *arg, struct strbuf *err)554{
555int opt = parse_signature_option(arg);556if (opt < 0)557return err_bad_arg(err, "signature", arg);558atom->u.signature.option = opt;559return 0;560}
561
562static int trailers_atom_parser(struct ref_format *format UNUSED,563struct used_atom *atom,564const char *arg, struct strbuf *err)565{
566atom->u.contents.trailer_opts.no_divider = 1;567
568if (arg) {569const char *argbuf = xstrfmt("%s)", arg);570char *invalid_arg = NULL;571
572if (format_set_trailers_options(&atom->u.contents.trailer_opts,573&ref_trailer_buf.filter_list,574&ref_trailer_buf.sepbuf,575&ref_trailer_buf.kvsepbuf,576&argbuf, &invalid_arg)) {577if (!invalid_arg)578strbuf_addf(err, _("expected %%(trailers:key=<value>)"));579else580strbuf_addf(err, _("unknown %%(trailers) argument: %s"), invalid_arg);581free((char *)invalid_arg);582return -1;583}584}585atom->u.contents.option = C_TRAILERS;586return 0;587}
588
589static int contents_atom_parser(struct ref_format *format, struct used_atom *atom,590const char *arg, struct strbuf *err)591{
592if (!arg)593atom->u.contents.option = C_BARE;594else if (!strcmp(arg, "body"))595atom->u.contents.option = C_BODY;596else if (!strcmp(arg, "size")) {597atom->type = FIELD_ULONG;598atom->u.contents.option = C_LENGTH;599} else if (!strcmp(arg, "signature"))600atom->u.contents.option = C_SIG;601else if (!strcmp(arg, "subject"))602atom->u.contents.option = C_SUB;603else if (!strcmp(arg, "trailers")) {604if (trailers_atom_parser(format, atom, NULL, err))605return -1;606} else if (skip_prefix(arg, "trailers:", &arg)) {607if (trailers_atom_parser(format, atom, arg, err))608return -1;609} else if (skip_prefix(arg, "lines=", &arg)) {610atom->u.contents.option = C_LINES;611if (strtoul_ui(arg, 10, &atom->u.contents.nlines))612return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);613} else614return err_bad_arg(err, "contents", arg);615return 0;616}
617
618static int describe_atom_option_parser(struct strvec *args, const char **arg,619struct strbuf *err)620{
621const char *argval;622size_t arglen = 0;623int optval = 0;624
625if (match_atom_bool_arg(*arg, "tags", arg, &optval)) {626if (!optval)627strvec_push(args, "--no-tags");628else629strvec_push(args, "--tags");630return 1;631}632
633if (match_atom_arg_value(*arg, "abbrev", arg, &argval, &arglen)) {634char *endptr;635
636if (!arglen)637return strbuf_addf_ret(err, -1,638_("argument expected for %s"),639"describe:abbrev");640if (strtol(argval, &endptr, 10) < 0)641return strbuf_addf_ret(err, -1,642_("positive value expected %s=%s"),643"describe:abbrev", argval);644if (endptr - argval != arglen)645return strbuf_addf_ret(err, -1,646_("cannot fully parse %s=%s"),647"describe:abbrev", argval);648
649strvec_pushf(args, "--abbrev=%.*s", (int)arglen, argval);650return 1;651}652
653if (match_atom_arg_value(*arg, "match", arg, &argval, &arglen)) {654if (!arglen)655return strbuf_addf_ret(err, -1,656_("value expected %s="),657"describe:match");658
659strvec_pushf(args, "--match=%.*s", (int)arglen, argval);660return 1;661}662
663if (match_atom_arg_value(*arg, "exclude", arg, &argval, &arglen)) {664if (!arglen)665return strbuf_addf_ret(err, -1,666_("value expected %s="),667"describe:exclude");668
669strvec_pushf(args, "--exclude=%.*s", (int)arglen, argval);670return 1;671}672
673return 0;674}
675
676static int describe_atom_parser(struct ref_format *format UNUSED,677struct used_atom *atom,678const char *arg, struct strbuf *err)679{
680struct strvec args = STRVEC_INIT;681
682for (;;) {683int found = 0;684const char *bad_arg = arg;685
686if (!arg || !*arg)687break;688
689found = describe_atom_option_parser(&args, &arg, err);690if (found < 0)691return found;692if (!found)693return err_bad_arg(err, "describe", bad_arg);694}695atom->u.describe_args = strvec_detach(&args);696return 0;697}
698
699static int raw_atom_parser(struct ref_format *format UNUSED,700struct used_atom *atom,701const char *arg, struct strbuf *err)702{
703if (!arg)704atom->u.raw_data.option = RAW_BARE;705else if (!strcmp(arg, "size")) {706atom->type = FIELD_ULONG;707atom->u.raw_data.option = RAW_LENGTH;708} else709return err_bad_arg(err, "raw", arg);710return 0;711}
712
713static int oid_atom_parser(struct ref_format *format UNUSED,714struct used_atom *atom,715const char *arg, struct strbuf *err)716{
717if (!arg)718atom->u.oid.option = O_FULL;719else if (!strcmp(arg, "short"))720atom->u.oid.option = O_SHORT;721else if (skip_prefix(arg, "short=", &arg)) {722atom->u.oid.option = O_LENGTH;723if (strtoul_ui(arg, 10, &atom->u.oid.length) ||724atom->u.oid.length == 0)725return strbuf_addf_ret(err, -1, _("positive value expected '%s' in %%(%s)"), arg, atom->name);726if (atom->u.oid.length < MINIMUM_ABBREV)727atom->u.oid.length = MINIMUM_ABBREV;728} else729return err_bad_arg(err, atom->name, arg);730return 0;731}
732
733static int person_name_atom_parser(struct ref_format *format UNUSED,734struct used_atom *atom,735const char *arg, struct strbuf *err)736{
737if (!arg)738atom->u.name_option.option = N_RAW;739else if (!strcmp(arg, "mailmap"))740atom->u.name_option.option = N_MAILMAP;741else742return err_bad_arg(err, atom->name, arg);743return 0;744}
745
746static int email_atom_option_parser(const char **arg)747{
748if (!*arg)749return EO_RAW;750if (skip_prefix(*arg, "trim", arg))751return EO_TRIM;752if (skip_prefix(*arg, "localpart", arg))753return EO_LOCALPART;754if (skip_prefix(*arg, "mailmap", arg))755return EO_MAILMAP;756return -1;757}
758
759static int person_email_atom_parser(struct ref_format *format UNUSED,760struct used_atom *atom,761const char *arg, struct strbuf *err)762{
763for (;;) {764int opt = email_atom_option_parser(&arg);765const char *bad_arg = arg;766
767if (opt < 0)768return err_bad_arg(err, atom->name, bad_arg);769atom->u.email_option.option |= opt;770
771if (!arg || !*arg)772break;773if (*arg == ',')774arg++;775else776return err_bad_arg(err, atom->name, bad_arg);777}778return 0;779}
780
781static int refname_atom_parser(struct ref_format *format UNUSED,782struct used_atom *atom,783const char *arg, struct strbuf *err)784{
785return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);786}
787
788static align_type parse_align_position(const char *s)789{
790if (!strcmp(s, "right"))791return ALIGN_RIGHT;792else if (!strcmp(s, "middle"))793return ALIGN_MIDDLE;794else if (!strcmp(s, "left"))795return ALIGN_LEFT;796return -1;797}
798
799static int align_atom_parser(struct ref_format *format UNUSED,800struct used_atom *atom,801const char *arg, struct strbuf *err)802{
803struct align *align = &atom->u.align;804struct string_list params = STRING_LIST_INIT_DUP;805int i;806unsigned int width = ~0U;807
808if (!arg)809return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));810
811align->position = ALIGN_LEFT;812
813string_list_split(¶ms, arg, ',', -1);814for (i = 0; i < params.nr; i++) {815const char *s = params.items[i].string;816int position;817
818if (skip_prefix(s, "position=", &s)) {819position = parse_align_position(s);820if (position < 0) {821strbuf_addf(err, _("unrecognized position:%s"), s);822string_list_clear(¶ms, 0);823return -1;824}825align->position = position;826} else if (skip_prefix(s, "width=", &s)) {827if (strtoul_ui(s, 10, &width)) {828strbuf_addf(err, _("unrecognized width:%s"), s);829string_list_clear(¶ms, 0);830return -1;831}832} else if (!strtoul_ui(s, 10, &width))833;834else if ((position = parse_align_position(s)) >= 0)835align->position = position;836else {837strbuf_addf(err, _("unrecognized %%(%s) argument: %s"), "align", s);838string_list_clear(¶ms, 0);839return -1;840}841}842
843if (width == ~0U) {844string_list_clear(¶ms, 0);845return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));846}847align->width = width;848string_list_clear(¶ms, 0);849return 0;850}
851
852static int if_atom_parser(struct ref_format *format UNUSED,853struct used_atom *atom,854const char *arg, struct strbuf *err)855{
856if (!arg) {857atom->u.if_then_else.cmp_status = COMPARE_NONE;858return 0;859} else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {860atom->u.if_then_else.cmp_status = COMPARE_EQUAL;861} else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {862atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;863} else864return err_bad_arg(err, "if", arg);865return 0;866}
867
868static int rest_atom_parser(struct ref_format *format UNUSED,869struct used_atom *atom UNUSED,870const char *arg, struct strbuf *err)871{
872if (arg)873return err_no_arg(err, "rest");874return 0;875}
876
877static int ahead_behind_atom_parser(struct ref_format *format,878struct used_atom *atom UNUSED,879const char *arg, struct strbuf *err)880{
881struct string_list_item *item;882
883if (!arg)884return strbuf_addf_ret(err, -1, _("expected format: %%(ahead-behind:<committish>)"));885
886item = string_list_append(&format->bases, arg);887item->util = lookup_commit_reference_by_name(arg);888if (!item->util)889die("failed to find '%s'", arg);890
891return 0;892}
893
894static int is_base_atom_parser(struct ref_format *format,895struct used_atom *atom UNUSED,896const char *arg, struct strbuf *err)897{
898struct string_list_item *item;899
900if (!arg)901return strbuf_addf_ret(err, -1, _("expected format: %%(is-base:<committish>)"));902
903item = string_list_append(&format->is_base_tips, arg);904item->util = lookup_commit_reference_by_name(arg);905if (!item->util)906die("failed to find '%s'", arg);907
908return 0;909}
910
911static int head_atom_parser(struct ref_format *format UNUSED,912struct used_atom *atom,913const char *arg, struct strbuf *err)914{
915if (arg)916return err_no_arg(err, "HEAD");917atom->u.head = refs_resolve_refdup(get_main_ref_store(the_repository),918"HEAD", RESOLVE_REF_READING, NULL,919NULL);920return 0;921}
922
923static struct {924const char *name;925info_source source;926cmp_type cmp_type;927int (*parser)(struct ref_format *format, struct used_atom *atom,928const char *arg, struct strbuf *err);929} valid_atom[] = {930[ATOM_REFNAME] = { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },931[ATOM_OBJECTTYPE] = { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },932[ATOM_OBJECTSIZE] = { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },933[ATOM_OBJECTNAME] = { "objectname", SOURCE_OTHER, FIELD_STR, oid_atom_parser },934[ATOM_DELTABASE] = { "deltabase", SOURCE_OTHER, FIELD_STR, deltabase_atom_parser },935[ATOM_TREE] = { "tree", SOURCE_OBJ, FIELD_STR, oid_atom_parser },936[ATOM_PARENT] = { "parent", SOURCE_OBJ, FIELD_STR, oid_atom_parser },937[ATOM_NUMPARENT] = { "numparent", SOURCE_OBJ, FIELD_ULONG },938[ATOM_OBJECT] = { "object", SOURCE_OBJ },939[ATOM_TYPE] = { "type", SOURCE_OBJ },940[ATOM_TAG] = { "tag", SOURCE_OBJ },941[ATOM_AUTHOR] = { "author", SOURCE_OBJ },942[ATOM_AUTHORNAME] = { "authorname", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },943[ATOM_AUTHOREMAIL] = { "authoremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },944[ATOM_AUTHORDATE] = { "authordate", SOURCE_OBJ, FIELD_TIME },945[ATOM_COMMITTER] = { "committer", SOURCE_OBJ },946[ATOM_COMMITTERNAME] = { "committername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },947[ATOM_COMMITTEREMAIL] = { "committeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },948[ATOM_COMMITTERDATE] = { "committerdate", SOURCE_OBJ, FIELD_TIME },949[ATOM_TAGGER] = { "tagger", SOURCE_OBJ },950[ATOM_TAGGERNAME] = { "taggername", SOURCE_OBJ, FIELD_STR, person_name_atom_parser },951[ATOM_TAGGEREMAIL] = { "taggeremail", SOURCE_OBJ, FIELD_STR, person_email_atom_parser },952[ATOM_TAGGERDATE] = { "taggerdate", SOURCE_OBJ, FIELD_TIME },953[ATOM_CREATOR] = { "creator", SOURCE_OBJ },954[ATOM_CREATORDATE] = { "creatordate", SOURCE_OBJ, FIELD_TIME },955[ATOM_DESCRIBE] = { "describe", SOURCE_OBJ, FIELD_STR, describe_atom_parser },956[ATOM_SUBJECT] = { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },957[ATOM_BODY] = { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },958[ATOM_TRAILERS] = { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },959[ATOM_CONTENTS] = { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },960[ATOM_SIGNATURE] = { "signature", SOURCE_OBJ, FIELD_STR, signature_atom_parser },961[ATOM_RAW] = { "raw", SOURCE_OBJ, FIELD_STR, raw_atom_parser },962[ATOM_UPSTREAM] = { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },963[ATOM_PUSH] = { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },964[ATOM_SYMREF] = { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },965[ATOM_FLAG] = { "flag", SOURCE_NONE },966[ATOM_HEAD] = { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },967[ATOM_COLOR] = { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },968[ATOM_WORKTREEPATH] = { "worktreepath", SOURCE_NONE },969[ATOM_ALIGN] = { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },970[ATOM_END] = { "end", SOURCE_NONE },971[ATOM_IF] = { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },972[ATOM_THEN] = { "then", SOURCE_NONE },973[ATOM_ELSE] = { "else", SOURCE_NONE },974[ATOM_REST] = { "rest", SOURCE_NONE, FIELD_STR, rest_atom_parser },975[ATOM_AHEADBEHIND] = { "ahead-behind", SOURCE_OTHER, FIELD_STR, ahead_behind_atom_parser },976[ATOM_ISBASE] = { "is-base", SOURCE_OTHER, FIELD_STR, is_base_atom_parser },977/*978* Please update $__git_ref_fieldlist in git-completion.bash
979* when you add new atoms
980*/
981};982
983#define REF_FORMATTING_STATE_INIT { 0 }984
985struct ref_formatting_stack {986struct ref_formatting_stack *prev;987struct strbuf output;988void (*at_end)(struct ref_formatting_stack **stack);989void *at_end_data;990};991
992struct ref_formatting_state {993int quote_style;994struct ref_formatting_stack *stack;995};996
997struct atom_value {998const char *s;999ssize_t s_size;1000int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,1001struct strbuf *err);1002uintmax_t value; /* used for sorting when not FIELD_STR */1003struct used_atom *atom;1004};1005
1006#define ATOM_SIZE_UNSPECIFIED (-1)1007
1008#define ATOM_VALUE_INIT { \1009.s_size = ATOM_SIZE_UNSPECIFIED \1010}
1011
1012/*
1013* Used to parse format string and sort specifiers
1014*/
1015static int parse_ref_filter_atom(struct ref_format *format,1016const char *atom, const char *ep,1017struct strbuf *err)1018{
1019const char *sp;1020const char *arg;1021int i, at, atom_len;1022
1023sp = atom;1024if (*sp == '*' && sp < ep)1025sp++; /* deref */1026if (ep <= sp)1027return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),1028(int)(ep-atom), atom);1029
1030/*1031* If the atom name has a colon, strip it and everything after
1032* it off - it specifies the format for this entry, and
1033* shouldn't be used for checking against the valid_atom
1034* table.
1035*/
1036arg = memchr(sp, ':', ep - sp);1037atom_len = (arg ? arg : ep) - sp;1038
1039/* Do we have the atom already used elsewhere? */1040for (i = 0; i < used_atom_cnt; i++) {1041int len = strlen(used_atom[i].name);1042if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))1043return i;1044}1045
1046/* Is the atom a valid one? */1047for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {1048int len = strlen(valid_atom[i].name);1049if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))1050break;1051}1052
1053if (ARRAY_SIZE(valid_atom) <= i)1054return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),1055(int)(ep-atom), atom);1056if (valid_atom[i].source != SOURCE_NONE && !have_git_dir())1057return strbuf_addf_ret(err, -1,1058_("not a git repository, but the field '%.*s' requires access to object data"),1059(int)(ep-atom), atom);1060
1061/* Add it in, including the deref prefix */1062at = used_atom_cnt;1063used_atom_cnt++;1064REALLOC_ARRAY(used_atom, used_atom_cnt);1065used_atom[at].atom_type = i;1066used_atom[at].name = xmemdupz(atom, ep - atom);1067used_atom[at].type = valid_atom[i].cmp_type;1068used_atom[at].source = valid_atom[i].source;1069if (used_atom[at].source == SOURCE_OBJ) {1070if (*atom == '*')1071oi_deref.info.contentp = &oi_deref.content;1072else1073oi.info.contentp = &oi.content;1074}1075if (arg) {1076arg = used_atom[at].name + (arg - atom) + 1;1077if (!*arg) {1078/*1079* Treat empty sub-arguments list as NULL (i.e.,
1080* "%(atom:)" is equivalent to "%(atom)").
1081*/
1082arg = NULL;1083}1084}1085memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));1086if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))1087return -1;1088if (*atom == '*')1089need_tagged = 1;1090if (i == ATOM_SYMREF)1091need_symref = 1;1092return at;1093}
1094
1095static void quote_formatting(struct strbuf *s, const char *str, ssize_t len, int quote_style)1096{
1097switch (quote_style) {1098case QUOTE_NONE:1099if (len < 0)1100strbuf_addstr(s, str);1101else1102strbuf_add(s, str, len);1103break;1104case QUOTE_SHELL:1105sq_quote_buf(s, str);1106break;1107case QUOTE_PERL:1108if (len < 0)1109perl_quote_buf(s, str);1110else1111perl_quote_buf_with_len(s, str, len);1112break;1113case QUOTE_PYTHON:1114python_quote_buf(s, str);1115break;1116case QUOTE_TCL:1117tcl_quote_buf(s, str);1118break;1119}1120}
1121
1122static int append_atom(struct atom_value *v, struct ref_formatting_state *state,1123struct strbuf *err UNUSED)1124{
1125/*1126* Quote formatting is only done when the stack has a single
1127* element. Otherwise quote formatting is done on the
1128* element's entire output strbuf when the %(end) atom is
1129* encountered.
1130*/
1131if (!state->stack->prev)1132quote_formatting(&state->stack->output, v->s, v->s_size, state->quote_style);1133else if (v->s_size < 0)1134strbuf_addstr(&state->stack->output, v->s);1135else1136strbuf_add(&state->stack->output, v->s, v->s_size);1137return 0;1138}
1139
1140static void push_stack_element(struct ref_formatting_stack **stack)1141{
1142struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));1143
1144strbuf_init(&s->output, 0);1145s->prev = *stack;1146*stack = s;1147}
1148
1149static void pop_stack_element(struct ref_formatting_stack **stack)1150{
1151struct ref_formatting_stack *current = *stack;1152struct ref_formatting_stack *prev = current->prev;1153
1154if (prev)1155strbuf_addbuf(&prev->output, ¤t->output);1156strbuf_release(¤t->output);1157free(current);1158*stack = prev;1159}
1160
1161static void end_align_handler(struct ref_formatting_stack **stack)1162{
1163struct ref_formatting_stack *cur = *stack;1164struct align *align = (struct align *)cur->at_end_data;1165struct strbuf s = STRBUF_INIT;1166
1167strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);1168strbuf_swap(&cur->output, &s);1169strbuf_release(&s);1170}
1171
1172static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,1173struct strbuf *err UNUSED)1174{
1175struct ref_formatting_stack *new_stack;1176
1177push_stack_element(&state->stack);1178new_stack = state->stack;1179new_stack->at_end = end_align_handler;1180new_stack->at_end_data = &atomv->atom->u.align;1181return 0;1182}
1183
1184static void if_then_else_handler(struct ref_formatting_stack **stack)1185{
1186struct ref_formatting_stack *cur = *stack;1187struct ref_formatting_stack *prev = cur->prev;1188struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;1189
1190if (!if_then_else->then_atom_seen)1191die(_("format: %%(%s) atom used without a %%(%s) atom"), "if", "then");1192
1193if (if_then_else->else_atom_seen) {1194/*1195* There is an %(else) atom: we need to drop one state from the
1196* stack, either the %(else) branch if the condition is satisfied, or
1197* the %(then) branch if it isn't.
1198*/
1199if (if_then_else->condition_satisfied) {1200strbuf_reset(&cur->output);1201pop_stack_element(&cur);1202} else {1203strbuf_swap(&cur->output, &prev->output);1204strbuf_reset(&cur->output);1205pop_stack_element(&cur);1206}1207} else if (!if_then_else->condition_satisfied) {1208/*1209* No %(else) atom: just drop the %(then) branch if the
1210* condition is not satisfied.
1211*/
1212strbuf_reset(&cur->output);1213}1214
1215*stack = cur;1216free(if_then_else);1217}
1218
1219static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,1220struct strbuf *err UNUSED)1221{
1222struct ref_formatting_stack *new_stack;1223struct if_then_else *if_then_else = xcalloc(1,1224sizeof(struct if_then_else));1225
1226if_then_else->str = atomv->atom->u.if_then_else.str;1227if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;1228
1229push_stack_element(&state->stack);1230new_stack = state->stack;1231new_stack->at_end = if_then_else_handler;1232new_stack->at_end_data = if_then_else;1233return 0;1234}
1235
1236static int is_empty(struct strbuf *buf)1237{
1238const char *cur = buf->buf;1239const char *end = buf->buf + buf->len;1240
1241while (cur != end && (isspace(*cur)))1242cur++;1243
1244return cur == end;1245}1246
1247static int then_atom_handler(struct atom_value *atomv UNUSED,1248struct ref_formatting_state *state,1249struct strbuf *err)1250{
1251struct ref_formatting_stack *cur = state->stack;1252struct if_then_else *if_then_else = NULL;1253size_t str_len = 0;1254
1255if (cur->at_end == if_then_else_handler)1256if_then_else = (struct if_then_else *)cur->at_end_data;1257if (!if_then_else)1258return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "then", "if");1259if (if_then_else->then_atom_seen)1260return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));1261if (if_then_else->else_atom_seen)1262return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));1263if_then_else->then_atom_seen = 1;1264if (if_then_else->str)1265str_len = strlen(if_then_else->str);1266/*1267* If the 'equals' or 'notequals' attribute is used then
1268* perform the required comparison. If not, only non-empty
1269* strings satisfy the 'if' condition.
1270*/
1271if (if_then_else->cmp_status == COMPARE_EQUAL) {1272if (str_len == cur->output.len &&1273!memcmp(if_then_else->str, cur->output.buf, cur->output.len))1274if_then_else->condition_satisfied = 1;1275} else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {1276if (str_len != cur->output.len ||1277memcmp(if_then_else->str, cur->output.buf, cur->output.len))1278if_then_else->condition_satisfied = 1;1279} else if (cur->output.len && !is_empty(&cur->output))1280if_then_else->condition_satisfied = 1;1281strbuf_reset(&cur->output);1282return 0;1283}
1284
1285static int else_atom_handler(struct atom_value *atomv UNUSED,1286struct ref_formatting_state *state,1287struct strbuf *err)1288{
1289struct ref_formatting_stack *prev = state->stack;1290struct if_then_else *if_then_else = NULL;1291
1292if (prev->at_end == if_then_else_handler)1293if_then_else = (struct if_then_else *)prev->at_end_data;1294if (!if_then_else)1295return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "if");1296if (!if_then_else->then_atom_seen)1297return strbuf_addf_ret(err, -1, _("format: %%(%s) atom used without a %%(%s) atom"), "else", "then");1298if (if_then_else->else_atom_seen)1299return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));1300if_then_else->else_atom_seen = 1;1301push_stack_element(&state->stack);1302state->stack->at_end_data = prev->at_end_data;1303state->stack->at_end = prev->at_end;1304return 0;1305}
1306
1307static int end_atom_handler(struct atom_value *atomv UNUSED,1308struct ref_formatting_state *state,1309struct strbuf *err)1310{
1311struct ref_formatting_stack *current = state->stack;1312struct strbuf s = STRBUF_INIT;1313
1314if (!current->at_end)1315return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));1316current->at_end(&state->stack);1317
1318/* Stack may have been popped within at_end(), hence reset the current pointer */1319current = state->stack;1320
1321/*1322* Perform quote formatting when the stack element is that of
1323* a supporting atom. If nested then perform quote formatting
1324* only on the topmost supporting atom.
1325*/
1326if (!current->prev->prev) {1327quote_formatting(&s, current->output.buf, current->output.len, state->quote_style);1328strbuf_swap(¤t->output, &s);1329}1330strbuf_release(&s);1331pop_stack_element(&state->stack);1332return 0;1333}
1334
1335/*
1336* In a format string, find the next occurrence of %(atom).
1337*/
1338static const char *find_next(const char *cp)1339{
1340while (*cp) {1341if (*cp == '%') {1342/*1343* %( is the start of an atom;
1344* %% is a quoted per-cent.
1345*/
1346if (cp[1] == '(')1347return cp;1348else if (cp[1] == '%')1349cp++; /* skip over two % */1350/* otherwise this is a singleton, literal % */1351}1352cp++;1353}1354return NULL;1355}
1356
1357static int reject_atom(enum atom_type atom_type)1358{
1359return atom_type == ATOM_REST;1360}
1361
1362/*
1363* Make sure the format string is well formed, and parse out
1364* the used atoms.
1365*/
1366int verify_ref_format(struct ref_format *format)1367{
1368const char *cp, *sp;1369
1370format->need_color_reset_at_eol = 0;1371for (cp = format->format; *cp && (sp = find_next(cp)); ) {1372struct strbuf err = STRBUF_INIT;1373const char *color, *ep = strchr(sp, ')');1374int at;1375
1376if (!ep)1377return error(_("malformed format string %s"), sp);1378/* sp points at "%(" and ep points at the closing ")" */1379at = parse_ref_filter_atom(format, sp + 2, ep, &err);1380if (at < 0)1381die("%s", err.buf);1382if (reject_atom(used_atom[at].atom_type))1383die(_("this command reject atom %%(%.*s)"), (int)(ep - sp - 2), sp + 2);1384
1385if ((format->quote_style == QUOTE_PYTHON ||1386format->quote_style == QUOTE_SHELL ||1387format->quote_style == QUOTE_TCL) &&1388used_atom[at].atom_type == ATOM_RAW &&1389used_atom[at].u.raw_data.option == RAW_BARE)1390die(_("--format=%.*s cannot be used with "1391"--python, --shell, --tcl"), (int)(ep - sp - 2), sp + 2);1392cp = ep + 1;1393
1394if (skip_prefix(used_atom[at].name, "color:", &color))1395format->need_color_reset_at_eol = !!strcmp(color, "reset");1396strbuf_release(&err);1397}1398if (format->need_color_reset_at_eol && !want_color(format->use_color))1399format->need_color_reset_at_eol = 0;1400return 0;1401}
1402
1403static const char *do_grab_oid(const char *field, const struct object_id *oid,1404struct used_atom *atom)1405{
1406switch (atom->u.oid.option) {1407case O_FULL:1408return oid_to_hex(oid);1409case O_LENGTH:1410return repo_find_unique_abbrev(the_repository, oid,1411atom->u.oid.length);1412case O_SHORT:1413return repo_find_unique_abbrev(the_repository, oid,1414DEFAULT_ABBREV);1415default:1416BUG("unknown %%(%s) option", field);1417}1418}
1419
1420static int grab_oid(const char *name, const char *field, const struct object_id *oid,1421struct atom_value *v, struct used_atom *atom)1422{
1423if (starts_with(name, field)) {1424v->s = xstrdup(do_grab_oid(field, oid, atom));1425return 1;1426}1427return 0;1428}
1429
1430/* See grab_values */
1431static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)1432{
1433int i;1434
1435for (i = 0; i < used_atom_cnt; i++) {1436const char *name = used_atom[i].name;1437enum atom_type atom_type = used_atom[i].atom_type;1438struct atom_value *v = &val[i];1439if (!!deref != (*name == '*'))1440continue;1441if (deref)1442name++;1443if (atom_type == ATOM_OBJECTTYPE)1444v->s = xstrdup(type_name(oi->type));1445else if (atom_type == ATOM_OBJECTSIZE) {1446if (used_atom[i].u.objectsize.option == O_SIZE_DISK) {1447v->value = oi->disk_size;1448v->s = xstrfmt("%"PRIuMAX, (uintmax_t)oi->disk_size);1449} else if (used_atom[i].u.objectsize.option == O_SIZE) {1450v->value = oi->size;1451v->s = xstrfmt("%"PRIuMAX , (uintmax_t)oi->size);1452}1453} else if (atom_type == ATOM_DELTABASE)1454v->s = xstrdup(oid_to_hex(&oi->delta_base_oid));1455else if (atom_type == ATOM_OBJECTNAME && deref)1456grab_oid(name, "objectname", &oi->oid, v, &used_atom[i]);1457}1458}
1459
1460/* See grab_values */
1461static void grab_tag_values(struct atom_value *val, int deref, struct object *obj)1462{
1463int i;1464struct tag *tag = (struct tag *) obj;1465
1466for (i = 0; i < used_atom_cnt; i++) {1467const char *name = used_atom[i].name;1468enum atom_type atom_type = used_atom[i].atom_type;1469struct atom_value *v = &val[i];1470if (!!deref != (*name == '*'))1471continue;1472if (deref)1473name++;1474if (atom_type == ATOM_TAG)1475v->s = xstrdup(tag->tag);1476else if (atom_type == ATOM_TYPE && tag->tagged)1477v->s = xstrdup(type_name(tag->tagged->type));1478else if (atom_type == ATOM_OBJECT && tag->tagged)1479v->s = xstrdup(oid_to_hex(&tag->tagged->oid));1480}1481}
1482
1483/* See grab_values */
1484static void grab_commit_values(struct atom_value *val, int deref, struct object *obj)1485{
1486int i;1487struct commit *commit = (struct commit *) obj;1488
1489for (i = 0; i < used_atom_cnt; i++) {1490const char *name = used_atom[i].name;1491enum atom_type atom_type = used_atom[i].atom_type;1492struct atom_value *v = &val[i];1493if (!!deref != (*name == '*'))1494continue;1495if (deref)1496name++;1497if (atom_type == ATOM_TREE &&1498grab_oid(name, "tree", get_commit_tree_oid(commit), v, &used_atom[i]))1499continue;1500if (atom_type == ATOM_NUMPARENT) {1501v->value = commit_list_count(commit->parents);1502v->s = xstrfmt("%lu", (unsigned long)v->value);1503}1504else if (atom_type == ATOM_PARENT) {1505struct commit_list *parents;1506struct strbuf s = STRBUF_INIT;1507for (parents = commit->parents; parents; parents = parents->next) {1508struct object_id *oid = &parents->item->object.oid;1509if (parents != commit->parents)1510strbuf_addch(&s, ' ');1511strbuf_addstr(&s, do_grab_oid("parent", oid, &used_atom[i]));1512}1513v->s = strbuf_detach(&s, NULL);1514}1515}1516}
1517
1518static const char *find_wholine(const char *who, int wholen, const char *buf)1519{
1520const char *eol;1521while (*buf) {1522if (!strncmp(buf, who, wholen) &&1523buf[wholen] == ' ')1524return buf + wholen + 1;1525eol = strchr(buf, '\n');1526if (!eol)1527return "";1528eol++;1529if (*eol == '\n')1530return ""; /* end of header */1531buf = eol;1532}1533return "";1534}
1535
1536static const char *copy_line(const char *buf)1537{
1538const char *eol = strchrnul(buf, '\n');1539return xmemdupz(buf, eol - buf);1540}
1541
1542static const char *copy_name(const char *buf)1543{
1544const char *cp;1545for (cp = buf; *cp && *cp != '\n'; cp++) {1546if (starts_with(cp, " <"))1547return xmemdupz(buf, cp - buf);1548}1549return xstrdup("");1550}
1551
1552static const char *find_end_of_email(const char *email, int opt)1553{
1554const char *eoemail;1555
1556if (opt & EO_LOCALPART) {1557eoemail = strchr(email, '@');1558if (eoemail)1559return eoemail;1560return strchr(email, '>');1561}1562
1563if (opt & EO_TRIM)1564return strchr(email, '>');1565
1566/*1567* The option here is either the raw email option or the raw
1568* mailmap option (that is EO_RAW or EO_MAILMAP). In such cases,
1569* we directly grab the whole email including the closing
1570* angle brackets.
1571*
1572* If EO_MAILMAP was set with any other option (that is either
1573* EO_TRIM or EO_LOCALPART), we already grab the end of email
1574* above.
1575*/
1576eoemail = strchr(email, '>');1577if (eoemail)1578eoemail++;1579return eoemail;1580}
1581
1582static const char *copy_email(const char *buf, struct used_atom *atom)1583{
1584const char *email = strchr(buf, '<');1585const char *eoemail;1586int opt = atom->u.email_option.option;1587
1588if (!email)1589return xstrdup("");1590
1591if (opt & (EO_LOCALPART | EO_TRIM))1592email++;1593
1594eoemail = find_end_of_email(email, opt);1595if (!eoemail)1596return xstrdup("");1597return xmemdupz(email, eoemail - email);1598}
1599
1600static char *copy_subject(const char *buf, unsigned long len)1601{
1602struct strbuf sb = STRBUF_INIT;1603int i;1604
1605for (i = 0; i < len; i++) {1606if (buf[i] == '\r' && i + 1 < len && buf[i + 1] == '\n')1607continue; /* ignore CR in CRLF */1608
1609if (buf[i] == '\n')1610strbuf_addch(&sb, ' ');1611else1612strbuf_addch(&sb, buf[i]);1613}1614return strbuf_detach(&sb, NULL);1615}
1616
1617static void grab_date(const char *buf, struct atom_value *v, const char *atomname)1618{
1619const char *eoemail = strstr(buf, "> ");1620char *zone;1621timestamp_t timestamp;1622long tz;1623struct date_mode date_mode = DATE_MODE_INIT;1624const char *formatp;1625
1626/*1627* We got here because atomname ends in "date" or "date<something>";
1628* it's not possible that <something> is not ":<format>" because
1629* parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1630* ":" means no format is specified, and use the default.
1631*/
1632formatp = strchr(atomname, ':');1633if (formatp) {1634formatp++;1635parse_date_format(formatp, &date_mode);1636
1637/*1638* If this is a sort field and a format was specified, we'll
1639* want to compare formatted date by string value.
1640*/
1641v->atom->type = FIELD_STR;1642}1643
1644if (!eoemail)1645goto bad;1646timestamp = parse_timestamp(eoemail + 2, &zone, 10);1647if (timestamp == TIME_MAX)1648goto bad;1649errno = 0;1650tz = strtol(zone, NULL, 10);1651if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)1652goto bad;1653v->s = xstrdup(show_date(timestamp, tz, date_mode));1654v->value = timestamp;1655date_mode_release(&date_mode);1656return;1657bad:1658v->s = xstrdup("");1659v->value = 0;1660}
1661
1662static struct string_list mailmap = STRING_LIST_INIT_NODUP;1663
1664/* See grab_values */
1665static void grab_person(const char *who, struct atom_value *val, int deref, void *buf)1666{
1667int i;1668int wholen = strlen(who);1669const char *wholine = NULL;1670const char *headers[] = { "author ", "committer ",1671"tagger ", NULL };1672
1673for (i = 0; i < used_atom_cnt; i++) {1674struct used_atom *atom = &used_atom[i];1675const char *name = atom->name;1676struct atom_value *v = &val[i];1677struct strbuf mailmap_buf = STRBUF_INIT;1678
1679if (!!deref != (*name == '*'))1680continue;1681if (deref)1682name++;1683if (strncmp(who, name, wholen))1684continue;1685if (name[wholen] != 0 &&1686!starts_with(name + wholen, "name") &&1687!starts_with(name + wholen, "email") &&1688!starts_with(name + wholen, "date"))1689continue;1690
1691if ((starts_with(name + wholen, "name") &&1692(atom->u.name_option.option == N_MAILMAP)) ||1693(starts_with(name + wholen, "email") &&1694(atom->u.email_option.option & EO_MAILMAP))) {1695if (!mailmap.items)1696read_mailmap(&mailmap);1697strbuf_addstr(&mailmap_buf, buf);1698apply_mailmap_to_header(&mailmap_buf, headers, &mailmap);1699wholine = find_wholine(who, wholen, mailmap_buf.buf);1700} else {1701wholine = find_wholine(who, wholen, buf);1702}1703
1704if (!wholine)1705return; /* no point looking for it */1706if (name[wholen] == 0)1707v->s = copy_line(wholine);1708else if (starts_with(name + wholen, "name"))1709v->s = copy_name(wholine);1710else if (starts_with(name + wholen, "email"))1711v->s = copy_email(wholine, &used_atom[i]);1712else if (starts_with(name + wholen, "date"))1713grab_date(wholine, v, name);1714
1715strbuf_release(&mailmap_buf);1716}1717
1718/*1719* For a tag or a commit object, if "creator" or "creatordate" is
1720* requested, do something special.
1721*/
1722if (strcmp(who, "tagger") && strcmp(who, "committer"))1723return; /* "author" for commit object is not wanted */1724if (!wholine)1725wholine = find_wholine(who, wholen, buf);1726if (!wholine)1727return;1728for (i = 0; i < used_atom_cnt; i++) {1729const char *name = used_atom[i].name;1730enum atom_type atom_type = used_atom[i].atom_type;1731struct atom_value *v = &val[i];1732if (!!deref != (*name == '*'))1733continue;1734if (deref)1735name++;1736
1737if (atom_type == ATOM_CREATORDATE)1738grab_date(wholine, v, name);1739else if (atom_type == ATOM_CREATOR)1740v->s = copy_line(wholine);1741}1742}
1743
1744static void grab_signature(struct atom_value *val, int deref, struct object *obj)1745{
1746int i;1747struct commit *commit = (struct commit *) obj;1748struct signature_check sigc = { 0 };1749int signature_checked = 0;1750
1751for (i = 0; i < used_atom_cnt; i++) {1752struct used_atom *atom = &used_atom[i];1753const char *name = atom->name;1754struct atom_value *v = &val[i];1755int opt;1756
1757if (!!deref != (*name == '*'))1758continue;1759if (deref)1760name++;1761
1762if (!skip_prefix(name, "signature", &name) ||1763(*name && *name != ':'))1764continue;1765if (!*name)1766name = NULL;1767else1768name++;1769
1770opt = parse_signature_option(name);1771if (opt < 0)1772continue;1773
1774if (!signature_checked) {1775check_commit_signature(commit, &sigc);1776signature_checked = 1;1777}1778
1779switch (opt) {1780case S_BARE:1781v->s = xstrdup(sigc.output ? sigc.output: "");1782break;1783case S_SIGNER:1784v->s = xstrdup(sigc.signer ? sigc.signer : "");1785break;1786case S_GRADE:1787switch (sigc.result) {1788case 'G':1789switch (sigc.trust_level) {1790case TRUST_UNDEFINED:1791case TRUST_NEVER:1792v->s = xstrfmt("%c", (char)'U');1793break;1794default:1795v->s = xstrfmt("%c", (char)'G');1796break;1797}1798break;1799case 'B':1800case 'E':1801case 'N':1802case 'X':1803case 'Y':1804case 'R':1805v->s = xstrfmt("%c", (char)sigc.result);1806break;1807}1808break;1809case S_KEY:1810v->s = xstrdup(sigc.key ? sigc.key : "");1811break;1812case S_FINGERPRINT:1813v->s = xstrdup(sigc.fingerprint ?1814sigc.fingerprint : "");1815break;1816case S_PRI_KEY_FP:1817v->s = xstrdup(sigc.primary_key_fingerprint ?1818sigc.primary_key_fingerprint : "");1819break;1820case S_TRUST_LEVEL:1821v->s = xstrdup(gpg_trust_level_to_str(sigc.trust_level));1822break;1823}1824}1825
1826if (signature_checked)1827signature_check_clear(&sigc);1828}
1829
1830static void find_subpos(const char *buf,1831const char **sub, size_t *sublen,1832const char **body, size_t *bodylen,1833size_t *nonsiglen,1834const char **sig, size_t *siglen)1835{
1836struct strbuf payload = STRBUF_INIT;1837struct strbuf signature = STRBUF_INIT;1838const char *eol;1839const char *end = buf + strlen(buf);1840const char *sigstart;1841
1842/* parse signature first; we might not even have a subject line */1843parse_signature(buf, end - buf, &payload, &signature);1844strbuf_release(&payload);1845
1846/* skip past header until we hit empty line */1847while (*buf && *buf != '\n') {1848eol = strchrnul(buf, '\n');1849if (*eol)1850eol++;1851buf = eol;1852}1853/* skip any empty lines */1854while (*buf == '\n')1855buf++;1856*sig = strbuf_detach(&signature, siglen);1857sigstart = buf + parse_signed_buffer(buf, strlen(buf));1858
1859/* subject is first non-empty line */1860*sub = buf;1861/* subject goes to first empty line before signature begins */1862if ((eol = strstr(*sub, "\n\n")) ||1863(eol = strstr(*sub, "\r\n\r\n"))) {1864eol = eol < sigstart ? eol : sigstart;1865} else {1866/* treat whole message as subject */1867eol = sigstart;1868}1869buf = eol;1870*sublen = buf - *sub;1871/* drop trailing newline, if present */1872while (*sublen && ((*sub)[*sublen - 1] == '\n' ||1873(*sub)[*sublen - 1] == '\r'))1874*sublen -= 1;1875
1876/* skip any empty lines */1877while (*buf == '\n' || *buf == '\r')1878buf++;1879*body = buf;1880*bodylen = strlen(buf);1881*nonsiglen = sigstart - buf;1882}
1883
1884/*
1885* If 'lines' is greater than 0, append that many lines from the given
1886* 'buf' of length 'size' to the given strbuf.
1887*/
1888static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)1889{
1890int i;1891const char *sp, *eol;1892size_t len;1893
1894sp = buf;1895
1896for (i = 0; i < lines && sp < buf + size; i++) {1897if (i)1898strbuf_addstr(out, "\n ");1899eol = memchr(sp, '\n', size - (sp - buf));1900len = eol ? eol - sp : size - (sp - buf);1901strbuf_add(out, sp, len);1902if (!eol)1903break;1904sp = eol + 1;1905}1906}
1907
1908static void grab_describe_values(struct atom_value *val, int deref,1909struct object *obj)1910{
1911struct commit *commit = (struct commit *)obj;1912int i;1913
1914for (i = 0; i < used_atom_cnt; i++) {1915struct used_atom *atom = &used_atom[i];1916enum atom_type type = atom->atom_type;1917const char *name = atom->name;1918struct atom_value *v = &val[i];1919
1920struct child_process cmd = CHILD_PROCESS_INIT;1921struct strbuf out = STRBUF_INIT;1922struct strbuf err = STRBUF_INIT;1923
1924if (type != ATOM_DESCRIBE)1925continue;1926
1927if (!!deref != (*name == '*'))1928continue;1929
1930cmd.git_cmd = 1;1931strvec_push(&cmd.args, "describe");1932strvec_pushv(&cmd.args, atom->u.describe_args);1933strvec_push(&cmd.args, oid_to_hex(&commit->object.oid));1934if (pipe_command(&cmd, NULL, 0, &out, 0, &err, 0) < 0) {1935error(_("failed to run 'describe'"));1936v->s = xstrdup("");1937continue;1938}1939strbuf_rtrim(&out);1940v->s = strbuf_detach(&out, NULL);1941
1942strbuf_release(&err);1943}1944}
1945
1946/* See grab_values */
1947static void grab_sub_body_contents(struct atom_value *val, int deref, struct expand_data *data)1948{
1949int i;1950const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;1951size_t sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;1952void *buf = data->content;1953
1954for (i = 0; i < used_atom_cnt; i++) {1955struct used_atom *atom = &used_atom[i];1956const char *name = atom->name;1957struct atom_value *v = &val[i];1958enum atom_type atom_type = atom->atom_type;1959
1960if (!!deref != (*name == '*'))1961continue;1962if (deref)1963name++;1964
1965if (atom_type == ATOM_RAW) {1966unsigned long buf_size = data->size;1967
1968if (atom->u.raw_data.option == RAW_BARE) {1969v->s = xmemdupz(buf, buf_size);1970v->s_size = buf_size;1971} else if (atom->u.raw_data.option == RAW_LENGTH) {1972v->value = buf_size;1973v->s = xstrfmt("%"PRIuMAX, v->value);1974}1975continue;1976}1977
1978if ((data->type != OBJ_TAG &&1979data->type != OBJ_COMMIT) ||1980(strcmp(name, "body") &&1981!starts_with(name, "subject") &&1982!starts_with(name, "trailers") &&1983!starts_with(name, "contents")))1984continue;1985if (!subpos)1986find_subpos(buf,1987&subpos, &sublen,1988&bodypos, &bodylen, &nonsiglen,1989&sigpos, &siglen);1990
1991if (atom->u.contents.option == C_SUB)1992v->s = copy_subject(subpos, sublen);1993else if (atom->u.contents.option == C_SUB_SANITIZE) {1994struct strbuf sb = STRBUF_INIT;1995format_sanitized_subject(&sb, subpos, sublen);1996v->s = strbuf_detach(&sb, NULL);1997} else if (atom->u.contents.option == C_BODY_DEP)1998v->s = xmemdupz(bodypos, bodylen);1999else if (atom->u.contents.option == C_LENGTH) {2000v->value = strlen(subpos);2001v->s = xstrfmt("%"PRIuMAX, v->value);2002} else if (atom->u.contents.option == C_BODY)2003v->s = xmemdupz(bodypos, nonsiglen);2004else if (atom->u.contents.option == C_SIG)2005v->s = xmemdupz(sigpos, siglen);2006else if (atom->u.contents.option == C_LINES) {2007struct strbuf s = STRBUF_INIT;2008const char *contents_end = bodypos + nonsiglen;2009
2010/* Size is the length of the message after removing the signature */2011append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);2012v->s = strbuf_detach(&s, NULL);2013} else if (atom->u.contents.option == C_TRAILERS) {2014struct strbuf s = STRBUF_INIT;2015
2016/* Format the trailer info according to the trailer_opts given */2017format_trailers_from_commit(&atom->u.contents.trailer_opts, subpos, &s);2018
2019v->s = strbuf_detach(&s, NULL);2020} else if (atom->u.contents.option == C_BARE)2021v->s = xstrdup(subpos);2022
2023}2024free((void *)sigpos);2025}
2026
2027/*
2028* We want to have empty print-string for field requests
2029* that do not apply (e.g. "authordate" for a tag object)
2030*/
2031static void fill_missing_values(struct atom_value *val)2032{
2033int i;2034for (i = 0; i < used_atom_cnt; i++) {2035struct atom_value *v = &val[i];2036if (!v->s)2037v->s = xstrdup("");2038}2039}
2040
2041/*
2042* val is a list of atom_value to hold returned values. Extract
2043* the values for atoms in used_atom array out of (obj, buf, sz).
2044* when deref is false, (obj, buf, sz) is the object that is
2045* pointed at by the ref itself; otherwise it is the object the
2046* ref (which is a tag) refers to.
2047*/
2048static void grab_values(struct atom_value *val, int deref, struct object *obj, struct expand_data *data)2049{
2050void *buf = data->content;2051
2052switch (obj->type) {2053case OBJ_TAG:2054grab_tag_values(val, deref, obj);2055grab_sub_body_contents(val, deref, data);2056grab_person("tagger", val, deref, buf);2057grab_describe_values(val, deref, obj);2058break;2059case OBJ_COMMIT:2060grab_commit_values(val, deref, obj);2061grab_sub_body_contents(val, deref, data);2062grab_person("author", val, deref, buf);2063grab_person("committer", val, deref, buf);2064grab_signature(val, deref, obj);2065grab_describe_values(val, deref, obj);2066break;2067case OBJ_TREE:2068/* grab_tree_values(val, deref, obj, buf, sz); */2069grab_sub_body_contents(val, deref, data);2070break;2071case OBJ_BLOB:2072/* grab_blob_values(val, deref, obj, buf, sz); */2073grab_sub_body_contents(val, deref, data);2074break;2075default:2076die("Eh? Object of type %d?", obj->type);2077}2078}
2079
2080static inline char *copy_advance(char *dst, const char *src)2081{
2082while (*src)2083*dst++ = *src++;2084return dst;2085}
2086
2087static const char *lstrip_ref_components(const char *refname, int len)2088{
2089long remaining = len;2090const char *start = xstrdup(refname);2091const char *to_free = start;2092
2093if (len < 0) {2094int i;2095const char *p = refname;2096
2097/* Find total no of '/' separated path-components */2098for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)2099;2100/*2101* The number of components we need to strip is now
2102* the total minus the components to be left (Plus one
2103* because we count the number of '/', but the number
2104* of components is one more than the no of '/').
2105*/
2106remaining = i + len + 1;2107}2108
2109while (remaining > 0) {2110switch (*start++) {2111case '\0':2112free((char *)to_free);2113return xstrdup("");2114case '/':2115remaining--;2116break;2117}2118}2119
2120start = xstrdup(start);2121free((char *)to_free);2122return start;2123}
2124
2125static const char *rstrip_ref_components(const char *refname, int len)2126{
2127long remaining = len;2128const char *start = xstrdup(refname);2129const char *to_free = start;2130
2131if (len < 0) {2132int i;2133const char *p = refname;2134
2135/* Find total no of '/' separated path-components */2136for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)2137;2138/*2139* The number of components we need to strip is now
2140* the total minus the components to be left (Plus one
2141* because we count the number of '/', but the number
2142* of components is one more than the no of '/').
2143*/
2144remaining = i + len + 1;2145}2146
2147while (remaining-- > 0) {2148char *p = strrchr(start, '/');2149if (!p) {2150free((char *)to_free);2151return xstrdup("");2152} else2153p[0] = '\0';2154}2155return start;2156}
2157
2158static const char *show_ref(struct refname_atom *atom, const char *refname)2159{
2160if (atom->option == R_SHORT)2161return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),2162refname,2163warn_ambiguous_refs);2164else if (atom->option == R_LSTRIP)2165return lstrip_ref_components(refname, atom->lstrip);2166else if (atom->option == R_RSTRIP)2167return rstrip_ref_components(refname, atom->rstrip);2168else2169return xstrdup(refname);2170}
2171
2172static void fill_remote_ref_details(struct used_atom *atom, const char *refname,2173struct branch *branch, const char **s)2174{
2175int num_ours, num_theirs;2176if (atom->u.remote_ref.option == RR_REF)2177*s = show_ref(&atom->u.remote_ref.refname, refname);2178else if (atom->u.remote_ref.option == RR_TRACK) {2179if (stat_tracking_info(branch, &num_ours, &num_theirs,2180NULL, atom->u.remote_ref.push,2181AHEAD_BEHIND_FULL) < 0) {2182*s = xstrdup(msgs.gone);2183} else if (!num_ours && !num_theirs)2184*s = xstrdup("");2185else if (!num_ours)2186*s = xstrfmt(msgs.behind, num_theirs);2187else if (!num_theirs)2188*s = xstrfmt(msgs.ahead, num_ours);2189else2190*s = xstrfmt(msgs.ahead_behind,2191num_ours, num_theirs);2192if (!atom->u.remote_ref.nobracket && *s[0]) {2193const char *to_free = *s;2194*s = xstrfmt("[%s]", *s);2195free((void *)to_free);2196}2197} else if (atom->u.remote_ref.option == RR_TRACKSHORT) {2198if (stat_tracking_info(branch, &num_ours, &num_theirs,2199NULL, atom->u.remote_ref.push,2200AHEAD_BEHIND_FULL) < 0) {2201*s = xstrdup("");2202return;2203}2204if (!num_ours && !num_theirs)2205*s = xstrdup("=");2206else if (!num_ours)2207*s = xstrdup("<");2208else if (!num_theirs)2209*s = xstrdup(">");2210else2211*s = xstrdup("<>");2212} else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {2213int explicit;2214const char *remote = atom->u.remote_ref.push ?2215pushremote_for_branch(branch, &explicit) :2216remote_for_branch(branch, &explicit);2217*s = xstrdup(explicit ? remote : "");2218} else if (atom->u.remote_ref.option == RR_REMOTE_REF) {2219const char *merge;2220
2221merge = remote_ref_for_branch(branch, atom->u.remote_ref.push);2222*s = xstrdup(merge ? merge : "");2223} else2224BUG("unhandled RR_* enum");2225}
2226
2227char *get_head_description(void)2228{
2229struct strbuf desc = STRBUF_INIT;2230struct wt_status_state state;2231memset(&state, 0, sizeof(state));2232wt_status_get_state(the_repository, &state, 1);2233if (state.rebase_in_progress ||2234state.rebase_interactive_in_progress) {2235if (state.branch)2236strbuf_addf(&desc, _("(no branch, rebasing %s)"),2237state.branch);2238else2239strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),2240state.detached_from);2241} else if (state.bisect_in_progress)2242strbuf_addf(&desc, _("(no branch, bisect started on %s)"),2243state.bisecting_from);2244else if (state.detached_from) {2245if (state.detached_at)2246strbuf_addf(&desc, _("(HEAD detached at %s)"),2247state.detached_from);2248else2249strbuf_addf(&desc, _("(HEAD detached from %s)"),2250state.detached_from);2251} else2252strbuf_addstr(&desc, _("(no branch)"));2253
2254wt_status_state_free_buffers(&state);2255
2256return strbuf_detach(&desc, NULL);2257}
2258
2259static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)2260{
2261if (!ref->symref)2262return xstrdup("");2263else2264return show_ref(&atom->u.refname, ref->symref);2265}
2266
2267static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)2268{
2269if (ref->kind & FILTER_REFS_DETACHED_HEAD)2270return get_head_description();2271return show_ref(&atom->u.refname, ref->refname);2272}
2273
2274static int get_object(struct ref_array_item *ref, int deref, struct object **obj,2275struct expand_data *oi, struct strbuf *err)2276{
2277/* parse_object_buffer() will set eaten to 0 if free() will be needed */2278int eaten = 1;2279if (oi->info.contentp) {2280/* We need to know that to use parse_object_buffer properly */2281oi->info.sizep = &oi->size;2282oi->info.typep = &oi->type;2283}2284if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,2285OBJECT_INFO_LOOKUP_REPLACE))2286return strbuf_addf_ret(err, -1, _("missing object %s for %s"),2287oid_to_hex(&oi->oid), ref->refname);2288if (oi->info.disk_sizep && oi->disk_size < 0)2289BUG("Object size is less than zero.");2290
2291if (oi->info.contentp) {2292*obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);2293if (!*obj) {2294if (!eaten)2295free(oi->content);2296return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),2297oid_to_hex(&oi->oid), ref->refname);2298}2299grab_values(ref->value, deref, *obj, oi);2300}2301
2302grab_common_values(ref->value, deref, oi);2303if (!eaten)2304free(oi->content);2305return 0;2306}
2307
2308static void populate_worktree_map(struct hashmap *map, struct worktree **worktrees)2309{
2310int i;2311
2312for (i = 0; worktrees[i]; i++) {2313if (worktrees[i]->head_ref) {2314struct ref_to_worktree_entry *entry;2315entry = xmalloc(sizeof(*entry));2316entry->wt = worktrees[i];2317hashmap_entry_init(&entry->ent,2318strhash(worktrees[i]->head_ref));2319
2320hashmap_add(map, &entry->ent);2321}2322}2323}
2324
2325static void lazy_init_worktree_map(void)2326{
2327if (ref_to_worktree_map.worktrees)2328return;2329
2330ref_to_worktree_map.worktrees = get_worktrees();2331hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);2332populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);2333}
2334
2335static char *get_worktree_path(const struct ref_array_item *ref)2336{
2337struct hashmap_entry entry, *e;2338struct ref_to_worktree_entry *lookup_result;2339
2340lazy_init_worktree_map();2341
2342hashmap_entry_init(&entry, strhash(ref->refname));2343e = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);2344
2345if (!e)2346return xstrdup("");2347
2348lookup_result = container_of(e, struct ref_to_worktree_entry, ent);2349
2350return xstrdup(lookup_result->wt->path);2351}
2352
2353/*
2354* Parse the object referred by ref, and grab needed value.
2355*/
2356static int populate_value(struct ref_array_item *ref, struct strbuf *err)2357{
2358struct object *obj;2359int i;2360struct object_info empty = OBJECT_INFO_INIT;2361int ahead_behind_atoms = 0;2362int is_base_atoms = 0;2363
2364CALLOC_ARRAY(ref->value, used_atom_cnt);2365
2366/**2367* NEEDSWORK: The following code might be unncessary if all codepaths
2368* that call populate_value() populates the symref member of ref_array_item
2369* like in apply_ref_filter(). Currently pretty_print_ref() is the only codepath
2370* that calls populate_value() without first populating symref.
2371*/
2372if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {2373ref->symref = refs_resolve_refdup(get_main_ref_store(the_repository),2374ref->refname,2375RESOLVE_REF_READING,2376NULL, NULL);2377if (!ref->symref)2378ref->symref = xstrdup("");2379}2380
2381/* Fill in specials first */2382for (i = 0; i < used_atom_cnt; i++) {2383struct used_atom *atom = &used_atom[i];2384enum atom_type atom_type = atom->atom_type;2385const char *name = used_atom[i].name;2386struct atom_value *v = &ref->value[i];2387int deref = 0;2388const char *refname;2389struct branch *branch = NULL;2390
2391v->s_size = ATOM_SIZE_UNSPECIFIED;2392v->handler = append_atom;2393v->value = 0;2394v->atom = atom;2395
2396if (*name == '*') {2397deref = 1;2398name++;2399}2400
2401if (atom_type == ATOM_REFNAME)2402refname = get_refname(atom, ref);2403else if (atom_type == ATOM_WORKTREEPATH) {2404if (ref->kind == FILTER_REFS_BRANCHES)2405v->s = get_worktree_path(ref);2406else2407v->s = xstrdup("");2408continue;2409}2410else if (atom_type == ATOM_SYMREF)2411refname = get_symref(atom, ref);2412else if (atom_type == ATOM_UPSTREAM) {2413const char *branch_name;2414/* only local branches may have an upstream */2415if (!skip_prefix(ref->refname, "refs/heads/",2416&branch_name)) {2417v->s = xstrdup("");2418continue;2419}2420branch = branch_get(branch_name);2421
2422refname = branch_get_upstream(branch, NULL);2423if (refname)2424fill_remote_ref_details(atom, refname, branch, &v->s);2425else2426v->s = xstrdup("");2427continue;2428} else if (atom_type == ATOM_PUSH && atom->u.remote_ref.push) {2429const char *branch_name;2430v->s = xstrdup("");2431if (!skip_prefix(ref->refname, "refs/heads/",2432&branch_name))2433continue;2434branch = branch_get(branch_name);2435
2436if (atom->u.remote_ref.push_remote)2437refname = NULL;2438else {2439refname = branch_get_push(branch, NULL);2440if (!refname)2441continue;2442}2443/* We will definitely re-init v->s on the next line. */2444free((char *)v->s);2445fill_remote_ref_details(atom, refname, branch, &v->s);2446continue;2447} else if (atom_type == ATOM_COLOR) {2448v->s = xstrdup(atom->u.color);2449continue;2450} else if (atom_type == ATOM_FLAG) {2451char buf[256], *cp = buf;2452if (ref->flag & REF_ISSYMREF)2453cp = copy_advance(cp, ",symref");2454if (ref->flag & REF_ISPACKED)2455cp = copy_advance(cp, ",packed");2456if (cp == buf)2457v->s = xstrdup("");2458else {2459*cp = '\0';2460v->s = xstrdup(buf + 1);2461}2462continue;2463} else if (!deref && atom_type == ATOM_OBJECTNAME &&2464grab_oid(name, "objectname", &ref->objectname, v, atom)) {2465continue;2466} else if (atom_type == ATOM_HEAD) {2467if (atom->u.head && !strcmp(ref->refname, atom->u.head))2468v->s = xstrdup("*");2469else2470v->s = xstrdup(" ");2471continue;2472} else if (atom_type == ATOM_ALIGN) {2473v->handler = align_atom_handler;2474v->s = xstrdup("");2475continue;2476} else if (atom_type == ATOM_END) {2477v->handler = end_atom_handler;2478v->s = xstrdup("");2479continue;2480} else if (atom_type == ATOM_IF) {2481const char *s;2482if (skip_prefix(name, "if:", &s))2483v->s = xstrdup(s);2484else2485v->s = xstrdup("");2486v->handler = if_atom_handler;2487continue;2488} else if (atom_type == ATOM_THEN) {2489v->handler = then_atom_handler;2490v->s = xstrdup("");2491continue;2492} else if (atom_type == ATOM_ELSE) {2493v->handler = else_atom_handler;2494v->s = xstrdup("");2495continue;2496} else if (atom_type == ATOM_REST) {2497if (ref->rest)2498v->s = xstrdup(ref->rest);2499else2500v->s = xstrdup("");2501continue;2502} else if (atom_type == ATOM_AHEADBEHIND) {2503if (ref->counts) {2504const struct ahead_behind_count *count;2505count = ref->counts[ahead_behind_atoms++];2506v->s = xstrfmt("%d %d", count->ahead, count->behind);2507} else {2508/* Not a commit. */2509v->s = xstrdup("");2510}2511continue;2512} else if (atom_type == ATOM_ISBASE) {2513if (ref->is_base && ref->is_base[is_base_atoms]) {2514v->s = xstrfmt("(%s)", ref->is_base[is_base_atoms]);2515free(ref->is_base[is_base_atoms]);2516} else {2517v->s = xstrdup("");2518}2519is_base_atoms++;2520continue;2521} else2522continue;2523
2524if (!deref)2525v->s = xstrdup(refname);2526else2527v->s = xstrfmt("%s^{}", refname);2528free((char *)refname);2529}2530
2531for (i = 0; i < used_atom_cnt; i++) {2532struct atom_value *v = &ref->value[i];2533if (v->s == NULL && used_atom[i].source == SOURCE_NONE)2534return strbuf_addf_ret(err, -1, _("missing object %s for %s"),2535oid_to_hex(&ref->objectname), ref->refname);2536}2537
2538if (need_tagged)2539oi.info.contentp = &oi.content;2540if (!memcmp(&oi.info, &empty, sizeof(empty)) &&2541!memcmp(&oi_deref.info, &empty, sizeof(empty)))2542return 0;2543
2544
2545oi.oid = ref->objectname;2546if (get_object(ref, 0, &obj, &oi, err))2547return -1;2548
2549/*2550* If there is no atom that wants to know about tagged
2551* object, we are done.
2552*/
2553if (!need_tagged || (obj->type != OBJ_TAG))2554return 0;2555
2556/*2557* If it is a tag object, see if we use the peeled value. If we do,
2558* grab the peeled OID.
2559*/
2560if (need_tagged && peel_iterated_oid(the_repository, &obj->oid, &oi_deref.oid))2561die("bad tag");2562
2563return get_object(ref, 1, &obj, &oi_deref, err);2564}
2565
2566/*
2567* Given a ref, return the value for the atom. This lazily gets value
2568* out of the object by calling populate value.
2569*/
2570static int get_ref_atom_value(struct ref_array_item *ref, int atom,2571struct atom_value **v, struct strbuf *err)2572{
2573if (!ref->value) {2574if (populate_value(ref, err))2575return -1;2576fill_missing_values(ref->value);2577}2578*v = &ref->value[atom];2579return 0;2580}
2581
2582/*
2583* Return 1 if the refname matches one of the patterns, otherwise 0.
2584* A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
2585* matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
2586* matches "refs/heads/mas*", too).
2587*/
2588static int match_pattern(const char **patterns, const char *refname,2589int ignore_case)2590{
2591unsigned flags = 0;2592
2593if (ignore_case)2594flags |= WM_CASEFOLD;2595
2596/*2597* When no '--format' option is given we need to skip the prefix
2598* for matching refs of tags and branches.
2599*/
2600(void)(skip_prefix(refname, "refs/tags/", &refname) ||2601skip_prefix(refname, "refs/heads/", &refname) ||2602skip_prefix(refname, "refs/remotes/", &refname) ||2603skip_prefix(refname, "refs/", &refname));2604
2605for (; *patterns; patterns++) {2606if (!wildmatch(*patterns, refname, flags))2607return 1;2608}2609return 0;2610}
2611
2612/*
2613* Return 1 if the refname matches one of the patterns, otherwise 0.
2614* A pattern can be path prefix (e.g. a refname "refs/heads/master"
2615* matches a pattern "refs/heads/" but not "refs/heads/m") or a
2616* wildcard (e.g. the same ref matches "refs/heads/m*", too).
2617*/
2618static int match_name_as_path(const char **pattern, const char *refname,2619int ignore_case)2620{
2621int namelen = strlen(refname);2622unsigned flags = WM_PATHNAME;2623
2624if (ignore_case)2625flags |= WM_CASEFOLD;2626
2627for (; *pattern; pattern++) {2628const char *p = *pattern;2629int plen = strlen(p);2630
2631if ((plen <= namelen) &&2632!strncmp(refname, p, plen) &&2633(refname[plen] == '\0' ||2634refname[plen] == '/' ||2635p[plen-1] == '/'))2636return 1;2637if (!wildmatch(p, refname, flags))2638return 1;2639}2640return 0;2641}
2642
2643/* Return 1 if the refname matches one of the patterns, otherwise 0. */
2644static int filter_pattern_match(struct ref_filter *filter, const char *refname)2645{
2646if (!*filter->name_patterns)2647return 1; /* No pattern always matches */2648if (filter->match_as_path)2649return match_name_as_path(filter->name_patterns, refname,2650filter->ignore_case);2651return match_pattern(filter->name_patterns, refname,2652filter->ignore_case);2653}
2654
2655static int filter_exclude_match(struct ref_filter *filter, const char *refname)2656{
2657if (!filter->exclude.nr)2658return 0;2659if (filter->match_as_path)2660return match_name_as_path(filter->exclude.v, refname,2661filter->ignore_case);2662return match_pattern(filter->exclude.v, refname, filter->ignore_case);2663}
2664
2665/*
2666* This is the same as for_each_fullref_in(), but it tries to iterate
2667* only over the patterns we'll care about. Note that it _doesn't_ do a full
2668* pattern match, so the callback still has to match each ref individually.
2669*/
2670static int for_each_fullref_in_pattern(struct ref_filter *filter,2671each_ref_fn cb,2672void *cb_data)2673{
2674if (filter->kind & FILTER_REFS_ROOT_REFS) {2675/* In this case, we want to print all refs including root refs. */2676return refs_for_each_include_root_refs(get_main_ref_store(the_repository),2677cb, cb_data);2678}2679
2680if (!filter->match_as_path) {2681/*2682* in this case, the patterns are applied after
2683* prefixes like "refs/heads/" etc. are stripped off,
2684* so we have to look at everything:
2685*/
2686return refs_for_each_fullref_in(get_main_ref_store(the_repository),2687"", NULL, cb, cb_data);2688}2689
2690if (filter->ignore_case) {2691/*2692* we can't handle case-insensitive comparisons,
2693* so just return everything and let the caller
2694* sort it out.
2695*/
2696return refs_for_each_fullref_in(get_main_ref_store(the_repository),2697"", NULL, cb, cb_data);2698}2699
2700if (!filter->name_patterns[0]) {2701/* no patterns; we have to look at everything */2702return refs_for_each_fullref_in(get_main_ref_store(the_repository),2703"", filter->exclude.v, cb, cb_data);2704}2705
2706return refs_for_each_fullref_in_prefixes(get_main_ref_store(the_repository),2707NULL, filter->name_patterns,2708filter->exclude.v,2709cb, cb_data);2710}
2711
2712/*
2713* Given a ref (oid, refname), check if the ref belongs to the array
2714* of oids. If the given ref is a tag, check if the given tag points
2715* at one of the oids in the given oid array. Returns non-zero if a
2716* match is found.
2717*
2718* NEEDSWORK:
2719* As the refs are cached we might know what refname peels to without
2720* the need to parse the object via parse_object(). peel_ref() might be a
2721* more efficient alternative to obtain the pointee.
2722*/
2723static int match_points_at(struct oid_array *points_at,2724const struct object_id *oid,2725const char *refname)2726{
2727struct object *obj;2728
2729if (oid_array_lookup(points_at, oid) >= 0)2730return 1;2731obj = parse_object_with_flags(the_repository, oid,2732PARSE_OBJECT_SKIP_HASH_CHECK);2733while (obj && obj->type == OBJ_TAG) {2734struct tag *tag = (struct tag *)obj;2735
2736if (parse_tag(tag) < 0) {2737obj = NULL;2738break;2739}2740
2741if (oid_array_lookup(points_at, get_tagged_oid(tag)) >= 0)2742return 1;2743
2744obj = tag->tagged;2745}2746if (!obj)2747die(_("malformed object at '%s'"), refname);2748return 0;2749}
2750
2751/*
2752* Allocate space for a new ref_array_item and copy the name and oid to it.
2753*
2754* Callers can then fill in other struct members at their leisure.
2755*/
2756static struct ref_array_item *new_ref_array_item(const char *refname,2757const struct object_id *oid)2758{
2759struct ref_array_item *ref;2760
2761FLEX_ALLOC_STR(ref, refname, refname);2762oidcpy(&ref->objectname, oid);2763ref->rest = NULL;2764
2765return ref;2766}
2767
2768static void ref_array_append(struct ref_array *array, struct ref_array_item *ref)2769{
2770ALLOC_GROW(array->items, array->nr + 1, array->alloc);2771array->items[array->nr++] = ref;2772}
2773
2774struct ref_array_item *ref_array_push(struct ref_array *array,2775const char *refname,2776const struct object_id *oid)2777{
2778struct ref_array_item *ref = new_ref_array_item(refname, oid);2779ref_array_append(array, ref);2780return ref;2781}
2782
2783static int ref_kind_from_refname(const char *refname)2784{
2785unsigned int i;2786
2787static struct {2788const char *prefix;2789unsigned int kind;2790} ref_kind[] = {2791{ "refs/heads/" , FILTER_REFS_BRANCHES },2792{ "refs/remotes/" , FILTER_REFS_REMOTES },2793{ "refs/tags/", FILTER_REFS_TAGS}2794};2795
2796if (!strcmp(refname, "HEAD"))2797return FILTER_REFS_DETACHED_HEAD;2798
2799for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {2800if (starts_with(refname, ref_kind[i].prefix))2801return ref_kind[i].kind;2802}2803
2804if (is_pseudo_ref(refname))2805return FILTER_REFS_PSEUDOREFS;2806if (is_root_ref(refname))2807return FILTER_REFS_ROOT_REFS;2808
2809return FILTER_REFS_OTHERS;2810}
2811
2812static int filter_ref_kind(struct ref_filter *filter, const char *refname)2813{
2814if (filter->kind == FILTER_REFS_BRANCHES ||2815filter->kind == FILTER_REFS_REMOTES ||2816filter->kind == FILTER_REFS_TAGS)2817return filter->kind;2818return ref_kind_from_refname(refname);2819}
2820
2821static struct ref_array_item *apply_ref_filter(const char *refname, const char *referent, const struct object_id *oid,2822int flag, struct ref_filter *filter)2823{
2824struct ref_array_item *ref;2825struct commit *commit = NULL;2826unsigned int kind;2827
2828if (flag & REF_BAD_NAME) {2829warning(_("ignoring ref with broken name %s"), refname);2830return NULL;2831}2832
2833if (flag & REF_ISBROKEN) {2834warning(_("ignoring broken ref %s"), refname);2835return NULL;2836}2837
2838/* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */2839kind = filter_ref_kind(filter, refname);2840
2841/*2842* Generally HEAD refs are printed with special description denoting a rebase,
2843* detached state and so forth. This is useful when only printing the HEAD ref
2844* But when it is being printed along with other root refs, it makes sense to
2845* keep the formatting consistent. So we mask the type to act like a root ref.
2846*/
2847if (filter->kind & FILTER_REFS_ROOT_REFS && kind == FILTER_REFS_DETACHED_HEAD)2848kind = FILTER_REFS_ROOT_REFS;2849else if (!(kind & filter->kind))2850return NULL;2851
2852if (!filter_pattern_match(filter, refname))2853return NULL;2854
2855if (filter_exclude_match(filter, refname))2856return NULL;2857
2858if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))2859return NULL;2860
2861/*2862* A merge filter is applied on refs pointing to commits. Hence
2863* obtain the commit using the 'oid' available and discard all
2864* non-commits early. The actual filtering is done later.
2865*/
2866if (filter->reachable_from || filter->unreachable_from ||2867filter->with_commit || filter->no_commit || filter->verbose) {2868commit = lookup_commit_reference_gently(the_repository, oid, 1);2869if (!commit)2870return NULL;2871/* We perform the filtering for the '--contains' option... */2872if (filter->with_commit &&2873!commit_contains(filter, commit, filter->with_commit, &filter->internal.contains_cache))2874return NULL;2875/* ...or for the `--no-contains' option */2876if (filter->no_commit &&2877commit_contains(filter, commit, filter->no_commit, &filter->internal.no_contains_cache))2878return NULL;2879}2880
2881/*2882* We do not open the object yet; sort may only need refname
2883* to do its job and the resulting list may yet to be pruned
2884* by maxcount logic.
2885*/
2886ref = new_ref_array_item(refname, oid);2887ref->commit = commit;2888ref->flag = flag;2889ref->kind = kind;2890ref->symref = xstrdup_or_null(referent);2891
2892return ref;2893}
2894
2895struct ref_filter_cbdata {2896struct ref_array *array;2897struct ref_filter *filter;2898};2899
2900/*
2901* A call-back given to for_each_ref(). Filter refs and keep them for
2902* later object processing.
2903*/
2904static int filter_one(const char *refname, const char *referent, const struct object_id *oid, int flag, void *cb_data)2905{
2906struct ref_filter_cbdata *ref_cbdata = cb_data;2907struct ref_array_item *ref;2908
2909ref = apply_ref_filter(refname, referent, oid, flag, ref_cbdata->filter);2910if (ref)2911ref_array_append(ref_cbdata->array, ref);2912
2913return 0;2914}
2915
2916/* Free memory allocated for a ref_array_item */
2917static void free_array_item(struct ref_array_item *item)2918{
2919free((char *)item->symref);2920if (item->value) {2921int i;2922for (i = 0; i < used_atom_cnt; i++)2923free((char *)item->value[i].s);2924free(item->value);2925}2926free(item->counts);2927free(item->is_base);2928free(item);2929}
2930
2931struct ref_filter_and_format_cbdata {2932struct ref_filter *filter;2933struct ref_format *format;2934
2935struct ref_filter_and_format_internal {2936int count;2937} internal;2938};2939
2940static int filter_and_format_one(const char *refname, const char *referent, const struct object_id *oid, int flag, void *cb_data)2941{
2942struct ref_filter_and_format_cbdata *ref_cbdata = cb_data;2943struct ref_array_item *ref;2944struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;2945
2946ref = apply_ref_filter(refname, referent, oid, flag, ref_cbdata->filter);2947if (!ref)2948return 0;2949
2950if (format_ref_array_item(ref, ref_cbdata->format, &output, &err))2951die("%s", err.buf);2952
2953if (output.len || !ref_cbdata->format->array_opts.omit_empty) {2954fwrite(output.buf, 1, output.len, stdout);2955putchar('\n');2956}2957
2958strbuf_release(&output);2959strbuf_release(&err);2960free_array_item(ref);2961
2962/*2963* Increment the running count of refs that match the filter. If
2964* max_count is set and we've reached the max, stop the ref
2965* iteration by returning a nonzero value.
2966*/
2967if (ref_cbdata->format->array_opts.max_count &&2968++ref_cbdata->internal.count >= ref_cbdata->format->array_opts.max_count)2969return 1;2970
2971return 0;2972}
2973
2974/* Free all memory allocated for ref_array */
2975void ref_array_clear(struct ref_array *array)2976{
2977int i;2978
2979for (i = 0; i < array->nr; i++)2980free_array_item(array->items[i]);2981FREE_AND_NULL(array->items);2982array->nr = array->alloc = 0;2983
2984for (i = 0; i < used_atom_cnt; i++) {2985struct used_atom *atom = &used_atom[i];2986if (atom->atom_type == ATOM_HEAD)2987free(atom->u.head);2988free((char *)atom->name);2989}2990FREE_AND_NULL(used_atom);2991used_atom_cnt = 0;2992
2993if (ref_to_worktree_map.worktrees) {2994hashmap_clear_and_free(&(ref_to_worktree_map.map),2995struct ref_to_worktree_entry, ent);2996free_worktrees(ref_to_worktree_map.worktrees);2997ref_to_worktree_map.worktrees = NULL;2998}2999
3000FREE_AND_NULL(array->counts);3001}
3002
3003#define EXCLUDE_REACHED 03004#define INCLUDE_REACHED 13005static void reach_filter(struct ref_array *array,3006struct commit_list **check_reachable,3007int include_reached)3008{
3009int i, old_nr;3010struct commit **to_clear;3011
3012if (!*check_reachable)3013return;3014
3015CALLOC_ARRAY(to_clear, array->nr);3016for (i = 0; i < array->nr; i++) {3017struct ref_array_item *item = array->items[i];3018to_clear[i] = item->commit;3019}3020
3021tips_reachable_from_bases(the_repository,3022*check_reachable,3023to_clear, array->nr,3024UNINTERESTING);3025
3026old_nr = array->nr;3027array->nr = 0;3028
3029for (i = 0; i < old_nr; i++) {3030struct ref_array_item *item = array->items[i];3031struct commit *commit = item->commit;3032
3033int is_merged = !!(commit->object.flags & UNINTERESTING);3034
3035if (is_merged == include_reached)3036array->items[array->nr++] = array->items[i];3037else3038free_array_item(item);3039}3040
3041clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);3042
3043while (*check_reachable) {3044struct commit *merge_commit = pop_commit(check_reachable);3045clear_commit_marks(merge_commit, ALL_REV_FLAGS);3046}3047
3048free(to_clear);3049}
3050
3051void filter_ahead_behind(struct repository *r,3052struct ref_format *format,3053struct ref_array *array)3054{
3055struct commit **commits;3056size_t commits_nr = format->bases.nr + array->nr;3057
3058if (!format->bases.nr || !array->nr)3059return;3060
3061ALLOC_ARRAY(commits, commits_nr);3062for (size_t i = 0; i < format->bases.nr; i++)3063commits[i] = format->bases.items[i].util;3064
3065ALLOC_ARRAY(array->counts, st_mult(format->bases.nr, array->nr));3066
3067commits_nr = format->bases.nr;3068array->counts_nr = 0;3069for (size_t i = 0; i < array->nr; i++) {3070const char *name = array->items[i]->refname;3071commits[commits_nr] = lookup_commit_reference_by_name(name);3072
3073if (!commits[commits_nr])3074continue;3075
3076CALLOC_ARRAY(array->items[i]->counts, format->bases.nr);3077for (size_t j = 0; j < format->bases.nr; j++) {3078struct ahead_behind_count *count;3079count = &array->counts[array->counts_nr++];3080count->tip_index = commits_nr;3081count->base_index = j;3082
3083array->items[i]->counts[j] = count;3084}3085commits_nr++;3086}3087
3088ahead_behind(r, commits, commits_nr, array->counts, array->counts_nr);3089free(commits);3090}
3091
3092void filter_is_base(struct repository *r,3093struct ref_format *format,3094struct ref_array *array)3095{
3096struct commit **bases;3097size_t bases_nr = 0;3098struct ref_array_item **back_index;3099
3100if (!format->is_base_tips.nr || !array->nr)3101return;3102
3103CALLOC_ARRAY(back_index, array->nr);3104CALLOC_ARRAY(bases, array->nr);3105
3106for (size_t i = 0; i < array->nr; i++) {3107const char *name = array->items[i]->refname;3108struct commit *c = lookup_commit_reference_by_name_gently(name, 1);3109
3110CALLOC_ARRAY(array->items[i]->is_base, format->is_base_tips.nr);3111
3112if (!c)3113continue;3114
3115back_index[bases_nr] = array->items[i];3116bases[bases_nr] = c;3117bases_nr++;3118}3119
3120for (size_t i = 0; i < format->is_base_tips.nr; i++) {3121struct commit *tip = format->is_base_tips.items[i].util;3122int base_index = get_branch_base_for_tip(r, tip, bases, bases_nr);3123
3124if (base_index < 0)3125continue;3126
3127/* Store the string for use in output later. */3128back_index[base_index]->is_base[i] = xstrdup(format->is_base_tips.items[i].string);3129}3130
3131free(back_index);3132free(bases);3133}
3134
3135static int do_filter_refs(struct ref_filter *filter, unsigned int type, each_ref_fn fn, void *cb_data)3136{
3137int ret = 0;3138
3139filter->kind = type & FILTER_REFS_KIND_MASK;3140
3141init_contains_cache(&filter->internal.contains_cache);3142init_contains_cache(&filter->internal.no_contains_cache);3143
3144/* Simple per-ref filtering */3145if (!filter->kind)3146die("filter_refs: invalid type");3147else {3148/*3149* For common cases where we need only branches or remotes or tags,
3150* we only iterate through those refs. If a mix of refs is needed,
3151* we iterate over all refs and filter out required refs with the help
3152* of filter_ref_kind().
3153*/
3154if (filter->kind == FILTER_REFS_BRANCHES)3155ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),3156"refs/heads/", NULL,3157fn, cb_data);3158else if (filter->kind == FILTER_REFS_REMOTES)3159ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),3160"refs/remotes/", NULL,3161fn, cb_data);3162else if (filter->kind == FILTER_REFS_TAGS)3163ret = refs_for_each_fullref_in(get_main_ref_store(the_repository),3164"refs/tags/", NULL, fn,3165cb_data);3166else if (filter->kind & FILTER_REFS_REGULAR)3167ret = for_each_fullref_in_pattern(filter, fn, cb_data);3168
3169/*3170* When printing all ref types, HEAD is already included,
3171* so we don't want to print HEAD again.
3172*/
3173if (!ret && !(filter->kind & FILTER_REFS_ROOT_REFS) &&3174(filter->kind & FILTER_REFS_DETACHED_HEAD))3175refs_head_ref(get_main_ref_store(the_repository), fn,3176cb_data);3177}3178
3179clear_contains_cache(&filter->internal.contains_cache);3180clear_contains_cache(&filter->internal.no_contains_cache);3181
3182return ret;3183}
3184
3185/*
3186* API for filtering a set of refs. Based on the type of refs the user
3187* has requested, we iterate through those refs and apply filters
3188* as per the given ref_filter structure and finally store the
3189* filtered refs in the ref_array structure.
3190*/
3191int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)3192{
3193struct ref_filter_cbdata ref_cbdata;3194int save_commit_buffer_orig;3195int ret = 0;3196
3197ref_cbdata.array = array;3198ref_cbdata.filter = filter;3199
3200save_commit_buffer_orig = save_commit_buffer;3201save_commit_buffer = 0;3202
3203ret = do_filter_refs(filter, type, filter_one, &ref_cbdata);3204
3205/* Filters that need revision walking */3206reach_filter(array, &filter->reachable_from, INCLUDE_REACHED);3207reach_filter(array, &filter->unreachable_from, EXCLUDE_REACHED);3208
3209save_commit_buffer = save_commit_buffer_orig;3210return ret;3211}
3212
3213static inline int can_do_iterative_format(struct ref_filter *filter,3214struct ref_sorting *sorting,3215struct ref_format *format)3216{
3217/*3218* Filtering & formatting results within a single ref iteration
3219* callback is not compatible with options that require
3220* post-processing a filtered ref_array. These include:
3221* - filtering on reachability
3222* - sorting the filtered results
3223* - including ahead-behind information in the formatted output
3224*/
3225return !(filter->reachable_from ||3226filter->unreachable_from ||3227sorting ||3228format->bases.nr ||3229format->is_base_tips.nr);3230}
3231
3232void filter_and_format_refs(struct ref_filter *filter, unsigned int type,3233struct ref_sorting *sorting,3234struct ref_format *format)3235{
3236if (can_do_iterative_format(filter, sorting, format)) {3237int save_commit_buffer_orig;3238struct ref_filter_and_format_cbdata ref_cbdata = {3239.filter = filter,3240.format = format,3241};3242
3243save_commit_buffer_orig = save_commit_buffer;3244save_commit_buffer = 0;3245
3246do_filter_refs(filter, type, filter_and_format_one, &ref_cbdata);3247
3248save_commit_buffer = save_commit_buffer_orig;3249} else {3250struct ref_array array = { 0 };3251filter_refs(&array, filter, type);3252filter_ahead_behind(the_repository, format, &array);3253filter_is_base(the_repository, format, &array);3254ref_array_sort(sorting, &array);3255print_formatted_ref_array(&array, format);3256ref_array_clear(&array);3257}3258}
3259
3260static int compare_detached_head(struct ref_array_item *a, struct ref_array_item *b)3261{
3262if (!(a->kind ^ b->kind))3263BUG("ref_kind_from_refname() should only mark one ref as HEAD");3264if (a->kind & FILTER_REFS_DETACHED_HEAD)3265return -1;3266else if (b->kind & FILTER_REFS_DETACHED_HEAD)3267return 1;3268BUG("should have died in the xor check above");3269return 0;3270}
3271
3272static int memcasecmp(const void *vs1, const void *vs2, size_t n)3273{
3274const char *s1 = vs1, *s2 = vs2;3275const char *end = s1 + n;3276
3277for (; s1 < end; s1++, s2++) {3278int diff = tolower(*s1) - tolower(*s2);3279if (diff)3280return diff;3281}3282return 0;3283}
3284
3285struct ref_sorting {3286struct ref_sorting *next;3287int atom; /* index into used_atom array (internal) */3288enum ref_sorting_order sort_flags;3289};3290
3291static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)3292{
3293struct atom_value *va, *vb;3294int cmp;3295int cmp_detached_head = 0;3296cmp_type cmp_type = used_atom[s->atom].type;3297struct strbuf err = STRBUF_INIT;3298
3299if (get_ref_atom_value(a, s->atom, &va, &err))3300die("%s", err.buf);3301if (get_ref_atom_value(b, s->atom, &vb, &err))3302die("%s", err.buf);3303strbuf_release(&err);3304if (s->sort_flags & REF_SORTING_DETACHED_HEAD_FIRST &&3305((a->kind | b->kind) & FILTER_REFS_DETACHED_HEAD)) {3306cmp = compare_detached_head(a, b);3307cmp_detached_head = 1;3308} else if (s->sort_flags & REF_SORTING_VERSION) {3309cmp = versioncmp(va->s, vb->s);3310} else if (cmp_type == FIELD_STR) {3311if (va->s_size < 0 && vb->s_size < 0) {3312int (*cmp_fn)(const char *, const char *);3313cmp_fn = s->sort_flags & REF_SORTING_ICASE3314? strcasecmp : strcmp;3315cmp = cmp_fn(va->s, vb->s);3316} else {3317size_t a_size = va->s_size < 0 ?3318strlen(va->s) : va->s_size;3319size_t b_size = vb->s_size < 0 ?3320strlen(vb->s) : vb->s_size;3321int (*cmp_fn)(const void *, const void *, size_t);3322cmp_fn = s->sort_flags & REF_SORTING_ICASE3323? memcasecmp : memcmp;3324
3325cmp = cmp_fn(va->s, vb->s, b_size > a_size ?3326a_size : b_size);3327if (!cmp) {3328if (a_size > b_size)3329cmp = 1;3330else if (a_size < b_size)3331cmp = -1;3332}3333}3334} else {3335if (va->value < vb->value)3336cmp = -1;3337else if (va->value == vb->value)3338cmp = 0;3339else3340cmp = 1;3341}3342
3343return (s->sort_flags & REF_SORTING_REVERSE && !cmp_detached_head)3344? -cmp : cmp;3345}
3346
3347static int compare_refs(const void *a_, const void *b_, void *ref_sorting)3348{
3349struct ref_array_item *a = *((struct ref_array_item **)a_);3350struct ref_array_item *b = *((struct ref_array_item **)b_);3351struct ref_sorting *s;3352
3353for (s = ref_sorting; s; s = s->next) {3354int cmp = cmp_ref_sorting(s, a, b);3355if (cmp)3356return cmp;3357}3358s = ref_sorting;3359return s && s->sort_flags & REF_SORTING_ICASE ?3360strcasecmp(a->refname, b->refname) :3361strcmp(a->refname, b->refname);3362}
3363
3364void ref_sorting_set_sort_flags_all(struct ref_sorting *sorting,3365unsigned int mask, int on)3366{
3367for (; sorting; sorting = sorting->next) {3368if (on)3369sorting->sort_flags |= mask;3370else3371sorting->sort_flags &= ~mask;3372}3373}
3374
3375void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)3376{
3377if (sorting)3378QSORT_S(array->items, array->nr, compare_refs, sorting);3379}
3380
3381static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)3382{
3383struct strbuf *s = &state->stack->output;3384
3385while (*cp && (!ep || cp < ep)) {3386if (*cp == '%') {3387if (cp[1] == '%')3388cp++;3389else {3390int ch = hex2chr(cp + 1);3391if (0 <= ch) {3392strbuf_addch(s, ch);3393cp += 3;3394continue;3395}3396}3397}3398strbuf_addch(s, *cp);3399cp++;3400}3401}
3402
3403int format_ref_array_item(struct ref_array_item *info,3404struct ref_format *format,3405struct strbuf *final_buf,3406struct strbuf *error_buf)3407{
3408const char *cp, *sp, *ep;3409struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;3410
3411state.quote_style = format->quote_style;3412push_stack_element(&state.stack);3413
3414for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {3415struct atom_value *atomv;3416int pos;3417
3418ep = strchr(sp, ')');3419if (cp < sp)3420append_literal(cp, sp, &state);3421pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);3422if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||3423atomv->handler(atomv, &state, error_buf)) {3424pop_stack_element(&state.stack);3425return -1;3426}3427}3428if (*cp) {3429sp = cp + strlen(cp);3430append_literal(cp, sp, &state);3431}3432if (format->need_color_reset_at_eol) {3433struct atom_value resetv = ATOM_VALUE_INIT;3434resetv.s = GIT_COLOR_RESET;3435if (append_atom(&resetv, &state, error_buf)) {3436pop_stack_element(&state.stack);3437return -1;3438}3439}3440if (state.stack->prev) {3441pop_stack_element(&state.stack);3442return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));3443}3444strbuf_addbuf(final_buf, &state.stack->output);3445pop_stack_element(&state.stack);3446return 0;3447}
3448
3449void print_formatted_ref_array(struct ref_array *array, struct ref_format *format)3450{
3451int total;3452struct strbuf output = STRBUF_INIT, err = STRBUF_INIT;3453
3454total = format->array_opts.max_count;3455if (!total || array->nr < total)3456total = array->nr;3457for (int i = 0; i < total; i++) {3458strbuf_reset(&err);3459strbuf_reset(&output);3460if (format_ref_array_item(array->items[i], format, &output, &err))3461die("%s", err.buf);3462if (output.len || !format->array_opts.omit_empty) {3463fwrite(output.buf, 1, output.len, stdout);3464putchar('\n');3465}3466}3467
3468strbuf_release(&err);3469strbuf_release(&output);3470}
3471
3472void pretty_print_ref(const char *name, const struct object_id *oid,3473struct ref_format *format)3474{
3475struct ref_array_item *ref_item;3476struct strbuf output = STRBUF_INIT;3477struct strbuf err = STRBUF_INIT;3478
3479ref_item = new_ref_array_item(name, oid);3480ref_item->kind = ref_kind_from_refname(name);3481if (format_ref_array_item(ref_item, format, &output, &err))3482die("%s", err.buf);3483fwrite(output.buf, 1, output.len, stdout);3484putchar('\n');3485
3486strbuf_release(&err);3487strbuf_release(&output);3488free_array_item(ref_item);3489}
3490
3491static int parse_sorting_atom(const char *atom)3492{
3493/*3494* This parses an atom using a dummy ref_format, since we don't
3495* actually care about the formatting details.
3496*/
3497struct ref_format dummy = REF_FORMAT_INIT;3498const char *end = atom + strlen(atom);3499struct strbuf err = STRBUF_INIT;3500int res = parse_ref_filter_atom(&dummy, atom, end, &err);3501if (res < 0)3502die("%s", err.buf);3503strbuf_release(&err);3504return res;3505}
3506
3507static void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)3508{
3509struct ref_sorting *s;3510
3511CALLOC_ARRAY(s, 1);3512s->next = *sorting_tail;3513*sorting_tail = s;3514
3515if (*arg == '-') {3516s->sort_flags |= REF_SORTING_REVERSE;3517arg++;3518}3519if (skip_prefix(arg, "version:", &arg) ||3520skip_prefix(arg, "v:", &arg))3521s->sort_flags |= REF_SORTING_VERSION;3522s->atom = parse_sorting_atom(arg);3523}
3524
3525struct ref_sorting *ref_sorting_options(struct string_list *options)3526{
3527struct string_list_item *item;3528struct ref_sorting *sorting = NULL, **tail = &sorting;3529
3530if (options->nr) {3531for_each_string_list_item(item, options)3532parse_ref_sorting(tail, item->string);3533}3534
3535/*3536* From here on, the ref_sorting list should be used to talk
3537* about the sort order used for the output. The caller
3538* should not touch the string form anymore.
3539*/
3540string_list_clear(options, 0);3541return sorting;3542}
3543
3544void ref_sorting_release(struct ref_sorting *sorting)3545{
3546while (sorting) {3547struct ref_sorting *next = sorting->next;3548free(sorting);3549sorting = next;3550}3551}
3552
3553int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)3554{
3555struct ref_filter *rf = opt->value;3556struct object_id oid;3557struct commit *merge_commit;3558
3559BUG_ON_OPT_NEG(unset);3560
3561if (repo_get_oid(the_repository, arg, &oid))3562die(_("malformed object name %s"), arg);3563
3564merge_commit = lookup_commit_reference_gently(the_repository, &oid, 0);3565
3566if (!merge_commit)3567return error(_("option `%s' must point to a commit"), opt->long_name);3568
3569if (starts_with(opt->long_name, "no"))3570commit_list_insert(merge_commit, &rf->unreachable_from);3571else3572commit_list_insert(merge_commit, &rf->reachable_from);3573
3574return 0;3575}
3576
3577void ref_filter_init(struct ref_filter *filter)3578{
3579struct ref_filter blank = REF_FILTER_INIT;3580memcpy(filter, &blank, sizeof(blank));3581}
3582
3583void ref_filter_clear(struct ref_filter *filter)3584{
3585strvec_clear(&filter->exclude);3586oid_array_clear(&filter->points_at);3587free_commit_list(filter->with_commit);3588free_commit_list(filter->no_commit);3589free_commit_list(filter->reachable_from);3590free_commit_list(filter->unreachable_from);3591ref_filter_init(filter);3592}
3593