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