Merge branch 'fk/threaded-grep'
[git/raj.git] / sha1_name.c
blobc7f1510ef102512f1270a064fbb7a842b1d9aed9
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 find_short_object_filename(int len, const char *name, unsigned char *sha1)
12 struct alternate_object_database *alt;
13 char hex[40];
14 int found = 0;
15 static struct alternate_object_database *fakeent;
17 if (!fakeent) {
18 const char *objdir = get_object_directory();
19 int objdir_len = strlen(objdir);
20 int entlen = objdir_len + 43;
21 fakeent = xmalloc(sizeof(*fakeent) + entlen);
22 memcpy(fakeent->base, objdir, objdir_len);
23 fakeent->name = fakeent->base + objdir_len + 1;
24 fakeent->name[-1] = '/';
26 fakeent->next = alt_odb_list;
28 sprintf(hex, "%.2s", name);
29 for (alt = fakeent; alt && found < 2; alt = alt->next) {
30 struct dirent *de;
31 DIR *dir;
32 sprintf(alt->name, "%.2s/", name);
33 dir = opendir(alt->base);
34 if (!dir)
35 continue;
36 while ((de = readdir(dir)) != NULL) {
37 if (strlen(de->d_name) != 38)
38 continue;
39 if (memcmp(de->d_name, name + 2, len - 2))
40 continue;
41 if (!found) {
42 memcpy(hex + 2, de->d_name, 38);
43 found++;
45 else if (memcmp(hex + 2, de->d_name, 38)) {
46 found = 2;
47 break;
50 closedir(dir);
52 if (found == 1)
53 return get_sha1_hex(hex, sha1) == 0;
54 return found;
57 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
59 do {
60 if (*a != *b)
61 return 0;
62 a++;
63 b++;
64 len -= 2;
65 } while (len > 1);
66 if (len)
67 if ((*a ^ *b) & 0xf0)
68 return 0;
69 return 1;
72 static int find_short_packed_object(int len, const unsigned char *match, unsigned char *sha1)
74 struct packed_git *p;
75 const unsigned char *found_sha1 = NULL;
76 int found = 0;
78 prepare_packed_git();
79 for (p = packed_git; p && found < 2; p = p->next) {
80 uint32_t num, last;
81 uint32_t first = 0;
82 open_pack_index(p);
83 num = p->num_objects;
84 last = num;
85 while (first < last) {
86 uint32_t mid = (first + last) / 2;
87 const unsigned char *now;
88 int cmp;
90 now = nth_packed_object_sha1(p, mid);
91 cmp = hashcmp(match, now);
92 if (!cmp) {
93 first = mid;
94 break;
96 if (cmp > 0) {
97 first = mid+1;
98 continue;
100 last = mid;
102 if (first < num) {
103 const unsigned char *now, *next;
104 now = nth_packed_object_sha1(p, first);
105 if (match_sha(len, match, now)) {
106 next = nth_packed_object_sha1(p, first+1);
107 if (!next|| !match_sha(len, match, next)) {
108 /* unique within this pack */
109 if (!found) {
110 found_sha1 = now;
111 found++;
113 else if (hashcmp(found_sha1, now)) {
114 found = 2;
115 break;
118 else {
119 /* not even unique within this pack */
120 found = 2;
121 break;
126 if (found == 1)
127 hashcpy(sha1, found_sha1);
128 return found;
131 #define SHORT_NAME_NOT_FOUND (-1)
132 #define SHORT_NAME_AMBIGUOUS (-2)
134 static int find_unique_short_object(int len, char *canonical,
135 unsigned char *res, unsigned char *sha1)
137 int has_unpacked, has_packed;
138 unsigned char unpacked_sha1[20], packed_sha1[20];
140 prepare_alt_odb();
141 has_unpacked = find_short_object_filename(len, canonical, unpacked_sha1);
142 has_packed = find_short_packed_object(len, res, packed_sha1);
143 if (!has_unpacked && !has_packed)
144 return SHORT_NAME_NOT_FOUND;
145 if (1 < has_unpacked || 1 < has_packed)
146 return SHORT_NAME_AMBIGUOUS;
147 if (has_unpacked != has_packed) {
148 hashcpy(sha1, (has_packed ? packed_sha1 : unpacked_sha1));
149 return 0;
151 /* Both have unique ones -- do they match? */
152 if (hashcmp(packed_sha1, unpacked_sha1))
153 return SHORT_NAME_AMBIGUOUS;
154 hashcpy(sha1, packed_sha1);
155 return 0;
158 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
159 int quietly)
161 int i, status;
162 char canonical[40];
163 unsigned char res[20];
165 if (len < MINIMUM_ABBREV || len > 40)
166 return -1;
167 hashclr(res);
168 memset(canonical, 'x', 40);
169 for (i = 0; i < len ;i++) {
170 unsigned char c = name[i];
171 unsigned char val;
172 if (c >= '0' && c <= '9')
173 val = c - '0';
174 else if (c >= 'a' && c <= 'f')
175 val = c - 'a' + 10;
176 else if (c >= 'A' && c <='F') {
177 val = c - 'A' + 10;
178 c -= 'A' - 'a';
180 else
181 return -1;
182 canonical[i] = c;
183 if (!(i & 1))
184 val <<= 4;
185 res[i >> 1] |= val;
188 status = find_unique_short_object(i, canonical, res, sha1);
189 if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
190 return error("short SHA1 %.*s is ambiguous.", len, canonical);
191 return status;
194 const char *find_unique_abbrev(const unsigned char *sha1, int len)
196 int status, exists;
197 static char hex[41];
199 exists = has_sha1_file(sha1);
200 memcpy(hex, sha1_to_hex(sha1), 40);
201 if (len == 40 || !len)
202 return hex;
203 while (len < 40) {
204 unsigned char sha1_ret[20];
205 status = get_short_sha1(hex, len, sha1_ret, 1);
206 if (exists
207 ? !status
208 : status == SHORT_NAME_NOT_FOUND) {
209 hex[len] = 0;
210 return hex;
212 len++;
214 return hex;
217 static int ambiguous_path(const char *path, int len)
219 int slash = 1;
220 int cnt;
222 for (cnt = 0; cnt < len; cnt++) {
223 switch (*path++) {
224 case '\0':
225 break;
226 case '/':
227 if (slash)
228 break;
229 slash = 1;
230 continue;
231 case '.':
232 continue;
233 default:
234 slash = 0;
235 continue;
237 break;
239 return slash;
243 * *string and *len will only be substituted, and *string returned (for
244 * later free()ing) if the string passed in is a magic short-hand form
245 * to name a branch.
247 static char *substitute_branch_name(const char **string, int *len)
249 struct strbuf buf = STRBUF_INIT;
250 int ret = interpret_branch_name(*string, &buf);
252 if (ret == *len) {
253 size_t size;
254 *string = strbuf_detach(&buf, &size);
255 *len = size;
256 return (char *)*string;
259 return NULL;
262 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
264 char *last_branch = substitute_branch_name(&str, &len);
265 const char **p, *r;
266 int refs_found = 0;
268 *ref = NULL;
269 for (p = ref_rev_parse_rules; *p; p++) {
270 char fullref[PATH_MAX];
271 unsigned char sha1_from_ref[20];
272 unsigned char *this_result;
273 int flag;
275 this_result = refs_found ? sha1_from_ref : sha1;
276 mksnpath(fullref, sizeof(fullref), *p, len, str);
277 r = resolve_ref(fullref, this_result, 1, &flag);
278 if (r) {
279 if (!refs_found++)
280 *ref = xstrdup(r);
281 if (!warn_ambiguous_refs)
282 break;
283 } else if ((flag & REF_ISSYMREF) &&
284 (len != 4 || strcmp(str, "HEAD")))
285 warning("ignoring dangling symref %s.", fullref);
287 free(last_branch);
288 return refs_found;
291 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
293 char *last_branch = substitute_branch_name(&str, &len);
294 const char **p;
295 int logs_found = 0;
297 *log = NULL;
298 for (p = ref_rev_parse_rules; *p; p++) {
299 struct stat st;
300 unsigned char hash[20];
301 char path[PATH_MAX];
302 const char *ref, *it;
304 mksnpath(path, sizeof(path), *p, len, str);
305 ref = resolve_ref(path, hash, 1, NULL);
306 if (!ref)
307 continue;
308 if (!stat(git_path("logs/%s", path), &st) &&
309 S_ISREG(st.st_mode))
310 it = path;
311 else if (strcmp(ref, path) &&
312 !stat(git_path("logs/%s", ref), &st) &&
313 S_ISREG(st.st_mode))
314 it = ref;
315 else
316 continue;
317 if (!logs_found++) {
318 *log = xstrdup(it);
319 hashcpy(sha1, hash);
321 if (!warn_ambiguous_refs)
322 break;
324 free(last_branch);
325 return logs_found;
328 static inline int upstream_mark(const char *string, int len)
330 const char *suffix[] = { "@{upstream}", "@{u}" };
331 int i;
333 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
334 int suffix_len = strlen(suffix[i]);
335 if (suffix_len <= len
336 && !memcmp(string, suffix[i], suffix_len))
337 return suffix_len;
339 return 0;
342 static int get_sha1_1(const char *name, int len, unsigned char *sha1);
344 static int get_sha1_basic(const char *str, int len, unsigned char *sha1)
346 static const char *warning = "warning: refname '%.*s' is ambiguous.\n";
347 char *real_ref = NULL;
348 int refs_found = 0;
349 int at, reflog_len;
351 if (len == 40 && !get_sha1_hex(str, sha1))
352 return 0;
354 /* basic@{time or number or -number} format to query ref-log */
355 reflog_len = at = 0;
356 if (len && str[len-1] == '}') {
357 for (at = len-2; at >= 0; at--) {
358 if (str[at] == '@' && str[at+1] == '{') {
359 if (!upstream_mark(str + at, len - at)) {
360 reflog_len = (len-1) - (at+2);
361 len = at;
363 break;
368 /* Accept only unambiguous ref paths. */
369 if (len && ambiguous_path(str, len))
370 return -1;
372 if (!len && reflog_len) {
373 struct strbuf buf = STRBUF_INIT;
374 int ret;
375 /* try the @{-N} syntax for n-th checkout */
376 ret = interpret_branch_name(str+at, &buf);
377 if (ret > 0) {
378 /* substitute this branch name and restart */
379 return get_sha1_1(buf.buf, buf.len, sha1);
380 } else if (ret == 0) {
381 return -1;
383 /* allow "@{...}" to mean the current branch reflog */
384 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
385 } else if (reflog_len)
386 refs_found = dwim_log(str, len, sha1, &real_ref);
387 else
388 refs_found = dwim_ref(str, len, sha1, &real_ref);
390 if (!refs_found)
391 return -1;
393 if (warn_ambiguous_refs && refs_found > 1)
394 fprintf(stderr, warning, len, str);
396 if (reflog_len) {
397 int nth, i;
398 unsigned long at_time;
399 unsigned long co_time;
400 int co_tz, co_cnt;
402 /* Is it asking for N-th entry, or approxidate? */
403 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
404 char ch = str[at+2+i];
405 if ('0' <= ch && ch <= '9')
406 nth = nth * 10 + ch - '0';
407 else
408 nth = -1;
410 if (100000000 <= nth) {
411 at_time = nth;
412 nth = -1;
413 } else if (0 <= nth)
414 at_time = 0;
415 else {
416 int errors = 0;
417 char *tmp = xstrndup(str + at + 2, reflog_len);
418 at_time = approxidate_careful(tmp, &errors);
419 free(tmp);
420 if (errors)
421 return -1;
423 if (read_ref_at(real_ref, at_time, nth, sha1, NULL,
424 &co_time, &co_tz, &co_cnt)) {
425 if (at_time)
426 fprintf(stderr,
427 "warning: Log for '%.*s' only goes "
428 "back to %s.\n", len, str,
429 show_date(co_time, co_tz, DATE_RFC2822));
430 else
431 fprintf(stderr,
432 "warning: Log for '%.*s' only has "
433 "%d entries.\n", len, str, co_cnt);
437 free(real_ref);
438 return 0;
441 static int get_parent(const char *name, int len,
442 unsigned char *result, int idx)
444 unsigned char sha1[20];
445 int ret = get_sha1_1(name, len, sha1);
446 struct commit *commit;
447 struct commit_list *p;
449 if (ret)
450 return ret;
451 commit = lookup_commit_reference(sha1);
452 if (!commit)
453 return -1;
454 if (parse_commit(commit))
455 return -1;
456 if (!idx) {
457 hashcpy(result, commit->object.sha1);
458 return 0;
460 p = commit->parents;
461 while (p) {
462 if (!--idx) {
463 hashcpy(result, p->item->object.sha1);
464 return 0;
466 p = p->next;
468 return -1;
471 static int get_nth_ancestor(const char *name, int len,
472 unsigned char *result, int generation)
474 unsigned char sha1[20];
475 struct commit *commit;
476 int ret;
478 ret = get_sha1_1(name, len, sha1);
479 if (ret)
480 return ret;
481 commit = lookup_commit_reference(sha1);
482 if (!commit)
483 return -1;
485 while (generation--) {
486 if (parse_commit(commit) || !commit->parents)
487 return -1;
488 commit = commit->parents->item;
490 hashcpy(result, commit->object.sha1);
491 return 0;
494 struct object *peel_to_type(const char *name, int namelen,
495 struct object *o, enum object_type expected_type)
497 if (name && !namelen)
498 namelen = strlen(name);
499 if (!o) {
500 unsigned char sha1[20];
501 if (get_sha1_1(name, namelen, sha1))
502 return NULL;
503 o = parse_object(sha1);
505 while (1) {
506 if (!o || (!o->parsed && !parse_object(o->sha1)))
507 return NULL;
508 if (o->type == expected_type)
509 return o;
510 if (o->type == OBJ_TAG)
511 o = ((struct tag*) o)->tagged;
512 else if (o->type == OBJ_COMMIT)
513 o = &(((struct commit *) o)->tree->object);
514 else {
515 if (name)
516 error("%.*s: expected %s type, but the object "
517 "dereferences to %s type",
518 namelen, name, typename(expected_type),
519 typename(o->type));
520 return NULL;
525 static int peel_onion(const char *name, int len, unsigned char *sha1)
527 unsigned char outer[20];
528 const char *sp;
529 unsigned int expected_type = 0;
530 struct object *o;
533 * "ref^{type}" dereferences ref repeatedly until you cannot
534 * dereference anymore, or you get an object of given type,
535 * whichever comes first. "ref^{}" means just dereference
536 * tags until you get a non-tag. "ref^0" is a shorthand for
537 * "ref^{commit}". "commit^{tree}" could be used to find the
538 * top-level tree of the given commit.
540 if (len < 4 || name[len-1] != '}')
541 return -1;
543 for (sp = name + len - 1; name <= sp; sp--) {
544 int ch = *sp;
545 if (ch == '{' && name < sp && sp[-1] == '^')
546 break;
548 if (sp <= name)
549 return -1;
551 sp++; /* beginning of type name, or closing brace for empty */
552 if (!strncmp(commit_type, sp, 6) && sp[6] == '}')
553 expected_type = OBJ_COMMIT;
554 else if (!strncmp(tree_type, sp, 4) && sp[4] == '}')
555 expected_type = OBJ_TREE;
556 else if (!strncmp(blob_type, sp, 4) && sp[4] == '}')
557 expected_type = OBJ_BLOB;
558 else if (sp[0] == '}')
559 expected_type = OBJ_NONE;
560 else
561 return -1;
563 if (get_sha1_1(name, sp - name - 2, outer))
564 return -1;
566 o = parse_object(outer);
567 if (!o)
568 return -1;
569 if (!expected_type) {
570 o = deref_tag(o, name, sp - name - 2);
571 if (!o || (!o->parsed && !parse_object(o->sha1)))
572 return -1;
573 hashcpy(sha1, o->sha1);
575 else {
577 * At this point, the syntax look correct, so
578 * if we do not get the needed object, we should
579 * barf.
581 o = peel_to_type(name, len, o, expected_type);
582 if (o) {
583 hashcpy(sha1, o->sha1);
584 return 0;
586 return -1;
588 return 0;
591 static int get_describe_name(const char *name, int len, unsigned char *sha1)
593 const char *cp;
595 for (cp = name + len - 1; name + 2 <= cp; cp--) {
596 char ch = *cp;
597 if (hexval(ch) & ~0377) {
598 /* We must be looking at g in "SOMETHING-g"
599 * for it to be describe output.
601 if (ch == 'g' && cp[-1] == '-') {
602 cp++;
603 len -= cp - name;
604 return get_short_sha1(cp, len, sha1, 1);
608 return -1;
611 static int get_sha1_1(const char *name, int len, unsigned char *sha1)
613 int ret, has_suffix;
614 const char *cp;
617 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
619 has_suffix = 0;
620 for (cp = name + len - 1; name <= cp; cp--) {
621 int ch = *cp;
622 if ('0' <= ch && ch <= '9')
623 continue;
624 if (ch == '~' || ch == '^')
625 has_suffix = ch;
626 break;
629 if (has_suffix) {
630 int num = 0;
631 int len1 = cp - name;
632 cp++;
633 while (cp < name + len)
634 num = num * 10 + *cp++ - '0';
635 if (!num && len1 == len - 1)
636 num = 1;
637 if (has_suffix == '^')
638 return get_parent(name, len1, sha1, num);
639 /* else if (has_suffix == '~') -- goes without saying */
640 return get_nth_ancestor(name, len1, sha1, num);
643 ret = peel_onion(name, len, sha1);
644 if (!ret)
645 return 0;
647 ret = get_sha1_basic(name, len, sha1);
648 if (!ret)
649 return 0;
651 /* It could be describe output that is "SOMETHING-gXXXX" */
652 ret = get_describe_name(name, len, sha1);
653 if (!ret)
654 return 0;
656 return get_short_sha1(name, len, sha1, 0);
659 static int handle_one_ref(const char *path,
660 const unsigned char *sha1, int flag, void *cb_data)
662 struct commit_list **list = cb_data;
663 struct object *object = parse_object(sha1);
664 if (!object)
665 return 0;
666 if (object->type == OBJ_TAG) {
667 object = deref_tag(object, path, strlen(path));
668 if (!object)
669 return 0;
671 if (object->type != OBJ_COMMIT)
672 return 0;
673 insert_by_date((struct commit *)object, list);
674 return 0;
678 * This interprets names like ':/Initial revision of "git"' by searching
679 * through history and returning the first commit whose message starts
680 * with the given string.
682 * For future extension, ':/!' is reserved. If you want to match a message
683 * beginning with a '!', you have to repeat the exclamation mark.
686 #define ONELINE_SEEN (1u<<20)
687 static int get_sha1_oneline(const char *prefix, unsigned char *sha1)
689 struct commit_list *list = NULL, *backup = NULL, *l;
690 int retval = -1;
691 char *temp_commit_buffer = NULL;
693 if (prefix[0] == '!') {
694 if (prefix[1] != '!')
695 die ("Invalid search pattern: %s", prefix);
696 prefix++;
698 for_each_ref(handle_one_ref, &list);
699 for (l = list; l; l = l->next)
700 commit_list_insert(l->item, &backup);
701 while (list) {
702 char *p;
703 struct commit *commit;
704 enum object_type type;
705 unsigned long size;
707 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
708 if (!parse_object(commit->object.sha1))
709 continue;
710 free(temp_commit_buffer);
711 if (commit->buffer)
712 p = commit->buffer;
713 else {
714 p = read_sha1_file(commit->object.sha1, &type, &size);
715 if (!p)
716 continue;
717 temp_commit_buffer = p;
719 if (!(p = strstr(p, "\n\n")))
720 continue;
721 if (!prefixcmp(p + 2, prefix)) {
722 hashcpy(sha1, commit->object.sha1);
723 retval = 0;
724 break;
727 free(temp_commit_buffer);
728 free_commit_list(list);
729 for (l = backup; l; l = l->next)
730 clear_commit_marks(l->item, ONELINE_SEEN);
731 return retval;
734 struct grab_nth_branch_switch_cbdata {
735 long cnt, alloc;
736 struct strbuf *buf;
739 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
740 const char *email, unsigned long timestamp, int tz,
741 const char *message, void *cb_data)
743 struct grab_nth_branch_switch_cbdata *cb = cb_data;
744 const char *match = NULL, *target = NULL;
745 size_t len;
746 int nth;
748 if (!prefixcmp(message, "checkout: moving from ")) {
749 match = message + strlen("checkout: moving from ");
750 target = strstr(match, " to ");
753 if (!match || !target)
754 return 0;
756 len = target - match;
757 nth = cb->cnt++ % cb->alloc;
758 strbuf_reset(&cb->buf[nth]);
759 strbuf_add(&cb->buf[nth], match, len);
760 return 0;
764 * Parse @{-N} syntax, return the number of characters parsed
765 * if successful; otherwise signal an error with negative value.
767 static int interpret_nth_prior_checkout(const char *name, struct strbuf *buf)
769 long nth;
770 int i, retval;
771 struct grab_nth_branch_switch_cbdata cb;
772 const char *brace;
773 char *num_end;
775 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
776 return -1;
777 brace = strchr(name, '}');
778 if (!brace)
779 return -1;
780 nth = strtol(name+3, &num_end, 10);
781 if (num_end != brace)
782 return -1;
783 if (nth <= 0)
784 return -1;
785 cb.alloc = nth;
786 cb.buf = xmalloc(nth * sizeof(struct strbuf));
787 for (i = 0; i < nth; i++)
788 strbuf_init(&cb.buf[i], 20);
789 cb.cnt = 0;
790 retval = 0;
791 for_each_recent_reflog_ent("HEAD", grab_nth_branch_switch, 40960, &cb);
792 if (cb.cnt < nth) {
793 cb.cnt = 0;
794 for_each_reflog_ent("HEAD", grab_nth_branch_switch, &cb);
796 if (cb.cnt < nth)
797 goto release_return;
798 i = cb.cnt % nth;
799 strbuf_reset(buf);
800 strbuf_add(buf, cb.buf[i].buf, cb.buf[i].len);
801 retval = brace-name+1;
803 release_return:
804 for (i = 0; i < nth; i++)
805 strbuf_release(&cb.buf[i]);
806 free(cb.buf);
808 return retval;
811 int get_sha1_mb(const char *name, unsigned char *sha1)
813 struct commit *one, *two;
814 struct commit_list *mbs;
815 unsigned char sha1_tmp[20];
816 const char *dots;
817 int st;
819 dots = strstr(name, "...");
820 if (!dots)
821 return get_sha1(name, sha1);
822 if (dots == name)
823 st = get_sha1("HEAD", sha1_tmp);
824 else {
825 struct strbuf sb;
826 strbuf_init(&sb, dots - name);
827 strbuf_add(&sb, name, dots - name);
828 st = get_sha1(sb.buf, sha1_tmp);
829 strbuf_release(&sb);
831 if (st)
832 return st;
833 one = lookup_commit_reference_gently(sha1_tmp, 0);
834 if (!one)
835 return -1;
837 if (get_sha1(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
838 return -1;
839 two = lookup_commit_reference_gently(sha1_tmp, 0);
840 if (!two)
841 return -1;
842 mbs = get_merge_bases(one, two, 1);
843 if (!mbs || mbs->next)
844 st = -1;
845 else {
846 st = 0;
847 hashcpy(sha1, mbs->item->object.sha1);
849 free_commit_list(mbs);
850 return st;
854 * This reads short-hand syntax that not only evaluates to a commit
855 * object name, but also can act as if the end user spelled the name
856 * of the branch from the command line.
858 * - "@{-N}" finds the name of the Nth previous branch we were on, and
859 * places the name of the branch in the given buf and returns the
860 * number of characters parsed if successful.
862 * - "<branch>@{upstream}" finds the name of the other ref that
863 * <branch> is configured to merge with (missing <branch> defaults
864 * to the current branch), and places the name of the branch in the
865 * given buf and returns the number of characters parsed if
866 * successful.
868 * If the input is not of the accepted format, it returns a negative
869 * number to signal an error.
871 * If the input was ok but there are not N branch switches in the
872 * reflog, it returns 0.
874 int interpret_branch_name(const char *name, struct strbuf *buf)
876 char *cp;
877 struct branch *upstream;
878 int namelen = strlen(name);
879 int len = interpret_nth_prior_checkout(name, buf);
880 int tmp_len;
882 if (!len)
883 return len; /* syntax Ok, not enough switches */
884 if (0 < len)
885 return len; /* consumed from the front */
886 cp = strchr(name, '@');
887 if (!cp)
888 return -1;
889 tmp_len = upstream_mark(cp, namelen - (cp - name));
890 if (!tmp_len)
891 return -1;
892 len = cp + tmp_len - name;
893 cp = xstrndup(name, cp - name);
894 upstream = branch_get(*cp ? cp : NULL);
895 if (!upstream
896 || !upstream->merge
897 || !upstream->merge[0]->dst)
898 return error("No upstream branch found for '%s'", cp);
899 free(cp);
900 cp = shorten_unambiguous_ref(upstream->merge[0]->dst, 0);
901 strbuf_reset(buf);
902 strbuf_addstr(buf, cp);
903 free(cp);
904 return len;
908 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
909 * notably "xyz^" for "parent of xyz"
911 int get_sha1(const char *name, unsigned char *sha1)
913 unsigned unused;
914 return get_sha1_with_mode(name, sha1, &unused);
917 /* Must be called only when object_name:filename doesn't exist. */
918 static void diagnose_invalid_sha1_path(const char *prefix,
919 const char *filename,
920 const unsigned char *tree_sha1,
921 const char *object_name)
923 struct stat st;
924 unsigned char sha1[20];
925 unsigned mode;
927 if (!prefix)
928 prefix = "";
930 if (!lstat(filename, &st))
931 die("Path '%s' exists on disk, but not in '%s'.",
932 filename, object_name);
933 if (errno == ENOENT || errno == ENOTDIR) {
934 char *fullname = xmalloc(strlen(filename)
935 + strlen(prefix) + 1);
936 strcpy(fullname, prefix);
937 strcat(fullname, filename);
939 if (!get_tree_entry(tree_sha1, fullname,
940 sha1, &mode)) {
941 die("Path '%s' exists, but not '%s'.\n"
942 "Did you mean '%s:%s'?",
943 fullname,
944 filename,
945 object_name,
946 fullname);
948 die("Path '%s' does not exist in '%s'",
949 filename, object_name);
953 /* Must be called only when :stage:filename doesn't exist. */
954 static void diagnose_invalid_index_path(int stage,
955 const char *prefix,
956 const char *filename)
958 struct stat st;
959 struct cache_entry *ce;
960 int pos;
961 unsigned namelen = strlen(filename);
962 unsigned fullnamelen;
963 char *fullname;
965 if (!prefix)
966 prefix = "";
968 /* Wrong stage number? */
969 pos = cache_name_pos(filename, namelen);
970 if (pos < 0)
971 pos = -pos - 1;
972 ce = active_cache[pos];
973 if (ce_namelen(ce) == namelen &&
974 !memcmp(ce->name, filename, namelen))
975 die("Path '%s' is in the index, but not at stage %d.\n"
976 "Did you mean ':%d:%s'?",
977 filename, stage,
978 ce_stage(ce), filename);
980 /* Confusion between relative and absolute filenames? */
981 fullnamelen = namelen + strlen(prefix);
982 fullname = xmalloc(fullnamelen + 1);
983 strcpy(fullname, prefix);
984 strcat(fullname, filename);
985 pos = cache_name_pos(fullname, fullnamelen);
986 if (pos < 0)
987 pos = -pos - 1;
988 ce = active_cache[pos];
989 if (ce_namelen(ce) == fullnamelen &&
990 !memcmp(ce->name, fullname, fullnamelen))
991 die("Path '%s' is in the index, but not '%s'.\n"
992 "Did you mean ':%d:%s'?",
993 fullname, filename,
994 ce_stage(ce), fullname);
996 if (!lstat(filename, &st))
997 die("Path '%s' exists on disk, but not in the index.", filename);
998 if (errno == ENOENT || errno == ENOTDIR)
999 die("Path '%s' does not exist (neither on disk nor in the index).",
1000 filename);
1002 free(fullname);
1006 int get_sha1_with_mode_1(const char *name, unsigned char *sha1, unsigned *mode, int gently, const char *prefix)
1008 int ret, bracket_depth;
1009 int namelen = strlen(name);
1010 const char *cp;
1012 *mode = S_IFINVALID;
1013 ret = get_sha1_1(name, namelen, sha1);
1014 if (!ret)
1015 return ret;
1016 /* sha1:path --> object name of path in ent sha1
1017 * :path -> object name of path in index
1018 * :[0-3]:path -> object name of path in index at stage
1020 if (name[0] == ':') {
1021 int stage = 0;
1022 struct cache_entry *ce;
1023 int pos;
1024 if (namelen > 2 && name[1] == '/')
1025 return get_sha1_oneline(name + 2, sha1);
1026 if (namelen < 3 ||
1027 name[2] != ':' ||
1028 name[1] < '0' || '3' < name[1])
1029 cp = name + 1;
1030 else {
1031 stage = name[1] - '0';
1032 cp = name + 3;
1034 namelen = namelen - (cp - name);
1035 if (!active_cache)
1036 read_cache();
1037 pos = cache_name_pos(cp, namelen);
1038 if (pos < 0)
1039 pos = -pos - 1;
1040 while (pos < active_nr) {
1041 ce = active_cache[pos];
1042 if (ce_namelen(ce) != namelen ||
1043 memcmp(ce->name, cp, namelen))
1044 break;
1045 if (ce_stage(ce) == stage) {
1046 hashcpy(sha1, ce->sha1);
1047 *mode = ce->ce_mode;
1048 return 0;
1050 pos++;
1052 if (!gently)
1053 diagnose_invalid_index_path(stage, prefix, cp);
1054 return -1;
1056 for (cp = name, bracket_depth = 0; *cp; cp++) {
1057 if (*cp == '{')
1058 bracket_depth++;
1059 else if (bracket_depth && *cp == '}')
1060 bracket_depth--;
1061 else if (!bracket_depth && *cp == ':')
1062 break;
1064 if (*cp == ':') {
1065 unsigned char tree_sha1[20];
1066 char *object_name = NULL;
1067 if (!gently) {
1068 object_name = xmalloc(cp-name+1);
1069 strncpy(object_name, name, cp-name);
1070 object_name[cp-name] = '\0';
1072 if (!get_sha1_1(name, cp-name, tree_sha1)) {
1073 const char *filename = cp+1;
1074 ret = get_tree_entry(tree_sha1, filename, sha1, mode);
1075 if (!gently) {
1076 diagnose_invalid_sha1_path(prefix, filename,
1077 tree_sha1, object_name);
1078 free(object_name);
1080 return ret;
1081 } else {
1082 if (!gently)
1083 die("Invalid object name '%s'.", object_name);
1086 return ret;