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