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