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