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