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