fill_sha1_file: write "boring" characters
[git.git] / sha1_name.c
blob770ea4fe805969b68fdbc65fed769cc5202440ff
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 fakeent = alloc_alt_odb(get_object_directory());
91 fakeent->next = alt_odb_list;
93 xsnprintf(hex, sizeof(hex), "%.2s", hex_pfx);
94 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
95 struct dirent *de;
96 DIR *dir;
99 * every alt_odb struct has 42 extra bytes after the base
100 * for exactly this purpose
102 xsnprintf(alt->name, 42, "%.2s/", hex_pfx);
103 dir = opendir(alt->scratch);
104 if (!dir)
105 continue;
107 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
108 unsigned char sha1[20];
110 if (strlen(de->d_name) != 38)
111 continue;
112 if (memcmp(de->d_name, hex_pfx + 2, len - 2))
113 continue;
114 memcpy(hex + 2, de->d_name, 38);
115 if (!get_sha1_hex(hex, sha1))
116 update_candidates(ds, sha1);
118 closedir(dir);
122 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
124 do {
125 if (*a != *b)
126 return 0;
127 a++;
128 b++;
129 len -= 2;
130 } while (len > 1);
131 if (len)
132 if ((*a ^ *b) & 0xf0)
133 return 0;
134 return 1;
137 static void unique_in_pack(int len,
138 const unsigned char *bin_pfx,
139 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(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(len, bin_pfx, current))
174 break;
175 update_candidates(ds, current);
179 static void find_short_packed_object(int len, const unsigned char *bin_pfx,
180 struct disambiguate_state *ds)
182 struct packed_git *p;
184 prepare_packed_git();
185 for (p = packed_git; p && !ds->ambiguous; p = p->next)
186 unique_in_pack(len, bin_pfx, p, ds);
189 #define SHORT_NAME_NOT_FOUND (-1)
190 #define SHORT_NAME_AMBIGUOUS (-2)
192 static int finish_object_disambiguation(struct disambiguate_state *ds,
193 unsigned char *sha1)
195 if (ds->ambiguous)
196 return SHORT_NAME_AMBIGUOUS;
198 if (!ds->candidate_exists)
199 return SHORT_NAME_NOT_FOUND;
201 if (!ds->candidate_checked)
203 * If this is the only candidate, there is no point
204 * calling the disambiguation hint callback.
206 * On the other hand, if the current candidate
207 * replaced an earlier candidate that did _not_ pass
208 * the disambiguation hint callback, then we do have
209 * more than one objects that match the short name
210 * given, so we should make sure this one matches;
211 * otherwise, if we discovered this one and the one
212 * that we previously discarded in the reverse order,
213 * we would end up showing different results in the
214 * same repository!
216 ds->candidate_ok = (!ds->disambiguate_fn_used ||
217 ds->fn(ds->candidate, ds->cb_data));
219 if (!ds->candidate_ok)
220 return SHORT_NAME_AMBIGUOUS;
222 hashcpy(sha1, ds->candidate);
223 return 0;
226 static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
228 int kind = sha1_object_info(sha1, NULL);
229 return kind == OBJ_COMMIT;
232 static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
234 struct object *obj;
235 int kind;
237 kind = sha1_object_info(sha1, NULL);
238 if (kind == OBJ_COMMIT)
239 return 1;
240 if (kind != OBJ_TAG)
241 return 0;
243 /* We need to do this the hard way... */
244 obj = deref_tag(parse_object(sha1), NULL, 0);
245 if (obj && obj->type == OBJ_COMMIT)
246 return 1;
247 return 0;
250 static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
252 int kind = sha1_object_info(sha1, NULL);
253 return kind == OBJ_TREE;
256 static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
258 struct object *obj;
259 int kind;
261 kind = sha1_object_info(sha1, NULL);
262 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
263 return 1;
264 if (kind != OBJ_TAG)
265 return 0;
267 /* We need to do this the hard way... */
268 obj = deref_tag(lookup_object(sha1), NULL, 0);
269 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
270 return 1;
271 return 0;
274 static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
276 int kind = sha1_object_info(sha1, NULL);
277 return kind == OBJ_BLOB;
280 static int prepare_prefixes(const char *name, int len,
281 unsigned char *bin_pfx,
282 char *hex_pfx)
284 int i;
286 hashclr(bin_pfx);
287 memset(hex_pfx, 'x', 40);
288 for (i = 0; i < len ;i++) {
289 unsigned char c = name[i];
290 unsigned char val;
291 if (c >= '0' && c <= '9')
292 val = c - '0';
293 else if (c >= 'a' && c <= 'f')
294 val = c - 'a' + 10;
295 else if (c >= 'A' && c <='F') {
296 val = c - 'A' + 10;
297 c -= 'A' - 'a';
299 else
300 return -1;
301 hex_pfx[i] = c;
302 if (!(i & 1))
303 val <<= 4;
304 bin_pfx[i >> 1] |= val;
306 return 0;
309 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
310 unsigned flags)
312 int status;
313 char hex_pfx[40];
314 unsigned char bin_pfx[20];
315 struct disambiguate_state ds;
316 int quietly = !!(flags & GET_SHA1_QUIETLY);
318 if (len < MINIMUM_ABBREV || len > 40)
319 return -1;
320 if (prepare_prefixes(name, len, bin_pfx, hex_pfx) < 0)
321 return -1;
323 prepare_alt_odb();
325 memset(&ds, 0, sizeof(ds));
326 if (flags & GET_SHA1_COMMIT)
327 ds.fn = disambiguate_commit_only;
328 else if (flags & GET_SHA1_COMMITTISH)
329 ds.fn = disambiguate_committish_only;
330 else if (flags & GET_SHA1_TREE)
331 ds.fn = disambiguate_tree_only;
332 else if (flags & GET_SHA1_TREEISH)
333 ds.fn = disambiguate_treeish_only;
334 else if (flags & GET_SHA1_BLOB)
335 ds.fn = disambiguate_blob_only;
337 find_short_object_filename(len, hex_pfx, &ds);
338 find_short_packed_object(len, bin_pfx, &ds);
339 status = finish_object_disambiguation(&ds, sha1);
341 if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
342 return error("short SHA1 %.*s is ambiguous.", len, hex_pfx);
343 return status;
346 int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
348 char hex_pfx[40];
349 unsigned char bin_pfx[20];
350 struct disambiguate_state ds;
351 int len = strlen(prefix);
353 if (len < MINIMUM_ABBREV || len > 40)
354 return -1;
355 if (prepare_prefixes(prefix, len, bin_pfx, hex_pfx) < 0)
356 return -1;
358 prepare_alt_odb();
360 memset(&ds, 0, sizeof(ds));
361 ds.always_call_fn = 1;
362 ds.cb_data = cb_data;
363 ds.fn = fn;
365 find_short_object_filename(len, hex_pfx, &ds);
366 find_short_packed_object(len, bin_pfx, &ds);
367 return ds.ambiguous;
370 int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
372 int status, exists;
374 sha1_to_hex_r(hex, sha1);
375 if (len == 40 || !len)
376 return 40;
377 exists = has_sha1_file(sha1);
378 while (len < 40) {
379 unsigned char sha1_ret[20];
380 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
381 if (exists
382 ? !status
383 : status == SHORT_NAME_NOT_FOUND) {
384 hex[len] = 0;
385 return len;
387 len++;
389 return len;
392 const char *find_unique_abbrev(const unsigned char *sha1, int len)
394 static char hex[GIT_SHA1_HEXSZ + 1];
395 find_unique_abbrev_r(hex, sha1, len);
396 return hex;
399 static int ambiguous_path(const char *path, int len)
401 int slash = 1;
402 int cnt;
404 for (cnt = 0; cnt < len; cnt++) {
405 switch (*path++) {
406 case '\0':
407 break;
408 case '/':
409 if (slash)
410 break;
411 slash = 1;
412 continue;
413 case '.':
414 continue;
415 default:
416 slash = 0;
417 continue;
419 break;
421 return slash;
424 static inline int at_mark(const char *string, int len,
425 const char **suffix, int nr)
427 int i;
429 for (i = 0; i < nr; i++) {
430 int suffix_len = strlen(suffix[i]);
431 if (suffix_len <= len
432 && !memcmp(string, suffix[i], suffix_len))
433 return suffix_len;
435 return 0;
438 static inline int upstream_mark(const char *string, int len)
440 const char *suffix[] = { "@{upstream}", "@{u}" };
441 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
444 static inline int push_mark(const char *string, int len)
446 const char *suffix[] = { "@{push}" };
447 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
450 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
451 static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
453 static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
454 unsigned int flags)
456 static const char *warn_msg = "refname '%.*s' is ambiguous.";
457 static const char *object_name_msg = N_(
458 "Git normally never creates a ref that ends with 40 hex characters\n"
459 "because it will be ignored when you just specify 40-hex. These refs\n"
460 "may be created by mistake. For example,\n"
461 "\n"
462 " git checkout -b $br $(git rev-parse ...)\n"
463 "\n"
464 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
465 "examine these refs and maybe delete them. Turn this message off by\n"
466 "running \"git config advice.objectNameWarning false\"");
467 unsigned char tmp_sha1[20];
468 char *real_ref = NULL;
469 int refs_found = 0;
470 int at, reflog_len, nth_prior = 0;
472 if (len == 40 && !get_sha1_hex(str, sha1)) {
473 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
474 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
475 if (refs_found > 0) {
476 warning(warn_msg, len, str);
477 if (advice_object_name_warning)
478 fprintf(stderr, "%s\n", _(object_name_msg));
480 free(real_ref);
482 return 0;
485 /* basic@{time or number or -number} format to query ref-log */
486 reflog_len = at = 0;
487 if (len && str[len-1] == '}') {
488 for (at = len-4; at >= 0; at--) {
489 if (str[at] == '@' && str[at+1] == '{') {
490 if (str[at+2] == '-') {
491 if (at != 0)
492 /* @{-N} not at start */
493 return -1;
494 nth_prior = 1;
495 continue;
497 if (!upstream_mark(str + at, len - at) &&
498 !push_mark(str + at, len - at)) {
499 reflog_len = (len-1) - (at+2);
500 len = at;
502 break;
507 /* Accept only unambiguous ref paths. */
508 if (len && ambiguous_path(str, len))
509 return -1;
511 if (nth_prior) {
512 struct strbuf buf = STRBUF_INIT;
513 int detached;
515 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
516 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
517 strbuf_release(&buf);
518 if (detached)
519 return 0;
523 if (!len && reflog_len)
524 /* allow "@{...}" to mean the current branch reflog */
525 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
526 else if (reflog_len)
527 refs_found = dwim_log(str, len, sha1, &real_ref);
528 else
529 refs_found = dwim_ref(str, len, sha1, &real_ref);
531 if (!refs_found)
532 return -1;
534 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
535 (refs_found > 1 ||
536 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
537 warning(warn_msg, len, str);
539 if (reflog_len) {
540 int nth, i;
541 unsigned long at_time;
542 unsigned long co_time;
543 int co_tz, co_cnt;
545 /* Is it asking for N-th entry, or approxidate? */
546 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
547 char ch = str[at+2+i];
548 if ('0' <= ch && ch <= '9')
549 nth = nth * 10 + ch - '0';
550 else
551 nth = -1;
553 if (100000000 <= nth) {
554 at_time = nth;
555 nth = -1;
556 } else if (0 <= nth)
557 at_time = 0;
558 else {
559 int errors = 0;
560 char *tmp = xstrndup(str + at + 2, reflog_len);
561 at_time = approxidate_careful(tmp, &errors);
562 free(tmp);
563 if (errors) {
564 free(real_ref);
565 return -1;
568 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
569 &co_time, &co_tz, &co_cnt)) {
570 if (!len) {
571 if (starts_with(real_ref, "refs/heads/")) {
572 str = real_ref + 11;
573 len = strlen(real_ref + 11);
574 } else {
575 /* detached HEAD */
576 str = "HEAD";
577 len = 4;
580 if (at_time) {
581 if (!(flags & GET_SHA1_QUIETLY)) {
582 warning("Log for '%.*s' only goes "
583 "back to %s.", len, str,
584 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
586 } else {
587 if (flags & GET_SHA1_QUIETLY) {
588 exit(128);
590 die("Log for '%.*s' only has %d entries.",
591 len, str, co_cnt);
596 free(real_ref);
597 return 0;
600 static int get_parent(const char *name, int len,
601 unsigned char *result, int idx)
603 unsigned char sha1[20];
604 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
605 struct commit *commit;
606 struct commit_list *p;
608 if (ret)
609 return ret;
610 commit = lookup_commit_reference(sha1);
611 if (parse_commit(commit))
612 return -1;
613 if (!idx) {
614 hashcpy(result, commit->object.oid.hash);
615 return 0;
617 p = commit->parents;
618 while (p) {
619 if (!--idx) {
620 hashcpy(result, p->item->object.oid.hash);
621 return 0;
623 p = p->next;
625 return -1;
628 static int get_nth_ancestor(const char *name, int len,
629 unsigned char *result, int generation)
631 unsigned char sha1[20];
632 struct commit *commit;
633 int ret;
635 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
636 if (ret)
637 return ret;
638 commit = lookup_commit_reference(sha1);
639 if (!commit)
640 return -1;
642 while (generation--) {
643 if (parse_commit(commit) || !commit->parents)
644 return -1;
645 commit = commit->parents->item;
647 hashcpy(result, commit->object.oid.hash);
648 return 0;
651 struct object *peel_to_type(const char *name, int namelen,
652 struct object *o, enum object_type expected_type)
654 if (name && !namelen)
655 namelen = strlen(name);
656 while (1) {
657 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
658 return NULL;
659 if (expected_type == OBJ_ANY || o->type == expected_type)
660 return o;
661 if (o->type == OBJ_TAG)
662 o = ((struct tag*) o)->tagged;
663 else if (o->type == OBJ_COMMIT)
664 o = &(((struct commit *) o)->tree->object);
665 else {
666 if (name)
667 error("%.*s: expected %s type, but the object "
668 "dereferences to %s type",
669 namelen, name, typename(expected_type),
670 typename(o->type));
671 return NULL;
676 static int peel_onion(const char *name, int len, unsigned char *sha1)
678 unsigned char outer[20];
679 const char *sp;
680 unsigned int expected_type = 0;
681 unsigned lookup_flags = 0;
682 struct object *o;
685 * "ref^{type}" dereferences ref repeatedly until you cannot
686 * dereference anymore, or you get an object of given type,
687 * whichever comes first. "ref^{}" means just dereference
688 * tags until you get a non-tag. "ref^0" is a shorthand for
689 * "ref^{commit}". "commit^{tree}" could be used to find the
690 * top-level tree of the given commit.
692 if (len < 4 || name[len-1] != '}')
693 return -1;
695 for (sp = name + len - 1; name <= sp; sp--) {
696 int ch = *sp;
697 if (ch == '{' && name < sp && sp[-1] == '^')
698 break;
700 if (sp <= name)
701 return -1;
703 sp++; /* beginning of type name, or closing brace for empty */
704 if (starts_with(sp, "commit}"))
705 expected_type = OBJ_COMMIT;
706 else if (starts_with(sp, "tag}"))
707 expected_type = OBJ_TAG;
708 else if (starts_with(sp, "tree}"))
709 expected_type = OBJ_TREE;
710 else if (starts_with(sp, "blob}"))
711 expected_type = OBJ_BLOB;
712 else if (starts_with(sp, "object}"))
713 expected_type = OBJ_ANY;
714 else if (sp[0] == '}')
715 expected_type = OBJ_NONE;
716 else if (sp[0] == '/')
717 expected_type = OBJ_COMMIT;
718 else
719 return -1;
721 if (expected_type == OBJ_COMMIT)
722 lookup_flags = GET_SHA1_COMMITTISH;
723 else if (expected_type == OBJ_TREE)
724 lookup_flags = GET_SHA1_TREEISH;
726 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
727 return -1;
729 o = parse_object(outer);
730 if (!o)
731 return -1;
732 if (!expected_type) {
733 o = deref_tag(o, name, sp - name - 2);
734 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
735 return -1;
736 hashcpy(sha1, o->oid.hash);
737 return 0;
741 * At this point, the syntax look correct, so
742 * if we do not get the needed object, we should
743 * barf.
745 o = peel_to_type(name, len, o, expected_type);
746 if (!o)
747 return -1;
749 hashcpy(sha1, o->oid.hash);
750 if (sp[0] == '/') {
751 /* "$commit^{/foo}" */
752 char *prefix;
753 int ret;
754 struct commit_list *list = NULL;
757 * $commit^{/}. Some regex implementation may reject.
758 * We don't need regex anyway. '' pattern always matches.
760 if (sp[1] == '}')
761 return 0;
763 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
764 commit_list_insert((struct commit *)o, &list);
765 ret = get_sha1_oneline(prefix, sha1, list);
766 free(prefix);
767 return ret;
769 return 0;
772 static int get_describe_name(const char *name, int len, unsigned char *sha1)
774 const char *cp;
775 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
777 for (cp = name + len - 1; name + 2 <= cp; cp--) {
778 char ch = *cp;
779 if (!isxdigit(ch)) {
780 /* We must be looking at g in "SOMETHING-g"
781 * for it to be describe output.
783 if (ch == 'g' && cp[-1] == '-') {
784 cp++;
785 len -= cp - name;
786 return get_short_sha1(cp, len, sha1, flags);
790 return -1;
793 static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
795 int ret, has_suffix;
796 const char *cp;
799 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
801 has_suffix = 0;
802 for (cp = name + len - 1; name <= cp; cp--) {
803 int ch = *cp;
804 if ('0' <= ch && ch <= '9')
805 continue;
806 if (ch == '~' || ch == '^')
807 has_suffix = ch;
808 break;
811 if (has_suffix) {
812 int num = 0;
813 int len1 = cp - name;
814 cp++;
815 while (cp < name + len)
816 num = num * 10 + *cp++ - '0';
817 if (!num && len1 == len - 1)
818 num = 1;
819 if (has_suffix == '^')
820 return get_parent(name, len1, sha1, num);
821 /* else if (has_suffix == '~') -- goes without saying */
822 return get_nth_ancestor(name, len1, sha1, num);
825 ret = peel_onion(name, len, sha1);
826 if (!ret)
827 return 0;
829 ret = get_sha1_basic(name, len, sha1, lookup_flags);
830 if (!ret)
831 return 0;
833 /* It could be describe output that is "SOMETHING-gXXXX" */
834 ret = get_describe_name(name, len, sha1);
835 if (!ret)
836 return 0;
838 return get_short_sha1(name, len, sha1, lookup_flags);
842 * This interprets names like ':/Initial revision of "git"' by searching
843 * through history and returning the first commit whose message starts
844 * the given regular expression.
846 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
848 * For a literal '!' character at the beginning of a pattern, you have to repeat
849 * that, like: ':/!!foo'
851 * For future extension, all other sequences beginning with ':/!' are reserved.
854 /* Remember to update object flag allocation in object.h */
855 #define ONELINE_SEEN (1u<<20)
857 static int handle_one_ref(const char *path, const struct object_id *oid,
858 int flag, void *cb_data)
860 struct commit_list **list = cb_data;
861 struct object *object = parse_object(oid->hash);
862 if (!object)
863 return 0;
864 if (object->type == OBJ_TAG) {
865 object = deref_tag(object, path, strlen(path));
866 if (!object)
867 return 0;
869 if (object->type != OBJ_COMMIT)
870 return 0;
871 commit_list_insert((struct commit *)object, list);
872 return 0;
875 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
876 struct commit_list *list)
878 struct commit_list *backup = NULL, *l;
879 int found = 0;
880 int negative = 0;
881 regex_t regex;
883 if (prefix[0] == '!') {
884 prefix++;
886 if (prefix[0] == '-') {
887 prefix++;
888 negative = 1;
889 } else if (prefix[0] != '!') {
890 return -1;
894 if (regcomp(&regex, prefix, REG_EXTENDED))
895 return -1;
897 for (l = list; l; l = l->next) {
898 l->item->object.flags |= ONELINE_SEEN;
899 commit_list_insert(l->item, &backup);
901 while (list) {
902 const char *p, *buf;
903 struct commit *commit;
904 int matches;
906 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
907 if (!parse_object(commit->object.oid.hash))
908 continue;
909 buf = get_commit_buffer(commit, NULL);
910 p = strstr(buf, "\n\n");
911 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
912 unuse_commit_buffer(commit, buf);
914 if (matches) {
915 hashcpy(sha1, commit->object.oid.hash);
916 found = 1;
917 break;
920 regfree(&regex);
921 free_commit_list(list);
922 for (l = backup; l; l = l->next)
923 clear_commit_marks(l->item, ONELINE_SEEN);
924 free_commit_list(backup);
925 return found ? 0 : -1;
928 struct grab_nth_branch_switch_cbdata {
929 int remaining;
930 struct strbuf buf;
933 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
934 const char *email, unsigned long timestamp, int tz,
935 const char *message, void *cb_data)
937 struct grab_nth_branch_switch_cbdata *cb = cb_data;
938 const char *match = NULL, *target = NULL;
939 size_t len;
941 if (skip_prefix(message, "checkout: moving from ", &match))
942 target = strstr(match, " to ");
944 if (!match || !target)
945 return 0;
946 if (--(cb->remaining) == 0) {
947 len = target - match;
948 strbuf_reset(&cb->buf);
949 strbuf_add(&cb->buf, match, len);
950 return 1; /* we are done */
952 return 0;
956 * Parse @{-N} syntax, return the number of characters parsed
957 * if successful; otherwise signal an error with negative value.
959 static int interpret_nth_prior_checkout(const char *name, int namelen,
960 struct strbuf *buf)
962 long nth;
963 int retval;
964 struct grab_nth_branch_switch_cbdata cb;
965 const char *brace;
966 char *num_end;
968 if (namelen < 4)
969 return -1;
970 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
971 return -1;
972 brace = memchr(name, '}', namelen);
973 if (!brace)
974 return -1;
975 nth = strtol(name + 3, &num_end, 10);
976 if (num_end != brace)
977 return -1;
978 if (nth <= 0)
979 return -1;
980 cb.remaining = nth;
981 strbuf_init(&cb.buf, 20);
983 retval = 0;
984 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
985 strbuf_reset(buf);
986 strbuf_addbuf(buf, &cb.buf);
987 retval = brace - name + 1;
990 strbuf_release(&cb.buf);
991 return retval;
994 int get_oid_mb(const char *name, struct object_id *oid)
996 struct commit *one, *two;
997 struct commit_list *mbs;
998 struct object_id oid_tmp;
999 const char *dots;
1000 int st;
1002 dots = strstr(name, "...");
1003 if (!dots)
1004 return get_oid(name, oid);
1005 if (dots == name)
1006 st = get_oid("HEAD", &oid_tmp);
1007 else {
1008 struct strbuf sb;
1009 strbuf_init(&sb, dots - name);
1010 strbuf_add(&sb, name, dots - name);
1011 st = get_sha1_committish(sb.buf, oid_tmp.hash);
1012 strbuf_release(&sb);
1014 if (st)
1015 return st;
1016 one = lookup_commit_reference_gently(oid_tmp.hash, 0);
1017 if (!one)
1018 return -1;
1020 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", oid_tmp.hash))
1021 return -1;
1022 two = lookup_commit_reference_gently(oid_tmp.hash, 0);
1023 if (!two)
1024 return -1;
1025 mbs = get_merge_bases(one, two);
1026 if (!mbs || mbs->next)
1027 st = -1;
1028 else {
1029 st = 0;
1030 oidcpy(oid, &mbs->item->object.oid);
1032 free_commit_list(mbs);
1033 return st;
1036 /* parse @something syntax, when 'something' is not {.*} */
1037 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1039 const char *next;
1041 if (len || name[1] == '{')
1042 return -1;
1044 /* make sure it's a single @, or @@{.*}, not @foo */
1045 next = memchr(name + len + 1, '@', namelen - len - 1);
1046 if (next && next[1] != '{')
1047 return -1;
1048 if (!next)
1049 next = name + namelen;
1050 if (next != name + 1)
1051 return -1;
1053 strbuf_reset(buf);
1054 strbuf_add(buf, "HEAD", 4);
1055 return 1;
1058 static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1060 /* we have extra data, which might need further processing */
1061 struct strbuf tmp = STRBUF_INIT;
1062 int used = buf->len;
1063 int ret;
1065 strbuf_add(buf, name + len, namelen - len);
1066 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
1067 /* that data was not interpreted, remove our cruft */
1068 if (ret < 0) {
1069 strbuf_setlen(buf, used);
1070 return len;
1072 strbuf_reset(buf);
1073 strbuf_addbuf(buf, &tmp);
1074 strbuf_release(&tmp);
1075 /* tweak for size of {-N} versus expanded ref name */
1076 return ret - used + len;
1079 static void set_shortened_ref(struct strbuf *buf, const char *ref)
1081 char *s = shorten_unambiguous_ref(ref, 0);
1082 strbuf_reset(buf);
1083 strbuf_addstr(buf, s);
1084 free(s);
1087 static int interpret_branch_mark(const char *name, int namelen,
1088 int at, struct strbuf *buf,
1089 int (*get_mark)(const char *, int),
1090 const char *(*get_data)(struct branch *,
1091 struct strbuf *))
1093 int len;
1094 struct branch *branch;
1095 struct strbuf err = STRBUF_INIT;
1096 const char *value;
1098 len = get_mark(name + at, namelen - at);
1099 if (!len)
1100 return -1;
1102 if (memchr(name, ':', at))
1103 return -1;
1105 if (at) {
1106 char *name_str = xmemdupz(name, at);
1107 branch = branch_get(name_str);
1108 free(name_str);
1109 } else
1110 branch = branch_get(NULL);
1112 value = get_data(branch, &err);
1113 if (!value)
1114 die("%s", err.buf);
1116 set_shortened_ref(buf, value);
1117 return len + at;
1121 * This reads short-hand syntax that not only evaluates to a commit
1122 * object name, but also can act as if the end user spelled the name
1123 * of the branch from the command line.
1125 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1126 * places the name of the branch in the given buf and returns the
1127 * number of characters parsed if successful.
1129 * - "<branch>@{upstream}" finds the name of the other ref that
1130 * <branch> is configured to merge with (missing <branch> defaults
1131 * to the current branch), and places the name of the branch in the
1132 * given buf and returns the number of characters parsed if
1133 * successful.
1135 * If the input is not of the accepted format, it returns a negative
1136 * number to signal an error.
1138 * If the input was ok but there are not N branch switches in the
1139 * reflog, it returns 0.
1141 int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
1143 char *at;
1144 const char *start;
1145 int len = interpret_nth_prior_checkout(name, namelen, buf);
1147 if (!namelen)
1148 namelen = strlen(name);
1150 if (!len) {
1151 return len; /* syntax Ok, not enough switches */
1152 } else if (len > 0) {
1153 if (len == namelen)
1154 return len; /* consumed all */
1155 else
1156 return reinterpret(name, namelen, len, buf);
1159 for (start = name;
1160 (at = memchr(start, '@', namelen - (start - name)));
1161 start = at + 1) {
1163 len = interpret_empty_at(name, namelen, at - name, buf);
1164 if (len > 0)
1165 return reinterpret(name, namelen, len, buf);
1167 len = interpret_branch_mark(name, namelen, at - name, buf,
1168 upstream_mark, branch_get_upstream);
1169 if (len > 0)
1170 return len;
1172 len = interpret_branch_mark(name, namelen, at - name, buf,
1173 push_mark, branch_get_push);
1174 if (len > 0)
1175 return len;
1178 return -1;
1181 int strbuf_branchname(struct strbuf *sb, const char *name)
1183 int len = strlen(name);
1184 int used = interpret_branch_name(name, len, sb);
1186 if (used == len)
1187 return 0;
1188 if (used < 0)
1189 used = 0;
1190 strbuf_add(sb, name + used, len - used);
1191 return len;
1194 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1196 strbuf_branchname(sb, name);
1197 if (name[0] == '-')
1198 return -1;
1199 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1200 return check_refname_format(sb->buf, 0);
1204 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1205 * notably "xyz^" for "parent of xyz"
1207 int get_sha1(const char *name, unsigned char *sha1)
1209 struct object_context unused;
1210 return get_sha1_with_context(name, 0, sha1, &unused);
1214 * This is like "get_sha1()", but for struct object_id.
1216 int get_oid(const char *name, struct object_id *oid)
1218 return get_sha1(name, oid->hash);
1223 * Many callers know that the user meant to name a commit-ish by
1224 * syntactical positions where the object name appears. Calling this
1225 * function allows the machinery to disambiguate shorter-than-unique
1226 * abbreviated object names between commit-ish and others.
1228 * Note that this does NOT error out when the named object is not a
1229 * commit-ish. It is merely to give a hint to the disambiguation
1230 * machinery.
1232 int get_sha1_committish(const char *name, unsigned char *sha1)
1234 struct object_context unused;
1235 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1236 sha1, &unused);
1239 int get_sha1_treeish(const char *name, unsigned char *sha1)
1241 struct object_context unused;
1242 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1243 sha1, &unused);
1246 int get_sha1_commit(const char *name, unsigned char *sha1)
1248 struct object_context unused;
1249 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1250 sha1, &unused);
1253 int get_sha1_tree(const char *name, unsigned char *sha1)
1255 struct object_context unused;
1256 return get_sha1_with_context(name, GET_SHA1_TREE,
1257 sha1, &unused);
1260 int get_sha1_blob(const char *name, unsigned char *sha1)
1262 struct object_context unused;
1263 return get_sha1_with_context(name, GET_SHA1_BLOB,
1264 sha1, &unused);
1267 /* Must be called only when object_name:filename doesn't exist. */
1268 static void diagnose_invalid_sha1_path(const char *prefix,
1269 const char *filename,
1270 const unsigned char *tree_sha1,
1271 const char *object_name,
1272 int object_name_len)
1274 unsigned char sha1[20];
1275 unsigned mode;
1277 if (!prefix)
1278 prefix = "";
1280 if (file_exists(filename))
1281 die("Path '%s' exists on disk, but not in '%.*s'.",
1282 filename, object_name_len, object_name);
1283 if (errno == ENOENT || errno == ENOTDIR) {
1284 char *fullname = xstrfmt("%s%s", prefix, filename);
1286 if (!get_tree_entry(tree_sha1, fullname,
1287 sha1, &mode)) {
1288 die("Path '%s' exists, but not '%s'.\n"
1289 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1290 fullname,
1291 filename,
1292 object_name_len, object_name,
1293 fullname,
1294 object_name_len, object_name,
1295 filename);
1297 die("Path '%s' does not exist in '%.*s'",
1298 filename, object_name_len, object_name);
1302 /* Must be called only when :stage:filename doesn't exist. */
1303 static void diagnose_invalid_index_path(int stage,
1304 const char *prefix,
1305 const char *filename)
1307 const struct cache_entry *ce;
1308 int pos;
1309 unsigned namelen = strlen(filename);
1310 struct strbuf fullname = STRBUF_INIT;
1312 if (!prefix)
1313 prefix = "";
1315 /* Wrong stage number? */
1316 pos = cache_name_pos(filename, namelen);
1317 if (pos < 0)
1318 pos = -pos - 1;
1319 if (pos < active_nr) {
1320 ce = active_cache[pos];
1321 if (ce_namelen(ce) == namelen &&
1322 !memcmp(ce->name, filename, namelen))
1323 die("Path '%s' is in the index, but not at stage %d.\n"
1324 "Did you mean ':%d:%s'?",
1325 filename, stage,
1326 ce_stage(ce), filename);
1329 /* Confusion between relative and absolute filenames? */
1330 strbuf_addstr(&fullname, prefix);
1331 strbuf_addstr(&fullname, filename);
1332 pos = cache_name_pos(fullname.buf, fullname.len);
1333 if (pos < 0)
1334 pos = -pos - 1;
1335 if (pos < active_nr) {
1336 ce = active_cache[pos];
1337 if (ce_namelen(ce) == fullname.len &&
1338 !memcmp(ce->name, fullname.buf, fullname.len))
1339 die("Path '%s' is in the index, but not '%s'.\n"
1340 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1341 fullname.buf, filename,
1342 ce_stage(ce), fullname.buf,
1343 ce_stage(ce), filename);
1346 if (file_exists(filename))
1347 die("Path '%s' exists on disk, but not in the index.", filename);
1348 if (errno == ENOENT || errno == ENOTDIR)
1349 die("Path '%s' does not exist (neither on disk nor in the index).",
1350 filename);
1352 strbuf_release(&fullname);
1356 static char *resolve_relative_path(const char *rel)
1358 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1359 return NULL;
1361 if (!is_inside_work_tree())
1362 die("relative path syntax can't be used outside working tree.");
1364 /* die() inside prefix_path() if resolved path is outside worktree */
1365 return prefix_path(startup_info->prefix,
1366 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1367 rel);
1370 static int get_sha1_with_context_1(const char *name,
1371 unsigned flags,
1372 const char *prefix,
1373 unsigned char *sha1,
1374 struct object_context *oc)
1376 int ret, bracket_depth;
1377 int namelen = strlen(name);
1378 const char *cp;
1379 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
1381 memset(oc, 0, sizeof(*oc));
1382 oc->mode = S_IFINVALID;
1383 ret = get_sha1_1(name, namelen, sha1, flags);
1384 if (!ret)
1385 return ret;
1387 * sha1:path --> object name of path in ent sha1
1388 * :path -> object name of absolute path in index
1389 * :./path -> object name of path relative to cwd in index
1390 * :[0-3]:path -> object name of path in index at stage
1391 * :/foo -> recent commit matching foo
1393 if (name[0] == ':') {
1394 int stage = 0;
1395 const struct cache_entry *ce;
1396 char *new_path = NULL;
1397 int pos;
1398 if (!only_to_die && namelen > 2 && name[1] == '/') {
1399 struct commit_list *list = NULL;
1401 for_each_ref(handle_one_ref, &list);
1402 commit_list_sort_by_date(&list);
1403 return get_sha1_oneline(name + 2, sha1, list);
1405 if (namelen < 3 ||
1406 name[2] != ':' ||
1407 name[1] < '0' || '3' < name[1])
1408 cp = name + 1;
1409 else {
1410 stage = name[1] - '0';
1411 cp = name + 3;
1413 new_path = resolve_relative_path(cp);
1414 if (!new_path) {
1415 namelen = namelen - (cp - name);
1416 } else {
1417 cp = new_path;
1418 namelen = strlen(cp);
1421 strlcpy(oc->path, cp, sizeof(oc->path));
1423 if (!active_cache)
1424 read_cache();
1425 pos = cache_name_pos(cp, namelen);
1426 if (pos < 0)
1427 pos = -pos - 1;
1428 while (pos < active_nr) {
1429 ce = active_cache[pos];
1430 if (ce_namelen(ce) != namelen ||
1431 memcmp(ce->name, cp, namelen))
1432 break;
1433 if (ce_stage(ce) == stage) {
1434 hashcpy(sha1, ce->oid.hash);
1435 oc->mode = ce->ce_mode;
1436 free(new_path);
1437 return 0;
1439 pos++;
1441 if (only_to_die && name[1] && name[1] != '/')
1442 diagnose_invalid_index_path(stage, prefix, cp);
1443 free(new_path);
1444 return -1;
1446 for (cp = name, bracket_depth = 0; *cp; cp++) {
1447 if (*cp == '{')
1448 bracket_depth++;
1449 else if (bracket_depth && *cp == '}')
1450 bracket_depth--;
1451 else if (!bracket_depth && *cp == ':')
1452 break;
1454 if (*cp == ':') {
1455 unsigned char tree_sha1[20];
1456 int len = cp - name;
1457 if (!get_sha1_1(name, len, tree_sha1, GET_SHA1_TREEISH)) {
1458 const char *filename = cp+1;
1459 char *new_filename = NULL;
1461 new_filename = resolve_relative_path(filename);
1462 if (new_filename)
1463 filename = new_filename;
1464 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1465 ret = get_tree_entry_follow_symlinks(tree_sha1,
1466 filename, sha1, &oc->symlink_path,
1467 &oc->mode);
1468 } else {
1469 ret = get_tree_entry(tree_sha1, filename,
1470 sha1, &oc->mode);
1471 if (ret && only_to_die) {
1472 diagnose_invalid_sha1_path(prefix,
1473 filename,
1474 tree_sha1,
1475 name, len);
1478 hashcpy(oc->tree, tree_sha1);
1479 strlcpy(oc->path, filename, sizeof(oc->path));
1481 free(new_filename);
1482 return ret;
1483 } else {
1484 if (only_to_die)
1485 die("Invalid object name '%.*s'.", len, name);
1488 return ret;
1492 * Call this function when you know "name" given by the end user must
1493 * name an object but it doesn't; the function _may_ die with a better
1494 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1495 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1496 * you have a chance to diagnose the error further.
1498 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1500 struct object_context oc;
1501 unsigned char sha1[20];
1502 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
1505 int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
1507 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1508 die("BUG: incompatible flags for get_sha1_with_context");
1509 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);