ident: add user.useConfigOnly boolean for when ident shouldn't be guessed
[git/git-svn.git] / sha1_name.c
blob892db21813bc484628e940274e742d103629b0ed
1 #include "cache.h"
2 #include "tag.h"
3 #include "commit.h"
4 #include "tree.h"
5 #include "blob.h"
6 #include "tree-walk.h"
7 #include "refs.h"
8 #include "remote.h"
9 #include "dir.h"
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;
17 void *cb_data;
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;
23 unsigned ambiguous: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;
31 return;
33 if (!ds->candidate_exists) {
34 /* this is the first candidate */
35 hashcpy(ds->candidate, current);
36 ds->candidate_exists = 1;
37 return;
38 } else if (!hashcmp(ds->candidate, current)) {
39 /* the same as what we already have seen */
40 return;
43 if (!ds->fn) {
44 /* cannot disambiguate between ds->candidate and current */
45 ds->ambiguous = 1;
46 return;
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;
59 return;
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
66 * disambiguate.
68 ds->candidate_ok = 0;
69 ds->ambiguous = 1;
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;
78 char hex[40];
79 static struct alternate_object_database *fakeent;
81 if (!fakeent) {
83 * Create a "fake" alternate object database that
84 * points to our own object database, to make it
85 * easier to get a temporary working space in
86 * alt->name/alt->base while iterating over the
87 * object databases including our own.
89 const char *objdir = get_object_directory();
90 int objdir_len = strlen(objdir);
91 int entlen = objdir_len + 43;
92 fakeent = xmalloc(sizeof(*fakeent) + entlen);
93 memcpy(fakeent->base, objdir, objdir_len);
94 fakeent->name = fakeent->base + objdir_len + 1;
95 fakeent->name[-1] = '/';
97 fakeent->next = alt_odb_list;
99 xsnprintf(hex, sizeof(hex), "%.2s", hex_pfx);
100 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
101 struct dirent *de;
102 DIR *dir;
104 * every alt_odb struct has 42 extra bytes after the base
105 * for exactly this purpose
107 xsnprintf(alt->name, 42, "%.2s/", hex_pfx);
108 dir = opendir(alt->base);
109 if (!dir)
110 continue;
112 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
113 unsigned char sha1[20];
115 if (strlen(de->d_name) != 38)
116 continue;
117 if (memcmp(de->d_name, hex_pfx + 2, len - 2))
118 continue;
119 memcpy(hex + 2, de->d_name, 38);
120 if (!get_sha1_hex(hex, sha1))
121 update_candidates(ds, sha1);
123 closedir(dir);
127 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
129 do {
130 if (*a != *b)
131 return 0;
132 a++;
133 b++;
134 len -= 2;
135 } while (len > 1);
136 if (len)
137 if ((*a ^ *b) & 0xf0)
138 return 0;
139 return 1;
142 static void unique_in_pack(int len,
143 const unsigned char *bin_pfx,
144 struct packed_git *p,
145 struct disambiguate_state *ds)
147 uint32_t num, last, i, first = 0;
148 const unsigned char *current = NULL;
150 open_pack_index(p);
151 num = p->num_objects;
152 last = num;
153 while (first < last) {
154 uint32_t mid = (first + last) / 2;
155 const unsigned char *current;
156 int cmp;
158 current = nth_packed_object_sha1(p, mid);
159 cmp = hashcmp(bin_pfx, current);
160 if (!cmp) {
161 first = mid;
162 break;
164 if (cmp > 0) {
165 first = mid+1;
166 continue;
168 last = mid;
172 * At this point, "first" is the location of the lowest object
173 * with an object name that could match "bin_pfx". See if we have
174 * 0, 1 or more objects that actually match(es).
176 for (i = first; i < num && !ds->ambiguous; i++) {
177 current = nth_packed_object_sha1(p, i);
178 if (!match_sha(len, bin_pfx, current))
179 break;
180 update_candidates(ds, current);
184 static void find_short_packed_object(int len, const unsigned char *bin_pfx,
185 struct disambiguate_state *ds)
187 struct packed_git *p;
189 prepare_packed_git();
190 for (p = packed_git; p && !ds->ambiguous; p = p->next)
191 unique_in_pack(len, bin_pfx, p, ds);
194 #define SHORT_NAME_NOT_FOUND (-1)
195 #define SHORT_NAME_AMBIGUOUS (-2)
197 static int finish_object_disambiguation(struct disambiguate_state *ds,
198 unsigned char *sha1)
200 if (ds->ambiguous)
201 return SHORT_NAME_AMBIGUOUS;
203 if (!ds->candidate_exists)
204 return SHORT_NAME_NOT_FOUND;
206 if (!ds->candidate_checked)
208 * If this is the only candidate, there is no point
209 * calling the disambiguation hint callback.
211 * On the other hand, if the current candidate
212 * replaced an earlier candidate that did _not_ pass
213 * the disambiguation hint callback, then we do have
214 * more than one objects that match the short name
215 * given, so we should make sure this one matches;
216 * otherwise, if we discovered this one and the one
217 * that we previously discarded in the reverse order,
218 * we would end up showing different results in the
219 * same repository!
221 ds->candidate_ok = (!ds->disambiguate_fn_used ||
222 ds->fn(ds->candidate, ds->cb_data));
224 if (!ds->candidate_ok)
225 return SHORT_NAME_AMBIGUOUS;
227 hashcpy(sha1, ds->candidate);
228 return 0;
231 static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
233 int kind = sha1_object_info(sha1, NULL);
234 return kind == OBJ_COMMIT;
237 static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
239 struct object *obj;
240 int kind;
242 kind = sha1_object_info(sha1, NULL);
243 if (kind == OBJ_COMMIT)
244 return 1;
245 if (kind != OBJ_TAG)
246 return 0;
248 /* We need to do this the hard way... */
249 obj = deref_tag(parse_object(sha1), NULL, 0);
250 if (obj && obj->type == OBJ_COMMIT)
251 return 1;
252 return 0;
255 static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
257 int kind = sha1_object_info(sha1, NULL);
258 return kind == OBJ_TREE;
261 static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
263 struct object *obj;
264 int kind;
266 kind = sha1_object_info(sha1, NULL);
267 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
268 return 1;
269 if (kind != OBJ_TAG)
270 return 0;
272 /* We need to do this the hard way... */
273 obj = deref_tag(lookup_object(sha1), NULL, 0);
274 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
275 return 1;
276 return 0;
279 static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
281 int kind = sha1_object_info(sha1, NULL);
282 return kind == OBJ_BLOB;
285 static int prepare_prefixes(const char *name, int len,
286 unsigned char *bin_pfx,
287 char *hex_pfx)
289 int i;
291 hashclr(bin_pfx);
292 memset(hex_pfx, 'x', 40);
293 for (i = 0; i < len ;i++) {
294 unsigned char c = name[i];
295 unsigned char val;
296 if (c >= '0' && c <= '9')
297 val = c - '0';
298 else if (c >= 'a' && c <= 'f')
299 val = c - 'a' + 10;
300 else if (c >= 'A' && c <='F') {
301 val = c - 'A' + 10;
302 c -= 'A' - 'a';
304 else
305 return -1;
306 hex_pfx[i] = c;
307 if (!(i & 1))
308 val <<= 4;
309 bin_pfx[i >> 1] |= val;
311 return 0;
314 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
315 unsigned flags)
317 int status;
318 char hex_pfx[40];
319 unsigned char bin_pfx[20];
320 struct disambiguate_state ds;
321 int quietly = !!(flags & GET_SHA1_QUIETLY);
323 if (len < MINIMUM_ABBREV || len > 40)
324 return -1;
325 if (prepare_prefixes(name, len, bin_pfx, hex_pfx) < 0)
326 return -1;
328 prepare_alt_odb();
330 memset(&ds, 0, sizeof(ds));
331 if (flags & GET_SHA1_COMMIT)
332 ds.fn = disambiguate_commit_only;
333 else if (flags & GET_SHA1_COMMITTISH)
334 ds.fn = disambiguate_committish_only;
335 else if (flags & GET_SHA1_TREE)
336 ds.fn = disambiguate_tree_only;
337 else if (flags & GET_SHA1_TREEISH)
338 ds.fn = disambiguate_treeish_only;
339 else if (flags & GET_SHA1_BLOB)
340 ds.fn = disambiguate_blob_only;
342 find_short_object_filename(len, hex_pfx, &ds);
343 find_short_packed_object(len, bin_pfx, &ds);
344 status = finish_object_disambiguation(&ds, sha1);
346 if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
347 return error("short SHA1 %.*s is ambiguous.", len, hex_pfx);
348 return status;
351 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
353 char hex_pfx[40];
354 unsigned char bin_pfx[20];
355 struct disambiguate_state ds;
356 int len = strlen(prefix);
358 if (len < MINIMUM_ABBREV || len > 40)
359 return -1;
360 if (prepare_prefixes(prefix, len, bin_pfx, hex_pfx) < 0)
361 return -1;
363 prepare_alt_odb();
365 memset(&ds, 0, sizeof(ds));
366 ds.always_call_fn = 1;
367 ds.cb_data = cb_data;
368 ds.fn = fn;
370 find_short_object_filename(len, hex_pfx, &ds);
371 find_short_packed_object(len, bin_pfx, &ds);
372 return ds.ambiguous;
375 int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
377 int status, exists;
379 sha1_to_hex_r(hex, sha1);
380 if (len == 40 || !len)
381 return 40;
382 exists = has_sha1_file(sha1);
383 while (len < 40) {
384 unsigned char sha1_ret[20];
385 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
386 if (exists
387 ? !status
388 : status == SHORT_NAME_NOT_FOUND) {
389 hex[len] = 0;
390 return len;
392 len++;
394 return len;
397 const char *find_unique_abbrev(const unsigned char *sha1, int len)
399 static char hex[GIT_SHA1_HEXSZ + 1];
400 find_unique_abbrev_r(hex, sha1, len);
401 return hex;
404 static int ambiguous_path(const char *path, int len)
406 int slash = 1;
407 int cnt;
409 for (cnt = 0; cnt < len; cnt++) {
410 switch (*path++) {
411 case '\0':
412 break;
413 case '/':
414 if (slash)
415 break;
416 slash = 1;
417 continue;
418 case '.':
419 continue;
420 default:
421 slash = 0;
422 continue;
424 break;
426 return slash;
429 static inline int at_mark(const char *string, int len,
430 const char **suffix, int nr)
432 int i;
434 for (i = 0; i < nr; i++) {
435 int suffix_len = strlen(suffix[i]);
436 if (suffix_len <= len
437 && !memcmp(string, suffix[i], suffix_len))
438 return suffix_len;
440 return 0;
443 static inline int upstream_mark(const char *string, int len)
445 const char *suffix[] = { "@{upstream}", "@{u}" };
446 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
449 static inline int push_mark(const char *string, int len)
451 const char *suffix[] = { "@{push}" };
452 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
455 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
456 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
458 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
459 unsigned int flags)
461 static const char *warn_msg = "refname '%.*s' is ambiguous.";
462 static const char *object_name_msg = N_(
463 "Git normally never creates a ref that ends with 40 hex characters\n"
464 "because it will be ignored when you just specify 40-hex. These refs\n"
465 "may be created by mistake. For example,\n"
466 "\n"
467 " git checkout -b $br $(git rev-parse ...)\n"
468 "\n"
469 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
470 "examine these refs and maybe delete them. Turn this message off by\n"
471 "running \"git config advice.objectNameWarning false\"");
472 unsigned char tmp_sha1[20];
473 char *real_ref = NULL;
474 int refs_found = 0;
475 int at, reflog_len, nth_prior = 0;
477 if (len == 40 && !get_sha1_hex(str, sha1)) {
478 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
479 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
480 if (refs_found > 0) {
481 warning(warn_msg, len, str);
482 if (advice_object_name_warning)
483 fprintf(stderr, "%s\n", _(object_name_msg));
485 free(real_ref);
487 return 0;
490 /* basic@{time or number or -number} format to query ref-log */
491 reflog_len = at = 0;
492 if (len && str[len-1] == '}') {
493 for (at = len-4; at >= 0; at--) {
494 if (str[at] == '@' && str[at+1] == '{') {
495 if (str[at+2] == '-') {
496 if (at != 0)
497 /* @{-N} not at start */
498 return -1;
499 nth_prior = 1;
500 continue;
502 if (!upstream_mark(str + at, len - at) &&
503 !push_mark(str + at, len - at)) {
504 reflog_len = (len-1) - (at+2);
505 len = at;
507 break;
512 /* Accept only unambiguous ref paths. */
513 if (len && ambiguous_path(str, len))
514 return -1;
516 if (nth_prior) {
517 struct strbuf buf = STRBUF_INIT;
518 int detached;
520 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
521 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
522 strbuf_release(&buf);
523 if (detached)
524 return 0;
528 if (!len && reflog_len)
529 /* allow "@{...}" to mean the current branch reflog */
530 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
531 else if (reflog_len)
532 refs_found = dwim_log(str, len, sha1, &real_ref);
533 else
534 refs_found = dwim_ref(str, len, sha1, &real_ref);
536 if (!refs_found)
537 return -1;
539 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
540 (refs_found > 1 ||
541 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
542 warning(warn_msg, len, str);
544 if (reflog_len) {
545 int nth, i;
546 unsigned long at_time;
547 unsigned long co_time;
548 int co_tz, co_cnt;
550 /* Is it asking for N-th entry, or approxidate? */
551 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
552 char ch = str[at+2+i];
553 if ('0' <= ch && ch <= '9')
554 nth = nth * 10 + ch - '0';
555 else
556 nth = -1;
558 if (100000000 <= nth) {
559 at_time = nth;
560 nth = -1;
561 } else if (0 <= nth)
562 at_time = 0;
563 else {
564 int errors = 0;
565 char *tmp = xstrndup(str + at + 2, reflog_len);
566 at_time = approxidate_careful(tmp, &errors);
567 free(tmp);
568 if (errors) {
569 free(real_ref);
570 return -1;
573 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
574 &co_time, &co_tz, &co_cnt)) {
575 if (!len) {
576 if (starts_with(real_ref, "refs/heads/")) {
577 str = real_ref + 11;
578 len = strlen(real_ref + 11);
579 } else {
580 /* detached HEAD */
581 str = "HEAD";
582 len = 4;
585 if (at_time) {
586 if (!(flags & GET_SHA1_QUIETLY)) {
587 warning("Log for '%.*s' only goes "
588 "back to %s.", len, str,
589 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
591 } else {
592 if (flags & GET_SHA1_QUIETLY) {
593 exit(128);
595 die("Log for '%.*s' only has %d entries.",
596 len, str, co_cnt);
601 free(real_ref);
602 return 0;
605 static int get_parent(const char *name, int len,
606 unsigned char *result, int idx)
608 unsigned char sha1[20];
609 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
610 struct commit *commit;
611 struct commit_list *p;
613 if (ret)
614 return ret;
615 commit = lookup_commit_reference(sha1);
616 if (parse_commit(commit))
617 return -1;
618 if (!idx) {
619 hashcpy(result, commit->object.oid.hash);
620 return 0;
622 p = commit->parents;
623 while (p) {
624 if (!--idx) {
625 hashcpy(result, p->item->object.oid.hash);
626 return 0;
628 p = p->next;
630 return -1;
633 static int get_nth_ancestor(const char *name, int len,
634 unsigned char *result, int generation)
636 unsigned char sha1[20];
637 struct commit *commit;
638 int ret;
640 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
641 if (ret)
642 return ret;
643 commit = lookup_commit_reference(sha1);
644 if (!commit)
645 return -1;
647 while (generation--) {
648 if (parse_commit(commit) || !commit->parents)
649 return -1;
650 commit = commit->parents->item;
652 hashcpy(result, commit->object.oid.hash);
653 return 0;
656 struct object *peel_to_type(const char *name, int namelen,
657 struct object *o, enum object_type expected_type)
659 if (name && !namelen)
660 namelen = strlen(name);
661 while (1) {
662 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
663 return NULL;
664 if (expected_type == OBJ_ANY || o->type == expected_type)
665 return o;
666 if (o->type == OBJ_TAG)
667 o = ((struct tag*) o)->tagged;
668 else if (o->type == OBJ_COMMIT)
669 o = &(((struct commit *) o)->tree->object);
670 else {
671 if (name)
672 error("%.*s: expected %s type, but the object "
673 "dereferences to %s type",
674 namelen, name, typename(expected_type),
675 typename(o->type));
676 return NULL;
681 static int peel_onion(const char *name, int len, unsigned char *sha1)
683 unsigned char outer[20];
684 const char *sp;
685 unsigned int expected_type = 0;
686 unsigned lookup_flags = 0;
687 struct object *o;
690 * "ref^{type}" dereferences ref repeatedly until you cannot
691 * dereference anymore, or you get an object of given type,
692 * whichever comes first. "ref^{}" means just dereference
693 * tags until you get a non-tag. "ref^0" is a shorthand for
694 * "ref^{commit}". "commit^{tree}" could be used to find the
695 * top-level tree of the given commit.
697 if (len < 4 || name[len-1] != '}')
698 return -1;
700 for (sp = name + len - 1; name <= sp; sp--) {
701 int ch = *sp;
702 if (ch == '{' && name < sp && sp[-1] == '^')
703 break;
705 if (sp <= name)
706 return -1;
708 sp++; /* beginning of type name, or closing brace for empty */
709 if (starts_with(sp, "commit}"))
710 expected_type = OBJ_COMMIT;
711 else if (starts_with(sp, "tag}"))
712 expected_type = OBJ_TAG;
713 else if (starts_with(sp, "tree}"))
714 expected_type = OBJ_TREE;
715 else if (starts_with(sp, "blob}"))
716 expected_type = OBJ_BLOB;
717 else if (starts_with(sp, "object}"))
718 expected_type = OBJ_ANY;
719 else if (sp[0] == '}')
720 expected_type = OBJ_NONE;
721 else if (sp[0] == '/')
722 expected_type = OBJ_COMMIT;
723 else
724 return -1;
726 if (expected_type == OBJ_COMMIT)
727 lookup_flags = GET_SHA1_COMMITTISH;
728 else if (expected_type == OBJ_TREE)
729 lookup_flags = GET_SHA1_TREEISH;
731 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
732 return -1;
734 o = parse_object(outer);
735 if (!o)
736 return -1;
737 if (!expected_type) {
738 o = deref_tag(o, name, sp - name - 2);
739 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
740 return -1;
741 hashcpy(sha1, o->oid.hash);
742 return 0;
746 * At this point, the syntax look correct, so
747 * if we do not get the needed object, we should
748 * barf.
750 o = peel_to_type(name, len, o, expected_type);
751 if (!o)
752 return -1;
754 hashcpy(sha1, o->oid.hash);
755 if (sp[0] == '/') {
756 /* "$commit^{/foo}" */
757 char *prefix;
758 int ret;
759 struct commit_list *list = NULL;
762 * $commit^{/}. Some regex implementation may reject.
763 * We don't need regex anyway. '' pattern always matches.
765 if (sp[1] == '}')
766 return 0;
768 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
769 commit_list_insert((struct commit *)o, &list);
770 ret = get_sha1_oneline(prefix, sha1, list);
771 free(prefix);
772 return ret;
774 return 0;
777 static int get_describe_name(const char *name, int len, unsigned char *sha1)
779 const char *cp;
780 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
782 for (cp = name + len - 1; name + 2 <= cp; cp--) {
783 char ch = *cp;
784 if (!isxdigit(ch)) {
785 /* We must be looking at g in "SOMETHING-g"
786 * for it to be describe output.
788 if (ch == 'g' && cp[-1] == '-') {
789 cp++;
790 len -= cp - name;
791 return get_short_sha1(cp, len, sha1, flags);
795 return -1;
798 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
800 int ret, has_suffix;
801 const char *cp;
804 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
806 has_suffix = 0;
807 for (cp = name + len - 1; name <= cp; cp--) {
808 int ch = *cp;
809 if ('0' <= ch && ch <= '9')
810 continue;
811 if (ch == '~' || ch == '^')
812 has_suffix = ch;
813 break;
816 if (has_suffix) {
817 int num = 0;
818 int len1 = cp - name;
819 cp++;
820 while (cp < name + len)
821 num = num * 10 + *cp++ - '0';
822 if (!num && len1 == len - 1)
823 num = 1;
824 if (has_suffix == '^')
825 return get_parent(name, len1, sha1, num);
826 /* else if (has_suffix == '~') -- goes without saying */
827 return get_nth_ancestor(name, len1, sha1, num);
830 ret = peel_onion(name, len, sha1);
831 if (!ret)
832 return 0;
834 ret = get_sha1_basic(name, len, sha1, lookup_flags);
835 if (!ret)
836 return 0;
838 /* It could be describe output that is "SOMETHING-gXXXX" */
839 ret = get_describe_name(name, len, sha1);
840 if (!ret)
841 return 0;
843 return get_short_sha1(name, len, sha1, lookup_flags);
847 * This interprets names like ':/Initial revision of "git"' by searching
848 * through history and returning the first commit whose message starts
849 * the given regular expression.
851 * For future extension, ':/!' is reserved. If you want to match a message
852 * beginning with a '!', you have to repeat the exclamation mark.
855 /* Remember to update object flag allocation in object.h */
856 #define ONELINE_SEEN (1u<<20)
858 static int handle_one_ref(const char *path, const struct object_id *oid,
859 int flag, void *cb_data)
861 struct commit_list **list = cb_data;
862 struct object *object = parse_object(oid->hash);
863 if (!object)
864 return 0;
865 if (object->type == OBJ_TAG) {
866 object = deref_tag(object, path, strlen(path));
867 if (!object)
868 return 0;
870 if (object->type != OBJ_COMMIT)
871 return 0;
872 commit_list_insert((struct commit *)object, list);
873 return 0;
876 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
877 struct commit_list *list)
879 struct commit_list *backup = NULL, *l;
880 int found = 0;
881 regex_t regex;
883 if (prefix[0] == '!') {
884 if (prefix[1] != '!')
885 die ("Invalid search pattern: %s", prefix);
886 prefix++;
889 if (regcomp(&regex, prefix, REG_EXTENDED))
890 die("Invalid search pattern: %s", prefix);
892 for (l = list; l; l = l->next) {
893 l->item->object.flags |= ONELINE_SEEN;
894 commit_list_insert(l->item, &backup);
896 while (list) {
897 const char *p, *buf;
898 struct commit *commit;
899 int matches;
901 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
902 if (!parse_object(commit->object.oid.hash))
903 continue;
904 buf = get_commit_buffer(commit, NULL);
905 p = strstr(buf, "\n\n");
906 matches = p && !regexec(&regex, p + 2, 0, NULL, 0);
907 unuse_commit_buffer(commit, buf);
909 if (matches) {
910 hashcpy(sha1, commit->object.oid.hash);
911 found = 1;
912 break;
915 regfree(&regex);
916 free_commit_list(list);
917 for (l = backup; l; l = l->next)
918 clear_commit_marks(l->item, ONELINE_SEEN);
919 free_commit_list(backup);
920 return found ? 0 : -1;
923 struct grab_nth_branch_switch_cbdata {
924 int remaining;
925 struct strbuf buf;
928 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
929 const char *email, unsigned long timestamp, int tz,
930 const char *message, void *cb_data)
932 struct grab_nth_branch_switch_cbdata *cb = cb_data;
933 const char *match = NULL, *target = NULL;
934 size_t len;
936 if (skip_prefix(message, "checkout: moving from ", &match))
937 target = strstr(match, " to ");
939 if (!match || !target)
940 return 0;
941 if (--(cb->remaining) == 0) {
942 len = target - match;
943 strbuf_reset(&cb->buf);
944 strbuf_add(&cb->buf, match, len);
945 return 1; /* we are done */
947 return 0;
951 * Parse @{-N} syntax, return the number of characters parsed
952 * if successful; otherwise signal an error with negative value.
954 static int interpret_nth_prior_checkout(const char *name, int namelen,
955 struct strbuf *buf)
957 long nth;
958 int retval;
959 struct grab_nth_branch_switch_cbdata cb;
960 const char *brace;
961 char *num_end;
963 if (namelen < 4)
964 return -1;
965 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
966 return -1;
967 brace = memchr(name, '}', namelen);
968 if (!brace)
969 return -1;
970 nth = strtol(name + 3, &num_end, 10);
971 if (num_end != brace)
972 return -1;
973 if (nth <= 0)
974 return -1;
975 cb.remaining = nth;
976 strbuf_init(&cb.buf, 20);
978 retval = 0;
979 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
980 strbuf_reset(buf);
981 strbuf_addbuf(buf, &cb.buf);
982 retval = brace - name + 1;
985 strbuf_release(&cb.buf);
986 return retval;
989 int get_sha1_mb(const char *name, unsigned char *sha1)
991 struct commit *one, *two;
992 struct commit_list *mbs;
993 unsigned char sha1_tmp[20];
994 const char *dots;
995 int st;
997 dots = strstr(name, "...");
998 if (!dots)
999 return get_sha1(name, sha1);
1000 if (dots == name)
1001 st = get_sha1("HEAD", sha1_tmp);
1002 else {
1003 struct strbuf sb;
1004 strbuf_init(&sb, dots - name);
1005 strbuf_add(&sb, name, dots - name);
1006 st = get_sha1_committish(sb.buf, sha1_tmp);
1007 strbuf_release(&sb);
1009 if (st)
1010 return st;
1011 one = lookup_commit_reference_gently(sha1_tmp, 0);
1012 if (!one)
1013 return -1;
1015 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
1016 return -1;
1017 two = lookup_commit_reference_gently(sha1_tmp, 0);
1018 if (!two)
1019 return -1;
1020 mbs = get_merge_bases(one, two);
1021 if (!mbs || mbs->next)
1022 st = -1;
1023 else {
1024 st = 0;
1025 hashcpy(sha1, mbs->item->object.oid.hash);
1027 free_commit_list(mbs);
1028 return st;
1031 /* parse @something syntax, when 'something' is not {.*} */
1032 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1034 const char *next;
1036 if (len || name[1] == '{')
1037 return -1;
1039 /* make sure it's a single @, or @@{.*}, not @foo */
1040 next = memchr(name + len + 1, '@', namelen - len - 1);
1041 if (next && next[1] != '{')
1042 return -1;
1043 if (!next)
1044 next = name + namelen;
1045 if (next != name + 1)
1046 return -1;
1048 strbuf_reset(buf);
1049 strbuf_add(buf, "HEAD", 4);
1050 return 1;
1053 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1055 /* we have extra data, which might need further processing */
1056 struct strbuf tmp = STRBUF_INIT;
1057 int used = buf->len;
1058 int ret;
1060 strbuf_add(buf, name + len, namelen - len);
1061 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1062 /* that data was not interpreted, remove our cruft */
1063 if (ret < 0) {
1064 strbuf_setlen(buf, used);
1065 return len;
1067 strbuf_reset(buf);
1068 strbuf_addbuf(buf, &tmp);
1069 strbuf_release(&tmp);
1070 /* tweak for size of {-N} versus expanded ref name */
1071 return ret - used + len;
1074 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1076 char *s = shorten_unambiguous_ref(ref, 0);
1077 strbuf_reset(buf);
1078 strbuf_addstr(buf, s);
1079 free(s);
1082 static int interpret_branch_mark(const char *name, int namelen,
1083 int at, struct strbuf *buf,
1084 int (*get_mark)(const char *, int),
1085 const char *(*get_data)(struct branch *,
1086 struct strbuf *))
1088 int len;
1089 struct branch *branch;
1090 struct strbuf err = STRBUF_INIT;
1091 const char *value;
1093 len = get_mark(name + at, namelen - at);
1094 if (!len)
1095 return -1;
1097 if (memchr(name, ':', at))
1098 return -1;
1100 if (at) {
1101 char *name_str = xmemdupz(name, at);
1102 branch = branch_get(name_str);
1103 free(name_str);
1104 } else
1105 branch = branch_get(NULL);
1107 value = get_data(branch, &err);
1108 if (!value)
1109 die("%s", err.buf);
1111 set_shortened_ref(buf, value);
1112 return len + at;
1116 * This reads short-hand syntax that not only evaluates to a commit
1117 * object name, but also can act as if the end user spelled the name
1118 * of the branch from the command line.
1120 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1121 * places the name of the branch in the given buf and returns the
1122 * number of characters parsed if successful.
1124 * - "<branch>@{upstream}" finds the name of the other ref that
1125 * <branch> is configured to merge with (missing <branch> defaults
1126 * to the current branch), and places the name of the branch in the
1127 * given buf and returns the number of characters parsed if
1128 * successful.
1130 * If the input is not of the accepted format, it returns a negative
1131 * number to signal an error.
1133 * If the input was ok but there are not N branch switches in the
1134 * reflog, it returns 0.
1136 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1138 char *at;
1139 const char *start;
1140 int len = interpret_nth_prior_checkout(name, namelen, buf);
1142 if (!namelen)
1143 namelen = strlen(name);
1145 if (!len) {
1146 return len; /* syntax Ok, not enough switches */
1147 } else if (len > 0) {
1148 if (len == namelen)
1149 return len; /* consumed all */
1150 else
1151 return reinterpret(name, namelen, len, buf);
1154 for (start = name;
1155 (at = memchr(start, '@', namelen - (start - name)));
1156 start = at + 1) {
1158 len = interpret_empty_at(name, namelen, at - name, buf);
1159 if (len > 0)
1160 return reinterpret(name, namelen, len, buf);
1162 len = interpret_branch_mark(name, namelen, at - name, buf,
1163 upstream_mark, branch_get_upstream);
1164 if (len > 0)
1165 return len;
1167 len = interpret_branch_mark(name, namelen, at - name, buf,
1168 push_mark, branch_get_push);
1169 if (len > 0)
1170 return len;
1173 return -1;
1176 int strbuf_branchname(struct strbuf *sb, const char *name)
1178 int len = strlen(name);
1179 int used = interpret_branch_name(name, len, sb);
1181 if (used == len)
1182 return 0;
1183 if (used < 0)
1184 used = 0;
1185 strbuf_add(sb, name + used, len - used);
1186 return len;
1189 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1191 strbuf_branchname(sb, name);
1192 if (name[0] == '-')
1193 return -1;
1194 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1195 return check_refname_format(sb->buf, 0);
1199 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1200 * notably "xyz^" for "parent of xyz"
1202 int get_sha1(const char *name, unsigned char *sha1)
1204 struct object_context unused;
1205 return get_sha1_with_context(name, 0, sha1, &unused);
1209 * Many callers know that the user meant to name a commit-ish by
1210 * syntactical positions where the object name appears. Calling this
1211 * function allows the machinery to disambiguate shorter-than-unique
1212 * abbreviated object names between commit-ish and others.
1214 * Note that this does NOT error out when the named object is not a
1215 * commit-ish. It is merely to give a hint to the disambiguation
1216 * machinery.
1218 int get_sha1_committish(const char *name, unsigned char *sha1)
1220 struct object_context unused;
1221 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1222 sha1, &unused);
1225 int get_sha1_treeish(const char *name, unsigned char *sha1)
1227 struct object_context unused;
1228 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1229 sha1, &unused);
1232 int get_sha1_commit(const char *name, unsigned char *sha1)
1234 struct object_context unused;
1235 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1236 sha1, &unused);
1239 int get_sha1_tree(const char *name, unsigned char *sha1)
1241 struct object_context unused;
1242 return get_sha1_with_context(name, GET_SHA1_TREE,
1243 sha1, &unused);
1246 int get_sha1_blob(const char *name, unsigned char *sha1)
1248 struct object_context unused;
1249 return get_sha1_with_context(name, GET_SHA1_BLOB,
1250 sha1, &unused);
1253 /* Must be called only when object_name:filename doesn't exist. */
1254 static void diagnose_invalid_sha1_path(const char *prefix,
1255 const char *filename,
1256 const unsigned char *tree_sha1,
1257 const char *object_name,
1258 int object_name_len)
1260 unsigned char sha1[20];
1261 unsigned mode;
1263 if (!prefix)
1264 prefix = "";
1266 if (file_exists(filename))
1267 die("Path '%s' exists on disk, but not in '%.*s'.",
1268 filename, object_name_len, object_name);
1269 if (errno == ENOENT || errno == ENOTDIR) {
1270 char *fullname = xstrfmt("%s%s", prefix, filename);
1272 if (!get_tree_entry(tree_sha1, fullname,
1273 sha1, &mode)) {
1274 die("Path '%s' exists, but not '%s'.\n"
1275 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1276 fullname,
1277 filename,
1278 object_name_len, object_name,
1279 fullname,
1280 object_name_len, object_name,
1281 filename);
1283 die("Path '%s' does not exist in '%.*s'",
1284 filename, object_name_len, object_name);
1288 /* Must be called only when :stage:filename doesn't exist. */
1289 static void diagnose_invalid_index_path(int stage,
1290 const char *prefix,
1291 const char *filename)
1293 const struct cache_entry *ce;
1294 int pos;
1295 unsigned namelen = strlen(filename);
1296 struct strbuf fullname = STRBUF_INIT;
1298 if (!prefix)
1299 prefix = "";
1301 /* Wrong stage number? */
1302 pos = cache_name_pos(filename, namelen);
1303 if (pos < 0)
1304 pos = -pos - 1;
1305 if (pos < active_nr) {
1306 ce = active_cache[pos];
1307 if (ce_namelen(ce) == namelen &&
1308 !memcmp(ce->name, filename, namelen))
1309 die("Path '%s' is in the index, but not at stage %d.\n"
1310 "Did you mean ':%d:%s'?",
1311 filename, stage,
1312 ce_stage(ce), filename);
1315 /* Confusion between relative and absolute filenames? */
1316 strbuf_addstr(&fullname, prefix);
1317 strbuf_addstr(&fullname, filename);
1318 pos = cache_name_pos(fullname.buf, fullname.len);
1319 if (pos < 0)
1320 pos = -pos - 1;
1321 if (pos < active_nr) {
1322 ce = active_cache[pos];
1323 if (ce_namelen(ce) == fullname.len &&
1324 !memcmp(ce->name, fullname.buf, fullname.len))
1325 die("Path '%s' is in the index, but not '%s'.\n"
1326 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1327 fullname.buf, filename,
1328 ce_stage(ce), fullname.buf,
1329 ce_stage(ce), filename);
1332 if (file_exists(filename))
1333 die("Path '%s' exists on disk, but not in the index.", filename);
1334 if (errno == ENOENT || errno == ENOTDIR)
1335 die("Path '%s' does not exist (neither on disk nor in the index).",
1336 filename);
1338 strbuf_release(&fullname);
1342 static char *resolve_relative_path(const char *rel)
1344 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1345 return NULL;
1347 if (!startup_info)
1348 die("BUG: startup_info struct is not initialized.");
1350 if (!is_inside_work_tree())
1351 die("relative path syntax can't be used outside working tree.");
1353 /* die() inside prefix_path() if resolved path is outside worktree */
1354 return prefix_path(startup_info->prefix,
1355 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1356 rel);
1359 static int get_sha1_with_context_1(const char *name,
1360 unsigned flags,
1361 const char *prefix,
1362 unsigned char *sha1,
1363 struct object_context *oc)
1365 int ret, bracket_depth;
1366 int namelen = strlen(name);
1367 const char *cp;
1368 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1370 memset(oc, 0, sizeof(*oc));
1371 oc->mode = S_IFINVALID;
1372 ret = get_sha1_1(name, namelen, sha1, flags);
1373 if (!ret)
1374 return ret;
1376 * sha1:path --> object name of path in ent sha1
1377 * :path -> object name of absolute path in index
1378 * :./path -> object name of path relative to cwd in index
1379 * :[0-3]:path -> object name of path in index at stage
1380 * :/foo -> recent commit matching foo
1382 if (name[0] == ':') {
1383 int stage = 0;
1384 const struct cache_entry *ce;
1385 char *new_path = NULL;
1386 int pos;
1387 if (!only_to_die && namelen > 2 && name[1] == '/') {
1388 struct commit_list *list = NULL;
1390 for_each_ref(handle_one_ref, &list);
1391 commit_list_sort_by_date(&list);
1392 return get_sha1_oneline(name + 2, sha1, list);
1394 if (namelen < 3 ||
1395 name[2] != ':' ||
1396 name[1] < '0' || '3' < name[1])
1397 cp = name + 1;
1398 else {
1399 stage = name[1] - '0';
1400 cp = name + 3;
1402 new_path = resolve_relative_path(cp);
1403 if (!new_path) {
1404 namelen = namelen - (cp - name);
1405 } else {
1406 cp = new_path;
1407 namelen = strlen(cp);
1410 strlcpy(oc->path, cp, sizeof(oc->path));
1412 if (!active_cache)
1413 read_cache();
1414 pos = cache_name_pos(cp, namelen);
1415 if (pos < 0)
1416 pos = -pos - 1;
1417 while (pos < active_nr) {
1418 ce = active_cache[pos];
1419 if (ce_namelen(ce) != namelen ||
1420 memcmp(ce->name, cp, namelen))
1421 break;
1422 if (ce_stage(ce) == stage) {
1423 hashcpy(sha1, ce->sha1);
1424 oc->mode = ce->ce_mode;
1425 free(new_path);
1426 return 0;
1428 pos++;
1430 if (only_to_die && name[1] && name[1] != '/')
1431 diagnose_invalid_index_path(stage, prefix, cp);
1432 free(new_path);
1433 return -1;
1435 for (cp = name, bracket_depth = 0; *cp; cp++) {
1436 if (*cp == '{')
1437 bracket_depth++;
1438 else if (bracket_depth && *cp == '}')
1439 bracket_depth--;
1440 else if (!bracket_depth && *cp == ':')
1441 break;
1443 if (*cp == ':') {
1444 unsigned char tree_sha1[20];
1445 int len = cp - name;
1446 if (!get_sha1_1(name, len, tree_sha1, GET_SHA1_TREEISH)) {
1447 const char *filename = cp+1;
1448 char *new_filename = NULL;
1450 new_filename = resolve_relative_path(filename);
1451 if (new_filename)
1452 filename = new_filename;
1453 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1454 ret = get_tree_entry_follow_symlinks(tree_sha1,
1455 filename, sha1, &oc->symlink_path,
1456 &oc->mode);
1457 } else {
1458 ret = get_tree_entry(tree_sha1, filename,
1459 sha1, &oc->mode);
1460 if (ret && only_to_die) {
1461 diagnose_invalid_sha1_path(prefix,
1462 filename,
1463 tree_sha1,
1464 name, len);
1467 hashcpy(oc->tree, tree_sha1);
1468 strlcpy(oc->path, filename, sizeof(oc->path));
1470 free(new_filename);
1471 return ret;
1472 } else {
1473 if (only_to_die)
1474 die("Invalid object name '%.*s'.", len, name);
1477 return ret;
1481 * Call this function when you know "name" given by the end user must
1482 * name an object but it doesn't; the function _may_ die with a better
1483 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1484 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1485 * you have a chance to diagnose the error further.
1487 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1489 struct object_context oc;
1490 unsigned char sha1[20];
1491 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1494 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1496 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1497 die("BUG: incompatible flags for get_sha1_with_context");
1498 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);