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