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