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