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
14static int get_oid_oneline(const char *, struct object_id *, struct commit_list *);
15
16typedef int (*disambiguate_hint_fn)(const struct object_id *, void *);
17
18struct disambiguate_state {
19 int len; /* length of prefix in hex chars */
20 char hex_pfx[GIT_MAX_HEXSZ + 1];
21 struct object_id bin_pfx;
22
23 disambiguate_hint_fn fn;
24 void *cb_data;
25 struct object_id candidate;
26 unsigned candidate_exists:1;
27 unsigned candidate_checked:1;
28 unsigned candidate_ok:1;
29 unsigned disambiguate_fn_used:1;
30 unsigned ambiguous:1;
31 unsigned always_call_fn:1;
32};
33
34static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
35{
36 if (ds->always_call_fn) {
37 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
38 return;
39 }
40 if (!ds->candidate_exists) {
41 /* this is the first candidate */
42 oidcpy(&ds->candidate, current);
43 ds->candidate_exists = 1;
44 return;
45 } else if (!oidcmp(&ds->candidate, current)) {
46 /* the same as what we already have seen */
47 return;
48 }
49
50 if (!ds->fn) {
51 /* cannot disambiguate between ds->candidate and current */
52 ds->ambiguous = 1;
53 return;
54 }
55
56 if (!ds->candidate_checked) {
57 ds->candidate_ok = ds->fn(&ds->candidate, ds->cb_data);
58 ds->disambiguate_fn_used = 1;
59 ds->candidate_checked = 1;
60 }
61
62 if (!ds->candidate_ok) {
63 /* discard the candidate; we know it does not satisfy fn */
64 oidcpy(&ds->candidate, current);
65 ds->candidate_checked = 0;
66 return;
67 }
68
69 /* if we reach this point, we know ds->candidate satisfies fn */
70 if (ds->fn(current, ds->cb_data)) {
71 /*
72 * if both current and candidate satisfy fn, we cannot
73 * disambiguate.
74 */
75 ds->candidate_ok = 0;
76 ds->ambiguous = 1;
77 }
78
79 /* otherwise, current can be discarded and candidate is still good */
80}
81
82static int append_loose_object(const struct object_id *oid, const char *path,
83 void *data)
84{
85 oid_array_append(data, oid);
86 return 0;
87}
88
89static int match_sha(unsigned, const unsigned char *, const unsigned char *);
90
91static void find_short_object_filename(struct disambiguate_state *ds)
92{
93 int subdir_nr = ds->bin_pfx.hash[0];
94 struct alternate_object_database *alt;
95 static struct alternate_object_database *fakeent;
96
97 if (!fakeent) {
98 /*
99 * Create a "fake" alternate object database that
100 * points to our own object database, to make it
101 * easier to get a temporary working space in
102 * alt->name/alt->base while iterating over the
103 * object databases including our own.
104 */
105 fakeent = alloc_alt_odb(get_object_directory());
106 }
107 fakeent->next = alt_odb_list;
108
109 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
110 int pos;
111
112 if (!alt->loose_objects_subdir_seen[subdir_nr]) {
113 struct strbuf *buf = alt_scratch_buf(alt);
114 for_each_file_in_obj_subdir(subdir_nr, buf,
115 append_loose_object,
116 NULL, NULL,
117 &alt->loose_objects_cache);
118 alt->loose_objects_subdir_seen[subdir_nr] = 1;
119 }
120
121 pos = oid_array_lookup(&alt->loose_objects_cache, &ds->bin_pfx);
122 if (pos < 0)
123 pos = -1 - pos;
124 while (!ds->ambiguous && pos < alt->loose_objects_cache.nr) {
125 const struct object_id *oid;
126 oid = alt->loose_objects_cache.oid + pos;
127 if (!match_sha(ds->len, ds->bin_pfx.hash, oid->hash))
128 break;
129 update_candidates(ds, oid);
130 pos++;
131 }
132 }
133}
134
135static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
136{
137 do {
138 if (*a != *b)
139 return 0;
140 a++;
141 b++;
142 len -= 2;
143 } while (len > 1);
144 if (len)
145 if ((*a ^ *b) & 0xf0)
146 return 0;
147 return 1;
148}
149
150static void unique_in_pack(struct packed_git *p,
151 struct disambiguate_state *ds)
152{
153 uint32_t num, last, i, first = 0;
154 const struct object_id *current = NULL;
155
156 open_pack_index(p);
157 num = p->num_objects;
158 last = num;
159 while (first < last) {
160 uint32_t mid = (first + last) / 2;
161 const unsigned char *current;
162 int cmp;
163
164 current = nth_packed_object_sha1(p, mid);
165 cmp = hashcmp(ds->bin_pfx.hash, current);
166 if (!cmp) {
167 first = mid;
168 break;
169 }
170 if (cmp > 0) {
171 first = mid+1;
172 continue;
173 }
174 last = mid;
175 }
176
177 /*
178 * At this point, "first" is the location of the lowest object
179 * with an object name that could match "bin_pfx". See if we have
180 * 0, 1 or more objects that actually match(es).
181 */
182 for (i = first; i < num && !ds->ambiguous; i++) {
183 struct object_id oid;
184 current = nth_packed_object_oid(&oid, p, i);
185 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
186 break;
187 update_candidates(ds, current);
188 }
189}
190
191static void find_short_packed_object(struct disambiguate_state *ds)
192{
193 struct packed_git *p;
194
195 prepare_packed_git();
196 for (p = packed_git; p && !ds->ambiguous; p = p->next)
197 unique_in_pack(p, ds);
198}
199
200#define SHORT_NAME_NOT_FOUND (-1)
201#define SHORT_NAME_AMBIGUOUS (-2)
202
203static int finish_object_disambiguation(struct disambiguate_state *ds,
204 struct object_id *oid)
205{
206 if (ds->ambiguous)
207 return SHORT_NAME_AMBIGUOUS;
208
209 if (!ds->candidate_exists)
210 return SHORT_NAME_NOT_FOUND;
211
212 if (!ds->candidate_checked)
213 /*
214 * If this is the only candidate, there is no point
215 * calling the disambiguation hint callback.
216 *
217 * On the other hand, if the current candidate
218 * replaced an earlier candidate that did _not_ pass
219 * the disambiguation hint callback, then we do have
220 * more than one objects that match the short name
221 * given, so we should make sure this one matches;
222 * otherwise, if we discovered this one and the one
223 * that we previously discarded in the reverse order,
224 * we would end up showing different results in the
225 * same repository!
226 */
227 ds->candidate_ok = (!ds->disambiguate_fn_used ||
228 ds->fn(&ds->candidate, ds->cb_data));
229
230 if (!ds->candidate_ok)
231 return SHORT_NAME_AMBIGUOUS;
232
233 oidcpy(oid, &ds->candidate);
234 return 0;
235}
236
237static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
238{
239 int kind = sha1_object_info(oid->hash, NULL);
240 return kind == OBJ_COMMIT;
241}
242
243static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
244{
245 struct object *obj;
246 int kind;
247
248 kind = sha1_object_info(oid->hash, NULL);
249 if (kind == OBJ_COMMIT)
250 return 1;
251 if (kind != OBJ_TAG)
252 return 0;
253
254 /* We need to do this the hard way... */
255 obj = deref_tag(parse_object(oid), NULL, 0);
256 if (obj && obj->type == OBJ_COMMIT)
257 return 1;
258 return 0;
259}
260
261static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
262{
263 int kind = sha1_object_info(oid->hash, NULL);
264 return kind == OBJ_TREE;
265}
266
267static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
268{
269 struct object *obj;
270 int kind;
271
272 kind = sha1_object_info(oid->hash, NULL);
273 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
274 return 1;
275 if (kind != OBJ_TAG)
276 return 0;
277
278 /* We need to do this the hard way... */
279 obj = deref_tag(parse_object(oid), NULL, 0);
280 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
281 return 1;
282 return 0;
283}
284
285static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
286{
287 int kind = sha1_object_info(oid->hash, NULL);
288 return kind == OBJ_BLOB;
289}
290
291static disambiguate_hint_fn default_disambiguate_hint;
292
293int set_disambiguate_hint_config(const char *var, const char *value)
294{
295 static const struct {
296 const char *name;
297 disambiguate_hint_fn fn;
298 } hints[] = {
299 { "none", NULL },
300 { "commit", disambiguate_commit_only },
301 { "committish", disambiguate_committish_only },
302 { "tree", disambiguate_tree_only },
303 { "treeish", disambiguate_treeish_only },
304 { "blob", disambiguate_blob_only }
305 };
306 int i;
307
308 if (!value)
309 return config_error_nonbool(var);
310
311 for (i = 0; i < ARRAY_SIZE(hints); i++) {
312 if (!strcasecmp(value, hints[i].name)) {
313 default_disambiguate_hint = hints[i].fn;
314 return 0;
315 }
316 }
317
318 return error("unknown hint type for '%s': %s", var, value);
319}
320
321static int init_object_disambiguation(const char *name, int len,
322 struct disambiguate_state *ds)
323{
324 int i;
325
326 if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
327 return -1;
328
329 memset(ds, 0, sizeof(*ds));
330
331 for (i = 0; i < len ;i++) {
332 unsigned char c = name[i];
333 unsigned char val;
334 if (c >= '0' && c <= '9')
335 val = c - '0';
336 else if (c >= 'a' && c <= 'f')
337 val = c - 'a' + 10;
338 else if (c >= 'A' && c <='F') {
339 val = c - 'A' + 10;
340 c -= 'A' - 'a';
341 }
342 else
343 return -1;
344 ds->hex_pfx[i] = c;
345 if (!(i & 1))
346 val <<= 4;
347 ds->bin_pfx.hash[i >> 1] |= val;
348 }
349
350 ds->len = len;
351 ds->hex_pfx[len] = '\0';
352 prepare_alt_odb();
353 return 0;
354}
355
356static int show_ambiguous_object(const struct object_id *oid, void *data)
357{
358 const struct disambiguate_state *ds = data;
359 struct strbuf desc = STRBUF_INIT;
360 int type;
361
362
363 if (ds->fn && !ds->fn(oid, ds->cb_data))
364 return 0;
365
366 type = sha1_object_info(oid->hash, NULL);
367 if (type == OBJ_COMMIT) {
368 struct commit *commit = lookup_commit(oid);
369 if (commit) {
370 struct pretty_print_context pp = {0};
371 pp.date_mode.type = DATE_SHORT;
372 format_commit_message(commit, " %ad - %s", &desc, &pp);
373 }
374 } else if (type == OBJ_TAG) {
375 struct tag *tag = lookup_tag(oid);
376 if (!parse_tag(tag) && tag->tag)
377 strbuf_addf(&desc, " %s", tag->tag);
378 }
379
380 advise(" %s %s%s",
381 find_unique_abbrev(oid->hash, DEFAULT_ABBREV),
382 typename(type) ? typename(type) : "unknown type",
383 desc.buf);
384
385 strbuf_release(&desc);
386 return 0;
387}
388
389static int get_short_oid(const char *name, int len, struct object_id *oid,
390 unsigned flags)
391{
392 int status;
393 struct disambiguate_state ds;
394 int quietly = !!(flags & GET_OID_QUIETLY);
395
396 if (init_object_disambiguation(name, len, &ds) < 0)
397 return -1;
398
399 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
400 die("BUG: multiple get_short_oid disambiguator flags");
401
402 if (flags & GET_OID_COMMIT)
403 ds.fn = disambiguate_commit_only;
404 else if (flags & GET_OID_COMMITTISH)
405 ds.fn = disambiguate_committish_only;
406 else if (flags & GET_OID_TREE)
407 ds.fn = disambiguate_tree_only;
408 else if (flags & GET_OID_TREEISH)
409 ds.fn = disambiguate_treeish_only;
410 else if (flags & GET_OID_BLOB)
411 ds.fn = disambiguate_blob_only;
412 else
413 ds.fn = default_disambiguate_hint;
414
415 find_short_object_filename(&ds);
416 find_short_packed_object(&ds);
417 status = finish_object_disambiguation(&ds, oid);
418
419 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
420 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
421
422 /*
423 * We may still have ambiguity if we simply saw a series of
424 * candidates that did not satisfy our hint function. In
425 * that case, we still want to show them, so disable the hint
426 * function entirely.
427 */
428 if (!ds.ambiguous)
429 ds.fn = NULL;
430
431 advise(_("The candidates are:"));
432 for_each_abbrev(ds.hex_pfx, show_ambiguous_object, &ds);
433 }
434
435 return status;
436}
437
438static int collect_ambiguous(const struct object_id *oid, void *data)
439{
440 oid_array_append(data, oid);
441 return 0;
442}
443
444int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
445{
446 struct oid_array collect = OID_ARRAY_INIT;
447 struct disambiguate_state ds;
448 int ret;
449
450 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
451 return -1;
452
453 ds.always_call_fn = 1;
454 ds.fn = collect_ambiguous;
455 ds.cb_data = &collect;
456 find_short_object_filename(&ds);
457 find_short_packed_object(&ds);
458
459 ret = oid_array_for_each_unique(&collect, fn, cb_data);
460 oid_array_clear(&collect);
461 return ret;
462}
463
464/*
465 * Return the slot of the most-significant bit set in "val". There are various
466 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
467 * probably not a big deal here.
468 */
469static unsigned msb(unsigned long val)
470{
471 unsigned r = 0;
472 while (val >>= 1)
473 r++;
474 return r;
475}
476
477struct min_abbrev_data {
478 unsigned int init_len;
479 unsigned int cur_len;
480 char *hex;
481};
482
483static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
484{
485 struct min_abbrev_data *mad = cb_data;
486
487 char *hex = oid_to_hex(oid);
488 unsigned int i = mad->init_len;
489 while (mad->hex[i] && mad->hex[i] == hex[i])
490 i++;
491
492 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
493 mad->cur_len = i + 1;
494
495 return 0;
496}
497
498int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
499{
500 struct disambiguate_state ds;
501 struct min_abbrev_data mad;
502 struct object_id oid_ret;
503 if (len < 0) {
504 unsigned long count = approximate_object_count();
505 /*
506 * Add one because the MSB only tells us the highest bit set,
507 * not including the value of all the _other_ bits (so "15"
508 * is only one off of 2^4, but the MSB is the 3rd bit.
509 */
510 len = msb(count) + 1;
511 /*
512 * We now know we have on the order of 2^len objects, which
513 * expects a collision at 2^(len/2). But we also care about hex
514 * chars, not bits, and there are 4 bits per hex. So all
515 * together we need to divide by 2 and round up.
516 */
517 len = DIV_ROUND_UP(len, 2);
518 /*
519 * For very small repos, we stick with our regular fallback.
520 */
521 if (len < FALLBACK_DEFAULT_ABBREV)
522 len = FALLBACK_DEFAULT_ABBREV;
523 }
524
525 sha1_to_hex_r(hex, sha1);
526 if (len == GIT_SHA1_HEXSZ || !len)
527 return GIT_SHA1_HEXSZ;
528
529 if (init_object_disambiguation(hex, len, &ds) < 0)
530 return -1;
531
532 mad.init_len = len;
533 mad.cur_len = len;
534 mad.hex = hex;
535
536 ds.fn = extend_abbrev_len;
537 ds.always_call_fn = 1;
538 ds.cb_data = (void *)&mad;
539
540 find_short_object_filename(&ds);
541 find_short_packed_object(&ds);
542 (void)finish_object_disambiguation(&ds, &oid_ret);
543
544 hex[mad.cur_len] = 0;
545 return mad.cur_len;
546}
547
548const char *find_unique_abbrev(const unsigned char *sha1, int len)
549{
550 static int bufno;
551 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
552 char *hex = hexbuffer[bufno];
553 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
554 find_unique_abbrev_r(hex, sha1, len);
555 return hex;
556}
557
558static int ambiguous_path(const char *path, int len)
559{
560 int slash = 1;
561 int cnt;
562
563 for (cnt = 0; cnt < len; cnt++) {
564 switch (*path++) {
565 case '\0':
566 break;
567 case '/':
568 if (slash)
569 break;
570 slash = 1;
571 continue;
572 case '.':
573 continue;
574 default:
575 slash = 0;
576 continue;
577 }
578 break;
579 }
580 return slash;
581}
582
583static inline int at_mark(const char *string, int len,
584 const char **suffix, int nr)
585{
586 int i;
587
588 for (i = 0; i < nr; i++) {
589 int suffix_len = strlen(suffix[i]);
590 if (suffix_len <= len
591 && !strncasecmp(string, suffix[i], suffix_len))
592 return suffix_len;
593 }
594 return 0;
595}
596
597static inline int upstream_mark(const char *string, int len)
598{
599 const char *suffix[] = { "@{upstream}", "@{u}" };
600 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
601}
602
603static inline int push_mark(const char *string, int len)
604{
605 const char *suffix[] = { "@{push}" };
606 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
607}
608
609static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags);
610static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
611
612static int get_oid_basic(const char *str, int len, struct object_id *oid,
613 unsigned int flags)
614{
615 static const char *warn_msg = "refname '%.*s' is ambiguous.";
616 static const char *object_name_msg = N_(
617 "Git normally never creates a ref that ends with 40 hex characters\n"
618 "because it will be ignored when you just specify 40-hex. These refs\n"
619 "may be created by mistake. For example,\n"
620 "\n"
621 " git checkout -b $br $(git rev-parse ...)\n"
622 "\n"
623 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
624 "examine these refs and maybe delete them. Turn this message off by\n"
625 "running \"git config advice.objectNameWarning false\"");
626 struct object_id tmp_oid;
627 char *real_ref = NULL;
628 int refs_found = 0;
629 int at, reflog_len, nth_prior = 0;
630
631 if (len == GIT_SHA1_HEXSZ && !get_oid_hex(str, oid)) {
632 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
633 refs_found = dwim_ref(str, len, tmp_oid.hash, &real_ref);
634 if (refs_found > 0) {
635 warning(warn_msg, len, str);
636 if (advice_object_name_warning)
637 fprintf(stderr, "%s\n", _(object_name_msg));
638 }
639 free(real_ref);
640 }
641 return 0;
642 }
643
644 /* basic@{time or number or -number} format to query ref-log */
645 reflog_len = at = 0;
646 if (len && str[len-1] == '}') {
647 for (at = len-4; at >= 0; at--) {
648 if (str[at] == '@' && str[at+1] == '{') {
649 if (str[at+2] == '-') {
650 if (at != 0)
651 /* @{-N} not at start */
652 return -1;
653 nth_prior = 1;
654 continue;
655 }
656 if (!upstream_mark(str + at, len - at) &&
657 !push_mark(str + at, len - at)) {
658 reflog_len = (len-1) - (at+2);
659 len = at;
660 }
661 break;
662 }
663 }
664 }
665
666 /* Accept only unambiguous ref paths. */
667 if (len && ambiguous_path(str, len))
668 return -1;
669
670 if (nth_prior) {
671 struct strbuf buf = STRBUF_INIT;
672 int detached;
673
674 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
675 detached = (buf.len == GIT_SHA1_HEXSZ && !get_oid_hex(buf.buf, oid));
676 strbuf_release(&buf);
677 if (detached)
678 return 0;
679 }
680 }
681
682 if (!len && reflog_len)
683 /* allow "@{...}" to mean the current branch reflog */
684 refs_found = dwim_ref("HEAD", 4, oid->hash, &real_ref);
685 else if (reflog_len)
686 refs_found = dwim_log(str, len, oid->hash, &real_ref);
687 else
688 refs_found = dwim_ref(str, len, oid->hash, &real_ref);
689
690 if (!refs_found)
691 return -1;
692
693 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
694 (refs_found > 1 ||
695 !get_short_oid(str, len, &tmp_oid, GET_OID_QUIETLY)))
696 warning(warn_msg, len, str);
697
698 if (reflog_len) {
699 int nth, i;
700 timestamp_t at_time;
701 timestamp_t co_time;
702 int co_tz, co_cnt;
703
704 /* Is it asking for N-th entry, or approxidate? */
705 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
706 char ch = str[at+2+i];
707 if ('0' <= ch && ch <= '9')
708 nth = nth * 10 + ch - '0';
709 else
710 nth = -1;
711 }
712 if (100000000 <= nth) {
713 at_time = nth;
714 nth = -1;
715 } else if (0 <= nth)
716 at_time = 0;
717 else {
718 int errors = 0;
719 char *tmp = xstrndup(str + at + 2, reflog_len);
720 at_time = approxidate_careful(tmp, &errors);
721 free(tmp);
722 if (errors) {
723 free(real_ref);
724 return -1;
725 }
726 }
727 if (read_ref_at(real_ref, flags, at_time, nth, oid->hash, NULL,
728 &co_time, &co_tz, &co_cnt)) {
729 if (!len) {
730 if (starts_with(real_ref, "refs/heads/")) {
731 str = real_ref + 11;
732 len = strlen(real_ref + 11);
733 } else {
734 /* detached HEAD */
735 str = "HEAD";
736 len = 4;
737 }
738 }
739 if (at_time) {
740 if (!(flags & GET_OID_QUIETLY)) {
741 warning("Log for '%.*s' only goes "
742 "back to %s.", len, str,
743 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
744 }
745 } else {
746 if (flags & GET_OID_QUIETLY) {
747 exit(128);
748 }
749 die("Log for '%.*s' only has %d entries.",
750 len, str, co_cnt);
751 }
752 }
753 }
754
755 free(real_ref);
756 return 0;
757}
758
759static int get_parent(const char *name, int len,
760 struct object_id *result, int idx)
761{
762 struct object_id oid;
763 int ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
764 struct commit *commit;
765 struct commit_list *p;
766
767 if (ret)
768 return ret;
769 commit = lookup_commit_reference(&oid);
770 if (parse_commit(commit))
771 return -1;
772 if (!idx) {
773 oidcpy(result, &commit->object.oid);
774 return 0;
775 }
776 p = commit->parents;
777 while (p) {
778 if (!--idx) {
779 oidcpy(result, &p->item->object.oid);
780 return 0;
781 }
782 p = p->next;
783 }
784 return -1;
785}
786
787static int get_nth_ancestor(const char *name, int len,
788 struct object_id *result, int generation)
789{
790 struct object_id oid;
791 struct commit *commit;
792 int ret;
793
794 ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
795 if (ret)
796 return ret;
797 commit = lookup_commit_reference(&oid);
798 if (!commit)
799 return -1;
800
801 while (generation--) {
802 if (parse_commit(commit) || !commit->parents)
803 return -1;
804 commit = commit->parents->item;
805 }
806 oidcpy(result, &commit->object.oid);
807 return 0;
808}
809
810struct object *peel_to_type(const char *name, int namelen,
811 struct object *o, enum object_type expected_type)
812{
813 if (name && !namelen)
814 namelen = strlen(name);
815 while (1) {
816 if (!o || (!o->parsed && !parse_object(&o->oid)))
817 return NULL;
818 if (expected_type == OBJ_ANY || o->type == expected_type)
819 return o;
820 if (o->type == OBJ_TAG)
821 o = ((struct tag*) o)->tagged;
822 else if (o->type == OBJ_COMMIT)
823 o = &(((struct commit *) o)->tree->object);
824 else {
825 if (name)
826 error("%.*s: expected %s type, but the object "
827 "dereferences to %s type",
828 namelen, name, typename(expected_type),
829 typename(o->type));
830 return NULL;
831 }
832 }
833}
834
835static int peel_onion(const char *name, int len, struct object_id *oid,
836 unsigned lookup_flags)
837{
838 struct object_id outer;
839 const char *sp;
840 unsigned int expected_type = 0;
841 struct object *o;
842
843 /*
844 * "ref^{type}" dereferences ref repeatedly until you cannot
845 * dereference anymore, or you get an object of given type,
846 * whichever comes first. "ref^{}" means just dereference
847 * tags until you get a non-tag. "ref^0" is a shorthand for
848 * "ref^{commit}". "commit^{tree}" could be used to find the
849 * top-level tree of the given commit.
850 */
851 if (len < 4 || name[len-1] != '}')
852 return -1;
853
854 for (sp = name + len - 1; name <= sp; sp--) {
855 int ch = *sp;
856 if (ch == '{' && name < sp && sp[-1] == '^')
857 break;
858 }
859 if (sp <= name)
860 return -1;
861
862 sp++; /* beginning of type name, or closing brace for empty */
863 if (starts_with(sp, "commit}"))
864 expected_type = OBJ_COMMIT;
865 else if (starts_with(sp, "tag}"))
866 expected_type = OBJ_TAG;
867 else if (starts_with(sp, "tree}"))
868 expected_type = OBJ_TREE;
869 else if (starts_with(sp, "blob}"))
870 expected_type = OBJ_BLOB;
871 else if (starts_with(sp, "object}"))
872 expected_type = OBJ_ANY;
873 else if (sp[0] == '}')
874 expected_type = OBJ_NONE;
875 else if (sp[0] == '/')
876 expected_type = OBJ_COMMIT;
877 else
878 return -1;
879
880 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
881 if (expected_type == OBJ_COMMIT)
882 lookup_flags |= GET_OID_COMMITTISH;
883 else if (expected_type == OBJ_TREE)
884 lookup_flags |= GET_OID_TREEISH;
885
886 if (get_oid_1(name, sp - name - 2, &outer, lookup_flags))
887 return -1;
888
889 o = parse_object(&outer);
890 if (!o)
891 return -1;
892 if (!expected_type) {
893 o = deref_tag(o, name, sp - name - 2);
894 if (!o || (!o->parsed && !parse_object(&o->oid)))
895 return -1;
896 oidcpy(oid, &o->oid);
897 return 0;
898 }
899
900 /*
901 * At this point, the syntax look correct, so
902 * if we do not get the needed object, we should
903 * barf.
904 */
905 o = peel_to_type(name, len, o, expected_type);
906 if (!o)
907 return -1;
908
909 oidcpy(oid, &o->oid);
910 if (sp[0] == '/') {
911 /* "$commit^{/foo}" */
912 char *prefix;
913 int ret;
914 struct commit_list *list = NULL;
915
916 /*
917 * $commit^{/}. Some regex implementation may reject.
918 * We don't need regex anyway. '' pattern always matches.
919 */
920 if (sp[1] == '}')
921 return 0;
922
923 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
924 commit_list_insert((struct commit *)o, &list);
925 ret = get_oid_oneline(prefix, oid, list);
926 free(prefix);
927 return ret;
928 }
929 return 0;
930}
931
932static int get_describe_name(const char *name, int len, struct object_id *oid)
933{
934 const char *cp;
935 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
936
937 for (cp = name + len - 1; name + 2 <= cp; cp--) {
938 char ch = *cp;
939 if (!isxdigit(ch)) {
940 /* We must be looking at g in "SOMETHING-g"
941 * for it to be describe output.
942 */
943 if (ch == 'g' && cp[-1] == '-') {
944 cp++;
945 len -= cp - name;
946 return get_short_oid(cp, len, oid, flags);
947 }
948 }
949 }
950 return -1;
951}
952
953static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags)
954{
955 int ret, has_suffix;
956 const char *cp;
957
958 /*
959 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
960 */
961 has_suffix = 0;
962 for (cp = name + len - 1; name <= cp; cp--) {
963 int ch = *cp;
964 if ('0' <= ch && ch <= '9')
965 continue;
966 if (ch == '~' || ch == '^')
967 has_suffix = ch;
968 break;
969 }
970
971 if (has_suffix) {
972 int num = 0;
973 int len1 = cp - name;
974 cp++;
975 while (cp < name + len)
976 num = num * 10 + *cp++ - '0';
977 if (!num && len1 == len - 1)
978 num = 1;
979 if (has_suffix == '^')
980 return get_parent(name, len1, oid, num);
981 /* else if (has_suffix == '~') -- goes without saying */
982 return get_nth_ancestor(name, len1, oid, num);
983 }
984
985 ret = peel_onion(name, len, oid, lookup_flags);
986 if (!ret)
987 return 0;
988
989 ret = get_oid_basic(name, len, oid, lookup_flags);
990 if (!ret)
991 return 0;
992
993 /* It could be describe output that is "SOMETHING-gXXXX" */
994 ret = get_describe_name(name, len, oid);
995 if (!ret)
996 return 0;
997
998 return get_short_oid(name, len, oid, lookup_flags);
999}
1000
1001/*
1002 * This interprets names like ':/Initial revision of "git"' by searching
1003 * through history and returning the first commit whose message starts
1004 * the given regular expression.
1005 *
1006 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1007 *
1008 * For a literal '!' character at the beginning of a pattern, you have to repeat
1009 * that, like: ':/!!foo'
1010 *
1011 * For future extension, all other sequences beginning with ':/!' are reserved.
1012 */
1013
1014/* Remember to update object flag allocation in object.h */
1015#define ONELINE_SEEN (1u<<20)
1016
1017static int handle_one_ref(const char *path, const struct object_id *oid,
1018 int flag, void *cb_data)
1019{
1020 struct commit_list **list = cb_data;
1021 struct object *object = parse_object(oid);
1022 if (!object)
1023 return 0;
1024 if (object->type == OBJ_TAG) {
1025 object = deref_tag(object, path, strlen(path));
1026 if (!object)
1027 return 0;
1028 }
1029 if (object->type != OBJ_COMMIT)
1030 return 0;
1031 commit_list_insert((struct commit *)object, list);
1032 return 0;
1033}
1034
1035static int get_oid_oneline(const char *prefix, struct object_id *oid,
1036 struct commit_list *list)
1037{
1038 struct commit_list *backup = NULL, *l;
1039 int found = 0;
1040 int negative = 0;
1041 regex_t regex;
1042
1043 if (prefix[0] == '!') {
1044 prefix++;
1045
1046 if (prefix[0] == '-') {
1047 prefix++;
1048 negative = 1;
1049 } else if (prefix[0] != '!') {
1050 return -1;
1051 }
1052 }
1053
1054 if (regcomp(®ex, prefix, REG_EXTENDED))
1055 return -1;
1056
1057 for (l = list; l; l = l->next) {
1058 l->item->object.flags |= ONELINE_SEEN;
1059 commit_list_insert(l->item, &backup);
1060 }
1061 while (list) {
1062 const char *p, *buf;
1063 struct commit *commit;
1064 int matches;
1065
1066 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1067 if (!parse_object(&commit->object.oid))
1068 continue;
1069 buf = get_commit_buffer(commit, NULL);
1070 p = strstr(buf, "\n\n");
1071 matches = negative ^ (p && !regexec(®ex, p + 2, 0, NULL, 0));
1072 unuse_commit_buffer(commit, buf);
1073
1074 if (matches) {
1075 oidcpy(oid, &commit->object.oid);
1076 found = 1;
1077 break;
1078 }
1079 }
1080 regfree(®ex);
1081 free_commit_list(list);
1082 for (l = backup; l; l = l->next)
1083 clear_commit_marks(l->item, ONELINE_SEEN);
1084 free_commit_list(backup);
1085 return found ? 0 : -1;
1086}
1087
1088struct grab_nth_branch_switch_cbdata {
1089 int remaining;
1090 struct strbuf buf;
1091};
1092
1093static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
1094 const char *email, timestamp_t timestamp, int tz,
1095 const char *message, void *cb_data)
1096{
1097 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1098 const char *match = NULL, *target = NULL;
1099 size_t len;
1100
1101 if (skip_prefix(message, "checkout: moving from ", &match))
1102 target = strstr(match, " to ");
1103
1104 if (!match || !target)
1105 return 0;
1106 if (--(cb->remaining) == 0) {
1107 len = target - match;
1108 strbuf_reset(&cb->buf);
1109 strbuf_add(&cb->buf, match, len);
1110 return 1; /* we are done */
1111 }
1112 return 0;
1113}
1114
1115/*
1116 * Parse @{-N} syntax, return the number of characters parsed
1117 * if successful; otherwise signal an error with negative value.
1118 */
1119static int interpret_nth_prior_checkout(const char *name, int namelen,
1120 struct strbuf *buf)
1121{
1122 long nth;
1123 int retval;
1124 struct grab_nth_branch_switch_cbdata cb;
1125 const char *brace;
1126 char *num_end;
1127
1128 if (namelen < 4)
1129 return -1;
1130 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1131 return -1;
1132 brace = memchr(name, '}', namelen);
1133 if (!brace)
1134 return -1;
1135 nth = strtol(name + 3, &num_end, 10);
1136 if (num_end != brace)
1137 return -1;
1138 if (nth <= 0)
1139 return -1;
1140 cb.remaining = nth;
1141 strbuf_init(&cb.buf, 20);
1142
1143 retval = 0;
1144 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1145 strbuf_reset(buf);
1146 strbuf_addbuf(buf, &cb.buf);
1147 retval = brace - name + 1;
1148 }
1149
1150 strbuf_release(&cb.buf);
1151 return retval;
1152}
1153
1154int get_oid_mb(const char *name, struct object_id *oid)
1155{
1156 struct commit *one, *two;
1157 struct commit_list *mbs;
1158 struct object_id oid_tmp;
1159 const char *dots;
1160 int st;
1161
1162 dots = strstr(name, "...");
1163 if (!dots)
1164 return get_oid(name, oid);
1165 if (dots == name)
1166 st = get_oid("HEAD", &oid_tmp);
1167 else {
1168 struct strbuf sb;
1169 strbuf_init(&sb, dots - name);
1170 strbuf_add(&sb, name, dots - name);
1171 st = get_oid_committish(sb.buf, &oid_tmp);
1172 strbuf_release(&sb);
1173 }
1174 if (st)
1175 return st;
1176 one = lookup_commit_reference_gently(&oid_tmp, 0);
1177 if (!one)
1178 return -1;
1179
1180 if (get_oid_committish(dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1181 return -1;
1182 two = lookup_commit_reference_gently(&oid_tmp, 0);
1183 if (!two)
1184 return -1;
1185 mbs = get_merge_bases(one, two);
1186 if (!mbs || mbs->next)
1187 st = -1;
1188 else {
1189 st = 0;
1190 oidcpy(oid, &mbs->item->object.oid);
1191 }
1192 free_commit_list(mbs);
1193 return st;
1194}
1195
1196/* parse @something syntax, when 'something' is not {.*} */
1197static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1198{
1199 const char *next;
1200
1201 if (len || name[1] == '{')
1202 return -1;
1203
1204 /* make sure it's a single @, or @@{.*}, not @foo */
1205 next = memchr(name + len + 1, '@', namelen - len - 1);
1206 if (next && next[1] != '{')
1207 return -1;
1208 if (!next)
1209 next = name + namelen;
1210 if (next != name + 1)
1211 return -1;
1212
1213 strbuf_reset(buf);
1214 strbuf_add(buf, "HEAD", 4);
1215 return 1;
1216}
1217
1218static int reinterpret(const char *name, int namelen, int len,
1219 struct strbuf *buf, unsigned allowed)
1220{
1221 /* we have extra data, which might need further processing */
1222 struct strbuf tmp = STRBUF_INIT;
1223 int used = buf->len;
1224 int ret;
1225
1226 strbuf_add(buf, name + len, namelen - len);
1227 ret = interpret_branch_name(buf->buf, buf->len, &tmp, allowed);
1228 /* that data was not interpreted, remove our cruft */
1229 if (ret < 0) {
1230 strbuf_setlen(buf, used);
1231 return len;
1232 }
1233 strbuf_reset(buf);
1234 strbuf_addbuf(buf, &tmp);
1235 strbuf_release(&tmp);
1236 /* tweak for size of {-N} versus expanded ref name */
1237 return ret - used + len;
1238}
1239
1240static void set_shortened_ref(struct strbuf *buf, const char *ref)
1241{
1242 char *s = shorten_unambiguous_ref(ref, 0);
1243 strbuf_reset(buf);
1244 strbuf_addstr(buf, s);
1245 free(s);
1246}
1247
1248static int branch_interpret_allowed(const char *refname, unsigned allowed)
1249{
1250 if (!allowed)
1251 return 1;
1252
1253 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1254 starts_with(refname, "refs/heads/"))
1255 return 1;
1256 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1257 starts_with(refname, "refs/remotes/"))
1258 return 1;
1259
1260 return 0;
1261}
1262
1263static int interpret_branch_mark(const char *name, int namelen,
1264 int at, struct strbuf *buf,
1265 int (*get_mark)(const char *, int),
1266 const char *(*get_data)(struct branch *,
1267 struct strbuf *),
1268 unsigned allowed)
1269{
1270 int len;
1271 struct branch *branch;
1272 struct strbuf err = STRBUF_INIT;
1273 const char *value;
1274
1275 len = get_mark(name + at, namelen - at);
1276 if (!len)
1277 return -1;
1278
1279 if (memchr(name, ':', at))
1280 return -1;
1281
1282 if (at) {
1283 char *name_str = xmemdupz(name, at);
1284 branch = branch_get(name_str);
1285 free(name_str);
1286 } else
1287 branch = branch_get(NULL);
1288
1289 value = get_data(branch, &err);
1290 if (!value)
1291 die("%s", err.buf);
1292
1293 if (!branch_interpret_allowed(value, allowed))
1294 return -1;
1295
1296 set_shortened_ref(buf, value);
1297 return len + at;
1298}
1299
1300int interpret_branch_name(const char *name, int namelen, struct strbuf *buf,
1301 unsigned allowed)
1302{
1303 char *at;
1304 const char *start;
1305 int len;
1306
1307 if (!namelen)
1308 namelen = strlen(name);
1309
1310 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1311 len = interpret_nth_prior_checkout(name, namelen, buf);
1312 if (!len) {
1313 return len; /* syntax Ok, not enough switches */
1314 } else if (len > 0) {
1315 if (len == namelen)
1316 return len; /* consumed all */
1317 else
1318 return reinterpret(name, namelen, len, buf, allowed);
1319 }
1320 }
1321
1322 for (start = name;
1323 (at = memchr(start, '@', namelen - (start - name)));
1324 start = at + 1) {
1325
1326 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1327 len = interpret_empty_at(name, namelen, at - name, buf);
1328 if (len > 0)
1329 return reinterpret(name, namelen, len, buf,
1330 allowed);
1331 }
1332
1333 len = interpret_branch_mark(name, namelen, at - name, buf,
1334 upstream_mark, branch_get_upstream,
1335 allowed);
1336 if (len > 0)
1337 return len;
1338
1339 len = interpret_branch_mark(name, namelen, at - name, buf,
1340 push_mark, branch_get_push,
1341 allowed);
1342 if (len > 0)
1343 return len;
1344 }
1345
1346 return -1;
1347}
1348
1349void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1350{
1351 int len = strlen(name);
1352 int used = interpret_branch_name(name, len, sb, allowed);
1353
1354 if (used < 0)
1355 used = 0;
1356 strbuf_add(sb, name + used, len - used);
1357}
1358
1359int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1360{
1361 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1362 if (name[0] == '-')
1363 return -1;
1364 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1365 return check_refname_format(sb->buf, 0);
1366}
1367
1368/*
1369 * This is like "get_oid_basic()", except it allows "object ID expressions",
1370 * notably "xyz^" for "parent of xyz"
1371 */
1372int get_oid(const char *name, struct object_id *oid)
1373{
1374 struct object_context unused;
1375 return get_oid_with_context(name, 0, oid, &unused);
1376}
1377
1378
1379/*
1380 * Many callers know that the user meant to name a commit-ish by
1381 * syntactical positions where the object name appears. Calling this
1382 * function allows the machinery to disambiguate shorter-than-unique
1383 * abbreviated object names between commit-ish and others.
1384 *
1385 * Note that this does NOT error out when the named object is not a
1386 * commit-ish. It is merely to give a hint to the disambiguation
1387 * machinery.
1388 */
1389int get_oid_committish(const char *name, struct object_id *oid)
1390{
1391 struct object_context unused;
1392 return get_oid_with_context(name, GET_OID_COMMITTISH,
1393 oid, &unused);
1394}
1395
1396int get_oid_treeish(const char *name, struct object_id *oid)
1397{
1398 struct object_context unused;
1399 return get_oid_with_context(name, GET_OID_TREEISH,
1400 oid, &unused);
1401}
1402
1403int get_oid_commit(const char *name, struct object_id *oid)
1404{
1405 struct object_context unused;
1406 return get_oid_with_context(name, GET_OID_COMMIT,
1407 oid, &unused);
1408}
1409
1410int get_oid_tree(const char *name, struct object_id *oid)
1411{
1412 struct object_context unused;
1413 return get_oid_with_context(name, GET_OID_TREE,
1414 oid, &unused);
1415}
1416
1417int get_oid_blob(const char *name, struct object_id *oid)
1418{
1419 struct object_context unused;
1420 return get_oid_with_context(name, GET_OID_BLOB,
1421 oid, &unused);
1422}
1423
1424/* Must be called only when object_name:filename doesn't exist. */
1425static void diagnose_invalid_oid_path(const char *prefix,
1426 const char *filename,
1427 const struct object_id *tree_oid,
1428 const char *object_name,
1429 int object_name_len)
1430{
1431 struct object_id oid;
1432 unsigned mode;
1433
1434 if (!prefix)
1435 prefix = "";
1436
1437 if (file_exists(filename))
1438 die("Path '%s' exists on disk, but not in '%.*s'.",
1439 filename, object_name_len, object_name);
1440 if (is_missing_file_error(errno)) {
1441 char *fullname = xstrfmt("%s%s", prefix, filename);
1442
1443 if (!get_tree_entry(tree_oid->hash, fullname,
1444 oid.hash, &mode)) {
1445 die("Path '%s' exists, but not '%s'.\n"
1446 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1447 fullname,
1448 filename,
1449 object_name_len, object_name,
1450 fullname,
1451 object_name_len, object_name,
1452 filename);
1453 }
1454 die("Path '%s' does not exist in '%.*s'",
1455 filename, object_name_len, object_name);
1456 }
1457}
1458
1459/* Must be called only when :stage:filename doesn't exist. */
1460static void diagnose_invalid_index_path(int stage,
1461 const char *prefix,
1462 const char *filename)
1463{
1464 const struct cache_entry *ce;
1465 int pos;
1466 unsigned namelen = strlen(filename);
1467 struct strbuf fullname = STRBUF_INIT;
1468
1469 if (!prefix)
1470 prefix = "";
1471
1472 /* Wrong stage number? */
1473 pos = cache_name_pos(filename, namelen);
1474 if (pos < 0)
1475 pos = -pos - 1;
1476 if (pos < active_nr) {
1477 ce = active_cache[pos];
1478 if (ce_namelen(ce) == namelen &&
1479 !memcmp(ce->name, filename, namelen))
1480 die("Path '%s' is in the index, but not at stage %d.\n"
1481 "Did you mean ':%d:%s'?",
1482 filename, stage,
1483 ce_stage(ce), filename);
1484 }
1485
1486 /* Confusion between relative and absolute filenames? */
1487 strbuf_addstr(&fullname, prefix);
1488 strbuf_addstr(&fullname, filename);
1489 pos = cache_name_pos(fullname.buf, fullname.len);
1490 if (pos < 0)
1491 pos = -pos - 1;
1492 if (pos < active_nr) {
1493 ce = active_cache[pos];
1494 if (ce_namelen(ce) == fullname.len &&
1495 !memcmp(ce->name, fullname.buf, fullname.len))
1496 die("Path '%s' is in the index, but not '%s'.\n"
1497 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1498 fullname.buf, filename,
1499 ce_stage(ce), fullname.buf,
1500 ce_stage(ce), filename);
1501 }
1502
1503 if (file_exists(filename))
1504 die("Path '%s' exists on disk, but not in the index.", filename);
1505 if (is_missing_file_error(errno))
1506 die("Path '%s' does not exist (neither on disk nor in the index).",
1507 filename);
1508
1509 strbuf_release(&fullname);
1510}
1511
1512
1513static char *resolve_relative_path(const char *rel)
1514{
1515 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1516 return NULL;
1517
1518 if (!is_inside_work_tree())
1519 die("relative path syntax can't be used outside working tree.");
1520
1521 /* die() inside prefix_path() if resolved path is outside worktree */
1522 return prefix_path(startup_info->prefix,
1523 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1524 rel);
1525}
1526
1527static int get_oid_with_context_1(const char *name,
1528 unsigned flags,
1529 const char *prefix,
1530 struct object_id *oid,
1531 struct object_context *oc)
1532{
1533 int ret, bracket_depth;
1534 int namelen = strlen(name);
1535 const char *cp;
1536 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
1537
1538 if (only_to_die)
1539 flags |= GET_OID_QUIETLY;
1540
1541 memset(oc, 0, sizeof(*oc));
1542 oc->mode = S_IFINVALID;
1543 strbuf_init(&oc->symlink_path, 0);
1544 ret = get_oid_1(name, namelen, oid, flags);
1545 if (!ret)
1546 return ret;
1547 /*
1548 * sha1:path --> object name of path in ent sha1
1549 * :path -> object name of absolute path in index
1550 * :./path -> object name of path relative to cwd in index
1551 * :[0-3]:path -> object name of path in index at stage
1552 * :/foo -> recent commit matching foo
1553 */
1554 if (name[0] == ':') {
1555 int stage = 0;
1556 const struct cache_entry *ce;
1557 char *new_path = NULL;
1558 int pos;
1559 if (!only_to_die && namelen > 2 && name[1] == '/') {
1560 struct commit_list *list = NULL;
1561
1562 for_each_ref(handle_one_ref, &list);
1563 commit_list_sort_by_date(&list);
1564 return get_oid_oneline(name + 2, oid, list);
1565 }
1566 if (namelen < 3 ||
1567 name[2] != ':' ||
1568 name[1] < '0' || '3' < name[1])
1569 cp = name + 1;
1570 else {
1571 stage = name[1] - '0';
1572 cp = name + 3;
1573 }
1574 new_path = resolve_relative_path(cp);
1575 if (!new_path) {
1576 namelen = namelen - (cp - name);
1577 } else {
1578 cp = new_path;
1579 namelen = strlen(cp);
1580 }
1581
1582 if (flags & GET_OID_RECORD_PATH)
1583 oc->path = xstrdup(cp);
1584
1585 if (!active_cache)
1586 read_cache();
1587 pos = cache_name_pos(cp, namelen);
1588 if (pos < 0)
1589 pos = -pos - 1;
1590 while (pos < active_nr) {
1591 ce = active_cache[pos];
1592 if (ce_namelen(ce) != namelen ||
1593 memcmp(ce->name, cp, namelen))
1594 break;
1595 if (ce_stage(ce) == stage) {
1596 oidcpy(oid, &ce->oid);
1597 oc->mode = ce->ce_mode;
1598 free(new_path);
1599 return 0;
1600 }
1601 pos++;
1602 }
1603 if (only_to_die && name[1] && name[1] != '/')
1604 diagnose_invalid_index_path(stage, prefix, cp);
1605 free(new_path);
1606 return -1;
1607 }
1608 for (cp = name, bracket_depth = 0; *cp; cp++) {
1609 if (*cp == '{')
1610 bracket_depth++;
1611 else if (bracket_depth && *cp == '}')
1612 bracket_depth--;
1613 else if (!bracket_depth && *cp == ':')
1614 break;
1615 }
1616 if (*cp == ':') {
1617 struct object_id tree_oid;
1618 int len = cp - name;
1619 unsigned sub_flags = flags;
1620
1621 sub_flags &= ~GET_OID_DISAMBIGUATORS;
1622 sub_flags |= GET_OID_TREEISH;
1623
1624 if (!get_oid_1(name, len, &tree_oid, sub_flags)) {
1625 const char *filename = cp+1;
1626 char *new_filename = NULL;
1627
1628 new_filename = resolve_relative_path(filename);
1629 if (new_filename)
1630 filename = new_filename;
1631 if (flags & GET_OID_FOLLOW_SYMLINKS) {
1632 ret = get_tree_entry_follow_symlinks(tree_oid.hash,
1633 filename, oid->hash, &oc->symlink_path,
1634 &oc->mode);
1635 } else {
1636 ret = get_tree_entry(tree_oid.hash, filename,
1637 oid->hash, &oc->mode);
1638 if (ret && only_to_die) {
1639 diagnose_invalid_oid_path(prefix,
1640 filename,
1641 &tree_oid,
1642 name, len);
1643 }
1644 }
1645 hashcpy(oc->tree, tree_oid.hash);
1646 if (flags & GET_OID_RECORD_PATH)
1647 oc->path = xstrdup(filename);
1648
1649 free(new_filename);
1650 return ret;
1651 } else {
1652 if (only_to_die)
1653 die("Invalid object name '%.*s'.", len, name);
1654 }
1655 }
1656 return ret;
1657}
1658
1659/*
1660 * Call this function when you know "name" given by the end user must
1661 * name an object but it doesn't; the function _may_ die with a better
1662 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1663 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1664 * you have a chance to diagnose the error further.
1665 */
1666void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1667{
1668 struct object_context oc;
1669 struct object_id oid;
1670 get_oid_with_context_1(name, GET_OID_ONLY_TO_DIE, prefix, &oid, &oc);
1671}
1672
1673int get_oid_with_context(const char *str, unsigned flags, struct object_id *oid, struct object_context *oc)
1674{
1675 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
1676 die("BUG: incompatible flags for get_sha1_with_context");
1677 return get_oid_with_context_1(str, flags, NULL, oid, oc);
1678}