Merge branch 'jk/upload-pack-use-prio-queue'
[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 int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
452 {
453         int status, exists;
454
455         sha1_to_hex_r(hex, sha1);
456         if (len == 40 || !len)
457                 return 40;
458         exists = has_sha1_file(sha1);
459         while (len < 40) {
460                 unsigned char sha1_ret[20];
461                 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
462                 if (exists
463                     ? !status
464                     : status == SHORT_NAME_NOT_FOUND) {
465                         hex[len] = 0;
466                         return len;
467                 }
468                 len++;
469         }
470         return len;
471 }
472
473 const char *find_unique_abbrev(const unsigned char *sha1, int len)
474 {
475         static char hex[GIT_SHA1_HEXSZ + 1];
476         find_unique_abbrev_r(hex, sha1, len);
477         return hex;
478 }
479
480 static int ambiguous_path(const char *path, int len)
481 {
482         int slash = 1;
483         int cnt;
484
485         for (cnt = 0; cnt < len; cnt++) {
486                 switch (*path++) {
487                 case '\0':
488                         break;
489                 case '/':
490                         if (slash)
491                                 break;
492                         slash = 1;
493                         continue;
494                 case '.':
495                         continue;
496                 default:
497                         slash = 0;
498                         continue;
499                 }
500                 break;
501         }
502         return slash;
503 }
504
505 static inline int at_mark(const char *string, int len,
506                           const char **suffix, int nr)
507 {
508         int i;
509
510         for (i = 0; i < nr; i++) {
511                 int suffix_len = strlen(suffix[i]);
512                 if (suffix_len <= len
513                     && !memcmp(string, suffix[i], suffix_len))
514                         return suffix_len;
515         }
516         return 0;
517 }
518
519 static inline int upstream_mark(const char *string, int len)
520 {
521         const char *suffix[] = { "@{upstream}", "@{u}" };
522         return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
523 }
524
525 static inline int push_mark(const char *string, int len)
526 {
527         const char *suffix[] = { "@{push}" };
528         return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
529 }
530
531 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
532 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
533
534 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
535                           unsigned int flags)
536 {
537         static const char *warn_msg = "refname '%.*s' is ambiguous.";
538         static const char *object_name_msg = N_(
539         "Git normally never creates a ref that ends with 40 hex characters\n"
540         "because it will be ignored when you just specify 40-hex. These refs\n"
541         "may be created by mistake. For example,\n"
542         "\n"
543         "  git checkout -b $br $(git rev-parse ...)\n"
544         "\n"
545         "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
546         "examine these refs and maybe delete them. Turn this message off by\n"
547         "running \"git config advice.objectNameWarning false\"");
548         unsigned char tmp_sha1[20];
549         char *real_ref = NULL;
550         int refs_found = 0;
551         int at, reflog_len, nth_prior = 0;
552
553         if (len == 40 && !get_sha1_hex(str, sha1)) {
554                 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
555                         refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
556                         if (refs_found > 0) {
557                                 warning(warn_msg, len, str);
558                                 if (advice_object_name_warning)
559                                         fprintf(stderr, "%s\n", _(object_name_msg));
560                         }
561                         free(real_ref);
562                 }
563                 return 0;
564         }
565
566         /* basic@{time or number or -number} format to query ref-log */
567         reflog_len = at = 0;
568         if (len && str[len-1] == '}') {
569                 for (at = len-4; at >= 0; at--) {
570                         if (str[at] == '@' && str[at+1] == '{') {
571                                 if (str[at+2] == '-') {
572                                         if (at != 0)
573                                                 /* @{-N} not at start */
574                                                 return -1;
575                                         nth_prior = 1;
576                                         continue;
577                                 }
578                                 if (!upstream_mark(str + at, len - at) &&
579                                     !push_mark(str + at, len - at)) {
580                                         reflog_len = (len-1) - (at+2);
581                                         len = at;
582                                 }
583                                 break;
584                         }
585                 }
586         }
587
588         /* Accept only unambiguous ref paths. */
589         if (len && ambiguous_path(str, len))
590                 return -1;
591
592         if (nth_prior) {
593                 struct strbuf buf = STRBUF_INIT;
594                 int detached;
595
596                 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
597                         detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
598                         strbuf_release(&buf);
599                         if (detached)
600                                 return 0;
601                 }
602         }
603
604         if (!len && reflog_len)
605                 /* allow "@{...}" to mean the current branch reflog */
606                 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
607         else if (reflog_len)
608                 refs_found = dwim_log(str, len, sha1, &real_ref);
609         else
610                 refs_found = dwim_ref(str, len, sha1, &real_ref);
611
612         if (!refs_found)
613                 return -1;
614
615         if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
616             (refs_found > 1 ||
617              !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
618                 warning(warn_msg, len, str);
619
620         if (reflog_len) {
621                 int nth, i;
622                 unsigned long at_time;
623                 unsigned long co_time;
624                 int co_tz, co_cnt;
625
626                 /* Is it asking for N-th entry, or approxidate? */
627                 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
628                         char ch = str[at+2+i];
629                         if ('0' <= ch && ch <= '9')
630                                 nth = nth * 10 + ch - '0';
631                         else
632                                 nth = -1;
633                 }
634                 if (100000000 <= nth) {
635                         at_time = nth;
636                         nth = -1;
637                 } else if (0 <= nth)
638                         at_time = 0;
639                 else {
640                         int errors = 0;
641                         char *tmp = xstrndup(str + at + 2, reflog_len);
642                         at_time = approxidate_careful(tmp, &errors);
643                         free(tmp);
644                         if (errors) {
645                                 free(real_ref);
646                                 return -1;
647                         }
648                 }
649                 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
650                                 &co_time, &co_tz, &co_cnt)) {
651                         if (!len) {
652                                 if (starts_with(real_ref, "refs/heads/")) {
653                                         str = real_ref + 11;
654                                         len = strlen(real_ref + 11);
655                                 } else {
656                                         /* detached HEAD */
657                                         str = "HEAD";
658                                         len = 4;
659                                 }
660                         }
661                         if (at_time) {
662                                 if (!(flags & GET_SHA1_QUIETLY)) {
663                                         warning("Log for '%.*s' only goes "
664                                                 "back to %s.", len, str,
665                                                 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
666                                 }
667                         } else {
668                                 if (flags & GET_SHA1_QUIETLY) {
669                                         exit(128);
670                                 }
671                                 die("Log for '%.*s' only has %d entries.",
672                                     len, str, co_cnt);
673                         }
674                 }
675         }
676
677         free(real_ref);
678         return 0;
679 }
680
681 static int get_parent(const char *name, int len,
682                       unsigned char *result, int idx)
683 {
684         unsigned char sha1[20];
685         int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
686         struct commit *commit;
687         struct commit_list *p;
688
689         if (ret)
690                 return ret;
691         commit = lookup_commit_reference(sha1);
692         if (parse_commit(commit))
693                 return -1;
694         if (!idx) {
695                 hashcpy(result, commit->object.oid.hash);
696                 return 0;
697         }
698         p = commit->parents;
699         while (p) {
700                 if (!--idx) {
701                         hashcpy(result, p->item->object.oid.hash);
702                         return 0;
703                 }
704                 p = p->next;
705         }
706         return -1;
707 }
708
709 static int get_nth_ancestor(const char *name, int len,
710                             unsigned char *result, int generation)
711 {
712         unsigned char sha1[20];
713         struct commit *commit;
714         int ret;
715
716         ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
717         if (ret)
718                 return ret;
719         commit = lookup_commit_reference(sha1);
720         if (!commit)
721                 return -1;
722
723         while (generation--) {
724                 if (parse_commit(commit) || !commit->parents)
725                         return -1;
726                 commit = commit->parents->item;
727         }
728         hashcpy(result, commit->object.oid.hash);
729         return 0;
730 }
731
732 struct object *peel_to_type(const char *name, int namelen,
733                             struct object *o, enum object_type expected_type)
734 {
735         if (name && !namelen)
736                 namelen = strlen(name);
737         while (1) {
738                 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
739                         return NULL;
740                 if (expected_type == OBJ_ANY || o->type == expected_type)
741                         return o;
742                 if (o->type == OBJ_TAG)
743                         o = ((struct tag*) o)->tagged;
744                 else if (o->type == OBJ_COMMIT)
745                         o = &(((struct commit *) o)->tree->object);
746                 else {
747                         if (name)
748                                 error("%.*s: expected %s type, but the object "
749                                       "dereferences to %s type",
750                                       namelen, name, typename(expected_type),
751                                       typename(o->type));
752                         return NULL;
753                 }
754         }
755 }
756
757 static int peel_onion(const char *name, int len, unsigned char *sha1,
758                       unsigned lookup_flags)
759 {
760         unsigned char outer[20];
761         const char *sp;
762         unsigned int expected_type = 0;
763         struct object *o;
764
765         /*
766          * "ref^{type}" dereferences ref repeatedly until you cannot
767          * dereference anymore, or you get an object of given type,
768          * whichever comes first.  "ref^{}" means just dereference
769          * tags until you get a non-tag.  "ref^0" is a shorthand for
770          * "ref^{commit}".  "commit^{tree}" could be used to find the
771          * top-level tree of the given commit.
772          */
773         if (len < 4 || name[len-1] != '}')
774                 return -1;
775
776         for (sp = name + len - 1; name <= sp; sp--) {
777                 int ch = *sp;
778                 if (ch == '{' && name < sp && sp[-1] == '^')
779                         break;
780         }
781         if (sp <= name)
782                 return -1;
783
784         sp++; /* beginning of type name, or closing brace for empty */
785         if (starts_with(sp, "commit}"))
786                 expected_type = OBJ_COMMIT;
787         else if (starts_with(sp, "tag}"))
788                 expected_type = OBJ_TAG;
789         else if (starts_with(sp, "tree}"))
790                 expected_type = OBJ_TREE;
791         else if (starts_with(sp, "blob}"))
792                 expected_type = OBJ_BLOB;
793         else if (starts_with(sp, "object}"))
794                 expected_type = OBJ_ANY;
795         else if (sp[0] == '}')
796                 expected_type = OBJ_NONE;
797         else if (sp[0] == '/')
798                 expected_type = OBJ_COMMIT;
799         else
800                 return -1;
801
802         lookup_flags &= ~GET_SHA1_DISAMBIGUATORS;
803         if (expected_type == OBJ_COMMIT)
804                 lookup_flags |= GET_SHA1_COMMITTISH;
805         else if (expected_type == OBJ_TREE)
806                 lookup_flags |= GET_SHA1_TREEISH;
807
808         if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
809                 return -1;
810
811         o = parse_object(outer);
812         if (!o)
813                 return -1;
814         if (!expected_type) {
815                 o = deref_tag(o, name, sp - name - 2);
816                 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
817                         return -1;
818                 hashcpy(sha1, o->oid.hash);
819                 return 0;
820         }
821
822         /*
823          * At this point, the syntax look correct, so
824          * if we do not get the needed object, we should
825          * barf.
826          */
827         o = peel_to_type(name, len, o, expected_type);
828         if (!o)
829                 return -1;
830
831         hashcpy(sha1, o->oid.hash);
832         if (sp[0] == '/') {
833                 /* "$commit^{/foo}" */
834                 char *prefix;
835                 int ret;
836                 struct commit_list *list = NULL;
837
838                 /*
839                  * $commit^{/}. Some regex implementation may reject.
840                  * We don't need regex anyway. '' pattern always matches.
841                  */
842                 if (sp[1] == '}')
843                         return 0;
844
845                 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
846                 commit_list_insert((struct commit *)o, &list);
847                 ret = get_sha1_oneline(prefix, sha1, list);
848                 free(prefix);
849                 return ret;
850         }
851         return 0;
852 }
853
854 static int get_describe_name(const char *name, int len, unsigned char *sha1)
855 {
856         const char *cp;
857         unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
858
859         for (cp = name + len - 1; name + 2 <= cp; cp--) {
860                 char ch = *cp;
861                 if (!isxdigit(ch)) {
862                         /* We must be looking at g in "SOMETHING-g"
863                          * for it to be describe output.
864                          */
865                         if (ch == 'g' && cp[-1] == '-') {
866                                 cp++;
867                                 len -= cp - name;
868                                 return get_short_sha1(cp, len, sha1, flags);
869                         }
870                 }
871         }
872         return -1;
873 }
874
875 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
876 {
877         int ret, has_suffix;
878         const char *cp;
879
880         /*
881          * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
882          */
883         has_suffix = 0;
884         for (cp = name + len - 1; name <= cp; cp--) {
885                 int ch = *cp;
886                 if ('0' <= ch && ch <= '9')
887                         continue;
888                 if (ch == '~' || ch == '^')
889                         has_suffix = ch;
890                 break;
891         }
892
893         if (has_suffix) {
894                 int num = 0;
895                 int len1 = cp - name;
896                 cp++;
897                 while (cp < name + len)
898                         num = num * 10 + *cp++ - '0';
899                 if (!num && len1 == len - 1)
900                         num = 1;
901                 if (has_suffix == '^')
902                         return get_parent(name, len1, sha1, num);
903                 /* else if (has_suffix == '~') -- goes without saying */
904                 return get_nth_ancestor(name, len1, sha1, num);
905         }
906
907         ret = peel_onion(name, len, sha1, lookup_flags);
908         if (!ret)
909                 return 0;
910
911         ret = get_sha1_basic(name, len, sha1, lookup_flags);
912         if (!ret)
913                 return 0;
914
915         /* It could be describe output that is "SOMETHING-gXXXX" */
916         ret = get_describe_name(name, len, sha1);
917         if (!ret)
918                 return 0;
919
920         return get_short_sha1(name, len, sha1, lookup_flags);
921 }
922
923 /*
924  * This interprets names like ':/Initial revision of "git"' by searching
925  * through history and returning the first commit whose message starts
926  * the given regular expression.
927  *
928  * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
929  *
930  * For a literal '!' character at the beginning of a pattern, you have to repeat
931  * that, like: ':/!!foo'
932  *
933  * For future extension, all other sequences beginning with ':/!' are reserved.
934  */
935
936 /* Remember to update object flag allocation in object.h */
937 #define ONELINE_SEEN (1u<<20)
938
939 static int handle_one_ref(const char *path, const struct object_id *oid,
940                           int flag, void *cb_data)
941 {
942         struct commit_list **list = cb_data;
943         struct object *object = parse_object(oid->hash);
944         if (!object)
945                 return 0;
946         if (object->type == OBJ_TAG) {
947                 object = deref_tag(object, path, strlen(path));
948                 if (!object)
949                         return 0;
950         }
951         if (object->type != OBJ_COMMIT)
952                 return 0;
953         commit_list_insert((struct commit *)object, list);
954         return 0;
955 }
956
957 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
958                             struct commit_list *list)
959 {
960         struct commit_list *backup = NULL, *l;
961         int found = 0;
962         int negative = 0;
963         regex_t regex;
964
965         if (prefix[0] == '!') {
966                 prefix++;
967
968                 if (prefix[0] == '-') {
969                         prefix++;
970                         negative = 1;
971                 } else if (prefix[0] != '!') {
972                         return -1;
973                 }
974         }
975
976         if (regcomp(&regex, prefix, REG_EXTENDED))
977                 return -1;
978
979         for (l = list; l; l = l->next) {
980                 l->item->object.flags |= ONELINE_SEEN;
981                 commit_list_insert(l->item, &backup);
982         }
983         while (list) {
984                 const char *p, *buf;
985                 struct commit *commit;
986                 int matches;
987
988                 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
989                 if (!parse_object(commit->object.oid.hash))
990                         continue;
991                 buf = get_commit_buffer(commit, NULL);
992                 p = strstr(buf, "\n\n");
993                 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
994                 unuse_commit_buffer(commit, buf);
995
996                 if (matches) {
997                         hashcpy(sha1, commit->object.oid.hash);
998                         found = 1;
999                         break;
1000                 }
1001         }
1002         regfree(&regex);
1003         free_commit_list(list);
1004         for (l = backup; l; l = l->next)
1005                 clear_commit_marks(l->item, ONELINE_SEEN);
1006         free_commit_list(backup);
1007         return found ? 0 : -1;
1008 }
1009
1010 struct grab_nth_branch_switch_cbdata {
1011         int remaining;
1012         struct strbuf buf;
1013 };
1014
1015 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
1016                                   const char *email, unsigned long timestamp, int tz,
1017                                   const char *message, void *cb_data)
1018 {
1019         struct grab_nth_branch_switch_cbdata *cb = cb_data;
1020         const char *match = NULL, *target = NULL;
1021         size_t len;
1022
1023         if (skip_prefix(message, "checkout: moving from ", &match))
1024                 target = strstr(match, " to ");
1025
1026         if (!match || !target)
1027                 return 0;
1028         if (--(cb->remaining) == 0) {
1029                 len = target - match;
1030                 strbuf_reset(&cb->buf);
1031                 strbuf_add(&cb->buf, match, len);
1032                 return 1; /* we are done */
1033         }
1034         return 0;
1035 }
1036
1037 /*
1038  * Parse @{-N} syntax, return the number of characters parsed
1039  * if successful; otherwise signal an error with negative value.
1040  */
1041 static int interpret_nth_prior_checkout(const char *name, int namelen,
1042                                         struct strbuf *buf)
1043 {
1044         long nth;
1045         int retval;
1046         struct grab_nth_branch_switch_cbdata cb;
1047         const char *brace;
1048         char *num_end;
1049
1050         if (namelen < 4)
1051                 return -1;
1052         if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1053                 return -1;
1054         brace = memchr(name, '}', namelen);
1055         if (!brace)
1056                 return -1;
1057         nth = strtol(name + 3, &num_end, 10);
1058         if (num_end != brace)
1059                 return -1;
1060         if (nth <= 0)
1061                 return -1;
1062         cb.remaining = nth;
1063         strbuf_init(&cb.buf, 20);
1064
1065         retval = 0;
1066         if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1067                 strbuf_reset(buf);
1068                 strbuf_addbuf(buf, &cb.buf);
1069                 retval = brace - name + 1;
1070         }
1071
1072         strbuf_release(&cb.buf);
1073         return retval;
1074 }
1075
1076 int get_oid_mb(const char *name, struct object_id *oid)
1077 {
1078         struct commit *one, *two;
1079         struct commit_list *mbs;
1080         struct object_id oid_tmp;
1081         const char *dots;
1082         int st;
1083
1084         dots = strstr(name, "...");
1085         if (!dots)
1086                 return get_oid(name, oid);
1087         if (dots == name)
1088                 st = get_oid("HEAD", &oid_tmp);
1089         else {
1090                 struct strbuf sb;
1091                 strbuf_init(&sb, dots - name);
1092                 strbuf_add(&sb, name, dots - name);
1093                 st = get_sha1_committish(sb.buf, oid_tmp.hash);
1094                 strbuf_release(&sb);
1095         }
1096         if (st)
1097                 return st;
1098         one = lookup_commit_reference_gently(oid_tmp.hash, 0);
1099         if (!one)
1100                 return -1;
1101
1102         if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", oid_tmp.hash))
1103                 return -1;
1104         two = lookup_commit_reference_gently(oid_tmp.hash, 0);
1105         if (!two)
1106                 return -1;
1107         mbs = get_merge_bases(one, two);
1108         if (!mbs || mbs->next)
1109                 st = -1;
1110         else {
1111                 st = 0;
1112                 oidcpy(oid, &mbs->item->object.oid);
1113         }
1114         free_commit_list(mbs);
1115         return st;
1116 }
1117
1118 /* parse @something syntax, when 'something' is not {.*} */
1119 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1120 {
1121         const char *next;
1122
1123         if (len || name[1] == '{')
1124                 return -1;
1125
1126         /* make sure it's a single @, or @@{.*}, not @foo */
1127         next = memchr(name + len + 1, '@', namelen - len - 1);
1128         if (next && next[1] != '{')
1129                 return -1;
1130         if (!next)
1131                 next = name + namelen;
1132         if (next != name + 1)
1133                 return -1;
1134
1135         strbuf_reset(buf);
1136         strbuf_add(buf, "HEAD", 4);
1137         return 1;
1138 }
1139
1140 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1141 {
1142         /* we have extra data, which might need further processing */
1143         struct strbuf tmp = STRBUF_INIT;
1144         int used = buf->len;
1145         int ret;
1146
1147         strbuf_add(buf, name + len, namelen - len);
1148         ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1149         /* that data was not interpreted, remove our cruft */
1150         if (ret < 0) {
1151                 strbuf_setlen(buf, used);
1152                 return len;
1153         }
1154         strbuf_reset(buf);
1155         strbuf_addbuf(buf, &tmp);
1156         strbuf_release(&tmp);
1157         /* tweak for size of {-N} versus expanded ref name */
1158         return ret - used + len;
1159 }
1160
1161 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1162 {
1163         char *s = shorten_unambiguous_ref(ref, 0);
1164         strbuf_reset(buf);
1165         strbuf_addstr(buf, s);
1166         free(s);
1167 }
1168
1169 static int interpret_branch_mark(const char *name, int namelen,
1170                                  int at, struct strbuf *buf,
1171                                  int (*get_mark)(const char *, int),
1172                                  const char *(*get_data)(struct branch *,
1173                                                          struct strbuf *))
1174 {
1175         int len;
1176         struct branch *branch;
1177         struct strbuf err = STRBUF_INIT;
1178         const char *value;
1179
1180         len = get_mark(name + at, namelen - at);
1181         if (!len)
1182                 return -1;
1183
1184         if (memchr(name, ':', at))
1185                 return -1;
1186
1187         if (at) {
1188                 char *name_str = xmemdupz(name, at);
1189                 branch = branch_get(name_str);
1190                 free(name_str);
1191         } else
1192                 branch = branch_get(NULL);
1193
1194         value = get_data(branch, &err);
1195         if (!value)
1196                 die("%s", err.buf);
1197
1198         set_shortened_ref(buf, value);
1199         return len + at;
1200 }
1201
1202 /*
1203  * This reads short-hand syntax that not only evaluates to a commit
1204  * object name, but also can act as if the end user spelled the name
1205  * of the branch from the command line.
1206  *
1207  * - "@{-N}" finds the name of the Nth previous branch we were on, and
1208  *   places the name of the branch in the given buf and returns the
1209  *   number of characters parsed if successful.
1210  *
1211  * - "<branch>@{upstream}" finds the name of the other ref that
1212  *   <branch> is configured to merge with (missing <branch> defaults
1213  *   to the current branch), and places the name of the branch in the
1214  *   given buf and returns the number of characters parsed if
1215  *   successful.
1216  *
1217  * If the input is not of the accepted format, it returns a negative
1218  * number to signal an error.
1219  *
1220  * If the input was ok but there are not N branch switches in the
1221  * reflog, it returns 0.
1222  */
1223 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1224 {
1225         char *at;
1226         const char *start;
1227         int len = interpret_nth_prior_checkout(name, namelen, buf);
1228
1229         if (!namelen)
1230                 namelen = strlen(name);
1231
1232         if (!len) {
1233                 return len; /* syntax Ok, not enough switches */
1234         } else if (len > 0) {
1235                 if (len == namelen)
1236                         return len; /* consumed all */
1237                 else
1238                         return reinterpret(name, namelen, len, buf);
1239         }
1240
1241         for (start = name;
1242              (at = memchr(start, '@', namelen - (start - name)));
1243              start = at + 1) {
1244
1245                 len = interpret_empty_at(name, namelen, at - name, buf);
1246                 if (len > 0)
1247                         return reinterpret(name, namelen, len, buf);
1248
1249                 len = interpret_branch_mark(name, namelen, at - name, buf,
1250                                             upstream_mark, branch_get_upstream);
1251                 if (len > 0)
1252                         return len;
1253
1254                 len = interpret_branch_mark(name, namelen, at - name, buf,
1255                                             push_mark, branch_get_push);
1256                 if (len > 0)
1257                         return len;
1258         }
1259
1260         return -1;
1261 }
1262
1263 int strbuf_branchname(struct strbuf *sb, const char *name)
1264 {
1265         int len = strlen(name);
1266         int used = interpret_branch_name(name, len, sb);
1267
1268         if (used == len)
1269                 return 0;
1270         if (used < 0)
1271                 used = 0;
1272         strbuf_add(sb, name + used, len - used);
1273         return len;
1274 }
1275
1276 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1277 {
1278         strbuf_branchname(sb, name);
1279         if (name[0] == '-')
1280                 return -1;
1281         strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1282         return check_refname_format(sb->buf, 0);
1283 }
1284
1285 /*
1286  * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1287  * notably "xyz^" for "parent of xyz"
1288  */
1289 int get_sha1(const char *name, unsigned char *sha1)
1290 {
1291         struct object_context unused;
1292         return get_sha1_with_context(name, 0, sha1, &unused);
1293 }
1294
1295 /*
1296  * This is like "get_sha1()", but for struct object_id.
1297  */
1298 int get_oid(const char *name, struct object_id *oid)
1299 {
1300         return get_sha1(name, oid->hash);
1301 }
1302
1303
1304 /*
1305  * Many callers know that the user meant to name a commit-ish by
1306  * syntactical positions where the object name appears.  Calling this
1307  * function allows the machinery to disambiguate shorter-than-unique
1308  * abbreviated object names between commit-ish and others.
1309  *
1310  * Note that this does NOT error out when the named object is not a
1311  * commit-ish. It is merely to give a hint to the disambiguation
1312  * machinery.
1313  */
1314 int get_sha1_committish(const char *name, unsigned char *sha1)
1315 {
1316         struct object_context unused;
1317         return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1318                                      sha1, &unused);
1319 }
1320
1321 int get_sha1_treeish(const char *name, unsigned char *sha1)
1322 {
1323         struct object_context unused;
1324         return get_sha1_with_context(name, GET_SHA1_TREEISH,
1325                                      sha1, &unused);
1326 }
1327
1328 int get_sha1_commit(const char *name, unsigned char *sha1)
1329 {
1330         struct object_context unused;
1331         return get_sha1_with_context(name, GET_SHA1_COMMIT,
1332                                      sha1, &unused);
1333 }
1334
1335 int get_sha1_tree(const char *name, unsigned char *sha1)
1336 {
1337         struct object_context unused;
1338         return get_sha1_with_context(name, GET_SHA1_TREE,
1339                                      sha1, &unused);
1340 }
1341
1342 int get_sha1_blob(const char *name, unsigned char *sha1)
1343 {
1344         struct object_context unused;
1345         return get_sha1_with_context(name, GET_SHA1_BLOB,
1346                                      sha1, &unused);
1347 }
1348
1349 /* Must be called only when object_name:filename doesn't exist. */
1350 static void diagnose_invalid_sha1_path(const char *prefix,
1351                                        const char *filename,
1352                                        const unsigned char *tree_sha1,
1353                                        const char *object_name,
1354                                        int object_name_len)
1355 {
1356         unsigned char sha1[20];
1357         unsigned mode;
1358
1359         if (!prefix)
1360                 prefix = "";
1361
1362         if (file_exists(filename))
1363                 die("Path '%s' exists on disk, but not in '%.*s'.",
1364                     filename, object_name_len, object_name);
1365         if (errno == ENOENT || errno == ENOTDIR) {
1366                 char *fullname = xstrfmt("%s%s", prefix, filename);
1367
1368                 if (!get_tree_entry(tree_sha1, fullname,
1369                                     sha1, &mode)) {
1370                         die("Path '%s' exists, but not '%s'.\n"
1371                             "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1372                             fullname,
1373                             filename,
1374                             object_name_len, object_name,
1375                             fullname,
1376                             object_name_len, object_name,
1377                             filename);
1378                 }
1379                 die("Path '%s' does not exist in '%.*s'",
1380                     filename, object_name_len, object_name);
1381         }
1382 }
1383
1384 /* Must be called only when :stage:filename doesn't exist. */
1385 static void diagnose_invalid_index_path(int stage,
1386                                         const char *prefix,
1387                                         const char *filename)
1388 {
1389         const struct cache_entry *ce;
1390         int pos;
1391         unsigned namelen = strlen(filename);
1392         struct strbuf fullname = STRBUF_INIT;
1393
1394         if (!prefix)
1395                 prefix = "";
1396
1397         /* Wrong stage number? */
1398         pos = cache_name_pos(filename, namelen);
1399         if (pos < 0)
1400                 pos = -pos - 1;
1401         if (pos < active_nr) {
1402                 ce = active_cache[pos];
1403                 if (ce_namelen(ce) == namelen &&
1404                     !memcmp(ce->name, filename, namelen))
1405                         die("Path '%s' is in the index, but not at stage %d.\n"
1406                             "Did you mean ':%d:%s'?",
1407                             filename, stage,
1408                             ce_stage(ce), filename);
1409         }
1410
1411         /* Confusion between relative and absolute filenames? */
1412         strbuf_addstr(&fullname, prefix);
1413         strbuf_addstr(&fullname, filename);
1414         pos = cache_name_pos(fullname.buf, fullname.len);
1415         if (pos < 0)
1416                 pos = -pos - 1;
1417         if (pos < active_nr) {
1418                 ce = active_cache[pos];
1419                 if (ce_namelen(ce) == fullname.len &&
1420                     !memcmp(ce->name, fullname.buf, fullname.len))
1421                         die("Path '%s' is in the index, but not '%s'.\n"
1422                             "Did you mean ':%d:%s' aka ':%d:./%s'?",
1423                             fullname.buf, filename,
1424                             ce_stage(ce), fullname.buf,
1425                             ce_stage(ce), filename);
1426         }
1427
1428         if (file_exists(filename))
1429                 die("Path '%s' exists on disk, but not in the index.", filename);
1430         if (errno == ENOENT || errno == ENOTDIR)
1431                 die("Path '%s' does not exist (neither on disk nor in the index).",
1432                     filename);
1433
1434         strbuf_release(&fullname);
1435 }
1436
1437
1438 static char *resolve_relative_path(const char *rel)
1439 {
1440         if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1441                 return NULL;
1442
1443         if (!is_inside_work_tree())
1444                 die("relative path syntax can't be used outside working tree.");
1445
1446         /* die() inside prefix_path() if resolved path is outside worktree */
1447         return prefix_path(startup_info->prefix,
1448                            startup_info->prefix ? strlen(startup_info->prefix) : 0,
1449                            rel);
1450 }
1451
1452 static int get_sha1_with_context_1(const char *name,
1453                                    unsigned flags,
1454                                    const char *prefix,
1455                                    unsigned char *sha1,
1456                                    struct object_context *oc)
1457 {
1458         int ret, bracket_depth;
1459         int namelen = strlen(name);
1460         const char *cp;
1461         int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1462
1463         if (only_to_die)
1464                 flags |= GET_SHA1_QUIETLY;
1465
1466         memset(oc, 0, sizeof(*oc));
1467         oc->mode = S_IFINVALID;
1468         ret = get_sha1_1(name, namelen, sha1, flags);
1469         if (!ret)
1470                 return ret;
1471         /*
1472          * sha1:path --> object name of path in ent sha1
1473          * :path -> object name of absolute path in index
1474          * :./path -> object name of path relative to cwd in index
1475          * :[0-3]:path -> object name of path in index at stage
1476          * :/foo -> recent commit matching foo
1477          */
1478         if (name[0] == ':') {
1479                 int stage = 0;
1480                 const struct cache_entry *ce;
1481                 char *new_path = NULL;
1482                 int pos;
1483                 if (!only_to_die && namelen > 2 && name[1] == '/') {
1484                         struct commit_list *list = NULL;
1485
1486                         for_each_ref(handle_one_ref, &list);
1487                         commit_list_sort_by_date(&list);
1488                         return get_sha1_oneline(name + 2, sha1, list);
1489                 }
1490                 if (namelen < 3 ||
1491                     name[2] != ':' ||
1492                     name[1] < '0' || '3' < name[1])
1493                         cp = name + 1;
1494                 else {
1495                         stage = name[1] - '0';
1496                         cp = name + 3;
1497                 }
1498                 new_path = resolve_relative_path(cp);
1499                 if (!new_path) {
1500                         namelen = namelen - (cp - name);
1501                 } else {
1502                         cp = new_path;
1503                         namelen = strlen(cp);
1504                 }
1505
1506                 strlcpy(oc->path, cp, sizeof(oc->path));
1507
1508                 if (!active_cache)
1509                         read_cache();
1510                 pos = cache_name_pos(cp, namelen);
1511                 if (pos < 0)
1512                         pos = -pos - 1;
1513                 while (pos < active_nr) {
1514                         ce = active_cache[pos];
1515                         if (ce_namelen(ce) != namelen ||
1516                             memcmp(ce->name, cp, namelen))
1517                                 break;
1518                         if (ce_stage(ce) == stage) {
1519                                 hashcpy(sha1, ce->oid.hash);
1520                                 oc->mode = ce->ce_mode;
1521                                 free(new_path);
1522                                 return 0;
1523                         }
1524                         pos++;
1525                 }
1526                 if (only_to_die && name[1] && name[1] != '/')
1527                         diagnose_invalid_index_path(stage, prefix, cp);
1528                 free(new_path);
1529                 return -1;
1530         }
1531         for (cp = name, bracket_depth = 0; *cp; cp++) {
1532                 if (*cp == '{')
1533                         bracket_depth++;
1534                 else if (bracket_depth && *cp == '}')
1535                         bracket_depth--;
1536                 else if (!bracket_depth && *cp == ':')
1537                         break;
1538         }
1539         if (*cp == ':') {
1540                 unsigned char tree_sha1[20];
1541                 int len = cp - name;
1542                 unsigned sub_flags = flags;
1543
1544                 sub_flags &= ~GET_SHA1_DISAMBIGUATORS;
1545                 sub_flags |= GET_SHA1_TREEISH;
1546
1547                 if (!get_sha1_1(name, len, tree_sha1, sub_flags)) {
1548                         const char *filename = cp+1;
1549                         char *new_filename = NULL;
1550
1551                         new_filename = resolve_relative_path(filename);
1552                         if (new_filename)
1553                                 filename = new_filename;
1554                         if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1555                                 ret = get_tree_entry_follow_symlinks(tree_sha1,
1556                                         filename, sha1, &oc->symlink_path,
1557                                         &oc->mode);
1558                         } else {
1559                                 ret = get_tree_entry(tree_sha1, filename,
1560                                                      sha1, &oc->mode);
1561                                 if (ret && only_to_die) {
1562                                         diagnose_invalid_sha1_path(prefix,
1563                                                                    filename,
1564                                                                    tree_sha1,
1565                                                                    name, len);
1566                                 }
1567                         }
1568                         hashcpy(oc->tree, tree_sha1);
1569                         strlcpy(oc->path, filename, sizeof(oc->path));
1570
1571                         free(new_filename);
1572                         return ret;
1573                 } else {
1574                         if (only_to_die)
1575                                 die("Invalid object name '%.*s'.", len, name);
1576                 }
1577         }
1578         return ret;
1579 }
1580
1581 /*
1582  * Call this function when you know "name" given by the end user must
1583  * name an object but it doesn't; the function _may_ die with a better
1584  * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1585  * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1586  * you have a chance to diagnose the error further.
1587  */
1588 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1589 {
1590         struct object_context oc;
1591         unsigned char sha1[20];
1592         get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1593 }
1594
1595 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1596 {
1597         if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1598                 die("BUG: incompatible flags for get_sha1_with_context");
1599         return get_sha1_with_context_1(str, flags, NULL, sha1, orc);
1600 }