sha1_name.c: rename "now" to "current"
[git.git] / sha1_name.c
blobc5c4591f98989e48b13f2625a9f09f09e546a2f8
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"
10 static int get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
12 static int find_short_object_filename(int len, const char *name, unsigned char *sha1)
14 struct alternate_object_database *alt;
15 char hex[40];
16 int found = 0;
17 static struct alternate_object_database *fakeent;
19 if (!fakeent) {
21 * Create a "fake" alternate object database that
22 * points to our own object database, to make it
23 * easier to get a temporary working space in
24 * alt->name/alt->base while iterating over the
25 * object databases including our own.
27 const char *objdir = get_object_directory();
28 int objdir_len = strlen(objdir);
29 int entlen = objdir_len + 43;
30 fakeent = xmalloc(sizeof(*fakeent) + entlen);
31 memcpy(fakeent->base, objdir, objdir_len);
32 fakeent->name = fakeent->base + objdir_len + 1;
33 fakeent->name[-1] = '/';
35 fakeent->next = alt_odb_list;
37 sprintf(hex, "%.2s", name);
38 for (alt = fakeent; alt && found < 2; alt = alt->next) {
39 struct dirent *de;
40 DIR *dir;
41 sprintf(alt->name, "%.2s/", name);
42 dir = opendir(alt->base);
43 if (!dir)
44 continue;
45 while ((de = readdir(dir)) != NULL) {
46 if (strlen(de->d_name) != 38)
47 continue;
48 if (memcmp(de->d_name, name + 2, len - 2))
49 continue;
50 if (!found) {
51 memcpy(hex + 2, de->d_name, 38);
52 found++;
54 else if (memcmp(hex + 2, de->d_name, 38)) {
55 found = 2;
56 break;
59 closedir(dir);
61 if (found == 1)
62 return get_sha1_hex(hex, sha1) == 0;
63 return found;
66 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
68 do {
69 if (*a != *b)
70 return 0;
71 a++;
72 b++;
73 len -= 2;
74 } while (len > 1);
75 if (len)
76 if ((*a ^ *b) & 0xf0)
77 return 0;
78 return 1;
81 static int find_short_packed_object(int len, const unsigned char *match, unsigned char *sha1)
83 struct packed_git *p;
84 const unsigned char *found_sha1 = NULL;
85 int found = 0;
87 prepare_packed_git();
88 for (p = packed_git; p && found < 2; p = p->next) {
89 uint32_t num, last;
90 uint32_t first = 0;
91 open_pack_index(p);
92 num = p->num_objects;
93 last = num;
94 while (first < last) {
95 uint32_t mid = (first + last) / 2;
96 const unsigned char *current;
97 int cmp;
99 current = nth_packed_object_sha1(p, mid);
100 cmp = hashcmp(match, current);
101 if (!cmp) {
102 first = mid;
103 break;
105 if (cmp > 0) {
106 first = mid+1;
107 continue;
109 last = mid;
111 if (first < num) {
112 const unsigned char *current, *next;
113 current = nth_packed_object_sha1(p, first);
114 if (match_sha(len, match, current)) {
115 next = nth_packed_object_sha1(p, first+1);
116 if (!next|| !match_sha(len, match, next)) {
117 /* unique within this pack */
118 if (!found) {
119 found_sha1 = current;
120 found++;
122 else if (hashcmp(found_sha1, current)) {
123 found = 2;
124 break;
127 else {
128 /* not even unique within this pack */
129 found = 2;
130 break;
135 if (found == 1)
136 hashcpy(sha1, found_sha1);
137 return found;
140 #define SHORT_NAME_NOT_FOUND (-1)
141 #define SHORT_NAME_AMBIGUOUS (-2)
143 static int find_unique_short_object(int len, char *canonical,
144 unsigned char *res, unsigned char *sha1)
146 int has_unpacked, has_packed;
147 unsigned char unpacked_sha1[20], packed_sha1[20];
149 prepare_alt_odb();
150 has_unpacked = find_short_object_filename(len, canonical, unpacked_sha1);
151 has_packed = find_short_packed_object(len, res, packed_sha1);
152 if (!has_unpacked && !has_packed)
153 return SHORT_NAME_NOT_FOUND;
154 if (1 < has_unpacked || 1 < has_packed)
155 return SHORT_NAME_AMBIGUOUS;
156 if (has_unpacked != has_packed) {
157 hashcpy(sha1, (has_packed ? packed_sha1 : unpacked_sha1));
158 return 0;
160 /* Both have unique ones -- do they match? */
161 if (hashcmp(packed_sha1, unpacked_sha1))
162 return SHORT_NAME_AMBIGUOUS;
163 hashcpy(sha1, packed_sha1);
164 return 0;
167 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
168 int quietly)
170 int i, status;
171 char canonical[40];
172 unsigned char res[20];
174 if (len < MINIMUM_ABBREV || len > 40)
175 return -1;
176 hashclr(res);
177 memset(canonical, 'x', 40);
178 for (i = 0; i < len ;i++) {
179 unsigned char c = name[i];
180 unsigned char val;
181 if (c >= '0' && c <= '9')
182 val = c - '0';
183 else if (c >= 'a' && c <= 'f')
184 val = c - 'a' + 10;
185 else if (c >= 'A' && c <='F') {
186 val = c - 'A' + 10;
187 c -= 'A' - 'a';
189 else
190 return -1;
191 canonical[i] = c;
192 if (!(i & 1))
193 val <<= 4;
194 res[i >> 1] |= val;
197 status = find_unique_short_object(i, canonical, res, sha1);
198 if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
199 return error("short SHA1 %.*s is ambiguous.", len, canonical);
200 return status;
203 const char *find_unique_abbrev(const unsigned char *sha1, int len)
205 int status, exists;
206 static char hex[41];
208 exists = has_sha1_file(sha1);
209 memcpy(hex, sha1_to_hex(sha1), 40);
210 if (len == 40 || !len)
211 return hex;
212 while (len < 40) {
213 unsigned char sha1_ret[20];
214 status = get_short_sha1(hex, len, sha1_ret, 1);
215 if (exists
216 ? !status
217 : status == SHORT_NAME_NOT_FOUND) {
218 hex[len] = 0;
219 return hex;
221 len++;
223 return hex;
226 static int ambiguous_path(const char *path, int len)
228 int slash = 1;
229 int cnt;
231 for (cnt = 0; cnt < len; cnt++) {
232 switch (*path++) {
233 case '\0':
234 break;
235 case '/':
236 if (slash)
237 break;
238 slash = 1;
239 continue;
240 case '.':
241 continue;
242 default:
243 slash = 0;
244 continue;
246 break;
248 return slash;
251 static inline int upstream_mark(const char *string, int len)
253 const char *suffix[] = { "@{upstream}", "@{u}" };
254 int i;
256 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
257 int suffix_len = strlen(suffix[i]);
258 if (suffix_len <= len
259 && !memcmp(string, suffix[i], suffix_len))
260 return suffix_len;
262 return 0;
265 static int get_sha1_1(const char *name, int len, unsigned char *sha1);
267 static int get_sha1_basic(const char *str, int len, unsigned char *sha1)
269 static const char *warn_msg = "refname '%.*s' is ambiguous.";
270 char *real_ref = NULL;
271 int refs_found = 0;
272 int at, reflog_len;
274 if (len == 40 && !get_sha1_hex(str, sha1))
275 return 0;
277 /* basic@{time or number or -number} format to query ref-log */
278 reflog_len = at = 0;
279 if (len && str[len-1] == '}') {
280 for (at = len-2; at >= 0; at--) {
281 if (str[at] == '@' && str[at+1] == '{') {
282 if (!upstream_mark(str + at, len - at)) {
283 reflog_len = (len-1) - (at+2);
284 len = at;
286 break;
291 /* Accept only unambiguous ref paths. */
292 if (len && ambiguous_path(str, len))
293 return -1;
295 if (!len && reflog_len) {
296 struct strbuf buf = STRBUF_INIT;
297 int ret;
298 /* try the @{-N} syntax for n-th checkout */
299 ret = interpret_branch_name(str+at, &buf);
300 if (ret > 0) {
301 /* substitute this branch name and restart */
302 return get_sha1_1(buf.buf, buf.len, sha1);
303 } else if (ret == 0) {
304 return -1;
306 /* allow "@{...}" to mean the current branch reflog */
307 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
308 } else if (reflog_len)
309 refs_found = dwim_log(str, len, sha1, &real_ref);
310 else
311 refs_found = dwim_ref(str, len, sha1, &real_ref);
313 if (!refs_found)
314 return -1;
316 if (warn_ambiguous_refs && refs_found > 1)
317 warning(warn_msg, len, str);
319 if (reflog_len) {
320 int nth, i;
321 unsigned long at_time;
322 unsigned long co_time;
323 int co_tz, co_cnt;
325 /* a @{-N} placed anywhere except the start is an error */
326 if (str[at+2] == '-')
327 return -1;
329 /* Is it asking for N-th entry, or approxidate? */
330 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
331 char ch = str[at+2+i];
332 if ('0' <= ch && ch <= '9')
333 nth = nth * 10 + ch - '0';
334 else
335 nth = -1;
337 if (100000000 <= nth) {
338 at_time = nth;
339 nth = -1;
340 } else if (0 <= nth)
341 at_time = 0;
342 else {
343 int errors = 0;
344 char *tmp = xstrndup(str + at + 2, reflog_len);
345 at_time = approxidate_careful(tmp, &errors);
346 free(tmp);
347 if (errors)
348 return -1;
350 if (read_ref_at(real_ref, at_time, nth, sha1, NULL,
351 &co_time, &co_tz, &co_cnt)) {
352 if (at_time)
353 warning("Log for '%.*s' only goes "
354 "back to %s.", len, str,
355 show_date(co_time, co_tz, DATE_RFC2822));
356 else {
357 free(real_ref);
358 die("Log for '%.*s' only has %d entries.",
359 len, str, co_cnt);
364 free(real_ref);
365 return 0;
368 static int get_parent(const char *name, int len,
369 unsigned char *result, int idx)
371 unsigned char sha1[20];
372 int ret = get_sha1_1(name, len, sha1);
373 struct commit *commit;
374 struct commit_list *p;
376 if (ret)
377 return ret;
378 commit = lookup_commit_reference(sha1);
379 if (!commit)
380 return -1;
381 if (parse_commit(commit))
382 return -1;
383 if (!idx) {
384 hashcpy(result, commit->object.sha1);
385 return 0;
387 p = commit->parents;
388 while (p) {
389 if (!--idx) {
390 hashcpy(result, p->item->object.sha1);
391 return 0;
393 p = p->next;
395 return -1;
398 static int get_nth_ancestor(const char *name, int len,
399 unsigned char *result, int generation)
401 unsigned char sha1[20];
402 struct commit *commit;
403 int ret;
405 ret = get_sha1_1(name, len, sha1);
406 if (ret)
407 return ret;
408 commit = lookup_commit_reference(sha1);
409 if (!commit)
410 return -1;
412 while (generation--) {
413 if (parse_commit(commit) || !commit->parents)
414 return -1;
415 commit = commit->parents->item;
417 hashcpy(result, commit->object.sha1);
418 return 0;
421 struct object *peel_to_type(const char *name, int namelen,
422 struct object *o, enum object_type expected_type)
424 if (name && !namelen)
425 namelen = strlen(name);
426 while (1) {
427 if (!o || (!o->parsed && !parse_object(o->sha1)))
428 return NULL;
429 if (o->type == expected_type)
430 return o;
431 if (o->type == OBJ_TAG)
432 o = ((struct tag*) o)->tagged;
433 else if (o->type == OBJ_COMMIT)
434 o = &(((struct commit *) o)->tree->object);
435 else {
436 if (name)
437 error("%.*s: expected %s type, but the object "
438 "dereferences to %s type",
439 namelen, name, typename(expected_type),
440 typename(o->type));
441 return NULL;
446 static int peel_onion(const char *name, int len, unsigned char *sha1)
448 unsigned char outer[20];
449 const char *sp;
450 unsigned int expected_type = 0;
451 struct object *o;
454 * "ref^{type}" dereferences ref repeatedly until you cannot
455 * dereference anymore, or you get an object of given type,
456 * whichever comes first. "ref^{}" means just dereference
457 * tags until you get a non-tag. "ref^0" is a shorthand for
458 * "ref^{commit}". "commit^{tree}" could be used to find the
459 * top-level tree of the given commit.
461 if (len < 4 || name[len-1] != '}')
462 return -1;
464 for (sp = name + len - 1; name <= sp; sp--) {
465 int ch = *sp;
466 if (ch == '{' && name < sp && sp[-1] == '^')
467 break;
469 if (sp <= name)
470 return -1;
472 sp++; /* beginning of type name, or closing brace for empty */
473 if (!strncmp(commit_type, sp, 6) && sp[6] == '}')
474 expected_type = OBJ_COMMIT;
475 else if (!strncmp(tree_type, sp, 4) && sp[4] == '}')
476 expected_type = OBJ_TREE;
477 else if (!strncmp(blob_type, sp, 4) && sp[4] == '}')
478 expected_type = OBJ_BLOB;
479 else if (sp[0] == '}')
480 expected_type = OBJ_NONE;
481 else if (sp[0] == '/')
482 expected_type = OBJ_COMMIT;
483 else
484 return -1;
486 if (get_sha1_1(name, sp - name - 2, outer))
487 return -1;
489 o = parse_object(outer);
490 if (!o)
491 return -1;
492 if (!expected_type) {
493 o = deref_tag(o, name, sp - name - 2);
494 if (!o || (!o->parsed && !parse_object(o->sha1)))
495 return -1;
496 hashcpy(sha1, o->sha1);
497 return 0;
501 * At this point, the syntax look correct, so
502 * if we do not get the needed object, we should
503 * barf.
505 o = peel_to_type(name, len, o, expected_type);
506 if (!o)
507 return -1;
509 hashcpy(sha1, o->sha1);
510 if (sp[0] == '/') {
511 /* "$commit^{/foo}" */
512 char *prefix;
513 int ret;
514 struct commit_list *list = NULL;
517 * $commit^{/}. Some regex implementation may reject.
518 * We don't need regex anyway. '' pattern always matches.
520 if (sp[1] == '}')
521 return 0;
523 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
524 commit_list_insert((struct commit *)o, &list);
525 ret = get_sha1_oneline(prefix, sha1, list);
526 free(prefix);
527 return ret;
529 return 0;
532 static int get_describe_name(const char *name, int len, unsigned char *sha1)
534 const char *cp;
536 for (cp = name + len - 1; name + 2 <= cp; cp--) {
537 char ch = *cp;
538 if (hexval(ch) & ~0377) {
539 /* We must be looking at g in "SOMETHING-g"
540 * for it to be describe output.
542 if (ch == 'g' && cp[-1] == '-') {
543 cp++;
544 len -= cp - name;
545 return get_short_sha1(cp, len, sha1, 1);
549 return -1;
552 static int get_sha1_1(const char *name, int len, unsigned char *sha1)
554 int ret, has_suffix;
555 const char *cp;
558 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
560 has_suffix = 0;
561 for (cp = name + len - 1; name <= cp; cp--) {
562 int ch = *cp;
563 if ('0' <= ch && ch <= '9')
564 continue;
565 if (ch == '~' || ch == '^')
566 has_suffix = ch;
567 break;
570 if (has_suffix) {
571 int num = 0;
572 int len1 = cp - name;
573 cp++;
574 while (cp < name + len)
575 num = num * 10 + *cp++ - '0';
576 if (!num && len1 == len - 1)
577 num = 1;
578 if (has_suffix == '^')
579 return get_parent(name, len1, sha1, num);
580 /* else if (has_suffix == '~') -- goes without saying */
581 return get_nth_ancestor(name, len1, sha1, num);
584 ret = peel_onion(name, len, sha1);
585 if (!ret)
586 return 0;
588 ret = get_sha1_basic(name, len, sha1);
589 if (!ret)
590 return 0;
592 /* It could be describe output that is "SOMETHING-gXXXX" */
593 ret = get_describe_name(name, len, sha1);
594 if (!ret)
595 return 0;
597 return get_short_sha1(name, len, sha1, 0);
601 * This interprets names like ':/Initial revision of "git"' by searching
602 * through history and returning the first commit whose message starts
603 * the given regular expression.
605 * For future extension, ':/!' is reserved. If you want to match a message
606 * beginning with a '!', you have to repeat the exclamation mark.
608 #define ONELINE_SEEN (1u<<20)
610 static int handle_one_ref(const char *path,
611 const unsigned char *sha1, int flag, void *cb_data)
613 struct commit_list **list = cb_data;
614 struct object *object = parse_object(sha1);
615 if (!object)
616 return 0;
617 if (object->type == OBJ_TAG) {
618 object = deref_tag(object, path, strlen(path));
619 if (!object)
620 return 0;
622 if (object->type != OBJ_COMMIT)
623 return 0;
624 commit_list_insert_by_date((struct commit *)object, list);
625 return 0;
628 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
629 struct commit_list *list)
631 struct commit_list *backup = NULL, *l;
632 int found = 0;
633 regex_t regex;
635 if (prefix[0] == '!') {
636 if (prefix[1] != '!')
637 die ("Invalid search pattern: %s", prefix);
638 prefix++;
641 if (regcomp(&regex, prefix, REG_EXTENDED))
642 die("Invalid search pattern: %s", prefix);
644 for (l = list; l; l = l->next) {
645 l->item->object.flags |= ONELINE_SEEN;
646 commit_list_insert(l->item, &backup);
648 while (list) {
649 char *p, *to_free = NULL;
650 struct commit *commit;
651 enum object_type type;
652 unsigned long size;
653 int matches;
655 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
656 if (!parse_object(commit->object.sha1))
657 continue;
658 if (commit->buffer)
659 p = commit->buffer;
660 else {
661 p = read_sha1_file(commit->object.sha1, &type, &size);
662 if (!p)
663 continue;
664 to_free = p;
667 p = strstr(p, "\n\n");
668 matches = p && !regexec(&regex, p + 2, 0, NULL, 0);
669 free(to_free);
671 if (matches) {
672 hashcpy(sha1, commit->object.sha1);
673 found = 1;
674 break;
677 regfree(&regex);
678 free_commit_list(list);
679 for (l = backup; l; l = l->next)
680 clear_commit_marks(l->item, ONELINE_SEEN);
681 free_commit_list(backup);
682 return found ? 0 : -1;
685 struct grab_nth_branch_switch_cbdata {
686 long cnt, alloc;
687 struct strbuf *buf;
690 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
691 const char *email, unsigned long timestamp, int tz,
692 const char *message, void *cb_data)
694 struct grab_nth_branch_switch_cbdata *cb = cb_data;
695 const char *match = NULL, *target = NULL;
696 size_t len;
697 int nth;
699 if (!prefixcmp(message, "checkout: moving from ")) {
700 match = message + strlen("checkout: moving from ");
701 target = strstr(match, " to ");
704 if (!match || !target)
705 return 0;
707 len = target - match;
708 nth = cb->cnt++ % cb->alloc;
709 strbuf_reset(&cb->buf[nth]);
710 strbuf_add(&cb->buf[nth], match, len);
711 return 0;
715 * Parse @{-N} syntax, return the number of characters parsed
716 * if successful; otherwise signal an error with negative value.
718 static int interpret_nth_prior_checkout(const char *name, struct strbuf *buf)
720 long nth;
721 int i, retval;
722 struct grab_nth_branch_switch_cbdata cb;
723 const char *brace;
724 char *num_end;
726 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
727 return -1;
728 brace = strchr(name, '}');
729 if (!brace)
730 return -1;
731 nth = strtol(name+3, &num_end, 10);
732 if (num_end != brace)
733 return -1;
734 if (nth <= 0)
735 return -1;
736 cb.alloc = nth;
737 cb.buf = xmalloc(nth * sizeof(struct strbuf));
738 for (i = 0; i < nth; i++)
739 strbuf_init(&cb.buf[i], 20);
740 cb.cnt = 0;
741 retval = 0;
742 for_each_recent_reflog_ent("HEAD", grab_nth_branch_switch, 40960, &cb);
743 if (cb.cnt < nth) {
744 cb.cnt = 0;
745 for_each_reflog_ent("HEAD", grab_nth_branch_switch, &cb);
747 if (cb.cnt < nth)
748 goto release_return;
749 i = cb.cnt % nth;
750 strbuf_reset(buf);
751 strbuf_add(buf, cb.buf[i].buf, cb.buf[i].len);
752 retval = brace-name+1;
754 release_return:
755 for (i = 0; i < nth; i++)
756 strbuf_release(&cb.buf[i]);
757 free(cb.buf);
759 return retval;
762 int get_sha1_mb(const char *name, unsigned char *sha1)
764 struct commit *one, *two;
765 struct commit_list *mbs;
766 unsigned char sha1_tmp[20];
767 const char *dots;
768 int st;
770 dots = strstr(name, "...");
771 if (!dots)
772 return get_sha1(name, sha1);
773 if (dots == name)
774 st = get_sha1("HEAD", sha1_tmp);
775 else {
776 struct strbuf sb;
777 strbuf_init(&sb, dots - name);
778 strbuf_add(&sb, name, dots - name);
779 st = get_sha1(sb.buf, sha1_tmp);
780 strbuf_release(&sb);
782 if (st)
783 return st;
784 one = lookup_commit_reference_gently(sha1_tmp, 0);
785 if (!one)
786 return -1;
788 if (get_sha1(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
789 return -1;
790 two = lookup_commit_reference_gently(sha1_tmp, 0);
791 if (!two)
792 return -1;
793 mbs = get_merge_bases(one, two, 1);
794 if (!mbs || mbs->next)
795 st = -1;
796 else {
797 st = 0;
798 hashcpy(sha1, mbs->item->object.sha1);
800 free_commit_list(mbs);
801 return st;
805 * This reads short-hand syntax that not only evaluates to a commit
806 * object name, but also can act as if the end user spelled the name
807 * of the branch from the command line.
809 * - "@{-N}" finds the name of the Nth previous branch we were on, and
810 * places the name of the branch in the given buf and returns the
811 * number of characters parsed if successful.
813 * - "<branch>@{upstream}" finds the name of the other ref that
814 * <branch> is configured to merge with (missing <branch> defaults
815 * to the current branch), and places the name of the branch in the
816 * given buf and returns the number of characters parsed if
817 * successful.
819 * If the input is not of the accepted format, it returns a negative
820 * number to signal an error.
822 * If the input was ok but there are not N branch switches in the
823 * reflog, it returns 0.
825 int interpret_branch_name(const char *name, struct strbuf *buf)
827 char *cp;
828 struct branch *upstream;
829 int namelen = strlen(name);
830 int len = interpret_nth_prior_checkout(name, buf);
831 int tmp_len;
833 if (!len)
834 return len; /* syntax Ok, not enough switches */
835 if (0 < len && len == namelen)
836 return len; /* consumed all */
837 else if (0 < len) {
838 /* we have extra data, which might need further processing */
839 struct strbuf tmp = STRBUF_INIT;
840 int used = buf->len;
841 int ret;
843 strbuf_add(buf, name + len, namelen - len);
844 ret = interpret_branch_name(buf->buf, &tmp);
845 /* that data was not interpreted, remove our cruft */
846 if (ret < 0) {
847 strbuf_setlen(buf, used);
848 return len;
850 strbuf_reset(buf);
851 strbuf_addbuf(buf, &tmp);
852 strbuf_release(&tmp);
853 /* tweak for size of {-N} versus expanded ref name */
854 return ret - used + len;
857 cp = strchr(name, '@');
858 if (!cp)
859 return -1;
860 tmp_len = upstream_mark(cp, namelen - (cp - name));
861 if (!tmp_len)
862 return -1;
863 len = cp + tmp_len - name;
864 cp = xstrndup(name, cp - name);
865 upstream = branch_get(*cp ? cp : NULL);
866 if (!upstream
867 || !upstream->merge
868 || !upstream->merge[0]->dst)
869 return error("No upstream branch found for '%s'", cp);
870 free(cp);
871 cp = shorten_unambiguous_ref(upstream->merge[0]->dst, 0);
872 strbuf_reset(buf);
873 strbuf_addstr(buf, cp);
874 free(cp);
875 return len;
878 int strbuf_branchname(struct strbuf *sb, const char *name)
880 int len = strlen(name);
881 if (interpret_branch_name(name, sb) == len)
882 return 0;
883 strbuf_add(sb, name, len);
884 return len;
887 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
889 strbuf_branchname(sb, name);
890 if (name[0] == '-')
891 return -1;
892 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
893 return check_refname_format(sb->buf, 0);
897 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
898 * notably "xyz^" for "parent of xyz"
900 int get_sha1(const char *name, unsigned char *sha1)
902 struct object_context unused;
903 return get_sha1_with_context(name, sha1, &unused);
906 /* Must be called only when object_name:filename doesn't exist. */
907 static void diagnose_invalid_sha1_path(const char *prefix,
908 const char *filename,
909 const unsigned char *tree_sha1,
910 const char *object_name)
912 struct stat st;
913 unsigned char sha1[20];
914 unsigned mode;
916 if (!prefix)
917 prefix = "";
919 if (!lstat(filename, &st))
920 die("Path '%s' exists on disk, but not in '%s'.",
921 filename, object_name);
922 if (errno == ENOENT || errno == ENOTDIR) {
923 char *fullname = xmalloc(strlen(filename)
924 + strlen(prefix) + 1);
925 strcpy(fullname, prefix);
926 strcat(fullname, filename);
928 if (!get_tree_entry(tree_sha1, fullname,
929 sha1, &mode)) {
930 die("Path '%s' exists, but not '%s'.\n"
931 "Did you mean '%s:%s' aka '%s:./%s'?",
932 fullname,
933 filename,
934 object_name,
935 fullname,
936 object_name,
937 filename);
939 die("Path '%s' does not exist in '%s'",
940 filename, object_name);
944 /* Must be called only when :stage:filename doesn't exist. */
945 static void diagnose_invalid_index_path(int stage,
946 const char *prefix,
947 const char *filename)
949 struct stat st;
950 struct cache_entry *ce;
951 int pos;
952 unsigned namelen = strlen(filename);
953 unsigned fullnamelen;
954 char *fullname;
956 if (!prefix)
957 prefix = "";
959 /* Wrong stage number? */
960 pos = cache_name_pos(filename, namelen);
961 if (pos < 0)
962 pos = -pos - 1;
963 if (pos < active_nr) {
964 ce = active_cache[pos];
965 if (ce_namelen(ce) == namelen &&
966 !memcmp(ce->name, filename, namelen))
967 die("Path '%s' is in the index, but not at stage %d.\n"
968 "Did you mean ':%d:%s'?",
969 filename, stage,
970 ce_stage(ce), filename);
973 /* Confusion between relative and absolute filenames? */
974 fullnamelen = namelen + strlen(prefix);
975 fullname = xmalloc(fullnamelen + 1);
976 strcpy(fullname, prefix);
977 strcat(fullname, filename);
978 pos = cache_name_pos(fullname, fullnamelen);
979 if (pos < 0)
980 pos = -pos - 1;
981 if (pos < active_nr) {
982 ce = active_cache[pos];
983 if (ce_namelen(ce) == fullnamelen &&
984 !memcmp(ce->name, fullname, fullnamelen))
985 die("Path '%s' is in the index, but not '%s'.\n"
986 "Did you mean ':%d:%s' aka ':%d:./%s'?",
987 fullname, filename,
988 ce_stage(ce), fullname,
989 ce_stage(ce), filename);
992 if (!lstat(filename, &st))
993 die("Path '%s' exists on disk, but not in the index.", filename);
994 if (errno == ENOENT || errno == ENOTDIR)
995 die("Path '%s' does not exist (neither on disk nor in the index).",
996 filename);
998 free(fullname);
1002 static char *resolve_relative_path(const char *rel)
1004 if (prefixcmp(rel, "./") && prefixcmp(rel, "../"))
1005 return NULL;
1007 if (!startup_info)
1008 die("BUG: startup_info struct is not initialized.");
1010 if (!is_inside_work_tree())
1011 die("relative path syntax can't be used outside working tree.");
1013 /* die() inside prefix_path() if resolved path is outside worktree */
1014 return prefix_path(startup_info->prefix,
1015 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1016 rel);
1019 static int get_sha1_with_context_1(const char *name, unsigned char *sha1,
1020 struct object_context *oc,
1021 int only_to_die, const char *prefix)
1023 int ret, bracket_depth;
1024 int namelen = strlen(name);
1025 const char *cp;
1027 memset(oc, 0, sizeof(*oc));
1028 oc->mode = S_IFINVALID;
1029 ret = get_sha1_1(name, namelen, sha1);
1030 if (!ret)
1031 return ret;
1032 /* sha1:path --> object name of path in ent sha1
1033 * :path -> object name of absolute path in index
1034 * :./path -> object name of path relative to cwd in index
1035 * :[0-3]:path -> object name of path in index at stage
1036 * :/foo -> recent commit matching foo
1038 if (name[0] == ':') {
1039 int stage = 0;
1040 struct cache_entry *ce;
1041 char *new_path = NULL;
1042 int pos;
1043 if (!only_to_die && namelen > 2 && name[1] == '/') {
1044 struct commit_list *list = NULL;
1045 for_each_ref(handle_one_ref, &list);
1046 return get_sha1_oneline(name + 2, sha1, list);
1048 if (namelen < 3 ||
1049 name[2] != ':' ||
1050 name[1] < '0' || '3' < name[1])
1051 cp = name + 1;
1052 else {
1053 stage = name[1] - '0';
1054 cp = name + 3;
1056 new_path = resolve_relative_path(cp);
1057 if (!new_path) {
1058 namelen = namelen - (cp - name);
1059 } else {
1060 cp = new_path;
1061 namelen = strlen(cp);
1064 strncpy(oc->path, cp,
1065 sizeof(oc->path));
1066 oc->path[sizeof(oc->path)-1] = '\0';
1068 if (!active_cache)
1069 read_cache();
1070 pos = cache_name_pos(cp, namelen);
1071 if (pos < 0)
1072 pos = -pos - 1;
1073 while (pos < active_nr) {
1074 ce = active_cache[pos];
1075 if (ce_namelen(ce) != namelen ||
1076 memcmp(ce->name, cp, namelen))
1077 break;
1078 if (ce_stage(ce) == stage) {
1079 hashcpy(sha1, ce->sha1);
1080 oc->mode = ce->ce_mode;
1081 free(new_path);
1082 return 0;
1084 pos++;
1086 if (only_to_die && name[1] && name[1] != '/')
1087 diagnose_invalid_index_path(stage, prefix, cp);
1088 free(new_path);
1089 return -1;
1091 for (cp = name, bracket_depth = 0; *cp; cp++) {
1092 if (*cp == '{')
1093 bracket_depth++;
1094 else if (bracket_depth && *cp == '}')
1095 bracket_depth--;
1096 else if (!bracket_depth && *cp == ':')
1097 break;
1099 if (*cp == ':') {
1100 unsigned char tree_sha1[20];
1101 char *object_name = NULL;
1102 if (only_to_die) {
1103 object_name = xmalloc(cp-name+1);
1104 strncpy(object_name, name, cp-name);
1105 object_name[cp-name] = '\0';
1107 if (!get_sha1_1(name, cp-name, tree_sha1)) {
1108 const char *filename = cp+1;
1109 char *new_filename = NULL;
1111 new_filename = resolve_relative_path(filename);
1112 if (new_filename)
1113 filename = new_filename;
1114 ret = get_tree_entry(tree_sha1, filename, sha1, &oc->mode);
1115 if (only_to_die) {
1116 diagnose_invalid_sha1_path(prefix, filename,
1117 tree_sha1, object_name);
1118 free(object_name);
1120 hashcpy(oc->tree, tree_sha1);
1121 strncpy(oc->path, filename,
1122 sizeof(oc->path));
1123 oc->path[sizeof(oc->path)-1] = '\0';
1125 free(new_filename);
1126 return ret;
1127 } else {
1128 if (only_to_die)
1129 die("Invalid object name '%s'.", object_name);
1132 return ret;
1136 * Call this function when you know "name" given by the end user must
1137 * name an object but it doesn't; the function _may_ die with a better
1138 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1139 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1140 * you have a chance to diagnose the error further.
1142 void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
1144 struct object_context oc;
1145 unsigned char sha1[20];
1146 get_sha1_with_context_1(name, sha1, &oc, 1, prefix);
1149 int get_sha1_with_context(const char *str, unsigned char *sha1, struct object_context *orc)
1151 return get_sha1_with_context_1(str, sha1, orc, 0, NULL);