10 #include "sha1-array.h"
12 static int get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
14 typedef int (*disambiguate_hint_fn)(const unsigned char *, void *);
16 struct disambiguate_state {
17 int len; /* length of prefix in hex chars */
18 unsigned int nrobjects;
19 char hex_pfx[GIT_SHA1_HEXSZ + 1];
20 unsigned char bin_pfx[GIT_SHA1_RAWSZ];
22 disambiguate_hint_fn fn;
24 unsigned char candidate[GIT_SHA1_RAWSZ];
25 unsigned candidate_exists:1;
26 unsigned candidate_checked:1;
27 unsigned candidate_ok:1;
28 unsigned disambiguate_fn_used:1;
30 unsigned always_call_fn:1;
33 static void update_candidates(struct disambiguate_state *ds, const unsigned char *current)
35 if (ds->always_call_fn) {
36 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
39 if (!ds->candidate_exists) {
40 /* this is the first candidate */
41 hashcpy(ds->candidate, current);
42 ds->candidate_exists = 1;
44 } else if (!hashcmp(ds->candidate, current)) {
45 /* the same as what we already have seen */
50 /* cannot disambiguate between ds->candidate and current */
55 if (!ds->candidate_checked) {
56 ds->candidate_ok = ds->fn(ds->candidate, ds->cb_data);
57 ds->disambiguate_fn_used = 1;
58 ds->candidate_checked = 1;
61 if (!ds->candidate_ok) {
62 /* discard the candidate; we know it does not satisfy fn */
63 hashcpy(ds->candidate, current);
64 ds->candidate_checked = 0;
68 /* if we reach this point, we know ds->candidate satisfies fn */
69 if (ds->fn(current, ds->cb_data)) {
71 * if both current and candidate satisfy fn, we cannot
78 /* otherwise, current can be discarded and candidate is still good */
81 static void find_short_object_filename(struct disambiguate_state *ds)
83 struct alternate_object_database *alt;
84 char hex[GIT_SHA1_HEXSZ];
85 static struct alternate_object_database *fakeent;
89 * Create a "fake" alternate object database that
90 * points to our own object database, to make it
91 * easier to get a temporary working space in
92 * alt->name/alt->base while iterating over the
93 * object databases including our own.
95 fakeent = alloc_alt_odb(get_object_directory());
97 fakeent->next = alt_odb_list;
99 xsnprintf(hex, sizeof(hex), "%.2s", ds->hex_pfx);
100 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
101 struct strbuf *buf = alt_scratch_buf(alt);
105 strbuf_addf(buf, "%.2s/", ds->hex_pfx);
106 dir = opendir(buf->buf);
110 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
111 unsigned char sha1[20];
113 if (strlen(de->d_name) != 38)
117 * We only look at the one subdirectory, and we assume
118 * each subdirectory is roughly similar, so each
119 * object we find probably has 255 other objects in
120 * the other fan-out directories.
122 ds->nrobjects += 256;
123 if (memcmp(de->d_name, ds->hex_pfx + 2, ds->len - 2))
125 memcpy(hex + 2, de->d_name, 38);
126 if (!get_sha1_hex(hex, sha1))
127 update_candidates(ds, sha1);
133 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
143 if ((*a ^ *b) & 0xf0)
148 static void unique_in_pack(struct packed_git *p,
149 struct disambiguate_state *ds)
151 uint32_t num, last, i, first = 0;
152 const unsigned char *current = NULL;
155 num = p->num_objects;
156 ds->nrobjects += num;
158 while (first < last) {
159 uint32_t mid = (first + last) / 2;
160 const unsigned char *current;
163 current = nth_packed_object_sha1(p, mid);
164 cmp = hashcmp(ds->bin_pfx, current);
177 * At this point, "first" is the location of the lowest object
178 * with an object name that could match "bin_pfx". See if we have
179 * 0, 1 or more objects that actually match(es).
181 for (i = first; i < num && !ds->ambiguous; i++) {
182 current = nth_packed_object_sha1(p, i);
183 if (!match_sha(ds->len, ds->bin_pfx, current))
185 update_candidates(ds, current);
189 static void find_short_packed_object(struct disambiguate_state *ds)
191 struct packed_git *p;
193 prepare_packed_git();
194 for (p = packed_git; p && !ds->ambiguous; p = p->next)
195 unique_in_pack(p, ds);
198 #define SHORT_NAME_NOT_FOUND (-1)
199 #define SHORT_NAME_AMBIGUOUS (-2)
201 static int finish_object_disambiguation(struct disambiguate_state *ds,
205 return SHORT_NAME_AMBIGUOUS;
207 if (!ds->candidate_exists)
208 return SHORT_NAME_NOT_FOUND;
210 if (!ds->candidate_checked)
212 * If this is the only candidate, there is no point
213 * calling the disambiguation hint callback.
215 * On the other hand, if the current candidate
216 * replaced an earlier candidate that did _not_ pass
217 * the disambiguation hint callback, then we do have
218 * more than one objects that match the short name
219 * given, so we should make sure this one matches;
220 * otherwise, if we discovered this one and the one
221 * that we previously discarded in the reverse order,
222 * we would end up showing different results in the
225 ds->candidate_ok = (!ds->disambiguate_fn_used ||
226 ds->fn(ds->candidate, ds->cb_data));
228 if (!ds->candidate_ok)
229 return SHORT_NAME_AMBIGUOUS;
231 hashcpy(sha1, ds->candidate);
235 static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
237 int kind = sha1_object_info(sha1, NULL);
238 return kind == OBJ_COMMIT;
241 static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
246 kind = sha1_object_info(sha1, NULL);
247 if (kind == OBJ_COMMIT)
252 /* We need to do this the hard way... */
253 obj = deref_tag(parse_object(sha1), NULL, 0);
254 if (obj && obj->type == OBJ_COMMIT)
259 static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
261 int kind = sha1_object_info(sha1, NULL);
262 return kind == OBJ_TREE;
265 static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
270 kind = sha1_object_info(sha1, NULL);
271 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
276 /* We need to do this the hard way... */
277 obj = deref_tag(parse_object(sha1), NULL, 0);
278 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
283 static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
285 int kind = sha1_object_info(sha1, NULL);
286 return kind == OBJ_BLOB;
289 static disambiguate_hint_fn default_disambiguate_hint;
291 int set_disambiguate_hint_config(const char *var, const char *value)
293 static const struct {
295 disambiguate_hint_fn fn;
298 { "commit", disambiguate_commit_only },
299 { "committish", disambiguate_committish_only },
300 { "tree", disambiguate_tree_only },
301 { "treeish", disambiguate_treeish_only },
302 { "blob", disambiguate_blob_only }
307 return config_error_nonbool(var);
309 for (i = 0; i < ARRAY_SIZE(hints); i++) {
310 if (!strcasecmp(value, hints[i].name)) {
311 default_disambiguate_hint = hints[i].fn;
316 return error("unknown hint type for '%s': %s", var, value);
319 static int init_object_disambiguation(const char *name, int len,
320 struct disambiguate_state *ds)
324 if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
327 memset(ds, 0, sizeof(*ds));
329 for (i = 0; i < len ;i++) {
330 unsigned char c = name[i];
332 if (c >= '0' && c <= '9')
334 else if (c >= 'a' && c <= 'f')
336 else if (c >= 'A' && c <='F') {
345 ds->bin_pfx[i >> 1] |= val;
349 ds->hex_pfx[len] = '\0';
354 static int show_ambiguous_object(const unsigned char *sha1, void *data)
356 const struct disambiguate_state *ds = data;
357 struct strbuf desc = STRBUF_INIT;
360 if (ds->fn && !ds->fn(sha1, ds->cb_data))
363 type = sha1_object_info(sha1, NULL);
364 if (type == OBJ_COMMIT) {
365 struct commit *commit = lookup_commit(sha1);
367 struct pretty_print_context pp = {0};
368 pp.date_mode.type = DATE_SHORT;
369 format_commit_message(commit, " %ad - %s", &desc, &pp);
371 } else if (type == OBJ_TAG) {
372 struct tag *tag = lookup_tag(sha1);
373 if (!parse_tag(tag) && tag->tag)
374 strbuf_addf(&desc, " %s", tag->tag);
378 find_unique_abbrev(sha1, DEFAULT_ABBREV),
379 typename(type) ? typename(type) : "unknown type",
382 strbuf_release(&desc);
386 /* start from our historical default before the automatic abbreviation */
387 static int default_automatic_abbrev = FALLBACK_DEFAULT_ABBREV;
389 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
393 struct disambiguate_state ds;
394 int quietly = !!(flags & GET_SHA1_QUIETLY);
396 if (init_object_disambiguation(name, len, &ds) < 0)
399 if (HAS_MULTI_BITS(flags & GET_SHA1_DISAMBIGUATORS))
400 die("BUG: multiple get_short_sha1 disambiguator flags");
402 if (flags & GET_SHA1_COMMIT)
403 ds.fn = disambiguate_commit_only;
404 else if (flags & GET_SHA1_COMMITTISH)
405 ds.fn = disambiguate_committish_only;
406 else if (flags & GET_SHA1_TREE)
407 ds.fn = disambiguate_tree_only;
408 else if (flags & GET_SHA1_TREEISH)
409 ds.fn = disambiguate_treeish_only;
410 else if (flags & GET_SHA1_BLOB)
411 ds.fn = disambiguate_blob_only;
413 ds.fn = default_disambiguate_hint;
415 find_short_object_filename(&ds);
416 find_short_packed_object(&ds);
417 status = finish_object_disambiguation(&ds, sha1);
419 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
420 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
423 * We may still have ambiguity if we simply saw a series of
424 * candidates that did not satisfy our hint function. In
425 * that case, we still want to show them, so disable the hint
431 advise(_("The candidates are:"));
432 for_each_abbrev(ds.hex_pfx, show_ambiguous_object, &ds);
435 if (len < 16 && !status && (flags & GET_SHA1_AUTOMATIC)) {
436 unsigned int expect_collision = 1 << (len * 2);
437 if (ds.nrobjects > expect_collision) {
438 default_automatic_abbrev = len+1;
439 return SHORT_NAME_AMBIGUOUS;
446 static int collect_ambiguous(const unsigned char *sha1, void *data)
448 sha1_array_append(data, sha1);
452 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
454 struct sha1_array collect = SHA1_ARRAY_INIT;
455 struct disambiguate_state ds;
458 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
461 ds.always_call_fn = 1;
462 ds.fn = collect_ambiguous;
463 ds.cb_data = &collect;
464 find_short_object_filename(&ds);
465 find_short_packed_object(&ds);
467 ret = sha1_array_for_each_unique(&collect, fn, cb_data);
468 sha1_array_clear(&collect);
472 int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
475 int flags = GET_SHA1_QUIETLY;
478 flags |= GET_SHA1_AUTOMATIC;
479 len = default_automatic_abbrev;
481 sha1_to_hex_r(hex, sha1);
482 if (len == 40 || !len)
484 exists = has_sha1_file(sha1);
486 unsigned char sha1_ret[20];
487 status = get_short_sha1(hex, len, sha1_ret, flags);
490 : status == SHORT_NAME_NOT_FOUND) {
499 const char *find_unique_abbrev(const unsigned char *sha1, int len)
501 static char hex[GIT_SHA1_HEXSZ + 1];
502 find_unique_abbrev_r(hex, sha1, len);
506 static int ambiguous_path(const char *path, int len)
511 for (cnt = 0; cnt < len; cnt++) {
531 static inline int at_mark(const char *string, int len,
532 const char **suffix, int nr)
536 for (i = 0; i < nr; i++) {
537 int suffix_len = strlen(suffix[i]);
538 if (suffix_len <= len
539 && !memcmp(string, suffix[i], suffix_len))
545 static inline int upstream_mark(const char *string, int len)
547 const char *suffix[] = { "@{upstream}", "@{u}" };
548 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
551 static inline int push_mark(const char *string, int len)
553 const char *suffix[] = { "@{push}" };
554 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
557 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
558 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
560 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
563 static const char *warn_msg = "refname '%.*s' is ambiguous.";
564 static const char *object_name_msg = N_(
565 "Git normally never creates a ref that ends with 40 hex characters\n"
566 "because it will be ignored when you just specify 40-hex. These refs\n"
567 "may be created by mistake. For example,\n"
569 " git checkout -b $br $(git rev-parse ...)\n"
571 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
572 "examine these refs and maybe delete them. Turn this message off by\n"
573 "running \"git config advice.objectNameWarning false\"");
574 unsigned char tmp_sha1[20];
575 char *real_ref = NULL;
577 int at, reflog_len, nth_prior = 0;
579 if (len == 40 && !get_sha1_hex(str, sha1)) {
580 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
581 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
582 if (refs_found > 0) {
583 warning(warn_msg, len, str);
584 if (advice_object_name_warning)
585 fprintf(stderr, "%s\n", _(object_name_msg));
592 /* basic@{time or number or -number} format to query ref-log */
594 if (len && str[len-1] == '}') {
595 for (at = len-4; at >= 0; at--) {
596 if (str[at] == '@' && str[at+1] == '{') {
597 if (str[at+2] == '-') {
599 /* @{-N} not at start */
604 if (!upstream_mark(str + at, len - at) &&
605 !push_mark(str + at, len - at)) {
606 reflog_len = (len-1) - (at+2);
614 /* Accept only unambiguous ref paths. */
615 if (len && ambiguous_path(str, len))
619 struct strbuf buf = STRBUF_INIT;
622 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
623 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
624 strbuf_release(&buf);
630 if (!len && reflog_len)
631 /* allow "@{...}" to mean the current branch reflog */
632 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
634 refs_found = dwim_log(str, len, sha1, &real_ref);
636 refs_found = dwim_ref(str, len, sha1, &real_ref);
641 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
643 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
644 warning(warn_msg, len, str);
648 unsigned long at_time;
649 unsigned long co_time;
652 /* Is it asking for N-th entry, or approxidate? */
653 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
654 char ch = str[at+2+i];
655 if ('0' <= ch && ch <= '9')
656 nth = nth * 10 + ch - '0';
660 if (100000000 <= nth) {
667 char *tmp = xstrndup(str + at + 2, reflog_len);
668 at_time = approxidate_careful(tmp, &errors);
675 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
676 &co_time, &co_tz, &co_cnt)) {
678 if (starts_with(real_ref, "refs/heads/")) {
680 len = strlen(real_ref + 11);
688 if (!(flags & GET_SHA1_QUIETLY)) {
689 warning("Log for '%.*s' only goes "
690 "back to %s.", len, str,
691 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
694 if (flags & GET_SHA1_QUIETLY) {
697 die("Log for '%.*s' only has %d entries.",
707 static int get_parent(const char *name, int len,
708 unsigned char *result, int idx)
710 unsigned char sha1[20];
711 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
712 struct commit *commit;
713 struct commit_list *p;
717 commit = lookup_commit_reference(sha1);
718 if (parse_commit(commit))
721 hashcpy(result, commit->object.oid.hash);
727 hashcpy(result, p->item->object.oid.hash);
735 static int get_nth_ancestor(const char *name, int len,
736 unsigned char *result, int generation)
738 unsigned char sha1[20];
739 struct commit *commit;
742 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
745 commit = lookup_commit_reference(sha1);
749 while (generation--) {
750 if (parse_commit(commit) || !commit->parents)
752 commit = commit->parents->item;
754 hashcpy(result, commit->object.oid.hash);
758 struct object *peel_to_type(const char *name, int namelen,
759 struct object *o, enum object_type expected_type)
761 if (name && !namelen)
762 namelen = strlen(name);
764 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
766 if (expected_type == OBJ_ANY || o->type == expected_type)
768 if (o->type == OBJ_TAG)
769 o = ((struct tag*) o)->tagged;
770 else if (o->type == OBJ_COMMIT)
771 o = &(((struct commit *) o)->tree->object);
774 error("%.*s: expected %s type, but the object "
775 "dereferences to %s type",
776 namelen, name, typename(expected_type),
783 static int peel_onion(const char *name, int len, unsigned char *sha1,
784 unsigned lookup_flags)
786 unsigned char outer[20];
788 unsigned int expected_type = 0;
792 * "ref^{type}" dereferences ref repeatedly until you cannot
793 * dereference anymore, or you get an object of given type,
794 * whichever comes first. "ref^{}" means just dereference
795 * tags until you get a non-tag. "ref^0" is a shorthand for
796 * "ref^{commit}". "commit^{tree}" could be used to find the
797 * top-level tree of the given commit.
799 if (len < 4 || name[len-1] != '}')
802 for (sp = name + len - 1; name <= sp; sp--) {
804 if (ch == '{' && name < sp && sp[-1] == '^')
810 sp++; /* beginning of type name, or closing brace for empty */
811 if (starts_with(sp, "commit}"))
812 expected_type = OBJ_COMMIT;
813 else if (starts_with(sp, "tag}"))
814 expected_type = OBJ_TAG;
815 else if (starts_with(sp, "tree}"))
816 expected_type = OBJ_TREE;
817 else if (starts_with(sp, "blob}"))
818 expected_type = OBJ_BLOB;
819 else if (starts_with(sp, "object}"))
820 expected_type = OBJ_ANY;
821 else if (sp[0] == '}')
822 expected_type = OBJ_NONE;
823 else if (sp[0] == '/')
824 expected_type = OBJ_COMMIT;
828 lookup_flags &= ~GET_SHA1_DISAMBIGUATORS;
829 if (expected_type == OBJ_COMMIT)
830 lookup_flags |= GET_SHA1_COMMITTISH;
831 else if (expected_type == OBJ_TREE)
832 lookup_flags |= GET_SHA1_TREEISH;
834 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
837 o = parse_object(outer);
840 if (!expected_type) {
841 o = deref_tag(o, name, sp - name - 2);
842 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
844 hashcpy(sha1, o->oid.hash);
849 * At this point, the syntax look correct, so
850 * if we do not get the needed object, we should
853 o = peel_to_type(name, len, o, expected_type);
857 hashcpy(sha1, o->oid.hash);
859 /* "$commit^{/foo}" */
862 struct commit_list *list = NULL;
865 * $commit^{/}. Some regex implementation may reject.
866 * We don't need regex anyway. '' pattern always matches.
871 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
872 commit_list_insert((struct commit *)o, &list);
873 ret = get_sha1_oneline(prefix, sha1, list);
880 static int get_describe_name(const char *name, int len, unsigned char *sha1)
883 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
885 for (cp = name + len - 1; name + 2 <= cp; cp--) {
888 /* We must be looking at g in "SOMETHING-g"
889 * for it to be describe output.
891 if (ch == 'g' && cp[-1] == '-') {
894 return get_short_sha1(cp, len, sha1, flags);
901 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
907 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
910 for (cp = name + len - 1; name <= cp; cp--) {
912 if ('0' <= ch && ch <= '9')
914 if (ch == '~' || ch == '^')
921 int len1 = cp - name;
923 while (cp < name + len)
924 num = num * 10 + *cp++ - '0';
925 if (!num && len1 == len - 1)
927 if (has_suffix == '^')
928 return get_parent(name, len1, sha1, num);
929 /* else if (has_suffix == '~') -- goes without saying */
930 return get_nth_ancestor(name, len1, sha1, num);
933 ret = peel_onion(name, len, sha1, lookup_flags);
937 ret = get_sha1_basic(name, len, sha1, lookup_flags);
941 /* It could be describe output that is "SOMETHING-gXXXX" */
942 ret = get_describe_name(name, len, sha1);
946 return get_short_sha1(name, len, sha1, lookup_flags);
950 * This interprets names like ':/Initial revision of "git"' by searching
951 * through history and returning the first commit whose message starts
952 * the given regular expression.
954 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
956 * For a literal '!' character at the beginning of a pattern, you have to repeat
957 * that, like: ':/!!foo'
959 * For future extension, all other sequences beginning with ':/!' are reserved.
962 /* Remember to update object flag allocation in object.h */
963 #define ONELINE_SEEN (1u<<20)
965 static int handle_one_ref(const char *path, const struct object_id *oid,
966 int flag, void *cb_data)
968 struct commit_list **list = cb_data;
969 struct object *object = parse_object(oid->hash);
972 if (object->type == OBJ_TAG) {
973 object = deref_tag(object, path, strlen(path));
977 if (object->type != OBJ_COMMIT)
979 commit_list_insert((struct commit *)object, list);
983 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
984 struct commit_list *list)
986 struct commit_list *backup = NULL, *l;
991 if (prefix[0] == '!') {
994 if (prefix[0] == '-') {
997 } else if (prefix[0] != '!') {
1002 if (regcomp(®ex, prefix, REG_EXTENDED))
1005 for (l = list; l; l = l->next) {
1006 l->item->object.flags |= ONELINE_SEEN;
1007 commit_list_insert(l->item, &backup);
1010 const char *p, *buf;
1011 struct commit *commit;
1014 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1015 if (!parse_object(commit->object.oid.hash))
1017 buf = get_commit_buffer(commit, NULL);
1018 p = strstr(buf, "\n\n");
1019 matches = negative ^ (p && !regexec(®ex, p + 2, 0, NULL, 0));
1020 unuse_commit_buffer(commit, buf);
1023 hashcpy(sha1, commit->object.oid.hash);
1029 free_commit_list(list);
1030 for (l = backup; l; l = l->next)
1031 clear_commit_marks(l->item, ONELINE_SEEN);
1032 free_commit_list(backup);
1033 return found ? 0 : -1;
1036 struct grab_nth_branch_switch_cbdata {
1041 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
1042 const char *email, unsigned long timestamp, int tz,
1043 const char *message, void *cb_data)
1045 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1046 const char *match = NULL, *target = NULL;
1049 if (skip_prefix(message, "checkout: moving from ", &match))
1050 target = strstr(match, " to ");
1052 if (!match || !target)
1054 if (--(cb->remaining) == 0) {
1055 len = target - match;
1056 strbuf_reset(&cb->buf);
1057 strbuf_add(&cb->buf, match, len);
1058 return 1; /* we are done */
1064 * Parse @{-N} syntax, return the number of characters parsed
1065 * if successful; otherwise signal an error with negative value.
1067 static int interpret_nth_prior_checkout(const char *name, int namelen,
1072 struct grab_nth_branch_switch_cbdata cb;
1078 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1080 brace = memchr(name, '}', namelen);
1083 nth = strtol(name + 3, &num_end, 10);
1084 if (num_end != brace)
1089 strbuf_init(&cb.buf, 20);
1092 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1094 strbuf_addbuf(buf, &cb.buf);
1095 retval = brace - name + 1;
1098 strbuf_release(&cb.buf);
1102 int get_oid_mb(const char *name, struct object_id *oid)
1104 struct commit *one, *two;
1105 struct commit_list *mbs;
1106 struct object_id oid_tmp;
1110 dots = strstr(name, "...");
1112 return get_oid(name, oid);
1114 st = get_oid("HEAD", &oid_tmp);
1117 strbuf_init(&sb, dots - name);
1118 strbuf_add(&sb, name, dots - name);
1119 st = get_sha1_committish(sb.buf, oid_tmp.hash);
1120 strbuf_release(&sb);
1124 one = lookup_commit_reference_gently(oid_tmp.hash, 0);
1128 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", oid_tmp.hash))
1130 two = lookup_commit_reference_gently(oid_tmp.hash, 0);
1133 mbs = get_merge_bases(one, two);
1134 if (!mbs || mbs->next)
1138 oidcpy(oid, &mbs->item->object.oid);
1140 free_commit_list(mbs);
1144 /* parse @something syntax, when 'something' is not {.*} */
1145 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1149 if (len || name[1] == '{')
1152 /* make sure it's a single @, or @@{.*}, not @foo */
1153 next = memchr(name + len + 1, '@', namelen - len - 1);
1154 if (next && next[1] != '{')
1157 next = name + namelen;
1158 if (next != name + 1)
1162 strbuf_add(buf, "HEAD", 4);
1166 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1168 /* we have extra data, which might need further processing */
1169 struct strbuf tmp = STRBUF_INIT;
1170 int used = buf->len;
1173 strbuf_add(buf, name + len, namelen - len);
1174 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1175 /* that data was not interpreted, remove our cruft */
1177 strbuf_setlen(buf, used);
1181 strbuf_addbuf(buf, &tmp);
1182 strbuf_release(&tmp);
1183 /* tweak for size of {-N} versus expanded ref name */
1184 return ret - used + len;
1187 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1189 char *s = shorten_unambiguous_ref(ref, 0);
1191 strbuf_addstr(buf, s);
1195 static int interpret_branch_mark(const char *name, int namelen,
1196 int at, struct strbuf *buf,
1197 int (*get_mark)(const char *, int),
1198 const char *(*get_data)(struct branch *,
1202 struct branch *branch;
1203 struct strbuf err = STRBUF_INIT;
1206 len = get_mark(name + at, namelen - at);
1210 if (memchr(name, ':', at))
1214 char *name_str = xmemdupz(name, at);
1215 branch = branch_get(name_str);
1218 branch = branch_get(NULL);
1220 value = get_data(branch, &err);
1224 set_shortened_ref(buf, value);
1229 * This reads short-hand syntax that not only evaluates to a commit
1230 * object name, but also can act as if the end user spelled the name
1231 * of the branch from the command line.
1233 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1234 * places the name of the branch in the given buf and returns the
1235 * number of characters parsed if successful.
1237 * - "<branch>@{upstream}" finds the name of the other ref that
1238 * <branch> is configured to merge with (missing <branch> defaults
1239 * to the current branch), and places the name of the branch in the
1240 * given buf and returns the number of characters parsed if
1243 * If the input is not of the accepted format, it returns a negative
1244 * number to signal an error.
1246 * If the input was ok but there are not N branch switches in the
1247 * reflog, it returns 0.
1249 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1253 int len = interpret_nth_prior_checkout(name, namelen, buf);
1256 namelen = strlen(name);
1259 return len; /* syntax Ok, not enough switches */
1260 } else if (len > 0) {
1262 return len; /* consumed all */
1264 return reinterpret(name, namelen, len, buf);
1268 (at = memchr(start, '@', namelen - (start - name)));
1271 len = interpret_empty_at(name, namelen, at - name, buf);
1273 return reinterpret(name, namelen, len, buf);
1275 len = interpret_branch_mark(name, namelen, at - name, buf,
1276 upstream_mark, branch_get_upstream);
1280 len = interpret_branch_mark(name, namelen, at - name, buf,
1281 push_mark, branch_get_push);
1289 int strbuf_branchname(struct strbuf *sb, const char *name)
1291 int len = strlen(name);
1292 int used = interpret_branch_name(name, len, sb);
1298 strbuf_add(sb, name + used, len - used);
1302 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1304 strbuf_branchname(sb, name);
1307 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1308 return check_refname_format(sb->buf, 0);
1312 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1313 * notably "xyz^" for "parent of xyz"
1315 int get_sha1(const char *name, unsigned char *sha1)
1317 struct object_context unused;
1318 return get_sha1_with_context(name, 0, sha1, &unused);
1322 * This is like "get_sha1()", but for struct object_id.
1324 int get_oid(const char *name, struct object_id *oid)
1326 return get_sha1(name, oid->hash);
1331 * Many callers know that the user meant to name a commit-ish by
1332 * syntactical positions where the object name appears. Calling this
1333 * function allows the machinery to disambiguate shorter-than-unique
1334 * abbreviated object names between commit-ish and others.
1336 * Note that this does NOT error out when the named object is not a
1337 * commit-ish. It is merely to give a hint to the disambiguation
1340 int get_sha1_committish(const char *name, unsigned char *sha1)
1342 struct object_context unused;
1343 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1347 int get_sha1_treeish(const char *name, unsigned char *sha1)
1349 struct object_context unused;
1350 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1354 int get_sha1_commit(const char *name, unsigned char *sha1)
1356 struct object_context unused;
1357 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1361 int get_sha1_tree(const char *name, unsigned char *sha1)
1363 struct object_context unused;
1364 return get_sha1_with_context(name, GET_SHA1_TREE,
1368 int get_sha1_blob(const char *name, unsigned char *sha1)
1370 struct object_context unused;
1371 return get_sha1_with_context(name, GET_SHA1_BLOB,
1375 /* Must be called only when object_name:filename doesn't exist. */
1376 static void diagnose_invalid_sha1_path(const char *prefix,
1377 const char *filename,
1378 const unsigned char *tree_sha1,
1379 const char *object_name,
1380 int object_name_len)
1382 unsigned char sha1[20];
1388 if (file_exists(filename))
1389 die("Path '%s' exists on disk, but not in '%.*s'.",
1390 filename, object_name_len, object_name);
1391 if (errno == ENOENT || errno == ENOTDIR) {
1392 char *fullname = xstrfmt("%s%s", prefix, filename);
1394 if (!get_tree_entry(tree_sha1, fullname,
1396 die("Path '%s' exists, but not '%s'.\n"
1397 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1400 object_name_len, object_name,
1402 object_name_len, object_name,
1405 die("Path '%s' does not exist in '%.*s'",
1406 filename, object_name_len, object_name);
1410 /* Must be called only when :stage:filename doesn't exist. */
1411 static void diagnose_invalid_index_path(int stage,
1413 const char *filename)
1415 const struct cache_entry *ce;
1417 unsigned namelen = strlen(filename);
1418 struct strbuf fullname = STRBUF_INIT;
1423 /* Wrong stage number? */
1424 pos = cache_name_pos(filename, namelen);
1427 if (pos < active_nr) {
1428 ce = active_cache[pos];
1429 if (ce_namelen(ce) == namelen &&
1430 !memcmp(ce->name, filename, namelen))
1431 die("Path '%s' is in the index, but not at stage %d.\n"
1432 "Did you mean ':%d:%s'?",
1434 ce_stage(ce), filename);
1437 /* Confusion between relative and absolute filenames? */
1438 strbuf_addstr(&fullname, prefix);
1439 strbuf_addstr(&fullname, filename);
1440 pos = cache_name_pos(fullname.buf, fullname.len);
1443 if (pos < active_nr) {
1444 ce = active_cache[pos];
1445 if (ce_namelen(ce) == fullname.len &&
1446 !memcmp(ce->name, fullname.buf, fullname.len))
1447 die("Path '%s' is in the index, but not '%s'.\n"
1448 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1449 fullname.buf, filename,
1450 ce_stage(ce), fullname.buf,
1451 ce_stage(ce), filename);
1454 if (file_exists(filename))
1455 die("Path '%s' exists on disk, but not in the index.", filename);
1456 if (errno == ENOENT || errno == ENOTDIR)
1457 die("Path '%s' does not exist (neither on disk nor in the index).",
1460 strbuf_release(&fullname);
1464 static char *resolve_relative_path(const char *rel)
1466 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1469 if (!is_inside_work_tree())
1470 die("relative path syntax can't be used outside working tree.");
1472 /* die() inside prefix_path() if resolved path is outside worktree */
1473 return prefix_path(startup_info->prefix,
1474 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1478 static int get_sha1_with_context_1(const char *name,
1481 unsigned char *sha1,
1482 struct object_context *oc)
1484 int ret, bracket_depth;
1485 int namelen = strlen(name);
1487 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1490 flags |= GET_SHA1_QUIETLY;
1492 memset(oc, 0, sizeof(*oc));
1493 oc->mode = S_IFINVALID;
1494 ret = get_sha1_1(name, namelen, sha1, flags);
1498 * sha1:path --> object name of path in ent sha1
1499 * :path -> object name of absolute path in index
1500 * :./path -> object name of path relative to cwd in index
1501 * :[0-3]:path -> object name of path in index at stage
1502 * :/foo -> recent commit matching foo
1504 if (name[0] == ':') {
1506 const struct cache_entry *ce;
1507 char *new_path = NULL;
1509 if (!only_to_die && namelen > 2 && name[1] == '/') {
1510 struct commit_list *list = NULL;
1512 for_each_ref(handle_one_ref, &list);
1513 commit_list_sort_by_date(&list);
1514 return get_sha1_oneline(name + 2, sha1, list);
1518 name[1] < '0' || '3' < name[1])
1521 stage = name[1] - '0';
1524 new_path = resolve_relative_path(cp);
1526 namelen = namelen - (cp - name);
1529 namelen = strlen(cp);
1532 strlcpy(oc->path, cp, sizeof(oc->path));
1536 pos = cache_name_pos(cp, namelen);
1539 while (pos < active_nr) {
1540 ce = active_cache[pos];
1541 if (ce_namelen(ce) != namelen ||
1542 memcmp(ce->name, cp, namelen))
1544 if (ce_stage(ce) == stage) {
1545 hashcpy(sha1, ce->oid.hash);
1546 oc->mode = ce->ce_mode;
1552 if (only_to_die && name[1] && name[1] != '/')
1553 diagnose_invalid_index_path(stage, prefix, cp);
1557 for (cp = name, bracket_depth = 0; *cp; cp++) {
1560 else if (bracket_depth && *cp == '}')
1562 else if (!bracket_depth && *cp == ':')
1566 unsigned char tree_sha1[20];
1567 int len = cp - name;
1568 unsigned sub_flags = flags;
1570 sub_flags &= ~GET_SHA1_DISAMBIGUATORS;
1571 sub_flags |= GET_SHA1_TREEISH;
1573 if (!get_sha1_1(name, len, tree_sha1, sub_flags)) {
1574 const char *filename = cp+1;
1575 char *new_filename = NULL;
1577 new_filename = resolve_relative_path(filename);
1579 filename = new_filename;
1580 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1581 ret = get_tree_entry_follow_symlinks(tree_sha1,
1582 filename, sha1, &oc->symlink_path,
1585 ret = get_tree_entry(tree_sha1, filename,
1587 if (ret && only_to_die) {
1588 diagnose_invalid_sha1_path(prefix,
1594 hashcpy(oc->tree, tree_sha1);
1595 strlcpy(oc->path, filename, sizeof(oc->path));
1601 die("Invalid object name '%.*s'.", len, name);
1608 * Call this function when you know "name" given by the end user must
1609 * name an object but it doesn't; the function _may_ die with a better
1610 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1611 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1612 * you have a chance to diagnose the error further.
1614 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1616 struct object_context oc;
1617 unsigned char sha1[20];
1618 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1621 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1623 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1624 die("BUG: incompatible flags for get_sha1_with_context");
1625 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);