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