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