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