11 #include "sha1-array.h"
13 static int get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
15 typedef int (*disambiguate_hint_fn)(const struct object_id *, void *);
17 struct disambiguate_state {
18 int len; /* length of prefix in hex chars */
19 char hex_pfx[GIT_MAX_HEXSZ + 1];
20 struct object_id bin_pfx;
22 disambiguate_hint_fn fn;
24 struct object_id candidate;
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 struct object_id *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 oidcpy(&ds->candidate, current);
42 ds->candidate_exists = 1;
44 } else if (!oidcmp(&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 oidcpy(&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_MAX_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 struct object_id oid;
113 if (strlen(de->d_name) != GIT_SHA1_HEXSZ - 2)
115 if (memcmp(de->d_name, ds->hex_pfx + 2, ds->len - 2))
117 memcpy(hex + 2, de->d_name, GIT_SHA1_HEXSZ - 2);
118 if (!get_oid_hex(hex, &oid))
119 update_candidates(ds, &oid);
125 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
135 if ((*a ^ *b) & 0xf0)
140 static void unique_in_pack(struct packed_git *p,
141 struct disambiguate_state *ds)
143 uint32_t num, last, i, first = 0;
144 const struct object_id *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(ds->bin_pfx.hash, 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 struct object_id oid;
174 current = nth_packed_object_oid(&oid, p, i);
175 if (!match_sha(ds->len, ds->bin_pfx.hash, current->hash))
177 update_candidates(ds, current);
181 static void find_short_packed_object(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(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.hash);
227 static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
229 int kind = sha1_object_info(oid->hash, NULL);
230 return kind == OBJ_COMMIT;
233 static int disambiguate_committish_only(const struct object_id *oid, void *cb_data_unused)
238 kind = sha1_object_info(oid->hash, NULL);
239 if (kind == OBJ_COMMIT)
244 /* We need to do this the hard way... */
245 obj = deref_tag(parse_object(oid), NULL, 0);
246 if (obj && obj->type == OBJ_COMMIT)
251 static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
253 int kind = sha1_object_info(oid->hash, NULL);
254 return kind == OBJ_TREE;
257 static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_unused)
262 kind = sha1_object_info(oid->hash, NULL);
263 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
268 /* We need to do this the hard way... */
269 obj = deref_tag(parse_object(oid), NULL, 0);
270 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
275 static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
277 int kind = sha1_object_info(oid->hash, NULL);
278 return kind == OBJ_BLOB;
281 static disambiguate_hint_fn default_disambiguate_hint;
283 int set_disambiguate_hint_config(const char *var, const char *value)
285 static const struct {
287 disambiguate_hint_fn fn;
290 { "commit", disambiguate_commit_only },
291 { "committish", disambiguate_committish_only },
292 { "tree", disambiguate_tree_only },
293 { "treeish", disambiguate_treeish_only },
294 { "blob", disambiguate_blob_only }
299 return config_error_nonbool(var);
301 for (i = 0; i < ARRAY_SIZE(hints); i++) {
302 if (!strcasecmp(value, hints[i].name)) {
303 default_disambiguate_hint = hints[i].fn;
308 return error("unknown hint type for '%s': %s", var, value);
311 static int init_object_disambiguation(const char *name, int len,
312 struct disambiguate_state *ds)
316 if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
319 memset(ds, 0, sizeof(*ds));
321 for (i = 0; i < len ;i++) {
322 unsigned char c = name[i];
324 if (c >= '0' && c <= '9')
326 else if (c >= 'a' && c <= 'f')
328 else if (c >= 'A' && c <='F') {
337 ds->bin_pfx.hash[i >> 1] |= val;
341 ds->hex_pfx[len] = '\0';
346 static int show_ambiguous_object(const struct object_id *oid, void *data)
348 const struct disambiguate_state *ds = data;
349 struct strbuf desc = STRBUF_INIT;
353 if (ds->fn && !ds->fn(oid, ds->cb_data))
356 type = sha1_object_info(oid->hash, NULL);
357 if (type == OBJ_COMMIT) {
358 struct commit *commit = lookup_commit(oid);
360 struct pretty_print_context pp = {0};
361 pp.date_mode.type = DATE_SHORT;
362 format_commit_message(commit, " %ad - %s", &desc, &pp);
364 } else if (type == OBJ_TAG) {
365 struct tag *tag = lookup_tag(oid);
366 if (!parse_tag(tag) && tag->tag)
367 strbuf_addf(&desc, " %s", tag->tag);
371 find_unique_abbrev(oid->hash, DEFAULT_ABBREV),
372 typename(type) ? typename(type) : "unknown type",
375 strbuf_release(&desc);
379 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
383 struct disambiguate_state ds;
384 int quietly = !!(flags & GET_SHA1_QUIETLY);
386 if (init_object_disambiguation(name, len, &ds) < 0)
389 if (HAS_MULTI_BITS(flags & GET_SHA1_DISAMBIGUATORS))
390 die("BUG: multiple get_short_sha1 disambiguator flags");
392 if (flags & GET_SHA1_COMMIT)
393 ds.fn = disambiguate_commit_only;
394 else if (flags & GET_SHA1_COMMITTISH)
395 ds.fn = disambiguate_committish_only;
396 else if (flags & GET_SHA1_TREE)
397 ds.fn = disambiguate_tree_only;
398 else if (flags & GET_SHA1_TREEISH)
399 ds.fn = disambiguate_treeish_only;
400 else if (flags & GET_SHA1_BLOB)
401 ds.fn = disambiguate_blob_only;
403 ds.fn = default_disambiguate_hint;
405 find_short_object_filename(&ds);
406 find_short_packed_object(&ds);
407 status = finish_object_disambiguation(&ds, sha1);
409 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
410 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
413 * We may still have ambiguity if we simply saw a series of
414 * candidates that did not satisfy our hint function. In
415 * that case, we still want to show them, so disable the hint
421 advise(_("The candidates are:"));
422 for_each_abbrev(ds.hex_pfx, show_ambiguous_object, &ds);
428 static int collect_ambiguous(const struct object_id *oid, void *data)
430 oid_array_append(data, oid);
434 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
436 struct oid_array collect = OID_ARRAY_INIT;
437 struct disambiguate_state ds;
440 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
443 ds.always_call_fn = 1;
444 ds.fn = collect_ambiguous;
445 ds.cb_data = &collect;
446 find_short_object_filename(&ds);
447 find_short_packed_object(&ds);
449 ret = oid_array_for_each_unique(&collect, fn, cb_data);
450 oid_array_clear(&collect);
455 * Return the slot of the most-significant bit set in "val". There are various
456 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
457 * probably not a big deal here.
459 static unsigned msb(unsigned long val)
467 int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
472 unsigned long count = approximate_object_count();
474 * Add one because the MSB only tells us the highest bit set,
475 * not including the value of all the _other_ bits (so "15"
476 * is only one off of 2^4, but the MSB is the 3rd bit.
478 len = msb(count) + 1;
480 * We now know we have on the order of 2^len objects, which
481 * expects a collision at 2^(len/2). But we also care about hex
482 * chars, not bits, and there are 4 bits per hex. So all
483 * together we need to divide by 2; but we also want to round
484 * odd numbers up, hence adding one before dividing.
488 * For very small repos, we stick with our regular fallback.
490 if (len < FALLBACK_DEFAULT_ABBREV)
491 len = FALLBACK_DEFAULT_ABBREV;
494 sha1_to_hex_r(hex, sha1);
495 if (len == 40 || !len)
497 exists = has_sha1_file(sha1);
499 unsigned char sha1_ret[20];
500 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
503 : status == SHORT_NAME_NOT_FOUND) {
512 const char *find_unique_abbrev(const unsigned char *sha1, int len)
515 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
516 char *hex = hexbuffer[bufno];
517 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
518 find_unique_abbrev_r(hex, sha1, len);
522 static int ambiguous_path(const char *path, int len)
527 for (cnt = 0; cnt < len; cnt++) {
547 static inline int at_mark(const char *string, int len,
548 const char **suffix, int nr)
552 for (i = 0; i < nr; i++) {
553 int suffix_len = strlen(suffix[i]);
554 if (suffix_len <= len
555 && !strncasecmp(string, suffix[i], suffix_len))
561 static inline int upstream_mark(const char *string, int len)
563 const char *suffix[] = { "@{upstream}", "@{u}" };
564 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
567 static inline int push_mark(const char *string, int len)
569 const char *suffix[] = { "@{push}" };
570 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
573 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
574 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
576 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
579 static const char *warn_msg = "refname '%.*s' is ambiguous.";
580 static const char *object_name_msg = N_(
581 "Git normally never creates a ref that ends with 40 hex characters\n"
582 "because it will be ignored when you just specify 40-hex. These refs\n"
583 "may be created by mistake. For example,\n"
585 " git checkout -b $br $(git rev-parse ...)\n"
587 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
588 "examine these refs and maybe delete them. Turn this message off by\n"
589 "running \"git config advice.objectNameWarning false\"");
590 unsigned char tmp_sha1[20];
591 char *real_ref = NULL;
593 int at, reflog_len, nth_prior = 0;
595 if (len == 40 && !get_sha1_hex(str, sha1)) {
596 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
597 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
598 if (refs_found > 0) {
599 warning(warn_msg, len, str);
600 if (advice_object_name_warning)
601 fprintf(stderr, "%s\n", _(object_name_msg));
608 /* basic@{time or number or -number} format to query ref-log */
610 if (len && str[len-1] == '}') {
611 for (at = len-4; at >= 0; at--) {
612 if (str[at] == '@' && str[at+1] == '{') {
613 if (str[at+2] == '-') {
615 /* @{-N} not at start */
620 if (!upstream_mark(str + at, len - at) &&
621 !push_mark(str + at, len - at)) {
622 reflog_len = (len-1) - (at+2);
630 /* Accept only unambiguous ref paths. */
631 if (len && ambiguous_path(str, len))
635 struct strbuf buf = STRBUF_INIT;
638 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
639 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
640 strbuf_release(&buf);
646 if (!len && reflog_len)
647 /* allow "@{...}" to mean the current branch reflog */
648 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
650 refs_found = dwim_log(str, len, sha1, &real_ref);
652 refs_found = dwim_ref(str, len, sha1, &real_ref);
657 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
659 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
660 warning(warn_msg, len, str);
668 /* Is it asking for N-th entry, or approxidate? */
669 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
670 char ch = str[at+2+i];
671 if ('0' <= ch && ch <= '9')
672 nth = nth * 10 + ch - '0';
676 if (100000000 <= nth) {
683 char *tmp = xstrndup(str + at + 2, reflog_len);
684 at_time = approxidate_careful(tmp, &errors);
691 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
692 &co_time, &co_tz, &co_cnt)) {
694 if (starts_with(real_ref, "refs/heads/")) {
696 len = strlen(real_ref + 11);
704 if (!(flags & GET_SHA1_QUIETLY)) {
705 warning("Log for '%.*s' only goes "
706 "back to %s.", len, str,
707 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
710 if (flags & GET_SHA1_QUIETLY) {
713 die("Log for '%.*s' only has %d entries.",
723 static int get_parent(const char *name, int len,
724 unsigned char *result, int idx)
726 struct object_id oid;
727 int ret = get_sha1_1(name, len, oid.hash, GET_SHA1_COMMITTISH);
728 struct commit *commit;
729 struct commit_list *p;
733 commit = lookup_commit_reference(&oid);
734 if (parse_commit(commit))
737 hashcpy(result, commit->object.oid.hash);
743 hashcpy(result, p->item->object.oid.hash);
751 static int get_nth_ancestor(const char *name, int len,
752 unsigned char *result, int generation)
754 struct object_id oid;
755 struct commit *commit;
758 ret = get_sha1_1(name, len, oid.hash, GET_SHA1_COMMITTISH);
761 commit = lookup_commit_reference(&oid);
765 while (generation--) {
766 if (parse_commit(commit) || !commit->parents)
768 commit = commit->parents->item;
770 hashcpy(result, commit->object.oid.hash);
774 struct object *peel_to_type(const char *name, int namelen,
775 struct object *o, enum object_type expected_type)
777 if (name && !namelen)
778 namelen = strlen(name);
780 if (!o || (!o->parsed && !parse_object(&o->oid)))
782 if (expected_type == OBJ_ANY || o->type == expected_type)
784 if (o->type == OBJ_TAG)
785 o = ((struct tag*) o)->tagged;
786 else if (o->type == OBJ_COMMIT)
787 o = &(((struct commit *) o)->tree->object);
790 error("%.*s: expected %s type, but the object "
791 "dereferences to %s type",
792 namelen, name, typename(expected_type),
799 static int peel_onion(const char *name, int len, unsigned char *sha1,
800 unsigned lookup_flags)
802 struct object_id outer;
804 unsigned int expected_type = 0;
808 * "ref^{type}" dereferences ref repeatedly until you cannot
809 * dereference anymore, or you get an object of given type,
810 * whichever comes first. "ref^{}" means just dereference
811 * tags until you get a non-tag. "ref^0" is a shorthand for
812 * "ref^{commit}". "commit^{tree}" could be used to find the
813 * top-level tree of the given commit.
815 if (len < 4 || name[len-1] != '}')
818 for (sp = name + len - 1; name <= sp; sp--) {
820 if (ch == '{' && name < sp && sp[-1] == '^')
826 sp++; /* beginning of type name, or closing brace for empty */
827 if (starts_with(sp, "commit}"))
828 expected_type = OBJ_COMMIT;
829 else if (starts_with(sp, "tag}"))
830 expected_type = OBJ_TAG;
831 else if (starts_with(sp, "tree}"))
832 expected_type = OBJ_TREE;
833 else if (starts_with(sp, "blob}"))
834 expected_type = OBJ_BLOB;
835 else if (starts_with(sp, "object}"))
836 expected_type = OBJ_ANY;
837 else if (sp[0] == '}')
838 expected_type = OBJ_NONE;
839 else if (sp[0] == '/')
840 expected_type = OBJ_COMMIT;
844 lookup_flags &= ~GET_SHA1_DISAMBIGUATORS;
845 if (expected_type == OBJ_COMMIT)
846 lookup_flags |= GET_SHA1_COMMITTISH;
847 else if (expected_type == OBJ_TREE)
848 lookup_flags |= GET_SHA1_TREEISH;
850 if (get_sha1_1(name, sp - name - 2, outer.hash, lookup_flags))
853 o = parse_object(&outer);
856 if (!expected_type) {
857 o = deref_tag(o, name, sp - name - 2);
858 if (!o || (!o->parsed && !parse_object(&o->oid)))
860 hashcpy(sha1, o->oid.hash);
865 * At this point, the syntax look correct, so
866 * if we do not get the needed object, we should
869 o = peel_to_type(name, len, o, expected_type);
873 hashcpy(sha1, o->oid.hash);
875 /* "$commit^{/foo}" */
878 struct commit_list *list = NULL;
881 * $commit^{/}. Some regex implementation may reject.
882 * We don't need regex anyway. '' pattern always matches.
887 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
888 commit_list_insert((struct commit *)o, &list);
889 ret = get_sha1_oneline(prefix, sha1, list);
896 static int get_describe_name(const char *name, int len, unsigned char *sha1)
899 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
901 for (cp = name + len - 1; name + 2 <= cp; cp--) {
904 /* We must be looking at g in "SOMETHING-g"
905 * for it to be describe output.
907 if (ch == 'g' && cp[-1] == '-') {
910 return get_short_sha1(cp, len, sha1, flags);
917 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
923 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
926 for (cp = name + len - 1; name <= cp; cp--) {
928 if ('0' <= ch && ch <= '9')
930 if (ch == '~' || ch == '^')
937 int len1 = cp - name;
939 while (cp < name + len)
940 num = num * 10 + *cp++ - '0';
941 if (!num && len1 == len - 1)
943 if (has_suffix == '^')
944 return get_parent(name, len1, sha1, num);
945 /* else if (has_suffix == '~') -- goes without saying */
946 return get_nth_ancestor(name, len1, sha1, num);
949 ret = peel_onion(name, len, sha1, lookup_flags);
953 ret = get_sha1_basic(name, len, sha1, lookup_flags);
957 /* It could be describe output that is "SOMETHING-gXXXX" */
958 ret = get_describe_name(name, len, sha1);
962 return get_short_sha1(name, len, sha1, lookup_flags);
966 * This interprets names like ':/Initial revision of "git"' by searching
967 * through history and returning the first commit whose message starts
968 * the given regular expression.
970 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
972 * For a literal '!' character at the beginning of a pattern, you have to repeat
973 * that, like: ':/!!foo'
975 * For future extension, all other sequences beginning with ':/!' are reserved.
978 /* Remember to update object flag allocation in object.h */
979 #define ONELINE_SEEN (1u<<20)
981 static int handle_one_ref(const char *path, const struct object_id *oid,
982 int flag, void *cb_data)
984 struct commit_list **list = cb_data;
985 struct object *object = parse_object(oid);
988 if (object->type == OBJ_TAG) {
989 object = deref_tag(object, path, strlen(path));
993 if (object->type != OBJ_COMMIT)
995 commit_list_insert((struct commit *)object, list);
999 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
1000 struct commit_list *list)
1002 struct commit_list *backup = NULL, *l;
1007 if (prefix[0] == '!') {
1010 if (prefix[0] == '-') {
1013 } else if (prefix[0] != '!') {
1018 if (regcomp(®ex, prefix, REG_EXTENDED))
1021 for (l = list; l; l = l->next) {
1022 l->item->object.flags |= ONELINE_SEEN;
1023 commit_list_insert(l->item, &backup);
1026 const char *p, *buf;
1027 struct commit *commit;
1030 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1031 if (!parse_object(&commit->object.oid))
1033 buf = get_commit_buffer(commit, NULL);
1034 p = strstr(buf, "\n\n");
1035 matches = negative ^ (p && !regexec(®ex, p + 2, 0, NULL, 0));
1036 unuse_commit_buffer(commit, buf);
1039 hashcpy(sha1, commit->object.oid.hash);
1045 free_commit_list(list);
1046 for (l = backup; l; l = l->next)
1047 clear_commit_marks(l->item, ONELINE_SEEN);
1048 free_commit_list(backup);
1049 return found ? 0 : -1;
1052 struct grab_nth_branch_switch_cbdata {
1057 static int grab_nth_branch_switch(struct object_id *ooid, struct object_id *noid,
1058 const char *email, timestamp_t timestamp, int tz,
1059 const char *message, void *cb_data)
1061 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1062 const char *match = NULL, *target = NULL;
1065 if (skip_prefix(message, "checkout: moving from ", &match))
1066 target = strstr(match, " to ");
1068 if (!match || !target)
1070 if (--(cb->remaining) == 0) {
1071 len = target - match;
1072 strbuf_reset(&cb->buf);
1073 strbuf_add(&cb->buf, match, len);
1074 return 1; /* we are done */
1080 * Parse @{-N} syntax, return the number of characters parsed
1081 * if successful; otherwise signal an error with negative value.
1083 static int interpret_nth_prior_checkout(const char *name, int namelen,
1088 struct grab_nth_branch_switch_cbdata cb;
1094 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1096 brace = memchr(name, '}', namelen);
1099 nth = strtol(name + 3, &num_end, 10);
1100 if (num_end != brace)
1105 strbuf_init(&cb.buf, 20);
1108 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1110 strbuf_addbuf(buf, &cb.buf);
1111 retval = brace - name + 1;
1114 strbuf_release(&cb.buf);
1118 int get_oid_mb(const char *name, struct object_id *oid)
1120 struct commit *one, *two;
1121 struct commit_list *mbs;
1122 struct object_id oid_tmp;
1126 dots = strstr(name, "...");
1128 return get_oid(name, oid);
1130 st = get_oid("HEAD", &oid_tmp);
1133 strbuf_init(&sb, dots - name);
1134 strbuf_add(&sb, name, dots - name);
1135 st = get_sha1_committish(sb.buf, oid_tmp.hash);
1136 strbuf_release(&sb);
1140 one = lookup_commit_reference_gently(&oid_tmp, 0);
1144 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", oid_tmp.hash))
1146 two = lookup_commit_reference_gently(&oid_tmp, 0);
1149 mbs = get_merge_bases(one, two);
1150 if (!mbs || mbs->next)
1154 oidcpy(oid, &mbs->item->object.oid);
1156 free_commit_list(mbs);
1160 /* parse @something syntax, when 'something' is not {.*} */
1161 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1165 if (len || name[1] == '{')
1168 /* make sure it's a single @, or @@{.*}, not @foo */
1169 next = memchr(name + len + 1, '@', namelen - len - 1);
1170 if (next && next[1] != '{')
1173 next = name + namelen;
1174 if (next != name + 1)
1178 strbuf_add(buf, "HEAD", 4);
1182 static int reinterpret(const char *name, int namelen, int len,
1183 struct strbuf *buf, unsigned allowed)
1185 /* we have extra data, which might need further processing */
1186 struct strbuf tmp = STRBUF_INIT;
1187 int used = buf->len;
1190 strbuf_add(buf, name + len, namelen - len);
1191 ret = interpret_branch_name(buf->buf, buf->len, &tmp, allowed);
1192 /* that data was not interpreted, remove our cruft */
1194 strbuf_setlen(buf, used);
1198 strbuf_addbuf(buf, &tmp);
1199 strbuf_release(&tmp);
1200 /* tweak for size of {-N} versus expanded ref name */
1201 return ret - used + len;
1204 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1206 char *s = shorten_unambiguous_ref(ref, 0);
1208 strbuf_addstr(buf, s);
1212 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1217 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1218 starts_with(refname, "refs/heads/"))
1220 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1221 starts_with(refname, "refs/remotes/"))
1227 static int interpret_branch_mark(const char *name, int namelen,
1228 int at, struct strbuf *buf,
1229 int (*get_mark)(const char *, int),
1230 const char *(*get_data)(struct branch *,
1235 struct branch *branch;
1236 struct strbuf err = STRBUF_INIT;
1239 len = get_mark(name + at, namelen - at);
1243 if (memchr(name, ':', at))
1247 char *name_str = xmemdupz(name, at);
1248 branch = branch_get(name_str);
1251 branch = branch_get(NULL);
1253 value = get_data(branch, &err);
1257 if (!branch_interpret_allowed(value, allowed))
1260 set_shortened_ref(buf, value);
1264 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf,
1272 namelen = strlen(name);
1274 if (!allowed || (allowed & INTERPRET_BRANCH_LOCAL)) {
1275 len = interpret_nth_prior_checkout(name, namelen, buf);
1277 return len; /* syntax Ok, not enough switches */
1278 } else if (len > 0) {
1280 return len; /* consumed all */
1282 return reinterpret(name, namelen, len, buf, allowed);
1287 (at = memchr(start, '@', namelen - (start - name)));
1290 if (!allowed || (allowed & INTERPRET_BRANCH_HEAD)) {
1291 len = interpret_empty_at(name, namelen, at - name, buf);
1293 return reinterpret(name, namelen, len, buf,
1297 len = interpret_branch_mark(name, namelen, at - name, buf,
1298 upstream_mark, branch_get_upstream,
1303 len = interpret_branch_mark(name, namelen, at - name, buf,
1304 push_mark, branch_get_push,
1313 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1315 int len = strlen(name);
1316 int used = interpret_branch_name(name, len, sb, allowed);
1320 strbuf_add(sb, name + used, len - used);
1323 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1325 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1328 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1329 return check_refname_format(sb->buf, 0);
1333 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1334 * notably "xyz^" for "parent of xyz"
1336 int get_sha1(const char *name, unsigned char *sha1)
1338 struct object_context unused;
1339 return get_sha1_with_context(name, 0, sha1, &unused);
1343 * This is like "get_sha1()", but for struct object_id.
1345 int get_oid(const char *name, struct object_id *oid)
1347 return get_sha1(name, oid->hash);
1352 * Many callers know that the user meant to name a commit-ish by
1353 * syntactical positions where the object name appears. Calling this
1354 * function allows the machinery to disambiguate shorter-than-unique
1355 * abbreviated object names between commit-ish and others.
1357 * Note that this does NOT error out when the named object is not a
1358 * commit-ish. It is merely to give a hint to the disambiguation
1361 int get_sha1_committish(const char *name, unsigned char *sha1)
1363 struct object_context unused;
1364 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1368 int get_sha1_treeish(const char *name, unsigned char *sha1)
1370 struct object_context unused;
1371 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1375 int get_sha1_commit(const char *name, unsigned char *sha1)
1377 struct object_context unused;
1378 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1382 int get_sha1_tree(const char *name, unsigned char *sha1)
1384 struct object_context unused;
1385 return get_sha1_with_context(name, GET_SHA1_TREE,
1389 int get_sha1_blob(const char *name, unsigned char *sha1)
1391 struct object_context unused;
1392 return get_sha1_with_context(name, GET_SHA1_BLOB,
1396 /* Must be called only when object_name:filename doesn't exist. */
1397 static void diagnose_invalid_sha1_path(const char *prefix,
1398 const char *filename,
1399 const unsigned char *tree_sha1,
1400 const char *object_name,
1401 int object_name_len)
1403 unsigned char sha1[20];
1409 if (file_exists(filename))
1410 die("Path '%s' exists on disk, but not in '%.*s'.",
1411 filename, object_name_len, object_name);
1412 if (is_missing_file_error(errno)) {
1413 char *fullname = xstrfmt("%s%s", prefix, filename);
1415 if (!get_tree_entry(tree_sha1, fullname,
1417 die("Path '%s' exists, but not '%s'.\n"
1418 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1421 object_name_len, object_name,
1423 object_name_len, object_name,
1426 die("Path '%s' does not exist in '%.*s'",
1427 filename, object_name_len, object_name);
1431 /* Must be called only when :stage:filename doesn't exist. */
1432 static void diagnose_invalid_index_path(int stage,
1434 const char *filename)
1436 const struct cache_entry *ce;
1438 unsigned namelen = strlen(filename);
1439 struct strbuf fullname = STRBUF_INIT;
1444 /* Wrong stage number? */
1445 pos = cache_name_pos(filename, namelen);
1448 if (pos < active_nr) {
1449 ce = active_cache[pos];
1450 if (ce_namelen(ce) == namelen &&
1451 !memcmp(ce->name, filename, namelen))
1452 die("Path '%s' is in the index, but not at stage %d.\n"
1453 "Did you mean ':%d:%s'?",
1455 ce_stage(ce), filename);
1458 /* Confusion between relative and absolute filenames? */
1459 strbuf_addstr(&fullname, prefix);
1460 strbuf_addstr(&fullname, filename);
1461 pos = cache_name_pos(fullname.buf, fullname.len);
1464 if (pos < active_nr) {
1465 ce = active_cache[pos];
1466 if (ce_namelen(ce) == fullname.len &&
1467 !memcmp(ce->name, fullname.buf, fullname.len))
1468 die("Path '%s' is in the index, but not '%s'.\n"
1469 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1470 fullname.buf, filename,
1471 ce_stage(ce), fullname.buf,
1472 ce_stage(ce), filename);
1475 if (file_exists(filename))
1476 die("Path '%s' exists on disk, but not in the index.", filename);
1477 if (is_missing_file_error(errno))
1478 die("Path '%s' does not exist (neither on disk nor in the index).",
1481 strbuf_release(&fullname);
1485 static char *resolve_relative_path(const char *rel)
1487 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1490 if (!is_inside_work_tree())
1491 die("relative path syntax can't be used outside working tree.");
1493 /* die() inside prefix_path() if resolved path is outside worktree */
1494 return prefix_path(startup_info->prefix,
1495 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1499 static int get_sha1_with_context_1(const char *name,
1502 unsigned char *sha1,
1503 struct object_context *oc)
1505 int ret, bracket_depth;
1506 int namelen = strlen(name);
1508 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1511 flags |= GET_SHA1_QUIETLY;
1513 memset(oc, 0, sizeof(*oc));
1514 oc->mode = S_IFINVALID;
1515 strbuf_init(&oc->symlink_path, 0);
1516 ret = get_sha1_1(name, namelen, sha1, flags);
1520 * sha1:path --> object name of path in ent sha1
1521 * :path -> object name of absolute path in index
1522 * :./path -> object name of path relative to cwd in index
1523 * :[0-3]:path -> object name of path in index at stage
1524 * :/foo -> recent commit matching foo
1526 if (name[0] == ':') {
1528 const struct cache_entry *ce;
1529 char *new_path = NULL;
1531 if (!only_to_die && namelen > 2 && name[1] == '/') {
1532 struct commit_list *list = NULL;
1534 for_each_ref(handle_one_ref, &list);
1535 commit_list_sort_by_date(&list);
1536 return get_sha1_oneline(name + 2, sha1, list);
1540 name[1] < '0' || '3' < name[1])
1543 stage = name[1] - '0';
1546 new_path = resolve_relative_path(cp);
1548 namelen = namelen - (cp - name);
1551 namelen = strlen(cp);
1554 if (flags & GET_SHA1_RECORD_PATH)
1555 oc->path = xstrdup(cp);
1559 pos = cache_name_pos(cp, namelen);
1562 while (pos < active_nr) {
1563 ce = active_cache[pos];
1564 if (ce_namelen(ce) != namelen ||
1565 memcmp(ce->name, cp, namelen))
1567 if (ce_stage(ce) == stage) {
1568 hashcpy(sha1, ce->oid.hash);
1569 oc->mode = ce->ce_mode;
1575 if (only_to_die && name[1] && name[1] != '/')
1576 diagnose_invalid_index_path(stage, prefix, cp);
1580 for (cp = name, bracket_depth = 0; *cp; cp++) {
1583 else if (bracket_depth && *cp == '}')
1585 else if (!bracket_depth && *cp == ':')
1589 unsigned char tree_sha1[20];
1590 int len = cp - name;
1591 unsigned sub_flags = flags;
1593 sub_flags &= ~GET_SHA1_DISAMBIGUATORS;
1594 sub_flags |= GET_SHA1_TREEISH;
1596 if (!get_sha1_1(name, len, tree_sha1, sub_flags)) {
1597 const char *filename = cp+1;
1598 char *new_filename = NULL;
1600 new_filename = resolve_relative_path(filename);
1602 filename = new_filename;
1603 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1604 ret = get_tree_entry_follow_symlinks(tree_sha1,
1605 filename, sha1, &oc->symlink_path,
1608 ret = get_tree_entry(tree_sha1, filename,
1610 if (ret && only_to_die) {
1611 diagnose_invalid_sha1_path(prefix,
1617 hashcpy(oc->tree, tree_sha1);
1618 if (flags & GET_SHA1_RECORD_PATH)
1619 oc->path = xstrdup(filename);
1625 die("Invalid object name '%.*s'.", len, name);
1632 * Call this function when you know "name" given by the end user must
1633 * name an object but it doesn't; the function _may_ die with a better
1634 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1635 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1636 * you have a chance to diagnose the error further.
1638 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1640 struct object_context oc;
1641 unsigned char sha1[20];
1642 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1645 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *oc)
1647 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1648 die("BUG: incompatible flags for get_sha1_with_context");
1649 return get_sha1_with_context_1(str, flags, NULL, sha1, oc);