11 #include "sha1-array.h"
13 #include "object-store.h"
14 #include "repository.h"
16 static int get_oid_oneline(const char *, struct object_id *, struct commit_list *);
18 typedef int (*disambiguate_hint_fn)(const struct object_id *, void *);
20 struct disambiguate_state {
21 int len; /* length of prefix in hex chars */
22 char hex_pfx[GIT_MAX_HEXSZ + 1];
23 struct object_id bin_pfx;
25 disambiguate_hint_fn fn;
27 struct object_id candidate;
28 unsigned candidate_exists:1;
29 unsigned candidate_checked:1;
30 unsigned candidate_ok:1;
31 unsigned disambiguate_fn_used:1;
33 unsigned always_call_fn:1;
36 static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
38 if (ds->always_call_fn) {
39 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
42 if (!ds->candidate_exists) {
43 /* this is the first candidate */
44 oidcpy(&ds->candidate, current);
45 ds->candidate_exists = 1;
47 } else if (!oidcmp(&ds->candidate, current)) {
48 /* the same as what we already have seen */
53 /* cannot disambiguate between ds->candidate and current */
58 if (!ds->candidate_checked) {
59 ds->candidate_ok = ds->fn(&ds->candidate, ds->cb_data);
60 ds->disambiguate_fn_used = 1;
61 ds->candidate_checked = 1;
64 if (!ds->candidate_ok) {
65 /* discard the candidate; we know it does not satisfy fn */
66 oidcpy(&ds->candidate, current);
67 ds->candidate_checked = 0;
71 /* if we reach this point, we know ds->candidate satisfies fn */
72 if (ds->fn(current, ds->cb_data)) {
74 * if both current and candidate satisfy fn, we cannot
81 /* otherwise, current can be discarded and candidate is still good */
84 static int append_loose_object(const struct object_id *oid, const char *path,
87 oid_array_append(data, oid);
91 static int match_sha(unsigned, const unsigned char *, const unsigned char *);
93 static void find_short_object_filename(struct disambiguate_state *ds)
95 int subdir_nr = ds->bin_pfx.hash[0];
96 struct alternate_object_database *alt;
97 static struct alternate_object_database *fakeent;
101 * Create a "fake" alternate object database that
102 * points to our own object database, to make it
103 * easier to get a temporary working space in
104 * alt->name/alt->base while iterating over the
105 * object databases including our own.
107 fakeent = alloc_alt_odb(get_object_directory());
109 fakeent->next = the_repository->objects->alt_odb_list;
111 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
114 if (!alt->loose_objects_subdir_seen[subdir_nr]) {
115 struct strbuf *buf = alt_scratch_buf(alt);
116 for_each_file_in_obj_subdir(subdir_nr, buf,
119 &alt->loose_objects_cache);
120 alt->loose_objects_subdir_seen[subdir_nr] = 1;
123 pos = oid_array_lookup(&alt->loose_objects_cache, &ds->bin_pfx);
126 while (!ds->ambiguous && pos < alt->loose_objects_cache.nr) {
127 const struct object_id *oid;
128 oid = alt->loose_objects_cache.oid + pos;
129 if (!match_sha(ds->len, ds->bin_pfx.hash, oid->hash))
131 update_candidates(ds, oid);
137 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
147 if ((*a ^ *b) & 0xf0)
152 static void unique_in_pack(struct packed_git *p,
153 struct disambiguate_state *ds)
155 uint32_t num, i, first = 0;
156 const struct object_id *current = NULL;
158 if (open_pack_index(p) || !p->num_objects)
161 num = p->num_objects;
162 bsearch_pack(&ds->bin_pfx, p, &first);
165 * At this point, "first" is the location of the lowest object
166 * with an object name that could match "bin_pfx". See if we have
167 * 0, 1 or more objects that actually match(es).
169 for (i = first; i < num && !ds->ambiguous; i++) {
170 struct object_id oid;
171 current = nth_packed_object_oid(&oid, p, i);
172 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
174 update_candidates(ds, current);
178 static void find_short_packed_object(struct disambiguate_state *ds)
180 struct packed_git *p;
182 for (p = get_packed_git(the_repository); p && !ds->ambiguous;
184 unique_in_pack(p, ds);
187 #define SHORT_NAME_NOT_FOUND (-1)
188 #define SHORT_NAME_AMBIGUOUS (-2)
190 static int finish_object_disambiguation(struct disambiguate_state *ds,
191 struct object_id *oid)
194 return SHORT_NAME_AMBIGUOUS;
196 if (!ds->candidate_exists)
197 return SHORT_NAME_NOT_FOUND;
199 if (!ds->candidate_checked)
201 * If this is the only candidate, there is no point
202 * calling the disambiguation hint callback.
204 * On the other hand, if the current candidate
205 * replaced an earlier candidate that did _not_ pass
206 * the disambiguation hint callback, then we do have
207 * more than one objects that match the short name
208 * given, so we should make sure this one matches;
209 * otherwise, if we discovered this one and the one
210 * that we previously discarded in the reverse order,
211 * we would end up showing different results in the
214 ds->candidate_ok = (!ds->disambiguate_fn_used ||
215 ds->fn(&ds->candidate, ds->cb_data));
217 if (!ds->candidate_ok)
218 return SHORT_NAME_AMBIGUOUS;
220 oidcpy(oid, &ds->candidate);
224 static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
226 int kind = oid_object_info(the_repository, oid, NULL);
227 return kind == OBJ_COMMIT;
230 static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
235 kind = oid_object_info(the_repository, oid, NULL);
236 if (kind == OBJ_COMMIT)
241 /* We need to do this the hard way... */
242 obj = deref_tag(the_repository, parse_object(the_repository, oid),
244 if (obj && obj->type == OBJ_COMMIT)
249 static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
251 int kind = oid_object_info(the_repository, oid, NULL);
252 return kind == OBJ_TREE;
255 static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
260 kind = oid_object_info(the_repository, oid, NULL);
261 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
266 /* We need to do this the hard way... */
267 obj = deref_tag(the_repository, parse_object(the_repository, oid),
269 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
274 static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
276 int kind = oid_object_info(the_repository, oid, NULL);
277 return kind == OBJ_BLOB;
280 static disambiguate_hint_fn default_disambiguate_hint;
282 int set_disambiguate_hint_config(const char *var, const char *value)
284 static const struct {
286 disambiguate_hint_fn fn;
289 { "commit", disambiguate_commit_only },
290 { "committish", disambiguate_committish_only },
291 { "tree", disambiguate_tree_only },
292 { "treeish", disambiguate_treeish_only },
293 { "blob", disambiguate_blob_only }
298 return config_error_nonbool(var);
300 for (i = 0; i < ARRAY_SIZE(hints); i++) {
301 if (!strcasecmp(value, hints[i].name)) {
302 default_disambiguate_hint = hints[i].fn;
307 return error("unknown hint type for '%s': %s", var, value);
310 static int init_object_disambiguation(const char *name, int len,
311 struct disambiguate_state *ds)
315 if (len < MINIMUM_ABBREV || len > the_hash_algo->hexsz)
318 memset(ds, 0, sizeof(*ds));
320 for (i = 0; i < len ;i++) {
321 unsigned char c = name[i];
323 if (c >= '0' && c <= '9')
325 else if (c >= 'a' && c <= 'f')
327 else if (c >= 'A' && c <='F') {
336 ds->bin_pfx.hash[i >> 1] |= val;
340 ds->hex_pfx[len] = '\0';
341 prepare_alt_odb(the_repository);
345 static int show_ambiguous_object(const struct object_id *oid, void *data)
347 const struct disambiguate_state *ds = data;
348 struct strbuf desc = STRBUF_INIT;
351 if (ds->fn && !ds->fn(oid, ds->cb_data))
354 type = oid_object_info(the_repository, oid, NULL);
355 if (type == OBJ_COMMIT) {
356 struct commit *commit = lookup_commit(the_repository, oid);
358 struct pretty_print_context pp = {0};
359 pp.date_mode.type = DATE_SHORT;
360 format_commit_message(commit, " %ad - %s", &desc, &pp);
362 } else if (type == OBJ_TAG) {
363 struct tag *tag = lookup_tag(the_repository, oid);
364 if (!parse_tag(tag) && tag->tag)
365 strbuf_addf(&desc, " %s", tag->tag);
369 find_unique_abbrev(oid, DEFAULT_ABBREV),
370 type_name(type) ? type_name(type) : "unknown type",
373 strbuf_release(&desc);
377 static int collect_ambiguous(const struct object_id *oid, void *data)
379 oid_array_append(data, oid);
383 static int sort_ambiguous(const void *a, const void *b)
385 int a_type = oid_object_info(the_repository, a, NULL);
386 int b_type = oid_object_info(the_repository, b, NULL);
391 * Sorts by hash within the same object type, just as
392 * oid_array_for_each_unique() would do.
394 if (a_type == b_type)
398 * Between object types show tags, then commits, and finally
401 * The object_type enum is commit, tree, blob, tag, but we
402 * want tag, commit, tree blob. Cleverly (perhaps too
403 * cleverly) do that with modulus, since the enum assigns 1 to
404 * commit, so tag becomes 0.
406 a_type_sort = a_type % 4;
407 b_type_sort = b_type % 4;
408 return a_type_sort > b_type_sort ? 1 : -1;
411 static int get_short_oid(const char *name, int len, struct object_id *oid,
415 struct disambiguate_state ds;
416 int quietly = !!(flags & GET_OID_QUIETLY);
418 if (init_object_disambiguation(name, len, &ds) < 0)
421 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
422 BUG("multiple get_short_oid disambiguator flags");
424 if (flags & GET_OID_COMMIT)
425 ds.fn = disambiguate_commit_only;
426 else if (flags & GET_OID_COMMITTISH)
427 ds.fn = disambiguate_committish_only;
428 else if (flags & GET_OID_TREE)
429 ds.fn = disambiguate_tree_only;
430 else if (flags & GET_OID_TREEISH)
431 ds.fn = disambiguate_treeish_only;
432 else if (flags & GET_OID_BLOB)
433 ds.fn = disambiguate_blob_only;
435 ds.fn = default_disambiguate_hint;
437 find_short_object_filename(&ds);
438 find_short_packed_object(&ds);
439 status = finish_object_disambiguation(&ds, oid);
441 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
442 struct oid_array collect = OID_ARRAY_INIT;
444 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
447 * We may still have ambiguity if we simply saw a series of
448 * candidates that did not satisfy our hint function. In
449 * that case, we still want to show them, so disable the hint
455 advise(_("The candidates are:"));
456 for_each_abbrev(ds.hex_pfx, collect_ambiguous, &collect);
457 QSORT(collect.oid, collect.nr, sort_ambiguous);
459 if (oid_array_for_each(&collect, show_ambiguous_object, &ds))
460 BUG("show_ambiguous_object shouldn't return non-zero");
461 oid_array_clear(&collect);
467 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
469 struct oid_array collect = OID_ARRAY_INIT;
470 struct disambiguate_state ds;
473 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
476 ds.always_call_fn = 1;
477 ds.fn = collect_ambiguous;
478 ds.cb_data = &collect;
479 find_short_object_filename(&ds);
480 find_short_packed_object(&ds);
482 ret = oid_array_for_each_unique(&collect, fn, cb_data);
483 oid_array_clear(&collect);
488 * Return the slot of the most-significant bit set in "val". There are various
489 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
490 * probably not a big deal here.
492 static unsigned msb(unsigned long val)
500 struct min_abbrev_data {
501 unsigned int init_len;
502 unsigned int cur_len;
504 const struct object_id *oid;
507 static inline char get_hex_char_from_oid(const struct object_id *oid,
510 static const char hex[] = "0123456789abcdef";
513 return hex[oid->hash[pos >> 1] >> 4];
515 return hex[oid->hash[pos >> 1] & 0xf];
518 static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
520 struct min_abbrev_data *mad = cb_data;
522 unsigned int i = mad->init_len;
523 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
526 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
527 mad->cur_len = i + 1;
532 static void find_abbrev_len_for_pack(struct packed_git *p,
533 struct min_abbrev_data *mad)
536 uint32_t num, first = 0;
537 struct object_id oid;
538 const struct object_id *mad_oid;
540 if (open_pack_index(p) || !p->num_objects)
543 num = p->num_objects;
545 match = bsearch_pack(mad_oid, p, &first);
548 * first is now the position in the packfile where we would insert
549 * mad->hash if it does not exist (or the position of mad->hash if
550 * it does exist). Hence, we consider a maximum of two objects
551 * nearby for the abbreviation length.
555 if (nth_packed_object_oid(&oid, p, first))
556 extend_abbrev_len(&oid, mad);
557 } else if (first < num - 1) {
558 if (nth_packed_object_oid(&oid, p, first + 1))
559 extend_abbrev_len(&oid, mad);
562 if (nth_packed_object_oid(&oid, p, first - 1))
563 extend_abbrev_len(&oid, mad);
565 mad->init_len = mad->cur_len;
568 static void find_abbrev_len_packed(struct min_abbrev_data *mad)
570 struct packed_git *p;
572 for (p = get_packed_git(the_repository); p; p = p->next)
573 find_abbrev_len_for_pack(p, mad);
576 int find_unique_abbrev_r(char *hex, const struct object_id *oid, int len)
578 struct disambiguate_state ds;
579 struct min_abbrev_data mad;
580 struct object_id oid_ret;
581 const unsigned hexsz = the_hash_algo->hexsz;
584 unsigned long count = approximate_object_count();
586 * Add one because the MSB only tells us the highest bit set,
587 * not including the value of all the _other_ bits (so "15"
588 * is only one off of 2^4, but the MSB is the 3rd bit.
590 len = msb(count) + 1;
592 * We now know we have on the order of 2^len objects, which
593 * expects a collision at 2^(len/2). But we also care about hex
594 * chars, not bits, and there are 4 bits per hex. So all
595 * together we need to divide by 2 and round up.
597 len = DIV_ROUND_UP(len, 2);
599 * For very small repos, we stick with our regular fallback.
601 if (len < FALLBACK_DEFAULT_ABBREV)
602 len = FALLBACK_DEFAULT_ABBREV;
605 oid_to_hex_r(hex, oid);
606 if (len == hexsz || !len)
614 find_abbrev_len_packed(&mad);
616 if (init_object_disambiguation(hex, mad.cur_len, &ds) < 0)
619 ds.fn = extend_abbrev_len;
620 ds.always_call_fn = 1;
621 ds.cb_data = (void *)&mad;
623 find_short_object_filename(&ds);
624 (void)finish_object_disambiguation(&ds, &oid_ret);
626 hex[mad.cur_len] = 0;
630 const char *find_unique_abbrev(const struct object_id *oid, int len)
633 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
634 char *hex = hexbuffer[bufno];
635 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
636 find_unique_abbrev_r(hex, oid, len);
640 static int ambiguous_path(const char *path, int len)
645 for (cnt = 0; cnt < len; cnt++) {
665 static inline int at_mark(const char *string, int len,
666 const char **suffix, int nr)
670 for (i = 0; i < nr; i++) {
671 int suffix_len = strlen(suffix[i]);
672 if (suffix_len <= len
673 && !strncasecmp(string, suffix[i], suffix_len))
679 static inline int upstream_mark(const char *string, int len)
681 const char *suffix[] = { "@{upstream}", "@{u}" };
682 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
685 static inline int push_mark(const char *string, int len)
687 const char *suffix[] = { "@{push}" };
688 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
691 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags);
692 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
694 static int get_oid_basic(const char *str, int len, struct object_id *oid,
697 static const char *warn_msg = "refname '%.*s' is ambiguous.";
698 static const char *object_name_msg = N_(
699 "Git normally never creates a ref that ends with 40 hex characters\n"
700 "because it will be ignored when you just specify 40-hex. These refs\n"
701 "may be created by mistake. For example,\n"
703 " git checkout -b $br $(git rev-parse ...)\n"
705 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
706 "examine these refs and maybe delete them. Turn this message off by\n"
707 "running \"git config advice.objectNameWarning false\"");
708 struct object_id tmp_oid;
709 char *real_ref = NULL;
711 int at, reflog_len, nth_prior = 0;
713 if (len == the_hash_algo->hexsz && !get_oid_hex(str, oid)) {
714 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
715 refs_found = dwim_ref(str, len, &tmp_oid, &real_ref);
716 if (refs_found > 0) {
717 warning(warn_msg, len, str);
718 if (advice_object_name_warning)
719 fprintf(stderr, "%s\n", _(object_name_msg));
726 /* basic@{time or number or -number} format to query ref-log */
728 if (len && str[len-1] == '}') {
729 for (at = len-4; at >= 0; at--) {
730 if (str[at] == '@' && str[at+1] == '{') {
731 if (str[at+2] == '-') {
733 /* @{-N} not at start */
738 if (!upstream_mark(str + at, len - at) &&
739 !push_mark(str + at, len - at)) {
740 reflog_len = (len-1) - (at+2);
748 /* Accept only unambiguous ref paths. */
749 if (len && ambiguous_path(str, len))
753 struct strbuf buf = STRBUF_INIT;
756 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
757 detached = (buf.len == the_hash_algo->hexsz && !get_oid_hex(buf.buf, oid));
758 strbuf_release(&buf);
764 if (!len && reflog_len)
765 /* allow "@{...}" to mean the current branch reflog */
766 refs_found = dwim_ref("HEAD", 4, oid, &real_ref);
768 refs_found = dwim_log(str, len, oid, &real_ref);
770 refs_found = dwim_ref(str, len, oid, &real_ref);
775 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
777 !get_short_oid(str, len, &tmp_oid, GET_OID_QUIETLY)))
778 warning(warn_msg, len, str);
786 /* Is it asking for N-th entry, or approxidate? */
787 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
788 char ch = str[at+2+i];
789 if ('0' <= ch && ch <= '9')
790 nth = nth * 10 + ch - '0';
794 if (100000000 <= nth) {
801 char *tmp = xstrndup(str + at + 2, reflog_len);
802 at_time = approxidate_careful(tmp, &errors);
809 if (read_ref_at(real_ref, flags, at_time, nth, oid, NULL,
810 &co_time, &co_tz, &co_cnt)) {
812 if (starts_with(real_ref, "refs/heads/")) {
814 len = strlen(real_ref + 11);
822 if (!(flags & GET_OID_QUIETLY)) {
823 warning("Log for '%.*s' only goes "
824 "back to %s.", len, str,
825 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
828 if (flags & GET_OID_QUIETLY) {
831 die("Log for '%.*s' only has %d entries.",
841 static int get_parent(const char *name, int len,
842 struct object_id *result, int idx)
844 struct object_id oid;
845 int ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
846 struct commit *commit;
847 struct commit_list *p;
851 commit = lookup_commit_reference(the_repository, &oid);
852 if (parse_commit(commit))
855 oidcpy(result, &commit->object.oid);
861 oidcpy(result, &p->item->object.oid);
869 static int get_nth_ancestor(const char *name, int len,
870 struct object_id *result, int generation)
872 struct object_id oid;
873 struct commit *commit;
876 ret = get_oid_1(name, len, &oid, GET_OID_COMMITTISH);
879 commit = lookup_commit_reference(the_repository, &oid);
883 while (generation--) {
884 if (parse_commit(commit) || !commit->parents)
886 commit = commit->parents->item;
888 oidcpy(result, &commit->object.oid);
892 struct object *peel_to_type(const char *name, int namelen,
893 struct object *o, enum object_type expected_type)
895 if (name && !namelen)
896 namelen = strlen(name);
898 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
900 if (expected_type == OBJ_ANY || o->type == expected_type)
902 if (o->type == OBJ_TAG)
903 o = ((struct tag*) o)->tagged;
904 else if (o->type == OBJ_COMMIT)
905 o = &(get_commit_tree(((struct commit *)o))->object);
908 error("%.*s: expected %s type, but the object "
909 "dereferences to %s type",
910 namelen, name, type_name(expected_type),
917 static int peel_onion(const char *name, int len, struct object_id *oid,
918 unsigned lookup_flags)
920 struct object_id outer;
922 unsigned int expected_type = 0;
926 * "ref^{type}" dereferences ref repeatedly until you cannot
927 * dereference anymore, or you get an object of given type,
928 * whichever comes first. "ref^{}" means just dereference
929 * tags until you get a non-tag. "ref^0" is a shorthand for
930 * "ref^{commit}". "commit^{tree}" could be used to find the
931 * top-level tree of the given commit.
933 if (len < 4 || name[len-1] != '}')
936 for (sp = name + len - 1; name <= sp; sp--) {
938 if (ch == '{' && name < sp && sp[-1] == '^')
944 sp++; /* beginning of type name, or closing brace for empty */
945 if (starts_with(sp, "commit}"))
946 expected_type = OBJ_COMMIT;
947 else if (starts_with(sp, "tag}"))
948 expected_type = OBJ_TAG;
949 else if (starts_with(sp, "tree}"))
950 expected_type = OBJ_TREE;
951 else if (starts_with(sp, "blob}"))
952 expected_type = OBJ_BLOB;
953 else if (starts_with(sp, "object}"))
954 expected_type = OBJ_ANY;
955 else if (sp[0] == '}')
956 expected_type = OBJ_NONE;
957 else if (sp[0] == '/')
958 expected_type = OBJ_COMMIT;
962 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
963 if (expected_type == OBJ_COMMIT)
964 lookup_flags |= GET_OID_COMMITTISH;
965 else if (expected_type == OBJ_TREE)
966 lookup_flags |= GET_OID_TREEISH;
968 if (get_oid_1(name, sp - name - 2, &outer, lookup_flags))
971 o = parse_object(the_repository, &outer);
974 if (!expected_type) {
975 o = deref_tag(the_repository, o, name, sp - name - 2);
976 if (!o || (!o->parsed && !parse_object(the_repository, &o->oid)))
978 oidcpy(oid, &o->oid);
983 * At this point, the syntax look correct, so
984 * if we do not get the needed object, we should
987 o = peel_to_type(name, len, o, expected_type);
991 oidcpy(oid, &o->oid);
993 /* "$commit^{/foo}" */
996 struct commit_list *list = NULL;
999 * $commit^{/}. Some regex implementation may reject.
1000 * We don't need regex anyway. '' pattern always matches.
1005 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
1006 commit_list_insert((struct commit *)o, &list);
1007 ret = get_oid_oneline(prefix, oid, list);
1014 static int get_describe_name(const char *name, int len, struct object_id *oid)
1017 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
1019 for (cp = name + len - 1; name + 2 <= cp; cp--) {
1021 if (!isxdigit(ch)) {
1022 /* We must be looking at g in "SOMETHING-g"
1023 * for it to be describe output.
1025 if (ch == 'g' && cp[-1] == '-') {
1028 return get_short_oid(cp, len, oid, flags);
1035 static int get_oid_1(const char *name, int len, struct object_id *oid, unsigned lookup_flags)
1037 int ret, has_suffix;
1041 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1044 for (cp = name + len - 1; name <= cp; cp--) {
1046 if ('0' <= ch && ch <= '9')
1048 if (ch == '~' || ch == '^')
1055 int len1 = cp - name;
1057 while (cp < name + len)
1058 num = num * 10 + *cp++ - '0';
1059 if (!num && len1 == len - 1)
1061 if (has_suffix == '^')
1062 return get_parent(name, len1, oid, num);
1063 /* else if (has_suffix == '~') -- goes without saying */
1064 return get_nth_ancestor(name, len1, oid, num);
1067 ret = peel_onion(name, len, oid, lookup_flags);
1071 ret = get_oid_basic(name, len, oid, lookup_flags);
1075 /* It could be describe output that is "SOMETHING-gXXXX" */
1076 ret = get_describe_name(name, len, oid);
1080 return get_short_oid(name, len, oid, lookup_flags);
1084 * This interprets names like ':/Initial revision of "git"' by searching
1085 * through history and returning the first commit whose message starts
1086 * the given regular expression.
1088 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1090 * For a literal '!' character at the beginning of a pattern, you have to repeat
1091 * that, like: ':/!!foo'
1093 * For future extension, all other sequences beginning with ':/!' are reserved.
1096 /* Remember to update object flag allocation in object.h */
1097 #define ONELINE_SEEN (1u<<20)
1099 static int handle_one_ref(const char *path, const struct object_id *oid,
1100 int flag, void *cb_data)
1102 struct commit_list **list = cb_data;
1103 struct object *object = parse_object(the_repository, oid);
1106 if (object->type == OBJ_TAG) {
1107 object = deref_tag(the_repository, object, path,
1112 if (object->type != OBJ_COMMIT)
1114 commit_list_insert((struct commit *)object, list);
1118 static int get_oid_oneline(const char *prefix, struct object_id *oid,
1119 struct commit_list *list)
1121 struct commit_list *backup = NULL, *l;
1126 if (prefix[0] == '!') {
1129 if (prefix[0] == '-') {
1132 } else if (prefix[0] != '!') {
1137 if (regcomp(®ex, prefix, REG_EXTENDED))
1140 for (l = list; l; l = l->next) {
1141 l->item->object.flags |= ONELINE_SEEN;
1142 commit_list_insert(l->item, &backup);
1145 const char *p, *buf;
1146 struct commit *commit;
1149 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1150 if (!parse_object(the_repository, &commit->object.oid))
1152 buf = get_commit_buffer(commit, NULL);
1153 p = strstr(buf, "\n\n");
1154 matches = negative ^ (p && !regexec(®ex, p + 2, 0, NULL, 0));
1155 unuse_commit_buffer(commit, buf);
1158 oidcpy(oid, &commit->object.oid);
1164 free_commit_list(list);
1165 for (l = backup; l; l = l->next)
1166 clear_commit_marks(l->item, ONELINE_SEEN);
1167 free_commit_list(backup);
1168 return found ? 0 : -1;
1171 struct grab_nth_branch_switch_cbdata {
1176 static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
1177 const char *email, timestamp_t timestamp, int tz,
1178 const char *message, void *cb_data)
1180 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1181 const char *match = NULL, *target = NULL;
1184 if (skip_prefix(message, "checkout: moving from ", &match))
1185 target = strstr(match, " to ");
1187 if (!match || !target)
1189 if (--(cb->remaining) == 0) {
1190 len = target - match;
1191 strbuf_reset(&cb->buf);
1192 strbuf_add(&cb->buf, match, len);
1193 return 1; /* we are done */
1199 * Parse @{-N} syntax, return the number of characters parsed
1200 * if successful; otherwise signal an error with negative value.
1202 static int interpret_nth_prior_checkout(const char *name, int namelen,
1207 struct grab_nth_branch_switch_cbdata cb;
1213 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1215 brace = memchr(name, '}', namelen);
1218 nth = strtol(name + 3, &num_end, 10);
1219 if (num_end != brace)
1224 strbuf_init(&cb.buf, 20);
1227 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1229 strbuf_addbuf(buf, &cb.buf);
1230 retval = brace - name + 1;
1233 strbuf_release(&cb.buf);
1237 int get_oid_mb(const char *name, struct object_id *oid)
1239 struct commit *one, *two;
1240 struct commit_list *mbs;
1241 struct object_id oid_tmp;
1245 dots = strstr(name, "...");
1247 return get_oid(name, oid);
1249 st = get_oid("HEAD", &oid_tmp);
1252 strbuf_init(&sb, dots - name);
1253 strbuf_add(&sb, name, dots - name);
1254 st = get_oid_committish(sb.buf, &oid_tmp);
1255 strbuf_release(&sb);
1259 one = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1263 if (get_oid_committish(dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1265 two = lookup_commit_reference_gently(the_repository, &oid_tmp, 0);
1268 mbs = get_merge_bases(one, two);
1269 if (!mbs || mbs->next)
1273 oidcpy(oid, &mbs->item->object.oid);
1275 free_commit_list(mbs);
1279 /* parse @something syntax, when 'something' is not {.*} */
1280 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1284 if (len || name[1] == '{')
1287 /* make sure it's a single @, or @@{.*}, not @foo */
1288 next = memchr(name + len + 1, '@', namelen - len - 1);
1289 if (next && next[1] != '{')
1292 next = name + namelen;
1293 if (next != name + 1)
1297 strbuf_add(buf, "HEAD", 4);
1301 static int reinterpret(const char *name, int namelen, int len,
1302 struct strbuf *buf, unsigned allowed)
1304 /* we have extra data, which might need further processing */
1305 struct strbuf tmp = STRBUF_INIT;
1306 int used = buf->len;
1309 strbuf_add(buf, name + len, namelen - len);
1310 ret = interpret_branch_name(buf->buf, buf->len, &tmp, allowed);
1311 /* that data was not interpreted, remove our cruft */
1313 strbuf_setlen(buf, used);
1317 strbuf_addbuf(buf, &tmp);
1318 strbuf_release(&tmp);
1319 /* tweak for size of {-N} versus expanded ref name */
1320 return ret - used + len;
1323 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1325 char *s = shorten_unambiguous_ref(ref, 0);
1327 strbuf_addstr(buf, s);
1331 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1336 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1337 starts_with(refname, "refs/heads/"))
1339 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1340 starts_with(refname, "refs/remotes/"))
1346 static int interpret_branch_mark(const char *name, int namelen,
1347 int at, struct strbuf *buf,
1348 int (*get_mark)(const char *, int),
1349 const char *(*get_data)(struct branch *,
1354 struct branch *branch;
1355 struct strbuf err = STRBUF_INIT;
1358 len = get_mark(name + at, namelen - at);
1362 if (memchr(name, ':', at))
1366 char *name_str = xmemdupz(name, at);
1367 branch = branch_get(name_str);
1370 branch = branch_get(NULL);
1372 value = get_data(branch, &err);
1376 if (!branch_interpret_allowed(value, allowed))
1379 set_shortened_ref(buf, value);
1383 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf,
1391 namelen = strlen(name);
1393 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1394 len = interpret_nth_prior_checkout(name, namelen, buf);
1396 return len; /* syntax Ok, not enough switches */
1397 } else if (len > 0) {
1399 return len; /* consumed all */
1401 return reinterpret(name, namelen, len, buf, allowed);
1406 (at = memchr(start, '@', namelen - (start - name)));
1409 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1410 len = interpret_empty_at(name, namelen, at - name, buf);
1412 return reinterpret(name, namelen, len, buf,
1416 len = interpret_branch_mark(name, namelen, at - name, buf,
1417 upstream_mark, branch_get_upstream,
1422 len = interpret_branch_mark(name, namelen, at - name, buf,
1423 push_mark, branch_get_push,
1432 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1434 int len = strlen(name);
1435 int used = interpret_branch_name(name, len, sb, allowed);
1439 strbuf_add(sb, name + used, len - used);
1442 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1444 if (startup_info->have_repository)
1445 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1447 strbuf_addstr(sb, name);
1450 * This splice must be done even if we end up rejecting the
1451 * name; builtin/branch.c::copy_or_rename_branch() still wants
1452 * to see what the name expanded to so that "branch -m" can be
1453 * used as a tool to correct earlier mistakes.
1455 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1458 !strcmp(sb->buf, "refs/heads/HEAD"))
1461 return check_refname_format(sb->buf, 0);
1465 * This is like "get_oid_basic()", except it allows "object ID expressions",
1466 * notably "xyz^" for "parent of xyz"
1468 int get_oid(const char *name, struct object_id *oid)
1470 struct object_context unused;
1471 return get_oid_with_context(name, 0, oid, &unused);
1476 * Many callers know that the user meant to name a commit-ish by
1477 * syntactical positions where the object name appears. Calling this
1478 * function allows the machinery to disambiguate shorter-than-unique
1479 * abbreviated object names between commit-ish and others.
1481 * Note that this does NOT error out when the named object is not a
1482 * commit-ish. It is merely to give a hint to the disambiguation
1485 int get_oid_committish(const char *name, struct object_id *oid)
1487 struct object_context unused;
1488 return get_oid_with_context(name, GET_OID_COMMITTISH,
1492 int get_oid_treeish(const char *name, struct object_id *oid)
1494 struct object_context unused;
1495 return get_oid_with_context(name, GET_OID_TREEISH,
1499 int get_oid_commit(const char *name, struct object_id *oid)
1501 struct object_context unused;
1502 return get_oid_with_context(name, GET_OID_COMMIT,
1506 int get_oid_tree(const char *name, struct object_id *oid)
1508 struct object_context unused;
1509 return get_oid_with_context(name, GET_OID_TREE,
1513 int get_oid_blob(const char *name, struct object_id *oid)
1515 struct object_context unused;
1516 return get_oid_with_context(name, GET_OID_BLOB,
1520 /* Must be called only when object_name:filename doesn't exist. */
1521 static void diagnose_invalid_oid_path(const char *prefix,
1522 const char *filename,
1523 const struct object_id *tree_oid,
1524 const char *object_name,
1525 int object_name_len)
1527 struct object_id oid;
1533 if (file_exists(filename))
1534 die("Path '%s' exists on disk, but not in '%.*s'.",
1535 filename, object_name_len, object_name);
1536 if (is_missing_file_error(errno)) {
1537 char *fullname = xstrfmt("%s%s", prefix, filename);
1539 if (!get_tree_entry(tree_oid, fullname, &oid, &mode)) {
1540 die("Path '%s' exists, but not '%s'.\n"
1541 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1544 object_name_len, object_name,
1546 object_name_len, object_name,
1549 die("Path '%s' does not exist in '%.*s'",
1550 filename, object_name_len, object_name);
1554 /* Must be called only when :stage:filename doesn't exist. */
1555 static void diagnose_invalid_index_path(int stage,
1557 const char *filename)
1559 const struct cache_entry *ce;
1561 unsigned namelen = strlen(filename);
1562 struct strbuf fullname = STRBUF_INIT;
1567 /* Wrong stage number? */
1568 pos = cache_name_pos(filename, namelen);
1571 if (pos < active_nr) {
1572 ce = active_cache[pos];
1573 if (ce_namelen(ce) == namelen &&
1574 !memcmp(ce->name, filename, namelen))
1575 die("Path '%s' is in the index, but not at stage %d.\n"
1576 "Did you mean ':%d:%s'?",
1578 ce_stage(ce), filename);
1581 /* Confusion between relative and absolute filenames? */
1582 strbuf_addstr(&fullname, prefix);
1583 strbuf_addstr(&fullname, filename);
1584 pos = cache_name_pos(fullname.buf, fullname.len);
1587 if (pos < active_nr) {
1588 ce = active_cache[pos];
1589 if (ce_namelen(ce) == fullname.len &&
1590 !memcmp(ce->name, fullname.buf, fullname.len))
1591 die("Path '%s' is in the index, but not '%s'.\n"
1592 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1593 fullname.buf, filename,
1594 ce_stage(ce), fullname.buf,
1595 ce_stage(ce), filename);
1598 if (file_exists(filename))
1599 die("Path '%s' exists on disk, but not in the index.", filename);
1600 if (is_missing_file_error(errno))
1601 die("Path '%s' does not exist (neither on disk nor in the index).",
1604 strbuf_release(&fullname);
1608 static char *resolve_relative_path(const char *rel)
1610 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1613 if (!is_inside_work_tree())
1614 die("relative path syntax can't be used outside working tree.");
1616 /* die() inside prefix_path() if resolved path is outside worktree */
1617 return prefix_path(startup_info->prefix,
1618 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1622 static int get_oid_with_context_1(const char *name,
1625 struct object_id *oid,
1626 struct object_context *oc)
1628 int ret, bracket_depth;
1629 int namelen = strlen(name);
1631 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
1634 flags |= GET_OID_QUIETLY;
1636 memset(oc, 0, sizeof(*oc));
1637 oc->mode = S_IFINVALID;
1638 strbuf_init(&oc->symlink_path, 0);
1639 ret = get_oid_1(name, namelen, oid, flags);
1643 * sha1:path --> object name of path in ent sha1
1644 * :path -> object name of absolute path in index
1645 * :./path -> object name of path relative to cwd in index
1646 * :[0-3]:path -> object name of path in index at stage
1647 * :/foo -> recent commit matching foo
1649 if (name[0] == ':') {
1651 const struct cache_entry *ce;
1652 char *new_path = NULL;
1654 if (!only_to_die && namelen > 2 && name[1] == '/') {
1655 struct commit_list *list = NULL;
1657 for_each_ref(handle_one_ref, &list);
1658 head_ref(handle_one_ref, &list);
1659 commit_list_sort_by_date(&list);
1660 return get_oid_oneline(name + 2, oid, list);
1664 name[1] < '0' || '3' < name[1])
1667 stage = name[1] - '0';
1670 new_path = resolve_relative_path(cp);
1672 namelen = namelen - (cp - name);
1675 namelen = strlen(cp);
1678 if (flags & GET_OID_RECORD_PATH)
1679 oc->path = xstrdup(cp);
1683 pos = cache_name_pos(cp, namelen);
1686 while (pos < active_nr) {
1687 ce = active_cache[pos];
1688 if (ce_namelen(ce) != namelen ||
1689 memcmp(ce->name, cp, namelen))
1691 if (ce_stage(ce) == stage) {
1692 oidcpy(oid, &ce->oid);
1693 oc->mode = ce->ce_mode;
1699 if (only_to_die && name[1] && name[1] != '/')
1700 diagnose_invalid_index_path(stage, prefix, cp);
1704 for (cp = name, bracket_depth = 0; *cp; cp++) {
1707 else if (bracket_depth && *cp == '}')
1709 else if (!bracket_depth && *cp == ':')
1713 struct object_id tree_oid;
1714 int len = cp - name;
1715 unsigned sub_flags = flags;
1717 sub_flags &= ~GET_OID_DISAMBIGUATORS;
1718 sub_flags |= GET_OID_TREEISH;
1720 if (!get_oid_1(name, len, &tree_oid, sub_flags)) {
1721 const char *filename = cp+1;
1722 char *new_filename = NULL;
1724 new_filename = resolve_relative_path(filename);
1726 filename = new_filename;
1727 if (flags & GET_OID_FOLLOW_SYMLINKS) {
1728 ret = get_tree_entry_follow_symlinks(&tree_oid,
1729 filename, oid, &oc->symlink_path,
1732 ret = get_tree_entry(&tree_oid, filename, oid,
1734 if (ret && only_to_die) {
1735 diagnose_invalid_oid_path(prefix,
1741 if (flags & GET_OID_RECORD_PATH)
1742 oc->path = xstrdup(filename);
1748 die("Invalid object name '%.*s'.", len, name);
1755 * Call this function when you know "name" given by the end user must
1756 * name an object but it doesn't; the function _may_ die with a better
1757 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1758 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1759 * you have a chance to diagnose the error further.
1761 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1763 struct object_context oc;
1764 struct object_id oid;
1765 get_oid_with_context_1(name, GET_OID_ONLY_TO_DIE, prefix, &oid, &oc);
1768 int get_oid_with_context(const char *str, unsigned flags, struct object_id *oid, struct object_context *oc)
1770 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
1771 BUG("incompatible flags for get_sha1_with_context");
1772 return get_oid_with_context_1(str, flags, NULL, oid, oc);