sha1-name.c: remove the_repo from find_abbrev_len_packed()
[git/raj.git] / sha1-name.c
blobb9381aaba6fd8e2c919d05d6d223a9e9faea24de
1 #include "cache.h"
2 #include "config.h"
3 #include "tag.h"
4 #include "commit.h"
5 #include "tree.h"
6 #include "blob.h"
7 #include "tree-walk.h"
8 #include "refs.h"
9 #include "remote.h"
10 #include "dir.h"
11 #include "sha1-array.h"
12 #include "packfile.h"
13 #include "object-store.h"
14 #include "repository.h"
15 #include "midx.h"
16 #include "commit-reach.h"
18 static int get_oid_oneline(const char *, struct object_id *, struct commit_list *);
20 typedef int (*disambiguate_hint_fn)(const struct object_id *, void *);
22 struct disambiguate_state {
23 int len; /* length of prefix in hex chars */
24 char hex_pfx[GIT_MAX_HEXSZ + 1];
25 struct object_id bin_pfx;
27 disambiguate_hint_fn fn;
28 void *cb_data;
29 struct object_id candidate;
30 unsigned candidate_exists:1;
31 unsigned candidate_checked:1;
32 unsigned candidate_ok:1;
33 unsigned disambiguate_fn_used:1;
34 unsigned ambiguous:1;
35 unsigned always_call_fn:1;
38 static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
40 if (ds->always_call_fn) {
41 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
42 return;
44 if (!ds->candidate_exists) {
45 /* this is the first candidate */
46 oidcpy(&ds->candidate, current);
47 ds->candidate_exists = 1;
48 return;
49 } else if (oideq(&ds->candidate, current)) {
50 /* the same as what we already have seen */
51 return;
54 if (!ds->fn) {
55 /* cannot disambiguate between ds->candidate and current */
56 ds->ambiguous = 1;
57 return;
60 if (!ds->candidate_checked) {
61 ds->candidate_ok = ds->fn(&ds->candidate, ds->cb_data);
62 ds->disambiguate_fn_used = 1;
63 ds->candidate_checked = 1;
66 if (!ds->candidate_ok) {
67 /* discard the candidate; we know it does not satisfy fn */
68 oidcpy(&ds->candidate, current);
69 ds->candidate_checked = 0;
70 return;
73 /* if we reach this point, we know ds->candidate satisfies fn */
74 if (ds->fn(current, ds->cb_data)) {
76 * if both current and candidate satisfy fn, we cannot
77 * disambiguate.
79 ds->candidate_ok = 0;
80 ds->ambiguous = 1;
83 /* otherwise, current can be discarded and candidate is still good */
86 static int match_sha(unsigned, const unsigned char *, const unsigned char *);
88 static void find_short_object_filename(struct disambiguate_state *ds)
90 struct object_directory *odb;
92 for (odb = the_repository->objects->odb;
93 odb && !ds->ambiguous;
94 odb = odb->next) {
95 int pos;
96 struct oid_array *loose_objects;
98 loose_objects = odb_loose_cache(odb, &ds->bin_pfx);
99 pos = oid_array_lookup(loose_objects, &ds->bin_pfx);
100 if (pos < 0)
101 pos = -1 - pos;
102 while (!ds->ambiguous && pos < loose_objects->nr) {
103 const struct object_id *oid;
104 oid = loose_objects->oid + pos;
105 if (!match_sha(ds->len, ds->bin_pfx.hash, oid->hash))
106 break;
107 update_candidates(ds, oid);
108 pos++;
113 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
115 do {
116 if (*a != *b)
117 return 0;
118 a++;
119 b++;
120 len -= 2;
121 } while (len > 1);
122 if (len)
123 if ((*a ^ *b) & 0xf0)
124 return 0;
125 return 1;
128 static void unique_in_midx(struct multi_pack_index *m,
129 struct disambiguate_state *ds)
131 uint32_t num, i, first = 0;
132 const struct object_id *current = NULL;
133 num = m->num_objects;
135 if (!num)
136 return;
138 bsearch_midx(&ds->bin_pfx, m, &first);
141 * At this point, "first" is the location of the lowest object
142 * with an object name that could match "bin_pfx". See if we have
143 * 0, 1 or more objects that actually match(es).
145 for (i = first; i < num && !ds->ambiguous; i++) {
146 struct object_id oid;
147 current = nth_midxed_object_oid(&oid, m, i);
148 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
149 break;
150 update_candidates(ds, current);
154 static void unique_in_pack(struct packed_git *p,
155 struct disambiguate_state *ds)
157 uint32_t num, i, first = 0;
158 const struct object_id *current = NULL;
160 if (open_pack_index(p) || !p->num_objects)
161 return;
163 num = p->num_objects;
164 bsearch_pack(&ds->bin_pfx, p, &first);
167 * At this point, "first" is the location of the lowest object
168 * with an object name that could match "bin_pfx". See if we have
169 * 0, 1 or more objects that actually match(es).
171 for (i = first; i < num && !ds->ambiguous; i++) {
172 struct object_id oid;
173 current = nth_packed_object_oid(&oid, p, i);
174 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
175 break;
176 update_candidates(ds, current);
180 static void find_short_packed_object(struct disambiguate_state *ds)
182 struct multi_pack_index *m;
183 struct packed_git *p;
185 for (m = get_multi_pack_index(the_repository); m && !ds->ambiguous;
186 m = m->next)
187 unique_in_midx(m, ds);
188 for (p = get_packed_git(the_repository); p && !ds->ambiguous;
189 p = p->next)
190 unique_in_pack(p, ds);
193 static int finish_object_disambiguation(struct disambiguate_state *ds,
194 struct object_id *oid)
196 if (ds->ambiguous)
197 return SHORT_NAME_AMBIGUOUS;
199 if (!ds->candidate_exists)
200 return MISSING_OBJECT;
202 if (!ds->candidate_checked)
204 * If this is the only candidate, there is no point
205 * calling the disambiguation hint callback.
207 * On the other hand, if the current candidate
208 * replaced an earlier candidate that did _not_ pass
209 * the disambiguation hint callback, then we do have
210 * more than one objects that match the short name
211 * given, so we should make sure this one matches;
212 * otherwise, if we discovered this one and the one
213 * that we previously discarded in the reverse order,
214 * we would end up showing different results in the
215 * same repository!
217 ds->candidate_ok = (!ds->disambiguate_fn_used ||
218 ds->fn(&ds->candidate, ds->cb_data));
220 if (!ds->candidate_ok)
221 return SHORT_NAME_AMBIGUOUS;
223 oidcpy(oid, &ds->candidate);
224 return 0;
227 static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
229 int kind = oid_object_info(the_repository, oid, NULL);
230 return kind == OBJ_COMMIT;
233 static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
235 struct object *obj;
236 int kind;
238 kind = oid_object_info(the_repository, oid, NULL);
239 if (kind == OBJ_COMMIT)
240 return 1;
241 if (kind != OBJ_TAG)
242 return 0;
244 /* We need to do this the hard way... */
245 obj = deref_tag(the_repository, parse_object(the_repository, oid),
246 NULL, 0);
247 if (obj && obj->type == OBJ_COMMIT)
248 return 1;
249 return 0;
252 static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
254 int kind = oid_object_info(the_repository, oid, NULL);
255 return kind == OBJ_TREE;
258 static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
260 struct object *obj;
261 int kind;
263 kind = oid_object_info(the_repository, oid, NULL);
264 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
265 return 1;
266 if (kind != OBJ_TAG)
267 return 0;
269 /* We need to do this the hard way... */
270 obj = deref_tag(the_repository, parse_object(the_repository, oid),
271 NULL, 0);
272 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
273 return 1;
274 return 0;
277 static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
279 int kind = oid_object_info(the_repository, oid, NULL);
280 return kind == OBJ_BLOB;
283 static disambiguate_hint_fn default_disambiguate_hint;
285 int set_disambiguate_hint_config(const char *var, const char *value)
287 static const struct {
288 const char *name;
289 disambiguate_hint_fn fn;
290 } hints[] = {
291 { "none", NULL },
292 { "commit", disambiguate_commit_only },
293 { "committish", disambiguate_committish_only },
294 { "tree", disambiguate_tree_only },
295 { "treeish", disambiguate_treeish_only },
296 { "blob", disambiguate_blob_only }
298 int i;
300 if (!value)
301 return config_error_nonbool(var);
303 for (i = 0; i < ARRAY_SIZE(hints); i++) {
304 if (!strcasecmp(value, hints[i].name)) {
305 default_disambiguate_hint = hints[i].fn;
306 return 0;
310 return error("unknown hint type for '%s': %s", var, value);
313 static int init_object_disambiguation(const char *name, int len,
314 struct disambiguate_state *ds)
316 int i;
318 if (len < MINIMUM_ABBREV || len > the_hash_algo->hexsz)
319 return -1;
321 memset(ds, 0, sizeof(*ds));
323 for (i = 0; i < len ;i++) {
324 unsigned char c = name[i];
325 unsigned char val;
326 if (c >= '0' && c <= '9')
327 val = c - '0';
328 else if (c >= 'a' && c <= 'f')
329 val = c - 'a' + 10;
330 else if (c >= 'A' && c <='F') {
331 val = c - 'A' + 10;
332 c -= 'A' - 'a';
334 else
335 return -1;
336 ds->hex_pfx[i] = c;
337 if (!(i & 1))
338 val <<= 4;
339 ds->bin_pfx.hash[i >> 1] |= val;
342 ds->len = len;
343 ds->hex_pfx[len] = '\0';
344 prepare_alt_odb(the_repository);
345 return 0;
348 static int show_ambiguous_object(const struct object_id *oid, void *data)
350 const struct disambiguate_state *ds = data;
351 struct strbuf desc = STRBUF_INIT;
352 int type;
354 if (ds->fn && !ds->fn(oid, ds->cb_data))
355 return 0;
357 type = oid_object_info(the_repository, oid, NULL);
358 if (type == OBJ_COMMIT) {
359 struct commit *commit = lookup_commit(the_repository, oid);
360 if (commit) {
361 struct pretty_print_context pp = {0};
362 pp.date_mode.type = DATE_SHORT;
363 format_commit_message(commit, " %ad - %s", &desc, &pp);
365 } else if (type == OBJ_TAG) {
366 struct tag *tag = lookup_tag(the_repository, oid);
367 if (!parse_tag(tag) && tag->tag)
368 strbuf_addf(&desc, " %s", tag->tag);
371 advise(" %s %s%s",
372 find_unique_abbrev(oid, DEFAULT_ABBREV),
373 type_name(type) ? type_name(type) : "unknown type",
374 desc.buf);
376 strbuf_release(&desc);
377 return 0;
380 static int collect_ambiguous(const struct object_id *oid, void *data)
382 oid_array_append(data, oid);
383 return 0;
386 static struct repository *sort_ambiguous_repo;
387 static int sort_ambiguous(const void *a, const void *b)
389 int a_type = oid_object_info(sort_ambiguous_repo, a, NULL);
390 int b_type = oid_object_info(sort_ambiguous_repo, b, NULL);
391 int a_type_sort;
392 int b_type_sort;
395 * Sorts by hash within the same object type, just as
396 * oid_array_for_each_unique() would do.
398 if (a_type == b_type)
399 return oidcmp(a, b);
402 * Between object types show tags, then commits, and finally
403 * trees and blobs.
405 * The object_type enum is commit, tree, blob, tag, but we
406 * want tag, commit, tree blob. Cleverly (perhaps too
407 * cleverly) do that with modulus, since the enum assigns 1 to
408 * commit, so tag becomes 0.
410 a_type_sort = a_type % 4;
411 b_type_sort = b_type % 4;
412 return a_type_sort > b_type_sort ? 1 : -1;
415 static void sort_ambiguous_oid_array(struct repository *r, struct oid_array *a)
417 /* mutex will be needed if this code is to be made thread safe */
418 sort_ambiguous_repo = r;
419 QSORT(a->oid, a->nr, sort_ambiguous);
420 sort_ambiguous_repo = NULL;
423 static enum get_oid_result get_short_oid(const char *name, int len,
424 struct object_id *oid,
425 unsigned flags)
427 int status;
428 struct disambiguate_state ds;
429 int quietly = !!(flags & GET_OID_QUIETLY);
431 if (init_object_disambiguation(name, len, &ds) < 0)
432 return -1;
434 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
435 BUG("multiple get_short_oid disambiguator flags");
437 if (flags & GET_OID_COMMIT)
438 ds.fn = disambiguate_commit_only;
439 else if (flags & GET_OID_COMMITTISH)
440 ds.fn = disambiguate_committish_only;
441 else if (flags & GET_OID_TREE)
442 ds.fn = disambiguate_tree_only;
443 else if (flags & GET_OID_TREEISH)
444 ds.fn = disambiguate_treeish_only;
445 else if (flags & GET_OID_BLOB)
446 ds.fn = disambiguate_blob_only;
447 else
448 ds.fn = default_disambiguate_hint;
450 find_short_object_filename(&ds);
451 find_short_packed_object(&ds);
452 status = finish_object_disambiguation(&ds, oid);
454 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
455 struct oid_array collect = OID_ARRAY_INIT;
457 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
460 * We may still have ambiguity if we simply saw a series of
461 * candidates that did not satisfy our hint function. In
462 * that case, we still want to show them, so disable the hint
463 * function entirely.
465 if (!ds.ambiguous)
466 ds.fn = NULL;
468 advise(_("The candidates are:"));
469 for_each_abbrev(ds.hex_pfx, collect_ambiguous, &collect);
470 sort_ambiguous_oid_array(the_repository, &collect);
472 if (oid_array_for_each(&collect, show_ambiguous_object, &ds))
473 BUG("show_ambiguous_object shouldn't return non-zero");
474 oid_array_clear(&collect);
477 return status;
480 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
482 struct oid_array collect = OID_ARRAY_INIT;
483 struct disambiguate_state ds;
484 int ret;
486 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
487 return -1;
489 ds.always_call_fn = 1;
490 ds.fn = collect_ambiguous;
491 ds.cb_data = &collect;
492 find_short_object_filename(&ds);
493 find_short_packed_object(&ds);
495 ret = oid_array_for_each_unique(&collect, fn, cb_data);
496 oid_array_clear(&collect);
497 return ret;
501 * Return the slot of the most-significant bit set in "val". There are various
502 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
503 * probably not a big deal here.
505 static unsigned msb(unsigned long val)
507 unsigned r = 0;
508 while (val >>= 1)
509 r++;
510 return r;
513 struct min_abbrev_data {
514 unsigned int init_len;
515 unsigned int cur_len;
516 char *hex;
517 struct repository *repo;
518 const struct object_id *oid;
521 static inline char get_hex_char_from_oid(const struct object_id *oid,
522 unsigned int pos)
524 static const char hex[] = "0123456789abcdef";
526 if ((pos & 1) == 0)
527 return hex[oid->hash[pos >> 1] >> 4];
528 else
529 return hex[oid->hash[pos >> 1] & 0xf];
532 static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
534 struct min_abbrev_data *mad = cb_data;
536 unsigned int i = mad->init_len;
537 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
538 i++;
540 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
541 mad->cur_len = i + 1;
543 return 0;
546 static void find_abbrev_len_for_midx(struct multi_pack_index *m,
547 struct min_abbrev_data *mad)
549 int match = 0;
550 uint32_t num, first = 0;
551 struct object_id oid;
552 const struct object_id *mad_oid;
554 if (!m->num_objects)
555 return;
557 num = m->num_objects;
558 mad_oid = mad->oid;
559 match = bsearch_midx(mad_oid, m, &first);
562 * first is now the position in the packfile where we would insert
563 * mad->hash if it does not exist (or the position of mad->hash if
564 * it does exist). Hence, we consider a maximum of two objects
565 * nearby for the abbreviation length.
567 mad->init_len = 0;
568 if (!match) {
569 if (nth_midxed_object_oid(&oid, m, first))
570 extend_abbrev_len(&oid, mad);
571 } else if (first < num - 1) {
572 if (nth_midxed_object_oid(&oid, m, first + 1))
573 extend_abbrev_len(&oid, mad);
575 if (first > 0) {
576 if (nth_midxed_object_oid(&oid, m, first - 1))
577 extend_abbrev_len(&oid, mad);
579 mad->init_len = mad->cur_len;
582 static void find_abbrev_len_for_pack(struct packed_git *p,
583 struct min_abbrev_data *mad)
585 int match = 0;
586 uint32_t num, first = 0;
587 struct object_id oid;
588 const struct object_id *mad_oid;
590 if (open_pack_index(p) || !p->num_objects)
591 return;
593 num = p->num_objects;
594 mad_oid = mad->oid;
595 match = bsearch_pack(mad_oid, p, &first);
598 * first is now the position in the packfile where we would insert
599 * mad->hash if it does not exist (or the position of mad->hash if
600 * it does exist). Hence, we consider a maximum of two objects
601 * nearby for the abbreviation length.
603 mad->init_len = 0;
604 if (!match) {
605 if (nth_packed_object_oid(&oid, p, first))
606 extend_abbrev_len(&oid, mad);
607 } else if (first < num - 1) {
608 if (nth_packed_object_oid(&oid, p, first + 1))
609 extend_abbrev_len(&oid, mad);
611 if (first > 0) {
612 if (nth_packed_object_oid(&oid, p, first - 1))
613 extend_abbrev_len(&oid, mad);
615 mad->init_len = mad->cur_len;
618 static void find_abbrev_len_packed(struct min_abbrev_data *mad)
620 struct multi_pack_index *m;
621 struct packed_git *p;
623 for (m = get_multi_pack_index(mad->repo); m; m = m->next)
624 find_abbrev_len_for_midx(m, mad);
625 for (p = get_packed_git(mad->repo); p; p = p->next)
626 find_abbrev_len_for_pack(p, mad);
629 int find_unique_abbrev_r(char *hex, const struct object_id *oid, int len)
631 struct disambiguate_state ds;
632 struct min_abbrev_data mad;
633 struct object_id oid_ret;
634 const unsigned hexsz = the_hash_algo->hexsz;
636 if (len < 0) {
637 unsigned long count = approximate_object_count();
639 * Add one because the MSB only tells us the highest bit set,
640 * not including the value of all the _other_ bits (so "15"
641 * is only one off of 2^4, but the MSB is the 3rd bit.
643 len = msb(count) + 1;
645 * We now know we have on the order of 2^len objects, which
646 * expects a collision at 2^(len/2). But we also care about hex
647 * chars, not bits, and there are 4 bits per hex. So all
648 * together we need to divide by 2 and round up.
650 len = DIV_ROUND_UP(len, 2);
652 * For very small repos, we stick with our regular fallback.
654 if (len < FALLBACK_DEFAULT_ABBREV)
655 len = FALLBACK_DEFAULT_ABBREV;
658 oid_to_hex_r(hex, oid);
659 if (len == hexsz || !len)
660 return hexsz;
662 mad.repo = the_repository;
663 mad.init_len = len;
664 mad.cur_len = len;
665 mad.hex = hex;
666 mad.oid = oid;
668 find_abbrev_len_packed(&mad);
670 if (init_object_disambiguation(hex, mad.cur_len, &ds) < 0)
671 return -1;
673 ds.fn = extend_abbrev_len;
674 ds.always_call_fn = 1;
675 ds.cb_data = (void *)&mad;
677 find_short_object_filename(&ds);
678 (void)finish_object_disambiguation(&ds, &oid_ret);
680 hex[mad.cur_len] = 0;
681 return mad.cur_len;
684 const char *find_unique_abbrev(const struct object_id *oid, int len)
686 static int bufno;
687 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
688 char *hex = hexbuffer[bufno];
689 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
690 find_unique_abbrev_r(hex, oid, len);
691 return hex;
694 static int ambiguous_path(const char *path, int len)
696 int slash = 1;
697 int cnt;
699 for (cnt = 0; cnt < len; cnt++) {
700 switch (*path++) {
701 case '\0':
702 break;
703 case '/':
704 if (slash)
705 break;
706 slash = 1;
707 continue;
708 case '.':
709 continue;
710 default:
711 slash = 0;
712 continue;
714 break;
716 return slash;
719 static inline int at_mark(const char *string, int len,
720 const char **suffix, int nr)
722 int i;
724 for (i = 0; i < nr; i++) {
725 int suffix_len = strlen(suffix[i]);
726 if (suffix_len <= len
727 && !strncasecmp(string, suffix[i], suffix_len))
728 return suffix_len;
730 return 0;
733 static inline int upstream_mark(const char *string, int len)
735 const char *suffix[] = { "@{upstream}", "@{u}" };
736 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
739 static inline int push_mark(const char *string, int len)
741 const char *suffix[] = { "@{push}" };
742 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
745 static enum get_oid_result get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags);
746 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
748 static int get_oid_basic(const char *str, int len, struct object_id *oid,
749 unsigned int flags)
751 static const char *warn_msg = "refname '%.*s' is ambiguous.";
752 static const char *object_name_msg = N_(
753 "Git normally never creates a ref that ends with 40 hex characters\n"
754 "because it will be ignored when you just specify 40-hex. These refs\n"
755 "may be created by mistake. For example,\n"
756 "\n"
757 " git checkout -b $br $(git rev-parse ...)\n"
758 "\n"
759 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
760 "examine these refs and maybe delete them. Turn this message off by\n"
761 "running \"git config advice.objectNameWarning false\"");
762 struct object_id tmp_oid;
763 char *real_ref = NULL;
764 int refs_found = 0;
765 int at, reflog_len, nth_prior = 0;
767 if (len == the_hash_algo->hexsz && !get_oid_hex(str, oid)) {
768 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
769 refs_found = dwim_ref(str, len, &tmp_oid, &real_ref);
770 if (refs_found > 0) {
771 warning(warn_msg, len, str);
772 if (advice_object_name_warning)
773 fprintf(stderr, "%s\n", _(object_name_msg));
775 free(real_ref);
777 return 0;
780 /* basic@{time or number or -number} format to query ref-log */
781 reflog_len = at = 0;
782 if (len && str[len-1] == '}') {
783 for (at = len-4; at >= 0; at--) {
784 if (str[at] == '@' && str[at+1] == '{') {
785 if (str[at+2] == '-') {
786 if (at != 0)
787 /* @{-N} not at start */
788 return -1;
789 nth_prior = 1;
790 continue;
792 if (!upstream_mark(str + at, len - at) &&
793 !push_mark(str + at, len - at)) {
794 reflog_len = (len-1) - (at+2);
795 len = at;
797 break;
802 /* Accept only unambiguous ref paths. */
803 if (len && ambiguous_path(str, len))
804 return -1;
806 if (nth_prior) {
807 struct strbuf buf = STRBUF_INIT;
808 int detached;
810 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
811 detached = (buf.len == the_hash_algo->hexsz && !get_oid_hex(buf.buf, oid));
812 strbuf_release(&buf);
813 if (detached)
814 return 0;
818 if (!len && reflog_len)
819 /* allow "@{...}" to mean the current branch reflog */
820 refs_found = dwim_ref("HEAD", 4, oid, &real_ref);
821 else if (reflog_len)
822 refs_found = dwim_log(str, len, oid, &real_ref);
823 else
824 refs_found = dwim_ref(str, len, oid, &real_ref);
826 if (!refs_found)
827 return -1;
829 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
830 (refs_found > 1 ||
831 !get_short_oid(str, len, &tmp_oid, GET_OID_QUIETLY)))
832 warning(warn_msg, len, str);
834 if (reflog_len) {
835 int nth, i;
836 timestamp_t at_time;
837 timestamp_t co_time;
838 int co_tz, co_cnt;
840 /* Is it asking for N-th entry, or approxidate? */
841 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
842 char ch = str[at+2+i];
843 if ('0' <= ch && ch <= '9')
844 nth = nth * 10 + ch - '0';
845 else
846 nth = -1;
848 if (100000000 <= nth) {
849 at_time = nth;
850 nth = -1;
851 } else if (0 <= nth)
852 at_time = 0;
853 else {
854 int errors = 0;
855 char *tmp = xstrndup(str + at + 2, reflog_len);
856 at_time = approxidate_careful(tmp, &errors);
857 free(tmp);
858 if (errors) {
859 free(real_ref);
860 return -1;
863 if (read_ref_at(get_main_ref_store(the_repository),
864 real_ref, flags, at_time, nth, oid, NULL,
865 &co_time, &co_tz, &co_cnt)) {
866 if (!len) {
867 if (starts_with(real_ref, "refs/heads/")) {
868 str = real_ref + 11;
869 len = strlen(real_ref + 11);
870 } else {
871 /* detached HEAD */
872 str = "HEAD";
873 len = 4;
876 if (at_time) {
877 if (!(flags & GET_OID_QUIETLY)) {
878 warning("Log for '%.*s' only goes "
879 "back to %s.", len, str,
880 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
882 } else {
883 if (flags & GET_OID_QUIETLY) {
884 exit(128);
886 die("Log for '%.*s' only has %d entries.",
887 len, str, co_cnt);
892 free(real_ref);
893 return 0;
896 static enum get_oid_result get_parent(const char *name, int len,
897 struct object_id *result, int idx)
899 struct object_id oid;
900 enum get_oid_result ret = get_oid_1(name, len, &oid,
901 GET_OID_COMMITTISH);
902 struct commit *commit;
903 struct commit_list *p;
905 if (ret)
906 return ret;
907 commit = lookup_commit_reference(the_repository, &oid);
908 if (parse_commit(commit))
909 return MISSING_OBJECT;
910 if (!idx) {
911 oidcpy(result, &commit->object.oid);
912 return FOUND;
914 p = commit->parents;
915 while (p) {
916 if (!--idx) {
917 oidcpy(result, &p->item->object.oid);
918 return FOUND;
920 p = p->next;
922 return MISSING_OBJECT;
925 static enum get_oid_result get_nth_ancestor(const char *name, int len,
926 struct object_id *result,
927 int generation)
929 struct object_id oid;
930 struct commit *commit;
931 int ret;
933 ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
934 if (ret)
935 return ret;
936 commit = lookup_commit_reference(the_repository, &oid);
937 if (!commit)
938 return MISSING_OBJECT;
940 while (generation--) {
941 if (parse_commit(commit) || !commit->parents)
942 return MISSING_OBJECT;
943 commit = commit->parents->item;
945 oidcpy(result, &commit->object.oid);
946 return FOUND;
949 struct object *peel_to_type(const char *name, int namelen,
950 struct object *o, enum object_type expected_type)
952 if (name && !namelen)
953 namelen = strlen(name);
954 while (1) {
955 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
956 return NULL;
957 if (expected_type == OBJ_ANY || o->type == expected_type)
958 return o;
959 if (o->type == OBJ_TAG)
960 o = ((struct tag*) o)->tagged;
961 else if (o->type == OBJ_COMMIT)
962 o = &(get_commit_tree(((struct commit *)o))->object);
963 else {
964 if (name)
965 error("%.*s: expected %s type, but the object "
966 "dereferences to %s type",
967 namelen, name, type_name(expected_type),
968 type_name(o->type));
969 return NULL;
974 static int peel_onion(const char *name, int len, struct object_id *oid,
975 unsigned lookup_flags)
977 struct object_id outer;
978 const char *sp;
979 unsigned int expected_type = 0;
980 struct object *o;
983 * "ref^{type}" dereferences ref repeatedly until you cannot
984 * dereference anymore, or you get an object of given type,
985 * whichever comes first. "ref^{}" means just dereference
986 * tags until you get a non-tag. "ref^0" is a shorthand for
987 * "ref^{commit}". "commit^{tree}" could be used to find the
988 * top-level tree of the given commit.
990 if (len < 4 || name[len-1] != '}')
991 return -1;
993 for (sp = name + len - 1; name <= sp; sp--) {
994 int ch = *sp;
995 if (ch == '{' && name < sp && sp[-1] == '^')
996 break;
998 if (sp <= name)
999 return -1;
1001 sp++; /* beginning of type name, or closing brace for empty */
1002 if (starts_with(sp, "commit}"))
1003 expected_type = OBJ_COMMIT;
1004 else if (starts_with(sp, "tag}"))
1005 expected_type = OBJ_TAG;
1006 else if (starts_with(sp, "tree}"))
1007 expected_type = OBJ_TREE;
1008 else if (starts_with(sp, "blob}"))
1009 expected_type = OBJ_BLOB;
1010 else if (starts_with(sp, "object}"))
1011 expected_type = OBJ_ANY;
1012 else if (sp[0] == '}')
1013 expected_type = OBJ_NONE;
1014 else if (sp[0] == '/')
1015 expected_type = OBJ_COMMIT;
1016 else
1017 return -1;
1019 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
1020 if (expected_type == OBJ_COMMIT)
1021 lookup_flags |= GET_OID_COMMITTISH;
1022 else if (expected_type == OBJ_TREE)
1023 lookup_flags |= GET_OID_TREEISH;
1025 if (get_oid_1(name, sp - name - 2, &outer, lookup_flags))
1026 return -1;
1028 o = parse_object(the_repository, &outer);
1029 if (!o)
1030 return -1;
1031 if (!expected_type) {
1032 o = deref_tag(the_repository, o, name, sp - name - 2);
1033 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
1034 return -1;
1035 oidcpy(oid, &o->oid);
1036 return 0;
1040 * At this point, the syntax look correct, so
1041 * if we do not get the needed object, we should
1042 * barf.
1044 o = peel_to_type(name, len, o, expected_type);
1045 if (!o)
1046 return -1;
1048 oidcpy(oid, &o->oid);
1049 if (sp[0] == '/') {
1050 /* "$commit^{/foo}" */
1051 char *prefix;
1052 int ret;
1053 struct commit_list *list = NULL;
1056 * $commit^{/}. Some regex implementation may reject.
1057 * We don't need regex anyway. '' pattern always matches.
1059 if (sp[1] == '}')
1060 return 0;
1062 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
1063 commit_list_insert((struct commit *)o, &list);
1064 ret = get_oid_oneline(prefix, oid, list);
1065 free(prefix);
1066 return ret;
1068 return 0;
1071 static int get_describe_name(const char *name, int len, struct object_id *oid)
1073 const char *cp;
1074 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
1076 for (cp = name + len - 1; name + 2 <= cp; cp--) {
1077 char ch = *cp;
1078 if (!isxdigit(ch)) {
1079 /* We must be looking at g in "SOMETHING-g"
1080 * for it to be describe output.
1082 if (ch == 'g' && cp[-1] == '-') {
1083 cp++;
1084 len -= cp - name;
1085 return get_short_oid(cp, len, oid, flags);
1089 return -1;
1092 static enum get_oid_result get_oid_1(const char *name, int len,
1093 struct object_id *oid,
1094 unsigned lookup_flags)
1096 int ret, has_suffix;
1097 const char *cp;
1100 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1102 has_suffix = 0;
1103 for (cp = name + len - 1; name <= cp; cp--) {
1104 int ch = *cp;
1105 if ('0' <= ch && ch <= '9')
1106 continue;
1107 if (ch == '~' || ch == '^')
1108 has_suffix = ch;
1109 break;
1112 if (has_suffix) {
1113 int num = 0;
1114 int len1 = cp - name;
1115 cp++;
1116 while (cp < name + len)
1117 num = num * 10 + *cp++ - '0';
1118 if (!num && len1 == len - 1)
1119 num = 1;
1120 if (has_suffix == '^')
1121 return get_parent(name, len1, oid, num);
1122 /* else if (has_suffix == '~') -- goes without saying */
1123 return get_nth_ancestor(name, len1, oid, num);
1126 ret = peel_onion(name, len, oid, lookup_flags);
1127 if (!ret)
1128 return FOUND;
1130 ret = get_oid_basic(name, len, oid, lookup_flags);
1131 if (!ret)
1132 return FOUND;
1134 /* It could be describe output that is "SOMETHING-gXXXX" */
1135 ret = get_describe_name(name, len, oid);
1136 if (!ret)
1137 return FOUND;
1139 return get_short_oid(name, len, oid, lookup_flags);
1143 * This interprets names like ':/Initial revision of "git"' by searching
1144 * through history and returning the first commit whose message starts
1145 * the given regular expression.
1147 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1149 * For a literal '!' character at the beginning of a pattern, you have to repeat
1150 * that, like: ':/!!foo'
1152 * For future extension, all other sequences beginning with ':/!' are reserved.
1155 /* Remember to update object flag allocation in object.h */
1156 #define ONELINE_SEEN (1u<<20)
1158 static int handle_one_ref(const char *path, const struct object_id *oid,
1159 int flag, void *cb_data)
1161 struct commit_list **list = cb_data;
1162 struct object *object = parse_object(the_repository, oid);
1163 if (!object)
1164 return 0;
1165 if (object->type == OBJ_TAG) {
1166 object = deref_tag(the_repository, object, path,
1167 strlen(path));
1168 if (!object)
1169 return 0;
1171 if (object->type != OBJ_COMMIT)
1172 return 0;
1173 commit_list_insert((struct commit *)object, list);
1174 return 0;
1177 static int get_oid_oneline(const char *prefix, struct object_id *oid,
1178 struct commit_list *list)
1180 struct commit_list *backup = NULL, *l;
1181 int found = 0;
1182 int negative = 0;
1183 regex_t regex;
1185 if (prefix[0] == '!') {
1186 prefix++;
1188 if (prefix[0] == '-') {
1189 prefix++;
1190 negative = 1;
1191 } else if (prefix[0] != '!') {
1192 return -1;
1196 if (regcomp(&regex, prefix, REG_EXTENDED))
1197 return -1;
1199 for (l = list; l; l = l->next) {
1200 l->item->object.flags |= ONELINE_SEEN;
1201 commit_list_insert(l->item, &backup);
1203 while (list) {
1204 const char *p, *buf;
1205 struct commit *commit;
1206 int matches;
1208 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1209 if (!parse_object(the_repository, &commit->object.oid))
1210 continue;
1211 buf = get_commit_buffer(commit, NULL);
1212 p = strstr(buf, "\n\n");
1213 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
1214 unuse_commit_buffer(commit, buf);
1216 if (matches) {
1217 oidcpy(oid, &commit->object.oid);
1218 found = 1;
1219 break;
1222 regfree(&regex);
1223 free_commit_list(list);
1224 for (l = backup; l; l = l->next)
1225 clear_commit_marks(l->item, ONELINE_SEEN);
1226 free_commit_list(backup);
1227 return found ? 0 : -1;
1230 struct grab_nth_branch_switch_cbdata {
1231 int remaining;
1232 struct strbuf buf;
1235 static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
1236 const char *email, timestamp_t timestamp, int tz,
1237 const char *message, void *cb_data)
1239 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1240 const char *match = NULL, *target = NULL;
1241 size_t len;
1243 if (skip_prefix(message, "checkout: moving from ", &match))
1244 target = strstr(match, " to ");
1246 if (!match || !target)
1247 return 0;
1248 if (--(cb->remaining) == 0) {
1249 len = target - match;
1250 strbuf_reset(&cb->buf);
1251 strbuf_add(&cb->buf, match, len);
1252 return 1; /* we are done */
1254 return 0;
1258 * Parse @{-N} syntax, return the number of characters parsed
1259 * if successful; otherwise signal an error with negative value.
1261 static int interpret_nth_prior_checkout(const char *name, int namelen,
1262 struct strbuf *buf)
1264 long nth;
1265 int retval;
1266 struct grab_nth_branch_switch_cbdata cb;
1267 const char *brace;
1268 char *num_end;
1270 if (namelen < 4)
1271 return -1;
1272 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1273 return -1;
1274 brace = memchr(name, '}', namelen);
1275 if (!brace)
1276 return -1;
1277 nth = strtol(name + 3, &num_end, 10);
1278 if (num_end != brace)
1279 return -1;
1280 if (nth <= 0)
1281 return -1;
1282 cb.remaining = nth;
1283 strbuf_init(&cb.buf, 20);
1285 retval = 0;
1286 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1287 strbuf_reset(buf);
1288 strbuf_addbuf(buf, &cb.buf);
1289 retval = brace - name + 1;
1292 strbuf_release(&cb.buf);
1293 return retval;
1296 int get_oid_mb(const char *name, struct object_id *oid)
1298 struct commit *one, *two;
1299 struct commit_list *mbs;
1300 struct object_id oid_tmp;
1301 const char *dots;
1302 int st;
1304 dots = strstr(name, "...");
1305 if (!dots)
1306 return get_oid(name, oid);
1307 if (dots == name)
1308 st = get_oid("HEAD", &oid_tmp);
1309 else {
1310 struct strbuf sb;
1311 strbuf_init(&sb, dots - name);
1312 strbuf_add(&sb, name, dots - name);
1313 st = get_oid_committish(sb.buf, &oid_tmp);
1314 strbuf_release(&sb);
1316 if (st)
1317 return st;
1318 one = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1319 if (!one)
1320 return -1;
1322 if (get_oid_committish(dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1323 return -1;
1324 two = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1325 if (!two)
1326 return -1;
1327 mbs = get_merge_bases(one, two);
1328 if (!mbs || mbs->next)
1329 st = -1;
1330 else {
1331 st = 0;
1332 oidcpy(oid, &mbs->item->object.oid);
1334 free_commit_list(mbs);
1335 return st;
1338 /* parse @something syntax, when 'something' is not {.*} */
1339 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1341 const char *next;
1343 if (len || name[1] == '{')
1344 return -1;
1346 /* make sure it's a single @, or @@{.*}, not @foo */
1347 next = memchr(name + len + 1, '@', namelen - len - 1);
1348 if (next && next[1] != '{')
1349 return -1;
1350 if (!next)
1351 next = name + namelen;
1352 if (next != name + 1)
1353 return -1;
1355 strbuf_reset(buf);
1356 strbuf_add(buf, "HEAD", 4);
1357 return 1;
1360 static int reinterpret(const char *name, int namelen, int len,
1361 struct strbuf *buf, unsigned allowed)
1363 /* we have extra data, which might need further processing */
1364 struct strbuf tmp = STRBUF_INIT;
1365 int used = buf->len;
1366 int ret;
1368 strbuf_add(buf, name + len, namelen - len);
1369 ret = interpret_branch_name(buf->buf, buf->len, &tmp, allowed);
1370 /* that data was not interpreted, remove our cruft */
1371 if (ret < 0) {
1372 strbuf_setlen(buf, used);
1373 return len;
1375 strbuf_reset(buf);
1376 strbuf_addbuf(buf, &tmp);
1377 strbuf_release(&tmp);
1378 /* tweak for size of {-N} versus expanded ref name */
1379 return ret - used + len;
1382 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1384 char *s = shorten_unambiguous_ref(ref, 0);
1385 strbuf_reset(buf);
1386 strbuf_addstr(buf, s);
1387 free(s);
1390 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1392 if (!allowed)
1393 return 1;
1395 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1396 starts_with(refname, "refs/heads/"))
1397 return 1;
1398 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1399 starts_with(refname, "refs/remotes/"))
1400 return 1;
1402 return 0;
1405 static int interpret_branch_mark(const char *name, int namelen,
1406 int at, struct strbuf *buf,
1407 int (*get_mark)(const char *, int),
1408 const char *(*get_data)(struct branch *,
1409 struct strbuf *),
1410 unsigned allowed)
1412 int len;
1413 struct branch *branch;
1414 struct strbuf err = STRBUF_INIT;
1415 const char *value;
1417 len = get_mark(name + at, namelen - at);
1418 if (!len)
1419 return -1;
1421 if (memchr(name, ':', at))
1422 return -1;
1424 if (at) {
1425 char *name_str = xmemdupz(name, at);
1426 branch = branch_get(name_str);
1427 free(name_str);
1428 } else
1429 branch = branch_get(NULL);
1431 value = get_data(branch, &err);
1432 if (!value)
1433 die("%s", err.buf);
1435 if (!branch_interpret_allowed(value, allowed))
1436 return -1;
1438 set_shortened_ref(buf, value);
1439 return len + at;
1442 int repo_interpret_branch_name(struct repository *r,
1443 const char *name, int namelen,
1444 struct strbuf *buf,
1445 unsigned allowed)
1447 char *at;
1448 const char *start;
1449 int len;
1451 if (r != the_repository)
1452 BUG("interpret_branch_name() does not really use 'r' yet");
1453 if (!namelen)
1454 namelen = strlen(name);
1456 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1457 len = interpret_nth_prior_checkout(name, namelen, buf);
1458 if (!len) {
1459 return len; /* syntax Ok, not enough switches */
1460 } else if (len > 0) {
1461 if (len == namelen)
1462 return len; /* consumed all */
1463 else
1464 return reinterpret(name, namelen, len, buf, allowed);
1468 for (start = name;
1469 (at = memchr(start, '@', namelen - (start - name)));
1470 start = at + 1) {
1472 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1473 len = interpret_empty_at(name, namelen, at - name, buf);
1474 if (len > 0)
1475 return reinterpret(name, namelen, len, buf,
1476 allowed);
1479 len = interpret_branch_mark(name, namelen, at - name, buf,
1480 upstream_mark, branch_get_upstream,
1481 allowed);
1482 if (len > 0)
1483 return len;
1485 len = interpret_branch_mark(name, namelen, at - name, buf,
1486 push_mark, branch_get_push,
1487 allowed);
1488 if (len > 0)
1489 return len;
1492 return -1;
1495 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1497 int len = strlen(name);
1498 int used = interpret_branch_name(name, len, sb, allowed);
1500 if (used < 0)
1501 used = 0;
1502 strbuf_add(sb, name + used, len - used);
1505 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1507 if (startup_info->have_repository)
1508 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1509 else
1510 strbuf_addstr(sb, name);
1513 * This splice must be done even if we end up rejecting the
1514 * name; builtin/branch.c::copy_or_rename_branch() still wants
1515 * to see what the name expanded to so that "branch -m" can be
1516 * used as a tool to correct earlier mistakes.
1518 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1520 if (*name == '-' ||
1521 !strcmp(sb->buf, "refs/heads/HEAD"))
1522 return -1;
1524 return check_refname_format(sb->buf, 0);
1528 * This is like "get_oid_basic()", except it allows "object ID expressions",
1529 * notably "xyz^" for "parent of xyz"
1531 int get_oid(const char *name, struct object_id *oid)
1533 struct object_context unused;
1534 return get_oid_with_context(the_repository, name, 0, oid, &unused);
1539 * Many callers know that the user meant to name a commit-ish by
1540 * syntactical positions where the object name appears. Calling this
1541 * function allows the machinery to disambiguate shorter-than-unique
1542 * abbreviated object names between commit-ish and others.
1544 * Note that this does NOT error out when the named object is not a
1545 * commit-ish. It is merely to give a hint to the disambiguation
1546 * machinery.
1548 int get_oid_committish(const char *name, struct object_id *oid)
1550 struct object_context unused;
1551 return get_oid_with_context(the_repository,
1552 name, GET_OID_COMMITTISH,
1553 oid, &unused);
1556 int get_oid_treeish(const char *name, struct object_id *oid)
1558 struct object_context unused;
1559 return get_oid_with_context(the_repository,
1560 name, GET_OID_TREEISH,
1561 oid, &unused);
1564 int get_oid_commit(const char *name, struct object_id *oid)
1566 struct object_context unused;
1567 return get_oid_with_context(the_repository,
1568 name, GET_OID_COMMIT,
1569 oid, &unused);
1572 int get_oid_tree(const char *name, struct object_id *oid)
1574 struct object_context unused;
1575 return get_oid_with_context(the_repository,
1576 name, GET_OID_TREE,
1577 oid, &unused);
1580 int get_oid_blob(const char *name, struct object_id *oid)
1582 struct object_context unused;
1583 return get_oid_with_context(the_repository,
1584 name, GET_OID_BLOB,
1585 oid, &unused);
1588 /* Must be called only when object_name:filename doesn't exist. */
1589 static void diagnose_invalid_oid_path(const char *prefix,
1590 const char *filename,
1591 const struct object_id *tree_oid,
1592 const char *object_name,
1593 int object_name_len)
1595 struct object_id oid;
1596 unsigned mode;
1598 if (!prefix)
1599 prefix = "";
1601 if (file_exists(filename))
1602 die("Path '%s' exists on disk, but not in '%.*s'.",
1603 filename, object_name_len, object_name);
1604 if (is_missing_file_error(errno)) {
1605 char *fullname = xstrfmt("%s%s", prefix, filename);
1607 if (!get_tree_entry(tree_oid, fullname, &oid, &mode)) {
1608 die("Path '%s' exists, but not '%s'.\n"
1609 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1610 fullname,
1611 filename,
1612 object_name_len, object_name,
1613 fullname,
1614 object_name_len, object_name,
1615 filename);
1617 die("Path '%s' does not exist in '%.*s'",
1618 filename, object_name_len, object_name);
1622 /* Must be called only when :stage:filename doesn't exist. */
1623 static void diagnose_invalid_index_path(struct index_state *istate,
1624 int stage,
1625 const char *prefix,
1626 const char *filename)
1628 const struct cache_entry *ce;
1629 int pos;
1630 unsigned namelen = strlen(filename);
1631 struct strbuf fullname = STRBUF_INIT;
1633 if (!prefix)
1634 prefix = "";
1636 /* Wrong stage number? */
1637 pos = index_name_pos(istate, filename, namelen);
1638 if (pos < 0)
1639 pos = -pos - 1;
1640 if (pos < istate->cache_nr) {
1641 ce = istate->cache[pos];
1642 if (ce_namelen(ce) == namelen &&
1643 !memcmp(ce->name, filename, namelen))
1644 die("Path '%s' is in the index, but not at stage %d.\n"
1645 "Did you mean ':%d:%s'?",
1646 filename, stage,
1647 ce_stage(ce), filename);
1650 /* Confusion between relative and absolute filenames? */
1651 strbuf_addstr(&fullname, prefix);
1652 strbuf_addstr(&fullname, filename);
1653 pos = index_name_pos(istate, fullname.buf, fullname.len);
1654 if (pos < 0)
1655 pos = -pos - 1;
1656 if (pos < istate->cache_nr) {
1657 ce = istate->cache[pos];
1658 if (ce_namelen(ce) == fullname.len &&
1659 !memcmp(ce->name, fullname.buf, fullname.len))
1660 die("Path '%s' is in the index, but not '%s'.\n"
1661 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1662 fullname.buf, filename,
1663 ce_stage(ce), fullname.buf,
1664 ce_stage(ce), filename);
1667 if (file_exists(filename))
1668 die("Path '%s' exists on disk, but not in the index.", filename);
1669 if (is_missing_file_error(errno))
1670 die("Path '%s' does not exist (neither on disk nor in the index).",
1671 filename);
1673 strbuf_release(&fullname);
1677 static char *resolve_relative_path(const char *rel)
1679 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1680 return NULL;
1682 if (!is_inside_work_tree())
1683 die("relative path syntax can't be used outside working tree.");
1685 /* die() inside prefix_path() if resolved path is outside worktree */
1686 return prefix_path(startup_info->prefix,
1687 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1688 rel);
1691 static enum get_oid_result get_oid_with_context_1(struct repository *repo,
1692 const char *name,
1693 unsigned flags,
1694 const char *prefix,
1695 struct object_id *oid,
1696 struct object_context *oc)
1698 int ret, bracket_depth;
1699 int namelen = strlen(name);
1700 const char *cp;
1701 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
1703 if (only_to_die)
1704 flags |= GET_OID_QUIETLY;
1706 memset(oc, 0, sizeof(*oc));
1707 oc->mode = S_IFINVALID;
1708 strbuf_init(&oc->symlink_path, 0);
1709 ret = get_oid_1(name, namelen, oid, flags);
1710 if (!ret)
1711 return ret;
1713 * sha1:path --> object name of path in ent sha1
1714 * :path -> object name of absolute path in index
1715 * :./path -> object name of path relative to cwd in index
1716 * :[0-3]:path -> object name of path in index at stage
1717 * :/foo -> recent commit matching foo
1719 if (name[0] == ':') {
1720 int stage = 0;
1721 const struct cache_entry *ce;
1722 char *new_path = NULL;
1723 int pos;
1724 if (!only_to_die && namelen > 2 && name[1] == '/') {
1725 struct commit_list *list = NULL;
1727 for_each_ref(handle_one_ref, &list);
1728 head_ref(handle_one_ref, &list);
1729 commit_list_sort_by_date(&list);
1730 return get_oid_oneline(name + 2, oid, list);
1732 if (namelen < 3 ||
1733 name[2] != ':' ||
1734 name[1] < '0' || '3' < name[1])
1735 cp = name + 1;
1736 else {
1737 stage = name[1] - '0';
1738 cp = name + 3;
1740 new_path = resolve_relative_path(cp);
1741 if (!new_path) {
1742 namelen = namelen - (cp - name);
1743 } else {
1744 cp = new_path;
1745 namelen = strlen(cp);
1748 if (flags & GET_OID_RECORD_PATH)
1749 oc->path = xstrdup(cp);
1751 if (!repo->index->cache)
1752 repo_read_index(the_repository);
1753 pos = index_name_pos(repo->index, cp, namelen);
1754 if (pos < 0)
1755 pos = -pos - 1;
1756 while (pos < repo->index->cache_nr) {
1757 ce = repo->index->cache[pos];
1758 if (ce_namelen(ce) != namelen ||
1759 memcmp(ce->name, cp, namelen))
1760 break;
1761 if (ce_stage(ce) == stage) {
1762 oidcpy(oid, &ce->oid);
1763 oc->mode = ce->ce_mode;
1764 free(new_path);
1765 return 0;
1767 pos++;
1769 if (only_to_die && name[1] && name[1] != '/')
1770 diagnose_invalid_index_path(repo->index, stage, prefix, cp);
1771 free(new_path);
1772 return -1;
1774 for (cp = name, bracket_depth = 0; *cp; cp++) {
1775 if (*cp == '{')
1776 bracket_depth++;
1777 else if (bracket_depth && *cp == '}')
1778 bracket_depth--;
1779 else if (!bracket_depth && *cp == ':')
1780 break;
1782 if (*cp == ':') {
1783 struct object_id tree_oid;
1784 int len = cp - name;
1785 unsigned sub_flags = flags;
1787 sub_flags &= ~GET_OID_DISAMBIGUATORS;
1788 sub_flags |= GET_OID_TREEISH;
1790 if (!get_oid_1(name, len, &tree_oid, sub_flags)) {
1791 const char *filename = cp+1;
1792 char *new_filename = NULL;
1794 new_filename = resolve_relative_path(filename);
1795 if (new_filename)
1796 filename = new_filename;
1797 if (flags & GET_OID_FOLLOW_SYMLINKS) {
1798 ret = get_tree_entry_follow_symlinks(&tree_oid,
1799 filename, oid, &oc->symlink_path,
1800 &oc->mode);
1801 } else {
1802 ret = get_tree_entry(&tree_oid, filename, oid,
1803 &oc->mode);
1804 if (ret && only_to_die) {
1805 diagnose_invalid_oid_path(prefix,
1806 filename,
1807 &tree_oid,
1808 name, len);
1811 if (flags & GET_OID_RECORD_PATH)
1812 oc->path = xstrdup(filename);
1814 free(new_filename);
1815 return ret;
1816 } else {
1817 if (only_to_die)
1818 die("Invalid object name '%.*s'.", len, name);
1821 return ret;
1825 * Call this function when you know "name" given by the end user must
1826 * name an object but it doesn't; the function _may_ die with a better
1827 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1828 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1829 * you have a chance to diagnose the error further.
1831 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1833 struct object_context oc;
1834 struct object_id oid;
1835 get_oid_with_context_1(the_repository, name, GET_OID_ONLY_TO_DIE,
1836 prefix, &oid, &oc);
1839 enum get_oid_result get_oid_with_context(struct repository *repo,
1840 const char *str,
1841 unsigned flags,
1842 struct object_id *oid,
1843 struct object_context *oc)
1845 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
1846 BUG("incompatible flags for get_sha1_with_context");
1847 return get_oid_with_context_1(repo, str, flags, NULL, oid, oc);