sha1-name.c: move around the collect_ambiguous() function
[git.git] / sha1-name.c
blob9d7bbd3e96f3227026909ff92bbb443976683a1f
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"
16 static int get_oid_oneline(const char *, struct object_id *, struct commit_list *);
18 typedef int (*disambiguate_hint_fn)(const struct object_id *, void *);
20 struct disambiguate_state {
21 int len; /* length of prefix in hex chars */
22 char hex_pfx[GIT_MAX_HEXSZ + 1];
23 struct object_id bin_pfx;
25 disambiguate_hint_fn fn;
26 void *cb_data;
27 struct object_id candidate;
28 unsigned candidate_exists:1;
29 unsigned candidate_checked:1;
30 unsigned candidate_ok:1;
31 unsigned disambiguate_fn_used:1;
32 unsigned ambiguous:1;
33 unsigned always_call_fn:1;
36 static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
38 if (ds->always_call_fn) {
39 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
40 return;
42 if (!ds->candidate_exists) {
43 /* this is the first candidate */
44 oidcpy(&ds->candidate, current);
45 ds->candidate_exists = 1;
46 return;
47 } else if (!oidcmp(&ds->candidate, current)) {
48 /* the same as what we already have seen */
49 return;
52 if (!ds->fn) {
53 /* cannot disambiguate between ds->candidate and current */
54 ds->ambiguous = 1;
55 return;
58 if (!ds->candidate_checked) {
59 ds->candidate_ok = ds->fn(&ds->candidate, ds->cb_data);
60 ds->disambiguate_fn_used = 1;
61 ds->candidate_checked = 1;
64 if (!ds->candidate_ok) {
65 /* discard the candidate; we know it does not satisfy fn */
66 oidcpy(&ds->candidate, current);
67 ds->candidate_checked = 0;
68 return;
71 /* if we reach this point, we know ds->candidate satisfies fn */
72 if (ds->fn(current, ds->cb_data)) {
74 * if both current and candidate satisfy fn, we cannot
75 * disambiguate.
77 ds->candidate_ok = 0;
78 ds->ambiguous = 1;
81 /* otherwise, current can be discarded and candidate is still good */
84 static int append_loose_object(const struct object_id *oid, const char *path,
85 void *data)
87 oid_array_append(data, oid);
88 return 0;
91 static int match_sha(unsigned, const unsigned char *, const unsigned char *);
93 static void find_short_object_filename(struct disambiguate_state *ds)
95 int subdir_nr = ds->bin_pfx.hash[0];
96 struct alternate_object_database *alt;
97 static struct alternate_object_database *fakeent;
99 if (!fakeent) {
101 * Create a "fake" alternate object database that
102 * points to our own object database, to make it
103 * easier to get a temporary working space in
104 * alt->name/alt->base while iterating over the
105 * object databases including our own.
107 fakeent = alloc_alt_odb(get_object_directory());
109 fakeent->next = the_repository->objects->alt_odb_list;
111 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
112 int pos;
114 if (!alt->loose_objects_subdir_seen[subdir_nr]) {
115 struct strbuf *buf = alt_scratch_buf(alt);
116 for_each_file_in_obj_subdir(subdir_nr, buf,
117 append_loose_object,
118 NULL, NULL,
119 &alt->loose_objects_cache);
120 alt->loose_objects_subdir_seen[subdir_nr] = 1;
123 pos = oid_array_lookup(&alt->loose_objects_cache, &ds->bin_pfx);
124 if (pos < 0)
125 pos = -1 - pos;
126 while (!ds->ambiguous && pos < alt->loose_objects_cache.nr) {
127 const struct object_id *oid;
128 oid = alt->loose_objects_cache.oid + pos;
129 if (!match_sha(ds->len, ds->bin_pfx.hash, oid->hash))
130 break;
131 update_candidates(ds, oid);
132 pos++;
137 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
139 do {
140 if (*a != *b)
141 return 0;
142 a++;
143 b++;
144 len -= 2;
145 } while (len > 1);
146 if (len)
147 if ((*a ^ *b) & 0xf0)
148 return 0;
149 return 1;
152 static void unique_in_pack(struct packed_git *p,
153 struct disambiguate_state *ds)
155 uint32_t num, i, first = 0;
156 const struct object_id *current = NULL;
158 if (open_pack_index(p) || !p->num_objects)
159 return;
161 num = p->num_objects;
162 bsearch_pack(&ds->bin_pfx, p, &first);
165 * At this point, "first" is the location of the lowest object
166 * with an object name that could match "bin_pfx". See if we have
167 * 0, 1 or more objects that actually match(es).
169 for (i = first; i < num && !ds->ambiguous; i++) {
170 struct object_id oid;
171 current = nth_packed_object_oid(&oid, p, i);
172 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
173 break;
174 update_candidates(ds, current);
178 static void find_short_packed_object(struct disambiguate_state *ds)
180 struct packed_git *p;
182 for (p = get_packed_git(the_repository); p && !ds->ambiguous;
183 p = p->next)
184 unique_in_pack(p, ds);
187 #define SHORT_NAME_NOT_FOUND (-1)
188 #define SHORT_NAME_AMBIGUOUS (-2)
190 static int finish_object_disambiguation(struct disambiguate_state *ds,
191 struct object_id *oid)
193 if (ds->ambiguous)
194 return SHORT_NAME_AMBIGUOUS;
196 if (!ds->candidate_exists)
197 return SHORT_NAME_NOT_FOUND;
199 if (!ds->candidate_checked)
201 * If this is the only candidate, there is no point
202 * calling the disambiguation hint callback.
204 * On the other hand, if the current candidate
205 * replaced an earlier candidate that did _not_ pass
206 * the disambiguation hint callback, then we do have
207 * more than one objects that match the short name
208 * given, so we should make sure this one matches;
209 * otherwise, if we discovered this one and the one
210 * that we previously discarded in the reverse order,
211 * we would end up showing different results in the
212 * same repository!
214 ds->candidate_ok = (!ds->disambiguate_fn_used ||
215 ds->fn(&ds->candidate, ds->cb_data));
217 if (!ds->candidate_ok)
218 return SHORT_NAME_AMBIGUOUS;
220 oidcpy(oid, &ds->candidate);
221 return 0;
224 static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
226 int kind = oid_object_info(oid, NULL);
227 return kind == OBJ_COMMIT;
230 static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
232 struct object *obj;
233 int kind;
235 kind = oid_object_info(oid, NULL);
236 if (kind == OBJ_COMMIT)
237 return 1;
238 if (kind != OBJ_TAG)
239 return 0;
241 /* We need to do this the hard way... */
242 obj = deref_tag(parse_object(oid), NULL, 0);
243 if (obj && obj->type == OBJ_COMMIT)
244 return 1;
245 return 0;
248 static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
250 int kind = oid_object_info(oid, NULL);
251 return kind == OBJ_TREE;
254 static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
256 struct object *obj;
257 int kind;
259 kind = oid_object_info(oid, NULL);
260 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
261 return 1;
262 if (kind != OBJ_TAG)
263 return 0;
265 /* We need to do this the hard way... */
266 obj = deref_tag(parse_object(oid), NULL, 0);
267 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
268 return 1;
269 return 0;
272 static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
274 int kind = oid_object_info(oid, NULL);
275 return kind == OBJ_BLOB;
278 static disambiguate_hint_fn default_disambiguate_hint;
280 int set_disambiguate_hint_config(const char *var, const char *value)
282 static const struct {
283 const char *name;
284 disambiguate_hint_fn fn;
285 } hints[] = {
286 { "none", NULL },
287 { "commit", disambiguate_commit_only },
288 { "committish", disambiguate_committish_only },
289 { "tree", disambiguate_tree_only },
290 { "treeish", disambiguate_treeish_only },
291 { "blob", disambiguate_blob_only }
293 int i;
295 if (!value)
296 return config_error_nonbool(var);
298 for (i = 0; i < ARRAY_SIZE(hints); i++) {
299 if (!strcasecmp(value, hints[i].name)) {
300 default_disambiguate_hint = hints[i].fn;
301 return 0;
305 return error("unknown hint type for '%s': %s", var, value);
308 static int init_object_disambiguation(const char *name, int len,
309 struct disambiguate_state *ds)
311 int i;
313 if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
314 return -1;
316 memset(ds, 0, sizeof(*ds));
318 for (i = 0; i < len ;i++) {
319 unsigned char c = name[i];
320 unsigned char val;
321 if (c >= '0' && c <= '9')
322 val = c - '0';
323 else if (c >= 'a' && c <= 'f')
324 val = c - 'a' + 10;
325 else if (c >= 'A' && c <='F') {
326 val = c - 'A' + 10;
327 c -= 'A' - 'a';
329 else
330 return -1;
331 ds->hex_pfx[i] = c;
332 if (!(i & 1))
333 val <<= 4;
334 ds->bin_pfx.hash[i >> 1] |= val;
337 ds->len = len;
338 ds->hex_pfx[len] = '\0';
339 prepare_alt_odb(the_repository);
340 return 0;
343 static int show_ambiguous_object(const struct object_id *oid, void *data)
345 const struct disambiguate_state *ds = data;
346 struct strbuf desc = STRBUF_INIT;
347 int type;
349 if (ds->fn && !ds->fn(oid, ds->cb_data))
350 return 0;
352 type = oid_object_info(oid, NULL);
353 if (type == OBJ_COMMIT) {
354 struct commit *commit = lookup_commit(oid);
355 if (commit) {
356 struct pretty_print_context pp = {0};
357 pp.date_mode.type = DATE_SHORT;
358 format_commit_message(commit, " %ad - %s", &desc, &pp);
360 } else if (type == OBJ_TAG) {
361 struct tag *tag = lookup_tag(oid);
362 if (!parse_tag(tag) && tag->tag)
363 strbuf_addf(&desc, " %s", tag->tag);
366 advise(" %s %s%s",
367 find_unique_abbrev(oid, DEFAULT_ABBREV),
368 type_name(type) ? type_name(type) : "unknown type",
369 desc.buf);
371 strbuf_release(&desc);
372 return 0;
375 static int collect_ambiguous(const struct object_id *oid, void *data)
377 oid_array_append(data, oid);
378 return 0;
381 static int get_short_oid(const char *name, int len, struct object_id *oid,
382 unsigned flags)
384 int status;
385 struct disambiguate_state ds;
386 int quietly = !!(flags & GET_OID_QUIETLY);
388 if (init_object_disambiguation(name, len, &ds) < 0)
389 return -1;
391 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
392 die("BUG: multiple get_short_oid disambiguator flags");
394 if (flags & GET_OID_COMMIT)
395 ds.fn = disambiguate_commit_only;
396 else if (flags & GET_OID_COMMITTISH)
397 ds.fn = disambiguate_committish_only;
398 else if (flags & GET_OID_TREE)
399 ds.fn = disambiguate_tree_only;
400 else if (flags & GET_OID_TREEISH)
401 ds.fn = disambiguate_treeish_only;
402 else if (flags & GET_OID_BLOB)
403 ds.fn = disambiguate_blob_only;
404 else
405 ds.fn = default_disambiguate_hint;
407 find_short_object_filename(&ds);
408 find_short_packed_object(&ds);
409 status = finish_object_disambiguation(&ds, oid);
411 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
412 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
415 * We may still have ambiguity if we simply saw a series of
416 * candidates that did not satisfy our hint function. In
417 * that case, we still want to show them, so disable the hint
418 * function entirely.
420 if (!ds.ambiguous)
421 ds.fn = NULL;
423 advise(_("The candidates are:"));
424 for_each_abbrev(ds.hex_pfx, show_ambiguous_object, &ds);
427 return status;
430 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
432 struct oid_array collect = OID_ARRAY_INIT;
433 struct disambiguate_state ds;
434 int ret;
436 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
437 return -1;
439 ds.always_call_fn = 1;
440 ds.fn = collect_ambiguous;
441 ds.cb_data = &collect;
442 find_short_object_filename(&ds);
443 find_short_packed_object(&ds);
445 ret = oid_array_for_each_unique(&collect, fn, cb_data);
446 oid_array_clear(&collect);
447 return ret;
451 * Return the slot of the most-significant bit set in "val". There are various
452 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
453 * probably not a big deal here.
455 static unsigned msb(unsigned long val)
457 unsigned r = 0;
458 while (val >>= 1)
459 r++;
460 return r;
463 struct min_abbrev_data {
464 unsigned int init_len;
465 unsigned int cur_len;
466 char *hex;
467 const struct object_id *oid;
470 static inline char get_hex_char_from_oid(const struct object_id *oid,
471 unsigned int pos)
473 static const char hex[] = "0123456789abcdef";
475 if ((pos & 1) == 0)
476 return hex[oid->hash[pos >> 1] >> 4];
477 else
478 return hex[oid->hash[pos >> 1] & 0xf];
481 static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
483 struct min_abbrev_data *mad = cb_data;
485 unsigned int i = mad->init_len;
486 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
487 i++;
489 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
490 mad->cur_len = i + 1;
492 return 0;
495 static void find_abbrev_len_for_pack(struct packed_git *p,
496 struct min_abbrev_data *mad)
498 int match = 0;
499 uint32_t num, first = 0;
500 struct object_id oid;
501 const struct object_id *mad_oid;
503 if (open_pack_index(p) || !p->num_objects)
504 return;
506 num = p->num_objects;
507 mad_oid = mad->oid;
508 match = bsearch_pack(mad_oid, p, &first);
511 * first is now the position in the packfile where we would insert
512 * mad->hash if it does not exist (or the position of mad->hash if
513 * it does exist). Hence, we consider a maximum of two objects
514 * nearby for the abbreviation length.
516 mad->init_len = 0;
517 if (!match) {
518 if (nth_packed_object_oid(&oid, p, first))
519 extend_abbrev_len(&oid, mad);
520 } else if (first < num - 1) {
521 if (nth_packed_object_oid(&oid, p, first + 1))
522 extend_abbrev_len(&oid, mad);
524 if (first > 0) {
525 if (nth_packed_object_oid(&oid, p, first - 1))
526 extend_abbrev_len(&oid, mad);
528 mad->init_len = mad->cur_len;
531 static void find_abbrev_len_packed(struct min_abbrev_data *mad)
533 struct packed_git *p;
535 for (p = get_packed_git(the_repository); p; p = p->next)
536 find_abbrev_len_for_pack(p, mad);
539 int find_unique_abbrev_r(char *hex, const struct object_id *oid, int len)
541 struct disambiguate_state ds;
542 struct min_abbrev_data mad;
543 struct object_id oid_ret;
544 if (len < 0) {
545 unsigned long count = approximate_object_count();
547 * Add one because the MSB only tells us the highest bit set,
548 * not including the value of all the _other_ bits (so "15"
549 * is only one off of 2^4, but the MSB is the 3rd bit.
551 len = msb(count) + 1;
553 * We now know we have on the order of 2^len objects, which
554 * expects a collision at 2^(len/2). But we also care about hex
555 * chars, not bits, and there are 4 bits per hex. So all
556 * together we need to divide by 2 and round up.
558 len = DIV_ROUND_UP(len, 2);
560 * For very small repos, we stick with our regular fallback.
562 if (len < FALLBACK_DEFAULT_ABBREV)
563 len = FALLBACK_DEFAULT_ABBREV;
566 oid_to_hex_r(hex, oid);
567 if (len == GIT_SHA1_HEXSZ || !len)
568 return GIT_SHA1_HEXSZ;
570 mad.init_len = len;
571 mad.cur_len = len;
572 mad.hex = hex;
573 mad.oid = oid;
575 find_abbrev_len_packed(&mad);
577 if (init_object_disambiguation(hex, mad.cur_len, &ds) < 0)
578 return -1;
580 ds.fn = extend_abbrev_len;
581 ds.always_call_fn = 1;
582 ds.cb_data = (void *)&mad;
584 find_short_object_filename(&ds);
585 (void)finish_object_disambiguation(&ds, &oid_ret);
587 hex[mad.cur_len] = 0;
588 return mad.cur_len;
591 const char *find_unique_abbrev(const struct object_id *oid, int len)
593 static int bufno;
594 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
595 char *hex = hexbuffer[bufno];
596 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
597 find_unique_abbrev_r(hex, oid, len);
598 return hex;
601 static int ambiguous_path(const char *path, int len)
603 int slash = 1;
604 int cnt;
606 for (cnt = 0; cnt < len; cnt++) {
607 switch (*path++) {
608 case '\0':
609 break;
610 case '/':
611 if (slash)
612 break;
613 slash = 1;
614 continue;
615 case '.':
616 continue;
617 default:
618 slash = 0;
619 continue;
621 break;
623 return slash;
626 static inline int at_mark(const char *string, int len,
627 const char **suffix, int nr)
629 int i;
631 for (i = 0; i < nr; i++) {
632 int suffix_len = strlen(suffix[i]);
633 if (suffix_len <= len
634 && !strncasecmp(string, suffix[i], suffix_len))
635 return suffix_len;
637 return 0;
640 static inline int upstream_mark(const char *string, int len)
642 const char *suffix[] = { "@{upstream}", "@{u}" };
643 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
646 static inline int push_mark(const char *string, int len)
648 const char *suffix[] = { "@{push}" };
649 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
652 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags);
653 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
655 static int get_oid_basic(const char *str, int len, struct object_id *oid,
656 unsigned int flags)
658 static const char *warn_msg = "refname '%.*s' is ambiguous.";
659 static const char *object_name_msg = N_(
660 "Git normally never creates a ref that ends with 40 hex characters\n"
661 "because it will be ignored when you just specify 40-hex. These refs\n"
662 "may be created by mistake. For example,\n"
663 "\n"
664 " git checkout -b $br $(git rev-parse ...)\n"
665 "\n"
666 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
667 "examine these refs and maybe delete them. Turn this message off by\n"
668 "running \"git config advice.objectNameWarning false\"");
669 struct object_id tmp_oid;
670 char *real_ref = NULL;
671 int refs_found = 0;
672 int at, reflog_len, nth_prior = 0;
674 if (len == GIT_SHA1_HEXSZ && !get_oid_hex(str, oid)) {
675 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
676 refs_found = dwim_ref(str, len, &tmp_oid, &real_ref);
677 if (refs_found > 0) {
678 warning(warn_msg, len, str);
679 if (advice_object_name_warning)
680 fprintf(stderr, "%s\n", _(object_name_msg));
682 free(real_ref);
684 return 0;
687 /* basic@{time or number or -number} format to query ref-log */
688 reflog_len = at = 0;
689 if (len && str[len-1] == '}') {
690 for (at = len-4; at >= 0; at--) {
691 if (str[at] == '@' && str[at+1] == '{') {
692 if (str[at+2] == '-') {
693 if (at != 0)
694 /* @{-N} not at start */
695 return -1;
696 nth_prior = 1;
697 continue;
699 if (!upstream_mark(str + at, len - at) &&
700 !push_mark(str + at, len - at)) {
701 reflog_len = (len-1) - (at+2);
702 len = at;
704 break;
709 /* Accept only unambiguous ref paths. */
710 if (len && ambiguous_path(str, len))
711 return -1;
713 if (nth_prior) {
714 struct strbuf buf = STRBUF_INIT;
715 int detached;
717 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
718 detached = (buf.len == GIT_SHA1_HEXSZ && !get_oid_hex(buf.buf, oid));
719 strbuf_release(&buf);
720 if (detached)
721 return 0;
725 if (!len && reflog_len)
726 /* allow "@{...}" to mean the current branch reflog */
727 refs_found = dwim_ref("HEAD", 4, oid, &real_ref);
728 else if (reflog_len)
729 refs_found = dwim_log(str, len, oid, &real_ref);
730 else
731 refs_found = dwim_ref(str, len, oid, &real_ref);
733 if (!refs_found)
734 return -1;
736 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
737 (refs_found > 1 ||
738 !get_short_oid(str, len, &tmp_oid, GET_OID_QUIETLY)))
739 warning(warn_msg, len, str);
741 if (reflog_len) {
742 int nth, i;
743 timestamp_t at_time;
744 timestamp_t co_time;
745 int co_tz, co_cnt;
747 /* Is it asking for N-th entry, or approxidate? */
748 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
749 char ch = str[at+2+i];
750 if ('0' <= ch && ch <= '9')
751 nth = nth * 10 + ch - '0';
752 else
753 nth = -1;
755 if (100000000 <= nth) {
756 at_time = nth;
757 nth = -1;
758 } else if (0 <= nth)
759 at_time = 0;
760 else {
761 int errors = 0;
762 char *tmp = xstrndup(str + at + 2, reflog_len);
763 at_time = approxidate_careful(tmp, &errors);
764 free(tmp);
765 if (errors) {
766 free(real_ref);
767 return -1;
770 if (read_ref_at(real_ref, flags, at_time, nth, oid, NULL,
771 &co_time, &co_tz, &co_cnt)) {
772 if (!len) {
773 if (starts_with(real_ref, "refs/heads/")) {
774 str = real_ref + 11;
775 len = strlen(real_ref + 11);
776 } else {
777 /* detached HEAD */
778 str = "HEAD";
779 len = 4;
782 if (at_time) {
783 if (!(flags & GET_OID_QUIETLY)) {
784 warning("Log for '%.*s' only goes "
785 "back to %s.", len, str,
786 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
788 } else {
789 if (flags & GET_OID_QUIETLY) {
790 exit(128);
792 die("Log for '%.*s' only has %d entries.",
793 len, str, co_cnt);
798 free(real_ref);
799 return 0;
802 static int get_parent(const char *name, int len,
803 struct object_id *result, int idx)
805 struct object_id oid;
806 int ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
807 struct commit *commit;
808 struct commit_list *p;
810 if (ret)
811 return ret;
812 commit = lookup_commit_reference(&oid);
813 if (parse_commit(commit))
814 return -1;
815 if (!idx) {
816 oidcpy(result, &commit->object.oid);
817 return 0;
819 p = commit->parents;
820 while (p) {
821 if (!--idx) {
822 oidcpy(result, &p->item->object.oid);
823 return 0;
825 p = p->next;
827 return -1;
830 static int get_nth_ancestor(const char *name, int len,
831 struct object_id *result, int generation)
833 struct object_id oid;
834 struct commit *commit;
835 int ret;
837 ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
838 if (ret)
839 return ret;
840 commit = lookup_commit_reference(&oid);
841 if (!commit)
842 return -1;
844 while (generation--) {
845 if (parse_commit(commit) || !commit->parents)
846 return -1;
847 commit = commit->parents->item;
849 oidcpy(result, &commit->object.oid);
850 return 0;
853 struct object *peel_to_type(const char *name, int namelen,
854 struct object *o, enum object_type expected_type)
856 if (name && !namelen)
857 namelen = strlen(name);
858 while (1) {
859 if (!o || (!o->parsed && !parse_object(&o->oid)))
860 return NULL;
861 if (expected_type == OBJ_ANY || o->type == expected_type)
862 return o;
863 if (o->type == OBJ_TAG)
864 o = ((struct tag*) o)->tagged;
865 else if (o->type == OBJ_COMMIT)
866 o = &(((struct commit *) o)->tree->object);
867 else {
868 if (name)
869 error("%.*s: expected %s type, but the object "
870 "dereferences to %s type",
871 namelen, name, type_name(expected_type),
872 type_name(o->type));
873 return NULL;
878 static int peel_onion(const char *name, int len, struct object_id *oid,
879 unsigned lookup_flags)
881 struct object_id outer;
882 const char *sp;
883 unsigned int expected_type = 0;
884 struct object *o;
887 * "ref^{type}" dereferences ref repeatedly until you cannot
888 * dereference anymore, or you get an object of given type,
889 * whichever comes first. "ref^{}" means just dereference
890 * tags until you get a non-tag. "ref^0" is a shorthand for
891 * "ref^{commit}". "commit^{tree}" could be used to find the
892 * top-level tree of the given commit.
894 if (len < 4 || name[len-1] != '}')
895 return -1;
897 for (sp = name + len - 1; name <= sp; sp--) {
898 int ch = *sp;
899 if (ch == '{' && name < sp && sp[-1] == '^')
900 break;
902 if (sp <= name)
903 return -1;
905 sp++; /* beginning of type name, or closing brace for empty */
906 if (starts_with(sp, "commit}"))
907 expected_type = OBJ_COMMIT;
908 else if (starts_with(sp, "tag}"))
909 expected_type = OBJ_TAG;
910 else if (starts_with(sp, "tree}"))
911 expected_type = OBJ_TREE;
912 else if (starts_with(sp, "blob}"))
913 expected_type = OBJ_BLOB;
914 else if (starts_with(sp, "object}"))
915 expected_type = OBJ_ANY;
916 else if (sp[0] == '}')
917 expected_type = OBJ_NONE;
918 else if (sp[0] == '/')
919 expected_type = OBJ_COMMIT;
920 else
921 return -1;
923 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
924 if (expected_type == OBJ_COMMIT)
925 lookup_flags |= GET_OID_COMMITTISH;
926 else if (expected_type == OBJ_TREE)
927 lookup_flags |= GET_OID_TREEISH;
929 if (get_oid_1(name, sp - name - 2, &outer, lookup_flags))
930 return -1;
932 o = parse_object(&outer);
933 if (!o)
934 return -1;
935 if (!expected_type) {
936 o = deref_tag(o, name, sp - name - 2);
937 if (!o || (!o->parsed && !parse_object(&o->oid)))
938 return -1;
939 oidcpy(oid, &o->oid);
940 return 0;
944 * At this point, the syntax look correct, so
945 * if we do not get the needed object, we should
946 * barf.
948 o = peel_to_type(name, len, o, expected_type);
949 if (!o)
950 return -1;
952 oidcpy(oid, &o->oid);
953 if (sp[0] == '/') {
954 /* "$commit^{/foo}" */
955 char *prefix;
956 int ret;
957 struct commit_list *list = NULL;
960 * $commit^{/}. Some regex implementation may reject.
961 * We don't need regex anyway. '' pattern always matches.
963 if (sp[1] == '}')
964 return 0;
966 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
967 commit_list_insert((struct commit *)o, &list);
968 ret = get_oid_oneline(prefix, oid, list);
969 free(prefix);
970 return ret;
972 return 0;
975 static int get_describe_name(const char *name, int len, struct object_id *oid)
977 const char *cp;
978 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
980 for (cp = name + len - 1; name + 2 <= cp; cp--) {
981 char ch = *cp;
982 if (!isxdigit(ch)) {
983 /* We must be looking at g in "SOMETHING-g"
984 * for it to be describe output.
986 if (ch == 'g' && cp[-1] == '-') {
987 cp++;
988 len -= cp - name;
989 return get_short_oid(cp, len, oid, flags);
993 return -1;
996 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags)
998 int ret, has_suffix;
999 const char *cp;
1002 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1004 has_suffix = 0;
1005 for (cp = name + len - 1; name <= cp; cp--) {
1006 int ch = *cp;
1007 if ('0' <= ch && ch <= '9')
1008 continue;
1009 if (ch == '~' || ch == '^')
1010 has_suffix = ch;
1011 break;
1014 if (has_suffix) {
1015 int num = 0;
1016 int len1 = cp - name;
1017 cp++;
1018 while (cp < name + len)
1019 num = num * 10 + *cp++ - '0';
1020 if (!num && len1 == len - 1)
1021 num = 1;
1022 if (has_suffix == '^')
1023 return get_parent(name, len1, oid, num);
1024 /* else if (has_suffix == '~') -- goes without saying */
1025 return get_nth_ancestor(name, len1, oid, num);
1028 ret = peel_onion(name, len, oid, lookup_flags);
1029 if (!ret)
1030 return 0;
1032 ret = get_oid_basic(name, len, oid, lookup_flags);
1033 if (!ret)
1034 return 0;
1036 /* It could be describe output that is "SOMETHING-gXXXX" */
1037 ret = get_describe_name(name, len, oid);
1038 if (!ret)
1039 return 0;
1041 return get_short_oid(name, len, oid, lookup_flags);
1045 * This interprets names like ':/Initial revision of "git"' by searching
1046 * through history and returning the first commit whose message starts
1047 * the given regular expression.
1049 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1051 * For a literal '!' character at the beginning of a pattern, you have to repeat
1052 * that, like: ':/!!foo'
1054 * For future extension, all other sequences beginning with ':/!' are reserved.
1057 /* Remember to update object flag allocation in object.h */
1058 #define ONELINE_SEEN (1u<<20)
1060 static int handle_one_ref(const char *path, const struct object_id *oid,
1061 int flag, void *cb_data)
1063 struct commit_list **list = cb_data;
1064 struct object *object = parse_object(oid);
1065 if (!object)
1066 return 0;
1067 if (object->type == OBJ_TAG) {
1068 object = deref_tag(object, path, strlen(path));
1069 if (!object)
1070 return 0;
1072 if (object->type != OBJ_COMMIT)
1073 return 0;
1074 commit_list_insert((struct commit *)object, list);
1075 return 0;
1078 static int get_oid_oneline(const char *prefix, struct object_id *oid,
1079 struct commit_list *list)
1081 struct commit_list *backup = NULL, *l;
1082 int found = 0;
1083 int negative = 0;
1084 regex_t regex;
1086 if (prefix[0] == '!') {
1087 prefix++;
1089 if (prefix[0] == '-') {
1090 prefix++;
1091 negative = 1;
1092 } else if (prefix[0] != '!') {
1093 return -1;
1097 if (regcomp(&regex, prefix, REG_EXTENDED))
1098 return -1;
1100 for (l = list; l; l = l->next) {
1101 l->item->object.flags |= ONELINE_SEEN;
1102 commit_list_insert(l->item, &backup);
1104 while (list) {
1105 const char *p, *buf;
1106 struct commit *commit;
1107 int matches;
1109 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1110 if (!parse_object(&commit->object.oid))
1111 continue;
1112 buf = get_commit_buffer(commit, NULL);
1113 p = strstr(buf, "\n\n");
1114 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
1115 unuse_commit_buffer(commit, buf);
1117 if (matches) {
1118 oidcpy(oid, &commit->object.oid);
1119 found = 1;
1120 break;
1123 regfree(&regex);
1124 free_commit_list(list);
1125 for (l = backup; l; l = l->next)
1126 clear_commit_marks(l->item, ONELINE_SEEN);
1127 free_commit_list(backup);
1128 return found ? 0 : -1;
1131 struct grab_nth_branch_switch_cbdata {
1132 int remaining;
1133 struct strbuf buf;
1136 static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
1137 const char *email, timestamp_t timestamp, int tz,
1138 const char *message, void *cb_data)
1140 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1141 const char *match = NULL, *target = NULL;
1142 size_t len;
1144 if (skip_prefix(message, "checkout: moving from ", &match))
1145 target = strstr(match, " to ");
1147 if (!match || !target)
1148 return 0;
1149 if (--(cb->remaining) == 0) {
1150 len = target - match;
1151 strbuf_reset(&cb->buf);
1152 strbuf_add(&cb->buf, match, len);
1153 return 1; /* we are done */
1155 return 0;
1159 * Parse @{-N} syntax, return the number of characters parsed
1160 * if successful; otherwise signal an error with negative value.
1162 static int interpret_nth_prior_checkout(const char *name, int namelen,
1163 struct strbuf *buf)
1165 long nth;
1166 int retval;
1167 struct grab_nth_branch_switch_cbdata cb;
1168 const char *brace;
1169 char *num_end;
1171 if (namelen < 4)
1172 return -1;
1173 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1174 return -1;
1175 brace = memchr(name, '}', namelen);
1176 if (!brace)
1177 return -1;
1178 nth = strtol(name + 3, &num_end, 10);
1179 if (num_end != brace)
1180 return -1;
1181 if (nth <= 0)
1182 return -1;
1183 cb.remaining = nth;
1184 strbuf_init(&cb.buf, 20);
1186 retval = 0;
1187 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1188 strbuf_reset(buf);
1189 strbuf_addbuf(buf, &cb.buf);
1190 retval = brace - name + 1;
1193 strbuf_release(&cb.buf);
1194 return retval;
1197 int get_oid_mb(const char *name, struct object_id *oid)
1199 struct commit *one, *two;
1200 struct commit_list *mbs;
1201 struct object_id oid_tmp;
1202 const char *dots;
1203 int st;
1205 dots = strstr(name, "...");
1206 if (!dots)
1207 return get_oid(name, oid);
1208 if (dots == name)
1209 st = get_oid("HEAD", &oid_tmp);
1210 else {
1211 struct strbuf sb;
1212 strbuf_init(&sb, dots - name);
1213 strbuf_add(&sb, name, dots - name);
1214 st = get_oid_committish(sb.buf, &oid_tmp);
1215 strbuf_release(&sb);
1217 if (st)
1218 return st;
1219 one = lookup_commit_reference_gently(&oid_tmp, 0);
1220 if (!one)
1221 return -1;
1223 if (get_oid_committish(dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1224 return -1;
1225 two = lookup_commit_reference_gently(&oid_tmp, 0);
1226 if (!two)
1227 return -1;
1228 mbs = get_merge_bases(one, two);
1229 if (!mbs || mbs->next)
1230 st = -1;
1231 else {
1232 st = 0;
1233 oidcpy(oid, &mbs->item->object.oid);
1235 free_commit_list(mbs);
1236 return st;
1239 /* parse @something syntax, when 'something' is not {.*} */
1240 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1242 const char *next;
1244 if (len || name[1] == '{')
1245 return -1;
1247 /* make sure it's a single @, or @@{.*}, not @foo */
1248 next = memchr(name + len + 1, '@', namelen - len - 1);
1249 if (next && next[1] != '{')
1250 return -1;
1251 if (!next)
1252 next = name + namelen;
1253 if (next != name + 1)
1254 return -1;
1256 strbuf_reset(buf);
1257 strbuf_add(buf, "HEAD", 4);
1258 return 1;
1261 static int reinterpret(const char *name, int namelen, int len,
1262 struct strbuf *buf, unsigned allowed)
1264 /* we have extra data, which might need further processing */
1265 struct strbuf tmp = STRBUF_INIT;
1266 int used = buf->len;
1267 int ret;
1269 strbuf_add(buf, name + len, namelen - len);
1270 ret = interpret_branch_name(buf->buf, buf->len, &tmp, allowed);
1271 /* that data was not interpreted, remove our cruft */
1272 if (ret < 0) {
1273 strbuf_setlen(buf, used);
1274 return len;
1276 strbuf_reset(buf);
1277 strbuf_addbuf(buf, &tmp);
1278 strbuf_release(&tmp);
1279 /* tweak for size of {-N} versus expanded ref name */
1280 return ret - used + len;
1283 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1285 char *s = shorten_unambiguous_ref(ref, 0);
1286 strbuf_reset(buf);
1287 strbuf_addstr(buf, s);
1288 free(s);
1291 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1293 if (!allowed)
1294 return 1;
1296 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1297 starts_with(refname, "refs/heads/"))
1298 return 1;
1299 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1300 starts_with(refname, "refs/remotes/"))
1301 return 1;
1303 return 0;
1306 static int interpret_branch_mark(const char *name, int namelen,
1307 int at, struct strbuf *buf,
1308 int (*get_mark)(const char *, int),
1309 const char *(*get_data)(struct branch *,
1310 struct strbuf *),
1311 unsigned allowed)
1313 int len;
1314 struct branch *branch;
1315 struct strbuf err = STRBUF_INIT;
1316 const char *value;
1318 len = get_mark(name + at, namelen - at);
1319 if (!len)
1320 return -1;
1322 if (memchr(name, ':', at))
1323 return -1;
1325 if (at) {
1326 char *name_str = xmemdupz(name, at);
1327 branch = branch_get(name_str);
1328 free(name_str);
1329 } else
1330 branch = branch_get(NULL);
1332 value = get_data(branch, &err);
1333 if (!value)
1334 die("%s", err.buf);
1336 if (!branch_interpret_allowed(value, allowed))
1337 return -1;
1339 set_shortened_ref(buf, value);
1340 return len + at;
1343 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf,
1344 unsigned allowed)
1346 char *at;
1347 const char *start;
1348 int len;
1350 if (!namelen)
1351 namelen = strlen(name);
1353 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1354 len = interpret_nth_prior_checkout(name, namelen, buf);
1355 if (!len) {
1356 return len; /* syntax Ok, not enough switches */
1357 } else if (len > 0) {
1358 if (len == namelen)
1359 return len; /* consumed all */
1360 else
1361 return reinterpret(name, namelen, len, buf, allowed);
1365 for (start = name;
1366 (at = memchr(start, '@', namelen - (start - name)));
1367 start = at + 1) {
1369 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1370 len = interpret_empty_at(name, namelen, at - name, buf);
1371 if (len > 0)
1372 return reinterpret(name, namelen, len, buf,
1373 allowed);
1376 len = interpret_branch_mark(name, namelen, at - name, buf,
1377 upstream_mark, branch_get_upstream,
1378 allowed);
1379 if (len > 0)
1380 return len;
1382 len = interpret_branch_mark(name, namelen, at - name, buf,
1383 push_mark, branch_get_push,
1384 allowed);
1385 if (len > 0)
1386 return len;
1389 return -1;
1392 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1394 int len = strlen(name);
1395 int used = interpret_branch_name(name, len, sb, allowed);
1397 if (used < 0)
1398 used = 0;
1399 strbuf_add(sb, name + used, len - used);
1402 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1404 if (startup_info->have_repository)
1405 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1406 else
1407 strbuf_addstr(sb, name);
1410 * This splice must be done even if we end up rejecting the
1411 * name; builtin/branch.c::copy_or_rename_branch() still wants
1412 * to see what the name expanded to so that "branch -m" can be
1413 * used as a tool to correct earlier mistakes.
1415 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1417 if (*name == '-' ||
1418 !strcmp(sb->buf, "refs/heads/HEAD"))
1419 return -1;
1421 return check_refname_format(sb->buf, 0);
1425 * This is like "get_oid_basic()", except it allows "object ID expressions",
1426 * notably "xyz^" for "parent of xyz"
1428 int get_oid(const char *name, struct object_id *oid)
1430 struct object_context unused;
1431 return get_oid_with_context(name, 0, oid, &unused);
1436 * Many callers know that the user meant to name a commit-ish by
1437 * syntactical positions where the object name appears. Calling this
1438 * function allows the machinery to disambiguate shorter-than-unique
1439 * abbreviated object names between commit-ish and others.
1441 * Note that this does NOT error out when the named object is not a
1442 * commit-ish. It is merely to give a hint to the disambiguation
1443 * machinery.
1445 int get_oid_committish(const char *name, struct object_id *oid)
1447 struct object_context unused;
1448 return get_oid_with_context(name, GET_OID_COMMITTISH,
1449 oid, &unused);
1452 int get_oid_treeish(const char *name, struct object_id *oid)
1454 struct object_context unused;
1455 return get_oid_with_context(name, GET_OID_TREEISH,
1456 oid, &unused);
1459 int get_oid_commit(const char *name, struct object_id *oid)
1461 struct object_context unused;
1462 return get_oid_with_context(name, GET_OID_COMMIT,
1463 oid, &unused);
1466 int get_oid_tree(const char *name, struct object_id *oid)
1468 struct object_context unused;
1469 return get_oid_with_context(name, GET_OID_TREE,
1470 oid, &unused);
1473 int get_oid_blob(const char *name, struct object_id *oid)
1475 struct object_context unused;
1476 return get_oid_with_context(name, GET_OID_BLOB,
1477 oid, &unused);
1480 /* Must be called only when object_name:filename doesn't exist. */
1481 static void diagnose_invalid_oid_path(const char *prefix,
1482 const char *filename,
1483 const struct object_id *tree_oid,
1484 const char *object_name,
1485 int object_name_len)
1487 struct object_id oid;
1488 unsigned mode;
1490 if (!prefix)
1491 prefix = "";
1493 if (file_exists(filename))
1494 die("Path '%s' exists on disk, but not in '%.*s'.",
1495 filename, object_name_len, object_name);
1496 if (is_missing_file_error(errno)) {
1497 char *fullname = xstrfmt("%s%s", prefix, filename);
1499 if (!get_tree_entry(tree_oid, fullname, &oid, &mode)) {
1500 die("Path '%s' exists, but not '%s'.\n"
1501 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1502 fullname,
1503 filename,
1504 object_name_len, object_name,
1505 fullname,
1506 object_name_len, object_name,
1507 filename);
1509 die("Path '%s' does not exist in '%.*s'",
1510 filename, object_name_len, object_name);
1514 /* Must be called only when :stage:filename doesn't exist. */
1515 static void diagnose_invalid_index_path(int stage,
1516 const char *prefix,
1517 const char *filename)
1519 const struct cache_entry *ce;
1520 int pos;
1521 unsigned namelen = strlen(filename);
1522 struct strbuf fullname = STRBUF_INIT;
1524 if (!prefix)
1525 prefix = "";
1527 /* Wrong stage number? */
1528 pos = cache_name_pos(filename, namelen);
1529 if (pos < 0)
1530 pos = -pos - 1;
1531 if (pos < active_nr) {
1532 ce = active_cache[pos];
1533 if (ce_namelen(ce) == namelen &&
1534 !memcmp(ce->name, filename, namelen))
1535 die("Path '%s' is in the index, but not at stage %d.\n"
1536 "Did you mean ':%d:%s'?",
1537 filename, stage,
1538 ce_stage(ce), filename);
1541 /* Confusion between relative and absolute filenames? */
1542 strbuf_addstr(&fullname, prefix);
1543 strbuf_addstr(&fullname, filename);
1544 pos = cache_name_pos(fullname.buf, fullname.len);
1545 if (pos < 0)
1546 pos = -pos - 1;
1547 if (pos < active_nr) {
1548 ce = active_cache[pos];
1549 if (ce_namelen(ce) == fullname.len &&
1550 !memcmp(ce->name, fullname.buf, fullname.len))
1551 die("Path '%s' is in the index, but not '%s'.\n"
1552 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1553 fullname.buf, filename,
1554 ce_stage(ce), fullname.buf,
1555 ce_stage(ce), filename);
1558 if (file_exists(filename))
1559 die("Path '%s' exists on disk, but not in the index.", filename);
1560 if (is_missing_file_error(errno))
1561 die("Path '%s' does not exist (neither on disk nor in the index).",
1562 filename);
1564 strbuf_release(&fullname);
1568 static char *resolve_relative_path(const char *rel)
1570 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1571 return NULL;
1573 if (!is_inside_work_tree())
1574 die("relative path syntax can't be used outside working tree.");
1576 /* die() inside prefix_path() if resolved path is outside worktree */
1577 return prefix_path(startup_info->prefix,
1578 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1579 rel);
1582 static int get_oid_with_context_1(const char *name,
1583 unsigned flags,
1584 const char *prefix,
1585 struct object_id *oid,
1586 struct object_context *oc)
1588 int ret, bracket_depth;
1589 int namelen = strlen(name);
1590 const char *cp;
1591 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
1593 if (only_to_die)
1594 flags |= GET_OID_QUIETLY;
1596 memset(oc, 0, sizeof(*oc));
1597 oc->mode = S_IFINVALID;
1598 strbuf_init(&oc->symlink_path, 0);
1599 ret = get_oid_1(name, namelen, oid, flags);
1600 if (!ret)
1601 return ret;
1603 * sha1:path --> object name of path in ent sha1
1604 * :path -> object name of absolute path in index
1605 * :./path -> object name of path relative to cwd in index
1606 * :[0-3]:path -> object name of path in index at stage
1607 * :/foo -> recent commit matching foo
1609 if (name[0] == ':') {
1610 int stage = 0;
1611 const struct cache_entry *ce;
1612 char *new_path = NULL;
1613 int pos;
1614 if (!only_to_die && namelen > 2 && name[1] == '/') {
1615 struct commit_list *list = NULL;
1617 for_each_ref(handle_one_ref, &list);
1618 commit_list_sort_by_date(&list);
1619 return get_oid_oneline(name + 2, oid, list);
1621 if (namelen < 3 ||
1622 name[2] != ':' ||
1623 name[1] < '0' || '3' < name[1])
1624 cp = name + 1;
1625 else {
1626 stage = name[1] - '0';
1627 cp = name + 3;
1629 new_path = resolve_relative_path(cp);
1630 if (!new_path) {
1631 namelen = namelen - (cp - name);
1632 } else {
1633 cp = new_path;
1634 namelen = strlen(cp);
1637 if (flags & GET_OID_RECORD_PATH)
1638 oc->path = xstrdup(cp);
1640 if (!active_cache)
1641 read_cache();
1642 pos = cache_name_pos(cp, namelen);
1643 if (pos < 0)
1644 pos = -pos - 1;
1645 while (pos < active_nr) {
1646 ce = active_cache[pos];
1647 if (ce_namelen(ce) != namelen ||
1648 memcmp(ce->name, cp, namelen))
1649 break;
1650 if (ce_stage(ce) == stage) {
1651 oidcpy(oid, &ce->oid);
1652 oc->mode = ce->ce_mode;
1653 free(new_path);
1654 return 0;
1656 pos++;
1658 if (only_to_die && name[1] && name[1] != '/')
1659 diagnose_invalid_index_path(stage, prefix, cp);
1660 free(new_path);
1661 return -1;
1663 for (cp = name, bracket_depth = 0; *cp; cp++) {
1664 if (*cp == '{')
1665 bracket_depth++;
1666 else if (bracket_depth && *cp == '}')
1667 bracket_depth--;
1668 else if (!bracket_depth && *cp == ':')
1669 break;
1671 if (*cp == ':') {
1672 struct object_id tree_oid;
1673 int len = cp - name;
1674 unsigned sub_flags = flags;
1676 sub_flags &= ~GET_OID_DISAMBIGUATORS;
1677 sub_flags |= GET_OID_TREEISH;
1679 if (!get_oid_1(name, len, &tree_oid, sub_flags)) {
1680 const char *filename = cp+1;
1681 char *new_filename = NULL;
1683 new_filename = resolve_relative_path(filename);
1684 if (new_filename)
1685 filename = new_filename;
1686 if (flags & GET_OID_FOLLOW_SYMLINKS) {
1687 ret = get_tree_entry_follow_symlinks(tree_oid.hash,
1688 filename, oid->hash, &oc->symlink_path,
1689 &oc->mode);
1690 } else {
1691 ret = get_tree_entry(&tree_oid, filename, oid,
1692 &oc->mode);
1693 if (ret && only_to_die) {
1694 diagnose_invalid_oid_path(prefix,
1695 filename,
1696 &tree_oid,
1697 name, len);
1700 hashcpy(oc->tree, tree_oid.hash);
1701 if (flags & GET_OID_RECORD_PATH)
1702 oc->path = xstrdup(filename);
1704 free(new_filename);
1705 return ret;
1706 } else {
1707 if (only_to_die)
1708 die("Invalid object name '%.*s'.", len, name);
1711 return ret;
1715 * Call this function when you know "name" given by the end user must
1716 * name an object but it doesn't; the function _may_ die with a better
1717 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1718 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1719 * you have a chance to diagnose the error further.
1721 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1723 struct object_context oc;
1724 struct object_id oid;
1725 get_oid_with_context_1(name, GET_OID_ONLY_TO_DIE, prefix, &oid, &oc);
1728 int get_oid_with_context(const char *str, unsigned flags, struct object_id *oid, struct object_context *oc)
1730 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
1731 die("BUG: incompatible flags for get_sha1_with_context");
1732 return get_oid_with_context_1(str, flags, NULL, oid, oc);