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