multi-pack-index: close file descriptor after mmap
[git.git] / sha1-name.c
blob6cccfbbfbff396fb17ac9f3f357dcead802ecf94
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"
17 static int get_oid_oneline(const char *, struct object_id *, struct commit_list *);
19 typedef int (*disambiguate_hint_fn)(const struct object_id *, void *);
21 struct disambiguate_state {
22 int len; /* length of prefix in hex chars */
23 char hex_pfx[GIT_MAX_HEXSZ + 1];
24 struct object_id bin_pfx;
26 disambiguate_hint_fn fn;
27 void *cb_data;
28 struct object_id candidate;
29 unsigned candidate_exists:1;
30 unsigned candidate_checked:1;
31 unsigned candidate_ok:1;
32 unsigned disambiguate_fn_used:1;
33 unsigned ambiguous:1;
34 unsigned always_call_fn:1;
37 static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
39 if (ds->always_call_fn) {
40 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
41 return;
43 if (!ds->candidate_exists) {
44 /* this is the first candidate */
45 oidcpy(&ds->candidate, current);
46 ds->candidate_exists = 1;
47 return;
48 } else if (!oidcmp(&ds->candidate, current)) {
49 /* the same as what we already have seen */
50 return;
53 if (!ds->fn) {
54 /* cannot disambiguate between ds->candidate and current */
55 ds->ambiguous = 1;
56 return;
59 if (!ds->candidate_checked) {
60 ds->candidate_ok = ds->fn(&ds->candidate, ds->cb_data);
61 ds->disambiguate_fn_used = 1;
62 ds->candidate_checked = 1;
65 if (!ds->candidate_ok) {
66 /* discard the candidate; we know it does not satisfy fn */
67 oidcpy(&ds->candidate, current);
68 ds->candidate_checked = 0;
69 return;
72 /* if we reach this point, we know ds->candidate satisfies fn */
73 if (ds->fn(current, ds->cb_data)) {
75 * if both current and candidate satisfy fn, we cannot
76 * disambiguate.
78 ds->candidate_ok = 0;
79 ds->ambiguous = 1;
82 /* otherwise, current can be discarded and candidate is still good */
85 static int append_loose_object(const struct object_id *oid, const char *path,
86 void *data)
88 oid_array_append(data, oid);
89 return 0;
92 static int match_sha(unsigned, const unsigned char *, const unsigned char *);
94 static void find_short_object_filename(struct disambiguate_state *ds)
96 int subdir_nr = ds->bin_pfx.hash[0];
97 struct alternate_object_database *alt;
98 static struct alternate_object_database *fakeent;
100 if (!fakeent) {
102 * Create a "fake" alternate object database that
103 * points to our own object database, to make it
104 * easier to get a temporary working space in
105 * alt->name/alt->base while iterating over the
106 * object databases including our own.
108 fakeent = alloc_alt_odb(get_object_directory());
110 fakeent->next = the_repository->objects->alt_odb_list;
112 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
113 int pos;
115 if (!alt->loose_objects_subdir_seen[subdir_nr]) {
116 struct strbuf *buf = alt_scratch_buf(alt);
117 for_each_file_in_obj_subdir(subdir_nr, buf,
118 append_loose_object,
119 NULL, NULL,
120 &alt->loose_objects_cache);
121 alt->loose_objects_subdir_seen[subdir_nr] = 1;
124 pos = oid_array_lookup(&alt->loose_objects_cache, &ds->bin_pfx);
125 if (pos < 0)
126 pos = -1 - pos;
127 while (!ds->ambiguous && pos < alt->loose_objects_cache.nr) {
128 const struct object_id *oid;
129 oid = alt->loose_objects_cache.oid + pos;
130 if (!match_sha(ds->len, ds->bin_pfx.hash, oid->hash))
131 break;
132 update_candidates(ds, oid);
133 pos++;
138 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
140 do {
141 if (*a != *b)
142 return 0;
143 a++;
144 b++;
145 len -= 2;
146 } while (len > 1);
147 if (len)
148 if ((*a ^ *b) & 0xf0)
149 return 0;
150 return 1;
153 static void unique_in_midx(struct multi_pack_index *m,
154 struct disambiguate_state *ds)
156 uint32_t num, i, first = 0;
157 const struct object_id *current = NULL;
158 num = m->num_objects;
160 if (!num)
161 return;
163 bsearch_midx(&ds->bin_pfx, m, &first);
166 * At this point, "first" is the location of the lowest object
167 * with an object name that could match "bin_pfx". See if we have
168 * 0, 1 or more objects that actually match(es).
170 for (i = first; i < num && !ds->ambiguous; i++) {
171 struct object_id oid;
172 current = nth_midxed_object_oid(&oid, m, i);
173 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
174 break;
175 update_candidates(ds, current);
179 static void unique_in_pack(struct packed_git *p,
180 struct disambiguate_state *ds)
182 uint32_t num, i, first = 0;
183 const struct object_id *current = NULL;
185 if (open_pack_index(p) || !p->num_objects)
186 return;
188 num = p->num_objects;
189 bsearch_pack(&ds->bin_pfx, p, &first);
192 * At this point, "first" is the location of the lowest object
193 * with an object name that could match "bin_pfx". See if we have
194 * 0, 1 or more objects that actually match(es).
196 for (i = first; i < num && !ds->ambiguous; i++) {
197 struct object_id oid;
198 current = nth_packed_object_oid(&oid, p, i);
199 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
200 break;
201 update_candidates(ds, current);
205 static void find_short_packed_object(struct disambiguate_state *ds)
207 struct multi_pack_index *m;
208 struct packed_git *p;
210 for (m = get_multi_pack_index(the_repository); m && !ds->ambiguous;
211 m = m->next)
212 unique_in_midx(m, ds);
213 for (p = get_packed_git(the_repository); p && !ds->ambiguous;
214 p = p->next)
215 unique_in_pack(p, ds);
218 #define SHORT_NAME_NOT_FOUND (-1)
219 #define SHORT_NAME_AMBIGUOUS (-2)
221 static int finish_object_disambiguation(struct disambiguate_state *ds,
222 struct object_id *oid)
224 if (ds->ambiguous)
225 return SHORT_NAME_AMBIGUOUS;
227 if (!ds->candidate_exists)
228 return SHORT_NAME_NOT_FOUND;
230 if (!ds->candidate_checked)
232 * If this is the only candidate, there is no point
233 * calling the disambiguation hint callback.
235 * On the other hand, if the current candidate
236 * replaced an earlier candidate that did _not_ pass
237 * the disambiguation hint callback, then we do have
238 * more than one objects that match the short name
239 * given, so we should make sure this one matches;
240 * otherwise, if we discovered this one and the one
241 * that we previously discarded in the reverse order,
242 * we would end up showing different results in the
243 * same repository!
245 ds->candidate_ok = (!ds->disambiguate_fn_used ||
246 ds->fn(&ds->candidate, ds->cb_data));
248 if (!ds->candidate_ok)
249 return SHORT_NAME_AMBIGUOUS;
251 oidcpy(oid, &ds->candidate);
252 return 0;
255 static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
257 int kind = oid_object_info(the_repository, oid, NULL);
258 return kind == OBJ_COMMIT;
261 static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
263 struct object *obj;
264 int kind;
266 kind = oid_object_info(the_repository, oid, NULL);
267 if (kind == OBJ_COMMIT)
268 return 1;
269 if (kind != OBJ_TAG)
270 return 0;
272 /* We need to do this the hard way... */
273 obj = deref_tag(the_repository, parse_object(the_repository, oid),
274 NULL, 0);
275 if (obj && obj->type == OBJ_COMMIT)
276 return 1;
277 return 0;
280 static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
282 int kind = oid_object_info(the_repository, oid, NULL);
283 return kind == OBJ_TREE;
286 static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
288 struct object *obj;
289 int kind;
291 kind = oid_object_info(the_repository, oid, NULL);
292 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
293 return 1;
294 if (kind != OBJ_TAG)
295 return 0;
297 /* We need to do this the hard way... */
298 obj = deref_tag(the_repository, parse_object(the_repository, oid),
299 NULL, 0);
300 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
301 return 1;
302 return 0;
305 static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
307 int kind = oid_object_info(the_repository, oid, NULL);
308 return kind == OBJ_BLOB;
311 static disambiguate_hint_fn default_disambiguate_hint;
313 int set_disambiguate_hint_config(const char *var, const char *value)
315 static const struct {
316 const char *name;
317 disambiguate_hint_fn fn;
318 } hints[] = {
319 { "none", NULL },
320 { "commit", disambiguate_commit_only },
321 { "committish", disambiguate_committish_only },
322 { "tree", disambiguate_tree_only },
323 { "treeish", disambiguate_treeish_only },
324 { "blob", disambiguate_blob_only }
326 int i;
328 if (!value)
329 return config_error_nonbool(var);
331 for (i = 0; i < ARRAY_SIZE(hints); i++) {
332 if (!strcasecmp(value, hints[i].name)) {
333 default_disambiguate_hint = hints[i].fn;
334 return 0;
338 return error("unknown hint type for '%s': %s", var, value);
341 static int init_object_disambiguation(const char *name, int len,
342 struct disambiguate_state *ds)
344 int i;
346 if (len < MINIMUM_ABBREV || len > the_hash_algo->hexsz)
347 return -1;
349 memset(ds, 0, sizeof(*ds));
351 for (i = 0; i < len ;i++) {
352 unsigned char c = name[i];
353 unsigned char val;
354 if (c >= '0' && c <= '9')
355 val = c - '0';
356 else if (c >= 'a' && c <= 'f')
357 val = c - 'a' + 10;
358 else if (c >= 'A' && c <='F') {
359 val = c - 'A' + 10;
360 c -= 'A' - 'a';
362 else
363 return -1;
364 ds->hex_pfx[i] = c;
365 if (!(i & 1))
366 val <<= 4;
367 ds->bin_pfx.hash[i >> 1] |= val;
370 ds->len = len;
371 ds->hex_pfx[len] = '\0';
372 prepare_alt_odb(the_repository);
373 return 0;
376 static int show_ambiguous_object(const struct object_id *oid, void *data)
378 const struct disambiguate_state *ds = data;
379 struct strbuf desc = STRBUF_INIT;
380 int type;
382 if (ds->fn && !ds->fn(oid, ds->cb_data))
383 return 0;
385 type = oid_object_info(the_repository, oid, NULL);
386 if (type == OBJ_COMMIT) {
387 struct commit *commit = lookup_commit(the_repository, oid);
388 if (commit) {
389 struct pretty_print_context pp = {0};
390 pp.date_mode.type = DATE_SHORT;
391 format_commit_message(commit, " %ad - %s", &desc, &pp);
393 } else if (type == OBJ_TAG) {
394 struct tag *tag = lookup_tag(the_repository, oid);
395 if (!parse_tag(tag) && tag->tag)
396 strbuf_addf(&desc, " %s", tag->tag);
399 advise(" %s %s%s",
400 find_unique_abbrev(oid, DEFAULT_ABBREV),
401 type_name(type) ? type_name(type) : "unknown type",
402 desc.buf);
404 strbuf_release(&desc);
405 return 0;
408 static int collect_ambiguous(const struct object_id *oid, void *data)
410 oid_array_append(data, oid);
411 return 0;
414 static int sort_ambiguous(const void *a, const void *b)
416 int a_type = oid_object_info(the_repository, a, NULL);
417 int b_type = oid_object_info(the_repository, b, NULL);
418 int a_type_sort;
419 int b_type_sort;
422 * Sorts by hash within the same object type, just as
423 * oid_array_for_each_unique() would do.
425 if (a_type == b_type)
426 return oidcmp(a, b);
429 * Between object types show tags, then commits, and finally
430 * trees and blobs.
432 * The object_type enum is commit, tree, blob, tag, but we
433 * want tag, commit, tree blob. Cleverly (perhaps too
434 * cleverly) do that with modulus, since the enum assigns 1 to
435 * commit, so tag becomes 0.
437 a_type_sort = a_type % 4;
438 b_type_sort = b_type % 4;
439 return a_type_sort > b_type_sort ? 1 : -1;
442 static int get_short_oid(const char *name, int len, struct object_id *oid,
443 unsigned flags)
445 int status;
446 struct disambiguate_state ds;
447 int quietly = !!(flags & GET_OID_QUIETLY);
449 if (init_object_disambiguation(name, len, &ds) < 0)
450 return -1;
452 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
453 BUG("multiple get_short_oid disambiguator flags");
455 if (flags & GET_OID_COMMIT)
456 ds.fn = disambiguate_commit_only;
457 else if (flags & GET_OID_COMMITTISH)
458 ds.fn = disambiguate_committish_only;
459 else if (flags & GET_OID_TREE)
460 ds.fn = disambiguate_tree_only;
461 else if (flags & GET_OID_TREEISH)
462 ds.fn = disambiguate_treeish_only;
463 else if (flags & GET_OID_BLOB)
464 ds.fn = disambiguate_blob_only;
465 else
466 ds.fn = default_disambiguate_hint;
468 find_short_object_filename(&ds);
469 find_short_packed_object(&ds);
470 status = finish_object_disambiguation(&ds, oid);
472 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
473 struct oid_array collect = OID_ARRAY_INIT;
475 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
478 * We may still have ambiguity if we simply saw a series of
479 * candidates that did not satisfy our hint function. In
480 * that case, we still want to show them, so disable the hint
481 * function entirely.
483 if (!ds.ambiguous)
484 ds.fn = NULL;
486 advise(_("The candidates are:"));
487 for_each_abbrev(ds.hex_pfx, collect_ambiguous, &collect);
488 QSORT(collect.oid, collect.nr, sort_ambiguous);
490 if (oid_array_for_each(&collect, show_ambiguous_object, &ds))
491 BUG("show_ambiguous_object shouldn't return non-zero");
492 oid_array_clear(&collect);
495 return status;
498 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
500 struct oid_array collect = OID_ARRAY_INIT;
501 struct disambiguate_state ds;
502 int ret;
504 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
505 return -1;
507 ds.always_call_fn = 1;
508 ds.fn = collect_ambiguous;
509 ds.cb_data = &collect;
510 find_short_object_filename(&ds);
511 find_short_packed_object(&ds);
513 ret = oid_array_for_each_unique(&collect, fn, cb_data);
514 oid_array_clear(&collect);
515 return ret;
519 * Return the slot of the most-significant bit set in "val". There are various
520 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
521 * probably not a big deal here.
523 static unsigned msb(unsigned long val)
525 unsigned r = 0;
526 while (val >>= 1)
527 r++;
528 return r;
531 struct min_abbrev_data {
532 unsigned int init_len;
533 unsigned int cur_len;
534 char *hex;
535 const struct object_id *oid;
538 static inline char get_hex_char_from_oid(const struct object_id *oid,
539 unsigned int pos)
541 static const char hex[] = "0123456789abcdef";
543 if ((pos & 1) == 0)
544 return hex[oid->hash[pos >> 1] >> 4];
545 else
546 return hex[oid->hash[pos >> 1] & 0xf];
549 static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
551 struct min_abbrev_data *mad = cb_data;
553 unsigned int i = mad->init_len;
554 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
555 i++;
557 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
558 mad->cur_len = i + 1;
560 return 0;
563 static void find_abbrev_len_for_midx(struct multi_pack_index *m,
564 struct min_abbrev_data *mad)
566 int match = 0;
567 uint32_t num, first = 0;
568 struct object_id oid;
569 const struct object_id *mad_oid;
571 if (!m->num_objects)
572 return;
574 num = m->num_objects;
575 mad_oid = mad->oid;
576 match = bsearch_midx(mad_oid, m, &first);
579 * first is now the position in the packfile where we would insert
580 * mad->hash if it does not exist (or the position of mad->hash if
581 * it does exist). Hence, we consider a maximum of two objects
582 * nearby for the abbreviation length.
584 mad->init_len = 0;
585 if (!match) {
586 if (nth_midxed_object_oid(&oid, m, first))
587 extend_abbrev_len(&oid, mad);
588 } else if (first < num - 1) {
589 if (nth_midxed_object_oid(&oid, m, first + 1))
590 extend_abbrev_len(&oid, mad);
592 if (first > 0) {
593 if (nth_midxed_object_oid(&oid, m, first - 1))
594 extend_abbrev_len(&oid, mad);
596 mad->init_len = mad->cur_len;
599 static void find_abbrev_len_for_pack(struct packed_git *p,
600 struct min_abbrev_data *mad)
602 int match = 0;
603 uint32_t num, first = 0;
604 struct object_id oid;
605 const struct object_id *mad_oid;
607 if (open_pack_index(p) || !p->num_objects)
608 return;
610 num = p->num_objects;
611 mad_oid = mad->oid;
612 match = bsearch_pack(mad_oid, p, &first);
615 * first is now the position in the packfile where we would insert
616 * mad->hash if it does not exist (or the position of mad->hash if
617 * it does exist). Hence, we consider a maximum of two objects
618 * nearby for the abbreviation length.
620 mad->init_len = 0;
621 if (!match) {
622 if (nth_packed_object_oid(&oid, p, first))
623 extend_abbrev_len(&oid, mad);
624 } else if (first < num - 1) {
625 if (nth_packed_object_oid(&oid, p, first + 1))
626 extend_abbrev_len(&oid, mad);
628 if (first > 0) {
629 if (nth_packed_object_oid(&oid, p, first - 1))
630 extend_abbrev_len(&oid, mad);
632 mad->init_len = mad->cur_len;
635 static void find_abbrev_len_packed(struct min_abbrev_data *mad)
637 struct multi_pack_index *m;
638 struct packed_git *p;
640 for (m = get_multi_pack_index(the_repository); m; m = m->next)
641 find_abbrev_len_for_midx(m, mad);
642 for (p = get_packed_git(the_repository); p; p = p->next)
643 find_abbrev_len_for_pack(p, mad);
646 int find_unique_abbrev_r(char *hex, const struct object_id *oid, int len)
648 struct disambiguate_state ds;
649 struct min_abbrev_data mad;
650 struct object_id oid_ret;
651 const unsigned hexsz = the_hash_algo->hexsz;
653 if (len < 0) {
654 unsigned long count = approximate_object_count();
656 * Add one because the MSB only tells us the highest bit set,
657 * not including the value of all the _other_ bits (so "15"
658 * is only one off of 2^4, but the MSB is the 3rd bit.
660 len = msb(count) + 1;
662 * We now know we have on the order of 2^len objects, which
663 * expects a collision at 2^(len/2). But we also care about hex
664 * chars, not bits, and there are 4 bits per hex. So all
665 * together we need to divide by 2 and round up.
667 len = DIV_ROUND_UP(len, 2);
669 * For very small repos, we stick with our regular fallback.
671 if (len < FALLBACK_DEFAULT_ABBREV)
672 len = FALLBACK_DEFAULT_ABBREV;
675 oid_to_hex_r(hex, oid);
676 if (len == hexsz || !len)
677 return hexsz;
679 mad.init_len = len;
680 mad.cur_len = len;
681 mad.hex = hex;
682 mad.oid = oid;
684 find_abbrev_len_packed(&mad);
686 if (init_object_disambiguation(hex, mad.cur_len, &ds) < 0)
687 return -1;
689 ds.fn = extend_abbrev_len;
690 ds.always_call_fn = 1;
691 ds.cb_data = (void *)&mad;
693 find_short_object_filename(&ds);
694 (void)finish_object_disambiguation(&ds, &oid_ret);
696 hex[mad.cur_len] = 0;
697 return mad.cur_len;
700 const char *find_unique_abbrev(const struct object_id *oid, int len)
702 static int bufno;
703 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
704 char *hex = hexbuffer[bufno];
705 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
706 find_unique_abbrev_r(hex, oid, len);
707 return hex;
710 static int ambiguous_path(const char *path, int len)
712 int slash = 1;
713 int cnt;
715 for (cnt = 0; cnt < len; cnt++) {
716 switch (*path++) {
717 case '\0':
718 break;
719 case '/':
720 if (slash)
721 break;
722 slash = 1;
723 continue;
724 case '.':
725 continue;
726 default:
727 slash = 0;
728 continue;
730 break;
732 return slash;
735 static inline int at_mark(const char *string, int len,
736 const char **suffix, int nr)
738 int i;
740 for (i = 0; i < nr; i++) {
741 int suffix_len = strlen(suffix[i]);
742 if (suffix_len <= len
743 && !strncasecmp(string, suffix[i], suffix_len))
744 return suffix_len;
746 return 0;
749 static inline int upstream_mark(const char *string, int len)
751 const char *suffix[] = { "@{upstream}", "@{u}" };
752 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
755 static inline int push_mark(const char *string, int len)
757 const char *suffix[] = { "@{push}" };
758 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
761 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags);
762 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
764 static int get_oid_basic(const char *str, int len, struct object_id *oid,
765 unsigned int flags)
767 static const char *warn_msg = "refname '%.*s' is ambiguous.";
768 static const char *object_name_msg = N_(
769 "Git normally never creates a ref that ends with 40 hex characters\n"
770 "because it will be ignored when you just specify 40-hex. These refs\n"
771 "may be created by mistake. For example,\n"
772 "\n"
773 " git checkout -b $br $(git rev-parse ...)\n"
774 "\n"
775 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
776 "examine these refs and maybe delete them. Turn this message off by\n"
777 "running \"git config advice.objectNameWarning false\"");
778 struct object_id tmp_oid;
779 char *real_ref = NULL;
780 int refs_found = 0;
781 int at, reflog_len, nth_prior = 0;
783 if (len == the_hash_algo->hexsz && !get_oid_hex(str, oid)) {
784 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
785 refs_found = dwim_ref(str, len, &tmp_oid, &real_ref);
786 if (refs_found > 0) {
787 warning(warn_msg, len, str);
788 if (advice_object_name_warning)
789 fprintf(stderr, "%s\n", _(object_name_msg));
791 free(real_ref);
793 return 0;
796 /* basic@{time or number or -number} format to query ref-log */
797 reflog_len = at = 0;
798 if (len && str[len-1] == '}') {
799 for (at = len-4; at >= 0; at--) {
800 if (str[at] == '@' && str[at+1] == '{') {
801 if (str[at+2] == '-') {
802 if (at != 0)
803 /* @{-N} not at start */
804 return -1;
805 nth_prior = 1;
806 continue;
808 if (!upstream_mark(str + at, len - at) &&
809 !push_mark(str + at, len - at)) {
810 reflog_len = (len-1) - (at+2);
811 len = at;
813 break;
818 /* Accept only unambiguous ref paths. */
819 if (len && ambiguous_path(str, len))
820 return -1;
822 if (nth_prior) {
823 struct strbuf buf = STRBUF_INIT;
824 int detached;
826 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
827 detached = (buf.len == the_hash_algo->hexsz && !get_oid_hex(buf.buf, oid));
828 strbuf_release(&buf);
829 if (detached)
830 return 0;
834 if (!len && reflog_len)
835 /* allow "@{...}" to mean the current branch reflog */
836 refs_found = dwim_ref("HEAD", 4, oid, &real_ref);
837 else if (reflog_len)
838 refs_found = dwim_log(str, len, oid, &real_ref);
839 else
840 refs_found = dwim_ref(str, len, oid, &real_ref);
842 if (!refs_found)
843 return -1;
845 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
846 (refs_found > 1 ||
847 !get_short_oid(str, len, &tmp_oid, GET_OID_QUIETLY)))
848 warning(warn_msg, len, str);
850 if (reflog_len) {
851 int nth, i;
852 timestamp_t at_time;
853 timestamp_t co_time;
854 int co_tz, co_cnt;
856 /* Is it asking for N-th entry, or approxidate? */
857 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
858 char ch = str[at+2+i];
859 if ('0' <= ch && ch <= '9')
860 nth = nth * 10 + ch - '0';
861 else
862 nth = -1;
864 if (100000000 <= nth) {
865 at_time = nth;
866 nth = -1;
867 } else if (0 <= nth)
868 at_time = 0;
869 else {
870 int errors = 0;
871 char *tmp = xstrndup(str + at + 2, reflog_len);
872 at_time = approxidate_careful(tmp, &errors);
873 free(tmp);
874 if (errors) {
875 free(real_ref);
876 return -1;
879 if (read_ref_at(real_ref, flags, at_time, nth, oid, NULL,
880 &co_time, &co_tz, &co_cnt)) {
881 if (!len) {
882 if (starts_with(real_ref, "refs/heads/")) {
883 str = real_ref + 11;
884 len = strlen(real_ref + 11);
885 } else {
886 /* detached HEAD */
887 str = "HEAD";
888 len = 4;
891 if (at_time) {
892 if (!(flags & GET_OID_QUIETLY)) {
893 warning("Log for '%.*s' only goes "
894 "back to %s.", len, str,
895 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
897 } else {
898 if (flags & GET_OID_QUIETLY) {
899 exit(128);
901 die("Log for '%.*s' only has %d entries.",
902 len, str, co_cnt);
907 free(real_ref);
908 return 0;
911 static int get_parent(const char *name, int len,
912 struct object_id *result, int idx)
914 struct object_id oid;
915 int ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
916 struct commit *commit;
917 struct commit_list *p;
919 if (ret)
920 return ret;
921 commit = lookup_commit_reference(the_repository, &oid);
922 if (parse_commit(commit))
923 return -1;
924 if (!idx) {
925 oidcpy(result, &commit->object.oid);
926 return 0;
928 p = commit->parents;
929 while (p) {
930 if (!--idx) {
931 oidcpy(result, &p->item->object.oid);
932 return 0;
934 p = p->next;
936 return -1;
939 static int get_nth_ancestor(const char *name, int len,
940 struct object_id *result, int generation)
942 struct object_id oid;
943 struct commit *commit;
944 int ret;
946 ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
947 if (ret)
948 return ret;
949 commit = lookup_commit_reference(the_repository, &oid);
950 if (!commit)
951 return -1;
953 while (generation--) {
954 if (parse_commit(commit) || !commit->parents)
955 return -1;
956 commit = commit->parents->item;
958 oidcpy(result, &commit->object.oid);
959 return 0;
962 struct object *peel_to_type(const char *name, int namelen,
963 struct object *o, enum object_type expected_type)
965 if (name && !namelen)
966 namelen = strlen(name);
967 while (1) {
968 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
969 return NULL;
970 if (expected_type == OBJ_ANY || o->type == expected_type)
971 return o;
972 if (o->type == OBJ_TAG)
973 o = ((struct tag*) o)->tagged;
974 else if (o->type == OBJ_COMMIT)
975 o = &(get_commit_tree(((struct commit *)o))->object);
976 else {
977 if (name)
978 error("%.*s: expected %s type, but the object "
979 "dereferences to %s type",
980 namelen, name, type_name(expected_type),
981 type_name(o->type));
982 return NULL;
987 static int peel_onion(const char *name, int len, struct object_id *oid,
988 unsigned lookup_flags)
990 struct object_id outer;
991 const char *sp;
992 unsigned int expected_type = 0;
993 struct object *o;
996 * "ref^{type}" dereferences ref repeatedly until you cannot
997 * dereference anymore, or you get an object of given type,
998 * whichever comes first. "ref^{}" means just dereference
999 * tags until you get a non-tag. "ref^0" is a shorthand for
1000 * "ref^{commit}". "commit^{tree}" could be used to find the
1001 * top-level tree of the given commit.
1003 if (len < 4 || name[len-1] != '}')
1004 return -1;
1006 for (sp = name + len - 1; name <= sp; sp--) {
1007 int ch = *sp;
1008 if (ch == '{' && name < sp && sp[-1] == '^')
1009 break;
1011 if (sp <= name)
1012 return -1;
1014 sp++; /* beginning of type name, or closing brace for empty */
1015 if (starts_with(sp, "commit}"))
1016 expected_type = OBJ_COMMIT;
1017 else if (starts_with(sp, "tag}"))
1018 expected_type = OBJ_TAG;
1019 else if (starts_with(sp, "tree}"))
1020 expected_type = OBJ_TREE;
1021 else if (starts_with(sp, "blob}"))
1022 expected_type = OBJ_BLOB;
1023 else if (starts_with(sp, "object}"))
1024 expected_type = OBJ_ANY;
1025 else if (sp[0] == '}')
1026 expected_type = OBJ_NONE;
1027 else if (sp[0] == '/')
1028 expected_type = OBJ_COMMIT;
1029 else
1030 return -1;
1032 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
1033 if (expected_type == OBJ_COMMIT)
1034 lookup_flags |= GET_OID_COMMITTISH;
1035 else if (expected_type == OBJ_TREE)
1036 lookup_flags |= GET_OID_TREEISH;
1038 if (get_oid_1(name, sp - name - 2, &outer, lookup_flags))
1039 return -1;
1041 o = parse_object(the_repository, &outer);
1042 if (!o)
1043 return -1;
1044 if (!expected_type) {
1045 o = deref_tag(the_repository, o, name, sp - name - 2);
1046 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
1047 return -1;
1048 oidcpy(oid, &o->oid);
1049 return 0;
1053 * At this point, the syntax look correct, so
1054 * if we do not get the needed object, we should
1055 * barf.
1057 o = peel_to_type(name, len, o, expected_type);
1058 if (!o)
1059 return -1;
1061 oidcpy(oid, &o->oid);
1062 if (sp[0] == '/') {
1063 /* "$commit^{/foo}" */
1064 char *prefix;
1065 int ret;
1066 struct commit_list *list = NULL;
1069 * $commit^{/}. Some regex implementation may reject.
1070 * We don't need regex anyway. '' pattern always matches.
1072 if (sp[1] == '}')
1073 return 0;
1075 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
1076 commit_list_insert((struct commit *)o, &list);
1077 ret = get_oid_oneline(prefix, oid, list);
1078 free(prefix);
1079 return ret;
1081 return 0;
1084 static int get_describe_name(const char *name, int len, struct object_id *oid)
1086 const char *cp;
1087 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
1089 for (cp = name + len - 1; name + 2 <= cp; cp--) {
1090 char ch = *cp;
1091 if (!isxdigit(ch)) {
1092 /* We must be looking at g in "SOMETHING-g"
1093 * for it to be describe output.
1095 if (ch == 'g' && cp[-1] == '-') {
1096 cp++;
1097 len -= cp - name;
1098 return get_short_oid(cp, len, oid, flags);
1102 return -1;
1105 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags)
1107 int ret, has_suffix;
1108 const char *cp;
1111 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1113 has_suffix = 0;
1114 for (cp = name + len - 1; name <= cp; cp--) {
1115 int ch = *cp;
1116 if ('0' <= ch && ch <= '9')
1117 continue;
1118 if (ch == '~' || ch == '^')
1119 has_suffix = ch;
1120 break;
1123 if (has_suffix) {
1124 int num = 0;
1125 int len1 = cp - name;
1126 cp++;
1127 while (cp < name + len)
1128 num = num * 10 + *cp++ - '0';
1129 if (!num && len1 == len - 1)
1130 num = 1;
1131 if (has_suffix == '^')
1132 return get_parent(name, len1, oid, num);
1133 /* else if (has_suffix == '~') -- goes without saying */
1134 return get_nth_ancestor(name, len1, oid, num);
1137 ret = peel_onion(name, len, oid, lookup_flags);
1138 if (!ret)
1139 return 0;
1141 ret = get_oid_basic(name, len, oid, lookup_flags);
1142 if (!ret)
1143 return 0;
1145 /* It could be describe output that is "SOMETHING-gXXXX" */
1146 ret = get_describe_name(name, len, oid);
1147 if (!ret)
1148 return 0;
1150 return get_short_oid(name, len, oid, lookup_flags);
1154 * This interprets names like ':/Initial revision of "git"' by searching
1155 * through history and returning the first commit whose message starts
1156 * the given regular expression.
1158 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1160 * For a literal '!' character at the beginning of a pattern, you have to repeat
1161 * that, like: ':/!!foo'
1163 * For future extension, all other sequences beginning with ':/!' are reserved.
1166 /* Remember to update object flag allocation in object.h */
1167 #define ONELINE_SEEN (1u<<20)
1169 static int handle_one_ref(const char *path, const struct object_id *oid,
1170 int flag, void *cb_data)
1172 struct commit_list **list = cb_data;
1173 struct object *object = parse_object(the_repository, oid);
1174 if (!object)
1175 return 0;
1176 if (object->type == OBJ_TAG) {
1177 object = deref_tag(the_repository, object, path,
1178 strlen(path));
1179 if (!object)
1180 return 0;
1182 if (object->type != OBJ_COMMIT)
1183 return 0;
1184 commit_list_insert((struct commit *)object, list);
1185 return 0;
1188 static int get_oid_oneline(const char *prefix, struct object_id *oid,
1189 struct commit_list *list)
1191 struct commit_list *backup = NULL, *l;
1192 int found = 0;
1193 int negative = 0;
1194 regex_t regex;
1196 if (prefix[0] == '!') {
1197 prefix++;
1199 if (prefix[0] == '-') {
1200 prefix++;
1201 negative = 1;
1202 } else if (prefix[0] != '!') {
1203 return -1;
1207 if (regcomp(&regex, prefix, REG_EXTENDED))
1208 return -1;
1210 for (l = list; l; l = l->next) {
1211 l->item->object.flags |= ONELINE_SEEN;
1212 commit_list_insert(l->item, &backup);
1214 while (list) {
1215 const char *p, *buf;
1216 struct commit *commit;
1217 int matches;
1219 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1220 if (!parse_object(the_repository, &commit->object.oid))
1221 continue;
1222 buf = get_commit_buffer(commit, NULL);
1223 p = strstr(buf, "\n\n");
1224 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
1225 unuse_commit_buffer(commit, buf);
1227 if (matches) {
1228 oidcpy(oid, &commit->object.oid);
1229 found = 1;
1230 break;
1233 regfree(&regex);
1234 free_commit_list(list);
1235 for (l = backup; l; l = l->next)
1236 clear_commit_marks(l->item, ONELINE_SEEN);
1237 free_commit_list(backup);
1238 return found ? 0 : -1;
1241 struct grab_nth_branch_switch_cbdata {
1242 int remaining;
1243 struct strbuf buf;
1246 static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
1247 const char *email, timestamp_t timestamp, int tz,
1248 const char *message, void *cb_data)
1250 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1251 const char *match = NULL, *target = NULL;
1252 size_t len;
1254 if (skip_prefix(message, "checkout: moving from ", &match))
1255 target = strstr(match, " to ");
1257 if (!match || !target)
1258 return 0;
1259 if (--(cb->remaining) == 0) {
1260 len = target - match;
1261 strbuf_reset(&cb->buf);
1262 strbuf_add(&cb->buf, match, len);
1263 return 1; /* we are done */
1265 return 0;
1269 * Parse @{-N} syntax, return the number of characters parsed
1270 * if successful; otherwise signal an error with negative value.
1272 static int interpret_nth_prior_checkout(const char *name, int namelen,
1273 struct strbuf *buf)
1275 long nth;
1276 int retval;
1277 struct grab_nth_branch_switch_cbdata cb;
1278 const char *brace;
1279 char *num_end;
1281 if (namelen < 4)
1282 return -1;
1283 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1284 return -1;
1285 brace = memchr(name, '}', namelen);
1286 if (!brace)
1287 return -1;
1288 nth = strtol(name + 3, &num_end, 10);
1289 if (num_end != brace)
1290 return -1;
1291 if (nth <= 0)
1292 return -1;
1293 cb.remaining = nth;
1294 strbuf_init(&cb.buf, 20);
1296 retval = 0;
1297 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1298 strbuf_reset(buf);
1299 strbuf_addbuf(buf, &cb.buf);
1300 retval = brace - name + 1;
1303 strbuf_release(&cb.buf);
1304 return retval;
1307 int get_oid_mb(const char *name, struct object_id *oid)
1309 struct commit *one, *two;
1310 struct commit_list *mbs;
1311 struct object_id oid_tmp;
1312 const char *dots;
1313 int st;
1315 dots = strstr(name, "...");
1316 if (!dots)
1317 return get_oid(name, oid);
1318 if (dots == name)
1319 st = get_oid("HEAD", &oid_tmp);
1320 else {
1321 struct strbuf sb;
1322 strbuf_init(&sb, dots - name);
1323 strbuf_add(&sb, name, dots - name);
1324 st = get_oid_committish(sb.buf, &oid_tmp);
1325 strbuf_release(&sb);
1327 if (st)
1328 return st;
1329 one = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1330 if (!one)
1331 return -1;
1333 if (get_oid_committish(dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1334 return -1;
1335 two = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1336 if (!two)
1337 return -1;
1338 mbs = get_merge_bases(one, two);
1339 if (!mbs || mbs->next)
1340 st = -1;
1341 else {
1342 st = 0;
1343 oidcpy(oid, &mbs->item->object.oid);
1345 free_commit_list(mbs);
1346 return st;
1349 /* parse @something syntax, when 'something' is not {.*} */
1350 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1352 const char *next;
1354 if (len || name[1] == '{')
1355 return -1;
1357 /* make sure it's a single @, or @@{.*}, not @foo */
1358 next = memchr(name + len + 1, '@', namelen - len - 1);
1359 if (next && next[1] != '{')
1360 return -1;
1361 if (!next)
1362 next = name + namelen;
1363 if (next != name + 1)
1364 return -1;
1366 strbuf_reset(buf);
1367 strbuf_add(buf, "HEAD", 4);
1368 return 1;
1371 static int reinterpret(const char *name, int namelen, int len,
1372 struct strbuf *buf, unsigned allowed)
1374 /* we have extra data, which might need further processing */
1375 struct strbuf tmp = STRBUF_INIT;
1376 int used = buf->len;
1377 int ret;
1379 strbuf_add(buf, name + len, namelen - len);
1380 ret = interpret_branch_name(buf->buf, buf->len, &tmp, allowed);
1381 /* that data was not interpreted, remove our cruft */
1382 if (ret < 0) {
1383 strbuf_setlen(buf, used);
1384 return len;
1386 strbuf_reset(buf);
1387 strbuf_addbuf(buf, &tmp);
1388 strbuf_release(&tmp);
1389 /* tweak for size of {-N} versus expanded ref name */
1390 return ret - used + len;
1393 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1395 char *s = shorten_unambiguous_ref(ref, 0);
1396 strbuf_reset(buf);
1397 strbuf_addstr(buf, s);
1398 free(s);
1401 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1403 if (!allowed)
1404 return 1;
1406 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1407 starts_with(refname, "refs/heads/"))
1408 return 1;
1409 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1410 starts_with(refname, "refs/remotes/"))
1411 return 1;
1413 return 0;
1416 static int interpret_branch_mark(const char *name, int namelen,
1417 int at, struct strbuf *buf,
1418 int (*get_mark)(const char *, int),
1419 const char *(*get_data)(struct branch *,
1420 struct strbuf *),
1421 unsigned allowed)
1423 int len;
1424 struct branch *branch;
1425 struct strbuf err = STRBUF_INIT;
1426 const char *value;
1428 len = get_mark(name + at, namelen - at);
1429 if (!len)
1430 return -1;
1432 if (memchr(name, ':', at))
1433 return -1;
1435 if (at) {
1436 char *name_str = xmemdupz(name, at);
1437 branch = branch_get(name_str);
1438 free(name_str);
1439 } else
1440 branch = branch_get(NULL);
1442 value = get_data(branch, &err);
1443 if (!value)
1444 die("%s", err.buf);
1446 if (!branch_interpret_allowed(value, allowed))
1447 return -1;
1449 set_shortened_ref(buf, value);
1450 return len + at;
1453 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf,
1454 unsigned allowed)
1456 char *at;
1457 const char *start;
1458 int len;
1460 if (!namelen)
1461 namelen = strlen(name);
1463 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1464 len = interpret_nth_prior_checkout(name, namelen, buf);
1465 if (!len) {
1466 return len; /* syntax Ok, not enough switches */
1467 } else if (len > 0) {
1468 if (len == namelen)
1469 return len; /* consumed all */
1470 else
1471 return reinterpret(name, namelen, len, buf, allowed);
1475 for (start = name;
1476 (at = memchr(start, '@', namelen - (start - name)));
1477 start = at + 1) {
1479 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1480 len = interpret_empty_at(name, namelen, at - name, buf);
1481 if (len > 0)
1482 return reinterpret(name, namelen, len, buf,
1483 allowed);
1486 len = interpret_branch_mark(name, namelen, at - name, buf,
1487 upstream_mark, branch_get_upstream,
1488 allowed);
1489 if (len > 0)
1490 return len;
1492 len = interpret_branch_mark(name, namelen, at - name, buf,
1493 push_mark, branch_get_push,
1494 allowed);
1495 if (len > 0)
1496 return len;
1499 return -1;
1502 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1504 int len = strlen(name);
1505 int used = interpret_branch_name(name, len, sb, allowed);
1507 if (used < 0)
1508 used = 0;
1509 strbuf_add(sb, name + used, len - used);
1512 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1514 if (startup_info->have_repository)
1515 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1516 else
1517 strbuf_addstr(sb, name);
1520 * This splice must be done even if we end up rejecting the
1521 * name; builtin/branch.c::copy_or_rename_branch() still wants
1522 * to see what the name expanded to so that "branch -m" can be
1523 * used as a tool to correct earlier mistakes.
1525 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1527 if (*name == '-' ||
1528 !strcmp(sb->buf, "refs/heads/HEAD"))
1529 return -1;
1531 return check_refname_format(sb->buf, 0);
1535 * This is like "get_oid_basic()", except it allows "object ID expressions",
1536 * notably "xyz^" for "parent of xyz"
1538 int get_oid(const char *name, struct object_id *oid)
1540 struct object_context unused;
1541 return get_oid_with_context(name, 0, oid, &unused);
1546 * Many callers know that the user meant to name a commit-ish by
1547 * syntactical positions where the object name appears. Calling this
1548 * function allows the machinery to disambiguate shorter-than-unique
1549 * abbreviated object names between commit-ish and others.
1551 * Note that this does NOT error out when the named object is not a
1552 * commit-ish. It is merely to give a hint to the disambiguation
1553 * machinery.
1555 int get_oid_committish(const char *name, struct object_id *oid)
1557 struct object_context unused;
1558 return get_oid_with_context(name, GET_OID_COMMITTISH,
1559 oid, &unused);
1562 int get_oid_treeish(const char *name, struct object_id *oid)
1564 struct object_context unused;
1565 return get_oid_with_context(name, GET_OID_TREEISH,
1566 oid, &unused);
1569 int get_oid_commit(const char *name, struct object_id *oid)
1571 struct object_context unused;
1572 return get_oid_with_context(name, GET_OID_COMMIT,
1573 oid, &unused);
1576 int get_oid_tree(const char *name, struct object_id *oid)
1578 struct object_context unused;
1579 return get_oid_with_context(name, GET_OID_TREE,
1580 oid, &unused);
1583 int get_oid_blob(const char *name, struct object_id *oid)
1585 struct object_context unused;
1586 return get_oid_with_context(name, GET_OID_BLOB,
1587 oid, &unused);
1590 /* Must be called only when object_name:filename doesn't exist. */
1591 static void diagnose_invalid_oid_path(const char *prefix,
1592 const char *filename,
1593 const struct object_id *tree_oid,
1594 const char *object_name,
1595 int object_name_len)
1597 struct object_id oid;
1598 unsigned mode;
1600 if (!prefix)
1601 prefix = "";
1603 if (file_exists(filename))
1604 die("Path '%s' exists on disk, but not in '%.*s'.",
1605 filename, object_name_len, object_name);
1606 if (is_missing_file_error(errno)) {
1607 char *fullname = xstrfmt("%s%s", prefix, filename);
1609 if (!get_tree_entry(tree_oid, fullname, &oid, &mode)) {
1610 die("Path '%s' exists, but not '%s'.\n"
1611 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1612 fullname,
1613 filename,
1614 object_name_len, object_name,
1615 fullname,
1616 object_name_len, object_name,
1617 filename);
1619 die("Path '%s' does not exist in '%.*s'",
1620 filename, object_name_len, object_name);
1624 /* Must be called only when :stage:filename doesn't exist. */
1625 static void diagnose_invalid_index_path(int stage,
1626 const char *prefix,
1627 const char *filename)
1629 const struct cache_entry *ce;
1630 int pos;
1631 unsigned namelen = strlen(filename);
1632 struct strbuf fullname = STRBUF_INIT;
1634 if (!prefix)
1635 prefix = "";
1637 /* Wrong stage number? */
1638 pos = cache_name_pos(filename, namelen);
1639 if (pos < 0)
1640 pos = -pos - 1;
1641 if (pos < active_nr) {
1642 ce = active_cache[pos];
1643 if (ce_namelen(ce) == namelen &&
1644 !memcmp(ce->name, filename, namelen))
1645 die("Path '%s' is in the index, but not at stage %d.\n"
1646 "Did you mean ':%d:%s'?",
1647 filename, stage,
1648 ce_stage(ce), filename);
1651 /* Confusion between relative and absolute filenames? */
1652 strbuf_addstr(&fullname, prefix);
1653 strbuf_addstr(&fullname, filename);
1654 pos = cache_name_pos(fullname.buf, fullname.len);
1655 if (pos < 0)
1656 pos = -pos - 1;
1657 if (pos < active_nr) {
1658 ce = active_cache[pos];
1659 if (ce_namelen(ce) == fullname.len &&
1660 !memcmp(ce->name, fullname.buf, fullname.len))
1661 die("Path '%s' is in the index, but not '%s'.\n"
1662 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1663 fullname.buf, filename,
1664 ce_stage(ce), fullname.buf,
1665 ce_stage(ce), filename);
1668 if (file_exists(filename))
1669 die("Path '%s' exists on disk, but not in the index.", filename);
1670 if (is_missing_file_error(errno))
1671 die("Path '%s' does not exist (neither on disk nor in the index).",
1672 filename);
1674 strbuf_release(&fullname);
1678 static char *resolve_relative_path(const char *rel)
1680 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1681 return NULL;
1683 if (!is_inside_work_tree())
1684 die("relative path syntax can't be used outside working tree.");
1686 /* die() inside prefix_path() if resolved path is outside worktree */
1687 return prefix_path(startup_info->prefix,
1688 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1689 rel);
1692 static int get_oid_with_context_1(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 (!active_cache)
1752 read_cache();
1753 pos = cache_name_pos(cp, namelen);
1754 if (pos < 0)
1755 pos = -pos - 1;
1756 while (pos < active_nr) {
1757 ce = active_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(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(name, GET_OID_ONLY_TO_DIE, prefix, &oid, &oc);
1838 int get_oid_with_context(const char *str, unsigned flags, struct object_id *oid, struct object_context *oc)
1840 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
1841 BUG("incompatible flags for get_sha1_with_context");
1842 return get_oid_with_context_1(str, flags, NULL, oid, oc);