has_sha1_file: don't bother if we are not in a repository
[git/debian.git] / sha1_name.c
blob45aa26b3227b235fb918df93ae1da0d9accbdca2
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"
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 char hex_pfx[GIT_SHA1_HEXSZ + 1];
19 unsigned char bin_pfx[GIT_SHA1_RAWSZ];
21 disambiguate_hint_fn fn;
22 void *cb_data;
23 unsigned char candidate[GIT_SHA1_RAWSZ];
24 unsigned candidate_exists:1;
25 unsigned candidate_checked:1;
26 unsigned candidate_ok:1;
27 unsigned disambiguate_fn_used:1;
28 unsigned ambiguous:1;
29 unsigned always_call_fn:1;
32 static void update_candidates(struct disambiguate_state *ds, const unsigned char *current)
34 if (ds->always_call_fn) {
35 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
36 return;
38 if (!ds->candidate_exists) {
39 /* this is the first candidate */
40 hashcpy(ds->candidate, current);
41 ds->candidate_exists = 1;
42 return;
43 } else if (!hashcmp(ds->candidate, current)) {
44 /* the same as what we already have seen */
45 return;
48 if (!ds->fn) {
49 /* cannot disambiguate between ds->candidate and current */
50 ds->ambiguous = 1;
51 return;
54 if (!ds->candidate_checked) {
55 ds->candidate_ok = ds->fn(ds->candidate, ds->cb_data);
56 ds->disambiguate_fn_used = 1;
57 ds->candidate_checked = 1;
60 if (!ds->candidate_ok) {
61 /* discard the candidate; we know it does not satisfy fn */
62 hashcpy(ds->candidate, current);
63 ds->candidate_checked = 0;
64 return;
67 /* if we reach this point, we know ds->candidate satisfies fn */
68 if (ds->fn(current, ds->cb_data)) {
70 * if both current and candidate satisfy fn, we cannot
71 * disambiguate.
73 ds->candidate_ok = 0;
74 ds->ambiguous = 1;
77 /* otherwise, current can be discarded and candidate is still good */
80 static void find_short_object_filename(struct disambiguate_state *ds)
82 struct alternate_object_database *alt;
83 char hex[GIT_SHA1_HEXSZ];
84 static struct alternate_object_database *fakeent;
86 if (!fakeent) {
88 * Create a "fake" alternate object database that
89 * points to our own object database, to make it
90 * easier to get a temporary working space in
91 * alt->name/alt->base while iterating over the
92 * object databases including our own.
94 fakeent = alloc_alt_odb(get_object_directory());
96 fakeent->next = alt_odb_list;
98 xsnprintf(hex, sizeof(hex), "%.2s", ds->hex_pfx);
99 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
100 struct strbuf *buf = alt_scratch_buf(alt);
101 struct dirent *de;
102 DIR *dir;
104 strbuf_addf(buf, "%.2s/", ds->hex_pfx);
105 dir = opendir(buf->buf);
106 if (!dir)
107 continue;
109 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
110 unsigned char sha1[20];
112 if (strlen(de->d_name) != 38)
113 continue;
114 if (memcmp(de->d_name, ds->hex_pfx + 2, ds->len - 2))
115 continue;
116 memcpy(hex + 2, de->d_name, 38);
117 if (!get_sha1_hex(hex, sha1))
118 update_candidates(ds, sha1);
120 closedir(dir);
124 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
126 do {
127 if (*a != *b)
128 return 0;
129 a++;
130 b++;
131 len -= 2;
132 } while (len > 1);
133 if (len)
134 if ((*a ^ *b) & 0xf0)
135 return 0;
136 return 1;
139 static void unique_in_pack(struct packed_git *p,
140 struct disambiguate_state *ds)
142 uint32_t num, last, i, first = 0;
143 const unsigned char *current = NULL;
145 open_pack_index(p);
146 num = p->num_objects;
147 last = num;
148 while (first < last) {
149 uint32_t mid = (first + last) / 2;
150 const unsigned char *current;
151 int cmp;
153 current = nth_packed_object_sha1(p, mid);
154 cmp = hashcmp(ds->bin_pfx, current);
155 if (!cmp) {
156 first = mid;
157 break;
159 if (cmp > 0) {
160 first = mid+1;
161 continue;
163 last = mid;
167 * At this point, "first" is the location of the lowest object
168 * with an object name that could match "bin_pfx". See if we have
169 * 0, 1 or more objects that actually match(es).
171 for (i = first; i < num && !ds->ambiguous; i++) {
172 current = nth_packed_object_sha1(p, i);
173 if (!match_sha(ds->len, ds->bin_pfx, current))
174 break;
175 update_candidates(ds, current);
179 static void find_short_packed_object(struct disambiguate_state *ds)
181 struct packed_git *p;
183 prepare_packed_git();
184 for (p = packed_git; p && !ds->ambiguous; p = p->next)
185 unique_in_pack(p, ds);
188 #define SHORT_NAME_NOT_FOUND (-1)
189 #define SHORT_NAME_AMBIGUOUS (-2)
191 static int finish_object_disambiguation(struct disambiguate_state *ds,
192 unsigned char *sha1)
194 if (ds->ambiguous)
195 return SHORT_NAME_AMBIGUOUS;
197 if (!ds->candidate_exists)
198 return SHORT_NAME_NOT_FOUND;
200 if (!ds->candidate_checked)
202 * If this is the only candidate, there is no point
203 * calling the disambiguation hint callback.
205 * On the other hand, if the current candidate
206 * replaced an earlier candidate that did _not_ pass
207 * the disambiguation hint callback, then we do have
208 * more than one objects that match the short name
209 * given, so we should make sure this one matches;
210 * otherwise, if we discovered this one and the one
211 * that we previously discarded in the reverse order,
212 * we would end up showing different results in the
213 * same repository!
215 ds->candidate_ok = (!ds->disambiguate_fn_used ||
216 ds->fn(ds->candidate, ds->cb_data));
218 if (!ds->candidate_ok)
219 return SHORT_NAME_AMBIGUOUS;
221 hashcpy(sha1, ds->candidate);
222 return 0;
225 static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
227 int kind = sha1_object_info(sha1, NULL);
228 return kind == OBJ_COMMIT;
231 static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
233 struct object *obj;
234 int kind;
236 kind = sha1_object_info(sha1, NULL);
237 if (kind == OBJ_COMMIT)
238 return 1;
239 if (kind != OBJ_TAG)
240 return 0;
242 /* We need to do this the hard way... */
243 obj = deref_tag(parse_object(sha1), NULL, 0);
244 if (obj && obj->type == OBJ_COMMIT)
245 return 1;
246 return 0;
249 static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
251 int kind = sha1_object_info(sha1, NULL);
252 return kind == OBJ_TREE;
255 static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
257 struct object *obj;
258 int kind;
260 kind = sha1_object_info(sha1, NULL);
261 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
262 return 1;
263 if (kind != OBJ_TAG)
264 return 0;
266 /* We need to do this the hard way... */
267 obj = deref_tag(parse_object(sha1), NULL, 0);
268 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
269 return 1;
270 return 0;
273 static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
275 int kind = sha1_object_info(sha1, NULL);
276 return kind == OBJ_BLOB;
279 static disambiguate_hint_fn default_disambiguate_hint;
281 int set_disambiguate_hint_config(const char *var, const char *value)
283 static const struct {
284 const char *name;
285 disambiguate_hint_fn fn;
286 } hints[] = {
287 { "none", NULL },
288 { "commit", disambiguate_commit_only },
289 { "committish", disambiguate_committish_only },
290 { "tree", disambiguate_tree_only },
291 { "treeish", disambiguate_treeish_only },
292 { "blob", disambiguate_blob_only }
294 int i;
296 if (!value)
297 return config_error_nonbool(var);
299 for (i = 0; i < ARRAY_SIZE(hints); i++) {
300 if (!strcasecmp(value, hints[i].name)) {
301 default_disambiguate_hint = hints[i].fn;
302 return 0;
306 return error("unknown hint type for '%s': %s", var, value);
309 static int init_object_disambiguation(const char *name, int len,
310 struct disambiguate_state *ds)
312 int i;
314 if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
315 return -1;
317 memset(ds, 0, sizeof(*ds));
319 for (i = 0; i < len ;i++) {
320 unsigned char c = name[i];
321 unsigned char val;
322 if (c >= '0' && c <= '9')
323 val = c - '0';
324 else if (c >= 'a' && c <= 'f')
325 val = c - 'a' + 10;
326 else if (c >= 'A' && c <='F') {
327 val = c - 'A' + 10;
328 c -= 'A' - 'a';
330 else
331 return -1;
332 ds->hex_pfx[i] = c;
333 if (!(i & 1))
334 val <<= 4;
335 ds->bin_pfx[i >> 1] |= val;
338 ds->len = len;
339 ds->hex_pfx[len] = '\0';
340 prepare_alt_odb();
341 return 0;
344 static int show_ambiguous_object(const unsigned char *sha1, void *data)
346 const struct disambiguate_state *ds = data;
347 struct strbuf desc = STRBUF_INIT;
348 int type;
350 if (ds->fn && !ds->fn(sha1, ds->cb_data))
351 return 0;
353 type = sha1_object_info(sha1, NULL);
354 if (type == OBJ_COMMIT) {
355 struct commit *commit = lookup_commit(sha1);
356 if (commit) {
357 struct pretty_print_context pp = {0};
358 pp.date_mode.type = DATE_SHORT;
359 format_commit_message(commit, " %ad - %s", &desc, &pp);
361 } else if (type == OBJ_TAG) {
362 struct tag *tag = lookup_tag(sha1);
363 if (!parse_tag(tag) && tag->tag)
364 strbuf_addf(&desc, " %s", tag->tag);
367 advise(" %s %s%s",
368 find_unique_abbrev(sha1, DEFAULT_ABBREV),
369 typename(type) ? typename(type) : "unknown type",
370 desc.buf);
372 strbuf_release(&desc);
373 return 0;
376 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
377 unsigned flags)
379 int status;
380 struct disambiguate_state ds;
381 int quietly = !!(flags & GET_SHA1_QUIETLY);
383 if (init_object_disambiguation(name, len, &ds) < 0)
384 return -1;
386 if (HAS_MULTI_BITS(flags & GET_SHA1_DISAMBIGUATORS))
387 die("BUG: multiple get_short_sha1 disambiguator flags");
389 if (flags & GET_SHA1_COMMIT)
390 ds.fn = disambiguate_commit_only;
391 else if (flags & GET_SHA1_COMMITTISH)
392 ds.fn = disambiguate_committish_only;
393 else if (flags & GET_SHA1_TREE)
394 ds.fn = disambiguate_tree_only;
395 else if (flags & GET_SHA1_TREEISH)
396 ds.fn = disambiguate_treeish_only;
397 else if (flags & GET_SHA1_BLOB)
398 ds.fn = disambiguate_blob_only;
399 else
400 ds.fn = default_disambiguate_hint;
402 find_short_object_filename(&ds);
403 find_short_packed_object(&ds);
404 status = finish_object_disambiguation(&ds, sha1);
406 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
407 error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
410 * We may still have ambiguity if we simply saw a series of
411 * candidates that did not satisfy our hint function. In
412 * that case, we still want to show them, so disable the hint
413 * function entirely.
415 if (!ds.ambiguous)
416 ds.fn = NULL;
418 advise(_("The candidates are:"));
419 for_each_abbrev(ds.hex_pfx, show_ambiguous_object, &ds);
422 return status;
425 static int collect_ambiguous(const unsigned char *sha1, void *data)
427 sha1_array_append(data, sha1);
428 return 0;
431 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
433 struct sha1_array collect = SHA1_ARRAY_INIT;
434 struct disambiguate_state ds;
435 int ret;
437 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
438 return -1;
440 ds.always_call_fn = 1;
441 ds.fn = collect_ambiguous;
442 ds.cb_data = &collect;
443 find_short_object_filename(&ds);
444 find_short_packed_object(&ds);
446 ret = sha1_array_for_each_unique(&collect, fn, cb_data);
447 sha1_array_clear(&collect);
448 return ret;
451 int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
453 int status, exists;
455 sha1_to_hex_r(hex, sha1);
456 if (len == 40 || !len)
457 return 40;
458 exists = has_sha1_file(sha1);
459 while (len < 40) {
460 unsigned char sha1_ret[20];
461 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
462 if (exists
463 ? !status
464 : status == SHORT_NAME_NOT_FOUND) {
465 hex[len] = 0;
466 return len;
468 len++;
470 return len;
473 const char *find_unique_abbrev(const unsigned char *sha1, int len)
475 static int bufno;
476 static char hexbuffer[4][GIT_SHA1_HEXSZ + 1];
477 char *hex = hexbuffer[bufno];
478 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
479 find_unique_abbrev_r(hex, sha1, len);
480 return hex;
483 static int ambiguous_path(const char *path, int len)
485 int slash = 1;
486 int cnt;
488 for (cnt = 0; cnt < len; cnt++) {
489 switch (*path++) {
490 case '\0':
491 break;
492 case '/':
493 if (slash)
494 break;
495 slash = 1;
496 continue;
497 case '.':
498 continue;
499 default:
500 slash = 0;
501 continue;
503 break;
505 return slash;
508 static inline int at_mark(const char *string, int len,
509 const char **suffix, int nr)
511 int i;
513 for (i = 0; i < nr; i++) {
514 int suffix_len = strlen(suffix[i]);
515 if (suffix_len <= len
516 && !memcmp(string, suffix[i], suffix_len))
517 return suffix_len;
519 return 0;
522 static inline int upstream_mark(const char *string, int len)
524 const char *suffix[] = { "@{upstream}", "@{u}" };
525 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
528 static inline int push_mark(const char *string, int len)
530 const char *suffix[] = { "@{push}" };
531 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
534 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
535 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
537 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
538 unsigned int flags)
540 static const char *warn_msg = "refname '%.*s' is ambiguous.";
541 static const char *object_name_msg = N_(
542 "Git normally never creates a ref that ends with 40 hex characters\n"
543 "because it will be ignored when you just specify 40-hex. These refs\n"
544 "may be created by mistake. For example,\n"
545 "\n"
546 " git checkout -b $br $(git rev-parse ...)\n"
547 "\n"
548 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
549 "examine these refs and maybe delete them. Turn this message off by\n"
550 "running \"git config advice.objectNameWarning false\"");
551 unsigned char tmp_sha1[20];
552 char *real_ref = NULL;
553 int refs_found = 0;
554 int at, reflog_len, nth_prior = 0;
556 if (len == 40 && !get_sha1_hex(str, sha1)) {
557 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
558 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
559 if (refs_found > 0) {
560 warning(warn_msg, len, str);
561 if (advice_object_name_warning)
562 fprintf(stderr, "%s\n", _(object_name_msg));
564 free(real_ref);
566 return 0;
569 /* basic@{time or number or -number} format to query ref-log */
570 reflog_len = at = 0;
571 if (len && str[len-1] == '}') {
572 for (at = len-4; at >= 0; at--) {
573 if (str[at] == '@' && str[at+1] == '{') {
574 if (str[at+2] == '-') {
575 if (at != 0)
576 /* @{-N} not at start */
577 return -1;
578 nth_prior = 1;
579 continue;
581 if (!upstream_mark(str + at, len - at) &&
582 !push_mark(str + at, len - at)) {
583 reflog_len = (len-1) - (at+2);
584 len = at;
586 break;
591 /* Accept only unambiguous ref paths. */
592 if (len && ambiguous_path(str, len))
593 return -1;
595 if (nth_prior) {
596 struct strbuf buf = STRBUF_INIT;
597 int detached;
599 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
600 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
601 strbuf_release(&buf);
602 if (detached)
603 return 0;
607 if (!len && reflog_len)
608 /* allow "@{...}" to mean the current branch reflog */
609 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
610 else if (reflog_len)
611 refs_found = dwim_log(str, len, sha1, &real_ref);
612 else
613 refs_found = dwim_ref(str, len, sha1, &real_ref);
615 if (!refs_found)
616 return -1;
618 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
619 (refs_found > 1 ||
620 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
621 warning(warn_msg, len, str);
623 if (reflog_len) {
624 int nth, i;
625 unsigned long at_time;
626 unsigned long co_time;
627 int co_tz, co_cnt;
629 /* Is it asking for N-th entry, or approxidate? */
630 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
631 char ch = str[at+2+i];
632 if ('0' <= ch && ch <= '9')
633 nth = nth * 10 + ch - '0';
634 else
635 nth = -1;
637 if (100000000 <= nth) {
638 at_time = nth;
639 nth = -1;
640 } else if (0 <= nth)
641 at_time = 0;
642 else {
643 int errors = 0;
644 char *tmp = xstrndup(str + at + 2, reflog_len);
645 at_time = approxidate_careful(tmp, &errors);
646 free(tmp);
647 if (errors) {
648 free(real_ref);
649 return -1;
652 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
653 &co_time, &co_tz, &co_cnt)) {
654 if (!len) {
655 if (starts_with(real_ref, "refs/heads/")) {
656 str = real_ref + 11;
657 len = strlen(real_ref + 11);
658 } else {
659 /* detached HEAD */
660 str = "HEAD";
661 len = 4;
664 if (at_time) {
665 if (!(flags & GET_SHA1_QUIETLY)) {
666 warning("Log for '%.*s' only goes "
667 "back to %s.", len, str,
668 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
670 } else {
671 if (flags & GET_SHA1_QUIETLY) {
672 exit(128);
674 die("Log for '%.*s' only has %d entries.",
675 len, str, co_cnt);
680 free(real_ref);
681 return 0;
684 static int get_parent(const char *name, int len,
685 unsigned char *result, int idx)
687 unsigned char sha1[20];
688 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
689 struct commit *commit;
690 struct commit_list *p;
692 if (ret)
693 return ret;
694 commit = lookup_commit_reference(sha1);
695 if (parse_commit(commit))
696 return -1;
697 if (!idx) {
698 hashcpy(result, commit->object.oid.hash);
699 return 0;
701 p = commit->parents;
702 while (p) {
703 if (!--idx) {
704 hashcpy(result, p->item->object.oid.hash);
705 return 0;
707 p = p->next;
709 return -1;
712 static int get_nth_ancestor(const char *name, int len,
713 unsigned char *result, int generation)
715 unsigned char sha1[20];
716 struct commit *commit;
717 int ret;
719 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
720 if (ret)
721 return ret;
722 commit = lookup_commit_reference(sha1);
723 if (!commit)
724 return -1;
726 while (generation--) {
727 if (parse_commit(commit) || !commit->parents)
728 return -1;
729 commit = commit->parents->item;
731 hashcpy(result, commit->object.oid.hash);
732 return 0;
735 struct object *peel_to_type(const char *name, int namelen,
736 struct object *o, enum object_type expected_type)
738 if (name && !namelen)
739 namelen = strlen(name);
740 while (1) {
741 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
742 return NULL;
743 if (expected_type == OBJ_ANY || o->type == expected_type)
744 return o;
745 if (o->type == OBJ_TAG)
746 o = ((struct tag*) o)->tagged;
747 else if (o->type == OBJ_COMMIT)
748 o = &(((struct commit *) o)->tree->object);
749 else {
750 if (name)
751 error("%.*s: expected %s type, but the object "
752 "dereferences to %s type",
753 namelen, name, typename(expected_type),
754 typename(o->type));
755 return NULL;
760 static int peel_onion(const char *name, int len, unsigned char *sha1,
761 unsigned lookup_flags)
763 unsigned char outer[20];
764 const char *sp;
765 unsigned int expected_type = 0;
766 struct object *o;
769 * "ref^{type}" dereferences ref repeatedly until you cannot
770 * dereference anymore, or you get an object of given type,
771 * whichever comes first. "ref^{}" means just dereference
772 * tags until you get a non-tag. "ref^0" is a shorthand for
773 * "ref^{commit}". "commit^{tree}" could be used to find the
774 * top-level tree of the given commit.
776 if (len < 4 || name[len-1] != '}')
777 return -1;
779 for (sp = name + len - 1; name <= sp; sp--) {
780 int ch = *sp;
781 if (ch == '{' && name < sp && sp[-1] == '^')
782 break;
784 if (sp <= name)
785 return -1;
787 sp++; /* beginning of type name, or closing brace for empty */
788 if (starts_with(sp, "commit}"))
789 expected_type = OBJ_COMMIT;
790 else if (starts_with(sp, "tag}"))
791 expected_type = OBJ_TAG;
792 else if (starts_with(sp, "tree}"))
793 expected_type = OBJ_TREE;
794 else if (starts_with(sp, "blob}"))
795 expected_type = OBJ_BLOB;
796 else if (starts_with(sp, "object}"))
797 expected_type = OBJ_ANY;
798 else if (sp[0] == '}')
799 expected_type = OBJ_NONE;
800 else if (sp[0] == '/')
801 expected_type = OBJ_COMMIT;
802 else
803 return -1;
805 lookup_flags &= ~GET_SHA1_DISAMBIGUATORS;
806 if (expected_type == OBJ_COMMIT)
807 lookup_flags |= GET_SHA1_COMMITTISH;
808 else if (expected_type == OBJ_TREE)
809 lookup_flags |= GET_SHA1_TREEISH;
811 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
812 return -1;
814 o = parse_object(outer);
815 if (!o)
816 return -1;
817 if (!expected_type) {
818 o = deref_tag(o, name, sp - name - 2);
819 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
820 return -1;
821 hashcpy(sha1, o->oid.hash);
822 return 0;
826 * At this point, the syntax look correct, so
827 * if we do not get the needed object, we should
828 * barf.
830 o = peel_to_type(name, len, o, expected_type);
831 if (!o)
832 return -1;
834 hashcpy(sha1, o->oid.hash);
835 if (sp[0] == '/') {
836 /* "$commit^{/foo}" */
837 char *prefix;
838 int ret;
839 struct commit_list *list = NULL;
842 * $commit^{/}. Some regex implementation may reject.
843 * We don't need regex anyway. '' pattern always matches.
845 if (sp[1] == '}')
846 return 0;
848 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
849 commit_list_insert((struct commit *)o, &list);
850 ret = get_sha1_oneline(prefix, sha1, list);
851 free(prefix);
852 return ret;
854 return 0;
857 static int get_describe_name(const char *name, int len, unsigned char *sha1)
859 const char *cp;
860 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
862 for (cp = name + len - 1; name + 2 <= cp; cp--) {
863 char ch = *cp;
864 if (!isxdigit(ch)) {
865 /* We must be looking at g in "SOMETHING-g"
866 * for it to be describe output.
868 if (ch == 'g' && cp[-1] == '-') {
869 cp++;
870 len -= cp - name;
871 return get_short_sha1(cp, len, sha1, flags);
875 return -1;
878 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
880 int ret, has_suffix;
881 const char *cp;
884 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
886 has_suffix = 0;
887 for (cp = name + len - 1; name <= cp; cp--) {
888 int ch = *cp;
889 if ('0' <= ch && ch <= '9')
890 continue;
891 if (ch == '~' || ch == '^')
892 has_suffix = ch;
893 break;
896 if (has_suffix) {
897 int num = 0;
898 int len1 = cp - name;
899 cp++;
900 while (cp < name + len)
901 num = num * 10 + *cp++ - '0';
902 if (!num && len1 == len - 1)
903 num = 1;
904 if (has_suffix == '^')
905 return get_parent(name, len1, sha1, num);
906 /* else if (has_suffix == '~') -- goes without saying */
907 return get_nth_ancestor(name, len1, sha1, num);
910 ret = peel_onion(name, len, sha1, lookup_flags);
911 if (!ret)
912 return 0;
914 ret = get_sha1_basic(name, len, sha1, lookup_flags);
915 if (!ret)
916 return 0;
918 /* It could be describe output that is "SOMETHING-gXXXX" */
919 ret = get_describe_name(name, len, sha1);
920 if (!ret)
921 return 0;
923 return get_short_sha1(name, len, sha1, lookup_flags);
927 * This interprets names like ':/Initial revision of "git"' by searching
928 * through history and returning the first commit whose message starts
929 * the given regular expression.
931 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
933 * For a literal '!' character at the beginning of a pattern, you have to repeat
934 * that, like: ':/!!foo'
936 * For future extension, all other sequences beginning with ':/!' are reserved.
939 /* Remember to update object flag allocation in object.h */
940 #define ONELINE_SEEN (1u<<20)
942 static int handle_one_ref(const char *path, const struct object_id *oid,
943 int flag, void *cb_data)
945 struct commit_list **list = cb_data;
946 struct object *object = parse_object(oid->hash);
947 if (!object)
948 return 0;
949 if (object->type == OBJ_TAG) {
950 object = deref_tag(object, path, strlen(path));
951 if (!object)
952 return 0;
954 if (object->type != OBJ_COMMIT)
955 return 0;
956 commit_list_insert((struct commit *)object, list);
957 return 0;
960 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
961 struct commit_list *list)
963 struct commit_list *backup = NULL, *l;
964 int found = 0;
965 int negative = 0;
966 regex_t regex;
968 if (prefix[0] == '!') {
969 prefix++;
971 if (prefix[0] == '-') {
972 prefix++;
973 negative = 1;
974 } else if (prefix[0] != '!') {
975 return -1;
979 if (regcomp(&regex, prefix, REG_EXTENDED))
980 return -1;
982 for (l = list; l; l = l->next) {
983 l->item->object.flags |= ONELINE_SEEN;
984 commit_list_insert(l->item, &backup);
986 while (list) {
987 const char *p, *buf;
988 struct commit *commit;
989 int matches;
991 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
992 if (!parse_object(commit->object.oid.hash))
993 continue;
994 buf = get_commit_buffer(commit, NULL);
995 p = strstr(buf, "\n\n");
996 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
997 unuse_commit_buffer(commit, buf);
999 if (matches) {
1000 hashcpy(sha1, commit->object.oid.hash);
1001 found = 1;
1002 break;
1005 regfree(&regex);
1006 free_commit_list(list);
1007 for (l = backup; l; l = l->next)
1008 clear_commit_marks(l->item, ONELINE_SEEN);
1009 free_commit_list(backup);
1010 return found ? 0 : -1;
1013 struct grab_nth_branch_switch_cbdata {
1014 int remaining;
1015 struct strbuf buf;
1018 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
1019 const char *email, unsigned long timestamp, int tz,
1020 const char *message, void *cb_data)
1022 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1023 const char *match = NULL, *target = NULL;
1024 size_t len;
1026 if (skip_prefix(message, "checkout: moving from ", &match))
1027 target = strstr(match, " to ");
1029 if (!match || !target)
1030 return 0;
1031 if (--(cb->remaining) == 0) {
1032 len = target - match;
1033 strbuf_reset(&cb->buf);
1034 strbuf_add(&cb->buf, match, len);
1035 return 1; /* we are done */
1037 return 0;
1041 * Parse @{-N} syntax, return the number of characters parsed
1042 * if successful; otherwise signal an error with negative value.
1044 static int interpret_nth_prior_checkout(const char *name, int namelen,
1045 struct strbuf *buf)
1047 long nth;
1048 int retval;
1049 struct grab_nth_branch_switch_cbdata cb;
1050 const char *brace;
1051 char *num_end;
1053 if (namelen < 4)
1054 return -1;
1055 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1056 return -1;
1057 brace = memchr(name, '}', namelen);
1058 if (!brace)
1059 return -1;
1060 nth = strtol(name + 3, &num_end, 10);
1061 if (num_end != brace)
1062 return -1;
1063 if (nth <= 0)
1064 return -1;
1065 cb.remaining = nth;
1066 strbuf_init(&cb.buf, 20);
1068 retval = 0;
1069 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
1070 strbuf_reset(buf);
1071 strbuf_addbuf(buf, &cb.buf);
1072 retval = brace - name + 1;
1075 strbuf_release(&cb.buf);
1076 return retval;
1079 int get_oid_mb(const char *name, struct object_id *oid)
1081 struct commit *one, *two;
1082 struct commit_list *mbs;
1083 struct object_id oid_tmp;
1084 const char *dots;
1085 int st;
1087 dots = strstr(name, "...");
1088 if (!dots)
1089 return get_oid(name, oid);
1090 if (dots == name)
1091 st = get_oid("HEAD", &oid_tmp);
1092 else {
1093 struct strbuf sb;
1094 strbuf_init(&sb, dots - name);
1095 strbuf_add(&sb, name, dots - name);
1096 st = get_sha1_committish(sb.buf, oid_tmp.hash);
1097 strbuf_release(&sb);
1099 if (st)
1100 return st;
1101 one = lookup_commit_reference_gently(oid_tmp.hash, 0);
1102 if (!one)
1103 return -1;
1105 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", oid_tmp.hash))
1106 return -1;
1107 two = lookup_commit_reference_gently(oid_tmp.hash, 0);
1108 if (!two)
1109 return -1;
1110 mbs = get_merge_bases(one, two);
1111 if (!mbs || mbs->next)
1112 st = -1;
1113 else {
1114 st = 0;
1115 oidcpy(oid, &mbs->item->object.oid);
1117 free_commit_list(mbs);
1118 return st;
1121 /* parse @something syntax, when 'something' is not {.*} */
1122 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1124 const char *next;
1126 if (len || name[1] == '{')
1127 return -1;
1129 /* make sure it's a single @, or @@{.*}, not @foo */
1130 next = memchr(name + len + 1, '@', namelen - len - 1);
1131 if (next && next[1] != '{')
1132 return -1;
1133 if (!next)
1134 next = name + namelen;
1135 if (next != name + 1)
1136 return -1;
1138 strbuf_reset(buf);
1139 strbuf_add(buf, "HEAD", 4);
1140 return 1;
1143 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1145 /* we have extra data, which might need further processing */
1146 struct strbuf tmp = STRBUF_INIT;
1147 int used = buf->len;
1148 int ret;
1150 strbuf_add(buf, name + len, namelen - len);
1151 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1152 /* that data was not interpreted, remove our cruft */
1153 if (ret < 0) {
1154 strbuf_setlen(buf, used);
1155 return len;
1157 strbuf_reset(buf);
1158 strbuf_addbuf(buf, &tmp);
1159 strbuf_release(&tmp);
1160 /* tweak for size of {-N} versus expanded ref name */
1161 return ret - used + len;
1164 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1166 char *s = shorten_unambiguous_ref(ref, 0);
1167 strbuf_reset(buf);
1168 strbuf_addstr(buf, s);
1169 free(s);
1172 static int interpret_branch_mark(const char *name, int namelen,
1173 int at, struct strbuf *buf,
1174 int (*get_mark)(const char *, int),
1175 const char *(*get_data)(struct branch *,
1176 struct strbuf *))
1178 int len;
1179 struct branch *branch;
1180 struct strbuf err = STRBUF_INIT;
1181 const char *value;
1183 len = get_mark(name + at, namelen - at);
1184 if (!len)
1185 return -1;
1187 if (memchr(name, ':', at))
1188 return -1;
1190 if (at) {
1191 char *name_str = xmemdupz(name, at);
1192 branch = branch_get(name_str);
1193 free(name_str);
1194 } else
1195 branch = branch_get(NULL);
1197 value = get_data(branch, &err);
1198 if (!value)
1199 die("%s", err.buf);
1201 set_shortened_ref(buf, value);
1202 return len + at;
1206 * This reads short-hand syntax that not only evaluates to a commit
1207 * object name, but also can act as if the end user spelled the name
1208 * of the branch from the command line.
1210 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1211 * places the name of the branch in the given buf and returns the
1212 * number of characters parsed if successful.
1214 * - "<branch>@{upstream}" finds the name of the other ref that
1215 * <branch> is configured to merge with (missing <branch> defaults
1216 * to the current branch), and places the name of the branch in the
1217 * given buf and returns the number of characters parsed if
1218 * successful.
1220 * If the input is not of the accepted format, it returns a negative
1221 * number to signal an error.
1223 * If the input was ok but there are not N branch switches in the
1224 * reflog, it returns 0.
1226 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1228 char *at;
1229 const char *start;
1230 int len = interpret_nth_prior_checkout(name, namelen, buf);
1232 if (!namelen)
1233 namelen = strlen(name);
1235 if (!len) {
1236 return len; /* syntax Ok, not enough switches */
1237 } else if (len > 0) {
1238 if (len == namelen)
1239 return len; /* consumed all */
1240 else
1241 return reinterpret(name, namelen, len, buf);
1244 for (start = name;
1245 (at = memchr(start, '@', namelen - (start - name)));
1246 start = at + 1) {
1248 len = interpret_empty_at(name, namelen, at - name, buf);
1249 if (len > 0)
1250 return reinterpret(name, namelen, len, buf);
1252 len = interpret_branch_mark(name, namelen, at - name, buf,
1253 upstream_mark, branch_get_upstream);
1254 if (len > 0)
1255 return len;
1257 len = interpret_branch_mark(name, namelen, at - name, buf,
1258 push_mark, branch_get_push);
1259 if (len > 0)
1260 return len;
1263 return -1;
1266 int strbuf_branchname(struct strbuf *sb, const char *name)
1268 int len = strlen(name);
1269 int used = interpret_branch_name(name, len, sb);
1271 if (used == len)
1272 return 0;
1273 if (used < 0)
1274 used = 0;
1275 strbuf_add(sb, name + used, len - used);
1276 return len;
1279 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1281 strbuf_branchname(sb, name);
1282 if (name[0] == '-')
1283 return -1;
1284 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1285 return check_refname_format(sb->buf, 0);
1289 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1290 * notably "xyz^" for "parent of xyz"
1292 int get_sha1(const char *name, unsigned char *sha1)
1294 struct object_context unused;
1295 return get_sha1_with_context(name, 0, sha1, &unused);
1299 * This is like "get_sha1()", but for struct object_id.
1301 int get_oid(const char *name, struct object_id *oid)
1303 return get_sha1(name, oid->hash);
1308 * Many callers know that the user meant to name a commit-ish by
1309 * syntactical positions where the object name appears. Calling this
1310 * function allows the machinery to disambiguate shorter-than-unique
1311 * abbreviated object names between commit-ish and others.
1313 * Note that this does NOT error out when the named object is not a
1314 * commit-ish. It is merely to give a hint to the disambiguation
1315 * machinery.
1317 int get_sha1_committish(const char *name, unsigned char *sha1)
1319 struct object_context unused;
1320 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1321 sha1, &unused);
1324 int get_sha1_treeish(const char *name, unsigned char *sha1)
1326 struct object_context unused;
1327 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1328 sha1, &unused);
1331 int get_sha1_commit(const char *name, unsigned char *sha1)
1333 struct object_context unused;
1334 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1335 sha1, &unused);
1338 int get_sha1_tree(const char *name, unsigned char *sha1)
1340 struct object_context unused;
1341 return get_sha1_with_context(name, GET_SHA1_TREE,
1342 sha1, &unused);
1345 int get_sha1_blob(const char *name, unsigned char *sha1)
1347 struct object_context unused;
1348 return get_sha1_with_context(name, GET_SHA1_BLOB,
1349 sha1, &unused);
1352 /* Must be called only when object_name:filename doesn't exist. */
1353 static void diagnose_invalid_sha1_path(const char *prefix,
1354 const char *filename,
1355 const unsigned char *tree_sha1,
1356 const char *object_name,
1357 int object_name_len)
1359 unsigned char sha1[20];
1360 unsigned mode;
1362 if (!prefix)
1363 prefix = "";
1365 if (file_exists(filename))
1366 die("Path '%s' exists on disk, but not in '%.*s'.",
1367 filename, object_name_len, object_name);
1368 if (errno == ENOENT || errno == ENOTDIR) {
1369 char *fullname = xstrfmt("%s%s", prefix, filename);
1371 if (!get_tree_entry(tree_sha1, fullname,
1372 sha1, &mode)) {
1373 die("Path '%s' exists, but not '%s'.\n"
1374 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1375 fullname,
1376 filename,
1377 object_name_len, object_name,
1378 fullname,
1379 object_name_len, object_name,
1380 filename);
1382 die("Path '%s' does not exist in '%.*s'",
1383 filename, object_name_len, object_name);
1387 /* Must be called only when :stage:filename doesn't exist. */
1388 static void diagnose_invalid_index_path(int stage,
1389 const char *prefix,
1390 const char *filename)
1392 const struct cache_entry *ce;
1393 int pos;
1394 unsigned namelen = strlen(filename);
1395 struct strbuf fullname = STRBUF_INIT;
1397 if (!prefix)
1398 prefix = "";
1400 /* Wrong stage number? */
1401 pos = cache_name_pos(filename, namelen);
1402 if (pos < 0)
1403 pos = -pos - 1;
1404 if (pos < active_nr) {
1405 ce = active_cache[pos];
1406 if (ce_namelen(ce) == namelen &&
1407 !memcmp(ce->name, filename, namelen))
1408 die("Path '%s' is in the index, but not at stage %d.\n"
1409 "Did you mean ':%d:%s'?",
1410 filename, stage,
1411 ce_stage(ce), filename);
1414 /* Confusion between relative and absolute filenames? */
1415 strbuf_addstr(&fullname, prefix);
1416 strbuf_addstr(&fullname, filename);
1417 pos = cache_name_pos(fullname.buf, fullname.len);
1418 if (pos < 0)
1419 pos = -pos - 1;
1420 if (pos < active_nr) {
1421 ce = active_cache[pos];
1422 if (ce_namelen(ce) == fullname.len &&
1423 !memcmp(ce->name, fullname.buf, fullname.len))
1424 die("Path '%s' is in the index, but not '%s'.\n"
1425 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1426 fullname.buf, filename,
1427 ce_stage(ce), fullname.buf,
1428 ce_stage(ce), filename);
1431 if (file_exists(filename))
1432 die("Path '%s' exists on disk, but not in the index.", filename);
1433 if (errno == ENOENT || errno == ENOTDIR)
1434 die("Path '%s' does not exist (neither on disk nor in the index).",
1435 filename);
1437 strbuf_release(&fullname);
1441 static char *resolve_relative_path(const char *rel)
1443 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1444 return NULL;
1446 if (!is_inside_work_tree())
1447 die("relative path syntax can't be used outside working tree.");
1449 /* die() inside prefix_path() if resolved path is outside worktree */
1450 return prefix_path(startup_info->prefix,
1451 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1452 rel);
1455 static int get_sha1_with_context_1(const char *name,
1456 unsigned flags,
1457 const char *prefix,
1458 unsigned char *sha1,
1459 struct object_context *oc)
1461 int ret, bracket_depth;
1462 int namelen = strlen(name);
1463 const char *cp;
1464 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1466 if (only_to_die)
1467 flags |= GET_SHA1_QUIETLY;
1469 memset(oc, 0, sizeof(*oc));
1470 oc->mode = S_IFINVALID;
1471 ret = get_sha1_1(name, namelen, sha1, flags);
1472 if (!ret)
1473 return ret;
1475 * sha1:path --> object name of path in ent sha1
1476 * :path -> object name of absolute path in index
1477 * :./path -> object name of path relative to cwd in index
1478 * :[0-3]:path -> object name of path in index at stage
1479 * :/foo -> recent commit matching foo
1481 if (name[0] == ':') {
1482 int stage = 0;
1483 const struct cache_entry *ce;
1484 char *new_path = NULL;
1485 int pos;
1486 if (!only_to_die && namelen > 2 && name[1] == '/') {
1487 struct commit_list *list = NULL;
1489 for_each_ref(handle_one_ref, &list);
1490 commit_list_sort_by_date(&list);
1491 return get_sha1_oneline(name + 2, sha1, list);
1493 if (namelen < 3 ||
1494 name[2] != ':' ||
1495 name[1] < '0' || '3' < name[1])
1496 cp = name + 1;
1497 else {
1498 stage = name[1] - '0';
1499 cp = name + 3;
1501 new_path = resolve_relative_path(cp);
1502 if (!new_path) {
1503 namelen = namelen - (cp - name);
1504 } else {
1505 cp = new_path;
1506 namelen = strlen(cp);
1509 strlcpy(oc->path, cp, sizeof(oc->path));
1511 if (!active_cache)
1512 read_cache();
1513 pos = cache_name_pos(cp, namelen);
1514 if (pos < 0)
1515 pos = -pos - 1;
1516 while (pos < active_nr) {
1517 ce = active_cache[pos];
1518 if (ce_namelen(ce) != namelen ||
1519 memcmp(ce->name, cp, namelen))
1520 break;
1521 if (ce_stage(ce) == stage) {
1522 hashcpy(sha1, ce->oid.hash);
1523 oc->mode = ce->ce_mode;
1524 free(new_path);
1525 return 0;
1527 pos++;
1529 if (only_to_die && name[1] && name[1] != '/')
1530 diagnose_invalid_index_path(stage, prefix, cp);
1531 free(new_path);
1532 return -1;
1534 for (cp = name, bracket_depth = 0; *cp; cp++) {
1535 if (*cp == '{')
1536 bracket_depth++;
1537 else if (bracket_depth && *cp == '}')
1538 bracket_depth--;
1539 else if (!bracket_depth && *cp == ':')
1540 break;
1542 if (*cp == ':') {
1543 unsigned char tree_sha1[20];
1544 int len = cp - name;
1545 unsigned sub_flags = flags;
1547 sub_flags &= ~GET_SHA1_DISAMBIGUATORS;
1548 sub_flags |= GET_SHA1_TREEISH;
1550 if (!get_sha1_1(name, len, tree_sha1, sub_flags)) {
1551 const char *filename = cp+1;
1552 char *new_filename = NULL;
1554 new_filename = resolve_relative_path(filename);
1555 if (new_filename)
1556 filename = new_filename;
1557 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1558 ret = get_tree_entry_follow_symlinks(tree_sha1,
1559 filename, sha1, &oc->symlink_path,
1560 &oc->mode);
1561 } else {
1562 ret = get_tree_entry(tree_sha1, filename,
1563 sha1, &oc->mode);
1564 if (ret && only_to_die) {
1565 diagnose_invalid_sha1_path(prefix,
1566 filename,
1567 tree_sha1,
1568 name, len);
1571 hashcpy(oc->tree, tree_sha1);
1572 strlcpy(oc->path, filename, sizeof(oc->path));
1574 free(new_filename);
1575 return ret;
1576 } else {
1577 if (only_to_die)
1578 die("Invalid object name '%.*s'.", len, name);
1581 return ret;
1585 * Call this function when you know "name" given by the end user must
1586 * name an object but it doesn't; the function _may_ die with a better
1587 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1588 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1589 * you have a chance to diagnose the error further.
1591 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1593 struct object_context oc;
1594 unsigned char sha1[20];
1595 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1598 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1600 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1601 die("BUG: incompatible flags for get_sha1_with_context");
1602 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);