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