11 static int get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
13 typedef int (*disambiguate_hint_fn)(const unsigned char *, void *);
15 struct disambiguate_state {
16 disambiguate_hint_fn fn;
18 unsigned char candidate[20];
19 unsigned candidate_exists:1;
20 unsigned candidate_checked:1;
21 unsigned candidate_ok:1;
22 unsigned disambiguate_fn_used:1;
24 unsigned always_call_fn:1;
27 static void update_candidates(struct disambiguate_state *ds, const unsigned char *current)
29 if (ds->always_call_fn) {
30 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
33 if (!ds->candidate_exists) {
34 /* this is the first candidate */
35 hashcpy(ds->candidate, current);
36 ds->candidate_exists = 1;
38 } else if (!hashcmp(ds->candidate, current)) {
39 /* the same as what we already have seen */
44 /* cannot disambiguate between ds->candidate and current */
49 if (!ds->candidate_checked) {
50 ds->candidate_ok = ds->fn(ds->candidate, ds->cb_data);
51 ds->disambiguate_fn_used = 1;
52 ds->candidate_checked = 1;
55 if (!ds->candidate_ok) {
56 /* discard the candidate; we know it does not satisfy fn */
57 hashcpy(ds->candidate, current);
58 ds->candidate_checked = 0;
62 /* if we reach this point, we know ds->candidate satisfies fn */
63 if (ds->fn(current, ds->cb_data)) {
65 * if both current and candidate satisfy fn, we cannot
72 /* otherwise, current can be discarded and candidate is still good */
75 static void find_short_object_filename(int len, const char *hex_pfx, struct disambiguate_state *ds)
77 struct alternate_object_database *alt;
79 static struct alternate_object_database *fakeent;
83 * Create a "fake" alternate object database that
84 * points to our own object database, to make it
85 * easier to get a temporary working space in
86 * alt->name/alt->base while iterating over the
87 * object databases including our own.
89 const char *objdir = get_object_directory();
90 int objdir_len = strlen(objdir);
91 int entlen = objdir_len + 43;
92 fakeent = xmalloc(sizeof(*fakeent) + entlen);
93 memcpy(fakeent->base, objdir, objdir_len);
94 fakeent->name = fakeent->base + objdir_len + 1;
95 fakeent->name[-1] = '/';
97 fakeent->next = alt_odb_list;
99 xsnprintf(hex, sizeof(hex), "%.2s", hex_pfx);
100 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
104 * every alt_odb struct has 42 extra bytes after the base
105 * for exactly this purpose
107 xsnprintf(alt->name, 42, "%.2s/", hex_pfx);
108 dir = opendir(alt->base);
112 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
113 unsigned char sha1[20];
115 if (strlen(de->d_name) != 38)
117 if (memcmp(de->d_name, hex_pfx + 2, len - 2))
119 memcpy(hex + 2, de->d_name, 38);
120 if (!get_sha1_hex(hex, sha1))
121 update_candidates(ds, sha1);
127 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
137 if ((*a ^ *b) & 0xf0)
142 static void unique_in_pack(int len,
143 const unsigned char *bin_pfx,
144 struct packed_git *p,
145 struct disambiguate_state *ds)
147 uint32_t num, last, i, first = 0;
148 const unsigned char *current = NULL;
151 num = p->num_objects;
153 while (first < last) {
154 uint32_t mid = (first + last) / 2;
155 const unsigned char *current;
158 current = nth_packed_object_sha1(p, mid);
159 cmp = hashcmp(bin_pfx, current);
172 * At this point, "first" is the location of the lowest object
173 * with an object name that could match "bin_pfx". See if we have
174 * 0, 1 or more objects that actually match(es).
176 for (i = first; i < num && !ds->ambiguous; i++) {
177 current = nth_packed_object_sha1(p, i);
178 if (!match_sha(len, bin_pfx, current))
180 update_candidates(ds, current);
184 static void find_short_packed_object(int len, const unsigned char *bin_pfx,
185 struct disambiguate_state *ds)
187 struct packed_git *p;
189 prepare_packed_git();
190 for (p = packed_git; p && !ds->ambiguous; p = p->next)
191 unique_in_pack(len, bin_pfx, p, ds);
194 #define SHORT_NAME_NOT_FOUND (-1)
195 #define SHORT_NAME_AMBIGUOUS (-2)
197 static int finish_object_disambiguation(struct disambiguate_state *ds,
201 return SHORT_NAME_AMBIGUOUS;
203 if (!ds->candidate_exists)
204 return SHORT_NAME_NOT_FOUND;
206 if (!ds->candidate_checked)
208 * If this is the only candidate, there is no point
209 * calling the disambiguation hint callback.
211 * On the other hand, if the current candidate
212 * replaced an earlier candidate that did _not_ pass
213 * the disambiguation hint callback, then we do have
214 * more than one objects that match the short name
215 * given, so we should make sure this one matches;
216 * otherwise, if we discovered this one and the one
217 * that we previously discarded in the reverse order,
218 * we would end up showing different results in the
221 ds->candidate_ok = (!ds->disambiguate_fn_used ||
222 ds->fn(ds->candidate, ds->cb_data));
224 if (!ds->candidate_ok)
225 return SHORT_NAME_AMBIGUOUS;
227 hashcpy(sha1, ds->candidate);
231 static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
233 int kind = sha1_object_info(sha1, NULL);
234 return kind == OBJ_COMMIT;
237 static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
242 kind = sha1_object_info(sha1, NULL);
243 if (kind == OBJ_COMMIT)
248 /* We need to do this the hard way... */
249 obj = deref_tag(parse_object(sha1), NULL, 0);
250 if (obj && obj->type == OBJ_COMMIT)
255 static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
257 int kind = sha1_object_info(sha1, NULL);
258 return kind == OBJ_TREE;
261 static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
266 kind = sha1_object_info(sha1, NULL);
267 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
272 /* We need to do this the hard way... */
273 obj = deref_tag(lookup_object(sha1), NULL, 0);
274 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
279 static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
281 int kind = sha1_object_info(sha1, NULL);
282 return kind == OBJ_BLOB;
285 static int prepare_prefixes(const char *name, int len,
286 unsigned char *bin_pfx,
292 memset(hex_pfx, 'x', 40);
293 for (i = 0; i < len ;i++) {
294 unsigned char c = name[i];
296 if (c >= '0' && c <= '9')
298 else if (c >= 'a' && c <= 'f')
300 else if (c >= 'A' && c <='F') {
309 bin_pfx[i >> 1] |= val;
314 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
319 unsigned char bin_pfx[20];
320 struct disambiguate_state ds;
321 int quietly = !!(flags & GET_SHA1_QUIETLY);
323 if (len < MINIMUM_ABBREV || len > 40)
325 if (prepare_prefixes(name, len, bin_pfx, hex_pfx) < 0)
330 memset(&ds, 0, sizeof(ds));
331 if (flags & GET_SHA1_COMMIT)
332 ds.fn = disambiguate_commit_only;
333 else if (flags & GET_SHA1_COMMITTISH)
334 ds.fn = disambiguate_committish_only;
335 else if (flags & GET_SHA1_TREE)
336 ds.fn = disambiguate_tree_only;
337 else if (flags & GET_SHA1_TREEISH)
338 ds.fn = disambiguate_treeish_only;
339 else if (flags & GET_SHA1_BLOB)
340 ds.fn = disambiguate_blob_only;
342 find_short_object_filename(len, hex_pfx, &ds);
343 find_short_packed_object(len, bin_pfx, &ds);
344 status = finish_object_disambiguation(&ds, sha1);
346 if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
347 return error("short SHA1 %.*s is ambiguous.", len, hex_pfx);
351 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
354 unsigned char bin_pfx[20];
355 struct disambiguate_state ds;
356 int len = strlen(prefix);
358 if (len < MINIMUM_ABBREV || len > 40)
360 if (prepare_prefixes(prefix, len, bin_pfx, hex_pfx) < 0)
365 memset(&ds, 0, sizeof(ds));
366 ds.always_call_fn = 1;
367 ds.cb_data = cb_data;
370 find_short_object_filename(len, hex_pfx, &ds);
371 find_short_packed_object(len, bin_pfx, &ds);
375 int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
379 sha1_to_hex_r(hex, sha1);
380 if (len == 40 || !len)
382 exists = has_sha1_file(sha1);
384 unsigned char sha1_ret[20];
385 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
388 : status == SHORT_NAME_NOT_FOUND) {
397 const char *find_unique_abbrev(const unsigned char *sha1, int len)
399 static char hex[GIT_SHA1_HEXSZ + 1];
400 find_unique_abbrev_r(hex, sha1, len);
404 static int ambiguous_path(const char *path, int len)
409 for (cnt = 0; cnt < len; cnt++) {
429 static inline int at_mark(const char *string, int len,
430 const char **suffix, int nr)
434 for (i = 0; i < nr; i++) {
435 int suffix_len = strlen(suffix[i]);
436 if (suffix_len <= len
437 && !memcmp(string, suffix[i], suffix_len))
443 static inline int upstream_mark(const char *string, int len)
445 const char *suffix[] = { "upstream", "u" };
446 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
449 static inline int push_mark(const char *string, int len)
451 const char *suffix[] = { "push" };
452 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
455 static inline int publish_mark(const char *string, int len)
457 const char *suffix[] = { "publish", "p" };
458 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
461 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
462 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
464 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
467 static const char *warn_msg = "refname '%.*s' is ambiguous.";
468 static const char *object_name_msg = N_(
469 "Git normally never creates a ref that ends with 40 hex characters\n"
470 "because it will be ignored when you just specify 40-hex. These refs\n"
471 "may be created by mistake. For example,\n"
473 " git checkout -b $br $(git rev-parse ...)\n"
475 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
476 "examine these refs and maybe delete them. Turn this message off by\n"
477 "running \"git config advice.objectNameWarning false\"");
478 unsigned char tmp_sha1[20];
479 char *real_ref = NULL;
481 int at, reflog_len, nth_prior = 0;
483 if (len == 40 && !get_sha1_hex(str, sha1)) {
484 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
485 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
486 if (refs_found > 0) {
487 warning(warn_msg, len, str);
488 if (advice_object_name_warning)
489 fprintf(stderr, "%s\n", _(object_name_msg));
496 /* basic@{time or number or -number} format to query ref-log */
498 if (len && str[len-1] == '}') {
499 for (at = len-4; at >= 0; at--) {
500 if (str[at] == '@' && str[at+1] == '{') {
501 if (str[at+2] == '-') {
503 /* @{-N} not at start */
508 if (!upstream_mark(str + at + 2, len - at - 3) &&
509 !push_mark(str + at + 2, len - at - 3) &&
510 !publish_mark(str + at + 2, len - at - 3)) {
511 reflog_len = (len-1) - (at+2);
519 /* Accept only unambiguous ref paths. */
520 if (len && ambiguous_path(str, len))
524 struct strbuf buf = STRBUF_INIT;
527 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
528 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
529 strbuf_release(&buf);
535 if (!len && reflog_len)
536 /* allow "@{...}" to mean the current branch reflog */
537 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
539 refs_found = dwim_log(str, len, sha1, &real_ref);
541 refs_found = dwim_ref(str, len, sha1, &real_ref);
546 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
548 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
549 warning(warn_msg, len, str);
553 unsigned long at_time;
554 unsigned long co_time;
557 /* Is it asking for N-th entry, or approxidate? */
558 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
559 char ch = str[at+2+i];
560 if ('0' <= ch && ch <= '9')
561 nth = nth * 10 + ch - '0';
565 if (100000000 <= nth) {
572 char *tmp = xstrndup(str + at + 2, reflog_len);
573 at_time = approxidate_careful(tmp, &errors);
580 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
581 &co_time, &co_tz, &co_cnt)) {
583 if (starts_with(real_ref, "refs/heads/")) {
585 len = strlen(real_ref + 11);
593 if (!(flags & GET_SHA1_QUIETLY)) {
594 warning("Log for '%.*s' only goes "
595 "back to %s.", len, str,
596 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
599 if (flags & GET_SHA1_QUIETLY) {
602 die("Log for '%.*s' only has %d entries.",
612 static int get_parent(const char *name, int len,
613 unsigned char *result, int idx)
615 unsigned char sha1[20];
616 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
617 struct commit *commit;
618 struct commit_list *p;
622 commit = lookup_commit_reference(sha1);
623 if (parse_commit(commit))
626 hashcpy(result, commit->object.oid.hash);
632 hashcpy(result, p->item->object.oid.hash);
640 static int get_nth_ancestor(const char *name, int len,
641 unsigned char *result, int generation)
643 unsigned char sha1[20];
644 struct commit *commit;
647 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
650 commit = lookup_commit_reference(sha1);
654 while (generation--) {
655 if (parse_commit(commit) || !commit->parents)
657 commit = commit->parents->item;
659 hashcpy(result, commit->object.oid.hash);
663 struct object *peel_to_type(const char *name, int namelen,
664 struct object *o, enum object_type expected_type)
666 if (name && !namelen)
667 namelen = strlen(name);
669 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
671 if (expected_type == OBJ_ANY || o->type == expected_type)
673 if (o->type == OBJ_TAG)
674 o = ((struct tag*) o)->tagged;
675 else if (o->type == OBJ_COMMIT)
676 o = &(((struct commit *) o)->tree->object);
679 error("%.*s: expected %s type, but the object "
680 "dereferences to %s type",
681 namelen, name, typename(expected_type),
688 static int peel_onion(const char *name, int len, unsigned char *sha1)
690 unsigned char outer[20];
692 unsigned int expected_type = 0;
693 unsigned lookup_flags = 0;
697 * "ref^{type}" dereferences ref repeatedly until you cannot
698 * dereference anymore, or you get an object of given type,
699 * whichever comes first. "ref^{}" means just dereference
700 * tags until you get a non-tag. "ref^0" is a shorthand for
701 * "ref^{commit}". "commit^{tree}" could be used to find the
702 * top-level tree of the given commit.
704 if (len < 4 || name[len-1] != '}')
707 for (sp = name + len - 1; name <= sp; sp--) {
709 if (ch == '{' && name < sp && sp[-1] == '^')
715 sp++; /* beginning of type name, or closing brace for empty */
716 if (starts_with(sp, "commit}"))
717 expected_type = OBJ_COMMIT;
718 else if (starts_with(sp, "tag}"))
719 expected_type = OBJ_TAG;
720 else if (starts_with(sp, "tree}"))
721 expected_type = OBJ_TREE;
722 else if (starts_with(sp, "blob}"))
723 expected_type = OBJ_BLOB;
724 else if (starts_with(sp, "object}"))
725 expected_type = OBJ_ANY;
726 else if (sp[0] == '}')
727 expected_type = OBJ_NONE;
728 else if (sp[0] == '/')
729 expected_type = OBJ_COMMIT;
733 if (expected_type == OBJ_COMMIT)
734 lookup_flags = GET_SHA1_COMMITTISH;
735 else if (expected_type == OBJ_TREE)
736 lookup_flags = GET_SHA1_TREEISH;
738 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
741 o = parse_object(outer);
744 if (!expected_type) {
745 o = deref_tag(o, name, sp - name - 2);
746 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
748 hashcpy(sha1, o->oid.hash);
753 * At this point, the syntax look correct, so
754 * if we do not get the needed object, we should
757 o = peel_to_type(name, len, o, expected_type);
761 hashcpy(sha1, o->oid.hash);
763 /* "$commit^{/foo}" */
766 struct commit_list *list = NULL;
769 * $commit^{/}. Some regex implementation may reject.
770 * We don't need regex anyway. '' pattern always matches.
775 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
776 commit_list_insert((struct commit *)o, &list);
777 ret = get_sha1_oneline(prefix, sha1, list);
784 static int get_describe_name(const char *name, int len, unsigned char *sha1)
787 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
789 for (cp = name + len - 1; name + 2 <= cp; cp--) {
792 /* We must be looking at g in "SOMETHING-g"
793 * for it to be describe output.
795 if (ch == 'g' && cp[-1] == '-') {
798 return get_short_sha1(cp, len, sha1, flags);
805 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
811 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
814 for (cp = name + len - 1; name <= cp; cp--) {
816 if ('0' <= ch && ch <= '9')
818 if (ch == '~' || ch == '^')
825 int len1 = cp - name;
827 while (cp < name + len)
828 num = num * 10 + *cp++ - '0';
829 if (!num && len1 == len - 1)
831 if (has_suffix == '^')
832 return get_parent(name, len1, sha1, num);
833 /* else if (has_suffix == '~') -- goes without saying */
834 return get_nth_ancestor(name, len1, sha1, num);
837 ret = peel_onion(name, len, sha1);
841 ret = get_sha1_basic(name, len, sha1, lookup_flags);
845 /* It could be describe output that is "SOMETHING-gXXXX" */
846 ret = get_describe_name(name, len, sha1);
850 return get_short_sha1(name, len, sha1, lookup_flags);
854 * This interprets names like ':/Initial revision of "git"' by searching
855 * through history and returning the first commit whose message starts
856 * the given regular expression.
858 * For future extension, ':/!' is reserved. If you want to match a message
859 * beginning with a '!', you have to repeat the exclamation mark.
862 /* Remember to update object flag allocation in object.h */
863 #define ONELINE_SEEN (1u<<20)
865 static int handle_one_ref(const char *path, const struct object_id *oid,
866 int flag, void *cb_data)
868 struct commit_list **list = cb_data;
869 struct object *object = parse_object(oid->hash);
872 if (object->type == OBJ_TAG) {
873 object = deref_tag(object, path, strlen(path));
877 if (object->type != OBJ_COMMIT)
879 commit_list_insert((struct commit *)object, list);
883 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
884 struct commit_list *list)
886 struct commit_list *backup = NULL, *l;
890 if (prefix[0] == '!') {
891 if (prefix[1] != '!')
892 die ("Invalid search pattern: %s", prefix);
896 if (regcomp(®ex, prefix, REG_EXTENDED))
897 die("Invalid search pattern: %s", prefix);
899 for (l = list; l; l = l->next) {
900 l->item->object.flags |= ONELINE_SEEN;
901 commit_list_insert(l->item, &backup);
905 struct commit *commit;
908 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
909 if (!parse_object(commit->object.oid.hash))
911 buf = get_commit_buffer(commit, NULL);
912 p = strstr(buf, "\n\n");
913 matches = p && !regexec(®ex, p + 2, 0, NULL, 0);
914 unuse_commit_buffer(commit, buf);
917 hashcpy(sha1, commit->object.oid.hash);
923 free_commit_list(list);
924 for (l = backup; l; l = l->next)
925 clear_commit_marks(l->item, ONELINE_SEEN);
926 free_commit_list(backup);
927 return found ? 0 : -1;
930 struct grab_nth_branch_switch_cbdata {
935 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
936 const char *email, unsigned long timestamp, int tz,
937 const char *message, void *cb_data)
939 struct grab_nth_branch_switch_cbdata *cb = cb_data;
940 const char *match = NULL, *target = NULL;
943 if (skip_prefix(message, "checkout: moving from ", &match))
944 target = strstr(match, " to ");
946 if (!match || !target)
948 if (--(cb->remaining) == 0) {
949 len = target - match;
950 strbuf_reset(&cb->buf);
951 strbuf_add(&cb->buf, match, len);
952 return 1; /* we are done */
958 * Parse @{-N} syntax, return the number of characters parsed
959 * if successful; otherwise signal an error with negative value.
961 static int interpret_nth_prior_checkout(const char *name, int namelen,
966 struct grab_nth_branch_switch_cbdata cb;
972 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
974 brace = memchr(name, '}', namelen);
977 nth = strtol(name + 3, &num_end, 10);
978 if (num_end != brace)
983 strbuf_init(&cb.buf, 20);
986 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
988 strbuf_addbuf(buf, &cb.buf);
989 retval = brace - name + 1;
992 strbuf_release(&cb.buf);
996 int get_sha1_mb(const char *name, unsigned char *sha1)
998 struct commit *one, *two;
999 struct commit_list *mbs;
1000 unsigned char sha1_tmp[20];
1004 dots = strstr(name, "...");
1006 return get_sha1(name, sha1);
1008 st = get_sha1("HEAD", sha1_tmp);
1011 strbuf_init(&sb, dots - name);
1012 strbuf_add(&sb, name, dots - name);
1013 st = get_sha1_committish(sb.buf, sha1_tmp);
1014 strbuf_release(&sb);
1018 one = lookup_commit_reference_gently(sha1_tmp, 0);
1022 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
1024 two = lookup_commit_reference_gently(sha1_tmp, 0);
1027 mbs = get_merge_bases(one, two);
1028 if (!mbs || mbs->next)
1032 hashcpy(sha1, mbs->item->object.oid.hash);
1034 free_commit_list(mbs);
1038 /* parse @something syntax, when 'something' is not {.*} */
1039 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1043 if (len || name[1] == '{')
1046 /* make sure it's a single @, or @@{.*}, not @foo */
1047 next = memchr(name + len + 1, '@', namelen - len - 1);
1048 if (next && next[1] != '{')
1051 next = name + namelen;
1052 if (next != name + 1)
1056 strbuf_add(buf, "HEAD", 4);
1060 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1062 /* we have extra data, which might need further processing */
1063 struct strbuf tmp = STRBUF_INIT;
1064 int used = buf->len;
1067 strbuf_add(buf, name + len, namelen - len);
1068 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1069 /* that data was not interpreted, remove our cruft */
1071 strbuf_setlen(buf, used);
1075 strbuf_addbuf(buf, &tmp);
1076 strbuf_release(&tmp);
1077 /* tweak for size of {-N} versus expanded ref name */
1078 return ret - used + len;
1081 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1083 char *s = shorten_unambiguous_ref(ref, 0);
1085 strbuf_addstr(buf, s);
1089 static int interpret_branch_mark(const char *name, int namelen,
1090 int at, struct strbuf *buf,
1091 int (*get_mark)(const char *, int),
1092 const char *(*get_data)(struct branch *,
1096 struct branch *branch;
1097 struct strbuf err = STRBUF_INIT;
1100 if (name[at + 1] != '{' || name[namelen - 1] != '}')
1103 len = get_mark(name + at + 2, namelen - at - 3);
1107 if (memchr(name, ':', at))
1111 char *name_str = xmemdupz(name, at);
1112 branch = branch_get(name_str);
1115 branch = branch_get(NULL);
1117 value = get_data(branch, &err);
1121 set_shortened_ref(buf, value);
1122 return len + at + 3;
1126 * This reads short-hand syntax that not only evaluates to a commit
1127 * object name, but also can act as if the end user spelled the name
1128 * of the branch from the command line.
1130 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1131 * places the name of the branch in the given buf and returns the
1132 * number of characters parsed if successful.
1134 * - "<branch>@{upstream}" finds the name of the other ref that
1135 * <branch> is configured to merge with (missing <branch> defaults
1136 * to the current branch), and places the name of the branch in the
1137 * given buf and returns the number of characters parsed if
1140 * If the input is not of the accepted format, it returns a negative
1141 * number to signal an error.
1143 * If the input was ok but there are not N branch switches in the
1144 * reflog, it returns 0.
1146 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1150 int len = interpret_nth_prior_checkout(name, namelen, buf);
1153 namelen = strlen(name);
1156 return len; /* syntax Ok, not enough switches */
1157 } else if (len > 0) {
1159 return len; /* consumed all */
1161 return reinterpret(name, namelen, len, buf);
1165 (at = memchr(start, '@', namelen - (start - name)));
1168 len = interpret_empty_at(name, namelen, at - name, buf);
1170 return reinterpret(name, namelen, len, buf);
1172 len = interpret_branch_mark(name, namelen, at - name, buf,
1173 upstream_mark, branch_get_upstream);
1177 len = interpret_branch_mark(name, namelen, at - name, buf,
1178 push_mark, branch_get_push);
1182 len = interpret_branch_mark(name, namelen, at - name, buf,
1183 publish_mark, branch_get_publish);
1191 int strbuf_branchname(struct strbuf *sb, const char *name)
1193 int len = strlen(name);
1194 int used = interpret_branch_name(name, len, sb);
1200 strbuf_add(sb, name + used, len - used);
1204 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1206 strbuf_branchname(sb, name);
1209 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1210 return check_refname_format(sb->buf, 0);
1214 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1215 * notably "xyz^" for "parent of xyz"
1217 int get_sha1(const char *name, unsigned char *sha1)
1219 struct object_context unused;
1220 return get_sha1_with_context(name, 0, sha1, &unused);
1224 * Many callers know that the user meant to name a commit-ish by
1225 * syntactical positions where the object name appears. Calling this
1226 * function allows the machinery to disambiguate shorter-than-unique
1227 * abbreviated object names between commit-ish and others.
1229 * Note that this does NOT error out when the named object is not a
1230 * commit-ish. It is merely to give a hint to the disambiguation
1233 int get_sha1_committish(const char *name, unsigned char *sha1)
1235 struct object_context unused;
1236 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1240 int get_sha1_treeish(const char *name, unsigned char *sha1)
1242 struct object_context unused;
1243 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1247 int get_sha1_commit(const char *name, unsigned char *sha1)
1249 struct object_context unused;
1250 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1254 int get_sha1_tree(const char *name, unsigned char *sha1)
1256 struct object_context unused;
1257 return get_sha1_with_context(name, GET_SHA1_TREE,
1261 int get_sha1_blob(const char *name, unsigned char *sha1)
1263 struct object_context unused;
1264 return get_sha1_with_context(name, GET_SHA1_BLOB,
1268 /* Must be called only when object_name:filename doesn't exist. */
1269 static void diagnose_invalid_sha1_path(const char *prefix,
1270 const char *filename,
1271 const unsigned char *tree_sha1,
1272 const char *object_name,
1273 int object_name_len)
1275 unsigned char sha1[20];
1281 if (file_exists(filename))
1282 die("Path '%s' exists on disk, but not in '%.*s'.",
1283 filename, object_name_len, object_name);
1284 if (errno == ENOENT || errno == ENOTDIR) {
1285 char *fullname = xstrfmt("%s%s", prefix, filename);
1287 if (!get_tree_entry(tree_sha1, fullname,
1289 die("Path '%s' exists, but not '%s'.\n"
1290 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1293 object_name_len, object_name,
1295 object_name_len, object_name,
1298 die("Path '%s' does not exist in '%.*s'",
1299 filename, object_name_len, object_name);
1303 /* Must be called only when :stage:filename doesn't exist. */
1304 static void diagnose_invalid_index_path(int stage,
1306 const char *filename)
1308 const struct cache_entry *ce;
1310 unsigned namelen = strlen(filename);
1311 struct strbuf fullname = STRBUF_INIT;
1316 /* Wrong stage number? */
1317 pos = cache_name_pos(filename, namelen);
1320 if (pos < active_nr) {
1321 ce = active_cache[pos];
1322 if (ce_namelen(ce) == namelen &&
1323 !memcmp(ce->name, filename, namelen))
1324 die("Path '%s' is in the index, but not at stage %d.\n"
1325 "Did you mean ':%d:%s'?",
1327 ce_stage(ce), filename);
1330 /* Confusion between relative and absolute filenames? */
1331 strbuf_addstr(&fullname, prefix);
1332 strbuf_addstr(&fullname, filename);
1333 pos = cache_name_pos(fullname.buf, fullname.len);
1336 if (pos < active_nr) {
1337 ce = active_cache[pos];
1338 if (ce_namelen(ce) == fullname.len &&
1339 !memcmp(ce->name, fullname.buf, fullname.len))
1340 die("Path '%s' is in the index, but not '%s'.\n"
1341 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1342 fullname.buf, filename,
1343 ce_stage(ce), fullname.buf,
1344 ce_stage(ce), filename);
1347 if (file_exists(filename))
1348 die("Path '%s' exists on disk, but not in the index.", filename);
1349 if (errno == ENOENT || errno == ENOTDIR)
1350 die("Path '%s' does not exist (neither on disk nor in the index).",
1353 strbuf_release(&fullname);
1357 static char *resolve_relative_path(const char *rel)
1359 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1363 die("BUG: startup_info struct is not initialized.");
1365 if (!is_inside_work_tree())
1366 die("relative path syntax can't be used outside working tree.");
1368 /* die() inside prefix_path() if resolved path is outside worktree */
1369 return prefix_path(startup_info->prefix,
1370 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1374 static int get_sha1_with_context_1(const char *name,
1377 unsigned char *sha1,
1378 struct object_context *oc)
1380 int ret, bracket_depth;
1381 int namelen = strlen(name);
1383 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1385 memset(oc, 0, sizeof(*oc));
1386 oc->mode = S_IFINVALID;
1387 ret = get_sha1_1(name, namelen, sha1, flags);
1391 * sha1:path --> object name of path in ent sha1
1392 * :path -> object name of absolute path in index
1393 * :./path -> object name of path relative to cwd in index
1394 * :[0-3]:path -> object name of path in index at stage
1395 * :/foo -> recent commit matching foo
1397 if (name[0] == ':') {
1399 const struct cache_entry *ce;
1400 char *new_path = NULL;
1402 if (!only_to_die && namelen > 2 && name[1] == '/') {
1403 struct commit_list *list = NULL;
1405 for_each_ref(handle_one_ref, &list);
1406 commit_list_sort_by_date(&list);
1407 return get_sha1_oneline(name + 2, sha1, list);
1411 name[1] < '0' || '3' < name[1])
1414 stage = name[1] - '0';
1417 new_path = resolve_relative_path(cp);
1419 namelen = namelen - (cp - name);
1422 namelen = strlen(cp);
1425 strlcpy(oc->path, cp, sizeof(oc->path));
1429 pos = cache_name_pos(cp, namelen);
1432 while (pos < active_nr) {
1433 ce = active_cache[pos];
1434 if (ce_namelen(ce) != namelen ||
1435 memcmp(ce->name, cp, namelen))
1437 if (ce_stage(ce) == stage) {
1438 hashcpy(sha1, ce->sha1);
1439 oc->mode = ce->ce_mode;
1445 if (only_to_die && name[1] && name[1] != '/')
1446 diagnose_invalid_index_path(stage, prefix, cp);
1450 for (cp = name, bracket_depth = 0; *cp; cp++) {
1453 else if (bracket_depth && *cp == '}')
1455 else if (!bracket_depth && *cp == ':')
1459 unsigned char tree_sha1[20];
1460 int len = cp - name;
1461 if (!get_sha1_1(name, len, tree_sha1, GET_SHA1_TREEISH)) {
1462 const char *filename = cp+1;
1463 char *new_filename = NULL;
1465 new_filename = resolve_relative_path(filename);
1467 filename = new_filename;
1468 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1469 ret = get_tree_entry_follow_symlinks(tree_sha1,
1470 filename, sha1, &oc->symlink_path,
1473 ret = get_tree_entry(tree_sha1, filename,
1475 if (ret && only_to_die) {
1476 diagnose_invalid_sha1_path(prefix,
1482 hashcpy(oc->tree, tree_sha1);
1483 strlcpy(oc->path, filename, sizeof(oc->path));
1489 die("Invalid object name '%.*s'.", len, name);
1496 * Call this function when you know "name" given by the end user must
1497 * name an object but it doesn't; the function _may_ die with a better
1498 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1499 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1500 * you have a chance to diagnose the error further.
1502 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1504 struct object_context oc;
1505 unsigned char sha1[20];
1506 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1509 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1511 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1512 die("BUG: incompatible flags for get_sha1_with_context");
1513 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);