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