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