Merge branch 'jp/get-ref-dir-unsorted'
[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 get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
11
12 static int find_short_object_filename(int len, const char *name, unsigned char *sha1)
13 {
14         struct alternate_object_database *alt;
15         char hex[40];
16         int found = 0;
17         static struct alternate_object_database *fakeent;
18
19         if (!fakeent) {
20                 const char *objdir = get_object_directory();
21                 int objdir_len = strlen(objdir);
22                 int entlen = objdir_len + 43;
23                 fakeent = xmalloc(sizeof(*fakeent) + entlen);
24                 memcpy(fakeent->base, objdir, objdir_len);
25                 fakeent->name = fakeent->base + objdir_len + 1;
26                 fakeent->name[-1] = '/';
27         }
28         fakeent->next = alt_odb_list;
29
30         sprintf(hex, "%.2s", name);
31         for (alt = fakeent; alt && found < 2; alt = alt->next) {
32                 struct dirent *de;
33                 DIR *dir;
34                 sprintf(alt->name, "%.2s/", name);
35                 dir = opendir(alt->base);
36                 if (!dir)
37                         continue;
38                 while ((de = readdir(dir)) != NULL) {
39                         if (strlen(de->d_name) != 38)
40                                 continue;
41                         if (memcmp(de->d_name, name + 2, len - 2))
42                                 continue;
43                         if (!found) {
44                                 memcpy(hex + 2, de->d_name, 38);
45                                 found++;
46                         }
47                         else if (memcmp(hex + 2, de->d_name, 38)) {
48                                 found = 2;
49                                 break;
50                         }
51                 }
52                 closedir(dir);
53         }
54         if (found == 1)
55                 return get_sha1_hex(hex, sha1) == 0;
56         return found;
57 }
58
59 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
60 {
61         do {
62                 if (*a != *b)
63                         return 0;
64                 a++;
65                 b++;
66                 len -= 2;
67         } while (len > 1);
68         if (len)
69                 if ((*a ^ *b) & 0xf0)
70                         return 0;
71         return 1;
72 }
73
74 static int find_short_packed_object(int len, const unsigned char *match, unsigned char *sha1)
75 {
76         struct packed_git *p;
77         const unsigned char *found_sha1 = NULL;
78         int found = 0;
79
80         prepare_packed_git();
81         for (p = packed_git; p && found < 2; p = p->next) {
82                 uint32_t num, last;
83                 uint32_t first = 0;
84                 open_pack_index(p);
85                 num = p->num_objects;
86                 last = num;
87                 while (first < last) {
88                         uint32_t mid = (first + last) / 2;
89                         const unsigned char *now;
90                         int cmp;
91
92                         now = nth_packed_object_sha1(p, mid);
93                         cmp = hashcmp(match, now);
94                         if (!cmp) {
95                                 first = mid;
96                                 break;
97                         }
98                         if (cmp > 0) {
99                                 first = mid+1;
100                                 continue;
101                         }
102                         last = mid;
103                 }
104                 if (first < num) {
105                         const unsigned char *now, *next;
106                        now = nth_packed_object_sha1(p, first);
107                         if (match_sha(len, match, now)) {
108                                 next = nth_packed_object_sha1(p, first+1);
109                                if (!next|| !match_sha(len, match, next)) {
110                                         /* unique within this pack */
111                                         if (!found) {
112                                                 found_sha1 = now;
113                                                 found++;
114                                         }
115                                         else if (hashcmp(found_sha1, now)) {
116                                                 found = 2;
117                                                 break;
118                                         }
119                                 }
120                                 else {
121                                         /* not even unique within this pack */
122                                         found = 2;
123                                         break;
124                                 }
125                         }
126                 }
127         }
128         if (found == 1)
129                 hashcpy(sha1, found_sha1);
130         return found;
131 }
132
133 #define SHORT_NAME_NOT_FOUND (-1)
134 #define SHORT_NAME_AMBIGUOUS (-2)
135
136 static int find_unique_short_object(int len, char *canonical,
137                                     unsigned char *res, unsigned char *sha1)
138 {
139         int has_unpacked, has_packed;
140         unsigned char unpacked_sha1[20], packed_sha1[20];
141
142         prepare_alt_odb();
143         has_unpacked = find_short_object_filename(len, canonical, unpacked_sha1);
144         has_packed = find_short_packed_object(len, res, packed_sha1);
145         if (!has_unpacked && !has_packed)
146                 return SHORT_NAME_NOT_FOUND;
147         if (1 < has_unpacked || 1 < has_packed)
148                 return SHORT_NAME_AMBIGUOUS;
149         if (has_unpacked != has_packed) {
150                 hashcpy(sha1, (has_packed ? packed_sha1 : unpacked_sha1));
151                 return 0;
152         }
153         /* Both have unique ones -- do they match? */
154         if (hashcmp(packed_sha1, unpacked_sha1))
155                 return SHORT_NAME_AMBIGUOUS;
156         hashcpy(sha1, packed_sha1);
157         return 0;
158 }
159
160 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
161                           int quietly)
162 {
163         int i, status;
164         char canonical[40];
165         unsigned char res[20];
166
167         if (len < MINIMUM_ABBREV || len > 40)
168                 return -1;
169         hashclr(res);
170         memset(canonical, 'x', 40);
171         for (i = 0; i < len ;i++) {
172                 unsigned char c = name[i];
173                 unsigned char val;
174                 if (c >= '0' && c <= '9')
175                         val = c - '0';
176                 else if (c >= 'a' && c <= 'f')
177                         val = c - 'a' + 10;
178                 else if (c >= 'A' && c <='F') {
179                         val = c - 'A' + 10;
180                         c -= 'A' - 'a';
181                 }
182                 else
183                         return -1;
184                 canonical[i] = c;
185                 if (!(i & 1))
186                         val <<= 4;
187                 res[i >> 1] |= val;
188         }
189
190         status = find_unique_short_object(i, canonical, res, sha1);
191         if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
192                 return error("short SHA1 %.*s is ambiguous.", len, canonical);
193         return status;
194 }
195
196 const char *find_unique_abbrev(const unsigned char *sha1, int len)
197 {
198         int status, exists;
199         static char hex[41];
200
201         exists = has_sha1_file(sha1);
202         memcpy(hex, sha1_to_hex(sha1), 40);
203         if (len == 40 || !len)
204                 return hex;
205         while (len < 40) {
206                 unsigned char sha1_ret[20];
207                 status = get_short_sha1(hex, len, sha1_ret, 1);
208                 if (exists
209                     ? !status
210                     : status == SHORT_NAME_NOT_FOUND) {
211                         hex[len] = 0;
212                         return hex;
213                 }
214                 len++;
215         }
216         return hex;
217 }
218
219 static int ambiguous_path(const char *path, int len)
220 {
221         int slash = 1;
222         int cnt;
223
224         for (cnt = 0; cnt < len; cnt++) {
225                 switch (*path++) {
226                 case '\0':
227                         break;
228                 case '/':
229                         if (slash)
230                                 break;
231                         slash = 1;
232                         continue;
233                 case '.':
234                         continue;
235                 default:
236                         slash = 0;
237                         continue;
238                 }
239                 break;
240         }
241         return slash;
242 }
243
244 /*
245  * *string and *len will only be substituted, and *string returned (for
246  * later free()ing) if the string passed in is a magic short-hand form
247  * to name a branch.
248  */
249 static char *substitute_branch_name(const char **string, int *len)
250 {
251         struct strbuf buf = STRBUF_INIT;
252         int ret = interpret_branch_name(*string, &buf);
253
254         if (ret == *len) {
255                 size_t size;
256                 *string = strbuf_detach(&buf, &size);
257                 *len = size;
258                 return (char *)*string;
259         }
260
261         return NULL;
262 }
263
264 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
265 {
266         char *last_branch = substitute_branch_name(&str, &len);
267         const char **p, *r;
268         int refs_found = 0;
269
270         *ref = NULL;
271         for (p = ref_rev_parse_rules; *p; p++) {
272                 char fullref[PATH_MAX];
273                 unsigned char sha1_from_ref[20];
274                 unsigned char *this_result;
275                 int flag;
276
277                 this_result = refs_found ? sha1_from_ref : sha1;
278                 mksnpath(fullref, sizeof(fullref), *p, len, str);
279                 r = resolve_ref(fullref, this_result, 1, &flag);
280                 if (r) {
281                         if (!refs_found++)
282                                 *ref = xstrdup(r);
283                         if (!warn_ambiguous_refs)
284                                 break;
285                 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD"))
286                         warning("ignoring dangling symref %s.", fullref);
287         }
288         free(last_branch);
289         return refs_found;
290 }
291
292 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
293 {
294         char *last_branch = substitute_branch_name(&str, &len);
295         const char **p;
296         int logs_found = 0;
297
298         *log = NULL;
299         for (p = ref_rev_parse_rules; *p; p++) {
300                 struct stat st;
301                 unsigned char hash[20];
302                 char path[PATH_MAX];
303                 const char *ref, *it;
304
305                 mksnpath(path, sizeof(path), *p, len, str);
306                 ref = resolve_ref(path, hash, 1, NULL);
307                 if (!ref)
308                         continue;
309                 if (!stat(git_path("logs/%s", path), &st) &&
310                     S_ISREG(st.st_mode))
311                         it = path;
312                 else if (strcmp(ref, path) &&
313                          !stat(git_path("logs/%s", ref), &st) &&
314                          S_ISREG(st.st_mode))
315                         it = ref;
316                 else
317                         continue;
318                 if (!logs_found++) {
319                         *log = xstrdup(it);
320                         hashcpy(sha1, hash);
321                 }
322                 if (!warn_ambiguous_refs)
323                         break;
324         }
325         free(last_branch);
326         return logs_found;
327 }
328
329 static inline int upstream_mark(const char *string, int len)
330 {
331         const char *suffix[] = { "@{upstream}", "@{u}" };
332         int i;
333
334         for (i = 0; i < ARRAY_SIZE(suffix); i++) {
335                 int suffix_len = strlen(suffix[i]);
336                 if (suffix_len <= len
337                     && !memcmp(string, suffix[i], suffix_len))
338                         return suffix_len;
339         }
340         return 0;
341 }
342
343 static int get_sha1_1(const char *name, int len, unsigned char *sha1);
344
345 static int get_sha1_basic(const char *str, int len, unsigned char *sha1)
346 {
347         static const char *warn_msg = "refname '%.*s' is ambiguous.";
348         char *real_ref = NULL;
349         int refs_found = 0;
350         int at, reflog_len;
351
352         if (len == 40 && !get_sha1_hex(str, sha1))
353                 return 0;
354
355         /* basic@{time or number or -number} format to query ref-log */
356         reflog_len = at = 0;
357         if (len && str[len-1] == '}') {
358                 for (at = len-2; at >= 0; at--) {
359                         if (str[at] == '@' && str[at+1] == '{') {
360                                 if (!upstream_mark(str + at, len - at)) {
361                                         reflog_len = (len-1) - (at+2);
362                                         len = at;
363                                 }
364                                 break;
365                         }
366                 }
367         }
368
369         /* Accept only unambiguous ref paths. */
370         if (len && ambiguous_path(str, len))
371                 return -1;
372
373         if (!len && reflog_len) {
374                 struct strbuf buf = STRBUF_INIT;
375                 int ret;
376                 /* try the @{-N} syntax for n-th checkout */
377                 ret = interpret_branch_name(str+at, &buf);
378                 if (ret > 0) {
379                         /* substitute this branch name and restart */
380                         return get_sha1_1(buf.buf, buf.len, sha1);
381                 } else if (ret == 0) {
382                         return -1;
383                 }
384                 /* allow "@{...}" to mean the current branch reflog */
385                 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
386         } else if (reflog_len)
387                 refs_found = dwim_log(str, len, sha1, &real_ref);
388         else
389                 refs_found = dwim_ref(str, len, sha1, &real_ref);
390
391         if (!refs_found)
392                 return -1;
393
394         if (warn_ambiguous_refs && refs_found > 1)
395                 warning(warn_msg, len, str);
396
397         if (reflog_len) {
398                 int nth, i;
399                 unsigned long at_time;
400                 unsigned long co_time;
401                 int co_tz, co_cnt;
402
403                 /* a @{-N} placed anywhere except the start is an error */
404                 if (str[at+2] == '-')
405                         return -1;
406
407                 /* Is it asking for N-th entry, or approxidate? */
408                 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
409                         char ch = str[at+2+i];
410                         if ('0' <= ch && ch <= '9')
411                                 nth = nth * 10 + ch - '0';
412                         else
413                                 nth = -1;
414                 }
415                 if (100000000 <= nth) {
416                         at_time = nth;
417                         nth = -1;
418                 } else if (0 <= nth)
419                         at_time = 0;
420                 else {
421                         int errors = 0;
422                         char *tmp = xstrndup(str + at + 2, reflog_len);
423                         at_time = approxidate_careful(tmp, &errors);
424                         free(tmp);
425                         if (errors)
426                                 return -1;
427                 }
428                 if (read_ref_at(real_ref, at_time, nth, sha1, NULL,
429                                 &co_time, &co_tz, &co_cnt)) {
430                         if (at_time)
431                                 warning("Log for '%.*s' only goes "
432                                         "back to %s.", len, str,
433                                         show_date(co_time, co_tz, DATE_RFC2822));
434                         else {
435                                 free(real_ref);
436                                 die("Log for '%.*s' only has %d entries.",
437                                     len, str, co_cnt);
438                         }
439                 }
440         }
441
442         free(real_ref);
443         return 0;
444 }
445
446 static int get_parent(const char *name, int len,
447                       unsigned char *result, int idx)
448 {
449         unsigned char sha1[20];
450         int ret = get_sha1_1(name, len, sha1);
451         struct commit *commit;
452         struct commit_list *p;
453
454         if (ret)
455                 return ret;
456         commit = lookup_commit_reference(sha1);
457         if (!commit)
458                 return -1;
459         if (parse_commit(commit))
460                 return -1;
461         if (!idx) {
462                 hashcpy(result, commit->object.sha1);
463                 return 0;
464         }
465         p = commit->parents;
466         while (p) {
467                 if (!--idx) {
468                         hashcpy(result, p->item->object.sha1);
469                         return 0;
470                 }
471                 p = p->next;
472         }
473         return -1;
474 }
475
476 static int get_nth_ancestor(const char *name, int len,
477                             unsigned char *result, int generation)
478 {
479         unsigned char sha1[20];
480         struct commit *commit;
481         int ret;
482
483         ret = get_sha1_1(name, len, sha1);
484         if (ret)
485                 return ret;
486         commit = lookup_commit_reference(sha1);
487         if (!commit)
488                 return -1;
489
490         while (generation--) {
491                 if (parse_commit(commit) || !commit->parents)
492                         return -1;
493                 commit = commit->parents->item;
494         }
495         hashcpy(result, commit->object.sha1);
496         return 0;
497 }
498
499 struct object *peel_to_type(const char *name, int namelen,
500                             struct object *o, enum object_type expected_type)
501 {
502         if (name && !namelen)
503                 namelen = strlen(name);
504         while (1) {
505                 if (!o || (!o->parsed && !parse_object(o->sha1)))
506                         return NULL;
507                 if (o->type == expected_type)
508                         return o;
509                 if (o->type == OBJ_TAG)
510                         o = ((struct tag*) o)->tagged;
511                 else if (o->type == OBJ_COMMIT)
512                         o = &(((struct commit *) o)->tree->object);
513                 else {
514                         if (name)
515                                 error("%.*s: expected %s type, but the object "
516                                       "dereferences to %s type",
517                                       namelen, name, typename(expected_type),
518                                       typename(o->type));
519                         return NULL;
520                 }
521         }
522 }
523
524 static int peel_onion(const char *name, int len, unsigned char *sha1)
525 {
526         unsigned char outer[20];
527         const char *sp;
528         unsigned int expected_type = 0;
529         struct object *o;
530
531         /*
532          * "ref^{type}" dereferences ref repeatedly until you cannot
533          * dereference anymore, or you get an object of given type,
534          * whichever comes first.  "ref^{}" means just dereference
535          * tags until you get a non-tag.  "ref^0" is a shorthand for
536          * "ref^{commit}".  "commit^{tree}" could be used to find the
537          * top-level tree of the given commit.
538          */
539         if (len < 4 || name[len-1] != '}')
540                 return -1;
541
542         for (sp = name + len - 1; name <= sp; sp--) {
543                 int ch = *sp;
544                 if (ch == '{' && name < sp && sp[-1] == '^')
545                         break;
546         }
547         if (sp <= name)
548                 return -1;
549
550         sp++; /* beginning of type name, or closing brace for empty */
551         if (!strncmp(commit_type, sp, 6) && sp[6] == '}')
552                 expected_type = OBJ_COMMIT;
553         else if (!strncmp(tree_type, sp, 4) && sp[4] == '}')
554                 expected_type = OBJ_TREE;
555         else if (!strncmp(blob_type, sp, 4) && sp[4] == '}')
556                 expected_type = OBJ_BLOB;
557         else if (sp[0] == '}')
558                 expected_type = OBJ_NONE;
559         else if (sp[0] == '/')
560                 expected_type = OBJ_COMMIT;
561         else
562                 return -1;
563
564         if (get_sha1_1(name, sp - name - 2, outer))
565                 return -1;
566
567         o = parse_object(outer);
568         if (!o)
569                 return -1;
570         if (!expected_type) {
571                 o = deref_tag(o, name, sp - name - 2);
572                 if (!o || (!o->parsed && !parse_object(o->sha1)))
573                         return -1;
574                 hashcpy(sha1, o->sha1);
575                 return 0;
576         }
577
578         /*
579          * At this point, the syntax look correct, so
580          * if we do not get the needed object, we should
581          * barf.
582          */
583         o = peel_to_type(name, len, o, expected_type);
584         if (!o)
585                 return -1;
586
587         hashcpy(sha1, o->sha1);
588         if (sp[0] == '/') {
589                 /* "$commit^{/foo}" */
590                 char *prefix;
591                 int ret;
592                 struct commit_list *list = NULL;
593
594                 /*
595                  * $commit^{/}. Some regex implementation may reject.
596                  * We don't need regex anyway. '' pattern always matches.
597                  */
598                 if (sp[1] == '}')
599                         return 0;
600
601                 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
602                 commit_list_insert((struct commit *)o, &list);
603                 ret = get_sha1_oneline(prefix, sha1, list);
604                 free(prefix);
605                 return ret;
606         }
607         return 0;
608 }
609
610 static int get_describe_name(const char *name, int len, unsigned char *sha1)
611 {
612         const char *cp;
613
614         for (cp = name + len - 1; name + 2 <= cp; cp--) {
615                 char ch = *cp;
616                 if (hexval(ch) & ~0377) {
617                         /* We must be looking at g in "SOMETHING-g"
618                          * for it to be describe output.
619                          */
620                         if (ch == 'g' && cp[-1] == '-') {
621                                 cp++;
622                                 len -= cp - name;
623                                 return get_short_sha1(cp, len, sha1, 1);
624                         }
625                 }
626         }
627         return -1;
628 }
629
630 static int get_sha1_1(const char *name, int len, unsigned char *sha1)
631 {
632         int ret, has_suffix;
633         const char *cp;
634
635         /*
636          * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
637          */
638         has_suffix = 0;
639         for (cp = name + len - 1; name <= cp; cp--) {
640                 int ch = *cp;
641                 if ('0' <= ch && ch <= '9')
642                         continue;
643                 if (ch == '~' || ch == '^')
644                         has_suffix = ch;
645                 break;
646         }
647
648         if (has_suffix) {
649                 int num = 0;
650                 int len1 = cp - name;
651                 cp++;
652                 while (cp < name + len)
653                         num = num * 10 + *cp++ - '0';
654                 if (!num && len1 == len - 1)
655                         num = 1;
656                 if (has_suffix == '^')
657                         return get_parent(name, len1, sha1, num);
658                 /* else if (has_suffix == '~') -- goes without saying */
659                 return get_nth_ancestor(name, len1, sha1, num);
660         }
661
662         ret = peel_onion(name, len, sha1);
663         if (!ret)
664                 return 0;
665
666         ret = get_sha1_basic(name, len, sha1);
667         if (!ret)
668                 return 0;
669
670         /* It could be describe output that is "SOMETHING-gXXXX" */
671         ret = get_describe_name(name, len, sha1);
672         if (!ret)
673                 return 0;
674
675         return get_short_sha1(name, len, sha1, 0);
676 }
677
678 /*
679  * This interprets names like ':/Initial revision of "git"' by searching
680  * through history and returning the first commit whose message starts
681  * the given regular expression.
682  *
683  * For future extension, ':/!' is reserved. If you want to match a message
684  * beginning with a '!', you have to repeat the exclamation mark.
685  */
686 #define ONELINE_SEEN (1u<<20)
687
688 static int handle_one_ref(const char *path,
689                 const unsigned char *sha1, int flag, void *cb_data)
690 {
691         struct commit_list **list = cb_data;
692         struct object *object = parse_object(sha1);
693         if (!object)
694                 return 0;
695         if (object->type == OBJ_TAG) {
696                 object = deref_tag(object, path, strlen(path));
697                 if (!object)
698                         return 0;
699         }
700         if (object->type != OBJ_COMMIT)
701                 return 0;
702         commit_list_insert_by_date((struct commit *)object, list);
703         return 0;
704 }
705
706 static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
707                             struct commit_list *list)
708 {
709         struct commit_list *backup = NULL, *l;
710         int found = 0;
711         regex_t regex;
712
713         if (prefix[0] == '!') {
714                 if (prefix[1] != '!')
715                         die ("Invalid search pattern: %s", prefix);
716                 prefix++;
717         }
718
719         if (regcomp(&regex, prefix, REG_EXTENDED))
720                 die("Invalid search pattern: %s", prefix);
721
722         for (l = list; l; l = l->next) {
723                 l->item->object.flags |= ONELINE_SEEN;
724                 commit_list_insert(l->item, &backup);
725         }
726         while (list) {
727                 char *p, *to_free = NULL;
728                 struct commit *commit;
729                 enum object_type type;
730                 unsigned long size;
731                 int matches;
732
733                 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
734                 if (!parse_object(commit->object.sha1))
735                         continue;
736                 if (commit->buffer)
737                         p = commit->buffer;
738                 else {
739                         p = read_sha1_file(commit->object.sha1, &type, &size);
740                         if (!p)
741                                 continue;
742                         to_free = p;
743                 }
744
745                 p = strstr(p, "\n\n");
746                 matches = p && !regexec(&regex, p + 2, 0, NULL, 0);
747                 free(to_free);
748
749                 if (matches) {
750                         hashcpy(sha1, commit->object.sha1);
751                         found = 1;
752                         break;
753                 }
754         }
755         regfree(&regex);
756         free_commit_list(list);
757         for (l = backup; l; l = l->next)
758                 clear_commit_marks(l->item, ONELINE_SEEN);
759         free_commit_list(backup);
760         return found ? 0 : -1;
761 }
762
763 struct grab_nth_branch_switch_cbdata {
764         long cnt, alloc;
765         struct strbuf *buf;
766 };
767
768 static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
769                                   const char *email, unsigned long timestamp, int tz,
770                                   const char *message, void *cb_data)
771 {
772         struct grab_nth_branch_switch_cbdata *cb = cb_data;
773         const char *match = NULL, *target = NULL;
774         size_t len;
775         int nth;
776
777         if (!prefixcmp(message, "checkout: moving from ")) {
778                 match = message + strlen("checkout: moving from ");
779                 target = strstr(match, " to ");
780         }
781
782         if (!match || !target)
783                 return 0;
784
785         len = target - match;
786         nth = cb->cnt++ % cb->alloc;
787         strbuf_reset(&cb->buf[nth]);
788         strbuf_add(&cb->buf[nth], match, len);
789         return 0;
790 }
791
792 /*
793  * Parse @{-N} syntax, return the number of characters parsed
794  * if successful; otherwise signal an error with negative value.
795  */
796 static int interpret_nth_prior_checkout(const char *name, struct strbuf *buf)
797 {
798         long nth;
799         int i, retval;
800         struct grab_nth_branch_switch_cbdata cb;
801         const char *brace;
802         char *num_end;
803
804         if (name[0] != '@' || name[1] != '{' || name[2] != '-')
805                 return -1;
806         brace = strchr(name, '}');
807         if (!brace)
808                 return -1;
809         nth = strtol(name+3, &num_end, 10);
810         if (num_end != brace)
811                 return -1;
812         if (nth <= 0)
813                 return -1;
814         cb.alloc = nth;
815         cb.buf = xmalloc(nth * sizeof(struct strbuf));
816         for (i = 0; i < nth; i++)
817                 strbuf_init(&cb.buf[i], 20);
818         cb.cnt = 0;
819         retval = 0;
820         for_each_recent_reflog_ent("HEAD", grab_nth_branch_switch, 40960, &cb);
821         if (cb.cnt < nth) {
822                 cb.cnt = 0;
823                 for_each_reflog_ent("HEAD", grab_nth_branch_switch, &cb);
824         }
825         if (cb.cnt < nth)
826                 goto release_return;
827         i = cb.cnt % nth;
828         strbuf_reset(buf);
829         strbuf_add(buf, cb.buf[i].buf, cb.buf[i].len);
830         retval = brace-name+1;
831
832 release_return:
833         for (i = 0; i < nth; i++)
834                 strbuf_release(&cb.buf[i]);
835         free(cb.buf);
836
837         return retval;
838 }
839
840 int get_sha1_mb(const char *name, unsigned char *sha1)
841 {
842         struct commit *one, *two;
843         struct commit_list *mbs;
844         unsigned char sha1_tmp[20];
845         const char *dots;
846         int st;
847
848         dots = strstr(name, "...");
849         if (!dots)
850                 return get_sha1(name, sha1);
851         if (dots == name)
852                 st = get_sha1("HEAD", sha1_tmp);
853         else {
854                 struct strbuf sb;
855                 strbuf_init(&sb, dots - name);
856                 strbuf_add(&sb, name, dots - name);
857                 st = get_sha1(sb.buf, sha1_tmp);
858                 strbuf_release(&sb);
859         }
860         if (st)
861                 return st;
862         one = lookup_commit_reference_gently(sha1_tmp, 0);
863         if (!one)
864                 return -1;
865
866         if (get_sha1(dots[3] ? (dots + 3) : "HEAD", sha1_tmp))
867                 return -1;
868         two = lookup_commit_reference_gently(sha1_tmp, 0);
869         if (!two)
870                 return -1;
871         mbs = get_merge_bases(one, two, 1);
872         if (!mbs || mbs->next)
873                 st = -1;
874         else {
875                 st = 0;
876                 hashcpy(sha1, mbs->item->object.sha1);
877         }
878         free_commit_list(mbs);
879         return st;
880 }
881
882 /*
883  * This reads short-hand syntax that not only evaluates to a commit
884  * object name, but also can act as if the end user spelled the name
885  * of the branch from the command line.
886  *
887  * - "@{-N}" finds the name of the Nth previous branch we were on, and
888  *   places the name of the branch in the given buf and returns the
889  *   number of characters parsed if successful.
890  *
891  * - "<branch>@{upstream}" finds the name of the other ref that
892  *   <branch> is configured to merge with (missing <branch> defaults
893  *   to the current branch), and places the name of the branch in the
894  *   given buf and returns the number of characters parsed if
895  *   successful.
896  *
897  * If the input is not of the accepted format, it returns a negative
898  * number to signal an error.
899  *
900  * If the input was ok but there are not N branch switches in the
901  * reflog, it returns 0.
902  */
903 int interpret_branch_name(const char *name, struct strbuf *buf)
904 {
905         char *cp;
906         struct branch *upstream;
907         int namelen = strlen(name);
908         int len = interpret_nth_prior_checkout(name, buf);
909         int tmp_len;
910
911         if (!len)
912                 return len; /* syntax Ok, not enough switches */
913         if (0 < len && len == namelen)
914                 return len; /* consumed all */
915         else if (0 < len) {
916                 /* we have extra data, which might need further processing */
917                 struct strbuf tmp = STRBUF_INIT;
918                 int used = buf->len;
919                 int ret;
920
921                 strbuf_add(buf, name + len, namelen - len);
922                 ret = interpret_branch_name(buf->buf, &tmp);
923                 /* that data was not interpreted, remove our cruft */
924                 if (ret < 0) {
925                         strbuf_setlen(buf, used);
926                         return len;
927                 }
928                 strbuf_reset(buf);
929                 strbuf_addbuf(buf, &tmp);
930                 strbuf_release(&tmp);
931                 /* tweak for size of {-N} versus expanded ref name */
932                 return ret - used + len;
933         }
934
935         cp = strchr(name, '@');
936         if (!cp)
937                 return -1;
938         tmp_len = upstream_mark(cp, namelen - (cp - name));
939         if (!tmp_len)
940                 return -1;
941         len = cp + tmp_len - name;
942         cp = xstrndup(name, cp - name);
943         upstream = branch_get(*cp ? cp : NULL);
944         if (!upstream
945             || !upstream->merge
946             || !upstream->merge[0]->dst)
947                 return error("No upstream branch found for '%s'", cp);
948         free(cp);
949         cp = shorten_unambiguous_ref(upstream->merge[0]->dst, 0);
950         strbuf_reset(buf);
951         strbuf_addstr(buf, cp);
952         free(cp);
953         return len;
954 }
955
956 int strbuf_branchname(struct strbuf *sb, const char *name)
957 {
958         int len = strlen(name);
959         if (interpret_branch_name(name, sb) == len)
960                 return 0;
961         strbuf_add(sb, name, len);
962         return len;
963 }
964
965 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
966 {
967         strbuf_branchname(sb, name);
968         if (name[0] == '-')
969                 return -1;
970         strbuf_splice(sb, 0, 0, "refs/heads/", 11);
971         return check_refname_format(sb->buf, 0);
972 }
973
974 /*
975  * This is like "get_sha1_basic()", except it allows "sha1 expressions",
976  * notably "xyz^" for "parent of xyz"
977  */
978 int get_sha1(const char *name, unsigned char *sha1)
979 {
980         struct object_context unused;
981         return get_sha1_with_context(name, sha1, &unused);
982 }
983
984 /* Must be called only when object_name:filename doesn't exist. */
985 static void diagnose_invalid_sha1_path(const char *prefix,
986                                        const char *filename,
987                                        const unsigned char *tree_sha1,
988                                        const char *object_name)
989 {
990         struct stat st;
991         unsigned char sha1[20];
992         unsigned mode;
993
994         if (!prefix)
995                 prefix = "";
996
997         if (!lstat(filename, &st))
998                 die("Path '%s' exists on disk, but not in '%s'.",
999                     filename, object_name);
1000         if (errno == ENOENT || errno == ENOTDIR) {
1001                 char *fullname = xmalloc(strlen(filename)
1002                                              + strlen(prefix) + 1);
1003                 strcpy(fullname, prefix);
1004                 strcat(fullname, filename);
1005
1006                 if (!get_tree_entry(tree_sha1, fullname,
1007                                     sha1, &mode)) {
1008                         die("Path '%s' exists, but not '%s'.\n"
1009                             "Did you mean '%s:%s' aka '%s:./%s'?",
1010                             fullname,
1011                             filename,
1012                             object_name,
1013                             fullname,
1014                             object_name,
1015                             filename);
1016                 }
1017                 die("Path '%s' does not exist in '%s'",
1018                     filename, object_name);
1019         }
1020 }
1021
1022 /* Must be called only when :stage:filename doesn't exist. */
1023 static void diagnose_invalid_index_path(int stage,
1024                                         const char *prefix,
1025                                         const char *filename)
1026 {
1027         struct stat st;
1028         struct cache_entry *ce;
1029         int pos;
1030         unsigned namelen = strlen(filename);
1031         unsigned fullnamelen;
1032         char *fullname;
1033
1034         if (!prefix)
1035                 prefix = "";
1036
1037         /* Wrong stage number? */
1038         pos = cache_name_pos(filename, namelen);
1039         if (pos < 0)
1040                 pos = -pos - 1;
1041         if (pos < active_nr) {
1042                 ce = active_cache[pos];
1043                 if (ce_namelen(ce) == namelen &&
1044                     !memcmp(ce->name, filename, namelen))
1045                         die("Path '%s' is in the index, but not at stage %d.\n"
1046                             "Did you mean ':%d:%s'?",
1047                             filename, stage,
1048                             ce_stage(ce), filename);
1049         }
1050
1051         /* Confusion between relative and absolute filenames? */
1052         fullnamelen = namelen + strlen(prefix);
1053         fullname = xmalloc(fullnamelen + 1);
1054         strcpy(fullname, prefix);
1055         strcat(fullname, filename);
1056         pos = cache_name_pos(fullname, fullnamelen);
1057         if (pos < 0)
1058                 pos = -pos - 1;
1059         if (pos < active_nr) {
1060                 ce = active_cache[pos];
1061                 if (ce_namelen(ce) == fullnamelen &&
1062                     !memcmp(ce->name, fullname, fullnamelen))
1063                         die("Path '%s' is in the index, but not '%s'.\n"
1064                             "Did you mean ':%d:%s' aka ':%d:./%s'?",
1065                             fullname, filename,
1066                             ce_stage(ce), fullname,
1067                             ce_stage(ce), filename);
1068         }
1069
1070         if (!lstat(filename, &st))
1071                 die("Path '%s' exists on disk, but not in the index.", filename);
1072         if (errno == ENOENT || errno == ENOTDIR)
1073                 die("Path '%s' does not exist (neither on disk nor in the index).",
1074                     filename);
1075
1076         free(fullname);
1077 }
1078
1079
1080 int get_sha1_with_mode_1(const char *name, unsigned char *sha1, unsigned *mode,
1081                          int only_to_die, const char *prefix)
1082 {
1083         struct object_context oc;
1084         int ret;
1085         ret = get_sha1_with_context_1(name, sha1, &oc, only_to_die, prefix);
1086         *mode = oc.mode;
1087         return ret;
1088 }
1089
1090 static char *resolve_relative_path(const char *rel)
1091 {
1092         if (prefixcmp(rel, "./") && prefixcmp(rel, "../"))
1093                 return NULL;
1094
1095         if (!startup_info)
1096                 die("BUG: startup_info struct is not initialized.");
1097
1098         if (!is_inside_work_tree())
1099                 die("relative path syntax can't be used outside working tree.");
1100
1101         /* die() inside prefix_path() if resolved path is outside worktree */
1102         return prefix_path(startup_info->prefix,
1103                            startup_info->prefix ? strlen(startup_info->prefix) : 0,
1104                            rel);
1105 }
1106
1107 int get_sha1_with_context_1(const char *name, unsigned char *sha1,
1108                             struct object_context *oc,
1109                             int only_to_die, const char *prefix)
1110 {
1111         int ret, bracket_depth;
1112         int namelen = strlen(name);
1113         const char *cp;
1114
1115         memset(oc, 0, sizeof(*oc));
1116         oc->mode = S_IFINVALID;
1117         ret = get_sha1_1(name, namelen, sha1);
1118         if (!ret)
1119                 return ret;
1120         /* sha1:path --> object name of path in ent sha1
1121          * :path -> object name of absolute path in index
1122          * :./path -> object name of path relative to cwd in index
1123          * :[0-3]:path -> object name of path in index at stage
1124          * :/foo -> recent commit matching foo
1125          */
1126         if (name[0] == ':') {
1127                 int stage = 0;
1128                 struct cache_entry *ce;
1129                 char *new_path = NULL;
1130                 int pos;
1131                 if (!only_to_die && namelen > 2 && name[1] == '/') {
1132                         struct commit_list *list = NULL;
1133                         for_each_ref(handle_one_ref, &list);
1134                         return get_sha1_oneline(name + 2, sha1, list);
1135                 }
1136                 if (namelen < 3 ||
1137                     name[2] != ':' ||
1138                     name[1] < '0' || '3' < name[1])
1139                         cp = name + 1;
1140                 else {
1141                         stage = name[1] - '0';
1142                         cp = name + 3;
1143                 }
1144                 new_path = resolve_relative_path(cp);
1145                 if (!new_path) {
1146                         namelen = namelen - (cp - name);
1147                 } else {
1148                         cp = new_path;
1149                         namelen = strlen(cp);
1150                 }
1151
1152                 strncpy(oc->path, cp,
1153                         sizeof(oc->path));
1154                 oc->path[sizeof(oc->path)-1] = '\0';
1155
1156                 if (!active_cache)
1157                         read_cache();
1158                 pos = cache_name_pos(cp, namelen);
1159                 if (pos < 0)
1160                         pos = -pos - 1;
1161                 while (pos < active_nr) {
1162                         ce = active_cache[pos];
1163                         if (ce_namelen(ce) != namelen ||
1164                             memcmp(ce->name, cp, namelen))
1165                                 break;
1166                         if (ce_stage(ce) == stage) {
1167                                 hashcpy(sha1, ce->sha1);
1168                                 oc->mode = ce->ce_mode;
1169                                 free(new_path);
1170                                 return 0;
1171                         }
1172                         pos++;
1173                 }
1174                 if (only_to_die && name[1] && name[1] != '/')
1175                         diagnose_invalid_index_path(stage, prefix, cp);
1176                 free(new_path);
1177                 return -1;
1178         }
1179         for (cp = name, bracket_depth = 0; *cp; cp++) {
1180                 if (*cp == '{')
1181                         bracket_depth++;
1182                 else if (bracket_depth && *cp == '}')
1183                         bracket_depth--;
1184                 else if (!bracket_depth && *cp == ':')
1185                         break;
1186         }
1187         if (*cp == ':') {
1188                 unsigned char tree_sha1[20];
1189                 char *object_name = NULL;
1190                 if (only_to_die) {
1191                         object_name = xmalloc(cp-name+1);
1192                         strncpy(object_name, name, cp-name);
1193                         object_name[cp-name] = '\0';
1194                 }
1195                 if (!get_sha1_1(name, cp-name, tree_sha1)) {
1196                         const char *filename = cp+1;
1197                         char *new_filename = NULL;
1198
1199                         new_filename = resolve_relative_path(filename);
1200                         if (new_filename)
1201                                 filename = new_filename;
1202                         ret = get_tree_entry(tree_sha1, filename, sha1, &oc->mode);
1203                         if (only_to_die) {
1204                                 diagnose_invalid_sha1_path(prefix, filename,
1205                                                            tree_sha1, object_name);
1206                                 free(object_name);
1207                         }
1208                         hashcpy(oc->tree, tree_sha1);
1209                         strncpy(oc->path, filename,
1210                                 sizeof(oc->path));
1211                         oc->path[sizeof(oc->path)-1] = '\0';
1212
1213                         free(new_filename);
1214                         return ret;
1215                 } else {
1216                         if (only_to_die)
1217                                 die("Invalid object name '%s'.", object_name);
1218                 }
1219         }
1220         return ret;
1221 }