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 append_loose_object(const struct object_id *oid, const char *path,
89 oid_array_append(data, oid);
93 static int match_sha(unsigned, const unsigned char *, const unsigned char *);
95 static void find_short_object_filename(struct disambiguate_state *ds)
97 int subdir_nr = ds->bin_pfx.hash[0];
98 struct alternate_object_database *alt;
99 static struct alternate_object_database *fakeent;
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.
109 fakeent = alloc_alt_odb(get_object_directory());
111 fakeent->next = the_repository->objects->alt_odb_list;
113 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
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,
121 &alt->loose_objects_cache);
122 alt->loose_objects_subdir_seen[subdir_nr] = 1;
125 pos = oid_array_lookup(&alt->loose_objects_cache, &ds->bin_pfx);
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))
133 update_candidates(ds, oid);
139 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
149 if ((*a ^ *b) & 0xf0)
154 static void unique_in_midx(struct multi_pack_index *m,
155 struct disambiguate_state *ds)
157 uint32_t num, i, first = 0;
158 const struct object_id *current = NULL;
159 num = m->num_objects;
164 bsearch_midx(&ds->bin_pfx, m, &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_midxed_object_oid(&oid, m, i);
174 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
176 update_candidates(ds, current);
180 static void unique_in_pack(struct packed_git *p,
181 struct disambiguate_state *ds)
183 uint32_t num, i, first = 0;
184 const struct object_id *current = NULL;
186 if (open_pack_index(p) || !p->num_objects)
189 num = p->num_objects;
190 bsearch_pack(&ds->bin_pfx, p, &first);
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).
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))
202 update_candidates(ds, current);
206 static void find_short_packed_object(struct disambiguate_state *ds)
208 struct multi_pack_index *m;
209 struct packed_git *p;
211 for (m = get_multi_pack_index(the_repository); m && !ds->ambiguous;
213 unique_in_midx(m, ds);
214 for (p = get_packed_git(the_repository); p && !ds->ambiguous;
216 unique_in_pack(p, ds);
219 #define SHORT_NAME_NOT_FOUND (-1)
220 #define SHORT_NAME_AMBIGUOUS (-2)
222 static int finish_object_disambiguation(struct disambiguate_state *ds,
223 struct object_id *oid)
226 return SHORT_NAME_AMBIGUOUS;
228 if (!ds->candidate_exists)
229 return SHORT_NAME_NOT_FOUND;
231 if (!ds->candidate_checked)
233 * If this is the only candidate, there is no point
234 * calling the disambiguation hint callback.
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
246 ds->candidate_ok = (!ds->disambiguate_fn_used ||
247 ds->fn(&ds->candidate, ds->cb_data));
249 if (!ds->candidate_ok)
250 return SHORT_NAME_AMBIGUOUS;
252 oidcpy(oid, &ds->candidate);
256 static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
258 int kind = oid_object_info(the_repository, oid, NULL);
259 return kind == OBJ_COMMIT;
262 static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
267 kind = oid_object_info(the_repository, oid, NULL);
268 if (kind == OBJ_COMMIT)
273 /* We need to do this the hard way... */
274 obj = deref_tag(the_repository, parse_object(the_repository, oid),
276 if (obj && obj->type == OBJ_COMMIT)
281 static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
283 int kind = oid_object_info(the_repository, oid, NULL);
284 return kind == OBJ_TREE;
287 static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
292 kind = oid_object_info(the_repository, oid, NULL);
293 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
298 /* We need to do this the hard way... */
299 obj = deref_tag(the_repository, parse_object(the_repository, oid),
301 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
306 static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
308 int kind = oid_object_info(the_repository, oid, NULL);
309 return kind == OBJ_BLOB;
312 static disambiguate_hint_fn default_disambiguate_hint;
314 int set_disambiguate_hint_config(const char *var, const char *value)
316 static const struct {
318 disambiguate_hint_fn fn;
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 }
330 return config_error_nonbool(var);
332 for (i = 0; i < ARRAY_SIZE(hints); i++) {
333 if (!strcasecmp(value, hints[i].name)) {
334 default_disambiguate_hint = hints[i].fn;
339 return error("unknown hint type for '%s': %s", var, value);
342 static int init_object_disambiguation(const char *name, int len,
343 struct disambiguate_state *ds)
347 if (len < MINIMUM_ABBREV || len > the_hash_algo->hexsz)
350 memset(ds, 0, sizeof(*ds));
352 for (i = 0; i < len ;i++) {
353 unsigned char c = name[i];
355 if (c >= '0' && c <= '9')
357 else if (c >= 'a' && c <= 'f')
359 else if (c >= 'A' && c <='F') {
368 ds->bin_pfx.hash[i >> 1] |= val;
372 ds->hex_pfx[len] = '\0';
373 prepare_alt_odb(the_repository);
377 static int show_ambiguous_object(const struct object_id *oid, void *data)
379 const struct disambiguate_state *ds = data;
380 struct strbuf desc = STRBUF_INIT;
383 if (ds->fn && !ds->fn(oid, ds->cb_data))
386 type = oid_object_info(the_repository, oid, NULL);
387 if (type == OBJ_COMMIT) {
388 struct commit *commit = lookup_commit(the_repository, oid);
390 struct pretty_print_context pp = {0};
391 pp.date_mode.type = DATE_SHORT;
392 format_commit_message(commit, " %ad - %s", &desc, &pp);
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);
401 find_unique_abbrev(oid, DEFAULT_ABBREV),
402 type_name(type) ? type_name(type) : "unknown type",
405 strbuf_release(&desc);
409 static int collect_ambiguous(const struct object_id *oid, void *data)
411 oid_array_append(data, oid);
415 static int sort_ambiguous(const void *a, const void *b)
417 int a_type = oid_object_info(the_repository, a, NULL);
418 int b_type = oid_object_info(the_repository, b, NULL);
423 * Sorts by hash within the same object type, just as
424 * oid_array_for_each_unique() would do.
426 if (a_type == b_type)
430 * Between object types show tags, then commits, and finally
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.
438 a_type_sort = a_type % 4;
439 b_type_sort = b_type % 4;
440 return a_type_sort > b_type_sort ? 1 : -1;
443 static int get_short_oid(const char *name, int len, struct object_id *oid,
447 struct disambiguate_state ds;
448 int quietly = !!(flags & GET_OID_QUIETLY);
450 if (init_object_disambiguation(name, len, &ds) < 0)
453 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
454 BUG("multiple get_short_oid disambiguator flags");
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;
467 ds.fn = default_disambiguate_hint;
469 find_short_object_filename(&ds);
470 find_short_packed_object(&ds);
471 status = finish_object_disambiguation(&ds, oid);
473 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
474 struct oid_array collect = OID_ARRAY_INIT;
476 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
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
487 advise(_("The candidates are:"));
488 for_each_abbrev(ds.hex_pfx, collect_ambiguous, &collect);
489 QSORT(collect.oid, collect.nr, sort_ambiguous);
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);
499 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
501 struct oid_array collect = OID_ARRAY_INIT;
502 struct disambiguate_state ds;
505 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
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);
514 ret = oid_array_for_each_unique(&collect, fn, cb_data);
515 oid_array_clear(&collect);
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.
524 static unsigned msb(unsigned long val)
532 struct min_abbrev_data {
533 unsigned int init_len;
534 unsigned int cur_len;
536 const struct object_id *oid;
539 static inline char get_hex_char_from_oid(const struct object_id *oid,
542 static const char hex[] = "0123456789abcdef";
545 return hex[oid->hash[pos >> 1] >> 4];
547 return hex[oid->hash[pos >> 1] & 0xf];
550 static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
552 struct min_abbrev_data *mad = cb_data;
554 unsigned int i = mad->init_len;
555 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
558 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
559 mad->cur_len = i + 1;
564 static void find_abbrev_len_for_midx(struct multi_pack_index *m,
565 struct min_abbrev_data *mad)
568 uint32_t num, first = 0;
569 struct object_id oid;
570 const struct object_id *mad_oid;
575 num = m->num_objects;
577 match = bsearch_midx(mad_oid, m, &first);
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.
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);
594 if (nth_midxed_object_oid(&oid, m, first - 1))
595 extend_abbrev_len(&oid, mad);
597 mad->init_len = mad->cur_len;
600 static void find_abbrev_len_for_pack(struct packed_git *p,
601 struct min_abbrev_data *mad)
604 uint32_t num, first = 0;
605 struct object_id oid;
606 const struct object_id *mad_oid;
608 if (open_pack_index(p) || !p->num_objects)
611 num = p->num_objects;
613 match = bsearch_pack(mad_oid, p, &first);
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.
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);
630 if (nth_packed_object_oid(&oid, p, first - 1))
631 extend_abbrev_len(&oid, mad);
633 mad->init_len = mad->cur_len;
636 static void find_abbrev_len_packed(struct min_abbrev_data *mad)
638 struct multi_pack_index *m;
639 struct packed_git *p;
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);
647 int find_unique_abbrev_r(char *hex, const struct object_id *oid, int len)
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;
655 unsigned long count = approximate_object_count();
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.
661 len = msb(count) + 1;
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.
668 len = DIV_ROUND_UP(len, 2);
670 * For very small repos, we stick with our regular fallback.
672 if (len < FALLBACK_DEFAULT_ABBREV)
673 len = FALLBACK_DEFAULT_ABBREV;
676 oid_to_hex_r(hex, oid);
677 if (len == hexsz || !len)
685 find_abbrev_len_packed(&mad);
687 if (init_object_disambiguation(hex, mad.cur_len, &ds) < 0)
690 ds.fn = extend_abbrev_len;
691 ds.always_call_fn = 1;
692 ds.cb_data = (void *)&mad;
694 find_short_object_filename(&ds);
695 (void)finish_object_disambiguation(&ds, &oid_ret);
697 hex[mad.cur_len] = 0;
701 const char *find_unique_abbrev(const struct object_id *oid, int len)
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);
711 static int ambiguous_path(const char *path, int len)
716 for (cnt = 0; cnt < len; cnt++) {
736 static inline int at_mark(const char *string, int len,
737 const char **suffix, int nr)
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))
750 static inline int upstream_mark(const char *string, int len)
752 const char *suffix[] = { "@{upstream}", "@{u}" };
753 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
756 static inline int push_mark(const char *string, int len)
758 const char *suffix[] = { "@{push}" };
759 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
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);
765 static int get_oid_basic(const char *str, int len, struct object_id *oid,
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"
774 " git checkout -b $br $(git rev-parse ...)\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;
782 int at, reflog_len, nth_prior = 0;
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));
797 /* basic@{time or number or -number} format to query ref-log */
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] == '-') {
804 /* @{-N} not at start */
809 if (!upstream_mark(str + at, len - at) &&
810 !push_mark(str + at, len - at)) {
811 reflog_len = (len-1) - (at+2);
819 /* Accept only unambiguous ref paths. */
820 if (len && ambiguous_path(str, len))
824 struct strbuf buf = STRBUF_INIT;
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);
835 if (!len && reflog_len)
836 /* allow "@{...}" to mean the current branch reflog */
837 refs_found = dwim_ref("HEAD", 4, oid, &real_ref);
839 refs_found = dwim_log(str, len, oid, &real_ref);
841 refs_found = dwim_ref(str, len, oid, &real_ref);
846 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
848 !get_short_oid(str, len, &tmp_oid, GET_OID_QUIETLY)))
849 warning(warn_msg, len, str);
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';
865 if (100000000 <= nth) {
872 char *tmp = xstrndup(str + at + 2, reflog_len);
873 at_time = approxidate_careful(tmp, &errors);
880 if (read_ref_at(real_ref, flags, at_time, nth, oid, NULL,
881 &co_time, &co_tz, &co_cnt)) {
883 if (starts_with(real_ref, "refs/heads/")) {
885 len = strlen(real_ref + 11);
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)));
899 if (flags & GET_OID_QUIETLY) {
902 die("Log for '%.*s' only has %d entries.",
912 static int get_parent(const char *name, int len,
913 struct object_id *result, int idx)
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;
922 commit = lookup_commit_reference(the_repository, &oid);
923 if (parse_commit(commit))
926 oidcpy(result, &commit->object.oid);
932 oidcpy(result, &p->item->object.oid);
940 static int get_nth_ancestor(const char *name, int len,
941 struct object_id *result, int generation)
943 struct object_id oid;
944 struct commit *commit;
947 ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
950 commit = lookup_commit_reference(the_repository, &oid);
954 while (generation--) {
955 if (parse_commit(commit) || !commit->parents)
957 commit = commit->parents->item;
959 oidcpy(result, &commit->object.oid);
963 struct object *peel_to_type(const char *name, int namelen,
964 struct object *o, enum object_type expected_type)
966 if (name && !namelen)
967 namelen = strlen(name);
969 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
971 if (expected_type == OBJ_ANY || o->type == expected_type)
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);
979 error("%.*s: expected %s type, but the object "
980 "dereferences to %s type",
981 namelen, name, type_name(expected_type),
988 static int peel_onion(const char *name, int len, struct object_id *oid,
989 unsigned lookup_flags)
991 struct object_id outer;
993 unsigned int expected_type = 0;
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.
1004 if (len < 4 || name[len-1] != '}')
1007 for (sp = name + len - 1; name <= sp; sp--) {
1009 if (ch == '{' && name < sp && sp[-1] == '^')
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;
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;
1039 if (get_oid_1(name, sp - name - 2, &outer, lookup_flags))
1042 o = parse_object(the_repository, &outer);
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)))
1049 oidcpy(oid, &o->oid);
1054 * At this point, the syntax look correct, so
1055 * if we do not get the needed object, we should
1058 o = peel_to_type(name, len, o, expected_type);
1062 oidcpy(oid, &o->oid);
1064 /* "$commit^{/foo}" */
1067 struct commit_list *list = NULL;
1070 * $commit^{/}. Some regex implementation may reject.
1071 * We don't need regex anyway. '' pattern always matches.
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);
1085 static int get_describe_name(const char *name, int len, struct object_id *oid)
1088 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
1090 for (cp = name + len - 1; name + 2 <= cp; cp--) {
1092 if (!isxdigit(ch)) {
1093 /* We must be looking at g in "SOMETHING-g"
1094 * for it to be describe output.
1096 if (ch == 'g' && cp[-1] == '-') {
1099 return get_short_oid(cp, len, oid, flags);
1106 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags)
1108 int ret, has_suffix;
1112 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1115 for (cp = name + len - 1; name <= cp; cp--) {
1117 if ('0' <= ch && ch <= '9')
1119 if (ch == '~' || ch == '^')
1126 int len1 = cp - name;
1128 while (cp < name + len)
1129 num = num * 10 + *cp++ - '0';
1130 if (!num && len1 == len - 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);
1138 ret = peel_onion(name, len, oid, lookup_flags);
1142 ret = get_oid_basic(name, len, oid, lookup_flags);
1146 /* It could be describe output that is "SOMETHING-gXXXX" */
1147 ret = get_describe_name(name, len, oid);
1151 return get_short_oid(name, len, oid, lookup_flags);
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.
1159 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1161 * For a literal '!' character at the beginning of a pattern, you have to repeat
1162 * that, like: ':/!!foo'
1164 * For future extension, all other sequences beginning with ':/!' are reserved.
1167 /* Remember to update object flag allocation in object.h */
1168 #define ONELINE_SEEN (1u<<20)
1170 static int handle_one_ref(const char *path, const struct object_id *oid,
1171 int flag, void *cb_data)
1173 struct commit_list **list = cb_data;
1174 struct object *object = parse_object(the_repository, oid);
1177 if (object->type == OBJ_TAG) {
1178 object = deref_tag(the_repository, object, path,
1183 if (object->type != OBJ_COMMIT)
1185 commit_list_insert((struct commit *)object, list);
1189 static int get_oid_oneline(const char *prefix, struct object_id *oid,
1190 struct commit_list *list)
1192 struct commit_list *backup = NULL, *l;
1197 if (prefix[0] == '!') {
1200 if (prefix[0] == '-') {
1203 } else if (prefix[0] != '!') {
1208 if (regcomp(®ex, prefix, REG_EXTENDED))
1211 for (l = list; l; l = l->next) {
1212 l->item->object.flags |= ONELINE_SEEN;
1213 commit_list_insert(l->item, &backup);
1216 const char *p, *buf;
1217 struct commit *commit;
1220 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1221 if (!parse_object(the_repository, &commit->object.oid))
1223 buf = get_commit_buffer(commit, NULL);
1224 p = strstr(buf, "\n\n");
1225 matches = negative ^ (p && !regexec(®ex, p + 2, 0, NULL, 0));
1226 unuse_commit_buffer(commit, buf);
1229 oidcpy(oid, &commit->object.oid);
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;
1242 struct grab_nth_branch_switch_cbdata {
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)
1251 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1252 const char *match = NULL, *target = NULL;
1255 if (skip_prefix(message, "checkout: moving from ", &match))
1256 target = strstr(match, " to ");
1258 if (!match || !target)
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 */
1270 * Parse @{-N} syntax, return the number of characters parsed
1271 * if successful; otherwise signal an error with negative value.
1273 static int interpret_nth_prior_checkout(const char *name, int namelen,
1278 struct grab_nth_branch_switch_cbdata cb;
1284 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1286 brace = memchr(name, '}', namelen);
1289 nth = strtol(name + 3, &num_end, 10);
1290 if (num_end != brace)
1295 strbuf_init(&cb.buf, 20);
1298 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1300 strbuf_addbuf(buf, &cb.buf);
1301 retval = brace - name + 1;
1304 strbuf_release(&cb.buf);
1308 int get_oid_mb(const char *name, struct object_id *oid)
1310 struct commit *one, *two;
1311 struct commit_list *mbs;
1312 struct object_id oid_tmp;
1316 dots = strstr(name, "...");
1318 return get_oid(name, oid);
1320 st = get_oid("HEAD", &oid_tmp);
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);
1330 one = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1334 if (get_oid_committish(dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1336 two = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1339 mbs = get_merge_bases(one, two);
1340 if (!mbs || mbs->next)
1344 oidcpy(oid, &mbs->item->object.oid);
1346 free_commit_list(mbs);
1350 /* parse @something syntax, when 'something' is not {.*} */
1351 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1355 if (len || name[1] == '{')
1358 /* make sure it's a single @, or @@{.*}, not @foo */
1359 next = memchr(name + len + 1, '@', namelen - len - 1);
1360 if (next && next[1] != '{')
1363 next = name + namelen;
1364 if (next != name + 1)
1368 strbuf_add(buf, "HEAD", 4);
1372 static int reinterpret(const char *name, int namelen, int len,
1373 struct strbuf *buf, unsigned allowed)
1375 /* we have extra data, which might need further processing */
1376 struct strbuf tmp = STRBUF_INIT;
1377 int used = buf->len;
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 */
1384 strbuf_setlen(buf, used);
1388 strbuf_addbuf(buf, &tmp);
1389 strbuf_release(&tmp);
1390 /* tweak for size of {-N} versus expanded ref name */
1391 return ret - used + len;
1394 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1396 char *s = shorten_unambiguous_ref(ref, 0);
1398 strbuf_addstr(buf, s);
1402 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1407 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1408 starts_with(refname, "refs/heads/"))
1410 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1411 starts_with(refname, "refs/remotes/"))
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 *,
1425 struct branch *branch;
1426 struct strbuf err = STRBUF_INIT;
1429 len = get_mark(name + at, namelen - at);
1433 if (memchr(name, ':', at))
1437 char *name_str = xmemdupz(name, at);
1438 branch = branch_get(name_str);
1441 branch = branch_get(NULL);
1443 value = get_data(branch, &err);
1447 if (!branch_interpret_allowed(value, allowed))
1450 set_shortened_ref(buf, value);
1454 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf,
1462 namelen = strlen(name);
1464 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1465 len = interpret_nth_prior_checkout(name, namelen, buf);
1467 return len; /* syntax Ok, not enough switches */
1468 } else if (len > 0) {
1470 return len; /* consumed all */
1472 return reinterpret(name, namelen, len, buf, allowed);
1477 (at = memchr(start, '@', namelen - (start - name)));
1480 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1481 len = interpret_empty_at(name, namelen, at - name, buf);
1483 return reinterpret(name, namelen, len, buf,
1487 len = interpret_branch_mark(name, namelen, at - name, buf,
1488 upstream_mark, branch_get_upstream,
1493 len = interpret_branch_mark(name, namelen, at - name, buf,
1494 push_mark, branch_get_push,
1503 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1505 int len = strlen(name);
1506 int used = interpret_branch_name(name, len, sb, allowed);
1510 strbuf_add(sb, name + used, len - used);
1513 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1515 if (startup_info->have_repository)
1516 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1518 strbuf_addstr(sb, name);
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.
1526 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1529 !strcmp(sb->buf, "refs/heads/HEAD"))
1532 return check_refname_format(sb->buf, 0);
1536 * This is like "get_oid_basic()", except it allows "object ID expressions",
1537 * notably "xyz^" for "parent of xyz"
1539 int get_oid(const char *name, struct object_id *oid)
1541 struct object_context unused;
1542 return get_oid_with_context(name, 0, oid, &unused);
1547 * Many callers know that the user meant to name a commit-ish by
1548 * syntactical positions where the object name appears. Calling this
1549 * function allows the machinery to disambiguate shorter-than-unique
1550 * abbreviated object names between commit-ish and others.
1552 * Note that this does NOT error out when the named object is not a
1553 * commit-ish. It is merely to give a hint to the disambiguation
1556 int get_oid_committish(const char *name, struct object_id *oid)
1558 struct object_context unused;
1559 return get_oid_with_context(name, GET_OID_COMMITTISH,
1563 int get_oid_treeish(const char *name, struct object_id *oid)
1565 struct object_context unused;
1566 return get_oid_with_context(name, GET_OID_TREEISH,
1570 int get_oid_commit(const char *name, struct object_id *oid)
1572 struct object_context unused;
1573 return get_oid_with_context(name, GET_OID_COMMIT,
1577 int get_oid_tree(const char *name, struct object_id *oid)
1579 struct object_context unused;
1580 return get_oid_with_context(name, GET_OID_TREE,
1584 int get_oid_blob(const char *name, struct object_id *oid)
1586 struct object_context unused;
1587 return get_oid_with_context(name, GET_OID_BLOB,
1591 /* Must be called only when object_name:filename doesn't exist. */
1592 static void diagnose_invalid_oid_path(const char *prefix,
1593 const char *filename,
1594 const struct object_id *tree_oid,
1595 const char *object_name,
1596 int object_name_len)
1598 struct object_id oid;
1604 if (file_exists(filename))
1605 die("Path '%s' exists on disk, but not in '%.*s'.",
1606 filename, object_name_len, object_name);
1607 if (is_missing_file_error(errno)) {
1608 char *fullname = xstrfmt("%s%s", prefix, filename);
1610 if (!get_tree_entry(tree_oid, fullname, &oid, &mode)) {
1611 die("Path '%s' exists, but not '%s'.\n"
1612 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1615 object_name_len, object_name,
1617 object_name_len, object_name,
1620 die("Path '%s' does not exist in '%.*s'",
1621 filename, object_name_len, object_name);
1625 /* Must be called only when :stage:filename doesn't exist. */
1626 static void diagnose_invalid_index_path(int stage,
1628 const char *filename)
1630 const struct cache_entry *ce;
1632 unsigned namelen = strlen(filename);
1633 struct strbuf fullname = STRBUF_INIT;
1638 /* Wrong stage number? */
1639 pos = cache_name_pos(filename, namelen);
1642 if (pos < active_nr) {
1643 ce = active_cache[pos];
1644 if (ce_namelen(ce) == namelen &&
1645 !memcmp(ce->name, filename, namelen))
1646 die("Path '%s' is in the index, but not at stage %d.\n"
1647 "Did you mean ':%d:%s'?",
1649 ce_stage(ce), filename);
1652 /* Confusion between relative and absolute filenames? */
1653 strbuf_addstr(&fullname, prefix);
1654 strbuf_addstr(&fullname, filename);
1655 pos = cache_name_pos(fullname.buf, fullname.len);
1658 if (pos < active_nr) {
1659 ce = active_cache[pos];
1660 if (ce_namelen(ce) == fullname.len &&
1661 !memcmp(ce->name, fullname.buf, fullname.len))
1662 die("Path '%s' is in the index, but not '%s'.\n"
1663 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1664 fullname.buf, filename,
1665 ce_stage(ce), fullname.buf,
1666 ce_stage(ce), filename);
1669 if (file_exists(filename))
1670 die("Path '%s' exists on disk, but not in the index.", filename);
1671 if (is_missing_file_error(errno))
1672 die("Path '%s' does not exist (neither on disk nor in the index).",
1675 strbuf_release(&fullname);
1679 static char *resolve_relative_path(const char *rel)
1681 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1684 if (!is_inside_work_tree())
1685 die("relative path syntax can't be used outside working tree.");
1687 /* die() inside prefix_path() if resolved path is outside worktree */
1688 return prefix_path(startup_info->prefix,
1689 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1693 static int get_oid_with_context_1(const char *name,
1696 struct object_id *oid,
1697 struct object_context *oc)
1699 int ret, bracket_depth;
1700 int namelen = strlen(name);
1702 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
1705 flags |= GET_OID_QUIETLY;
1707 memset(oc, 0, sizeof(*oc));
1708 oc->mode = S_IFINVALID;
1709 strbuf_init(&oc->symlink_path, 0);
1710 ret = get_oid_1(name, namelen, oid, flags);
1714 * sha1:path --> object name of path in ent sha1
1715 * :path -> object name of absolute path in index
1716 * :./path -> object name of path relative to cwd in index
1717 * :[0-3]:path -> object name of path in index at stage
1718 * :/foo -> recent commit matching foo
1720 if (name[0] == ':') {
1722 const struct cache_entry *ce;
1723 char *new_path = NULL;
1725 if (!only_to_die && namelen > 2 && name[1] == '/') {
1726 struct commit_list *list = NULL;
1728 for_each_ref(handle_one_ref, &list);
1729 head_ref(handle_one_ref, &list);
1730 commit_list_sort_by_date(&list);
1731 return get_oid_oneline(name + 2, oid, list);
1735 name[1] < '0' || '3' < name[1])
1738 stage = name[1] - '0';
1741 new_path = resolve_relative_path(cp);
1743 namelen = namelen - (cp - name);
1746 namelen = strlen(cp);
1749 if (flags & GET_OID_RECORD_PATH)
1750 oc->path = xstrdup(cp);
1754 pos = cache_name_pos(cp, namelen);
1757 while (pos < active_nr) {
1758 ce = active_cache[pos];
1759 if (ce_namelen(ce) != namelen ||
1760 memcmp(ce->name, cp, namelen))
1762 if (ce_stage(ce) == stage) {
1763 oidcpy(oid, &ce->oid);
1764 oc->mode = ce->ce_mode;
1770 if (only_to_die && name[1] && name[1] != '/')
1771 diagnose_invalid_index_path(stage, prefix, cp);
1775 for (cp = name, bracket_depth = 0; *cp; cp++) {
1778 else if (bracket_depth && *cp == '}')
1780 else if (!bracket_depth && *cp == ':')
1784 struct object_id tree_oid;
1785 int len = cp - name;
1786 unsigned sub_flags = flags;
1788 sub_flags &= ~GET_OID_DISAMBIGUATORS;
1789 sub_flags |= GET_OID_TREEISH;
1791 if (!get_oid_1(name, len, &tree_oid, sub_flags)) {
1792 const char *filename = cp+1;
1793 char *new_filename = NULL;
1795 new_filename = resolve_relative_path(filename);
1797 filename = new_filename;
1798 if (flags & GET_OID_FOLLOW_SYMLINKS) {
1799 ret = get_tree_entry_follow_symlinks(&tree_oid,
1800 filename, oid, &oc->symlink_path,
1803 ret = get_tree_entry(&tree_oid, filename, oid,
1805 if (ret && only_to_die) {
1806 diagnose_invalid_oid_path(prefix,
1812 if (flags & GET_OID_RECORD_PATH)
1813 oc->path = xstrdup(filename);
1819 die("Invalid object name '%.*s'.", len, name);
1826 * Call this function when you know "name" given by the end user must
1827 * name an object but it doesn't; the function _may_ die with a better
1828 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1829 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1830 * you have a chance to diagnose the error further.
1832 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1834 struct object_context oc;
1835 struct object_id oid;
1836 get_oid_with_context_1(name, GET_OID_ONLY_TO_DIE, prefix, &oid, &oc);
1839 int get_oid_with_context(const char *str, unsigned flags, struct object_id *oid, struct object_context *oc)
1841 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
1842 BUG("incompatible flags for get_sha1_with_context");
1843 return get_oid_with_context_1(str, flags, NULL, oid, oc);