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