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