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