Merge branch 'jk/rev-list-no-bitmap-while-pruning'
[alt-git.git] / sha1_name.c
blobe57513e61032fb851a669255c30d8417f66c81f9
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 sprintf(hex, "%.2s", hex_pfx);
100 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
101 struct dirent *de;
102 DIR *dir;
103 sprintf(alt->name, "%.2s/", hex_pfx);
104 dir = opendir(alt->base);
105 if (!dir)
106 continue;
108 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
109 unsigned char sha1[20];
111 if (strlen(de->d_name) != 38)
112 continue;
113 if (memcmp(de->d_name, hex_pfx + 2, len - 2))
114 continue;
115 memcpy(hex + 2, de->d_name, 38);
116 if (!get_sha1_hex(hex, sha1))
117 update_candidates(ds, sha1);
119 closedir(dir);
123 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
125 do {
126 if (*a != *b)
127 return 0;
128 a++;
129 b++;
130 len -= 2;
131 } while (len > 1);
132 if (len)
133 if ((*a ^ *b) & 0xf0)
134 return 0;
135 return 1;
138 static void unique_in_pack(int len,
139 const unsigned char *bin_pfx,
140 struct packed_git *p,
141 struct disambiguate_state *ds)
143 uint32_t num, last, i, first = 0;
144 const unsigned char *current = NULL;
146 open_pack_index(p);
147 num = p->num_objects;
148 last = num;
149 while (first < last) {
150 uint32_t mid = (first + last) / 2;
151 const unsigned char *current;
152 int cmp;
154 current = nth_packed_object_sha1(p, mid);
155 cmp = hashcmp(bin_pfx, current);
156 if (!cmp) {
157 first = mid;
158 break;
160 if (cmp > 0) {
161 first = mid+1;
162 continue;
164 last = mid;
168 * At this point, "first" is the location of the lowest object
169 * with an object name that could match "bin_pfx". See if we have
170 * 0, 1 or more objects that actually match(es).
172 for (i = first; i < num && !ds->ambiguous; i++) {
173 current = nth_packed_object_sha1(p, i);
174 if (!match_sha(len, bin_pfx, current))
175 break;
176 update_candidates(ds, current);
180 static void find_short_packed_object(int len, const unsigned char *bin_pfx,
181 struct disambiguate_state *ds)
183 struct packed_git *p;
185 prepare_packed_git();
186 for (p = packed_git; p && !ds->ambiguous; p = p->next)
187 unique_in_pack(len, bin_pfx, p, ds);
190 #define SHORT_NAME_NOT_FOUND (-1)
191 #define SHORT_NAME_AMBIGUOUS (-2)
193 static int finish_object_disambiguation(struct disambiguate_state *ds,
194 unsigned char *sha1)
196 if (ds->ambiguous)
197 return SHORT_NAME_AMBIGUOUS;
199 if (!ds->candidate_exists)
200 return SHORT_NAME_NOT_FOUND;
202 if (!ds->candidate_checked)
204 * If this is the only candidate, there is no point
205 * calling the disambiguation hint callback.
207 * On the other hand, if the current candidate
208 * replaced an earlier candidate that did _not_ pass
209 * the disambiguation hint callback, then we do have
210 * more than one objects that match the short name
211 * given, so we should make sure this one matches;
212 * otherwise, if we discovered this one and the one
213 * that we previously discarded in the reverse order,
214 * we would end up showing different results in the
215 * same repository!
217 ds->candidate_ok = (!ds->disambiguate_fn_used ||
218 ds->fn(ds->candidate, ds->cb_data));
220 if (!ds->candidate_ok)
221 return SHORT_NAME_AMBIGUOUS;
223 hashcpy(sha1, ds->candidate);
224 return 0;
227 static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
229 int kind = sha1_object_info(sha1, NULL);
230 return kind == OBJ_COMMIT;
233 static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
235 struct object *obj;
236 int kind;
238 kind = sha1_object_info(sha1, NULL);
239 if (kind == OBJ_COMMIT)
240 return 1;
241 if (kind != OBJ_TAG)
242 return 0;
244 /* We need to do this the hard way... */
245 obj = deref_tag(parse_object(sha1), NULL, 0);
246 if (obj && obj->type == OBJ_COMMIT)
247 return 1;
248 return 0;
251 static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
253 int kind = sha1_object_info(sha1, NULL);
254 return kind == OBJ_TREE;
257 static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
259 struct object *obj;
260 int kind;
262 kind = sha1_object_info(sha1, NULL);
263 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
264 return 1;
265 if (kind != OBJ_TAG)
266 return 0;
268 /* We need to do this the hard way... */
269 obj = deref_tag(lookup_object(sha1), NULL, 0);
270 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
271 return 1;
272 return 0;
275 static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
277 int kind = sha1_object_info(sha1, NULL);
278 return kind == OBJ_BLOB;
281 static int prepare_prefixes(const char *name, int len,
282 unsigned char *bin_pfx,
283 char *hex_pfx)
285 int i;
287 hashclr(bin_pfx);
288 memset(hex_pfx, 'x', 40);
289 for (i = 0; i < len ;i++) {
290 unsigned char c = name[i];
291 unsigned char val;
292 if (c >= '0' && c <= '9')
293 val = c - '0';
294 else if (c >= 'a' && c <= 'f')
295 val = c - 'a' + 10;
296 else if (c >= 'A' && c <='F') {
297 val = c - 'A' + 10;
298 c -= 'A' - 'a';
300 else
301 return -1;
302 hex_pfx[i] = c;
303 if (!(i & 1))
304 val <<= 4;
305 bin_pfx[i >> 1] |= val;
307 return 0;
310 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
311 unsigned flags)
313 int status;
314 char hex_pfx[40];
315 unsigned char bin_pfx[20];
316 struct disambiguate_state ds;
317 int quietly = !!(flags & GET_SHA1_QUIETLY);
319 if (len < MINIMUM_ABBREV || len > 40)
320 return -1;
321 if (prepare_prefixes(name, len, bin_pfx, hex_pfx) < 0)
322 return -1;
324 prepare_alt_odb();
326 memset(&ds, 0, sizeof(ds));
327 if (flags & GET_SHA1_COMMIT)
328 ds.fn = disambiguate_commit_only;
329 else if (flags & GET_SHA1_COMMITTISH)
330 ds.fn = disambiguate_committish_only;
331 else if (flags & GET_SHA1_TREE)
332 ds.fn = disambiguate_tree_only;
333 else if (flags & GET_SHA1_TREEISH)
334 ds.fn = disambiguate_treeish_only;
335 else if (flags & GET_SHA1_BLOB)
336 ds.fn = disambiguate_blob_only;
338 find_short_object_filename(len, hex_pfx, &ds);
339 find_short_packed_object(len, bin_pfx, &ds);
340 status = finish_object_disambiguation(&ds, sha1);
342 if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
343 return error("short SHA1 %.*s is ambiguous.", len, hex_pfx);
344 return status;
347 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
349 char hex_pfx[40];
350 unsigned char bin_pfx[20];
351 struct disambiguate_state ds;
352 int len = strlen(prefix);
354 if (len < MINIMUM_ABBREV || len > 40)
355 return -1;
356 if (prepare_prefixes(prefix, len, bin_pfx, hex_pfx) < 0)
357 return -1;
359 prepare_alt_odb();
361 memset(&ds, 0, sizeof(ds));
362 ds.always_call_fn = 1;
363 ds.cb_data = cb_data;
364 ds.fn = fn;
366 find_short_object_filename(len, hex_pfx, &ds);
367 find_short_packed_object(len, bin_pfx, &ds);
368 return ds.ambiguous;
371 const char *find_unique_abbrev(const unsigned char *sha1, int len)
373 int status, exists;
374 static char hex[41];
376 memcpy(hex, sha1_to_hex(sha1), 40);
377 if (len == 40 || !len)
378 return hex;
379 exists = has_sha1_file(sha1);
380 while (len < 40) {
381 unsigned char sha1_ret[20];
382 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
383 if (exists
384 ? !status
385 : status == SHORT_NAME_NOT_FOUND) {
386 hex[len] = 0;
387 return hex;
389 len++;
391 return hex;
394 static int ambiguous_path(const char *path, int len)
396 int slash = 1;
397 int cnt;
399 for (cnt = 0; cnt < len; cnt++) {
400 switch (*path++) {
401 case '\0':
402 break;
403 case '/':
404 if (slash)
405 break;
406 slash = 1;
407 continue;
408 case '.':
409 continue;
410 default:
411 slash = 0;
412 continue;
414 break;
416 return slash;
419 static inline int at_mark(const char *string, int len,
420 const char **suffix, int nr)
422 int i;
424 for (i = 0; i < nr; i++) {
425 int suffix_len = strlen(suffix[i]);
426 if (suffix_len <= len
427 && !memcmp(string, suffix[i], suffix_len))
428 return suffix_len;
430 return 0;
433 static inline int upstream_mark(const char *string, int len)
435 const char *suffix[] = { "@{upstream}", "@{u}" };
436 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
439 static inline int push_mark(const char *string, int len)
441 const char *suffix[] = { "@{push}" };
442 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
445 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
446 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
448 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
449 unsigned int flags)
451 static const char *warn_msg = "refname '%.*s' is ambiguous.";
452 static const char *object_name_msg = N_(
453 "Git normally never creates a ref that ends with 40 hex characters\n"
454 "because it will be ignored when you just specify 40-hex. These refs\n"
455 "may be created by mistake. For example,\n"
456 "\n"
457 " git checkout -b $br $(git rev-parse ...)\n"
458 "\n"
459 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
460 "examine these refs and maybe delete them. Turn this message off by\n"
461 "running \"git config advice.objectNameWarning false\"");
462 unsigned char tmp_sha1[20];
463 char *real_ref = NULL;
464 int refs_found = 0;
465 int at, reflog_len, nth_prior = 0;
467 if (len == 40 && !get_sha1_hex(str, sha1)) {
468 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
469 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
470 if (refs_found > 0) {
471 warning(warn_msg, len, str);
472 if (advice_object_name_warning)
473 fprintf(stderr, "%s\n", _(object_name_msg));
475 free(real_ref);
477 return 0;
480 /* basic@{time or number or -number} format to query ref-log */
481 reflog_len = at = 0;
482 if (len && str[len-1] == '}') {
483 for (at = len-4; at >= 0; at--) {
484 if (str[at] == '@' && str[at+1] == '{') {
485 if (str[at+2] == '-') {
486 if (at != 0)
487 /* @{-N} not at start */
488 return -1;
489 nth_prior = 1;
490 continue;
492 if (!upstream_mark(str + at, len - at) &&
493 !push_mark(str + at, len - at)) {
494 reflog_len = (len-1) - (at+2);
495 len = at;
497 break;
502 /* Accept only unambiguous ref paths. */
503 if (len && ambiguous_path(str, len))
504 return -1;
506 if (nth_prior) {
507 struct strbuf buf = STRBUF_INIT;
508 int detached;
510 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
511 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
512 strbuf_release(&buf);
513 if (detached)
514 return 0;
518 if (!len && reflog_len)
519 /* allow "@{...}" to mean the current branch reflog */
520 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
521 else if (reflog_len)
522 refs_found = dwim_log(str, len, sha1, &real_ref);
523 else
524 refs_found = dwim_ref(str, len, sha1, &real_ref);
526 if (!refs_found)
527 return -1;
529 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
530 (refs_found > 1 ||
531 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
532 warning(warn_msg, len, str);
534 if (reflog_len) {
535 int nth, i;
536 unsigned long at_time;
537 unsigned long co_time;
538 int co_tz, co_cnt;
540 /* Is it asking for N-th entry, or approxidate? */
541 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
542 char ch = str[at+2+i];
543 if ('0' <= ch && ch <= '9')
544 nth = nth * 10 + ch - '0';
545 else
546 nth = -1;
548 if (100000000 <= nth) {
549 at_time = nth;
550 nth = -1;
551 } else if (0 <= nth)
552 at_time = 0;
553 else {
554 int errors = 0;
555 char *tmp = xstrndup(str + at + 2, reflog_len);
556 at_time = approxidate_careful(tmp, &errors);
557 free(tmp);
558 if (errors) {
559 free(real_ref);
560 return -1;
563 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
564 &co_time, &co_tz, &co_cnt)) {
565 if (!len) {
566 if (starts_with(real_ref, "refs/heads/")) {
567 str = real_ref + 11;
568 len = strlen(real_ref + 11);
569 } else {
570 /* detached HEAD */
571 str = "HEAD";
572 len = 4;
575 if (at_time) {
576 if (!(flags & GET_SHA1_QUIETLY)) {
577 warning("Log for '%.*s' only goes "
578 "back to %s.", len, str,
579 show_date(co_time, co_tz, DATE_RFC2822));
581 } else {
582 if (flags & GET_SHA1_QUIETLY) {
583 exit(128);
585 die("Log for '%.*s' only has %d entries.",
586 len, str, co_cnt);
591 free(real_ref);
592 return 0;
595 static int get_parent(const char *name, int len,
596 unsigned char *result, int idx)
598 unsigned char sha1[20];
599 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
600 struct commit *commit;
601 struct commit_list *p;
603 if (ret)
604 return ret;
605 commit = lookup_commit_reference(sha1);
606 if (parse_commit(commit))
607 return -1;
608 if (!idx) {
609 hashcpy(result, commit->object.sha1);
610 return 0;
612 p = commit->parents;
613 while (p) {
614 if (!--idx) {
615 hashcpy(result, p->item->object.sha1);
616 return 0;
618 p = p->next;
620 return -1;
623 static int get_nth_ancestor(const char *name, int len,
624 unsigned char *result, int generation)
626 unsigned char sha1[20];
627 struct commit *commit;
628 int ret;
630 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
631 if (ret)
632 return ret;
633 commit = lookup_commit_reference(sha1);
634 if (!commit)
635 return -1;
637 while (generation--) {
638 if (parse_commit(commit) || !commit->parents)
639 return -1;
640 commit = commit->parents->item;
642 hashcpy(result, commit->object.sha1);
643 return 0;
646 struct object *peel_to_type(const char *name, int namelen,
647 struct object *o, enum object_type expected_type)
649 if (name && !namelen)
650 namelen = strlen(name);
651 while (1) {
652 if (!o || (!o->parsed && !parse_object(o->sha1)))
653 return NULL;
654 if (expected_type == OBJ_ANY || o->type == expected_type)
655 return o;
656 if (o->type == OBJ_TAG)
657 o = ((struct tag*) o)->tagged;
658 else if (o->type == OBJ_COMMIT)
659 o = &(((struct commit *) o)->tree->object);
660 else {
661 if (name)
662 error("%.*s: expected %s type, but the object "
663 "dereferences to %s type",
664 namelen, name, typename(expected_type),
665 typename(o->type));
666 return NULL;
671 static int peel_onion(const char *name, int len, unsigned char *sha1)
673 unsigned char outer[20];
674 const char *sp;
675 unsigned int expected_type = 0;
676 unsigned lookup_flags = 0;
677 struct object *o;
680 * "ref^{type}" dereferences ref repeatedly until you cannot
681 * dereference anymore, or you get an object of given type,
682 * whichever comes first. "ref^{}" means just dereference
683 * tags until you get a non-tag. "ref^0" is a shorthand for
684 * "ref^{commit}". "commit^{tree}" could be used to find the
685 * top-level tree of the given commit.
687 if (len < 4 || name[len-1] != '}')
688 return -1;
690 for (sp = name + len - 1; name <= sp; sp--) {
691 int ch = *sp;
692 if (ch == '{' && name < sp && sp[-1] == '^')
693 break;
695 if (sp <= name)
696 return -1;
698 sp++; /* beginning of type name, or closing brace for empty */
699 if (starts_with(sp, "commit}"))
700 expected_type = OBJ_COMMIT;
701 else if (starts_with(sp, "tag}"))
702 expected_type = OBJ_TAG;
703 else if (starts_with(sp, "tree}"))
704 expected_type = OBJ_TREE;
705 else if (starts_with(sp, "blob}"))
706 expected_type = OBJ_BLOB;
707 else if (starts_with(sp, "object}"))
708 expected_type = OBJ_ANY;
709 else if (sp[0] == '}')
710 expected_type = OBJ_NONE;
711 else if (sp[0] == '/')
712 expected_type = OBJ_COMMIT;
713 else
714 return -1;
716 if (expected_type == OBJ_COMMIT)
717 lookup_flags = GET_SHA1_COMMITTISH;
718 else if (expected_type == OBJ_TREE)
719 lookup_flags = GET_SHA1_TREEISH;
721 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
722 return -1;
724 o = parse_object(outer);
725 if (!o)
726 return -1;
727 if (!expected_type) {
728 o = deref_tag(o, name, sp - name - 2);
729 if (!o || (!o->parsed && !parse_object(o->sha1)))
730 return -1;
731 hashcpy(sha1, o->sha1);
732 return 0;
736 * At this point, the syntax look correct, so
737 * if we do not get the needed object, we should
738 * barf.
740 o = peel_to_type(name, len, o, expected_type);
741 if (!o)
742 return -1;
744 hashcpy(sha1, o->sha1);
745 if (sp[0] == '/') {
746 /* "$commit^{/foo}" */
747 char *prefix;
748 int ret;
749 struct commit_list *list = NULL;
752 * $commit^{/}. Some regex implementation may reject.
753 * We don't need regex anyway. '' pattern always matches.
755 if (sp[1] == '}')
756 return 0;
758 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
759 commit_list_insert((struct commit *)o, &list);
760 ret = get_sha1_oneline(prefix, sha1, list);
761 free(prefix);
762 return ret;
764 return 0;
767 static int get_describe_name(const char *name, int len, unsigned char *sha1)
769 const char *cp;
770 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
772 for (cp = name + len - 1; name + 2 <= cp; cp--) {
773 char ch = *cp;
774 if (!isxdigit(ch)) {
775 /* We must be looking at g in "SOMETHING-g"
776 * for it to be describe output.
778 if (ch == 'g' && cp[-1] == '-') {
779 cp++;
780 len -= cp - name;
781 return get_short_sha1(cp, len, sha1, flags);
785 return -1;
788 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
790 int ret, has_suffix;
791 const char *cp;
794 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
796 has_suffix = 0;
797 for (cp = name + len - 1; name <= cp; cp--) {
798 int ch = *cp;
799 if ('0' <= ch && ch <= '9')
800 continue;
801 if (ch == '~' || ch == '^')
802 has_suffix = ch;
803 break;
806 if (has_suffix) {
807 int num = 0;
808 int len1 = cp - name;
809 cp++;
810 while (cp < name + len)
811 num = num * 10 + *cp++ - '0';
812 if (!num && len1 == len - 1)
813 num = 1;
814 if (has_suffix == '^')
815 return get_parent(name, len1, sha1, num);
816 /* else if (has_suffix == '~') -- goes without saying */
817 return get_nth_ancestor(name, len1, sha1, num);
820 ret = peel_onion(name, len, sha1);
821 if (!ret)
822 return 0;
824 ret = get_sha1_basic(name, len, sha1, lookup_flags);
825 if (!ret)
826 return 0;
828 /* It could be describe output that is "SOMETHING-gXXXX" */
829 ret = get_describe_name(name, len, sha1);
830 if (!ret)
831 return 0;
833 return get_short_sha1(name, len, sha1, lookup_flags);
837 * This interprets names like ':/Initial revision of "git"' by searching
838 * through history and returning the first commit whose message starts
839 * the given regular expression.
841 * For future extension, ':/!' is reserved. If you want to match a message
842 * beginning with a '!', you have to repeat the exclamation mark.
845 /* Remember to update object flag allocation in object.h */
846 #define ONELINE_SEEN (1u<<20)
848 static int handle_one_ref(const char *path, const struct object_id *oid,
849 int flag, void *cb_data)
851 struct commit_list **list = cb_data;
852 struct object *object = parse_object(oid->hash);
853 if (!object)
854 return 0;
855 if (object->type == OBJ_TAG) {
856 object = deref_tag(object, path, strlen(path));
857 if (!object)
858 return 0;
860 if (object->type != OBJ_COMMIT)
861 return 0;
862 commit_list_insert((struct commit *)object, list);
863 return 0;
866 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
867 struct commit_list *list)
869 struct commit_list *backup = NULL, *l;
870 int found = 0;
871 regex_t regex;
873 if (prefix[0] == '!') {
874 if (prefix[1] != '!')
875 die ("Invalid search pattern: %s", prefix);
876 prefix++;
879 if (regcomp(&regex, prefix, REG_EXTENDED))
880 die("Invalid search pattern: %s", prefix);
882 for (l = list; l; l = l->next) {
883 l->item->object.flags |= ONELINE_SEEN;
884 commit_list_insert(l->item, &backup);
886 while (list) {
887 const char *p, *buf;
888 struct commit *commit;
889 int matches;
891 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
892 if (!parse_object(commit->object.sha1))
893 continue;
894 buf = get_commit_buffer(commit, NULL);
895 p = strstr(buf, "\n\n");
896 matches = p && !regexec(&regex, p + 2, 0, NULL, 0);
897 unuse_commit_buffer(commit, buf);
899 if (matches) {
900 hashcpy(sha1, commit->object.sha1);
901 found = 1;
902 break;
905 regfree(&regex);
906 free_commit_list(list);
907 for (l = backup; l; l = l->next)
908 clear_commit_marks(l->item, ONELINE_SEEN);
909 free_commit_list(backup);
910 return found ? 0 : -1;
913 struct grab_nth_branch_switch_cbdata {
914 int remaining;
915 struct strbuf buf;
918 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
919 const char *email, unsigned long timestamp, int tz,
920 const char *message, void *cb_data)
922 struct grab_nth_branch_switch_cbdata *cb = cb_data;
923 const char *match = NULL, *target = NULL;
924 size_t len;
926 if (skip_prefix(message, "checkout: moving from ", &match))
927 target = strstr(match, " to ");
929 if (!match || !target)
930 return 0;
931 if (--(cb->remaining) == 0) {
932 len = target - match;
933 strbuf_reset(&cb->buf);
934 strbuf_add(&cb->buf, match, len);
935 return 1; /* we are done */
937 return 0;
941 * Parse @{-N} syntax, return the number of characters parsed
942 * if successful; otherwise signal an error with negative value.
944 static int interpret_nth_prior_checkout(const char *name, int namelen,
945 struct strbuf *buf)
947 long nth;
948 int retval;
949 struct grab_nth_branch_switch_cbdata cb;
950 const char *brace;
951 char *num_end;
953 if (namelen < 4)
954 return -1;
955 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
956 return -1;
957 brace = memchr(name, '}', namelen);
958 if (!brace)
959 return -1;
960 nth = strtol(name + 3, &num_end, 10);
961 if (num_end != brace)
962 return -1;
963 if (nth <= 0)
964 return -1;
965 cb.remaining = nth;
966 strbuf_init(&cb.buf, 20);
968 retval = 0;
969 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
970 strbuf_reset(buf);
971 strbuf_addbuf(buf, &cb.buf);
972 retval = brace - name + 1;
975 strbuf_release(&cb.buf);
976 return retval;
979 int get_sha1_mb(const char *name, unsigned char *sha1)
981 struct commit *one, *two;
982 struct commit_list *mbs;
983 unsigned char sha1_tmp[20];
984 const char *dots;
985 int st;
987 dots = strstr(name, "...");
988 if (!dots)
989 return get_sha1(name, sha1);
990 if (dots == name)
991 st = get_sha1("HEAD", sha1_tmp);
992 else {
993 struct strbuf sb;
994 strbuf_init(&sb, dots - name);
995 strbuf_add(&sb, name, dots - name);
996 st = get_sha1_committish(sb.buf, sha1_tmp);
997 strbuf_release(&sb);
999 if (st)
1000 return st;
1001 one = lookup_commit_reference_gently(sha1_tmp, 0);
1002 if (!one)
1003 return -1;
1005 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
1006 return -1;
1007 two = lookup_commit_reference_gently(sha1_tmp, 0);
1008 if (!two)
1009 return -1;
1010 mbs = get_merge_bases(one, two);
1011 if (!mbs || mbs->next)
1012 st = -1;
1013 else {
1014 st = 0;
1015 hashcpy(sha1, mbs->item->object.sha1);
1017 free_commit_list(mbs);
1018 return st;
1021 /* parse @something syntax, when 'something' is not {.*} */
1022 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1024 const char *next;
1026 if (len || name[1] == '{')
1027 return -1;
1029 /* make sure it's a single @, or @@{.*}, not @foo */
1030 next = memchr(name + len + 1, '@', namelen - len - 1);
1031 if (next && next[1] != '{')
1032 return -1;
1033 if (!next)
1034 next = name + namelen;
1035 if (next != name + 1)
1036 return -1;
1038 strbuf_reset(buf);
1039 strbuf_add(buf, "HEAD", 4);
1040 return 1;
1043 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1045 /* we have extra data, which might need further processing */
1046 struct strbuf tmp = STRBUF_INIT;
1047 int used = buf->len;
1048 int ret;
1050 strbuf_add(buf, name + len, namelen - len);
1051 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1052 /* that data was not interpreted, remove our cruft */
1053 if (ret < 0) {
1054 strbuf_setlen(buf, used);
1055 return len;
1057 strbuf_reset(buf);
1058 strbuf_addbuf(buf, &tmp);
1059 strbuf_release(&tmp);
1060 /* tweak for size of {-N} versus expanded ref name */
1061 return ret - used + len;
1064 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1066 char *s = shorten_unambiguous_ref(ref, 0);
1067 strbuf_reset(buf);
1068 strbuf_addstr(buf, s);
1069 free(s);
1072 static int interpret_branch_mark(const char *name, int namelen,
1073 int at, struct strbuf *buf,
1074 int (*get_mark)(const char *, int),
1075 const char *(*get_data)(struct branch *,
1076 struct strbuf *))
1078 int len;
1079 struct branch *branch;
1080 struct strbuf err = STRBUF_INIT;
1081 const char *value;
1083 len = get_mark(name + at, namelen - at);
1084 if (!len)
1085 return -1;
1087 if (memchr(name, ':', at))
1088 return -1;
1090 if (at) {
1091 char *name_str = xmemdupz(name, at);
1092 branch = branch_get(name_str);
1093 free(name_str);
1094 } else
1095 branch = branch_get(NULL);
1097 value = get_data(branch, &err);
1098 if (!value)
1099 die("%s", err.buf);
1101 set_shortened_ref(buf, value);
1102 return len + at;
1106 * This reads short-hand syntax that not only evaluates to a commit
1107 * object name, but also can act as if the end user spelled the name
1108 * of the branch from the command line.
1110 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1111 * places the name of the branch in the given buf and returns the
1112 * number of characters parsed if successful.
1114 * - "<branch>@{upstream}" finds the name of the other ref that
1115 * <branch> is configured to merge with (missing <branch> defaults
1116 * to the current branch), and places the name of the branch in the
1117 * given buf and returns the number of characters parsed if
1118 * successful.
1120 * If the input is not of the accepted format, it returns a negative
1121 * number to signal an error.
1123 * If the input was ok but there are not N branch switches in the
1124 * reflog, it returns 0.
1126 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1128 char *at;
1129 const char *start;
1130 int len = interpret_nth_prior_checkout(name, namelen, buf);
1132 if (!namelen)
1133 namelen = strlen(name);
1135 if (!len) {
1136 return len; /* syntax Ok, not enough switches */
1137 } else if (len > 0) {
1138 if (len == namelen)
1139 return len; /* consumed all */
1140 else
1141 return reinterpret(name, namelen, len, buf);
1144 for (start = name;
1145 (at = memchr(start, '@', namelen - (start - name)));
1146 start = at + 1) {
1148 len = interpret_empty_at(name, namelen, at - name, buf);
1149 if (len > 0)
1150 return reinterpret(name, namelen, len, buf);
1152 len = interpret_branch_mark(name, namelen, at - name, buf,
1153 upstream_mark, branch_get_upstream);
1154 if (len > 0)
1155 return len;
1157 len = interpret_branch_mark(name, namelen, at - name, buf,
1158 push_mark, branch_get_push);
1159 if (len > 0)
1160 return len;
1163 return -1;
1166 int strbuf_branchname(struct strbuf *sb, const char *name)
1168 int len = strlen(name);
1169 int used = interpret_branch_name(name, len, sb);
1171 if (used == len)
1172 return 0;
1173 if (used < 0)
1174 used = 0;
1175 strbuf_add(sb, name + used, len - used);
1176 return len;
1179 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1181 strbuf_branchname(sb, name);
1182 if (name[0] == '-')
1183 return -1;
1184 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1185 return check_refname_format(sb->buf, 0);
1189 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1190 * notably "xyz^" for "parent of xyz"
1192 int get_sha1(const char *name, unsigned char *sha1)
1194 struct object_context unused;
1195 return get_sha1_with_context(name, 0, sha1, &unused);
1199 * Many callers know that the user meant to name a commit-ish by
1200 * syntactical positions where the object name appears. Calling this
1201 * function allows the machinery to disambiguate shorter-than-unique
1202 * abbreviated object names between commit-ish and others.
1204 * Note that this does NOT error out when the named object is not a
1205 * commit-ish. It is merely to give a hint to the disambiguation
1206 * machinery.
1208 int get_sha1_committish(const char *name, unsigned char *sha1)
1210 struct object_context unused;
1211 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1212 sha1, &unused);
1215 int get_sha1_treeish(const char *name, unsigned char *sha1)
1217 struct object_context unused;
1218 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1219 sha1, &unused);
1222 int get_sha1_commit(const char *name, unsigned char *sha1)
1224 struct object_context unused;
1225 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1226 sha1, &unused);
1229 int get_sha1_tree(const char *name, unsigned char *sha1)
1231 struct object_context unused;
1232 return get_sha1_with_context(name, GET_SHA1_TREE,
1233 sha1, &unused);
1236 int get_sha1_blob(const char *name, unsigned char *sha1)
1238 struct object_context unused;
1239 return get_sha1_with_context(name, GET_SHA1_BLOB,
1240 sha1, &unused);
1243 /* Must be called only when object_name:filename doesn't exist. */
1244 static void diagnose_invalid_sha1_path(const char *prefix,
1245 const char *filename,
1246 const unsigned char *tree_sha1,
1247 const char *object_name,
1248 int object_name_len)
1250 unsigned char sha1[20];
1251 unsigned mode;
1253 if (!prefix)
1254 prefix = "";
1256 if (file_exists(filename))
1257 die("Path '%s' exists on disk, but not in '%.*s'.",
1258 filename, object_name_len, object_name);
1259 if (errno == ENOENT || errno == ENOTDIR) {
1260 char *fullname = xstrfmt("%s%s", prefix, filename);
1262 if (!get_tree_entry(tree_sha1, fullname,
1263 sha1, &mode)) {
1264 die("Path '%s' exists, but not '%s'.\n"
1265 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1266 fullname,
1267 filename,
1268 object_name_len, object_name,
1269 fullname,
1270 object_name_len, object_name,
1271 filename);
1273 die("Path '%s' does not exist in '%.*s'",
1274 filename, object_name_len, object_name);
1278 /* Must be called only when :stage:filename doesn't exist. */
1279 static void diagnose_invalid_index_path(int stage,
1280 const char *prefix,
1281 const char *filename)
1283 const struct cache_entry *ce;
1284 int pos;
1285 unsigned namelen = strlen(filename);
1286 unsigned fullnamelen;
1287 char *fullname;
1289 if (!prefix)
1290 prefix = "";
1292 /* Wrong stage number? */
1293 pos = cache_name_pos(filename, namelen);
1294 if (pos < 0)
1295 pos = -pos - 1;
1296 if (pos < active_nr) {
1297 ce = active_cache[pos];
1298 if (ce_namelen(ce) == namelen &&
1299 !memcmp(ce->name, filename, namelen))
1300 die("Path '%s' is in the index, but not at stage %d.\n"
1301 "Did you mean ':%d:%s'?",
1302 filename, stage,
1303 ce_stage(ce), filename);
1306 /* Confusion between relative and absolute filenames? */
1307 fullnamelen = namelen + strlen(prefix);
1308 fullname = xmalloc(fullnamelen + 1);
1309 strcpy(fullname, prefix);
1310 strcat(fullname, filename);
1311 pos = cache_name_pos(fullname, fullnamelen);
1312 if (pos < 0)
1313 pos = -pos - 1;
1314 if (pos < active_nr) {
1315 ce = active_cache[pos];
1316 if (ce_namelen(ce) == fullnamelen &&
1317 !memcmp(ce->name, fullname, fullnamelen))
1318 die("Path '%s' is in the index, but not '%s'.\n"
1319 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1320 fullname, filename,
1321 ce_stage(ce), fullname,
1322 ce_stage(ce), filename);
1325 if (file_exists(filename))
1326 die("Path '%s' exists on disk, but not in the index.", filename);
1327 if (errno == ENOENT || errno == ENOTDIR)
1328 die("Path '%s' does not exist (neither on disk nor in the index).",
1329 filename);
1331 free(fullname);
1335 static char *resolve_relative_path(const char *rel)
1337 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1338 return NULL;
1340 if (!startup_info)
1341 die("BUG: startup_info struct is not initialized.");
1343 if (!is_inside_work_tree())
1344 die("relative path syntax can't be used outside working tree.");
1346 /* die() inside prefix_path() if resolved path is outside worktree */
1347 return prefix_path(startup_info->prefix,
1348 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1349 rel);
1352 static int get_sha1_with_context_1(const char *name,
1353 unsigned flags,
1354 const char *prefix,
1355 unsigned char *sha1,
1356 struct object_context *oc)
1358 int ret, bracket_depth;
1359 int namelen = strlen(name);
1360 const char *cp;
1361 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1363 memset(oc, 0, sizeof(*oc));
1364 oc->mode = S_IFINVALID;
1365 ret = get_sha1_1(name, namelen, sha1, flags);
1366 if (!ret)
1367 return ret;
1369 * sha1:path --> object name of path in ent sha1
1370 * :path -> object name of absolute path in index
1371 * :./path -> object name of path relative to cwd in index
1372 * :[0-3]:path -> object name of path in index at stage
1373 * :/foo -> recent commit matching foo
1375 if (name[0] == ':') {
1376 int stage = 0;
1377 const struct cache_entry *ce;
1378 char *new_path = NULL;
1379 int pos;
1380 if (!only_to_die && namelen > 2 && name[1] == '/') {
1381 struct commit_list *list = NULL;
1383 for_each_ref(handle_one_ref, &list);
1384 commit_list_sort_by_date(&list);
1385 return get_sha1_oneline(name + 2, sha1, list);
1387 if (namelen < 3 ||
1388 name[2] != ':' ||
1389 name[1] < '0' || '3' < name[1])
1390 cp = name + 1;
1391 else {
1392 stage = name[1] - '0';
1393 cp = name + 3;
1395 new_path = resolve_relative_path(cp);
1396 if (!new_path) {
1397 namelen = namelen - (cp - name);
1398 } else {
1399 cp = new_path;
1400 namelen = strlen(cp);
1403 strlcpy(oc->path, cp, sizeof(oc->path));
1405 if (!active_cache)
1406 read_cache();
1407 pos = cache_name_pos(cp, namelen);
1408 if (pos < 0)
1409 pos = -pos - 1;
1410 while (pos < active_nr) {
1411 ce = active_cache[pos];
1412 if (ce_namelen(ce) != namelen ||
1413 memcmp(ce->name, cp, namelen))
1414 break;
1415 if (ce_stage(ce) == stage) {
1416 hashcpy(sha1, ce->sha1);
1417 oc->mode = ce->ce_mode;
1418 free(new_path);
1419 return 0;
1421 pos++;
1423 if (only_to_die && name[1] && name[1] != '/')
1424 diagnose_invalid_index_path(stage, prefix, cp);
1425 free(new_path);
1426 return -1;
1428 for (cp = name, bracket_depth = 0; *cp; cp++) {
1429 if (*cp == '{')
1430 bracket_depth++;
1431 else if (bracket_depth && *cp == '}')
1432 bracket_depth--;
1433 else if (!bracket_depth && *cp == ':')
1434 break;
1436 if (*cp == ':') {
1437 unsigned char tree_sha1[20];
1438 int len = cp - name;
1439 if (!get_sha1_1(name, len, tree_sha1, GET_SHA1_TREEISH)) {
1440 const char *filename = cp+1;
1441 char *new_filename = NULL;
1443 new_filename = resolve_relative_path(filename);
1444 if (new_filename)
1445 filename = new_filename;
1446 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1447 ret = get_tree_entry_follow_symlinks(tree_sha1,
1448 filename, sha1, &oc->symlink_path,
1449 &oc->mode);
1450 } else {
1451 ret = get_tree_entry(tree_sha1, filename,
1452 sha1, &oc->mode);
1453 if (ret && only_to_die) {
1454 diagnose_invalid_sha1_path(prefix,
1455 filename,
1456 tree_sha1,
1457 name, len);
1460 hashcpy(oc->tree, tree_sha1);
1461 strlcpy(oc->path, filename, sizeof(oc->path));
1463 free(new_filename);
1464 return ret;
1465 } else {
1466 if (only_to_die)
1467 die("Invalid object name '%.*s'.", len, name);
1470 return ret;
1474 * Call this function when you know "name" given by the end user must
1475 * name an object but it doesn't; the function _may_ die with a better
1476 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1477 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1478 * you have a chance to diagnose the error further.
1480 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1482 struct object_context oc;
1483 unsigned char sha1[20];
1484 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1487 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1489 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1490 die("BUG: incompatible flags for get_sha1_with_context");
1491 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);