reject @{-1} not at beginning of object name
[git] / sha1_name.c
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
10 static int find_short_object_filename(int len, const char *name, unsigned char *sha1)
11 {
12         struct alternate_object_database *alt;
13         char hex[40];
14         int found = 0;
15         static struct alternate_object_database *fakeent;
16
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] = '/';
25         }
26         fakeent->next = alt_odb_list;
27
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++;
44                         }
45                         else if (memcmp(hex + 2, de->d_name, 38)) {
46                                 found = 2;
47                                 break;
48                         }
49                 }
50                 closedir(dir);
51         }
52         if (found == 1)
53                 return get_sha1_hex(hex, sha1) == 0;
54         return found;
55 }
56
57 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
58 {
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;
70 }
71
72 static int find_short_packed_object(int len, const unsigned char *match, unsigned char *sha1)
73 {
74         struct packed_git *p;
75         const unsigned char *found_sha1 = NULL;
76         int found = 0;
77
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;
89
90                         now = nth_packed_object_sha1(p, mid);
91                         cmp = hashcmp(match, now);
92                         if (!cmp) {
93                                 first = mid;
94                                 break;
95                         }
96                         if (cmp > 0) {
97                                 first = mid+1;
98                                 continue;
99                         }
100                         last = mid;
101                 }
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++;
112                                         }
113                                         else if (hashcmp(found_sha1, now)) {
114                                                 found = 2;
115                                                 break;
116                                         }
117                                 }
118                                 else {
119                                         /* not even unique within this pack */
120                                         found = 2;
121                                         break;
122                                 }
123                         }
124                 }
125         }
126         if (found == 1)
127                 hashcpy(sha1, found_sha1);
128         return found;
129 }
130
131 #define SHORT_NAME_NOT_FOUND (-1)
132 #define SHORT_NAME_AMBIGUOUS (-2)
133
134 static int find_unique_short_object(int len, char *canonical,
135                                     unsigned char *res, unsigned char *sha1)
136 {
137         int has_unpacked, has_packed;
138         unsigned char unpacked_sha1[20], packed_sha1[20];
139
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;
150         }
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;
156 }
157
158 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
159                           int quietly)
160 {
161         int i, status;
162         char canonical[40];
163         unsigned char res[20];
164
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';
179                 }
180                 else
181                         return -1;
182                 canonical[i] = c;
183                 if (!(i & 1))
184                         val <<= 4;
185                 res[i >> 1] |= val;
186         }
187
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;
192 }
193
194 const char *find_unique_abbrev(const unsigned char *sha1, int len)
195 {
196         int status, exists;
197         static char hex[41];
198
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;
211                 }
212                 len++;
213         }
214         return hex;
215 }
216
217 static int ambiguous_path(const char *path, int len)
218 {
219         int slash = 1;
220         int cnt;
221
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;
236                 }
237                 break;
238         }
239         return slash;
240 }
241
242 /*
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.
246  */
247 static char *substitute_branch_name(const char **string, int *len)
248 {
249         struct strbuf buf = STRBUF_INIT;
250         int ret = interpret_branch_name(*string, &buf);
251
252         if (ret == *len) {
253                 size_t size;
254                 *string = strbuf_detach(&buf, &size);
255                 *len = size;
256                 return (char *)*string;
257         }
258
259         return NULL;
260 }
261
262 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
263 {
264         char *last_branch = substitute_branch_name(&str, &len);
265         const char **p, *r;
266         int refs_found = 0;
267
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;
274
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);
286         }
287         free(last_branch);
288         return refs_found;
289 }
290
291 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
292 {
293         char *last_branch = substitute_branch_name(&str, &len);
294         const char **p;
295         int logs_found = 0;
296
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;
303
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);
320                 }
321                 if (!warn_ambiguous_refs)
322                         break;
323         }
324         free(last_branch);
325         return logs_found;
326 }
327
328 static inline int upstream_mark(const char *string, int len)
329 {
330         const char *suffix[] = { "@{upstream}", "@{u}" };
331         int i;
332
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;
338         }
339         return 0;
340 }
341
342 static int get_sha1_1(const char *name, int len, unsigned char *sha1);
343
344 static int get_sha1_basic(const char *str, int len, unsigned char *sha1)
345 {
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;
350
351         if (len == 40 && !get_sha1_hex(str, sha1))
352                 return 0;
353
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;
362                                 }
363                                 break;
364                         }
365                 }
366         }
367
368         /* Accept only unambiguous ref paths. */
369         if (len && ambiguous_path(str, len))
370                 return -1;
371
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;
382                 }
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);
389
390         if (!refs_found)
391                 return -1;
392
393         if (warn_ambiguous_refs && refs_found > 1)
394                 fprintf(stderr, warning, len, str);
395
396         if (reflog_len) {
397                 int nth, i;
398                 unsigned long at_time;
399                 unsigned long co_time;
400                 int co_tz, co_cnt;
401
402                 /* a @{-N} placed anywhere except the start is an error */
403                 if (str[at+2] == '-')
404                         return -1;
405
406                 /* Is it asking for N-th entry, or approxidate? */
407                 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
408                         char ch = str[at+2+i];
409                         if ('0' <= ch && ch <= '9')
410                                 nth = nth * 10 + ch - '0';
411                         else
412                                 nth = -1;
413                 }
414                 if (100000000 <= nth) {
415                         at_time = nth;
416                         nth = -1;
417                 } else if (0 <= nth)
418                         at_time = 0;
419                 else {
420                         int errors = 0;
421                         char *tmp = xstrndup(str + at + 2, reflog_len);
422                         at_time = approxidate_careful(tmp, &errors);
423                         free(tmp);
424                         if (errors)
425                                 return -1;
426                 }
427                 if (read_ref_at(real_ref, at_time, nth, sha1, NULL,
428                                 &co_time, &co_tz, &co_cnt)) {
429                         if (at_time)
430                                 fprintf(stderr,
431                                         "warning: Log for '%.*s' only goes "
432                                         "back to %s.\n", len, str,
433                                         show_date(co_time, co_tz, DATE_RFC2822));
434                         else
435                                 fprintf(stderr,
436                                         "warning: Log for '%.*s' only has "
437                                         "%d entries.\n", len, str, co_cnt);
438                 }
439         }
440
441         free(real_ref);
442         return 0;
443 }
444
445 static int get_parent(const char *name, int len,
446                       unsigned char *result, int idx)
447 {
448         unsigned char sha1[20];
449         int ret = get_sha1_1(name, len, sha1);
450         struct commit *commit;
451         struct commit_list *p;
452
453         if (ret)
454                 return ret;
455         commit = lookup_commit_reference(sha1);
456         if (!commit)
457                 return -1;
458         if (parse_commit(commit))
459                 return -1;
460         if (!idx) {
461                 hashcpy(result, commit->object.sha1);
462                 return 0;
463         }
464         p = commit->parents;
465         while (p) {
466                 if (!--idx) {
467                         hashcpy(result, p->item->object.sha1);
468                         return 0;
469                 }
470                 p = p->next;
471         }
472         return -1;
473 }
474
475 static int get_nth_ancestor(const char *name, int len,
476                             unsigned char *result, int generation)
477 {
478         unsigned char sha1[20];
479         struct commit *commit;
480         int ret;
481
482         ret = get_sha1_1(name, len, sha1);
483         if (ret)
484                 return ret;
485         commit = lookup_commit_reference(sha1);
486         if (!commit)
487                 return -1;
488
489         while (generation--) {
490                 if (parse_commit(commit) || !commit->parents)
491                         return -1;
492                 commit = commit->parents->item;
493         }
494         hashcpy(result, commit->object.sha1);
495         return 0;
496 }
497
498 struct object *peel_to_type(const char *name, int namelen,
499                             struct object *o, enum object_type expected_type)
500 {
501         if (name && !namelen)
502                 namelen = strlen(name);
503         if (!o) {
504                 unsigned char sha1[20];
505                 if (get_sha1_1(name, namelen, sha1))
506                         return NULL;
507                 o = parse_object(sha1);
508         }
509         while (1) {
510                 if (!o || (!o->parsed && !parse_object(o->sha1)))
511                         return NULL;
512                 if (o->type == expected_type)
513                         return o;
514                 if (o->type == OBJ_TAG)
515                         o = ((struct tag*) o)->tagged;
516                 else if (o->type == OBJ_COMMIT)
517                         o = &(((struct commit *) o)->tree->object);
518                 else {
519                         if (name)
520                                 error("%.*s: expected %s type, but the object "
521                                       "dereferences to %s type",
522                                       namelen, name, typename(expected_type),
523                                       typename(o->type));
524                         return NULL;
525                 }
526         }
527 }
528
529 static int peel_onion(const char *name, int len, unsigned char *sha1)
530 {
531         unsigned char outer[20];
532         const char *sp;
533         unsigned int expected_type = 0;
534         struct object *o;
535
536         /*
537          * "ref^{type}" dereferences ref repeatedly until you cannot
538          * dereference anymore, or you get an object of given type,
539          * whichever comes first.  "ref^{}" means just dereference
540          * tags until you get a non-tag.  "ref^0" is a shorthand for
541          * "ref^{commit}".  "commit^{tree}" could be used to find the
542          * top-level tree of the given commit.
543          */
544         if (len < 4 || name[len-1] != '}')
545                 return -1;
546
547         for (sp = name + len - 1; name <= sp; sp--) {
548                 int ch = *sp;
549                 if (ch == '{' && name < sp && sp[-1] == '^')
550                         break;
551         }
552         if (sp <= name)
553                 return -1;
554
555         sp++; /* beginning of type name, or closing brace for empty */
556         if (!strncmp(commit_type, sp, 6) && sp[6] == '}')
557                 expected_type = OBJ_COMMIT;
558         else if (!strncmp(tree_type, sp, 4) && sp[4] == '}')
559                 expected_type = OBJ_TREE;
560         else if (!strncmp(blob_type, sp, 4) && sp[4] == '}')
561                 expected_type = OBJ_BLOB;
562         else if (sp[0] == '}')
563                 expected_type = OBJ_NONE;
564         else
565                 return -1;
566
567         if (get_sha1_1(name, sp - name - 2, outer))
568                 return -1;
569
570         o = parse_object(outer);
571         if (!o)
572                 return -1;
573         if (!expected_type) {
574                 o = deref_tag(o, name, sp - name - 2);
575                 if (!o || (!o->parsed && !parse_object(o->sha1)))
576                         return -1;
577                 hashcpy(sha1, o->sha1);
578         }
579         else {
580                 /*
581                  * At this point, the syntax look correct, so
582                  * if we do not get the needed object, we should
583                  * barf.
584                  */
585                 o = peel_to_type(name, len, o, expected_type);
586                 if (o) {
587                         hashcpy(sha1, o->sha1);
588                         return 0;
589                 }
590                 return -1;
591         }
592         return 0;
593 }
594
595 static int get_describe_name(const char *name, int len, unsigned char *sha1)
596 {
597         const char *cp;
598
599         for (cp = name + len - 1; name + 2 <= cp; cp--) {
600                 char ch = *cp;
601                 if (hexval(ch) & ~0377) {
602                         /* We must be looking at g in "SOMETHING-g"
603                          * for it to be describe output.
604                          */
605                         if (ch == 'g' && cp[-1] == '-') {
606                                 cp++;
607                                 len -= cp - name;
608                                 return get_short_sha1(cp, len, sha1, 1);
609                         }
610                 }
611         }
612         return -1;
613 }
614
615 static int get_sha1_1(const char *name, int len, unsigned char *sha1)
616 {
617         int ret, has_suffix;
618         const char *cp;
619
620         /*
621          * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
622          */
623         has_suffix = 0;
624         for (cp = name + len - 1; name <= cp; cp--) {
625                 int ch = *cp;
626                 if ('0' <= ch && ch <= '9')
627                         continue;
628                 if (ch == '~' || ch == '^')
629                         has_suffix = ch;
630                 break;
631         }
632
633         if (has_suffix) {
634                 int num = 0;
635                 int len1 = cp - name;
636                 cp++;
637                 while (cp < name + len)
638                         num = num * 10 + *cp++ - '0';
639                 if (!num && len1 == len - 1)
640                         num = 1;
641                 if (has_suffix == '^')
642                         return get_parent(name, len1, sha1, num);
643                 /* else if (has_suffix == '~') -- goes without saying */
644                 return get_nth_ancestor(name, len1, sha1, num);
645         }
646
647         ret = peel_onion(name, len, sha1);
648         if (!ret)
649                 return 0;
650
651         ret = get_sha1_basic(name, len, sha1);
652         if (!ret)
653                 return 0;
654
655         /* It could be describe output that is "SOMETHING-gXXXX" */
656         ret = get_describe_name(name, len, sha1);
657         if (!ret)
658                 return 0;
659
660         return get_short_sha1(name, len, sha1, 0);
661 }
662
663 static int handle_one_ref(const char *path,
664                 const unsigned char *sha1, int flag, void *cb_data)
665 {
666         struct commit_list **list = cb_data;
667         struct object *object = parse_object(sha1);
668         if (!object)
669                 return 0;
670         if (object->type == OBJ_TAG) {
671                 object = deref_tag(object, path, strlen(path));
672                 if (!object)
673                         return 0;
674         }
675         if (object->type != OBJ_COMMIT)
676                 return 0;
677         insert_by_date((struct commit *)object, list);
678         return 0;
679 }
680
681 /*
682  * This interprets names like ':/Initial revision of "git"' by searching
683  * through history and returning the first commit whose message starts
684  * with the given string.
685  *
686  * For future extension, ':/!' is reserved. If you want to match a message
687  * beginning with a '!', you have to repeat the exclamation mark.
688  */
689
690 #define ONELINE_SEEN (1u<<20)
691 static int get_sha1_oneline(const char *prefix, unsigned char *sha1)
692 {
693         struct commit_list *list = NULL, *backup = NULL, *l;
694         int retval = -1;
695         char *temp_commit_buffer = NULL;
696
697         if (prefix[0] == '!') {
698                 if (prefix[1] != '!')
699                         die ("Invalid search pattern: %s", prefix);
700                 prefix++;
701         }
702         for_each_ref(handle_one_ref, &list);
703         for (l = list; l; l = l->next)
704                 commit_list_insert(l->item, &backup);
705         while (list) {
706                 char *p;
707                 struct commit *commit;
708                 enum object_type type;
709                 unsigned long size;
710
711                 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
712                 if (!parse_object(commit->object.sha1))
713                         continue;
714                 free(temp_commit_buffer);
715                 if (commit->buffer)
716                         p = commit->buffer;
717                 else {
718                         p = read_sha1_file(commit->object.sha1, &type, &size);
719                         if (!p)
720                                 continue;
721                         temp_commit_buffer = p;
722                 }
723                 if (!(p = strstr(p, "\n\n")))
724                         continue;
725                 if (!prefixcmp(p + 2, prefix)) {
726                         hashcpy(sha1, commit->object.sha1);
727                         retval = 0;
728                         break;
729                 }
730         }
731         free(temp_commit_buffer);
732         free_commit_list(list);
733         for (l = backup; l; l = l->next)
734                 clear_commit_marks(l->item, ONELINE_SEEN);
735         return retval;
736 }
737
738 struct grab_nth_branch_switch_cbdata {
739         long cnt, alloc;
740         struct strbuf *buf;
741 };
742
743 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
744                                   const char *email, unsigned long timestamp, int tz,
745                                   const char *message, void *cb_data)
746 {
747         struct grab_nth_branch_switch_cbdata *cb = cb_data;
748         const char *match = NULL, *target = NULL;
749         size_t len;
750         int nth;
751
752         if (!prefixcmp(message, "checkout: moving from ")) {
753                 match = message + strlen("checkout: moving from ");
754                 target = strstr(match, " to ");
755         }
756
757         if (!match || !target)
758                 return 0;
759
760         len = target - match;
761         nth = cb->cnt++ % cb->alloc;
762         strbuf_reset(&cb->buf[nth]);
763         strbuf_add(&cb->buf[nth], match, len);
764         return 0;
765 }
766
767 /*
768  * Parse @{-N} syntax, return the number of characters parsed
769  * if successful; otherwise signal an error with negative value.
770  */
771 static int interpret_nth_prior_checkout(const char *name, struct strbuf *buf)
772 {
773         long nth;
774         int i, retval;
775         struct grab_nth_branch_switch_cbdata cb;
776         const char *brace;
777         char *num_end;
778
779         if (name[0] != '@' || name[1] != '{' || name[2] != '-')
780                 return -1;
781         brace = strchr(name, '}');
782         if (!brace)
783                 return -1;
784         nth = strtol(name+3, &num_end, 10);
785         if (num_end != brace)
786                 return -1;
787         if (nth <= 0)
788                 return -1;
789         cb.alloc = nth;
790         cb.buf = xmalloc(nth * sizeof(struct strbuf));
791         for (i = 0; i < nth; i++)
792                 strbuf_init(&cb.buf[i], 20);
793         cb.cnt = 0;
794         retval = 0;
795         for_each_recent_reflog_ent("HEAD", grab_nth_branch_switch, 40960, &cb);
796         if (cb.cnt < nth) {
797                 cb.cnt = 0;
798                 for_each_reflog_ent("HEAD", grab_nth_branch_switch, &cb);
799         }
800         if (cb.cnt < nth)
801                 goto release_return;
802         i = cb.cnt % nth;
803         strbuf_reset(buf);
804         strbuf_add(buf, cb.buf[i].buf, cb.buf[i].len);
805         retval = brace-name+1;
806
807 release_return:
808         for (i = 0; i < nth; i++)
809                 strbuf_release(&cb.buf[i]);
810         free(cb.buf);
811
812         return retval;
813 }
814
815 int get_sha1_mb(const char *name, unsigned char *sha1)
816 {
817         struct commit *one, *two;
818         struct commit_list *mbs;
819         unsigned char sha1_tmp[20];
820         const char *dots;
821         int st;
822
823         dots = strstr(name, "...");
824         if (!dots)
825                 return get_sha1(name, sha1);
826         if (dots == name)
827                 st = get_sha1("HEAD", sha1_tmp);
828         else {
829                 struct strbuf sb;
830                 strbuf_init(&sb, dots - name);
831                 strbuf_add(&sb, name, dots - name);
832                 st = get_sha1(sb.buf, sha1_tmp);
833                 strbuf_release(&sb);
834         }
835         if (st)
836                 return st;
837         one = lookup_commit_reference_gently(sha1_tmp, 0);
838         if (!one)
839                 return -1;
840
841         if (get_sha1(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
842                 return -1;
843         two = lookup_commit_reference_gently(sha1_tmp, 0);
844         if (!two)
845                 return -1;
846         mbs = get_merge_bases(one, two, 1);
847         if (!mbs || mbs->next)
848                 st = -1;
849         else {
850                 st = 0;
851                 hashcpy(sha1, mbs->item->object.sha1);
852         }
853         free_commit_list(mbs);
854         return st;
855 }
856
857 /*
858  * This reads short-hand syntax that not only evaluates to a commit
859  * object name, but also can act as if the end user spelled the name
860  * of the branch from the command line.
861  *
862  * - "@{-N}" finds the name of the Nth previous branch we were on, and
863  *   places the name of the branch in the given buf and returns the
864  *   number of characters parsed if successful.
865  *
866  * - "<branch>@{upstream}" finds the name of the other ref that
867  *   <branch> is configured to merge with (missing <branch> defaults
868  *   to the current branch), and places the name of the branch in the
869  *   given buf and returns the number of characters parsed if
870  *   successful.
871  *
872  * If the input is not of the accepted format, it returns a negative
873  * number to signal an error.
874  *
875  * If the input was ok but there are not N branch switches in the
876  * reflog, it returns 0.
877  */
878 int interpret_branch_name(const char *name, struct strbuf *buf)
879 {
880         char *cp;
881         struct branch *upstream;
882         int namelen = strlen(name);
883         int len = interpret_nth_prior_checkout(name, buf);
884         int tmp_len;
885
886         if (!len)
887                 return len; /* syntax Ok, not enough switches */
888         if (0 < len && len == namelen)
889                 return len; /* consumed all */
890         else if (0 < len) {
891                 /* we have extra data, which might need further processing */
892                 struct strbuf tmp = STRBUF_INIT;
893                 int used = buf->len;
894                 int ret;
895
896                 strbuf_add(buf, name + len, namelen - len);
897                 ret = interpret_branch_name(buf->buf, &tmp);
898                 /* that data was not interpreted, remove our cruft */
899                 if (ret < 0) {
900                         strbuf_setlen(buf, used);
901                         return len;
902                 }
903                 strbuf_reset(buf);
904                 strbuf_addbuf(buf, &tmp);
905                 strbuf_release(&tmp);
906                 /* tweak for size of {-N} versus expanded ref name */
907                 return ret - used + len;
908         }
909
910         cp = strchr(name, '@');
911         if (!cp)
912                 return -1;
913         tmp_len = upstream_mark(cp, namelen - (cp - name));
914         if (!tmp_len)
915                 return -1;
916         len = cp + tmp_len - name;
917         cp = xstrndup(name, cp - name);
918         upstream = branch_get(*cp ? cp : NULL);
919         if (!upstream
920             || !upstream->merge
921             || !upstream->merge[0]->dst)
922                 return error("No upstream branch found for '%s'", cp);
923         free(cp);
924         cp = shorten_unambiguous_ref(upstream->merge[0]->dst, 0);
925         strbuf_reset(buf);
926         strbuf_addstr(buf, cp);
927         free(cp);
928         return len;
929 }
930
931 /*
932  * This is like "get_sha1_basic()", except it allows "sha1 expressions",
933  * notably "xyz^" for "parent of xyz"
934  */
935 int get_sha1(const char *name, unsigned char *sha1)
936 {
937         unsigned unused;
938         return get_sha1_with_mode(name, sha1, &unused);
939 }
940
941 /* Must be called only when object_name:filename doesn't exist. */
942 static void diagnose_invalid_sha1_path(const char *prefix,
943                                        const char *filename,
944                                        const unsigned char *tree_sha1,
945                                        const char *object_name)
946 {
947         struct stat st;
948         unsigned char sha1[20];
949         unsigned mode;
950
951         if (!prefix)
952                 prefix = "";
953
954         if (!lstat(filename, &st))
955                 die("Path '%s' exists on disk, but not in '%s'.",
956                     filename, object_name);
957         if (errno == ENOENT || errno == ENOTDIR) {
958                 char *fullname = xmalloc(strlen(filename)
959                                              + strlen(prefix) + 1);
960                 strcpy(fullname, prefix);
961                 strcat(fullname, filename);
962
963                 if (!get_tree_entry(tree_sha1, fullname,
964                                     sha1, &mode)) {
965                         die("Path '%s' exists, but not '%s'.\n"
966                             "Did you mean '%s:%s'?",
967                             fullname,
968                             filename,
969                             object_name,
970                             fullname);
971                 }
972                 die("Path '%s' does not exist in '%s'",
973                     filename, object_name);
974         }
975 }
976
977 /* Must be called only when :stage:filename doesn't exist. */
978 static void diagnose_invalid_index_path(int stage,
979                                         const char *prefix,
980                                         const char *filename)
981 {
982         struct stat st;
983         struct cache_entry *ce;
984         int pos;
985         unsigned namelen = strlen(filename);
986         unsigned fullnamelen;
987         char *fullname;
988
989         if (!prefix)
990                 prefix = "";
991
992         /* Wrong stage number? */
993         pos = cache_name_pos(filename, namelen);
994         if (pos < 0)
995                 pos = -pos - 1;
996         ce = active_cache[pos];
997         if (ce_namelen(ce) == namelen &&
998             !memcmp(ce->name, filename, namelen))
999                 die("Path '%s' is in the index, but not at stage %d.\n"
1000                     "Did you mean ':%d:%s'?",
1001                     filename, stage,
1002                     ce_stage(ce), filename);
1003
1004         /* Confusion between relative and absolute filenames? */
1005         fullnamelen = namelen + strlen(prefix);
1006         fullname = xmalloc(fullnamelen + 1);
1007         strcpy(fullname, prefix);
1008         strcat(fullname, filename);
1009         pos = cache_name_pos(fullname, fullnamelen);
1010         if (pos < 0)
1011                 pos = -pos - 1;
1012         ce = active_cache[pos];
1013         if (ce_namelen(ce) == fullnamelen &&
1014             !memcmp(ce->name, fullname, fullnamelen))
1015                 die("Path '%s' is in the index, but not '%s'.\n"
1016                     "Did you mean ':%d:%s'?",
1017                     fullname, filename,
1018                     ce_stage(ce), fullname);
1019
1020         if (!lstat(filename, &st))
1021                 die("Path '%s' exists on disk, but not in the index.", filename);
1022         if (errno == ENOENT || errno == ENOTDIR)
1023                 die("Path '%s' does not exist (neither on disk nor in the index).",
1024                     filename);
1025
1026         free(fullname);
1027 }
1028
1029
1030 int get_sha1_with_mode_1(const char *name, unsigned char *sha1, unsigned *mode, int gently, const char *prefix)
1031 {
1032         int ret, bracket_depth;
1033         int namelen = strlen(name);
1034         const char *cp;
1035
1036         *mode = S_IFINVALID;
1037         ret = get_sha1_1(name, namelen, sha1);
1038         if (!ret)
1039                 return ret;
1040         /* sha1:path --> object name of path in ent sha1
1041          * :path -> object name of path in index
1042          * :[0-3]:path -> object name of path in index at stage
1043          */
1044         if (name[0] == ':') {
1045                 int stage = 0;
1046                 struct cache_entry *ce;
1047                 int pos;
1048                 if (namelen > 2 && name[1] == '/')
1049                         return get_sha1_oneline(name + 2, sha1);
1050                 if (namelen < 3 ||
1051                     name[2] != ':' ||
1052                     name[1] < '0' || '3' < name[1])
1053                         cp = name + 1;
1054                 else {
1055                         stage = name[1] - '0';
1056                         cp = name + 3;
1057                 }
1058                 namelen = namelen - (cp - name);
1059                 if (!active_cache)
1060                         read_cache();
1061                 pos = cache_name_pos(cp, namelen);
1062                 if (pos < 0)
1063                         pos = -pos - 1;
1064                 while (pos < active_nr) {
1065                         ce = active_cache[pos];
1066                         if (ce_namelen(ce) != namelen ||
1067                             memcmp(ce->name, cp, namelen))
1068                                 break;
1069                         if (ce_stage(ce) == stage) {
1070                                 hashcpy(sha1, ce->sha1);
1071                                 *mode = ce->ce_mode;
1072                                 return 0;
1073                         }
1074                         pos++;
1075                 }
1076                 if (!gently)
1077                         diagnose_invalid_index_path(stage, prefix, cp);
1078                 return -1;
1079         }
1080         for (cp = name, bracket_depth = 0; *cp; cp++) {
1081                 if (*cp == '{')
1082                         bracket_depth++;
1083                 else if (bracket_depth && *cp == '}')
1084                         bracket_depth--;
1085                 else if (!bracket_depth && *cp == ':')
1086                         break;
1087         }
1088         if (*cp == ':') {
1089                 unsigned char tree_sha1[20];
1090                 char *object_name = NULL;
1091                 if (!gently) {
1092                         object_name = xmalloc(cp-name+1);
1093                         strncpy(object_name, name, cp-name);
1094                         object_name[cp-name] = '\0';
1095                 }
1096                 if (!get_sha1_1(name, cp-name, tree_sha1)) {
1097                         const char *filename = cp+1;
1098                         ret = get_tree_entry(tree_sha1, filename, sha1, mode);
1099                         if (!gently) {
1100                                 diagnose_invalid_sha1_path(prefix, filename,
1101                                                            tree_sha1, object_name);
1102                                 free(object_name);
1103                         }
1104                         return ret;
1105                 } else {
1106                         if (!gently)
1107                                 die("Invalid object name '%s'.", object_name);
1108                 }
1109         }
1110         return ret;
1111 }