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