git
/
object-name.c
2165 строк · 54.1 Кб
1#define USE_THE_REPOSITORY_VARIABLE2
3#include "git-compat-util.h"4#include "object-name.h"5#include "advice.h"6#include "config.h"7#include "environment.h"8#include "gettext.h"9#include "hex.h"10#include "tag.h"11#include "commit.h"12#include "tree.h"13#include "tree-walk.h"14#include "refs.h"15#include "remote.h"16#include "dir.h"17#include "oid-array.h"18#include "oidtree.h"19#include "packfile.h"20#include "pretty.h"21#include "object-store-ll.h"22#include "read-cache-ll.h"23#include "repository.h"24#include "setup.h"25#include "midx.h"26#include "commit-reach.h"27#include "date.h"28#include "object-file-convert.h"29
30static int get_oid_oneline(struct repository *r, const char *, struct object_id *,31const struct commit_list *);32
33typedef int (*disambiguate_hint_fn)(struct repository *, const struct object_id *, void *);34
35struct disambiguate_state {36int len; /* length of prefix in hex chars */37char hex_pfx[GIT_MAX_HEXSZ + 1];38struct object_id bin_pfx;39
40struct repository *repo;41disambiguate_hint_fn fn;42void *cb_data;43struct object_id candidate;44unsigned candidate_exists:1;45unsigned candidate_checked:1;46unsigned candidate_ok:1;47unsigned disambiguate_fn_used:1;48unsigned ambiguous:1;49unsigned always_call_fn:1;50};51
52static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)53{
54/* The hash algorithm of current has already been filtered */55if (ds->always_call_fn) {56ds->ambiguous = ds->fn(ds->repo, current, ds->cb_data) ? 1 : 0;57return;58}59if (!ds->candidate_exists) {60/* this is the first candidate */61oidcpy(&ds->candidate, current);62ds->candidate_exists = 1;63return;64} else if (oideq(&ds->candidate, current)) {65/* the same as what we already have seen */66return;67}68
69if (!ds->fn) {70/* cannot disambiguate between ds->candidate and current */71ds->ambiguous = 1;72return;73}74
75if (!ds->candidate_checked) {76ds->candidate_ok = ds->fn(ds->repo, &ds->candidate, ds->cb_data);77ds->disambiguate_fn_used = 1;78ds->candidate_checked = 1;79}80
81if (!ds->candidate_ok) {82/* discard the candidate; we know it does not satisfy fn */83oidcpy(&ds->candidate, current);84ds->candidate_checked = 0;85return;86}87
88/* if we reach this point, we know ds->candidate satisfies fn */89if (ds->fn(ds->repo, current, ds->cb_data)) {90/*91* if both current and candidate satisfy fn, we cannot
92* disambiguate.
93*/
94ds->candidate_ok = 0;95ds->ambiguous = 1;96}97
98/* otherwise, current can be discarded and candidate is still good */99}
100
101static int match_hash(unsigned, const unsigned char *, const unsigned char *);102
103static enum cb_next match_prefix(const struct object_id *oid, void *arg)104{
105struct disambiguate_state *ds = arg;106/* no need to call match_hash, oidtree_each did prefix match */107update_candidates(ds, oid);108return ds->ambiguous ? CB_BREAK : CB_CONTINUE;109}
110
111static void find_short_object_filename(struct disambiguate_state *ds)112{
113struct object_directory *odb;114
115for (odb = ds->repo->objects->odb; odb && !ds->ambiguous; odb = odb->next)116oidtree_each(odb_loose_cache(odb, &ds->bin_pfx),117&ds->bin_pfx, ds->len, match_prefix, ds);118}
119
120static int match_hash(unsigned len, const unsigned char *a, const unsigned char *b)121{
122do {123if (*a != *b)124return 0;125a++;126b++;127len -= 2;128} while (len > 1);129if (len)130if ((*a ^ *b) & 0xf0)131return 0;132return 1;133}
134
135static void unique_in_midx(struct multi_pack_index *m,136struct disambiguate_state *ds)137{
138for (; m; m = m->base_midx) {139uint32_t num, i, first = 0;140const struct object_id *current = NULL;141int len = ds->len > ds->repo->hash_algo->hexsz ?142ds->repo->hash_algo->hexsz : ds->len;143
144if (!m->num_objects)145continue;146
147num = m->num_objects + m->num_objects_in_base;148
149bsearch_one_midx(&ds->bin_pfx, m, &first);150
151/*152* At this point, "first" is the location of the lowest
153* object with an object name that could match
154* "bin_pfx". See if we have 0, 1 or more objects that
155* actually match(es).
156*/
157for (i = first; i < num && !ds->ambiguous; i++) {158struct object_id oid;159current = nth_midxed_object_oid(&oid, m, i);160if (!match_hash(len, ds->bin_pfx.hash, current->hash))161break;162update_candidates(ds, current);163}164}165}
166
167static void unique_in_pack(struct packed_git *p,168struct disambiguate_state *ds)169{
170uint32_t num, i, first = 0;171int len = ds->len > ds->repo->hash_algo->hexsz ?172ds->repo->hash_algo->hexsz : ds->len;173
174if (p->multi_pack_index)175return;176
177if (open_pack_index(p) || !p->num_objects)178return;179
180num = p->num_objects;181bsearch_pack(&ds->bin_pfx, p, &first);182
183/*184* At this point, "first" is the location of the lowest object
185* with an object name that could match "bin_pfx". See if we have
186* 0, 1 or more objects that actually match(es).
187*/
188for (i = first; i < num && !ds->ambiguous; i++) {189struct object_id oid;190nth_packed_object_id(&oid, p, i);191if (!match_hash(len, ds->bin_pfx.hash, oid.hash))192break;193update_candidates(ds, &oid);194}195}
196
197static void find_short_packed_object(struct disambiguate_state *ds)198{
199struct multi_pack_index *m;200struct packed_git *p;201
202/* Skip, unless oids from the storage hash algorithm are wanted */203if (ds->bin_pfx.algo && (&hash_algos[ds->bin_pfx.algo] != ds->repo->hash_algo))204return;205
206for (m = get_multi_pack_index(ds->repo); m && !ds->ambiguous;207m = m->next)208unique_in_midx(m, ds);209for (p = get_packed_git(ds->repo); p && !ds->ambiguous;210p = p->next)211unique_in_pack(p, ds);212}
213
214static int finish_object_disambiguation(struct disambiguate_state *ds,215struct object_id *oid)216{
217if (ds->ambiguous)218return SHORT_NAME_AMBIGUOUS;219
220if (!ds->candidate_exists)221return MISSING_OBJECT;222
223if (!ds->candidate_checked)224/*225* If this is the only candidate, there is no point
226* calling the disambiguation hint callback.
227*
228* On the other hand, if the current candidate
229* replaced an earlier candidate that did _not_ pass
230* the disambiguation hint callback, then we do have
231* more than one objects that match the short name
232* given, so we should make sure this one matches;
233* otherwise, if we discovered this one and the one
234* that we previously discarded in the reverse order,
235* we would end up showing different results in the
236* same repository!
237*/
238ds->candidate_ok = (!ds->disambiguate_fn_used ||239ds->fn(ds->repo, &ds->candidate, ds->cb_data));240
241if (!ds->candidate_ok)242return SHORT_NAME_AMBIGUOUS;243
244oidcpy(oid, &ds->candidate);245return 0;246}
247
248static int disambiguate_commit_only(struct repository *r,249const struct object_id *oid,250void *cb_data UNUSED)251{
252int kind = oid_object_info(r, oid, NULL);253return kind == OBJ_COMMIT;254}
255
256static int disambiguate_committish_only(struct repository *r,257const struct object_id *oid,258void *cb_data UNUSED)259{
260struct object *obj;261int kind;262
263kind = oid_object_info(r, oid, NULL);264if (kind == OBJ_COMMIT)265return 1;266if (kind != OBJ_TAG)267return 0;268
269/* We need to do this the hard way... */270obj = deref_tag(r, parse_object(r, oid), NULL, 0);271if (obj && obj->type == OBJ_COMMIT)272return 1;273return 0;274}
275
276static int disambiguate_tree_only(struct repository *r,277const struct object_id *oid,278void *cb_data UNUSED)279{
280int kind = oid_object_info(r, oid, NULL);281return kind == OBJ_TREE;282}
283
284static int disambiguate_treeish_only(struct repository *r,285const struct object_id *oid,286void *cb_data UNUSED)287{
288struct object *obj;289int kind;290
291kind = oid_object_info(r, oid, NULL);292if (kind == OBJ_TREE || kind == OBJ_COMMIT)293return 1;294if (kind != OBJ_TAG)295return 0;296
297/* We need to do this the hard way... */298obj = deref_tag(r, parse_object(r, oid), NULL, 0);299if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))300return 1;301return 0;302}
303
304static int disambiguate_blob_only(struct repository *r,305const struct object_id *oid,306void *cb_data UNUSED)307{
308int kind = oid_object_info(r, oid, NULL);309return kind == OBJ_BLOB;310}
311
312static disambiguate_hint_fn default_disambiguate_hint;313
314int set_disambiguate_hint_config(const char *var, const char *value)315{
316static const struct {317const char *name;318disambiguate_hint_fn fn;319} hints[] = {320{ "none", NULL },321{ "commit", disambiguate_commit_only },322{ "committish", disambiguate_committish_only },323{ "tree", disambiguate_tree_only },324{ "treeish", disambiguate_treeish_only },325{ "blob", disambiguate_blob_only }326};327int i;328
329if (!value)330return config_error_nonbool(var);331
332for (i = 0; i < ARRAY_SIZE(hints); i++) {333if (!strcasecmp(value, hints[i].name)) {334default_disambiguate_hint = hints[i].fn;335return 0;336}337}338
339return error("unknown hint type for '%s': %s", var, value);340}
341
342static int init_object_disambiguation(struct repository *r,343const char *name, int len,344const struct git_hash_algo *algo,345struct disambiguate_state *ds)346{
347int i;348
349if (len < MINIMUM_ABBREV || len > GIT_MAX_HEXSZ)350return -1;351
352memset(ds, 0, sizeof(*ds));353
354for (i = 0; i < len ;i++) {355unsigned char c = name[i];356unsigned char val;357if (c >= '0' && c <= '9')358val = c - '0';359else if (c >= 'a' && c <= 'f')360val = c - 'a' + 10;361else if (c >= 'A' && c <='F') {362val = c - 'A' + 10;363c -= 'A' - 'a';364}365else366return -1;367ds->hex_pfx[i] = c;368if (!(i & 1))369val <<= 4;370ds->bin_pfx.hash[i >> 1] |= val;371}372
373ds->len = len;374ds->hex_pfx[len] = '\0';375ds->repo = r;376ds->bin_pfx.algo = algo ? hash_algo_by_ptr(algo) : GIT_HASH_UNKNOWN;377prepare_alt_odb(r);378return 0;379}
380
381struct ambiguous_output {382const struct disambiguate_state *ds;383struct strbuf advice;384struct strbuf sb;385};386
387static int show_ambiguous_object(const struct object_id *oid, void *data)388{
389struct ambiguous_output *state = data;390const struct disambiguate_state *ds = state->ds;391struct strbuf *advice = &state->advice;392struct strbuf *sb = &state->sb;393int type;394const char *hash;395
396if (ds->fn && !ds->fn(ds->repo, oid, ds->cb_data))397return 0;398
399hash = repo_find_unique_abbrev(ds->repo, oid, DEFAULT_ABBREV);400type = oid_object_info(ds->repo, oid, NULL);401
402if (type < 0) {403/*404* TRANSLATORS: This is a line of ambiguous object
405* output shown when we cannot look up or parse the
406* object in question. E.g. "deadbeef [bad object]".
407*/
408strbuf_addf(sb, _("%s [bad object]"), hash);409goto out;410}411
412assert(type == OBJ_TREE || type == OBJ_COMMIT ||413type == OBJ_BLOB || type == OBJ_TAG);414
415if (type == OBJ_COMMIT) {416struct strbuf date = STRBUF_INIT;417struct strbuf msg = STRBUF_INIT;418struct commit *commit = lookup_commit(ds->repo, oid);419
420if (commit) {421struct pretty_print_context pp = {0};422pp.date_mode.type = DATE_SHORT;423repo_format_commit_message(the_repository, commit,424"%ad", &date, &pp);425repo_format_commit_message(the_repository, commit,426"%s", &msg, &pp);427}428
429/*430* TRANSLATORS: This is a line of ambiguous commit
431* object output. E.g.:
432*
433* "deadbeef commit 2021-01-01 - Some Commit Message"
434*/
435strbuf_addf(sb, _("%s commit %s - %s"), hash, date.buf,436msg.buf);437
438strbuf_release(&date);439strbuf_release(&msg);440} else if (type == OBJ_TAG) {441struct tag *tag = lookup_tag(ds->repo, oid);442
443if (!parse_tag(tag) && tag->tag) {444/*445* TRANSLATORS: This is a line of ambiguous
446* tag object output. E.g.:
447*
448* "deadbeef tag 2022-01-01 - Some Tag Message"
449*
450* The second argument is the YYYY-MM-DD found
451* in the tag.
452*
453* The third argument is the "tag" string
454* from object.c.
455*/
456strbuf_addf(sb, _("%s tag %s - %s"), hash,457show_date(tag->date, 0, DATE_MODE(SHORT)),458tag->tag);459} else {460/*461* TRANSLATORS: This is a line of ambiguous
462* tag object output where we couldn't parse
463* the tag itself. E.g.:
464*
465* "deadbeef [bad tag, could not parse it]"
466*/
467strbuf_addf(sb, _("%s [bad tag, could not parse it]"),468hash);469}470} else if (type == OBJ_TREE) {471/*472* TRANSLATORS: This is a line of ambiguous <type>
473* object output. E.g. "deadbeef tree".
474*/
475strbuf_addf(sb, _("%s tree"), hash);476} else if (type == OBJ_BLOB) {477/*478* TRANSLATORS: This is a line of ambiguous <type>
479* object output. E.g. "deadbeef blob".
480*/
481strbuf_addf(sb, _("%s blob"), hash);482}483
484
485out:486/*487* TRANSLATORS: This is line item of ambiguous object output
488* from describe_ambiguous_object() above. For RTL languages
489* you'll probably want to swap the "%s" and leading " " space
490* around.
491*/
492strbuf_addf(advice, _(" %s\n"), sb->buf);493
494strbuf_reset(sb);495return 0;496}
497
498static int collect_ambiguous(const struct object_id *oid, void *data)499{
500oid_array_append(data, oid);501return 0;502}
503
504static int repo_collect_ambiguous(struct repository *r UNUSED,505const struct object_id *oid,506void *data)507{
508return collect_ambiguous(oid, data);509}
510
511static int sort_ambiguous(const void *va, const void *vb, void *ctx)512{
513struct repository *sort_ambiguous_repo = ctx;514const struct object_id *a = va, *b = vb;515int a_type = oid_object_info(sort_ambiguous_repo, a, NULL);516int b_type = oid_object_info(sort_ambiguous_repo, b, NULL);517int a_type_sort;518int b_type_sort;519
520/*521* Sorts by hash within the same object type, just as
522* oid_array_for_each_unique() would do.
523*/
524if (a_type == b_type) {525if (a->algo == b->algo)526return oidcmp(a, b);527else528return a->algo > b->algo ? 1 : -1;529}530
531/*532* Between object types show tags, then commits, and finally
533* trees and blobs.
534*
535* The object_type enum is commit, tree, blob, tag, but we
536* want tag, commit, tree blob. Cleverly (perhaps too
537* cleverly) do that with modulus, since the enum assigns 1 to
538* commit, so tag becomes 0.
539*/
540a_type_sort = a_type % 4;541b_type_sort = b_type % 4;542return a_type_sort > b_type_sort ? 1 : -1;543}
544
545static void sort_ambiguous_oid_array(struct repository *r, struct oid_array *a)546{
547QSORT_S(a->oid, a->nr, sort_ambiguous, r);548}
549
550static enum get_oid_result get_short_oid(struct repository *r,551const char *name, int len,552struct object_id *oid,553unsigned flags)554{
555int status;556struct disambiguate_state ds;557int quietly = !!(flags & GET_OID_QUIETLY);558const struct git_hash_algo *algo = r->hash_algo;559
560if (flags & GET_OID_HASH_ANY)561algo = NULL;562
563if (init_object_disambiguation(r, name, len, algo, &ds) < 0)564return -1;565
566if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))567BUG("multiple get_short_oid disambiguator flags");568
569if (flags & GET_OID_COMMIT)570ds.fn = disambiguate_commit_only;571else if (flags & GET_OID_COMMITTISH)572ds.fn = disambiguate_committish_only;573else if (flags & GET_OID_TREE)574ds.fn = disambiguate_tree_only;575else if (flags & GET_OID_TREEISH)576ds.fn = disambiguate_treeish_only;577else if (flags & GET_OID_BLOB)578ds.fn = disambiguate_blob_only;579else580ds.fn = default_disambiguate_hint;581
582find_short_object_filename(&ds);583find_short_packed_object(&ds);584status = finish_object_disambiguation(&ds, oid);585
586/*587* If we didn't find it, do the usual reprepare() slow-path,
588* since the object may have recently been added to the repository
589* or migrated from loose to packed.
590*/
591if (status == MISSING_OBJECT) {592reprepare_packed_git(r);593find_short_object_filename(&ds);594find_short_packed_object(&ds);595status = finish_object_disambiguation(&ds, oid);596}597
598if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {599struct oid_array collect = OID_ARRAY_INIT;600struct ambiguous_output out = {601.ds = &ds,602.sb = STRBUF_INIT,603.advice = STRBUF_INIT,604};605
606error(_("short object ID %s is ambiguous"), ds.hex_pfx);607
608/*609* We may still have ambiguity if we simply saw a series of
610* candidates that did not satisfy our hint function. In
611* that case, we still want to show them, so disable the hint
612* function entirely.
613*/
614if (!ds.ambiguous)615ds.fn = NULL;616
617repo_for_each_abbrev(r, ds.hex_pfx, algo, collect_ambiguous, &collect);618sort_ambiguous_oid_array(r, &collect);619
620if (oid_array_for_each(&collect, show_ambiguous_object, &out))621BUG("show_ambiguous_object shouldn't return non-zero");622
623/*624* TRANSLATORS: The argument is the list of ambiguous
625* objects composed in show_ambiguous_object(). See
626* its "TRANSLATORS" comments for details.
627*/
628advise(_("The candidates are:\n%s"), out.advice.buf);629
630oid_array_clear(&collect);631strbuf_release(&out.advice);632strbuf_release(&out.sb);633}634
635return status;636}
637
638int repo_for_each_abbrev(struct repository *r, const char *prefix,639const struct git_hash_algo *algo,640each_abbrev_fn fn, void *cb_data)641{
642struct oid_array collect = OID_ARRAY_INIT;643struct disambiguate_state ds;644int ret;645
646if (init_object_disambiguation(r, prefix, strlen(prefix), algo, &ds) < 0)647return -1;648
649ds.always_call_fn = 1;650ds.fn = repo_collect_ambiguous;651ds.cb_data = &collect;652find_short_object_filename(&ds);653find_short_packed_object(&ds);654
655ret = oid_array_for_each_unique(&collect, fn, cb_data);656oid_array_clear(&collect);657return ret;658}
659
660/*
661* Return the slot of the most-significant bit set in "val". There are various
662* ways to do this quickly with fls() or __builtin_clzl(), but speed is
663* probably not a big deal here.
664*/
665static unsigned msb(unsigned long val)666{
667unsigned r = 0;668while (val >>= 1)669r++;670return r;671}
672
673struct min_abbrev_data {674unsigned int init_len;675unsigned int cur_len;676char *hex;677struct repository *repo;678const struct object_id *oid;679};680
681static inline char get_hex_char_from_oid(const struct object_id *oid,682unsigned int pos)683{
684static const char hex[] = "0123456789abcdef";685
686if ((pos & 1) == 0)687return hex[oid->hash[pos >> 1] >> 4];688else689return hex[oid->hash[pos >> 1] & 0xf];690}
691
692static int extend_abbrev_len(const struct object_id *oid, void *cb_data)693{
694struct min_abbrev_data *mad = cb_data;695
696unsigned int i = mad->init_len;697while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))698i++;699
700if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)701mad->cur_len = i + 1;702
703return 0;704}
705
706static int repo_extend_abbrev_len(struct repository *r UNUSED,707const struct object_id *oid,708void *cb_data)709{
710return extend_abbrev_len(oid, cb_data);711}
712
713static void find_abbrev_len_for_midx(struct multi_pack_index *m,714struct min_abbrev_data *mad)715{
716for (; m; m = m->base_midx) {717int match = 0;718uint32_t num, first = 0;719struct object_id oid;720const struct object_id *mad_oid;721
722if (!m->num_objects)723continue;724
725num = m->num_objects + m->num_objects_in_base;726mad_oid = mad->oid;727match = bsearch_one_midx(mad_oid, m, &first);728
729/*730* first is now the position in the packfile where we
731* would insert mad->hash if it does not exist (or the
732* position of mad->hash if it does exist). Hence, we
733* consider a maximum of two objects nearby for the
734* abbreviation length.
735*/
736mad->init_len = 0;737if (!match) {738if (nth_midxed_object_oid(&oid, m, first))739extend_abbrev_len(&oid, mad);740} else if (first < num - 1) {741if (nth_midxed_object_oid(&oid, m, first + 1))742extend_abbrev_len(&oid, mad);743}744if (first > 0) {745if (nth_midxed_object_oid(&oid, m, first - 1))746extend_abbrev_len(&oid, mad);747}748mad->init_len = mad->cur_len;749}750}
751
752static void find_abbrev_len_for_pack(struct packed_git *p,753struct min_abbrev_data *mad)754{
755int match = 0;756uint32_t num, first = 0;757struct object_id oid;758const struct object_id *mad_oid;759
760if (p->multi_pack_index)761return;762
763if (open_pack_index(p) || !p->num_objects)764return;765
766num = p->num_objects;767mad_oid = mad->oid;768match = bsearch_pack(mad_oid, p, &first);769
770/*771* first is now the position in the packfile where we would insert
772* mad->hash if it does not exist (or the position of mad->hash if
773* it does exist). Hence, we consider a maximum of two objects
774* nearby for the abbreviation length.
775*/
776mad->init_len = 0;777if (!match) {778if (!nth_packed_object_id(&oid, p, first))779extend_abbrev_len(&oid, mad);780} else if (first < num - 1) {781if (!nth_packed_object_id(&oid, p, first + 1))782extend_abbrev_len(&oid, mad);783}784if (first > 0) {785if (!nth_packed_object_id(&oid, p, first - 1))786extend_abbrev_len(&oid, mad);787}788mad->init_len = mad->cur_len;789}
790
791static void find_abbrev_len_packed(struct min_abbrev_data *mad)792{
793struct multi_pack_index *m;794struct packed_git *p;795
796for (m = get_multi_pack_index(mad->repo); m; m = m->next)797find_abbrev_len_for_midx(m, mad);798for (p = get_packed_git(mad->repo); p; p = p->next)799find_abbrev_len_for_pack(p, mad);800}
801
802void strbuf_repo_add_unique_abbrev(struct strbuf *sb, struct repository *repo,803const struct object_id *oid, int abbrev_len)804{
805int r;806strbuf_grow(sb, GIT_MAX_HEXSZ + 1);807r = repo_find_unique_abbrev_r(repo, sb->buf + sb->len, oid, abbrev_len);808strbuf_setlen(sb, sb->len + r);809}
810
811void strbuf_add_unique_abbrev(struct strbuf *sb, const struct object_id *oid,812int abbrev_len)813{
814strbuf_repo_add_unique_abbrev(sb, the_repository, oid, abbrev_len);815}
816
817int repo_find_unique_abbrev_r(struct repository *r, char *hex,818const struct object_id *oid, int len)819{
820const struct git_hash_algo *algo =821oid->algo ? &hash_algos[oid->algo] : r->hash_algo;822struct disambiguate_state ds;823struct min_abbrev_data mad;824struct object_id oid_ret;825const unsigned hexsz = algo->hexsz;826
827if (len < 0) {828unsigned long count = repo_approximate_object_count(r);829/*830* Add one because the MSB only tells us the highest bit set,
831* not including the value of all the _other_ bits (so "15"
832* is only one off of 2^4, but the MSB is the 3rd bit.
833*/
834len = msb(count) + 1;835/*836* We now know we have on the order of 2^len objects, which
837* expects a collision at 2^(len/2). But we also care about hex
838* chars, not bits, and there are 4 bits per hex. So all
839* together we need to divide by 2 and round up.
840*/
841len = DIV_ROUND_UP(len, 2);842/*843* For very small repos, we stick with our regular fallback.
844*/
845if (len < FALLBACK_DEFAULT_ABBREV)846len = FALLBACK_DEFAULT_ABBREV;847}848
849oid_to_hex_r(hex, oid);850if (len >= hexsz || !len)851return hexsz;852
853mad.repo = r;854mad.init_len = len;855mad.cur_len = len;856mad.hex = hex;857mad.oid = oid;858
859find_abbrev_len_packed(&mad);860
861if (init_object_disambiguation(r, hex, mad.cur_len, algo, &ds) < 0)862return -1;863
864ds.fn = repo_extend_abbrev_len;865ds.always_call_fn = 1;866ds.cb_data = (void *)&mad;867
868find_short_object_filename(&ds);869(void)finish_object_disambiguation(&ds, &oid_ret);870
871hex[mad.cur_len] = 0;872return mad.cur_len;873}
874
875const char *repo_find_unique_abbrev(struct repository *r,876const struct object_id *oid,877int len)878{
879static int bufno;880static char hexbuffer[4][GIT_MAX_HEXSZ + 1];881char *hex = hexbuffer[bufno];882bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);883repo_find_unique_abbrev_r(r, hex, oid, len);884return hex;885}
886
887static int ambiguous_path(const char *path, int len)888{
889int slash = 1;890int cnt;891
892for (cnt = 0; cnt < len; cnt++) {893switch (*path++) {894case '\0':895break;896case '/':897if (slash)898break;899slash = 1;900continue;901case '.':902continue;903default:904slash = 0;905continue;906}907break;908}909return slash;910}
911
912static inline int at_mark(const char *string, int len,913const char **suffix, int nr)914{
915int i;916
917for (i = 0; i < nr; i++) {918int suffix_len = strlen(suffix[i]);919if (suffix_len <= len920&& !strncasecmp(string, suffix[i], suffix_len))921return suffix_len;922}923return 0;924}
925
926static inline int upstream_mark(const char *string, int len)927{
928const char *suffix[] = { "@{upstream}", "@{u}" };929return at_mark(string, len, suffix, ARRAY_SIZE(suffix));930}
931
932static inline int push_mark(const char *string, int len)933{
934const char *suffix[] = { "@{push}" };935return at_mark(string, len, suffix, ARRAY_SIZE(suffix));936}
937
938static enum get_oid_result get_oid_1(struct repository *r, const char *name, int len, struct object_id *oid, unsigned lookup_flags);939static int interpret_nth_prior_checkout(struct repository *r, const char *name, int namelen, struct strbuf *buf);940
941static int get_oid_basic(struct repository *r, const char *str, int len,942struct object_id *oid, unsigned int flags)943{
944static const char *warn_msg = "refname '%.*s' is ambiguous.";945static const char *object_name_msg = N_(946"Git normally never creates a ref that ends with 40 hex characters\n"947"because it will be ignored when you just specify 40-hex. These refs\n"948"may be created by mistake. For example,\n"949"\n"950" git switch -c $br $(git rev-parse ...)\n"951"\n"952"where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"953"examine these refs and maybe delete them. Turn this message off by\n"954"running \"git config advice.objectNameWarning false\"");955struct object_id tmp_oid;956char *real_ref = NULL;957int refs_found = 0;958int at, reflog_len, nth_prior = 0;959int fatal = !(flags & GET_OID_QUIETLY);960
961if (len == r->hash_algo->hexsz && !get_oid_hex(str, oid)) {962if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {963refs_found = repo_dwim_ref(r, str, len, &tmp_oid, &real_ref, 0);964if (refs_found > 0) {965warning(warn_msg, len, str);966if (advice_enabled(ADVICE_OBJECT_NAME_WARNING))967fprintf(stderr, "%s\n", _(object_name_msg));968}969free(real_ref);970}971return 0;972}973
974/* basic@{time or number or -number} format to query ref-log */975reflog_len = at = 0;976if (len && str[len-1] == '}') {977for (at = len-4; at >= 0; at--) {978if (str[at] == '@' && str[at+1] == '{') {979if (str[at+2] == '-') {980if (at != 0)981/* @{-N} not at start */982return -1;983nth_prior = 1;984continue;985}986if (!upstream_mark(str + at, len - at) &&987!push_mark(str + at, len - at)) {988reflog_len = (len-1) - (at+2);989len = at;990}991break;992}993}994}995
996/* Accept only unambiguous ref paths. */997if (len && ambiguous_path(str, len))998return -1;999
1000if (nth_prior) {1001struct strbuf buf = STRBUF_INIT;1002int detached;1003
1004if (interpret_nth_prior_checkout(r, str, len, &buf) > 0) {1005detached = (buf.len == r->hash_algo->hexsz && !get_oid_hex(buf.buf, oid));1006strbuf_release(&buf);1007if (detached)1008return 0;1009}1010}1011
1012if (!len && reflog_len)1013/* allow "@{...}" to mean the current branch reflog */1014refs_found = repo_dwim_ref(r, "HEAD", 4, oid, &real_ref, !fatal);1015else if (reflog_len)1016refs_found = repo_dwim_log(r, str, len, oid, &real_ref);1017else1018refs_found = repo_dwim_ref(r, str, len, oid, &real_ref, !fatal);1019
1020if (!refs_found)1021return -1;1022
1023if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&1024(refs_found > 1 ||1025!get_short_oid(r, str, len, &tmp_oid, GET_OID_QUIETLY)))1026warning(warn_msg, len, str);1027
1028if (reflog_len) {1029int nth, i;1030timestamp_t at_time;1031timestamp_t co_time;1032int co_tz, co_cnt;1033
1034/* Is it asking for N-th entry, or approxidate? */1035for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {1036char ch = str[at+2+i];1037if ('0' <= ch && ch <= '9')1038nth = nth * 10 + ch - '0';1039else1040nth = -1;1041}1042if (100000000 <= nth) {1043at_time = nth;1044nth = -1;1045} else if (0 <= nth)1046at_time = 0;1047else {1048int errors = 0;1049char *tmp = xstrndup(str + at + 2, reflog_len);1050at_time = approxidate_careful(tmp, &errors);1051free(tmp);1052if (errors) {1053free(real_ref);1054return -1;1055}1056}1057if (read_ref_at(get_main_ref_store(r),1058real_ref, flags, at_time, nth, oid, NULL,1059&co_time, &co_tz, &co_cnt)) {1060if (!len) {1061if (!skip_prefix(real_ref, "refs/heads/", &str))1062str = "HEAD";1063len = strlen(str);1064}1065if (at_time) {1066if (!(flags & GET_OID_QUIETLY)) {1067warning(_("log for '%.*s' only goes back to %s"),1068len, str,1069show_date(co_time, co_tz, DATE_MODE(RFC2822)));1070}1071} else if (nth == co_cnt && !is_null_oid(oid)) {1072/*1073* We were asked for the Nth reflog (counting
1074* from 0), but there were only N entries.
1075* read_ref_at() will have returned "1" to tell
1076* us it did not find an entry, but it did
1077* still fill in the oid with the "old" value,
1078* which we can use.
1079*/
1080} else {1081if (flags & GET_OID_QUIETLY) {1082exit(128);1083}1084die(_("log for '%.*s' only has %d entries"),1085len, str, co_cnt);1086}1087}1088}1089
1090free(real_ref);1091return 0;1092}
1093
1094static enum get_oid_result get_parent(struct repository *r,1095const char *name, int len,1096struct object_id *result, int idx)1097{
1098struct object_id oid;1099enum get_oid_result ret = get_oid_1(r, name, len, &oid,1100GET_OID_COMMITTISH);1101struct commit *commit;1102struct commit_list *p;1103
1104if (ret)1105return ret;1106commit = lookup_commit_reference(r, &oid);1107if (repo_parse_commit(r, commit))1108return MISSING_OBJECT;1109if (!idx) {1110oidcpy(result, &commit->object.oid);1111return FOUND;1112}1113p = commit->parents;1114while (p) {1115if (!--idx) {1116oidcpy(result, &p->item->object.oid);1117return FOUND;1118}1119p = p->next;1120}1121return MISSING_OBJECT;1122}
1123
1124static enum get_oid_result get_nth_ancestor(struct repository *r,1125const char *name, int len,1126struct object_id *result,1127int generation)1128{
1129struct object_id oid;1130struct commit *commit;1131int ret;1132
1133ret = get_oid_1(r, name, len, &oid, GET_OID_COMMITTISH);1134if (ret)1135return ret;1136commit = lookup_commit_reference(r, &oid);1137if (!commit)1138return MISSING_OBJECT;1139
1140while (generation--) {1141if (repo_parse_commit(r, commit) || !commit->parents)1142return MISSING_OBJECT;1143commit = commit->parents->item;1144}1145oidcpy(result, &commit->object.oid);1146return FOUND;1147}
1148
1149struct object *repo_peel_to_type(struct repository *r, const char *name, int namelen,1150struct object *o, enum object_type expected_type)1151{
1152if (name && !namelen)1153namelen = strlen(name);1154while (1) {1155if (!o || (!o->parsed && !parse_object(r, &o->oid)))1156return NULL;1157if (expected_type == OBJ_ANY || o->type == expected_type)1158return o;1159if (o->type == OBJ_TAG)1160o = ((struct tag*) o)->tagged;1161else if (o->type == OBJ_COMMIT)1162o = &(repo_get_commit_tree(r, ((struct commit *)o))->object);1163else {1164if (name)1165error("%.*s: expected %s type, but the object "1166"dereferences to %s type",1167namelen, name, type_name(expected_type),1168type_name(o->type));1169return NULL;1170}1171}1172}
1173
1174static int peel_onion(struct repository *r, const char *name, int len,1175struct object_id *oid, unsigned lookup_flags)1176{
1177struct object_id outer;1178const char *sp;1179unsigned int expected_type = 0;1180struct object *o;1181
1182/*1183* "ref^{type}" dereferences ref repeatedly until you cannot
1184* dereference anymore, or you get an object of given type,
1185* whichever comes first. "ref^{}" means just dereference
1186* tags until you get a non-tag. "ref^0" is a shorthand for
1187* "ref^{commit}". "commit^{tree}" could be used to find the
1188* top-level tree of the given commit.
1189*/
1190if (len < 4 || name[len-1] != '}')1191return -1;1192
1193for (sp = name + len - 1; name <= sp; sp--) {1194int ch = *sp;1195if (ch == '{' && name < sp && sp[-1] == '^')1196break;1197}1198if (sp <= name)1199return -1;1200
1201sp++; /* beginning of type name, or closing brace for empty */1202if (starts_with(sp, "commit}"))1203expected_type = OBJ_COMMIT;1204else if (starts_with(sp, "tag}"))1205expected_type = OBJ_TAG;1206else if (starts_with(sp, "tree}"))1207expected_type = OBJ_TREE;1208else if (starts_with(sp, "blob}"))1209expected_type = OBJ_BLOB;1210else if (starts_with(sp, "object}"))1211expected_type = OBJ_ANY;1212else if (sp[0] == '}')1213expected_type = OBJ_NONE;1214else if (sp[0] == '/')1215expected_type = OBJ_COMMIT;1216else1217return -1;1218
1219lookup_flags &= ~GET_OID_DISAMBIGUATORS;1220if (expected_type == OBJ_COMMIT)1221lookup_flags |= GET_OID_COMMITTISH;1222else if (expected_type == OBJ_TREE)1223lookup_flags |= GET_OID_TREEISH;1224
1225if (get_oid_1(r, name, sp - name - 2, &outer, lookup_flags))1226return -1;1227
1228o = parse_object(r, &outer);1229if (!o)1230return -1;1231if (!expected_type) {1232o = deref_tag(r, o, name, sp - name - 2);1233if (!o || (!o->parsed && !parse_object(r, &o->oid)))1234return -1;1235oidcpy(oid, &o->oid);1236return 0;1237}1238
1239/*1240* At this point, the syntax look correct, so
1241* if we do not get the needed object, we should
1242* barf.
1243*/
1244o = repo_peel_to_type(r, name, len, o, expected_type);1245if (!o)1246return -1;1247
1248oidcpy(oid, &o->oid);1249if (sp[0] == '/') {1250/* "$commit^{/foo}" */1251char *prefix;1252int ret;1253struct commit_list *list = NULL;1254
1255/*1256* $commit^{/}. Some regex implementation may reject.
1257* We don't need regex anyway. '' pattern always matches.
1258*/
1259if (sp[1] == '}')1260return 0;1261
1262prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));1263commit_list_insert((struct commit *)o, &list);1264ret = get_oid_oneline(r, prefix, oid, list);1265
1266free_commit_list(list);1267free(prefix);1268return ret;1269}1270return 0;1271}
1272
1273static int get_describe_name(struct repository *r,1274const char *name, int len,1275struct object_id *oid)1276{
1277const char *cp;1278unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;1279
1280for (cp = name + len - 1; name + 2 <= cp; cp--) {1281char ch = *cp;1282if (!isxdigit(ch)) {1283/* We must be looking at g in "SOMETHING-g"1284* for it to be describe output.
1285*/
1286if (ch == 'g' && cp[-1] == '-') {1287cp++;1288len -= cp - name;1289return get_short_oid(r,1290cp, len, oid, flags);1291}1292}1293}1294return -1;1295}
1296
1297static enum get_oid_result get_oid_1(struct repository *r,1298const char *name, int len,1299struct object_id *oid,1300unsigned lookup_flags)1301{
1302int ret, has_suffix;1303const char *cp;1304
1305/*1306* "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1307*/
1308has_suffix = 0;1309for (cp = name + len - 1; name <= cp; cp--) {1310int ch = *cp;1311if ('0' <= ch && ch <= '9')1312continue;1313if (ch == '~' || ch == '^')1314has_suffix = ch;1315break;1316}1317
1318if (has_suffix) {1319unsigned int num = 0;1320int len1 = cp - name;1321cp++;1322while (cp < name + len) {1323unsigned int digit = *cp++ - '0';1324if (unsigned_mult_overflows(num, 10))1325return MISSING_OBJECT;1326num *= 10;1327if (unsigned_add_overflows(num, digit))1328return MISSING_OBJECT;1329num += digit;1330}1331if (!num && len1 == len - 1)1332num = 1;1333else if (num > INT_MAX)1334return MISSING_OBJECT;1335if (has_suffix == '^')1336return get_parent(r, name, len1, oid, num);1337/* else if (has_suffix == '~') -- goes without saying */1338return get_nth_ancestor(r, name, len1, oid, num);1339}1340
1341ret = peel_onion(r, name, len, oid, lookup_flags);1342if (!ret)1343return FOUND;1344
1345ret = get_oid_basic(r, name, len, oid, lookup_flags);1346if (!ret)1347return FOUND;1348
1349/* It could be describe output that is "SOMETHING-gXXXX" */1350ret = get_describe_name(r, name, len, oid);1351if (!ret)1352return FOUND;1353
1354return get_short_oid(r, name, len, oid, lookup_flags);1355}
1356
1357/*
1358* This interprets names like ':/Initial revision of "git"' by searching
1359* through history and returning the first commit whose message starts
1360* the given regular expression.
1361*
1362* For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1363*
1364* For a literal '!' character at the beginning of a pattern, you have to repeat
1365* that, like: ':/!!foo'
1366*
1367* For future extension, all other sequences beginning with ':/!' are reserved.
1368*/
1369
1370/* Remember to update object flag allocation in object.h */
1371#define ONELINE_SEEN (1u<<20)1372
1373struct handle_one_ref_cb {1374struct repository *repo;1375struct commit_list **list;1376};1377
1378static int handle_one_ref(const char *path, const char *referent UNUSED, const struct object_id *oid,1379int flag UNUSED,1380void *cb_data)1381{
1382struct handle_one_ref_cb *cb = cb_data;1383struct commit_list **list = cb->list;1384struct object *object = parse_object(cb->repo, oid);1385if (!object)1386return 0;1387if (object->type == OBJ_TAG) {1388object = deref_tag(cb->repo, object, path,1389strlen(path));1390if (!object)1391return 0;1392}1393if (object->type != OBJ_COMMIT)1394return 0;1395commit_list_insert((struct commit *)object, list);1396return 0;1397}
1398
1399static int get_oid_oneline(struct repository *r,1400const char *prefix, struct object_id *oid,1401const struct commit_list *list)1402{
1403struct commit_list *copy = NULL;1404const struct commit_list *l;1405int found = 0;1406int negative = 0;1407regex_t regex;1408
1409if (prefix[0] == '!') {1410prefix++;1411
1412if (prefix[0] == '-') {1413prefix++;1414negative = 1;1415} else if (prefix[0] != '!') {1416return -1;1417}1418}1419
1420if (regcomp(®ex, prefix, REG_EXTENDED))1421return -1;1422
1423for (l = list; l; l = l->next) {1424l->item->object.flags |= ONELINE_SEEN;1425commit_list_insert(l->item, ©);1426}1427while (copy) {1428const char *p, *buf;1429struct commit *commit;1430int matches;1431
1432commit = pop_most_recent_commit(©, ONELINE_SEEN);1433if (!parse_object(r, &commit->object.oid))1434continue;1435buf = repo_get_commit_buffer(r, commit, NULL);1436p = strstr(buf, "\n\n");1437matches = negative ^ (p && !regexec(®ex, p + 2, 0, NULL, 0));1438repo_unuse_commit_buffer(r, commit, buf);1439
1440if (matches) {1441oidcpy(oid, &commit->object.oid);1442found = 1;1443break;1444}1445}1446regfree(®ex);1447for (l = list; l; l = l->next)1448clear_commit_marks(l->item, ONELINE_SEEN);1449free_commit_list(copy);1450return found ? 0 : -1;1451}
1452
1453struct grab_nth_branch_switch_cbdata {1454int remaining;1455struct strbuf *sb;1456};1457
1458static int grab_nth_branch_switch(struct object_id *ooid UNUSED,1459struct object_id *noid UNUSED,1460const char *email UNUSED,1461timestamp_t timestamp UNUSED,1462int tz UNUSED,1463const char *message, void *cb_data)1464{
1465struct grab_nth_branch_switch_cbdata *cb = cb_data;1466const char *match = NULL, *target = NULL;1467size_t len;1468
1469if (skip_prefix(message, "checkout: moving from ", &match))1470target = strstr(match, " to ");1471
1472if (!match || !target)1473return 0;1474if (--(cb->remaining) == 0) {1475len = target - match;1476strbuf_reset(cb->sb);1477strbuf_add(cb->sb, match, len);1478return 1; /* we are done */1479}1480return 0;1481}
1482
1483/*
1484* Parse @{-N} syntax, return the number of characters parsed
1485* if successful; otherwise signal an error with negative value.
1486*/
1487static int interpret_nth_prior_checkout(struct repository *r,1488const char *name, int namelen,1489struct strbuf *buf)1490{
1491long nth;1492int retval;1493struct grab_nth_branch_switch_cbdata cb;1494const char *brace;1495char *num_end;1496
1497if (namelen < 4)1498return -1;1499if (name[0] != '@' || name[1] != '{' || name[2] != '-')1500return -1;1501brace = memchr(name, '}', namelen);1502if (!brace)1503return -1;1504nth = strtol(name + 3, &num_end, 10);1505if (num_end != brace)1506return -1;1507if (nth <= 0)1508return -1;1509cb.remaining = nth;1510cb.sb = buf;1511
1512retval = refs_for_each_reflog_ent_reverse(get_main_ref_store(r),1513"HEAD", grab_nth_branch_switch, &cb);1514if (0 < retval) {1515retval = brace - name + 1;1516} else1517retval = 0;1518
1519return retval;1520}
1521
1522int repo_get_oid_mb(struct repository *r,1523const char *name,1524struct object_id *oid)1525{
1526struct commit *one, *two;1527struct commit_list *mbs = NULL;1528struct object_id oid_tmp;1529const char *dots;1530int st;1531
1532dots = strstr(name, "...");1533if (!dots)1534return repo_get_oid(r, name, oid);1535if (dots == name)1536st = repo_get_oid(r, "HEAD", &oid_tmp);1537else {1538struct strbuf sb;1539strbuf_init(&sb, dots - name);1540strbuf_add(&sb, name, dots - name);1541st = repo_get_oid_committish(r, sb.buf, &oid_tmp);1542strbuf_release(&sb);1543}1544if (st)1545return st;1546one = lookup_commit_reference_gently(r, &oid_tmp, 0);1547if (!one)1548return -1;1549
1550if (repo_get_oid_committish(r, dots[3] ? (dots + 3) : "HEAD", &oid_tmp))1551return -1;1552two = lookup_commit_reference_gently(r, &oid_tmp, 0);1553if (!two)1554return -1;1555if (repo_get_merge_bases(r, one, two, &mbs) < 0) {1556free_commit_list(mbs);1557return -1;1558}1559if (!mbs || mbs->next)1560st = -1;1561else {1562st = 0;1563oidcpy(oid, &mbs->item->object.oid);1564}1565free_commit_list(mbs);1566return st;1567}
1568
1569/* parse @something syntax, when 'something' is not {.*} */
1570static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)1571{
1572const char *next;1573
1574if (len || name[1] == '{')1575return -1;1576
1577/* make sure it's a single @, or @@{.*}, not @foo */1578next = memchr(name + len + 1, '@', namelen - len - 1);1579if (next && next[1] != '{')1580return -1;1581if (!next)1582next = name + namelen;1583if (next != name + 1)1584return -1;1585
1586strbuf_reset(buf);1587strbuf_add(buf, "HEAD", 4);1588return 1;1589}
1590
1591static int reinterpret(struct repository *r,1592const char *name, int namelen, int len,1593struct strbuf *buf, unsigned allowed)1594{
1595/* we have extra data, which might need further processing */1596struct strbuf tmp = STRBUF_INIT;1597int used = buf->len;1598int ret;1599struct interpret_branch_name_options options = {1600.allowed = allowed1601};1602
1603strbuf_add(buf, name + len, namelen - len);1604ret = repo_interpret_branch_name(r, buf->buf, buf->len, &tmp, &options);1605/* that data was not interpreted, remove our cruft */1606if (ret < 0) {1607strbuf_setlen(buf, used);1608return len;1609}1610strbuf_reset(buf);1611strbuf_addbuf(buf, &tmp);1612strbuf_release(&tmp);1613/* tweak for size of {-N} versus expanded ref name */1614return ret - used + len;1615}
1616
1617static void set_shortened_ref(struct repository *r, struct strbuf *buf, const char *ref)1618{
1619char *s = refs_shorten_unambiguous_ref(get_main_ref_store(r), ref, 0);1620strbuf_reset(buf);1621strbuf_addstr(buf, s);1622free(s);1623}
1624
1625static int branch_interpret_allowed(const char *refname, unsigned allowed)1626{
1627if (!allowed)1628return 1;1629
1630if ((allowed & INTERPRET_BRANCH_LOCAL) &&1631starts_with(refname, "refs/heads/"))1632return 1;1633if ((allowed & INTERPRET_BRANCH_REMOTE) &&1634starts_with(refname, "refs/remotes/"))1635return 1;1636
1637return 0;1638}
1639
1640static int interpret_branch_mark(struct repository *r,1641const char *name, int namelen,1642int at, struct strbuf *buf,1643int (*get_mark)(const char *, int),1644const char *(*get_data)(struct branch *,1645struct strbuf *),1646const struct interpret_branch_name_options *options)1647{
1648int len;1649struct branch *branch;1650struct strbuf err = STRBUF_INIT;1651const char *value;1652
1653len = get_mark(name + at, namelen - at);1654if (!len)1655return -1;1656
1657if (memchr(name, ':', at))1658return -1;1659
1660if (at) {1661char *name_str = xmemdupz(name, at);1662branch = branch_get(name_str);1663free(name_str);1664} else1665branch = branch_get(NULL);1666
1667value = get_data(branch, &err);1668if (!value) {1669if (options->nonfatal_dangling_mark) {1670strbuf_release(&err);1671return -1;1672} else {1673die("%s", err.buf);1674}1675}1676
1677if (!branch_interpret_allowed(value, options->allowed))1678return -1;1679
1680set_shortened_ref(r, buf, value);1681return len + at;1682}
1683
1684int repo_interpret_branch_name(struct repository *r,1685const char *name, int namelen,1686struct strbuf *buf,1687const struct interpret_branch_name_options *options)1688{
1689char *at;1690const char *start;1691int len;1692
1693if (!namelen)1694namelen = strlen(name);1695
1696if (!options->allowed || (options->allowed & INTERPRET_BRANCH_LOCAL)) {1697len = interpret_nth_prior_checkout(r, name, namelen, buf);1698if (!len) {1699return len; /* syntax Ok, not enough switches */1700} else if (len > 0) {1701if (len == namelen)1702return len; /* consumed all */1703else1704return reinterpret(r, name, namelen, len, buf,1705options->allowed);1706}1707}1708
1709for (start = name;1710(at = memchr(start, '@', namelen - (start - name)));1711start = at + 1) {1712
1713if (!options->allowed || (options->allowed & INTERPRET_BRANCH_HEAD)) {1714len = interpret_empty_at(name, namelen, at - name, buf);1715if (len > 0)1716return reinterpret(r, name, namelen, len, buf,1717options->allowed);1718}1719
1720len = interpret_branch_mark(r, name, namelen, at - name, buf,1721upstream_mark, branch_get_upstream,1722options);1723if (len > 0)1724return len;1725
1726len = interpret_branch_mark(r, name, namelen, at - name, buf,1727push_mark, branch_get_push,1728options);1729if (len > 0)1730return len;1731}1732
1733return -1;1734}
1735
1736void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)1737{
1738int len = strlen(name);1739struct interpret_branch_name_options options = {1740.allowed = allowed1741};1742int used = repo_interpret_branch_name(the_repository, name, len, sb,1743&options);1744
1745if (used < 0)1746used = 0;1747strbuf_add(sb, name + used, len - used);1748}
1749
1750int strbuf_check_branch_ref(struct strbuf *sb, const char *name)1751{
1752if (startup_info->have_repository)1753strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);1754else1755strbuf_addstr(sb, name);1756
1757/*1758* This splice must be done even if we end up rejecting the
1759* name; builtin/branch.c::copy_or_rename_branch() still wants
1760* to see what the name expanded to so that "branch -m" can be
1761* used as a tool to correct earlier mistakes.
1762*/
1763strbuf_splice(sb, 0, 0, "refs/heads/", 11);1764
1765if (*name == '-' ||1766!strcmp(sb->buf, "refs/heads/HEAD"))1767return -1;1768
1769return check_refname_format(sb->buf, 0);1770}
1771
1772void object_context_release(struct object_context *ctx)1773{
1774free(ctx->path);1775strbuf_release(&ctx->symlink_path);1776}
1777
1778/*
1779* This is like "get_oid_basic()", except it allows "object ID expressions",
1780* notably "xyz^" for "parent of xyz"
1781*/
1782int repo_get_oid(struct repository *r, const char *name, struct object_id *oid)1783{
1784struct object_context unused;1785int ret = get_oid_with_context(r, name, 0, oid, &unused);1786object_context_release(&unused);1787return ret;1788}
1789
1790/*
1791* This returns a non-zero value if the string (built using printf
1792* format and the given arguments) is not a valid object.
1793*/
1794int get_oidf(struct object_id *oid, const char *fmt, ...)1795{
1796va_list ap;1797int ret;1798struct strbuf sb = STRBUF_INIT;1799
1800va_start(ap, fmt);1801strbuf_vaddf(&sb, fmt, ap);1802va_end(ap);1803
1804ret = repo_get_oid(the_repository, sb.buf, oid);1805strbuf_release(&sb);1806
1807return ret;1808}
1809
1810/*
1811* Many callers know that the user meant to name a commit-ish by
1812* syntactical positions where the object name appears. Calling this
1813* function allows the machinery to disambiguate shorter-than-unique
1814* abbreviated object names between commit-ish and others.
1815*
1816* Note that this does NOT error out when the named object is not a
1817* commit-ish. It is merely to give a hint to the disambiguation
1818* machinery.
1819*/
1820int repo_get_oid_committish(struct repository *r,1821const char *name,1822struct object_id *oid)1823{
1824struct object_context unused;1825int ret = get_oid_with_context(r, name, GET_OID_COMMITTISH,1826oid, &unused);1827object_context_release(&unused);1828return ret;1829}
1830
1831int repo_get_oid_treeish(struct repository *r,1832const char *name,1833struct object_id *oid)1834{
1835struct object_context unused;1836int ret = get_oid_with_context(r, name, GET_OID_TREEISH,1837oid, &unused);1838object_context_release(&unused);1839return ret;1840}
1841
1842int repo_get_oid_commit(struct repository *r,1843const char *name,1844struct object_id *oid)1845{
1846struct object_context unused;1847int ret = get_oid_with_context(r, name, GET_OID_COMMIT,1848oid, &unused);1849object_context_release(&unused);1850return ret;1851}
1852
1853int repo_get_oid_tree(struct repository *r,1854const char *name,1855struct object_id *oid)1856{
1857struct object_context unused;1858int ret = get_oid_with_context(r, name, GET_OID_TREE,1859oid, &unused);1860object_context_release(&unused);1861return ret;1862}
1863
1864int repo_get_oid_blob(struct repository *r,1865const char *name,1866struct object_id *oid)1867{
1868struct object_context unused;1869int ret = get_oid_with_context(r, name, GET_OID_BLOB,1870oid, &unused);1871object_context_release(&unused);1872return ret;1873}
1874
1875/* Must be called only when object_name:filename doesn't exist. */
1876static void diagnose_invalid_oid_path(struct repository *r,1877const char *prefix,1878const char *filename,1879const struct object_id *tree_oid,1880const char *object_name,1881int object_name_len)1882{
1883struct object_id oid;1884unsigned short mode;1885
1886if (!prefix)1887prefix = "";1888
1889if (file_exists(filename))1890die(_("path '%s' exists on disk, but not in '%.*s'"),1891filename, object_name_len, object_name);1892if (is_missing_file_error(errno)) {1893char *fullname = xstrfmt("%s%s", prefix, filename);1894
1895if (!get_tree_entry(r, tree_oid, fullname, &oid, &mode)) {1896die(_("path '%s' exists, but not '%s'\n"1897"hint: Did you mean '%.*s:%s' aka '%.*s:./%s'?"),1898fullname,1899filename,1900object_name_len, object_name,1901fullname,1902object_name_len, object_name,1903filename);1904}1905die(_("path '%s' does not exist in '%.*s'"),1906filename, object_name_len, object_name);1907}1908}
1909
1910/* Must be called only when :stage:filename doesn't exist. */
1911static void diagnose_invalid_index_path(struct repository *r,1912int stage,1913const char *prefix,1914const char *filename)1915{
1916struct index_state *istate = r->index;1917const struct cache_entry *ce;1918int pos;1919unsigned namelen = strlen(filename);1920struct strbuf fullname = STRBUF_INIT;1921
1922if (!prefix)1923prefix = "";1924
1925/* Wrong stage number? */1926pos = index_name_pos(istate, filename, namelen);1927if (pos < 0)1928pos = -pos - 1;1929if (pos < istate->cache_nr) {1930ce = istate->cache[pos];1931if (!S_ISSPARSEDIR(ce->ce_mode) &&1932ce_namelen(ce) == namelen &&1933!memcmp(ce->name, filename, namelen))1934die(_("path '%s' is in the index, but not at stage %d\n"1935"hint: Did you mean ':%d:%s'?"),1936filename, stage,1937ce_stage(ce), filename);1938}1939
1940/* Confusion between relative and absolute filenames? */1941strbuf_addstr(&fullname, prefix);1942strbuf_addstr(&fullname, filename);1943pos = index_name_pos(istate, fullname.buf, fullname.len);1944if (pos < 0)1945pos = -pos - 1;1946if (pos < istate->cache_nr) {1947ce = istate->cache[pos];1948if (!S_ISSPARSEDIR(ce->ce_mode) &&1949ce_namelen(ce) == fullname.len &&1950!memcmp(ce->name, fullname.buf, fullname.len))1951die(_("path '%s' is in the index, but not '%s'\n"1952"hint: Did you mean ':%d:%s' aka ':%d:./%s'?"),1953fullname.buf, filename,1954ce_stage(ce), fullname.buf,1955ce_stage(ce), filename);1956}1957
1958if (repo_file_exists(r, filename))1959die(_("path '%s' exists on disk, but not in the index"), filename);1960if (is_missing_file_error(errno))1961die(_("path '%s' does not exist (neither on disk nor in the index)"),1962filename);1963
1964strbuf_release(&fullname);1965}
1966
1967
1968static char *resolve_relative_path(struct repository *r, const char *rel)1969{
1970if (!starts_with(rel, "./") && !starts_with(rel, "../"))1971return NULL;1972
1973if (r != the_repository || !is_inside_work_tree())1974die(_("relative path syntax can't be used outside working tree"));1975
1976/* die() inside prefix_path() if resolved path is outside worktree */1977return prefix_path(startup_info->prefix,1978startup_info->prefix ? strlen(startup_info->prefix) : 0,1979rel);1980}
1981
1982static int reject_tree_in_index(struct repository *repo,1983int only_to_die,1984const struct cache_entry *ce,1985int stage,1986const char *prefix,1987const char *cp)1988{
1989if (!S_ISSPARSEDIR(ce->ce_mode))1990return 0;1991if (only_to_die)1992diagnose_invalid_index_path(repo, stage, prefix, cp);1993return -1;1994}
1995
1996static enum get_oid_result get_oid_with_context_1(struct repository *repo,1997const char *name,1998unsigned flags,1999const char *prefix,2000struct object_id *oid,2001struct object_context *oc)2002{
2003int ret, bracket_depth;2004int namelen = strlen(name);2005const char *cp;2006int only_to_die = flags & GET_OID_ONLY_TO_DIE;2007
2008memset(oc, 0, sizeof(*oc));2009oc->mode = S_IFINVALID;2010strbuf_init(&oc->symlink_path, 0);2011ret = get_oid_1(repo, name, namelen, oid, flags);2012if (!ret && flags & GET_OID_REQUIRE_PATH)2013die(_("<object>:<path> required, only <object> '%s' given"),2014name);2015if (!ret)2016return ret;2017/*2018* tree:path --> object name of path in tree
2019* :path -> object name of absolute path in index
2020* :./path -> object name of path relative to cwd in index
2021* :[0-3]:path -> object name of path in index at stage
2022* :/foo -> recent commit matching foo
2023*/
2024if (name[0] == ':') {2025int stage = 0;2026const struct cache_entry *ce;2027char *new_path = NULL;2028int pos;2029if (!only_to_die && namelen > 2 && name[1] == '/') {2030struct handle_one_ref_cb cb;2031struct commit_list *list = NULL;2032
2033cb.repo = repo;2034cb.list = &list;2035refs_for_each_ref(get_main_ref_store(repo), handle_one_ref, &cb);2036refs_head_ref(get_main_ref_store(repo), handle_one_ref, &cb);2037commit_list_sort_by_date(&list);2038ret = get_oid_oneline(repo, name + 2, oid, list);2039
2040free_commit_list(list);2041return ret;2042}2043if (namelen < 3 ||2044name[2] != ':' ||2045name[1] < '0' || '3' < name[1])2046cp = name + 1;2047else {2048stage = name[1] - '0';2049cp = name + 3;2050}2051new_path = resolve_relative_path(repo, cp);2052if (!new_path) {2053namelen = namelen - (cp - name);2054} else {2055cp = new_path;2056namelen = strlen(cp);2057}2058
2059if (flags & GET_OID_RECORD_PATH)2060oc->path = xstrdup(cp);2061
2062if (!repo->index || !repo->index->cache)2063repo_read_index(repo);2064pos = index_name_pos(repo->index, cp, namelen);2065if (pos < 0)2066pos = -pos - 1;2067while (pos < repo->index->cache_nr) {2068ce = repo->index->cache[pos];2069if (ce_namelen(ce) != namelen ||2070memcmp(ce->name, cp, namelen))2071break;2072if (ce_stage(ce) == stage) {2073free(new_path);2074if (reject_tree_in_index(repo, only_to_die, ce,2075stage, prefix, cp))2076return -1;2077oidcpy(oid, &ce->oid);2078oc->mode = ce->ce_mode;2079return 0;2080}2081pos++;2082}2083if (only_to_die && name[1] && name[1] != '/')2084diagnose_invalid_index_path(repo, stage, prefix, cp);2085free(new_path);2086return -1;2087}2088for (cp = name, bracket_depth = 0; *cp; cp++) {2089if (*cp == '{')2090bracket_depth++;2091else if (bracket_depth && *cp == '}')2092bracket_depth--;2093else if (!bracket_depth && *cp == ':')2094break;2095}2096if (*cp == ':') {2097struct object_id tree_oid;2098int len = cp - name;2099unsigned sub_flags = flags;2100
2101sub_flags &= ~GET_OID_DISAMBIGUATORS;2102sub_flags |= GET_OID_TREEISH;2103
2104if (!get_oid_1(repo, name, len, &tree_oid, sub_flags)) {2105const char *filename = cp+1;2106char *new_filename = NULL;2107
2108new_filename = resolve_relative_path(repo, filename);2109if (new_filename)2110filename = new_filename;2111if (flags & GET_OID_FOLLOW_SYMLINKS) {2112ret = get_tree_entry_follow_symlinks(repo, &tree_oid,2113filename, oid, &oc->symlink_path,2114&oc->mode);2115} else {2116ret = get_tree_entry(repo, &tree_oid, filename, oid,2117&oc->mode);2118if (ret && only_to_die) {2119diagnose_invalid_oid_path(repo, prefix,2120filename,2121&tree_oid,2122name, len);2123}2124}2125if (flags & GET_OID_RECORD_PATH)2126oc->path = xstrdup(filename);2127
2128free(new_filename);2129return ret;2130} else {2131if (only_to_die)2132die(_("invalid object name '%.*s'."), len, name);2133}2134}2135return ret;2136}
2137
2138/*
2139* Call this function when you know "name" given by the end user must
2140* name an object but it doesn't; the function _may_ die with a better
2141* diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
2142* exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
2143* you have a chance to diagnose the error further.
2144*/
2145void maybe_die_on_misspelt_object_name(struct repository *r,2146const char *name,2147const char *prefix)2148{
2149struct object_context oc;2150struct object_id oid;2151get_oid_with_context_1(r, name, GET_OID_ONLY_TO_DIE | GET_OID_QUIETLY,2152prefix, &oid, &oc);2153object_context_release(&oc);2154}
2155
2156enum get_oid_result get_oid_with_context(struct repository *repo,2157const char *str,2158unsigned flags,2159struct object_id *oid,2160struct object_context *oc)2161{
2162if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)2163BUG("incompatible flags for get_oid_with_context");2164return get_oid_with_context_1(repo, str, flags, NULL, oid, oc);2165}
2166