11 #include "sha1-array.h"
13 #include "object-store.h"
14 #include "repository.h"
16 #include "commit-reach.h"
18 static int get_oid_oneline(const char *, struct object_id *, struct commit_list *);
20 typedef int (*disambiguate_hint_fn)(const struct object_id *, void *);
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;
27 disambiguate_hint_fn fn;
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;
35 unsigned always_call_fn:1;
38 static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
40 if (ds->always_call_fn) {
41 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
44 if (!ds->candidate_exists) {
45 /* this is the first candidate */
46 oidcpy(&ds->candidate, current);
47 ds->candidate_exists = 1;
49 } else if (oideq(&ds->candidate, current)) {
50 /* the same as what we already have seen */
55 /* cannot disambiguate between ds->candidate and current */
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;
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;
73 /* if we reach this point, we know ds->candidate satisfies fn */
74 if (ds->fn(current, ds->cb_data)) {
76 * if both current and candidate satisfy fn, we cannot
83 /* otherwise, current can be discarded and candidate is still good */
86 static int match_sha(unsigned, const unsigned char *, const unsigned char *);
88 static void find_short_object_filename(struct disambiguate_state *ds)
90 int subdir_nr = ds->bin_pfx.hash[0];
91 struct object_directory *odb;
93 for (odb = the_repository->objects->odb;
94 odb && !ds->ambiguous;
98 odb_load_loose_cache(odb, subdir_nr);
99 pos = oid_array_lookup(&odb->loose_objects_cache, &ds->bin_pfx);
102 while (!ds->ambiguous && pos < odb->loose_objects_cache.nr) {
103 const struct object_id *oid;
104 oid = odb->loose_objects_cache.oid + pos;
105 if (!match_sha(ds->len, ds->bin_pfx.hash, oid->hash))
107 update_candidates(ds, oid);
113 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
123 if ((*a ^ *b) & 0xf0)
128 static void unique_in_midx(struct multi_pack_index *m,
129 struct disambiguate_state *ds)
131 uint32_t num, i, first = 0;
132 const struct object_id *current = NULL;
133 num = m->num_objects;
138 bsearch_midx(&ds->bin_pfx, m, &first);
141 * At this point, "first" is the location of the lowest object
142 * with an object name that could match "bin_pfx". See if we have
143 * 0, 1 or more objects that actually match(es).
145 for (i = first; i < num && !ds->ambiguous; i++) {
146 struct object_id oid;
147 current = nth_midxed_object_oid(&oid, m, i);
148 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
150 update_candidates(ds, current);
154 static void unique_in_pack(struct packed_git *p,
155 struct disambiguate_state *ds)
157 uint32_t num, i, first = 0;
158 const struct object_id *current = NULL;
160 if (open_pack_index(p) || !p->num_objects)
163 num = p->num_objects;
164 bsearch_pack(&ds->bin_pfx, p, &first);
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).
171 for (i = first; i < num && !ds->ambiguous; i++) {
172 struct object_id oid;
173 current = nth_packed_object_oid(&oid, p, i);
174 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
176 update_candidates(ds, current);
180 static void find_short_packed_object(struct disambiguate_state *ds)
182 struct multi_pack_index *m;
183 struct packed_git *p;
185 for (m = get_multi_pack_index(the_repository); m && !ds->ambiguous;
187 unique_in_midx(m, ds);
188 for (p = get_packed_git(the_repository); p && !ds->ambiguous;
190 unique_in_pack(p, ds);
193 #define SHORT_NAME_NOT_FOUND (-1)
194 #define SHORT_NAME_AMBIGUOUS (-2)
196 static int finish_object_disambiguation(struct disambiguate_state *ds,
197 struct object_id *oid)
200 return SHORT_NAME_AMBIGUOUS;
202 if (!ds->candidate_exists)
203 return SHORT_NAME_NOT_FOUND;
205 if (!ds->candidate_checked)
207 * If this is the only candidate, there is no point
208 * calling the disambiguation hint callback.
210 * On the other hand, if the current candidate
211 * replaced an earlier candidate that did _not_ pass
212 * the disambiguation hint callback, then we do have
213 * more than one objects that match the short name
214 * given, so we should make sure this one matches;
215 * otherwise, if we discovered this one and the one
216 * that we previously discarded in the reverse order,
217 * we would end up showing different results in the
220 ds->candidate_ok = (!ds->disambiguate_fn_used ||
221 ds->fn(&ds->candidate, ds->cb_data));
223 if (!ds->candidate_ok)
224 return SHORT_NAME_AMBIGUOUS;
226 oidcpy(oid, &ds->candidate);
230 static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
232 int kind = oid_object_info(the_repository, oid, NULL);
233 return kind == OBJ_COMMIT;
236 static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
241 kind = oid_object_info(the_repository, oid, NULL);
242 if (kind == OBJ_COMMIT)
247 /* We need to do this the hard way... */
248 obj = deref_tag(the_repository, parse_object(the_repository, oid),
250 if (obj && obj->type == OBJ_COMMIT)
255 static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
257 int kind = oid_object_info(the_repository, oid, NULL);
258 return kind == OBJ_TREE;
261 static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
266 kind = oid_object_info(the_repository, oid, NULL);
267 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
272 /* We need to do this the hard way... */
273 obj = deref_tag(the_repository, parse_object(the_repository, oid),
275 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
280 static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
282 int kind = oid_object_info(the_repository, oid, NULL);
283 return kind == OBJ_BLOB;
286 static disambiguate_hint_fn default_disambiguate_hint;
288 int set_disambiguate_hint_config(const char *var, const char *value)
290 static const struct {
292 disambiguate_hint_fn fn;
295 { "commit", disambiguate_commit_only },
296 { "committish", disambiguate_committish_only },
297 { "tree", disambiguate_tree_only },
298 { "treeish", disambiguate_treeish_only },
299 { "blob", disambiguate_blob_only }
304 return config_error_nonbool(var);
306 for (i = 0; i < ARRAY_SIZE(hints); i++) {
307 if (!strcasecmp(value, hints[i].name)) {
308 default_disambiguate_hint = hints[i].fn;
313 return error("unknown hint type for '%s': %s", var, value);
316 static int init_object_disambiguation(const char *name, int len,
317 struct disambiguate_state *ds)
321 if (len < MINIMUM_ABBREV || len > the_hash_algo->hexsz)
324 memset(ds, 0, sizeof(*ds));
326 for (i = 0; i < len ;i++) {
327 unsigned char c = name[i];
329 if (c >= '0' && c <= '9')
331 else if (c >= 'a' && c <= 'f')
333 else if (c >= 'A' && c <='F') {
342 ds->bin_pfx.hash[i >> 1] |= val;
346 ds->hex_pfx[len] = '\0';
347 prepare_alt_odb(the_repository);
351 static int show_ambiguous_object(const struct object_id *oid, void *data)
353 const struct disambiguate_state *ds = data;
354 struct strbuf desc = STRBUF_INIT;
357 if (ds->fn && !ds->fn(oid, ds->cb_data))
360 type = oid_object_info(the_repository, oid, NULL);
361 if (type == OBJ_COMMIT) {
362 struct commit *commit = lookup_commit(the_repository, oid);
364 struct pretty_print_context pp = {0};
365 pp.date_mode.type = DATE_SHORT;
366 format_commit_message(commit, " %ad - %s", &desc, &pp);
368 } else if (type == OBJ_TAG) {
369 struct tag *tag = lookup_tag(the_repository, oid);
370 if (!parse_tag(tag) && tag->tag)
371 strbuf_addf(&desc, " %s", tag->tag);
375 find_unique_abbrev(oid, DEFAULT_ABBREV),
376 type_name(type) ? type_name(type) : "unknown type",
379 strbuf_release(&desc);
383 static int collect_ambiguous(const struct object_id *oid, void *data)
385 oid_array_append(data, oid);
389 static int sort_ambiguous(const void *a, const void *b)
391 int a_type = oid_object_info(the_repository, a, NULL);
392 int b_type = oid_object_info(the_repository, b, NULL);
397 * Sorts by hash within the same object type, just as
398 * oid_array_for_each_unique() would do.
400 if (a_type == b_type)
404 * Between object types show tags, then commits, and finally
407 * The object_type enum is commit, tree, blob, tag, but we
408 * want tag, commit, tree blob. Cleverly (perhaps too
409 * cleverly) do that with modulus, since the enum assigns 1 to
410 * commit, so tag becomes 0.
412 a_type_sort = a_type % 4;
413 b_type_sort = b_type % 4;
414 return a_type_sort > b_type_sort ? 1 : -1;
417 static int get_short_oid(const char *name, int len, struct object_id *oid,
421 struct disambiguate_state ds;
422 int quietly = !!(flags & GET_OID_QUIETLY);
424 if (init_object_disambiguation(name, len, &ds) < 0)
427 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
428 BUG("multiple get_short_oid disambiguator flags");
430 if (flags & GET_OID_COMMIT)
431 ds.fn = disambiguate_commit_only;
432 else if (flags & GET_OID_COMMITTISH)
433 ds.fn = disambiguate_committish_only;
434 else if (flags & GET_OID_TREE)
435 ds.fn = disambiguate_tree_only;
436 else if (flags & GET_OID_TREEISH)
437 ds.fn = disambiguate_treeish_only;
438 else if (flags & GET_OID_BLOB)
439 ds.fn = disambiguate_blob_only;
441 ds.fn = default_disambiguate_hint;
443 find_short_object_filename(&ds);
444 find_short_packed_object(&ds);
445 status = finish_object_disambiguation(&ds, oid);
447 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
448 struct oid_array collect = OID_ARRAY_INIT;
450 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
453 * We may still have ambiguity if we simply saw a series of
454 * candidates that did not satisfy our hint function. In
455 * that case, we still want to show them, so disable the hint
461 advise(_("The candidates are:"));
462 for_each_abbrev(ds.hex_pfx, collect_ambiguous, &collect);
463 QSORT(collect.oid, collect.nr, sort_ambiguous);
465 if (oid_array_for_each(&collect, show_ambiguous_object, &ds))
466 BUG("show_ambiguous_object shouldn't return non-zero");
467 oid_array_clear(&collect);
473 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
475 struct oid_array collect = OID_ARRAY_INIT;
476 struct disambiguate_state ds;
479 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
482 ds.always_call_fn = 1;
483 ds.fn = collect_ambiguous;
484 ds.cb_data = &collect;
485 find_short_object_filename(&ds);
486 find_short_packed_object(&ds);
488 ret = oid_array_for_each_unique(&collect, fn, cb_data);
489 oid_array_clear(&collect);
494 * Return the slot of the most-significant bit set in "val". There are various
495 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
496 * probably not a big deal here.
498 static unsigned msb(unsigned long val)
506 struct min_abbrev_data {
507 unsigned int init_len;
508 unsigned int cur_len;
510 const struct object_id *oid;
513 static inline char get_hex_char_from_oid(const struct object_id *oid,
516 static const char hex[] = "0123456789abcdef";
519 return hex[oid->hash[pos >> 1] >> 4];
521 return hex[oid->hash[pos >> 1] & 0xf];
524 static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
526 struct min_abbrev_data *mad = cb_data;
528 unsigned int i = mad->init_len;
529 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
532 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
533 mad->cur_len = i + 1;
538 static void find_abbrev_len_for_midx(struct multi_pack_index *m,
539 struct min_abbrev_data *mad)
542 uint32_t num, first = 0;
543 struct object_id oid;
544 const struct object_id *mad_oid;
549 num = m->num_objects;
551 match = bsearch_midx(mad_oid, m, &first);
554 * first is now the position in the packfile where we would insert
555 * mad->hash if it does not exist (or the position of mad->hash if
556 * it does exist). Hence, we consider a maximum of two objects
557 * nearby for the abbreviation length.
561 if (nth_midxed_object_oid(&oid, m, first))
562 extend_abbrev_len(&oid, mad);
563 } else if (first < num - 1) {
564 if (nth_midxed_object_oid(&oid, m, first + 1))
565 extend_abbrev_len(&oid, mad);
568 if (nth_midxed_object_oid(&oid, m, first - 1))
569 extend_abbrev_len(&oid, mad);
571 mad->init_len = mad->cur_len;
574 static void find_abbrev_len_for_pack(struct packed_git *p,
575 struct min_abbrev_data *mad)
578 uint32_t num, first = 0;
579 struct object_id oid;
580 const struct object_id *mad_oid;
582 if (open_pack_index(p) || !p->num_objects)
585 num = p->num_objects;
587 match = bsearch_pack(mad_oid, p, &first);
590 * first is now the position in the packfile where we would insert
591 * mad->hash if it does not exist (or the position of mad->hash if
592 * it does exist). Hence, we consider a maximum of two objects
593 * nearby for the abbreviation length.
597 if (nth_packed_object_oid(&oid, p, first))
598 extend_abbrev_len(&oid, mad);
599 } else if (first < num - 1) {
600 if (nth_packed_object_oid(&oid, p, first + 1))
601 extend_abbrev_len(&oid, mad);
604 if (nth_packed_object_oid(&oid, p, first - 1))
605 extend_abbrev_len(&oid, mad);
607 mad->init_len = mad->cur_len;
610 static void find_abbrev_len_packed(struct min_abbrev_data *mad)
612 struct multi_pack_index *m;
613 struct packed_git *p;
615 for (m = get_multi_pack_index(the_repository); m; m = m->next)
616 find_abbrev_len_for_midx(m, mad);
617 for (p = get_packed_git(the_repository); p; p = p->next)
618 find_abbrev_len_for_pack(p, mad);
621 int find_unique_abbrev_r(char *hex, const struct object_id *oid, int len)
623 struct disambiguate_state ds;
624 struct min_abbrev_data mad;
625 struct object_id oid_ret;
626 const unsigned hexsz = the_hash_algo->hexsz;
629 unsigned long count = approximate_object_count();
631 * Add one because the MSB only tells us the highest bit set,
632 * not including the value of all the _other_ bits (so "15"
633 * is only one off of 2^4, but the MSB is the 3rd bit.
635 len = msb(count) + 1;
637 * We now know we have on the order of 2^len objects, which
638 * expects a collision at 2^(len/2). But we also care about hex
639 * chars, not bits, and there are 4 bits per hex. So all
640 * together we need to divide by 2 and round up.
642 len = DIV_ROUND_UP(len, 2);
644 * For very small repos, we stick with our regular fallback.
646 if (len < FALLBACK_DEFAULT_ABBREV)
647 len = FALLBACK_DEFAULT_ABBREV;
650 oid_to_hex_r(hex, oid);
651 if (len == hexsz || !len)
659 find_abbrev_len_packed(&mad);
661 if (init_object_disambiguation(hex, mad.cur_len, &ds) < 0)
664 ds.fn = extend_abbrev_len;
665 ds.always_call_fn = 1;
666 ds.cb_data = (void *)&mad;
668 find_short_object_filename(&ds);
669 (void)finish_object_disambiguation(&ds, &oid_ret);
671 hex[mad.cur_len] = 0;
675 const char *find_unique_abbrev(const struct object_id *oid, int len)
678 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
679 char *hex = hexbuffer[bufno];
680 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
681 find_unique_abbrev_r(hex, oid, len);
685 static int ambiguous_path(const char *path, int len)
690 for (cnt = 0; cnt < len; cnt++) {
710 static inline int at_mark(const char *string, int len,
711 const char **suffix, int nr)
715 for (i = 0; i < nr; i++) {
716 int suffix_len = strlen(suffix[i]);
717 if (suffix_len <= len
718 && !strncasecmp(string, suffix[i], suffix_len))
724 static inline int upstream_mark(const char *string, int len)
726 const char *suffix[] = { "@{upstream}", "@{u}" };
727 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
730 static inline int push_mark(const char *string, int len)
732 const char *suffix[] = { "@{push}" };
733 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
736 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags);
737 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
739 static int get_oid_basic(const char *str, int len, struct object_id *oid,
742 static const char *warn_msg = "refname '%.*s' is ambiguous.";
743 static const char *object_name_msg = N_(
744 "Git normally never creates a ref that ends with 40 hex characters\n"
745 "because it will be ignored when you just specify 40-hex. These refs\n"
746 "may be created by mistake. For example,\n"
748 " git checkout -b $br $(git rev-parse ...)\n"
750 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
751 "examine these refs and maybe delete them. Turn this message off by\n"
752 "running \"git config advice.objectNameWarning false\"");
753 struct object_id tmp_oid;
754 char *real_ref = NULL;
756 int at, reflog_len, nth_prior = 0;
758 if (len == the_hash_algo->hexsz && !get_oid_hex(str, oid)) {
759 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
760 refs_found = dwim_ref(str, len, &tmp_oid, &real_ref);
761 if (refs_found > 0) {
762 warning(warn_msg, len, str);
763 if (advice_object_name_warning)
764 fprintf(stderr, "%s\n", _(object_name_msg));
771 /* basic@{time or number or -number} format to query ref-log */
773 if (len && str[len-1] == '}') {
774 for (at = len-4; at >= 0; at--) {
775 if (str[at] == '@' && str[at+1] == '{') {
776 if (str[at+2] == '-') {
778 /* @{-N} not at start */
783 if (!upstream_mark(str + at, len - at) &&
784 !push_mark(str + at, len - at)) {
785 reflog_len = (len-1) - (at+2);
793 /* Accept only unambiguous ref paths. */
794 if (len && ambiguous_path(str, len))
798 struct strbuf buf = STRBUF_INIT;
801 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
802 detached = (buf.len == the_hash_algo->hexsz && !get_oid_hex(buf.buf, oid));
803 strbuf_release(&buf);
809 if (!len && reflog_len)
810 /* allow "@{...}" to mean the current branch reflog */
811 refs_found = dwim_ref("HEAD", 4, oid, &real_ref);
813 refs_found = dwim_log(str, len, oid, &real_ref);
815 refs_found = dwim_ref(str, len, oid, &real_ref);
820 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
822 !get_short_oid(str, len, &tmp_oid, GET_OID_QUIETLY)))
823 warning(warn_msg, len, str);
831 /* Is it asking for N-th entry, or approxidate? */
832 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
833 char ch = str[at+2+i];
834 if ('0' <= ch && ch <= '9')
835 nth = nth * 10 + ch - '0';
839 if (100000000 <= nth) {
846 char *tmp = xstrndup(str + at + 2, reflog_len);
847 at_time = approxidate_careful(tmp, &errors);
854 if (read_ref_at(real_ref, flags, at_time, nth, oid, NULL,
855 &co_time, &co_tz, &co_cnt)) {
857 if (starts_with(real_ref, "refs/heads/")) {
859 len = strlen(real_ref + 11);
867 if (!(flags & GET_OID_QUIETLY)) {
868 warning("Log for '%.*s' only goes "
869 "back to %s.", len, str,
870 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
873 if (flags & GET_OID_QUIETLY) {
876 die("Log for '%.*s' only has %d entries.",
886 static int get_parent(const char *name, int len,
887 struct object_id *result, int idx)
889 struct object_id oid;
890 int ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
891 struct commit *commit;
892 struct commit_list *p;
896 commit = lookup_commit_reference(the_repository, &oid);
897 if (parse_commit(commit))
900 oidcpy(result, &commit->object.oid);
906 oidcpy(result, &p->item->object.oid);
914 static int get_nth_ancestor(const char *name, int len,
915 struct object_id *result, int generation)
917 struct object_id oid;
918 struct commit *commit;
921 ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
924 commit = lookup_commit_reference(the_repository, &oid);
928 while (generation--) {
929 if (parse_commit(commit) || !commit->parents)
931 commit = commit->parents->item;
933 oidcpy(result, &commit->object.oid);
937 struct object *peel_to_type(const char *name, int namelen,
938 struct object *o, enum object_type expected_type)
940 if (name && !namelen)
941 namelen = strlen(name);
943 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
945 if (expected_type == OBJ_ANY || o->type == expected_type)
947 if (o->type == OBJ_TAG)
948 o = ((struct tag*) o)->tagged;
949 else if (o->type == OBJ_COMMIT)
950 o = &(get_commit_tree(((struct commit *)o))->object);
953 error("%.*s: expected %s type, but the object "
954 "dereferences to %s type",
955 namelen, name, type_name(expected_type),
962 static int peel_onion(const char *name, int len, struct object_id *oid,
963 unsigned lookup_flags)
965 struct object_id outer;
967 unsigned int expected_type = 0;
971 * "ref^{type}" dereferences ref repeatedly until you cannot
972 * dereference anymore, or you get an object of given type,
973 * whichever comes first. "ref^{}" means just dereference
974 * tags until you get a non-tag. "ref^0" is a shorthand for
975 * "ref^{commit}". "commit^{tree}" could be used to find the
976 * top-level tree of the given commit.
978 if (len < 4 || name[len-1] != '}')
981 for (sp = name + len - 1; name <= sp; sp--) {
983 if (ch == '{' && name < sp && sp[-1] == '^')
989 sp++; /* beginning of type name, or closing brace for empty */
990 if (starts_with(sp, "commit}"))
991 expected_type = OBJ_COMMIT;
992 else if (starts_with(sp, "tag}"))
993 expected_type = OBJ_TAG;
994 else if (starts_with(sp, "tree}"))
995 expected_type = OBJ_TREE;
996 else if (starts_with(sp, "blob}"))
997 expected_type = OBJ_BLOB;
998 else if (starts_with(sp, "object}"))
999 expected_type = OBJ_ANY;
1000 else if (sp[0] == '}')
1001 expected_type = OBJ_NONE;
1002 else if (sp[0] == '/')
1003 expected_type = OBJ_COMMIT;
1007 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
1008 if (expected_type == OBJ_COMMIT)
1009 lookup_flags |= GET_OID_COMMITTISH;
1010 else if (expected_type == OBJ_TREE)
1011 lookup_flags |= GET_OID_TREEISH;
1013 if (get_oid_1(name, sp - name - 2, &outer, lookup_flags))
1016 o = parse_object(the_repository, &outer);
1019 if (!expected_type) {
1020 o = deref_tag(the_repository, o, name, sp - name - 2);
1021 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
1023 oidcpy(oid, &o->oid);
1028 * At this point, the syntax look correct, so
1029 * if we do not get the needed object, we should
1032 o = peel_to_type(name, len, o, expected_type);
1036 oidcpy(oid, &o->oid);
1038 /* "$commit^{/foo}" */
1041 struct commit_list *list = NULL;
1044 * $commit^{/}. Some regex implementation may reject.
1045 * We don't need regex anyway. '' pattern always matches.
1050 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
1051 commit_list_insert((struct commit *)o, &list);
1052 ret = get_oid_oneline(prefix, oid, list);
1059 static int get_describe_name(const char *name, int len, struct object_id *oid)
1062 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
1064 for (cp = name + len - 1; name + 2 <= cp; cp--) {
1066 if (!isxdigit(ch)) {
1067 /* We must be looking at g in "SOMETHING-g"
1068 * for it to be describe output.
1070 if (ch == 'g' && cp[-1] == '-') {
1073 return get_short_oid(cp, len, oid, flags);
1080 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags)
1082 int ret, has_suffix;
1086 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1089 for (cp = name + len - 1; name <= cp; cp--) {
1091 if ('0' <= ch && ch <= '9')
1093 if (ch == '~' || ch == '^')
1100 int len1 = cp - name;
1102 while (cp < name + len)
1103 num = num * 10 + *cp++ - '0';
1104 if (!num && len1 == len - 1)
1106 if (has_suffix == '^')
1107 return get_parent(name, len1, oid, num);
1108 /* else if (has_suffix == '~') -- goes without saying */
1109 return get_nth_ancestor(name, len1, oid, num);
1112 ret = peel_onion(name, len, oid, lookup_flags);
1116 ret = get_oid_basic(name, len, oid, lookup_flags);
1120 /* It could be describe output that is "SOMETHING-gXXXX" */
1121 ret = get_describe_name(name, len, oid);
1125 return get_short_oid(name, len, oid, lookup_flags);
1129 * This interprets names like ':/Initial revision of "git"' by searching
1130 * through history and returning the first commit whose message starts
1131 * the given regular expression.
1133 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1135 * For a literal '!' character at the beginning of a pattern, you have to repeat
1136 * that, like: ':/!!foo'
1138 * For future extension, all other sequences beginning with ':/!' are reserved.
1141 /* Remember to update object flag allocation in object.h */
1142 #define ONELINE_SEEN (1u<<20)
1144 static int handle_one_ref(const char *path, const struct object_id *oid,
1145 int flag, void *cb_data)
1147 struct commit_list **list = cb_data;
1148 struct object *object = parse_object(the_repository, oid);
1151 if (object->type == OBJ_TAG) {
1152 object = deref_tag(the_repository, object, path,
1157 if (object->type != OBJ_COMMIT)
1159 commit_list_insert((struct commit *)object, list);
1163 static int get_oid_oneline(const char *prefix, struct object_id *oid,
1164 struct commit_list *list)
1166 struct commit_list *backup = NULL, *l;
1171 if (prefix[0] == '!') {
1174 if (prefix[0] == '-') {
1177 } else if (prefix[0] != '!') {
1182 if (regcomp(®ex, prefix, REG_EXTENDED))
1185 for (l = list; l; l = l->next) {
1186 l->item->object.flags |= ONELINE_SEEN;
1187 commit_list_insert(l->item, &backup);
1190 const char *p, *buf;
1191 struct commit *commit;
1194 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1195 if (!parse_object(the_repository, &commit->object.oid))
1197 buf = get_commit_buffer(commit, NULL);
1198 p = strstr(buf, "\n\n");
1199 matches = negative ^ (p && !regexec(®ex, p + 2, 0, NULL, 0));
1200 unuse_commit_buffer(commit, buf);
1203 oidcpy(oid, &commit->object.oid);
1209 free_commit_list(list);
1210 for (l = backup; l; l = l->next)
1211 clear_commit_marks(l->item, ONELINE_SEEN);
1212 free_commit_list(backup);
1213 return found ? 0 : -1;
1216 struct grab_nth_branch_switch_cbdata {
1221 static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
1222 const char *email, timestamp_t timestamp, int tz,
1223 const char *message, void *cb_data)
1225 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1226 const char *match = NULL, *target = NULL;
1229 if (skip_prefix(message, "checkout: moving from ", &match))
1230 target = strstr(match, " to ");
1232 if (!match || !target)
1234 if (--(cb->remaining) == 0) {
1235 len = target - match;
1236 strbuf_reset(&cb->buf);
1237 strbuf_add(&cb->buf, match, len);
1238 return 1; /* we are done */
1244 * Parse @{-N} syntax, return the number of characters parsed
1245 * if successful; otherwise signal an error with negative value.
1247 static int interpret_nth_prior_checkout(const char *name, int namelen,
1252 struct grab_nth_branch_switch_cbdata cb;
1258 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1260 brace = memchr(name, '}', namelen);
1263 nth = strtol(name + 3, &num_end, 10);
1264 if (num_end != brace)
1269 strbuf_init(&cb.buf, 20);
1272 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1274 strbuf_addbuf(buf, &cb.buf);
1275 retval = brace - name + 1;
1278 strbuf_release(&cb.buf);
1282 int get_oid_mb(const char *name, struct object_id *oid)
1284 struct commit *one, *two;
1285 struct commit_list *mbs;
1286 struct object_id oid_tmp;
1290 dots = strstr(name, "...");
1292 return get_oid(name, oid);
1294 st = get_oid("HEAD", &oid_tmp);
1297 strbuf_init(&sb, dots - name);
1298 strbuf_add(&sb, name, dots - name);
1299 st = get_oid_committish(sb.buf, &oid_tmp);
1300 strbuf_release(&sb);
1304 one = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1308 if (get_oid_committish(dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1310 two = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1313 mbs = get_merge_bases(one, two);
1314 if (!mbs || mbs->next)
1318 oidcpy(oid, &mbs->item->object.oid);
1320 free_commit_list(mbs);
1324 /* parse @something syntax, when 'something' is not {.*} */
1325 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1329 if (len || name[1] == '{')
1332 /* make sure it's a single @, or @@{.*}, not @foo */
1333 next = memchr(name + len + 1, '@', namelen - len - 1);
1334 if (next && next[1] != '{')
1337 next = name + namelen;
1338 if (next != name + 1)
1342 strbuf_add(buf, "HEAD", 4);
1346 static int reinterpret(const char *name, int namelen, int len,
1347 struct strbuf *buf, unsigned allowed)
1349 /* we have extra data, which might need further processing */
1350 struct strbuf tmp = STRBUF_INIT;
1351 int used = buf->len;
1354 strbuf_add(buf, name + len, namelen - len);
1355 ret = interpret_branch_name(buf->buf, buf->len, &tmp, allowed);
1356 /* that data was not interpreted, remove our cruft */
1358 strbuf_setlen(buf, used);
1362 strbuf_addbuf(buf, &tmp);
1363 strbuf_release(&tmp);
1364 /* tweak for size of {-N} versus expanded ref name */
1365 return ret - used + len;
1368 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1370 char *s = shorten_unambiguous_ref(ref, 0);
1372 strbuf_addstr(buf, s);
1376 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1381 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1382 starts_with(refname, "refs/heads/"))
1384 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1385 starts_with(refname, "refs/remotes/"))
1391 static int interpret_branch_mark(const char *name, int namelen,
1392 int at, struct strbuf *buf,
1393 int (*get_mark)(const char *, int),
1394 const char *(*get_data)(struct branch *,
1399 struct branch *branch;
1400 struct strbuf err = STRBUF_INIT;
1403 len = get_mark(name + at, namelen - at);
1407 if (memchr(name, ':', at))
1411 char *name_str = xmemdupz(name, at);
1412 branch = branch_get(name_str);
1415 branch = branch_get(NULL);
1417 value = get_data(branch, &err);
1421 if (!branch_interpret_allowed(value, allowed))
1424 set_shortened_ref(buf, value);
1428 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf,
1436 namelen = strlen(name);
1438 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1439 len = interpret_nth_prior_checkout(name, namelen, buf);
1441 return len; /* syntax Ok, not enough switches */
1442 } else if (len > 0) {
1444 return len; /* consumed all */
1446 return reinterpret(name, namelen, len, buf, allowed);
1451 (at = memchr(start, '@', namelen - (start - name)));
1454 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1455 len = interpret_empty_at(name, namelen, at - name, buf);
1457 return reinterpret(name, namelen, len, buf,
1461 len = interpret_branch_mark(name, namelen, at - name, buf,
1462 upstream_mark, branch_get_upstream,
1467 len = interpret_branch_mark(name, namelen, at - name, buf,
1468 push_mark, branch_get_push,
1477 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1479 int len = strlen(name);
1480 int used = interpret_branch_name(name, len, sb, allowed);
1484 strbuf_add(sb, name + used, len - used);
1487 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1489 if (startup_info->have_repository)
1490 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1492 strbuf_addstr(sb, name);
1495 * This splice must be done even if we end up rejecting the
1496 * name; builtin/branch.c::copy_or_rename_branch() still wants
1497 * to see what the name expanded to so that "branch -m" can be
1498 * used as a tool to correct earlier mistakes.
1500 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1503 !strcmp(sb->buf, "refs/heads/HEAD"))
1506 return check_refname_format(sb->buf, 0);
1510 * This is like "get_oid_basic()", except it allows "object ID expressions",
1511 * notably "xyz^" for "parent of xyz"
1513 int get_oid(const char *name, struct object_id *oid)
1515 struct object_context unused;
1516 return get_oid_with_context(name, 0, oid, &unused);
1521 * Many callers know that the user meant to name a commit-ish by
1522 * syntactical positions where the object name appears. Calling this
1523 * function allows the machinery to disambiguate shorter-than-unique
1524 * abbreviated object names between commit-ish and others.
1526 * Note that this does NOT error out when the named object is not a
1527 * commit-ish. It is merely to give a hint to the disambiguation
1530 int get_oid_committish(const char *name, struct object_id *oid)
1532 struct object_context unused;
1533 return get_oid_with_context(name, GET_OID_COMMITTISH,
1537 int get_oid_treeish(const char *name, struct object_id *oid)
1539 struct object_context unused;
1540 return get_oid_with_context(name, GET_OID_TREEISH,
1544 int get_oid_commit(const char *name, struct object_id *oid)
1546 struct object_context unused;
1547 return get_oid_with_context(name, GET_OID_COMMIT,
1551 int get_oid_tree(const char *name, struct object_id *oid)
1553 struct object_context unused;
1554 return get_oid_with_context(name, GET_OID_TREE,
1558 int get_oid_blob(const char *name, struct object_id *oid)
1560 struct object_context unused;
1561 return get_oid_with_context(name, GET_OID_BLOB,
1565 /* Must be called only when object_name:filename doesn't exist. */
1566 static void diagnose_invalid_oid_path(const char *prefix,
1567 const char *filename,
1568 const struct object_id *tree_oid,
1569 const char *object_name,
1570 int object_name_len)
1572 struct object_id oid;
1578 if (file_exists(filename))
1579 die("Path '%s' exists on disk, but not in '%.*s'.",
1580 filename, object_name_len, object_name);
1581 if (is_missing_file_error(errno)) {
1582 char *fullname = xstrfmt("%s%s", prefix, filename);
1584 if (!get_tree_entry(tree_oid, fullname, &oid, &mode)) {
1585 die("Path '%s' exists, but not '%s'.\n"
1586 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1589 object_name_len, object_name,
1591 object_name_len, object_name,
1594 die("Path '%s' does not exist in '%.*s'",
1595 filename, object_name_len, object_name);
1599 /* Must be called only when :stage:filename doesn't exist. */
1600 static void diagnose_invalid_index_path(int stage,
1602 const char *filename)
1604 const struct cache_entry *ce;
1606 unsigned namelen = strlen(filename);
1607 struct strbuf fullname = STRBUF_INIT;
1612 /* Wrong stage number? */
1613 pos = cache_name_pos(filename, namelen);
1616 if (pos < active_nr) {
1617 ce = active_cache[pos];
1618 if (ce_namelen(ce) == namelen &&
1619 !memcmp(ce->name, filename, namelen))
1620 die("Path '%s' is in the index, but not at stage %d.\n"
1621 "Did you mean ':%d:%s'?",
1623 ce_stage(ce), filename);
1626 /* Confusion between relative and absolute filenames? */
1627 strbuf_addstr(&fullname, prefix);
1628 strbuf_addstr(&fullname, filename);
1629 pos = cache_name_pos(fullname.buf, fullname.len);
1632 if (pos < active_nr) {
1633 ce = active_cache[pos];
1634 if (ce_namelen(ce) == fullname.len &&
1635 !memcmp(ce->name, fullname.buf, fullname.len))
1636 die("Path '%s' is in the index, but not '%s'.\n"
1637 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1638 fullname.buf, filename,
1639 ce_stage(ce), fullname.buf,
1640 ce_stage(ce), filename);
1643 if (file_exists(filename))
1644 die("Path '%s' exists on disk, but not in the index.", filename);
1645 if (is_missing_file_error(errno))
1646 die("Path '%s' does not exist (neither on disk nor in the index).",
1649 strbuf_release(&fullname);
1653 static char *resolve_relative_path(const char *rel)
1655 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1658 if (!is_inside_work_tree())
1659 die("relative path syntax can't be used outside working tree.");
1661 /* die() inside prefix_path() if resolved path is outside worktree */
1662 return prefix_path(startup_info->prefix,
1663 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1667 static int get_oid_with_context_1(const char *name,
1670 struct object_id *oid,
1671 struct object_context *oc)
1673 int ret, bracket_depth;
1674 int namelen = strlen(name);
1676 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
1679 flags |= GET_OID_QUIETLY;
1681 memset(oc, 0, sizeof(*oc));
1682 oc->mode = S_IFINVALID;
1683 strbuf_init(&oc->symlink_path, 0);
1684 ret = get_oid_1(name, namelen, oid, flags);
1688 * sha1:path --> object name of path in ent sha1
1689 * :path -> object name of absolute path in index
1690 * :./path -> object name of path relative to cwd in index
1691 * :[0-3]:path -> object name of path in index at stage
1692 * :/foo -> recent commit matching foo
1694 if (name[0] == ':') {
1696 const struct cache_entry *ce;
1697 char *new_path = NULL;
1699 if (!only_to_die && namelen > 2 && name[1] == '/') {
1700 struct commit_list *list = NULL;
1702 for_each_ref(handle_one_ref, &list);
1703 head_ref(handle_one_ref, &list);
1704 commit_list_sort_by_date(&list);
1705 return get_oid_oneline(name + 2, oid, list);
1709 name[1] < '0' || '3' < name[1])
1712 stage = name[1] - '0';
1715 new_path = resolve_relative_path(cp);
1717 namelen = namelen - (cp - name);
1720 namelen = strlen(cp);
1723 if (flags & GET_OID_RECORD_PATH)
1724 oc->path = xstrdup(cp);
1728 pos = cache_name_pos(cp, namelen);
1731 while (pos < active_nr) {
1732 ce = active_cache[pos];
1733 if (ce_namelen(ce) != namelen ||
1734 memcmp(ce->name, cp, namelen))
1736 if (ce_stage(ce) == stage) {
1737 oidcpy(oid, &ce->oid);
1738 oc->mode = ce->ce_mode;
1744 if (only_to_die && name[1] && name[1] != '/')
1745 diagnose_invalid_index_path(stage, prefix, cp);
1749 for (cp = name, bracket_depth = 0; *cp; cp++) {
1752 else if (bracket_depth && *cp == '}')
1754 else if (!bracket_depth && *cp == ':')
1758 struct object_id tree_oid;
1759 int len = cp - name;
1760 unsigned sub_flags = flags;
1762 sub_flags &= ~GET_OID_DISAMBIGUATORS;
1763 sub_flags |= GET_OID_TREEISH;
1765 if (!get_oid_1(name, len, &tree_oid, sub_flags)) {
1766 const char *filename = cp+1;
1767 char *new_filename = NULL;
1769 new_filename = resolve_relative_path(filename);
1771 filename = new_filename;
1772 if (flags & GET_OID_FOLLOW_SYMLINKS) {
1773 ret = get_tree_entry_follow_symlinks(&tree_oid,
1774 filename, oid, &oc->symlink_path,
1777 ret = get_tree_entry(&tree_oid, filename, oid,
1779 if (ret && only_to_die) {
1780 diagnose_invalid_oid_path(prefix,
1786 if (flags & GET_OID_RECORD_PATH)
1787 oc->path = xstrdup(filename);
1793 die("Invalid object name '%.*s'.", len, name);
1800 * Call this function when you know "name" given by the end user must
1801 * name an object but it doesn't; the function _may_ die with a better
1802 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1803 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1804 * you have a chance to diagnose the error further.
1806 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1808 struct object_context oc;
1809 struct object_id oid;
1810 get_oid_with_context_1(name, GET_OID_ONLY_TO_DIE, prefix, &oid, &oc);
1813 int get_oid_with_context(const char *str, unsigned flags, struct object_id *oid, struct object_context *oc)
1815 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
1816 BUG("incompatible flags for get_sha1_with_context");
1817 return get_oid_with_context_1(str, flags, NULL, oid, oc);