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