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 sprintf(hex, "%.2s", hex_pfx);
100 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
103 sprintf(alt->name, "%.2s/", hex_pfx);
104 dir = opendir(alt->base);
108 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
109 unsigned char sha1[20];
111 if (strlen(de->d_name) != 38)
113 if (memcmp(de->d_name, hex_pfx + 2, len - 2))
115 memcpy(hex + 2, de->d_name, 38);
116 if (!get_sha1_hex(hex, sha1))
117 update_candidates(ds, sha1);
123 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
133 if ((*a ^ *b) & 0xf0)
138 static void unique_in_pack(int len,
139 const unsigned char *bin_pfx,
140 struct packed_git *p,
141 struct disambiguate_state *ds)
143 uint32_t num, last, i, first = 0;
144 const unsigned char *current = NULL;
147 num = p->num_objects;
149 while (first < last) {
150 uint32_t mid = (first + last) / 2;
151 const unsigned char *current;
154 current = nth_packed_object_sha1(p, mid);
155 cmp = hashcmp(bin_pfx, current);
168 * At this point, "first" is the location of the lowest object
169 * with an object name that could match "bin_pfx". See if we have
170 * 0, 1 or more objects that actually match(es).
172 for (i = first; i < num && !ds->ambiguous; i++) {
173 current = nth_packed_object_sha1(p, i);
174 if (!match_sha(len, bin_pfx, current))
176 update_candidates(ds, current);
180 static void find_short_packed_object(int len, const unsigned char *bin_pfx,
181 struct disambiguate_state *ds)
183 struct packed_git *p;
185 prepare_packed_git();
186 for (p = packed_git; p && !ds->ambiguous; p = p->next)
187 unique_in_pack(len, bin_pfx, p, ds);
190 #define SHORT_NAME_NOT_FOUND (-1)
191 #define SHORT_NAME_AMBIGUOUS (-2)
193 static int finish_object_disambiguation(struct disambiguate_state *ds,
197 return SHORT_NAME_AMBIGUOUS;
199 if (!ds->candidate_exists)
200 return SHORT_NAME_NOT_FOUND;
202 if (!ds->candidate_checked)
204 * If this is the only candidate, there is no point
205 * calling the disambiguation hint callback.
207 * On the other hand, if the current candidate
208 * replaced an earlier candidate that did _not_ pass
209 * the disambiguation hint callback, then we do have
210 * more than one objects that match the short name
211 * given, so we should make sure this one matches;
212 * otherwise, if we discovered this one and the one
213 * that we previously discarded in the reverse order,
214 * we would end up showing different results in the
217 ds->candidate_ok = (!ds->disambiguate_fn_used ||
218 ds->fn(ds->candidate, ds->cb_data));
220 if (!ds->candidate_ok)
221 return SHORT_NAME_AMBIGUOUS;
223 hashcpy(sha1, ds->candidate);
227 static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
229 int kind = sha1_object_info(sha1, NULL);
230 return kind == OBJ_COMMIT;
233 static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
238 kind = sha1_object_info(sha1, NULL);
239 if (kind == OBJ_COMMIT)
244 /* We need to do this the hard way... */
245 obj = deref_tag(parse_object(sha1), NULL, 0);
246 if (obj && obj->type == OBJ_COMMIT)
251 static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
253 int kind = sha1_object_info(sha1, NULL);
254 return kind == OBJ_TREE;
257 static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
262 kind = sha1_object_info(sha1, NULL);
263 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
268 /* We need to do this the hard way... */
269 obj = deref_tag(lookup_object(sha1), NULL, 0);
270 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
275 static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
277 int kind = sha1_object_info(sha1, NULL);
278 return kind == OBJ_BLOB;
281 static int prepare_prefixes(const char *name, int len,
282 unsigned char *bin_pfx,
288 memset(hex_pfx, 'x', 40);
289 for (i = 0; i < len ;i++) {
290 unsigned char c = name[i];
292 if (c >= '0' && c <= '9')
294 else if (c >= 'a' && c <= 'f')
296 else if (c >= 'A' && c <='F') {
305 bin_pfx[i >> 1] |= val;
310 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
315 unsigned char bin_pfx[20];
316 struct disambiguate_state ds;
317 int quietly = !!(flags & GET_SHA1_QUIETLY);
319 if (len < MINIMUM_ABBREV || len > 40)
321 if (prepare_prefixes(name, len, bin_pfx, hex_pfx) < 0)
326 memset(&ds, 0, sizeof(ds));
327 if (flags & GET_SHA1_COMMIT)
328 ds.fn = disambiguate_commit_only;
329 else if (flags & GET_SHA1_COMMITTISH)
330 ds.fn = disambiguate_committish_only;
331 else if (flags & GET_SHA1_TREE)
332 ds.fn = disambiguate_tree_only;
333 else if (flags & GET_SHA1_TREEISH)
334 ds.fn = disambiguate_treeish_only;
335 else if (flags & GET_SHA1_BLOB)
336 ds.fn = disambiguate_blob_only;
338 find_short_object_filename(len, hex_pfx, &ds);
339 find_short_packed_object(len, bin_pfx, &ds);
340 status = finish_object_disambiguation(&ds, sha1);
342 if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
343 return error("short SHA1 %.*s is ambiguous.", len, hex_pfx);
347 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
350 unsigned char bin_pfx[20];
351 struct disambiguate_state ds;
352 int len = strlen(prefix);
354 if (len < MINIMUM_ABBREV || len > 40)
356 if (prepare_prefixes(prefix, len, bin_pfx, hex_pfx) < 0)
361 memset(&ds, 0, sizeof(ds));
362 ds.always_call_fn = 1;
363 ds.cb_data = cb_data;
366 find_short_object_filename(len, hex_pfx, &ds);
367 find_short_packed_object(len, bin_pfx, &ds);
371 const char *find_unique_abbrev(const unsigned char *sha1, int len)
376 memcpy(hex, sha1_to_hex(sha1), 40);
377 if (len == 40 || !len)
379 exists = has_sha1_file(sha1);
381 unsigned char sha1_ret[20];
382 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
385 : status == SHORT_NAME_NOT_FOUND) {
394 static int ambiguous_path(const char *path, int len)
399 for (cnt = 0; cnt < len; cnt++) {
419 static inline int upstream_mark(const char *string, int len)
421 const char *suffix[] = { "@{upstream}", "@{u}" };
424 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
425 int suffix_len = strlen(suffix[i]);
426 if (suffix_len <= len
427 && !memcmp(string, suffix[i], suffix_len))
433 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
434 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
436 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
439 static const char *warn_msg = "refname '%.*s' is ambiguous.";
440 static const char *object_name_msg = N_(
441 "Git normally never creates a ref that ends with 40 hex characters\n"
442 "because it will be ignored when you just specify 40-hex. These refs\n"
443 "may be created by mistake. For example,\n"
445 " git checkout -b $br $(git rev-parse ...)\n"
447 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
448 "examine these refs and maybe delete them. Turn this message off by\n"
449 "running \"git config advice.objectNameWarning false\"");
450 unsigned char tmp_sha1[20];
451 char *real_ref = NULL;
453 int at, reflog_len, nth_prior = 0;
455 if (len == 40 && !get_sha1_hex(str, sha1)) {
456 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
457 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
458 if (refs_found > 0) {
459 warning(warn_msg, len, str);
460 if (advice_object_name_warning)
461 fprintf(stderr, "%s\n", _(object_name_msg));
468 /* basic@{time or number or -number} format to query ref-log */
470 if (len && str[len-1] == '}') {
471 for (at = len-4; at >= 0; at--) {
472 if (str[at] == '@' && str[at+1] == '{') {
473 if (str[at+2] == '-') {
475 /* @{-N} not at start */
480 if (!upstream_mark(str + at, len - at)) {
481 reflog_len = (len-1) - (at+2);
489 /* Accept only unambiguous ref paths. */
490 if (len && ambiguous_path(str, len))
494 struct strbuf buf = STRBUF_INIT;
497 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
498 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
499 strbuf_release(&buf);
505 if (!len && reflog_len)
506 /* allow "@{...}" to mean the current branch reflog */
507 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
509 refs_found = dwim_log(str, len, sha1, &real_ref);
511 refs_found = dwim_ref(str, len, sha1, &real_ref);
516 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
518 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
519 warning(warn_msg, len, str);
523 unsigned long at_time;
524 unsigned long co_time;
527 /* Is it asking for N-th entry, or approxidate? */
528 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
529 char ch = str[at+2+i];
530 if ('0' <= ch && ch <= '9')
531 nth = nth * 10 + ch - '0';
535 if (100000000 <= nth) {
542 char *tmp = xstrndup(str + at + 2, reflog_len);
543 at_time = approxidate_careful(tmp, &errors);
550 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
551 &co_time, &co_tz, &co_cnt)) {
553 if (starts_with(real_ref, "refs/heads/")) {
555 len = strlen(real_ref + 11);
563 if (!(flags & GET_SHA1_QUIETLY)) {
564 warning("Log for '%.*s' only goes "
565 "back to %s.", len, str,
566 show_date(co_time, co_tz, DATE_RFC2822));
569 if (flags & GET_SHA1_QUIETLY) {
572 die("Log for '%.*s' only has %d entries.",
582 static int get_parent(const char *name, int len,
583 unsigned char *result, int idx)
585 unsigned char sha1[20];
586 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
587 struct commit *commit;
588 struct commit_list *p;
592 commit = lookup_commit_reference(sha1);
593 if (parse_commit(commit))
596 hashcpy(result, commit->object.sha1);
602 hashcpy(result, p->item->object.sha1);
610 static int get_nth_ancestor(const char *name, int len,
611 unsigned char *result, int generation)
613 unsigned char sha1[20];
614 struct commit *commit;
617 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
620 commit = lookup_commit_reference(sha1);
624 while (generation--) {
625 if (parse_commit(commit) || !commit->parents)
627 commit = commit->parents->item;
629 hashcpy(result, commit->object.sha1);
633 struct object *peel_to_type(const char *name, int namelen,
634 struct object *o, enum object_type expected_type)
636 if (name && !namelen)
637 namelen = strlen(name);
639 if (!o || (!o->parsed && !parse_object(o->sha1)))
641 if (expected_type == OBJ_ANY || o->type == expected_type)
643 if (o->type == OBJ_TAG)
644 o = ((struct tag*) o)->tagged;
645 else if (o->type == OBJ_COMMIT)
646 o = &(((struct commit *) o)->tree->object);
649 error("%.*s: expected %s type, but the object "
650 "dereferences to %s type",
651 namelen, name, typename(expected_type),
658 static int peel_onion(const char *name, int len, unsigned char *sha1)
660 unsigned char outer[20];
662 unsigned int expected_type = 0;
663 unsigned lookup_flags = 0;
667 * "ref^{type}" dereferences ref repeatedly until you cannot
668 * dereference anymore, or you get an object of given type,
669 * whichever comes first. "ref^{}" means just dereference
670 * tags until you get a non-tag. "ref^0" is a shorthand for
671 * "ref^{commit}". "commit^{tree}" could be used to find the
672 * top-level tree of the given commit.
674 if (len < 4 || name[len-1] != '}')
677 for (sp = name + len - 1; name <= sp; sp--) {
679 if (ch == '{' && name < sp && sp[-1] == '^')
685 sp++; /* beginning of type name, or closing brace for empty */
686 if (starts_with(sp, "commit}"))
687 expected_type = OBJ_COMMIT;
688 else if (starts_with(sp, "tag}"))
689 expected_type = OBJ_TAG;
690 else if (starts_with(sp, "tree}"))
691 expected_type = OBJ_TREE;
692 else if (starts_with(sp, "blob}"))
693 expected_type = OBJ_BLOB;
694 else if (starts_with(sp, "object}"))
695 expected_type = OBJ_ANY;
696 else if (sp[0] == '}')
697 expected_type = OBJ_NONE;
698 else if (sp[0] == '/')
699 expected_type = OBJ_COMMIT;
703 if (expected_type == OBJ_COMMIT)
704 lookup_flags = GET_SHA1_COMMITTISH;
705 else if (expected_type == OBJ_TREE)
706 lookup_flags = GET_SHA1_TREEISH;
708 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
711 o = parse_object(outer);
714 if (!expected_type) {
715 o = deref_tag(o, name, sp - name - 2);
716 if (!o || (!o->parsed && !parse_object(o->sha1)))
718 hashcpy(sha1, o->sha1);
723 * At this point, the syntax look correct, so
724 * if we do not get the needed object, we should
727 o = peel_to_type(name, len, o, expected_type);
731 hashcpy(sha1, o->sha1);
733 /* "$commit^{/foo}" */
736 struct commit_list *list = NULL;
739 * $commit^{/}. Some regex implementation may reject.
740 * We don't need regex anyway. '' pattern always matches.
745 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
746 commit_list_insert((struct commit *)o, &list);
747 ret = get_sha1_oneline(prefix, sha1, list);
754 static int get_describe_name(const char *name, int len, unsigned char *sha1)
757 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
759 for (cp = name + len - 1; name + 2 <= cp; cp--) {
762 /* We must be looking at g in "SOMETHING-g"
763 * for it to be describe output.
765 if (ch == 'g' && cp[-1] == '-') {
768 return get_short_sha1(cp, len, sha1, flags);
775 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
781 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
784 for (cp = name + len - 1; name <= cp; cp--) {
786 if ('0' <= ch && ch <= '9')
788 if (ch == '~' || ch == '^')
795 int len1 = cp - name;
797 while (cp < name + len)
798 num = num * 10 + *cp++ - '0';
799 if (!num && len1 == len - 1)
801 if (has_suffix == '^')
802 return get_parent(name, len1, sha1, num);
803 /* else if (has_suffix == '~') -- goes without saying */
804 return get_nth_ancestor(name, len1, sha1, num);
807 ret = peel_onion(name, len, sha1);
811 ret = get_sha1_basic(name, len, sha1, lookup_flags);
815 /* It could be describe output that is "SOMETHING-gXXXX" */
816 ret = get_describe_name(name, len, sha1);
820 return get_short_sha1(name, len, sha1, lookup_flags);
824 * This interprets names like ':/Initial revision of "git"' by searching
825 * through history and returning the first commit whose message starts
826 * the given regular expression.
828 * For future extension, ':/!' is reserved. If you want to match a message
829 * beginning with a '!', you have to repeat the exclamation mark.
832 /* Remember to update object flag allocation in object.h */
833 #define ONELINE_SEEN (1u<<20)
835 static int handle_one_ref(const char *path,
836 const unsigned char *sha1, int flag, void *cb_data)
838 struct commit_list **list = cb_data;
839 struct object *object = parse_object(sha1);
842 if (object->type == OBJ_TAG) {
843 object = deref_tag(object, path, strlen(path));
847 if (object->type != OBJ_COMMIT)
849 commit_list_insert((struct commit *)object, list);
853 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
854 struct commit_list *list)
856 struct commit_list *backup = NULL, *l;
860 if (prefix[0] == '!') {
861 if (prefix[1] != '!')
862 die ("Invalid search pattern: %s", prefix);
866 if (regcomp(®ex, prefix, REG_EXTENDED))
867 die("Invalid search pattern: %s", prefix);
869 for (l = list; l; l = l->next) {
870 l->item->object.flags |= ONELINE_SEEN;
871 commit_list_insert(l->item, &backup);
875 struct commit *commit;
878 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
879 if (!parse_object(commit->object.sha1))
881 buf = get_commit_buffer(commit, NULL);
882 p = strstr(buf, "\n\n");
883 matches = p && !regexec(®ex, p + 2, 0, NULL, 0);
884 unuse_commit_buffer(commit, buf);
887 hashcpy(sha1, commit->object.sha1);
893 free_commit_list(list);
894 for (l = backup; l; l = l->next)
895 clear_commit_marks(l->item, ONELINE_SEEN);
896 free_commit_list(backup);
897 return found ? 0 : -1;
900 struct grab_nth_branch_switch_cbdata {
905 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
906 const char *email, unsigned long timestamp, int tz,
907 const char *message, void *cb_data)
909 struct grab_nth_branch_switch_cbdata *cb = cb_data;
910 const char *match = NULL, *target = NULL;
913 if (skip_prefix(message, "checkout: moving from ", &match))
914 target = strstr(match, " to ");
916 if (!match || !target)
918 if (--(cb->remaining) == 0) {
919 len = target - match;
920 strbuf_reset(&cb->buf);
921 strbuf_add(&cb->buf, match, len);
922 return 1; /* we are done */
928 * Parse @{-N} syntax, return the number of characters parsed
929 * if successful; otherwise signal an error with negative value.
931 static int interpret_nth_prior_checkout(const char *name, int namelen,
936 struct grab_nth_branch_switch_cbdata cb;
942 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
944 brace = memchr(name, '}', namelen);
947 nth = strtol(name + 3, &num_end, 10);
948 if (num_end != brace)
953 strbuf_init(&cb.buf, 20);
956 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
958 strbuf_addbuf(buf, &cb.buf);
959 retval = brace - name + 1;
962 strbuf_release(&cb.buf);
966 int get_sha1_mb(const char *name, unsigned char *sha1)
968 struct commit *one, *two;
969 struct commit_list *mbs;
970 unsigned char sha1_tmp[20];
974 dots = strstr(name, "...");
976 return get_sha1(name, sha1);
978 st = get_sha1("HEAD", sha1_tmp);
981 strbuf_init(&sb, dots - name);
982 strbuf_add(&sb, name, dots - name);
983 st = get_sha1_committish(sb.buf, sha1_tmp);
988 one = lookup_commit_reference_gently(sha1_tmp, 0);
992 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
994 two = lookup_commit_reference_gently(sha1_tmp, 0);
997 mbs = get_merge_bases(one, two);
998 if (!mbs || mbs->next)
1002 hashcpy(sha1, mbs->item->object.sha1);
1004 free_commit_list(mbs);
1008 /* parse @something syntax, when 'something' is not {.*} */
1009 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1013 if (len || name[1] == '{')
1016 /* make sure it's a single @, or @@{.*}, not @foo */
1017 next = memchr(name + len + 1, '@', namelen - len - 1);
1018 if (next && next[1] != '{')
1021 next = name + namelen;
1022 if (next != name + 1)
1026 strbuf_add(buf, "HEAD", 4);
1030 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1032 /* we have extra data, which might need further processing */
1033 struct strbuf tmp = STRBUF_INIT;
1034 int used = buf->len;
1037 strbuf_add(buf, name + len, namelen - len);
1038 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1039 /* that data was not interpreted, remove our cruft */
1041 strbuf_setlen(buf, used);
1045 strbuf_addbuf(buf, &tmp);
1046 strbuf_release(&tmp);
1047 /* tweak for size of {-N} versus expanded ref name */
1048 return ret - used + len;
1051 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1053 char *s = shorten_unambiguous_ref(ref, 0);
1055 strbuf_addstr(buf, s);
1059 static const char *get_upstream_branch(const char *branch_buf, int len)
1061 char *branch = xstrndup(branch_buf, len);
1062 struct branch *upstream = branch_get(*branch ? branch : NULL);
1065 * Upstream can be NULL only if branch refers to HEAD and HEAD
1066 * points to something different than a branch.
1069 die(_("HEAD does not point to a branch"));
1070 if (!upstream->merge || !upstream->merge[0]->dst) {
1071 if (!ref_exists(upstream->refname))
1072 die(_("No such branch: '%s'"), branch);
1073 if (!upstream->merge) {
1074 die(_("No upstream configured for branch '%s'"),
1078 _("Upstream branch '%s' not stored as a remote-tracking branch"),
1079 upstream->merge[0]->src);
1083 return upstream->merge[0]->dst;
1086 static int interpret_upstream_mark(const char *name, int namelen,
1087 int at, struct strbuf *buf)
1091 len = upstream_mark(name + at, namelen - at);
1095 if (memchr(name, ':', at))
1098 set_shortened_ref(buf, get_upstream_branch(name, at));
1103 * This reads short-hand syntax that not only evaluates to a commit
1104 * object name, but also can act as if the end user spelled the name
1105 * of the branch from the command line.
1107 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1108 * places the name of the branch in the given buf and returns the
1109 * number of characters parsed if successful.
1111 * - "<branch>@{upstream}" finds the name of the other ref that
1112 * <branch> is configured to merge with (missing <branch> defaults
1113 * to the current branch), and places the name of the branch in the
1114 * given buf and returns the number of characters parsed if
1117 * If the input is not of the accepted format, it returns a negative
1118 * number to signal an error.
1120 * If the input was ok but there are not N branch switches in the
1121 * reflog, it returns 0.
1123 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1127 int len = interpret_nth_prior_checkout(name, namelen, buf);
1130 namelen = strlen(name);
1133 return len; /* syntax Ok, not enough switches */
1134 } else if (len > 0) {
1136 return len; /* consumed all */
1138 return reinterpret(name, namelen, len, buf);
1142 (at = memchr(start, '@', namelen - (start - name)));
1145 len = interpret_empty_at(name, namelen, at - name, buf);
1147 return reinterpret(name, namelen, len, buf);
1149 len = interpret_upstream_mark(name, namelen, at - name, buf);
1157 int strbuf_branchname(struct strbuf *sb, const char *name)
1159 int len = strlen(name);
1160 int used = interpret_branch_name(name, len, sb);
1166 strbuf_add(sb, name + used, len - used);
1170 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1172 strbuf_branchname(sb, name);
1175 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1176 return check_refname_format(sb->buf, 0);
1180 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1181 * notably "xyz^" for "parent of xyz"
1183 int get_sha1(const char *name, unsigned char *sha1)
1185 struct object_context unused;
1186 return get_sha1_with_context(name, 0, sha1, &unused);
1190 * Many callers know that the user meant to name a commit-ish by
1191 * syntactical positions where the object name appears. Calling this
1192 * function allows the machinery to disambiguate shorter-than-unique
1193 * abbreviated object names between commit-ish and others.
1195 * Note that this does NOT error out when the named object is not a
1196 * commit-ish. It is merely to give a hint to the disambiguation
1199 int get_sha1_committish(const char *name, unsigned char *sha1)
1201 struct object_context unused;
1202 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1206 int get_sha1_treeish(const char *name, unsigned char *sha1)
1208 struct object_context unused;
1209 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1213 int get_sha1_commit(const char *name, unsigned char *sha1)
1215 struct object_context unused;
1216 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1220 int get_sha1_tree(const char *name, unsigned char *sha1)
1222 struct object_context unused;
1223 return get_sha1_with_context(name, GET_SHA1_TREE,
1227 int get_sha1_blob(const char *name, unsigned char *sha1)
1229 struct object_context unused;
1230 return get_sha1_with_context(name, GET_SHA1_BLOB,
1234 /* Must be called only when object_name:filename doesn't exist. */
1235 static void diagnose_invalid_sha1_path(const char *prefix,
1236 const char *filename,
1237 const unsigned char *tree_sha1,
1238 const char *object_name,
1239 int object_name_len)
1241 unsigned char sha1[20];
1247 if (file_exists(filename))
1248 die("Path '%s' exists on disk, but not in '%.*s'.",
1249 filename, object_name_len, object_name);
1250 if (errno == ENOENT || errno == ENOTDIR) {
1251 char *fullname = xstrfmt("%s%s", prefix, filename);
1253 if (!get_tree_entry(tree_sha1, fullname,
1255 die("Path '%s' exists, but not '%s'.\n"
1256 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1259 object_name_len, object_name,
1261 object_name_len, object_name,
1264 die("Path '%s' does not exist in '%.*s'",
1265 filename, object_name_len, object_name);
1269 /* Must be called only when :stage:filename doesn't exist. */
1270 static void diagnose_invalid_index_path(int stage,
1272 const char *filename)
1274 const struct cache_entry *ce;
1276 unsigned namelen = strlen(filename);
1277 unsigned fullnamelen;
1283 /* Wrong stage number? */
1284 pos = cache_name_pos(filename, namelen);
1287 if (pos < active_nr) {
1288 ce = active_cache[pos];
1289 if (ce_namelen(ce) == namelen &&
1290 !memcmp(ce->name, filename, namelen))
1291 die("Path '%s' is in the index, but not at stage %d.\n"
1292 "Did you mean ':%d:%s'?",
1294 ce_stage(ce), filename);
1297 /* Confusion between relative and absolute filenames? */
1298 fullnamelen = namelen + strlen(prefix);
1299 fullname = xmalloc(fullnamelen + 1);
1300 strcpy(fullname, prefix);
1301 strcat(fullname, filename);
1302 pos = cache_name_pos(fullname, fullnamelen);
1305 if (pos < active_nr) {
1306 ce = active_cache[pos];
1307 if (ce_namelen(ce) == fullnamelen &&
1308 !memcmp(ce->name, fullname, fullnamelen))
1309 die("Path '%s' is in the index, but not '%s'.\n"
1310 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1312 ce_stage(ce), fullname,
1313 ce_stage(ce), filename);
1316 if (file_exists(filename))
1317 die("Path '%s' exists on disk, but not in the index.", filename);
1318 if (errno == ENOENT || errno == ENOTDIR)
1319 die("Path '%s' does not exist (neither on disk nor in the index).",
1326 static char *resolve_relative_path(const char *rel)
1328 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1332 die("BUG: startup_info struct is not initialized.");
1334 if (!is_inside_work_tree())
1335 die("relative path syntax can't be used outside working tree.");
1337 /* die() inside prefix_path() if resolved path is outside worktree */
1338 return prefix_path(startup_info->prefix,
1339 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1343 static int get_sha1_with_context_1(const char *name,
1346 unsigned char *sha1,
1347 struct object_context *oc)
1349 int ret, bracket_depth;
1350 int namelen = strlen(name);
1352 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1354 memset(oc, 0, sizeof(*oc));
1355 oc->mode = S_IFINVALID;
1356 ret = get_sha1_1(name, namelen, sha1, flags);
1360 * sha1:path --> object name of path in ent sha1
1361 * :path -> object name of absolute path in index
1362 * :./path -> object name of path relative to cwd in index
1363 * :[0-3]:path -> object name of path in index at stage
1364 * :/foo -> recent commit matching foo
1366 if (name[0] == ':') {
1368 const struct cache_entry *ce;
1369 char *new_path = NULL;
1371 if (!only_to_die && namelen > 2 && name[1] == '/') {
1372 struct commit_list *list = NULL;
1373 for_each_ref(handle_one_ref, &list);
1374 commit_list_sort_by_date(&list);
1375 return get_sha1_oneline(name + 2, sha1, list);
1379 name[1] < '0' || '3' < name[1])
1382 stage = name[1] - '0';
1385 new_path = resolve_relative_path(cp);
1387 namelen = namelen - (cp - name);
1390 namelen = strlen(cp);
1393 strlcpy(oc->path, cp, sizeof(oc->path));
1397 pos = cache_name_pos(cp, namelen);
1400 while (pos < active_nr) {
1401 ce = active_cache[pos];
1402 if (ce_namelen(ce) != namelen ||
1403 memcmp(ce->name, cp, namelen))
1405 if (ce_stage(ce) == stage) {
1406 hashcpy(sha1, ce->sha1);
1407 oc->mode = ce->ce_mode;
1413 if (only_to_die && name[1] && name[1] != '/')
1414 diagnose_invalid_index_path(stage, prefix, cp);
1418 for (cp = name, bracket_depth = 0; *cp; cp++) {
1421 else if (bracket_depth && *cp == '}')
1423 else if (!bracket_depth && *cp == ':')
1427 unsigned char tree_sha1[20];
1428 int len = cp - name;
1429 if (!get_sha1_1(name, len, tree_sha1, GET_SHA1_TREEISH)) {
1430 const char *filename = cp+1;
1431 char *new_filename = NULL;
1433 new_filename = resolve_relative_path(filename);
1435 filename = new_filename;
1436 ret = get_tree_entry(tree_sha1, filename, sha1, &oc->mode);
1437 if (ret && only_to_die) {
1438 diagnose_invalid_sha1_path(prefix, filename,
1442 hashcpy(oc->tree, tree_sha1);
1443 strlcpy(oc->path, filename, sizeof(oc->path));
1449 die("Invalid object name '%.*s'.", len, name);
1456 * Call this function when you know "name" given by the end user must
1457 * name an object but it doesn't; the function _may_ die with a better
1458 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1459 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1460 * you have a chance to diagnose the error further.
1462 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1464 struct object_context oc;
1465 unsigned char sha1[20];
1466 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1469 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1471 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);