10 #include "sha1-array.h"
12 static int get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
14 typedef int (*disambiguate_hint_fn)(const unsigned char *, void *);
16 struct disambiguate_state {
17 int len; /* length of prefix in hex chars */
18 unsigned int nrobjects;
19 char hex_pfx[GIT_SHA1_HEXSZ + 1];
20 unsigned char bin_pfx[GIT_SHA1_RAWSZ];
22 disambiguate_hint_fn fn;
24 unsigned char candidate[GIT_SHA1_RAWSZ];
25 unsigned candidate_exists:1;
26 unsigned candidate_checked:1;
27 unsigned candidate_ok:1;
28 unsigned disambiguate_fn_used:1;
30 unsigned always_call_fn:1;
33 static void update_candidates(struct disambiguate_state *ds, const unsigned char *current)
35 if (ds->always_call_fn) {
36 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
39 if (!ds->candidate_exists) {
40 /* this is the first candidate */
41 hashcpy(ds->candidate, current);
42 ds->candidate_exists = 1;
44 } else if (!hashcmp(ds->candidate, current)) {
45 /* the same as what we already have seen */
50 /* cannot disambiguate between ds->candidate and current */
55 if (!ds->candidate_checked) {
56 ds->candidate_ok = ds->fn(ds->candidate, ds->cb_data);
57 ds->disambiguate_fn_used = 1;
58 ds->candidate_checked = 1;
61 if (!ds->candidate_ok) {
62 /* discard the candidate; we know it does not satisfy fn */
63 hashcpy(ds->candidate, current);
64 ds->candidate_checked = 0;
68 /* if we reach this point, we know ds->candidate satisfies fn */
69 if (ds->fn(current, ds->cb_data)) {
71 * if both current and candidate satisfy fn, we cannot
78 /* otherwise, current can be discarded and candidate is still good */
81 static void find_short_object_filename(struct disambiguate_state *ds)
83 struct alternate_object_database *alt;
84 char hex[GIT_SHA1_HEXSZ];
85 static struct alternate_object_database *fakeent;
89 * Create a "fake" alternate object database that
90 * points to our own object database, to make it
91 * easier to get a temporary working space in
92 * alt->name/alt->base while iterating over the
93 * object databases including our own.
95 const char *objdir = get_object_directory();
96 size_t objdir_len = strlen(objdir);
97 fakeent = xmalloc(st_add3(sizeof(*fakeent), objdir_len, 43));
98 memcpy(fakeent->base, objdir, objdir_len);
99 fakeent->name = fakeent->base + objdir_len + 1;
100 fakeent->name[-1] = '/';
102 fakeent->next = alt_odb_list;
104 xsnprintf(hex, sizeof(hex), "%.2s", ds->hex_pfx);
105 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
109 * every alt_odb struct has 42 extra bytes after the base
110 * for exactly this purpose
112 xsnprintf(alt->name, 42, "%.2s/", ds->hex_pfx);
113 dir = opendir(alt->base);
117 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
118 unsigned char sha1[20];
120 if (strlen(de->d_name) != 38)
124 * We only look at the one subdirectory, and we assume
125 * each subdirectory is roughly similar, so each
126 * object we find probably has 255 other objects in
127 * the other fan-out directories.
129 ds->nrobjects += 256;
130 if (memcmp(de->d_name, ds->hex_pfx + 2, ds->len - 2))
132 memcpy(hex + 2, de->d_name, 38);
133 if (!get_sha1_hex(hex, sha1))
134 update_candidates(ds, sha1);
140 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
150 if ((*a ^ *b) & 0xf0)
155 static void unique_in_pack(struct packed_git *p,
156 struct disambiguate_state *ds)
158 uint32_t num, last, i, first = 0;
159 const unsigned char *current = NULL;
162 num = p->num_objects;
163 ds->nrobjects += num;
165 while (first < last) {
166 uint32_t mid = (first + last) / 2;
167 const unsigned char *current;
170 current = nth_packed_object_sha1(p, mid);
171 cmp = hashcmp(ds->bin_pfx, current);
184 * At this point, "first" is the location of the lowest object
185 * with an object name that could match "bin_pfx". See if we have
186 * 0, 1 or more objects that actually match(es).
188 for (i = first; i < num && !ds->ambiguous; i++) {
189 current = nth_packed_object_sha1(p, i);
190 if (!match_sha(ds->len, ds->bin_pfx, current))
192 update_candidates(ds, current);
196 static void find_short_packed_object(struct disambiguate_state *ds)
198 struct packed_git *p;
200 prepare_packed_git();
201 for (p = packed_git; p && !ds->ambiguous; p = p->next)
202 unique_in_pack(p, ds);
205 #define SHORT_NAME_NOT_FOUND (-1)
206 #define SHORT_NAME_AMBIGUOUS (-2)
208 static int finish_object_disambiguation(struct disambiguate_state *ds,
212 return SHORT_NAME_AMBIGUOUS;
214 if (!ds->candidate_exists)
215 return SHORT_NAME_NOT_FOUND;
217 if (!ds->candidate_checked)
219 * If this is the only candidate, there is no point
220 * calling the disambiguation hint callback.
222 * On the other hand, if the current candidate
223 * replaced an earlier candidate that did _not_ pass
224 * the disambiguation hint callback, then we do have
225 * more than one objects that match the short name
226 * given, so we should make sure this one matches;
227 * otherwise, if we discovered this one and the one
228 * that we previously discarded in the reverse order,
229 * we would end up showing different results in the
232 ds->candidate_ok = (!ds->disambiguate_fn_used ||
233 ds->fn(ds->candidate, ds->cb_data));
235 if (!ds->candidate_ok)
236 return SHORT_NAME_AMBIGUOUS;
238 hashcpy(sha1, ds->candidate);
242 static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
244 int kind = sha1_object_info(sha1, NULL);
245 return kind == OBJ_COMMIT;
248 static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
253 kind = sha1_object_info(sha1, NULL);
254 if (kind == OBJ_COMMIT)
259 /* We need to do this the hard way... */
260 obj = deref_tag(parse_object(sha1), NULL, 0);
261 if (obj && obj->type == OBJ_COMMIT)
266 static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
268 int kind = sha1_object_info(sha1, NULL);
269 return kind == OBJ_TREE;
272 static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
277 kind = sha1_object_info(sha1, NULL);
278 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
283 /* We need to do this the hard way... */
284 obj = deref_tag(parse_object(sha1), NULL, 0);
285 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
290 static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
292 int kind = sha1_object_info(sha1, NULL);
293 return kind == OBJ_BLOB;
296 static disambiguate_hint_fn default_disambiguate_hint;
298 int set_disambiguate_hint_config(const char *var, const char *value)
300 static const struct {
302 disambiguate_hint_fn fn;
305 { "commit", disambiguate_commit_only },
306 { "committish", disambiguate_committish_only },
307 { "tree", disambiguate_tree_only },
308 { "treeish", disambiguate_treeish_only },
309 { "blob", disambiguate_blob_only }
314 return config_error_nonbool(var);
316 for (i = 0; i < ARRAY_SIZE(hints); i++) {
317 if (!strcasecmp(value, hints[i].name)) {
318 default_disambiguate_hint = hints[i].fn;
323 return error("unknown hint type for '%s': %s", var, value);
326 static int init_object_disambiguation(const char *name, int len,
327 struct disambiguate_state *ds)
331 if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
334 memset(ds, 0, sizeof(*ds));
336 for (i = 0; i < len ;i++) {
337 unsigned char c = name[i];
339 if (c >= '0' && c <= '9')
341 else if (c >= 'a' && c <= 'f')
343 else if (c >= 'A' && c <='F') {
352 ds->bin_pfx[i >> 1] |= val;
356 ds->hex_pfx[len] = '\0';
361 static int show_ambiguous_object(const unsigned char *sha1, void *data)
363 const struct disambiguate_state *ds = data;
364 struct strbuf desc = STRBUF_INIT;
367 if (ds->fn && !ds->fn(sha1, ds->cb_data))
370 type = sha1_object_info(sha1, NULL);
371 if (type == OBJ_COMMIT) {
372 struct commit *commit = lookup_commit(sha1);
374 struct pretty_print_context pp = {0};
375 pp.date_mode.type = DATE_SHORT;
376 format_commit_message(commit, " %ad - %s", &desc, &pp);
378 } else if (type == OBJ_TAG) {
379 struct tag *tag = lookup_tag(sha1);
380 if (!parse_tag(tag) && tag->tag)
381 strbuf_addf(&desc, " %s", tag->tag);
385 find_unique_abbrev(sha1, DEFAULT_ABBREV),
386 typename(type) ? typename(type) : "unknown type",
389 strbuf_release(&desc);
393 /* start from our historical default before the automatic abbreviation */
394 static int default_automatic_abbrev = FALLBACK_DEFAULT_ABBREV;
396 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
400 struct disambiguate_state ds;
401 int quietly = !!(flags & GET_SHA1_QUIETLY);
403 if (init_object_disambiguation(name, len, &ds) < 0)
406 if (HAS_MULTI_BITS(flags & GET_SHA1_DISAMBIGUATORS))
407 die("BUG: multiple get_short_sha1 disambiguator flags");
409 if (flags & GET_SHA1_COMMIT)
410 ds.fn = disambiguate_commit_only;
411 else if (flags & GET_SHA1_COMMITTISH)
412 ds.fn = disambiguate_committish_only;
413 else if (flags & GET_SHA1_TREE)
414 ds.fn = disambiguate_tree_only;
415 else if (flags & GET_SHA1_TREEISH)
416 ds.fn = disambiguate_treeish_only;
417 else if (flags & GET_SHA1_BLOB)
418 ds.fn = disambiguate_blob_only;
420 ds.fn = default_disambiguate_hint;
422 find_short_object_filename(&ds);
423 find_short_packed_object(&ds);
424 status = finish_object_disambiguation(&ds, sha1);
426 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
427 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
430 * We may still have ambiguity if we simply saw a series of
431 * candidates that did not satisfy our hint function. In
432 * that case, we still want to show them, so disable the hint
438 advise(_("The candidates are:"));
439 for_each_abbrev(ds.hex_pfx, show_ambiguous_object, &ds);
442 if (len < 16 && !status && (flags & GET_SHA1_AUTOMATIC)) {
443 unsigned int expect_collision = 1 << (len * 2);
444 if (ds.nrobjects > expect_collision) {
445 default_automatic_abbrev = len+1;
446 return SHORT_NAME_AMBIGUOUS;
453 static int collect_ambiguous(const unsigned char *sha1, void *data)
455 sha1_array_append(data, sha1);
459 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
461 struct sha1_array collect = SHA1_ARRAY_INIT;
462 struct disambiguate_state ds;
465 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
468 ds.always_call_fn = 1;
469 ds.fn = collect_ambiguous;
470 ds.cb_data = &collect;
471 find_short_object_filename(&ds);
472 find_short_packed_object(&ds);
474 ret = sha1_array_for_each_unique(&collect, fn, cb_data);
475 sha1_array_clear(&collect);
479 int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
482 int flags = GET_SHA1_QUIETLY;
485 flags |= GET_SHA1_AUTOMATIC;
486 len = default_automatic_abbrev;
488 sha1_to_hex_r(hex, sha1);
489 if (len == 40 || !len)
491 exists = has_sha1_file(sha1);
493 unsigned char sha1_ret[20];
494 status = get_short_sha1(hex, len, sha1_ret, flags);
497 : status == SHORT_NAME_NOT_FOUND) {
506 const char *find_unique_abbrev(const unsigned char *sha1, int len)
508 static char hex[GIT_SHA1_HEXSZ + 1];
509 find_unique_abbrev_r(hex, sha1, len);
513 static int ambiguous_path(const char *path, int len)
518 for (cnt = 0; cnt < len; cnt++) {
538 static inline int at_mark(const char *string, int len,
539 const char **suffix, int nr)
543 for (i = 0; i < nr; i++) {
544 int suffix_len = strlen(suffix[i]);
545 if (suffix_len <= len
546 && !memcmp(string, suffix[i], suffix_len))
552 static inline int upstream_mark(const char *string, int len)
554 const char *suffix[] = { "@{upstream}", "@{u}" };
555 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
558 static inline int push_mark(const char *string, int len)
560 const char *suffix[] = { "@{push}" };
561 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
564 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
565 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
567 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
570 static const char *warn_msg = "refname '%.*s' is ambiguous.";
571 static const char *object_name_msg = N_(
572 "Git normally never creates a ref that ends with 40 hex characters\n"
573 "because it will be ignored when you just specify 40-hex. These refs\n"
574 "may be created by mistake. For example,\n"
576 " git checkout -b $br $(git rev-parse ...)\n"
578 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
579 "examine these refs and maybe delete them. Turn this message off by\n"
580 "running \"git config advice.objectNameWarning false\"");
581 unsigned char tmp_sha1[20];
582 char *real_ref = NULL;
584 int at, reflog_len, nth_prior = 0;
586 if (len == 40 && !get_sha1_hex(str, sha1)) {
587 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
588 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
589 if (refs_found > 0) {
590 warning(warn_msg, len, str);
591 if (advice_object_name_warning)
592 fprintf(stderr, "%s\n", _(object_name_msg));
599 /* basic@{time or number or -number} format to query ref-log */
601 if (len && str[len-1] == '}') {
602 for (at = len-4; at >= 0; at--) {
603 if (str[at] == '@' && str[at+1] == '{') {
604 if (str[at+2] == '-') {
606 /* @{-N} not at start */
611 if (!upstream_mark(str + at, len - at) &&
612 !push_mark(str + at, len - at)) {
613 reflog_len = (len-1) - (at+2);
621 /* Accept only unambiguous ref paths. */
622 if (len && ambiguous_path(str, len))
626 struct strbuf buf = STRBUF_INIT;
629 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
630 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
631 strbuf_release(&buf);
637 if (!len && reflog_len)
638 /* allow "@{...}" to mean the current branch reflog */
639 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
641 refs_found = dwim_log(str, len, sha1, &real_ref);
643 refs_found = dwim_ref(str, len, sha1, &real_ref);
648 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
650 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
651 warning(warn_msg, len, str);
655 unsigned long at_time;
656 unsigned long co_time;
659 /* Is it asking for N-th entry, or approxidate? */
660 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
661 char ch = str[at+2+i];
662 if ('0' <= ch && ch <= '9')
663 nth = nth * 10 + ch - '0';
667 if (100000000 <= nth) {
674 char *tmp = xstrndup(str + at + 2, reflog_len);
675 at_time = approxidate_careful(tmp, &errors);
682 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
683 &co_time, &co_tz, &co_cnt)) {
685 if (starts_with(real_ref, "refs/heads/")) {
687 len = strlen(real_ref + 11);
695 if (!(flags & GET_SHA1_QUIETLY)) {
696 warning("Log for '%.*s' only goes "
697 "back to %s.", len, str,
698 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
701 if (flags & GET_SHA1_QUIETLY) {
704 die("Log for '%.*s' only has %d entries.",
714 static int get_parent(const char *name, int len,
715 unsigned char *result, int idx)
717 unsigned char sha1[20];
718 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
719 struct commit *commit;
720 struct commit_list *p;
724 commit = lookup_commit_reference(sha1);
725 if (parse_commit(commit))
728 hashcpy(result, commit->object.oid.hash);
734 hashcpy(result, p->item->object.oid.hash);
742 static int get_nth_ancestor(const char *name, int len,
743 unsigned char *result, int generation)
745 unsigned char sha1[20];
746 struct commit *commit;
749 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
752 commit = lookup_commit_reference(sha1);
756 while (generation--) {
757 if (parse_commit(commit) || !commit->parents)
759 commit = commit->parents->item;
761 hashcpy(result, commit->object.oid.hash);
765 struct object *peel_to_type(const char *name, int namelen,
766 struct object *o, enum object_type expected_type)
768 if (name && !namelen)
769 namelen = strlen(name);
771 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
773 if (expected_type == OBJ_ANY || o->type == expected_type)
775 if (o->type == OBJ_TAG)
776 o = ((struct tag*) o)->tagged;
777 else if (o->type == OBJ_COMMIT)
778 o = &(((struct commit *) o)->tree->object);
781 error("%.*s: expected %s type, but the object "
782 "dereferences to %s type",
783 namelen, name, typename(expected_type),
790 static int peel_onion(const char *name, int len, unsigned char *sha1,
791 unsigned lookup_flags)
793 unsigned char outer[20];
795 unsigned int expected_type = 0;
799 * "ref^{type}" dereferences ref repeatedly until you cannot
800 * dereference anymore, or you get an object of given type,
801 * whichever comes first. "ref^{}" means just dereference
802 * tags until you get a non-tag. "ref^0" is a shorthand for
803 * "ref^{commit}". "commit^{tree}" could be used to find the
804 * top-level tree of the given commit.
806 if (len < 4 || name[len-1] != '}')
809 for (sp = name + len - 1; name <= sp; sp--) {
811 if (ch == '{' && name < sp && sp[-1] == '^')
817 sp++; /* beginning of type name, or closing brace for empty */
818 if (starts_with(sp, "commit}"))
819 expected_type = OBJ_COMMIT;
820 else if (starts_with(sp, "tag}"))
821 expected_type = OBJ_TAG;
822 else if (starts_with(sp, "tree}"))
823 expected_type = OBJ_TREE;
824 else if (starts_with(sp, "blob}"))
825 expected_type = OBJ_BLOB;
826 else if (starts_with(sp, "object}"))
827 expected_type = OBJ_ANY;
828 else if (sp[0] == '}')
829 expected_type = OBJ_NONE;
830 else if (sp[0] == '/')
831 expected_type = OBJ_COMMIT;
835 lookup_flags &= ~GET_SHA1_DISAMBIGUATORS;
836 if (expected_type == OBJ_COMMIT)
837 lookup_flags |= GET_SHA1_COMMITTISH;
838 else if (expected_type == OBJ_TREE)
839 lookup_flags |= GET_SHA1_TREEISH;
841 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
844 o = parse_object(outer);
847 if (!expected_type) {
848 o = deref_tag(o, name, sp - name - 2);
849 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
851 hashcpy(sha1, o->oid.hash);
856 * At this point, the syntax look correct, so
857 * if we do not get the needed object, we should
860 o = peel_to_type(name, len, o, expected_type);
864 hashcpy(sha1, o->oid.hash);
866 /* "$commit^{/foo}" */
869 struct commit_list *list = NULL;
872 * $commit^{/}. Some regex implementation may reject.
873 * We don't need regex anyway. '' pattern always matches.
878 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
879 commit_list_insert((struct commit *)o, &list);
880 ret = get_sha1_oneline(prefix, sha1, list);
887 static int get_describe_name(const char *name, int len, unsigned char *sha1)
890 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
892 for (cp = name + len - 1; name + 2 <= cp; cp--) {
895 /* We must be looking at g in "SOMETHING-g"
896 * for it to be describe output.
898 if (ch == 'g' && cp[-1] == '-') {
901 return get_short_sha1(cp, len, sha1, flags);
908 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
914 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
917 for (cp = name + len - 1; name <= cp; cp--) {
919 if ('0' <= ch && ch <= '9')
921 if (ch == '~' || ch == '^')
928 int len1 = cp - name;
930 while (cp < name + len)
931 num = num * 10 + *cp++ - '0';
932 if (!num && len1 == len - 1)
934 if (has_suffix == '^')
935 return get_parent(name, len1, sha1, num);
936 /* else if (has_suffix == '~') -- goes without saying */
937 return get_nth_ancestor(name, len1, sha1, num);
940 ret = peel_onion(name, len, sha1, lookup_flags);
944 ret = get_sha1_basic(name, len, sha1, lookup_flags);
948 /* It could be describe output that is "SOMETHING-gXXXX" */
949 ret = get_describe_name(name, len, sha1);
953 return get_short_sha1(name, len, sha1, lookup_flags);
957 * This interprets names like ':/Initial revision of "git"' by searching
958 * through history and returning the first commit whose message starts
959 * the given regular expression.
961 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
963 * For a literal '!' character at the beginning of a pattern, you have to repeat
964 * that, like: ':/!!foo'
966 * For future extension, all other sequences beginning with ':/!' are reserved.
969 /* Remember to update object flag allocation in object.h */
970 #define ONELINE_SEEN (1u<<20)
972 static int handle_one_ref(const char *path, const struct object_id *oid,
973 int flag, void *cb_data)
975 struct commit_list **list = cb_data;
976 struct object *object = parse_object(oid->hash);
979 if (object->type == OBJ_TAG) {
980 object = deref_tag(object, path, strlen(path));
984 if (object->type != OBJ_COMMIT)
986 commit_list_insert((struct commit *)object, list);
990 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
991 struct commit_list *list)
993 struct commit_list *backup = NULL, *l;
998 if (prefix[0] == '!') {
1001 if (prefix[0] == '-') {
1004 } else if (prefix[0] != '!') {
1009 if (regcomp(®ex, prefix, REG_EXTENDED))
1012 for (l = list; l; l = l->next) {
1013 l->item->object.flags |= ONELINE_SEEN;
1014 commit_list_insert(l->item, &backup);
1017 const char *p, *buf;
1018 struct commit *commit;
1021 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1022 if (!parse_object(commit->object.oid.hash))
1024 buf = get_commit_buffer(commit, NULL);
1025 p = strstr(buf, "\n\n");
1026 matches = negative ^ (p && !regexec(®ex, p + 2, 0, NULL, 0));
1027 unuse_commit_buffer(commit, buf);
1030 hashcpy(sha1, commit->object.oid.hash);
1036 free_commit_list(list);
1037 for (l = backup; l; l = l->next)
1038 clear_commit_marks(l->item, ONELINE_SEEN);
1039 free_commit_list(backup);
1040 return found ? 0 : -1;
1043 struct grab_nth_branch_switch_cbdata {
1048 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
1049 const char *email, unsigned long timestamp, int tz,
1050 const char *message, void *cb_data)
1052 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1053 const char *match = NULL, *target = NULL;
1056 if (skip_prefix(message, "checkout: moving from ", &match))
1057 target = strstr(match, " to ");
1059 if (!match || !target)
1061 if (--(cb->remaining) == 0) {
1062 len = target - match;
1063 strbuf_reset(&cb->buf);
1064 strbuf_add(&cb->buf, match, len);
1065 return 1; /* we are done */
1071 * Parse @{-N} syntax, return the number of characters parsed
1072 * if successful; otherwise signal an error with negative value.
1074 static int interpret_nth_prior_checkout(const char *name, int namelen,
1079 struct grab_nth_branch_switch_cbdata cb;
1085 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1087 brace = memchr(name, '}', namelen);
1090 nth = strtol(name + 3, &num_end, 10);
1091 if (num_end != brace)
1096 strbuf_init(&cb.buf, 20);
1099 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1101 strbuf_addbuf(buf, &cb.buf);
1102 retval = brace - name + 1;
1105 strbuf_release(&cb.buf);
1109 int get_oid_mb(const char *name, struct object_id *oid)
1111 struct commit *one, *two;
1112 struct commit_list *mbs;
1113 struct object_id oid_tmp;
1117 dots = strstr(name, "...");
1119 return get_oid(name, oid);
1121 st = get_oid("HEAD", &oid_tmp);
1124 strbuf_init(&sb, dots - name);
1125 strbuf_add(&sb, name, dots - name);
1126 st = get_sha1_committish(sb.buf, oid_tmp.hash);
1127 strbuf_release(&sb);
1131 one = lookup_commit_reference_gently(oid_tmp.hash, 0);
1135 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", oid_tmp.hash))
1137 two = lookup_commit_reference_gently(oid_tmp.hash, 0);
1140 mbs = get_merge_bases(one, two);
1141 if (!mbs || mbs->next)
1145 oidcpy(oid, &mbs->item->object.oid);
1147 free_commit_list(mbs);
1151 /* parse @something syntax, when 'something' is not {.*} */
1152 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1156 if (len || name[1] == '{')
1159 /* make sure it's a single @, or @@{.*}, not @foo */
1160 next = memchr(name + len + 1, '@', namelen - len - 1);
1161 if (next && next[1] != '{')
1164 next = name + namelen;
1165 if (next != name + 1)
1169 strbuf_add(buf, "HEAD", 4);
1173 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1175 /* we have extra data, which might need further processing */
1176 struct strbuf tmp = STRBUF_INIT;
1177 int used = buf->len;
1180 strbuf_add(buf, name + len, namelen - len);
1181 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1182 /* that data was not interpreted, remove our cruft */
1184 strbuf_setlen(buf, used);
1188 strbuf_addbuf(buf, &tmp);
1189 strbuf_release(&tmp);
1190 /* tweak for size of {-N} versus expanded ref name */
1191 return ret - used + len;
1194 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1196 char *s = shorten_unambiguous_ref(ref, 0);
1198 strbuf_addstr(buf, s);
1202 static int interpret_branch_mark(const char *name, int namelen,
1203 int at, struct strbuf *buf,
1204 int (*get_mark)(const char *, int),
1205 const char *(*get_data)(struct branch *,
1209 struct branch *branch;
1210 struct strbuf err = STRBUF_INIT;
1213 len = get_mark(name + at, namelen - at);
1217 if (memchr(name, ':', at))
1221 char *name_str = xmemdupz(name, at);
1222 branch = branch_get(name_str);
1225 branch = branch_get(NULL);
1227 value = get_data(branch, &err);
1231 set_shortened_ref(buf, value);
1236 * This reads short-hand syntax that not only evaluates to a commit
1237 * object name, but also can act as if the end user spelled the name
1238 * of the branch from the command line.
1240 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1241 * places the name of the branch in the given buf and returns the
1242 * number of characters parsed if successful.
1244 * - "<branch>@{upstream}" finds the name of the other ref that
1245 * <branch> is configured to merge with (missing <branch> defaults
1246 * to the current branch), and places the name of the branch in the
1247 * given buf and returns the number of characters parsed if
1250 * If the input is not of the accepted format, it returns a negative
1251 * number to signal an error.
1253 * If the input was ok but there are not N branch switches in the
1254 * reflog, it returns 0.
1256 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1260 int len = interpret_nth_prior_checkout(name, namelen, buf);
1263 namelen = strlen(name);
1266 return len; /* syntax Ok, not enough switches */
1267 } else if (len > 0) {
1269 return len; /* consumed all */
1271 return reinterpret(name, namelen, len, buf);
1275 (at = memchr(start, '@', namelen - (start - name)));
1278 len = interpret_empty_at(name, namelen, at - name, buf);
1280 return reinterpret(name, namelen, len, buf);
1282 len = interpret_branch_mark(name, namelen, at - name, buf,
1283 upstream_mark, branch_get_upstream);
1287 len = interpret_branch_mark(name, namelen, at - name, buf,
1288 push_mark, branch_get_push);
1296 int strbuf_branchname(struct strbuf *sb, const char *name)
1298 int len = strlen(name);
1299 int used = interpret_branch_name(name, len, sb);
1305 strbuf_add(sb, name + used, len - used);
1309 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1311 strbuf_branchname(sb, name);
1314 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1315 return check_refname_format(sb->buf, 0);
1319 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1320 * notably "xyz^" for "parent of xyz"
1322 int get_sha1(const char *name, unsigned char *sha1)
1324 struct object_context unused;
1325 return get_sha1_with_context(name, 0, sha1, &unused);
1329 * This is like "get_sha1()", but for struct object_id.
1331 int get_oid(const char *name, struct object_id *oid)
1333 return get_sha1(name, oid->hash);
1338 * Many callers know that the user meant to name a commit-ish by
1339 * syntactical positions where the object name appears. Calling this
1340 * function allows the machinery to disambiguate shorter-than-unique
1341 * abbreviated object names between commit-ish and others.
1343 * Note that this does NOT error out when the named object is not a
1344 * commit-ish. It is merely to give a hint to the disambiguation
1347 int get_sha1_committish(const char *name, unsigned char *sha1)
1349 struct object_context unused;
1350 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1354 int get_sha1_treeish(const char *name, unsigned char *sha1)
1356 struct object_context unused;
1357 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1361 int get_sha1_commit(const char *name, unsigned char *sha1)
1363 struct object_context unused;
1364 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1368 int get_sha1_tree(const char *name, unsigned char *sha1)
1370 struct object_context unused;
1371 return get_sha1_with_context(name, GET_SHA1_TREE,
1375 int get_sha1_blob(const char *name, unsigned char *sha1)
1377 struct object_context unused;
1378 return get_sha1_with_context(name, GET_SHA1_BLOB,
1382 /* Must be called only when object_name:filename doesn't exist. */
1383 static void diagnose_invalid_sha1_path(const char *prefix,
1384 const char *filename,
1385 const unsigned char *tree_sha1,
1386 const char *object_name,
1387 int object_name_len)
1389 unsigned char sha1[20];
1395 if (file_exists(filename))
1396 die("Path '%s' exists on disk, but not in '%.*s'.",
1397 filename, object_name_len, object_name);
1398 if (errno == ENOENT || errno == ENOTDIR) {
1399 char *fullname = xstrfmt("%s%s", prefix, filename);
1401 if (!get_tree_entry(tree_sha1, fullname,
1403 die("Path '%s' exists, but not '%s'.\n"
1404 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1407 object_name_len, object_name,
1409 object_name_len, object_name,
1412 die("Path '%s' does not exist in '%.*s'",
1413 filename, object_name_len, object_name);
1417 /* Must be called only when :stage:filename doesn't exist. */
1418 static void diagnose_invalid_index_path(int stage,
1420 const char *filename)
1422 const struct cache_entry *ce;
1424 unsigned namelen = strlen(filename);
1425 struct strbuf fullname = STRBUF_INIT;
1430 /* Wrong stage number? */
1431 pos = cache_name_pos(filename, namelen);
1434 if (pos < active_nr) {
1435 ce = active_cache[pos];
1436 if (ce_namelen(ce) == namelen &&
1437 !memcmp(ce->name, filename, namelen))
1438 die("Path '%s' is in the index, but not at stage %d.\n"
1439 "Did you mean ':%d:%s'?",
1441 ce_stage(ce), filename);
1444 /* Confusion between relative and absolute filenames? */
1445 strbuf_addstr(&fullname, prefix);
1446 strbuf_addstr(&fullname, filename);
1447 pos = cache_name_pos(fullname.buf, fullname.len);
1450 if (pos < active_nr) {
1451 ce = active_cache[pos];
1452 if (ce_namelen(ce) == fullname.len &&
1453 !memcmp(ce->name, fullname.buf, fullname.len))
1454 die("Path '%s' is in the index, but not '%s'.\n"
1455 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1456 fullname.buf, filename,
1457 ce_stage(ce), fullname.buf,
1458 ce_stage(ce), filename);
1461 if (file_exists(filename))
1462 die("Path '%s' exists on disk, but not in the index.", filename);
1463 if (errno == ENOENT || errno == ENOTDIR)
1464 die("Path '%s' does not exist (neither on disk nor in the index).",
1467 strbuf_release(&fullname);
1471 static char *resolve_relative_path(const char *rel)
1473 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1476 if (!is_inside_work_tree())
1477 die("relative path syntax can't be used outside working tree.");
1479 /* die() inside prefix_path() if resolved path is outside worktree */
1480 return prefix_path(startup_info->prefix,
1481 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1485 static int get_sha1_with_context_1(const char *name,
1488 unsigned char *sha1,
1489 struct object_context *oc)
1491 int ret, bracket_depth;
1492 int namelen = strlen(name);
1494 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1497 flags |= GET_SHA1_QUIETLY;
1499 memset(oc, 0, sizeof(*oc));
1500 oc->mode = S_IFINVALID;
1501 ret = get_sha1_1(name, namelen, sha1, flags);
1505 * sha1:path --> object name of path in ent sha1
1506 * :path -> object name of absolute path in index
1507 * :./path -> object name of path relative to cwd in index
1508 * :[0-3]:path -> object name of path in index at stage
1509 * :/foo -> recent commit matching foo
1511 if (name[0] == ':') {
1513 const struct cache_entry *ce;
1514 char *new_path = NULL;
1516 if (!only_to_die && namelen > 2 && name[1] == '/') {
1517 struct commit_list *list = NULL;
1519 for_each_ref(handle_one_ref, &list);
1520 commit_list_sort_by_date(&list);
1521 return get_sha1_oneline(name + 2, sha1, list);
1525 name[1] < '0' || '3' < name[1])
1528 stage = name[1] - '0';
1531 new_path = resolve_relative_path(cp);
1533 namelen = namelen - (cp - name);
1536 namelen = strlen(cp);
1539 strlcpy(oc->path, cp, sizeof(oc->path));
1543 pos = cache_name_pos(cp, namelen);
1546 while (pos < active_nr) {
1547 ce = active_cache[pos];
1548 if (ce_namelen(ce) != namelen ||
1549 memcmp(ce->name, cp, namelen))
1551 if (ce_stage(ce) == stage) {
1552 hashcpy(sha1, ce->oid.hash);
1553 oc->mode = ce->ce_mode;
1559 if (only_to_die && name[1] && name[1] != '/')
1560 diagnose_invalid_index_path(stage, prefix, cp);
1564 for (cp = name, bracket_depth = 0; *cp; cp++) {
1567 else if (bracket_depth && *cp == '}')
1569 else if (!bracket_depth && *cp == ':')
1573 unsigned char tree_sha1[20];
1574 int len = cp - name;
1575 unsigned sub_flags = flags;
1577 sub_flags &= ~GET_SHA1_DISAMBIGUATORS;
1578 sub_flags |= GET_SHA1_TREEISH;
1580 if (!get_sha1_1(name, len, tree_sha1, sub_flags)) {
1581 const char *filename = cp+1;
1582 char *new_filename = NULL;
1584 new_filename = resolve_relative_path(filename);
1586 filename = new_filename;
1587 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1588 ret = get_tree_entry_follow_symlinks(tree_sha1,
1589 filename, sha1, &oc->symlink_path,
1592 ret = get_tree_entry(tree_sha1, filename,
1594 if (ret && only_to_die) {
1595 diagnose_invalid_sha1_path(prefix,
1601 hashcpy(oc->tree, tree_sha1);
1602 strlcpy(oc->path, filename, sizeof(oc->path));
1608 die("Invalid object name '%.*s'.", len, name);
1615 * Call this function when you know "name" given by the end user must
1616 * name an object but it doesn't; the function _may_ die with a better
1617 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1618 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1619 * you have a chance to diagnose the error further.
1621 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1623 struct object_context oc;
1624 unsigned char sha1[20];
1625 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1628 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1630 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1631 die("BUG: incompatible flags for get_sha1_with_context");
1632 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);