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