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