get_short_sha1: refactor init of disambiguation code
[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"
dbe44faa 9#include "dir.h"
9938af6a 10
32574b68
NTND
11static int get_sha1_oneline(const char *, unsigned char *, struct commit_list *);
12
a78fafe7
JH
13typedef int (*disambiguate_hint_fn)(const unsigned char *, void *);
14
15struct disambiguate_state {
0016043b
JK
16 int len; /* length of prefix in hex chars */
17 char hex_pfx[GIT_SHA1_HEXSZ];
18 unsigned char bin_pfx[GIT_SHA1_RAWSZ];
19
a78fafe7
JH
20 disambiguate_hint_fn fn;
21 void *cb_data;
0016043b 22 unsigned char candidate[GIT_SHA1_RAWSZ];
a78fafe7
JH
23 unsigned candidate_exists:1;
24 unsigned candidate_checked:1;
25 unsigned candidate_ok:1;
26 unsigned disambiguate_fn_used:1;
27 unsigned ambiguous:1;
957d7406 28 unsigned always_call_fn:1;
a78fafe7
JH
29};
30
31static void update_candidates(struct disambiguate_state *ds, const unsigned char *current)
32{
957d7406
JH
33 if (ds->always_call_fn) {
34 ds->ambiguous = ds->fn(current, ds->cb_data) ? 1 : 0;
35 return;
36 }
a78fafe7
JH
37 if (!ds->candidate_exists) {
38 /* this is the first candidate */
39 hashcpy(ds->candidate, current);
40 ds->candidate_exists = 1;
41 return;
42 } else if (!hashcmp(ds->candidate, current)) {
43 /* the same as what we already have seen */
44 return;
45 }
46
47 if (!ds->fn) {
48 /* cannot disambiguate between ds->candidate and current */
49 ds->ambiguous = 1;
50 return;
51 }
52
53 if (!ds->candidate_checked) {
54 ds->candidate_ok = ds->fn(ds->candidate, ds->cb_data);
55 ds->disambiguate_fn_used = 1;
56 ds->candidate_checked = 1;
57 }
58
59 if (!ds->candidate_ok) {
749f763d 60 /* discard the candidate; we know it does not satisfy fn */
a78fafe7
JH
61 hashcpy(ds->candidate, current);
62 ds->candidate_checked = 0;
63 return;
64 }
65
66 /* if we reach this point, we know ds->candidate satisfies fn */
67 if (ds->fn(current, ds->cb_data)) {
68 /*
69 * if both current and candidate satisfy fn, we cannot
70 * disambiguate.
71 */
72 ds->candidate_ok = 0;
73 ds->ambiguous = 1;
74 }
75
76 /* otherwise, current can be discarded and candidate is still good */
77}
78
0016043b 79static void find_short_object_filename(struct disambiguate_state *ds)
9938af6a 80{
99a19b43 81 struct alternate_object_database *alt;
0016043b 82 char hex[GIT_SHA1_HEXSZ];
99a19b43
JH
83 static struct alternate_object_database *fakeent;
84
85 if (!fakeent) {
274ac009
JH
86 /*
87 * Create a "fake" alternate object database that
88 * points to our own object database, to make it
89 * easier to get a temporary working space in
90 * alt->name/alt->base while iterating over the
91 * object databases including our own.
92 */
99a19b43 93 const char *objdir = get_object_directory();
50a6c8ef
JK
94 size_t objdir_len = strlen(objdir);
95 fakeent = xmalloc(st_add3(sizeof(*fakeent), objdir_len, 43));
99a19b43
JH
96 memcpy(fakeent->base, objdir, objdir_len);
97 fakeent->name = fakeent->base + objdir_len + 1;
98 fakeent->name[-1] = '/';
99 }
100 fakeent->next = alt_odb_list;
9938af6a 101
0016043b 102 xsnprintf(hex, sizeof(hex), "%.2s", ds->hex_pfx);
a78fafe7 103 for (alt = fakeent; alt && !ds->ambiguous; alt = alt->next) {
9938af6a 104 struct dirent *de;
99a19b43 105 DIR *dir;
c3bb0ac7
JK
106 /*
107 * every alt_odb struct has 42 extra bytes after the base
108 * for exactly this purpose
109 */
0016043b 110 xsnprintf(alt->name, 42, "%.2s/", ds->hex_pfx);
99a19b43
JH
111 dir = opendir(alt->base);
112 if (!dir)
113 continue;
a78fafe7
JH
114
115 while (!ds->ambiguous && (de = readdir(dir)) != NULL) {
116 unsigned char sha1[20];
117
9938af6a
JH
118 if (strlen(de->d_name) != 38)
119 continue;
0016043b 120 if (memcmp(de->d_name, ds->hex_pfx + 2, ds->len - 2))
9938af6a 121 continue;
a78fafe7
JH
122 memcpy(hex + 2, de->d_name, 38);
123 if (!get_sha1_hex(hex, sha1))
124 update_candidates(ds, sha1);
9938af6a
JH
125 }
126 closedir(dir);
127 }
9938af6a
JH
128}
129
130static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
131{
132 do {
133 if (*a != *b)
134 return 0;
135 a++;
136 b++;
137 len -= 2;
138 } while (len > 1);
139 if (len)
140 if ((*a ^ *b) & 0xf0)
141 return 0;
142 return 1;
143}
144
0016043b 145static void unique_in_pack(struct packed_git *p,
a78fafe7 146 struct disambiguate_state *ds)
9938af6a 147{
f703e6ea
JH
148 uint32_t num, last, i, first = 0;
149 const unsigned char *current = NULL;
150
151 open_pack_index(p);
152 num = p->num_objects;
153 last = num;
154 while (first < last) {
155 uint32_t mid = (first + last) / 2;
156 const unsigned char *current;
157 int cmp;
158
159 current = nth_packed_object_sha1(p, mid);
0016043b 160 cmp = hashcmp(ds->bin_pfx, current);
f703e6ea
JH
161 if (!cmp) {
162 first = mid;
163 break;
9938af6a 164 }
f703e6ea
JH
165 if (cmp > 0) {
166 first = mid+1;
167 continue;
9938af6a 168 }
f703e6ea
JH
169 last = mid;
170 }
171
172 /*
173 * At this point, "first" is the location of the lowest object
1703f9aa 174 * with an object name that could match "bin_pfx". See if we have
f703e6ea
JH
175 * 0, 1 or more objects that actually match(es).
176 */
a78fafe7
JH
177 for (i = first; i < num && !ds->ambiguous; i++) {
178 current = nth_packed_object_sha1(p, i);
0016043b 179 if (!match_sha(ds->len, ds->bin_pfx, current))
f703e6ea 180 break;
a78fafe7 181 update_candidates(ds, current);
9938af6a 182 }
f703e6ea
JH
183}
184
0016043b 185static void find_short_packed_object(struct disambiguate_state *ds)
9938af6a
JH
186{
187 struct packed_git *p;
188
189 prepare_packed_git();
a78fafe7 190 for (p = packed_git; p && !ds->ambiguous; p = p->next)
0016043b 191 unique_in_pack(p, ds);
99a19b43
JH
192}
193
013f276e
JH
194#define SHORT_NAME_NOT_FOUND (-1)
195#define SHORT_NAME_AMBIGUOUS (-2)
196
a78fafe7
JH
197static int finish_object_disambiguation(struct disambiguate_state *ds,
198 unsigned char *sha1)
99a19b43 199{
a78fafe7
JH
200 if (ds->ambiguous)
201 return SHORT_NAME_AMBIGUOUS;
99a19b43 202
a78fafe7 203 if (!ds->candidate_exists)
013f276e 204 return SHORT_NAME_NOT_FOUND;
a78fafe7
JH
205
206 if (!ds->candidate_checked)
207 /*
208 * If this is the only candidate, there is no point
209 * calling the disambiguation hint callback.
210 *
211 * On the other hand, if the current candidate
212 * replaced an earlier candidate that did _not_ pass
213 * the disambiguation hint callback, then we do have
214 * more than one objects that match the short name
215 * given, so we should make sure this one matches;
216 * otherwise, if we discovered this one and the one
217 * that we previously discarded in the reverse order,
218 * we would end up showing different results in the
219 * same repository!
220 */
221 ds->candidate_ok = (!ds->disambiguate_fn_used ||
222 ds->fn(ds->candidate, ds->cb_data));
223
224 if (!ds->candidate_ok)
013f276e 225 return SHORT_NAME_AMBIGUOUS;
a78fafe7
JH
226
227 hashcpy(sha1, ds->candidate);
9938af6a
JH
228 return 0;
229}
230
aa1dec9e
JH
231static int disambiguate_commit_only(const unsigned char *sha1, void *cb_data_unused)
232{
233 int kind = sha1_object_info(sha1, NULL);
234 return kind == OBJ_COMMIT;
235}
236
e2643617
JH
237static int disambiguate_committish_only(const unsigned char *sha1, void *cb_data_unused)
238{
239 struct object *obj;
240 int kind;
241
242 kind = sha1_object_info(sha1, NULL);
243 if (kind == OBJ_COMMIT)
244 return 1;
245 if (kind != OBJ_TAG)
99a19b43 246 return 0;
e2643617
JH
247
248 /* We need to do this the hard way... */
94d75d1e 249 obj = deref_tag(parse_object(sha1), NULL, 0);
e2643617
JH
250 if (obj && obj->type == OBJ_COMMIT)
251 return 1;
9938af6a
JH
252 return 0;
253}
254
daba53ae 255static int disambiguate_tree_only(const unsigned char *sha1, void *cb_data_unused)
9938af6a 256{
daba53ae
JH
257 int kind = sha1_object_info(sha1, NULL);
258 return kind == OBJ_TREE;
259}
9938af6a 260
daba53ae
JH
261static int disambiguate_treeish_only(const unsigned char *sha1, void *cb_data_unused)
262{
263 struct object *obj;
264 int kind;
265
266 kind = sha1_object_info(sha1, NULL);
267 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
268 return 1;
269 if (kind != OBJ_TAG)
270 return 0;
271
272 /* We need to do this the hard way... */
5d5def2a 273 obj = deref_tag(parse_object(sha1), NULL, 0);
daba53ae
JH
274 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
275 return 1;
276 return 0;
277}
278
279static int disambiguate_blob_only(const unsigned char *sha1, void *cb_data_unused)
280{
281 int kind = sha1_object_info(sha1, NULL);
282 return kind == OBJ_BLOB;
283}
284
0016043b
JK
285static int init_object_disambiguation(const char *name, int len,
286 struct disambiguate_state *ds)
9938af6a 287{
957d7406 288 int i;
9938af6a 289
0016043b
JK
290 if (len < MINIMUM_ABBREV || len > GIT_SHA1_HEXSZ)
291 return -1;
292
293 memset(ds, 0, sizeof(*ds));
294 memset(ds->hex_pfx, 'x', GIT_SHA1_HEXSZ);
295
af61c6e0 296 for (i = 0; i < len ;i++) {
9938af6a
JH
297 unsigned char c = name[i];
298 unsigned char val;
9938af6a
JH
299 if (c >= '0' && c <= '9')
300 val = c - '0';
301 else if (c >= 'a' && c <= 'f')
302 val = c - 'a' + 10;
303 else if (c >= 'A' && c <='F') {
304 val = c - 'A' + 10;
305 c -= 'A' - 'a';
306 }
307 else
308 return -1;
0016043b 309 ds->hex_pfx[i] = c;
9938af6a
JH
310 if (!(i & 1))
311 val <<= 4;
0016043b 312 ds->bin_pfx[i >> 1] |= val;
9938af6a 313 }
0016043b
JK
314
315 ds->len = len;
316 prepare_alt_odb();
957d7406
JH
317 return 0;
318}
319
320static int get_short_sha1(const char *name, int len, unsigned char *sha1,
321 unsigned flags)
322{
323 int status;
957d7406
JH
324 struct disambiguate_state ds;
325 int quietly = !!(flags & GET_SHA1_QUIETLY);
326
0016043b 327 if (init_object_disambiguation(name, len, &ds) < 0)
957d7406 328 return -1;
99a19b43 329
259942f5
JK
330 if (HAS_MULTI_BITS(flags & GET_SHA1_DISAMBIGUATORS))
331 die("BUG: multiple get_short_sha1 disambiguator flags");
332
aa1dec9e
JH
333 if (flags & GET_SHA1_COMMIT)
334 ds.fn = disambiguate_commit_only;
e2643617
JH
335 else if (flags & GET_SHA1_COMMITTISH)
336 ds.fn = disambiguate_committish_only;
daba53ae
JH
337 else if (flags & GET_SHA1_TREE)
338 ds.fn = disambiguate_tree_only;
339 else if (flags & GET_SHA1_TREEISH)
340 ds.fn = disambiguate_treeish_only;
341 else if (flags & GET_SHA1_BLOB)
342 ds.fn = disambiguate_blob_only;
aa1dec9e 343
0016043b
JK
344 find_short_object_filename(&ds);
345 find_short_packed_object(&ds);
a78fafe7 346 status = finish_object_disambiguation(&ds, sha1);
99a19b43 347
013f276e 348 if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
0016043b 349 return error("short SHA1 %.*s is ambiguous.", ds.len, ds.hex_pfx);
013f276e
JH
350 return status;
351}
352
957d7406
JH
353int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
354{
957d7406 355 struct disambiguate_state ds;
957d7406 356
0016043b 357 if (init_object_disambiguation(prefix, strlen(prefix), &ds) < 0)
957d7406 358 return -1;
957d7406 359
957d7406
JH
360 ds.always_call_fn = 1;
361 ds.cb_data = cb_data;
362 ds.fn = fn;
363
0016043b
JK
364 find_short_object_filename(&ds);
365 find_short_packed_object(&ds);
957d7406
JH
366 return ds.ambiguous;
367}
368
af49c6d0 369int find_unique_abbrev_r(char *hex, const unsigned char *sha1, int len)
013f276e 370{
b66fde9a 371 int status, exists;
47dd0d59 372
af49c6d0 373 sha1_to_hex_r(hex, sha1);
02c5cba2 374 if (len == 40 || !len)
af49c6d0 375 return 40;
61e704e3 376 exists = has_sha1_file(sha1);
013f276e
JH
377 while (len < 40) {
378 unsigned char sha1_ret[20];
37c00e55 379 status = get_short_sha1(hex, len, sha1_ret, GET_SHA1_QUIETLY);
b66fde9a
JH
380 if (exists
381 ? !status
382 : status == SHORT_NAME_NOT_FOUND) {
ea2c69ed 383 hex[len] = 0;
af49c6d0 384 return len;
013f276e 385 }
013f276e
JH
386 len++;
387 }
af49c6d0
JK
388 return len;
389}
390
391const char *find_unique_abbrev(const unsigned char *sha1, int len)
392{
393 static char hex[GIT_SHA1_HEXSZ + 1];
394 find_unique_abbrev_r(hex, sha1, len);
b66fde9a 395 return hex;
9938af6a
JH
396}
397
6677c466 398static int ambiguous_path(const char *path, int len)
af13cdf2
LT
399{
400 int slash = 1;
6677c466 401 int cnt;
af13cdf2 402
6677c466 403 for (cnt = 0; cnt < len; cnt++) {
af13cdf2
LT
404 switch (*path++) {
405 case '\0':
406 break;
407 case '/':
408 if (slash)
409 break;
410 slash = 1;
411 continue;
412 case '.':
413 continue;
414 default:
415 slash = 0;
416 continue;
417 }
c054d64e 418 break;
af13cdf2 419 }
6677c466 420 return slash;
af13cdf2
LT
421}
422
a1ad0eb0
JK
423static inline int at_mark(const char *string, int len,
424 const char **suffix, int nr)
ae0ba8e2 425{
ae0ba8e2
JH
426 int i;
427
a1ad0eb0 428 for (i = 0; i < nr; i++) {
ae0ba8e2
JH
429 int suffix_len = strlen(suffix[i]);
430 if (suffix_len <= len
431 && !memcmp(string, suffix[i], suffix_len))
432 return suffix_len;
433 }
434 return 0;
435}
436
a1ad0eb0
JK
437static inline int upstream_mark(const char *string, int len)
438{
439 const char *suffix[] = { "@{upstream}", "@{u}" };
440 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
441}
442
adfe5d04
JK
443static inline int push_mark(const char *string, int len)
444{
445 const char *suffix[] = { "@{push}" };
446 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
447}
448
e48ba200 449static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags);
8cd4249c 450static int interpret_nth_prior_checkout(const char *name, int namelen, struct strbuf *buf);
d18ba221 451
c41a87dd
DA
452static int get_sha1_basic(const char *str, int len, unsigned char *sha1,
453 unsigned int flags)
e86eb666 454{
eedce784 455 static const char *warn_msg = "refname '%.*s' is ambiguous.";
798c35fc
NTND
456 static const char *object_name_msg = N_(
457 "Git normally never creates a ref that ends with 40 hex characters\n"
458 "because it will be ignored when you just specify 40-hex. These refs\n"
459 "may be created by mistake. For example,\n"
460 "\n"
461 " git checkout -b $br $(git rev-parse ...)\n"
462 "\n"
463 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
464 "examine these refs and maybe delete them. Turn this message off by\n"
8dc84fdc 465 "running \"git config advice.objectNameWarning false\"");
798c35fc 466 unsigned char tmp_sha1[20];
ed378ec7 467 char *real_ref = NULL;
ab2a1a32 468 int refs_found = 0;
128fd54d 469 int at, reflog_len, nth_prior = 0;
9938af6a 470
798c35fc 471 if (len == 40 && !get_sha1_hex(str, sha1)) {
832cf74c 472 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
25fba78d 473 refs_found = dwim_ref(str, len, tmp_sha1, &real_ref);
832cf74c 474 if (refs_found > 0) {
25fba78d
JK
475 warning(warn_msg, len, str);
476 if (advice_object_name_warning)
477 fprintf(stderr, "%s\n", _(object_name_msg));
478 }
479 free(real_ref);
798c35fc 480 }
9938af6a 481 return 0;
798c35fc 482 }
9938af6a 483
d18ba221 484 /* basic@{time or number or -number} format to query ref-log */
694500ed 485 reflog_len = at = 0;
f265458f 486 if (len && str[len-1] == '}') {
e883a057 487 for (at = len-4; at >= 0; at--) {
ab2a1a32 488 if (str[at] == '@' && str[at+1] == '{') {
83d16bc7
RR
489 if (str[at+2] == '-') {
490 if (at != 0)
491 /* @{-N} not at start */
492 return -1;
128fd54d
FC
493 nth_prior = 1;
494 continue;
495 }
adfe5d04
JK
496 if (!upstream_mark(str + at, len - at) &&
497 !push_mark(str + at, len - at)) {
28fb8438
JS
498 reflog_len = (len-1) - (at+2);
499 len = at;
500 }
ab2a1a32
JH
501 break;
502 }
d556fae2
SP
503 }
504 }
505
af13cdf2 506 /* Accept only unambiguous ref paths. */
11cf8801 507 if (len && ambiguous_path(str, len))
af13cdf2
LT
508 return -1;
509
128fd54d 510 if (nth_prior) {
d18ba221 511 struct strbuf buf = STRBUF_INIT;
128fd54d
FC
512 int detached;
513
8cd4249c 514 if (interpret_nth_prior_checkout(str, len, &buf) > 0) {
128fd54d
FC
515 detached = (buf.len == 40 && !get_sha1_hex(buf.buf, sha1));
516 strbuf_release(&buf);
517 if (detached)
518 return 0;
d18ba221 519 }
128fd54d
FC
520 }
521
522 if (!len && reflog_len)
11cf8801
NP
523 /* allow "@{...}" to mean the current branch reflog */
524 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
128fd54d 525 else if (reflog_len)
f2eba66d
NP
526 refs_found = dwim_log(str, len, sha1, &real_ref);
527 else
11cf8801 528 refs_found = dwim_ref(str, len, sha1, &real_ref);
d556fae2
SP
529
530 if (!refs_found)
531 return -1;
532
c41a87dd 533 if (warn_ambiguous_refs && !(flags & GET_SHA1_QUIETLY) &&
798c35fc
NTND
534 (refs_found > 1 ||
535 !get_short_sha1(str, len, tmp_sha1, GET_SHA1_QUIETLY)))
eedce784 536 warning(warn_msg, len, str);
d556fae2 537
ab2a1a32 538 if (reflog_len) {
ab2a1a32
JH
539 int nth, i;
540 unsigned long at_time;
16d7cc90
JH
541 unsigned long co_time;
542 int co_tz, co_cnt;
543
fe558516 544 /* Is it asking for N-th entry, or approxidate? */
ab2a1a32
JH
545 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
546 char ch = str[at+2+i];
547 if ('0' <= ch && ch <= '9')
548 nth = nth * 10 + ch - '0';
549 else
550 nth = -1;
551 }
ea360dd0
SP
552 if (100000000 <= nth) {
553 at_time = nth;
554 nth = -1;
555 } else if (0 <= nth)
ab2a1a32 556 at_time = 0;
861f00e3 557 else {
93cfa7c7 558 int errors = 0;
861f00e3 559 char *tmp = xstrndup(str + at + 2, reflog_len);
93cfa7c7 560 at_time = approxidate_careful(tmp, &errors);
861f00e3 561 free(tmp);
28b35632
JK
562 if (errors) {
563 free(real_ref);
a5e10acb 564 return -1;
28b35632 565 }
861f00e3 566 }
c41a87dd 567 if (read_ref_at(real_ref, flags, at_time, nth, sha1, NULL,
16d7cc90 568 &co_time, &co_tz, &co_cnt)) {
305ebea0 569 if (!len) {
59556548 570 if (starts_with(real_ref, "refs/heads/")) {
305ebea0
RR
571 str = real_ref + 11;
572 len = strlen(real_ref + 11);
573 } else {
574 /* detached HEAD */
575 str = "HEAD";
576 len = 4;
577 }
578 }
c41a87dd
DA
579 if (at_time) {
580 if (!(flags & GET_SHA1_QUIETLY)) {
581 warning("Log for '%.*s' only goes "
582 "back to %s.", len, str,
a5481a6c 583 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
c41a87dd
DA
584 }
585 } else {
586 if (flags & GET_SHA1_QUIETLY) {
587 exit(128);
588 }
e6eedc31
JS
589 die("Log for '%.*s' only has %d entries.",
590 len, str, co_cnt);
591 }
16d7cc90 592 }
d556fae2
SP
593 }
594
ed378ec7 595 free(real_ref);
d556fae2 596 return 0;
9938af6a
JH
597}
598
9938af6a
JH
599static int get_parent(const char *name, int len,
600 unsigned char *result, int idx)
601{
602 unsigned char sha1[20];
e2643617 603 int ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
9938af6a
JH
604 struct commit *commit;
605 struct commit_list *p;
606
607 if (ret)
608 return ret;
609 commit = lookup_commit_reference(sha1);
9938af6a
JH
610 if (parse_commit(commit))
611 return -1;
612 if (!idx) {
ed1c9977 613 hashcpy(result, commit->object.oid.hash);
9938af6a
JH
614 return 0;
615 }
616 p = commit->parents;
617 while (p) {
618 if (!--idx) {
ed1c9977 619 hashcpy(result, p->item->object.oid.hash);
9938af6a
JH
620 return 0;
621 }
622 p = p->next;
623 }
624 return -1;
625}
626
4f7599ac
JH
627static int get_nth_ancestor(const char *name, int len,
628 unsigned char *result, int generation)
629{
630 unsigned char sha1[20];
621ff675
LT
631 struct commit *commit;
632 int ret;
633
e2643617 634 ret = get_sha1_1(name, len, sha1, GET_SHA1_COMMITTISH);
4f7599ac
JH
635 if (ret)
636 return ret;
621ff675
LT
637 commit = lookup_commit_reference(sha1);
638 if (!commit)
639 return -1;
4f7599ac
JH
640
641 while (generation--) {
621ff675 642 if (parse_commit(commit) || !commit->parents)
4f7599ac 643 return -1;
621ff675 644 commit = commit->parents->item;
4f7599ac 645 }
ed1c9977 646 hashcpy(result, commit->object.oid.hash);
4f7599ac
JH
647 return 0;
648}
649
81776315
JH
650struct object *peel_to_type(const char *name, int namelen,
651 struct object *o, enum object_type expected_type)
652{
653 if (name && !namelen)
654 namelen = strlen(name);
81776315 655 while (1) {
ed1c9977 656 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
81776315 657 return NULL;
a6a3f2cc 658 if (expected_type == OBJ_ANY || o->type == expected_type)
81776315
JH
659 return o;
660 if (o->type == OBJ_TAG)
661 o = ((struct tag*) o)->tagged;
662 else if (o->type == OBJ_COMMIT)
663 o = &(((struct commit *) o)->tree->object);
664 else {
665 if (name)
666 error("%.*s: expected %s type, but the object "
667 "dereferences to %s type",
668 namelen, name, typename(expected_type),
669 typename(o->type));
670 return NULL;
671 }
672 }
673}
674
8a10fea4
JK
675static int peel_onion(const char *name, int len, unsigned char *sha1,
676 unsigned lookup_flags)
5385f52d
JH
677{
678 unsigned char outer[20];
679 const char *sp;
885a86ab 680 unsigned int expected_type = 0;
5385f52d
JH
681 struct object *o;
682
683 /*
684 * "ref^{type}" dereferences ref repeatedly until you cannot
685 * dereference anymore, or you get an object of given type,
686 * whichever comes first. "ref^{}" means just dereference
687 * tags until you get a non-tag. "ref^0" is a shorthand for
688 * "ref^{commit}". "commit^{tree}" could be used to find the
689 * top-level tree of the given commit.
690 */
691 if (len < 4 || name[len-1] != '}')
692 return -1;
693
694 for (sp = name + len - 1; name <= sp; sp--) {
695 int ch = *sp;
696 if (ch == '{' && name < sp && sp[-1] == '^')
697 break;
698 }
699 if (sp <= name)
700 return -1;
701
702 sp++; /* beginning of type name, or closing brace for empty */
59556548 703 if (starts_with(sp, "commit}"))
1974632c 704 expected_type = OBJ_COMMIT;
59556548 705 else if (starts_with(sp, "tag}"))
75aa26d3 706 expected_type = OBJ_TAG;
59556548 707 else if (starts_with(sp, "tree}"))
1974632c 708 expected_type = OBJ_TREE;
59556548 709 else if (starts_with(sp, "blob}"))
1974632c 710 expected_type = OBJ_BLOB;
59556548 711 else if (starts_with(sp, "object}"))
a6a3f2cc 712 expected_type = OBJ_ANY;
5385f52d 713 else if (sp[0] == '}')
1974632c 714 expected_type = OBJ_NONE;
32574b68
NTND
715 else if (sp[0] == '/')
716 expected_type = OBJ_COMMIT;
5385f52d
JH
717 else
718 return -1;
719
8a10fea4 720 lookup_flags &= ~GET_SHA1_DISAMBIGUATORS;
e2643617 721 if (expected_type == OBJ_COMMIT)
8a10fea4 722 lookup_flags |= GET_SHA1_COMMITTISH;
ed1ca602 723 else if (expected_type == OBJ_TREE)
8a10fea4 724 lookup_flags |= GET_SHA1_TREEISH;
e2643617
JH
725
726 if (get_sha1_1(name, sp - name - 2, outer, lookup_flags))
5385f52d
JH
727 return -1;
728
729 o = parse_object(outer);
730 if (!o)
731 return -1;
885a86ab 732 if (!expected_type) {
9534f40b 733 o = deref_tag(o, name, sp - name - 2);
ed1c9977 734 if (!o || (!o->parsed && !parse_object(o->oid.hash)))
6e1c6c10 735 return -1;
f2fd0760 736 hashcpy(sha1, o->oid.hash);
32574b68 737 return 0;
5385f52d 738 }
32574b68
NTND
739
740 /*
741 * At this point, the syntax look correct, so
742 * if we do not get the needed object, we should
743 * barf.
744 */
745 o = peel_to_type(name, len, o, expected_type);
746 if (!o)
81776315 747 return -1;
32574b68 748
ed1c9977 749 hashcpy(sha1, o->oid.hash);
32574b68
NTND
750 if (sp[0] == '/') {
751 /* "$commit^{/foo}" */
752 char *prefix;
753 int ret;
754 struct commit_list *list = NULL;
755
81776315 756 /*
4322842a
NTND
757 * $commit^{/}. Some regex implementation may reject.
758 * We don't need regex anyway. '' pattern always matches.
5385f52d 759 */
4322842a 760 if (sp[1] == '}')
81776315 761 return 0;
4322842a 762
32574b68
NTND
763 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
764 commit_list_insert((struct commit *)o, &list);
765 ret = get_sha1_oneline(prefix, sha1, list);
766 free(prefix);
767 return ret;
5385f52d
JH
768 }
769 return 0;
770}
771
7dd45e15
JH
772static int get_describe_name(const char *name, int len, unsigned char *sha1)
773{
774 const char *cp;
6269b6b6 775 unsigned flags = GET_SHA1_QUIETLY | GET_SHA1_COMMIT;
7dd45e15
JH
776
777 for (cp = name + len - 1; name + 2 <= cp; cp--) {
778 char ch = *cp;
6f75d45b 779 if (!isxdigit(ch)) {
7dd45e15
JH
780 /* We must be looking at g in "SOMETHING-g"
781 * for it to be describe output.
782 */
783 if (ch == 'g' && cp[-1] == '-') {
784 cp++;
785 len -= cp - name;
6269b6b6 786 return get_short_sha1(cp, len, sha1, flags);
7dd45e15
JH
787 }
788 }
789 }
790 return -1;
791}
792
e48ba200 793static int get_sha1_1(const char *name, int len, unsigned char *sha1, unsigned lookup_flags)
9938af6a 794{
0601dbe1 795 int ret, has_suffix;
4f7599ac 796 const char *cp;
9938af6a 797
621ff675
LT
798 /*
799 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
4f7599ac 800 */
0601dbe1 801 has_suffix = 0;
4f7599ac
JH
802 for (cp = name + len - 1; name <= cp; cp--) {
803 int ch = *cp;
804 if ('0' <= ch && ch <= '9')
805 continue;
0601dbe1
JH
806 if (ch == '~' || ch == '^')
807 has_suffix = ch;
4f7599ac
JH
808 break;
809 }
0601dbe1
JH
810
811 if (has_suffix) {
812 int num = 0;
4f7599ac
JH
813 int len1 = cp - name;
814 cp++;
815 while (cp < name + len)
0601dbe1 816 num = num * 10 + *cp++ - '0';
621ff675
LT
817 if (!num && len1 == len - 1)
818 num = 1;
819 if (has_suffix == '^')
0601dbe1 820 return get_parent(name, len1, sha1, num);
0601dbe1
JH
821 /* else if (has_suffix == '~') -- goes without saying */
822 return get_nth_ancestor(name, len1, sha1, num);
4f7599ac
JH
823 }
824
8a10fea4 825 ret = peel_onion(name, len, sha1, lookup_flags);
5385f52d
JH
826 if (!ret)
827 return 0;
828
c41a87dd 829 ret = get_sha1_basic(name, len, sha1, lookup_flags);
9938af6a
JH
830 if (!ret)
831 return 0;
7dd45e15
JH
832
833 /* It could be describe output that is "SOMETHING-gXXXX" */
834 ret = get_describe_name(name, len, sha1);
835 if (!ret)
836 return 0;
837
e2643617 838 return get_short_sha1(name, len, sha1, lookup_flags);
9938af6a
JH
839}
840
f7bff003
JH
841/*
842 * This interprets names like ':/Initial revision of "git"' by searching
843 * through history and returning the first commit whose message starts
3d045897 844 * the given regular expression.
f7bff003 845 *
0769854f
WP
846 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
847 *
848 * For a literal '!' character at the beginning of a pattern, you have to repeat
849 * that, like: ':/!!foo'
850 *
851 * For future extension, all other sequences beginning with ':/!' are reserved.
f7bff003 852 */
208acbfb
NTND
853
854/* Remember to update object flag allocation in object.h */
f7bff003
JH
855#define ONELINE_SEEN (1u<<20)
856
9c5fe0b8
MH
857static int handle_one_ref(const char *path, const struct object_id *oid,
858 int flag, void *cb_data)
28a4d940
JS
859{
860 struct commit_list **list = cb_data;
9c5fe0b8 861 struct object *object = parse_object(oid->hash);
28a4d940
JS
862 if (!object)
863 return 0;
affeef12 864 if (object->type == OBJ_TAG) {
28a4d940 865 object = deref_tag(object, path, strlen(path));
affeef12
MK
866 if (!object)
867 return 0;
868 }
28a4d940
JS
869 if (object->type != OBJ_COMMIT)
870 return 0;
e8d1dfe6 871 commit_list_insert((struct commit *)object, list);
28a4d940
JS
872 return 0;
873}
874
84baa31b
NTND
875static int get_sha1_oneline(const char *prefix, unsigned char *sha1,
876 struct commit_list *list)
28a4d940 877{
84baa31b 878 struct commit_list *backup = NULL, *l;
28042dbc 879 int found = 0;
0769854f 880 int negative = 0;
57895105 881 regex_t regex;
28a4d940
JS
882
883 if (prefix[0] == '!') {
28a4d940 884 prefix++;
0769854f
WP
885
886 if (prefix[0] == '-') {
887 prefix++;
888 negative = 1;
889 } else if (prefix[0] != '!') {
e6a6a768 890 return -1;
0769854f 891 }
28a4d940 892 }
57895105
LT
893
894 if (regcomp(&regex, prefix, REG_EXTENDED))
aac4fac1 895 return -1;
57895105 896
84baa31b
NTND
897 for (l = list; l; l = l->next) {
898 l->item->object.flags |= ONELINE_SEEN;
28a4d940 899 commit_list_insert(l->item, &backup);
84baa31b 900 }
ed8ad7e2 901 while (list) {
ba41c1c9 902 const char *p, *buf;
1358e7d6 903 struct commit *commit;
28042dbc 904 int matches;
ed8ad7e2
JM
905
906 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
ed1c9977 907 if (!parse_object(commit->object.oid.hash))
283cdbcf 908 continue;
8597ea3a 909 buf = get_commit_buffer(commit, NULL);
ba41c1c9 910 p = strstr(buf, "\n\n");
0769854f 911 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
ba41c1c9 912 unuse_commit_buffer(commit, buf);
28042dbc
JH
913
914 if (matches) {
ed1c9977 915 hashcpy(sha1, commit->object.oid.hash);
28042dbc 916 found = 1;
28a4d940
JS
917 break;
918 }
919 }
57895105 920 regfree(&regex);
28a4d940
JS
921 free_commit_list(list);
922 for (l = backup; l; l = l->next)
923 clear_commit_marks(l->item, ONELINE_SEEN);
28042dbc
JH
924 free_commit_list(backup);
925 return found ? 0 : -1;
28a4d940
JS
926}
927
ae5a6c36 928struct grab_nth_branch_switch_cbdata {
98f85ff4
JH
929 int remaining;
930 struct strbuf buf;
ae5a6c36
JH
931};
932
933static int grab_nth_branch_switch(unsigned char *osha1, unsigned char *nsha1,
934 const char *email, unsigned long timestamp, int tz,
935 const char *message, void *cb_data)
936{
937 struct grab_nth_branch_switch_cbdata *cb = cb_data;
a884d0cb
TR
938 const char *match = NULL, *target = NULL;
939 size_t len;
940
95b567c7 941 if (skip_prefix(message, "checkout: moving from ", &match))
d7c03c1f 942 target = strstr(match, " to ");
ae5a6c36 943
c829774c 944 if (!match || !target)
ae5a6c36 945 return 0;
98f85ff4
JH
946 if (--(cb->remaining) == 0) {
947 len = target - match;
948 strbuf_reset(&cb->buf);
949 strbuf_add(&cb->buf, match, len);
950 return 1; /* we are done */
951 }
ae5a6c36
JH
952 return 0;
953}
954
955/*
ae0ba8e2
JH
956 * Parse @{-N} syntax, return the number of characters parsed
957 * if successful; otherwise signal an error with negative value.
ae5a6c36 958 */
8cd4249c
JK
959static int interpret_nth_prior_checkout(const char *name, int namelen,
960 struct strbuf *buf)
ae5a6c36 961{
c2883e62 962 long nth;
98f85ff4 963 int retval;
ae5a6c36 964 struct grab_nth_branch_switch_cbdata cb;
a884d0cb
TR
965 const char *brace;
966 char *num_end;
ae5a6c36 967
8cd4249c
JK
968 if (namelen < 4)
969 return -1;
ae5a6c36
JH
970 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
971 return -1;
8cd4249c 972 brace = memchr(name, '}', namelen);
a884d0cb
TR
973 if (!brace)
974 return -1;
98f85ff4 975 nth = strtol(name + 3, &num_end, 10);
a884d0cb 976 if (num_end != brace)
ae5a6c36 977 return -1;
c2883e62
JH
978 if (nth <= 0)
979 return -1;
98f85ff4
JH
980 cb.remaining = nth;
981 strbuf_init(&cb.buf, 20);
982
39765e59 983 retval = 0;
98f85ff4
JH
984 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch, &cb)) {
985 strbuf_reset(buf);
e992d1eb 986 strbuf_addbuf(buf, &cb.buf);
98f85ff4
JH
987 retval = brace - name + 1;
988 }
a884d0cb 989
98f85ff4 990 strbuf_release(&cb.buf);
39765e59 991 return retval;
ae5a6c36
JH
992}
993
151b2911 994int get_oid_mb(const char *name, struct object_id *oid)
619a644d
JH
995{
996 struct commit *one, *two;
997 struct commit_list *mbs;
151b2911 998 struct object_id oid_tmp;
619a644d
JH
999 const char *dots;
1000 int st;
1001
1002 dots = strstr(name, "...");
1003 if (!dots)
151b2911 1004 return get_oid(name, oid);
619a644d 1005 if (dots == name)
151b2911 1006 st = get_oid("HEAD", &oid_tmp);
619a644d
JH
1007 else {
1008 struct strbuf sb;
1009 strbuf_init(&sb, dots - name);
1010 strbuf_add(&sb, name, dots - name);
151b2911 1011 st = get_sha1_committish(sb.buf, oid_tmp.hash);
619a644d
JH
1012 strbuf_release(&sb);
1013 }
1014 if (st)
1015 return st;
151b2911 1016 one = lookup_commit_reference_gently(oid_tmp.hash, 0);
619a644d
JH
1017 if (!one)
1018 return -1;
1019
151b2911 1020 if (get_sha1_committish(dots[3] ? (dots + 3) : "HEAD", oid_tmp.hash))
619a644d 1021 return -1;
151b2911 1022 two = lookup_commit_reference_gently(oid_tmp.hash, 0);
619a644d
JH
1023 if (!two)
1024 return -1;
2ce406cc 1025 mbs = get_merge_bases(one, two);
619a644d
JH
1026 if (!mbs || mbs->next)
1027 st = -1;
1028 else {
1029 st = 0;
151b2911 1030 oidcpy(oid, &mbs->item->object.oid);
619a644d
JH
1031 }
1032 free_commit_list(mbs);
1033 return st;
1034}
1035
9ba89f48
FC
1036/* parse @something syntax, when 'something' is not {.*} */
1037static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1038{
1039 const char *next;
1040
1041 if (len || name[1] == '{')
1042 return -1;
1043
1044 /* make sure it's a single @, or @@{.*}, not @foo */
8cd4249c 1045 next = memchr(name + len + 1, '@', namelen - len - 1);
9ba89f48
FC
1046 if (next && next[1] != '{')
1047 return -1;
1048 if (!next)
1049 next = name + namelen;
1050 if (next != name + 1)
1051 return -1;
1052
1053 strbuf_reset(buf);
1054 strbuf_add(buf, "HEAD", 4);
1055 return 1;
1056}
1057
7a0a49a7
FC
1058static int reinterpret(const char *name, int namelen, int len, struct strbuf *buf)
1059{
1060 /* we have extra data, which might need further processing */
1061 struct strbuf tmp = STRBUF_INIT;
1062 int used = buf->len;
1063 int ret;
1064
1065 strbuf_add(buf, name + len, namelen - len);
cf99a761 1066 ret = interpret_branch_name(buf->buf, buf->len, &tmp);
7a0a49a7
FC
1067 /* that data was not interpreted, remove our cruft */
1068 if (ret < 0) {
1069 strbuf_setlen(buf, used);
1070 return len;
1071 }
1072 strbuf_reset(buf);
1073 strbuf_addbuf(buf, &tmp);
1074 strbuf_release(&tmp);
1075 /* tweak for size of {-N} versus expanded ref name */
1076 return ret - used + len;
1077}
1078
a39c14af
JK
1079static void set_shortened_ref(struct strbuf *buf, const char *ref)
1080{
1081 char *s = shorten_unambiguous_ref(ref, 0);
1082 strbuf_reset(buf);
1083 strbuf_addstr(buf, s);
1084 free(s);
1085}
1086
48c58471
JK
1087static int interpret_branch_mark(const char *name, int namelen,
1088 int at, struct strbuf *buf,
1089 int (*get_mark)(const char *, int),
1090 const char *(*get_data)(struct branch *,
1091 struct strbuf *))
a39c14af
JK
1092{
1093 int len;
48c58471
JK
1094 struct branch *branch;
1095 struct strbuf err = STRBUF_INIT;
1096 const char *value;
a39c14af 1097
48c58471 1098 len = get_mark(name + at, namelen - at);
a39c14af
JK
1099 if (!len)
1100 return -1;
1101
3f6eb30f
JK
1102 if (memchr(name, ':', at))
1103 return -1;
1104
48c58471
JK
1105 if (at) {
1106 char *name_str = xmemdupz(name, at);
1107 branch = branch_get(name_str);
1108 free(name_str);
1109 } else
1110 branch = branch_get(NULL);
1111
1112 value = get_data(branch, &err);
1113 if (!value)
1114 die("%s", err.buf);
1115
1116 set_shortened_ref(buf, value);
a39c14af
JK
1117 return len + at;
1118}
1119
ae0ba8e2
JH
1120/*
1121 * This reads short-hand syntax that not only evaluates to a commit
1122 * object name, but also can act as if the end user spelled the name
1123 * of the branch from the command line.
1124 *
1125 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1126 * places the name of the branch in the given buf and returns the
1127 * number of characters parsed if successful.
1128 *
1129 * - "<branch>@{upstream}" finds the name of the other ref that
1130 * <branch> is configured to merge with (missing <branch> defaults
1131 * to the current branch), and places the name of the branch in the
1132 * given buf and returns the number of characters parsed if
1133 * successful.
1134 *
1135 * If the input is not of the accepted format, it returns a negative
1136 * number to signal an error.
1137 *
1138 * If the input was ok but there are not N branch switches in the
1139 * reflog, it returns 0.
1140 */
cf99a761 1141int interpret_branch_name(const char *name, int namelen, struct strbuf *buf)
ae0ba8e2 1142{
f278f40f 1143 char *at;
9892d5d4 1144 const char *start;
8cd4249c 1145 int len = interpret_nth_prior_checkout(name, namelen, buf);
ae0ba8e2 1146
cf99a761
FC
1147 if (!namelen)
1148 namelen = strlen(name);
1149
1f27e7d5 1150 if (!len) {
ae0ba8e2 1151 return len; /* syntax Ok, not enough switches */
1f27e7d5
FC
1152 } else if (len > 0) {
1153 if (len == namelen)
1154 return len; /* consumed all */
1155 else
1156 return reinterpret(name, namelen, len, buf);
d46a8301
JK
1157 }
1158
9892d5d4
JK
1159 for (start = name;
1160 (at = memchr(start, '@', namelen - (start - name)));
1161 start = at + 1) {
9ba89f48 1162
9892d5d4
JK
1163 len = interpret_empty_at(name, namelen, at - name, buf);
1164 if (len > 0)
1165 return reinterpret(name, namelen, len, buf);
9ba89f48 1166
48c58471
JK
1167 len = interpret_branch_mark(name, namelen, at - name, buf,
1168 upstream_mark, branch_get_upstream);
9892d5d4
JK
1169 if (len > 0)
1170 return len;
adfe5d04
JK
1171
1172 len = interpret_branch_mark(name, namelen, at - name, buf,
1173 push_mark, branch_get_push);
9892d5d4
JK
1174 if (len > 0)
1175 return len;
bb0dab5d 1176 }
9ba89f48 1177
a39c14af 1178 return -1;
ae0ba8e2
JH
1179}
1180
6bab74e7
JN
1181int strbuf_branchname(struct strbuf *sb, const char *name)
1182{
1183 int len = strlen(name);
cf99a761 1184 int used = interpret_branch_name(name, len, sb);
84cf2466
JH
1185
1186 if (used == len)
6bab74e7 1187 return 0;
84cf2466
JH
1188 if (used < 0)
1189 used = 0;
1190 strbuf_add(sb, name + used, len - used);
6bab74e7
JN
1191 return len;
1192}
1193
1194int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1195{
1196 strbuf_branchname(sb, name);
1197 if (name[0] == '-')
8d9c5010 1198 return -1;
6bab74e7 1199 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
8d9c5010 1200 return check_refname_format(sb->buf, 0);
6bab74e7
JN
1201}
1202
9938af6a
JH
1203/*
1204 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1205 * notably "xyz^" for "parent of xyz"
1206 */
1207int get_sha1(const char *name, unsigned char *sha1)
1208{
573285e5 1209 struct object_context unused;
33bd598c 1210 return get_sha1_with_context(name, 0, sha1, &unused);
a0cd87a5
MK
1211}
1212
2764fd93 1213/*
1214 * This is like "get_sha1()", but for struct object_id.
1215 */
1216int get_oid(const char *name, struct object_id *oid)
1217{
1218 return get_sha1(name, oid->hash);
1219}
1220
1221
cd74e473 1222/*
a8a5406a 1223 * Many callers know that the user meant to name a commit-ish by
cd74e473
JH
1224 * syntactical positions where the object name appears. Calling this
1225 * function allows the machinery to disambiguate shorter-than-unique
a8a5406a 1226 * abbreviated object names between commit-ish and others.
cd74e473
JH
1227 *
1228 * Note that this does NOT error out when the named object is not a
a8a5406a 1229 * commit-ish. It is merely to give a hint to the disambiguation
cd74e473
JH
1230 * machinery.
1231 */
1232int get_sha1_committish(const char *name, unsigned char *sha1)
1233{
1234 struct object_context unused;
1235 return get_sha1_with_context(name, GET_SHA1_COMMITTISH,
1236 sha1, &unused);
1237}
1238
daba53ae
JH
1239int get_sha1_treeish(const char *name, unsigned char *sha1)
1240{
1241 struct object_context unused;
1242 return get_sha1_with_context(name, GET_SHA1_TREEISH,
1243 sha1, &unused);
1244}
1245
1246int get_sha1_commit(const char *name, unsigned char *sha1)
1247{
1248 struct object_context unused;
1249 return get_sha1_with_context(name, GET_SHA1_COMMIT,
1250 sha1, &unused);
1251}
1252
1253int get_sha1_tree(const char *name, unsigned char *sha1)
1254{
1255 struct object_context unused;
1256 return get_sha1_with_context(name, GET_SHA1_TREE,
1257 sha1, &unused);
1258}
1259
1260int get_sha1_blob(const char *name, unsigned char *sha1)
1261{
1262 struct object_context unused;
1263 return get_sha1_with_context(name, GET_SHA1_BLOB,
1264 sha1, &unused);
a0cd87a5
MK
1265}
1266
009fee47
MM
1267/* Must be called only when object_name:filename doesn't exist. */
1268static void diagnose_invalid_sha1_path(const char *prefix,
1269 const char *filename,
1270 const unsigned char *tree_sha1,
b2981d06
RS
1271 const char *object_name,
1272 int object_name_len)
009fee47 1273{
009fee47
MM
1274 unsigned char sha1[20];
1275 unsigned mode;
1276
1277 if (!prefix)
1278 prefix = "";
1279
dbe44faa 1280 if (file_exists(filename))
b2981d06
RS
1281 die("Path '%s' exists on disk, but not in '%.*s'.",
1282 filename, object_name_len, object_name);
009fee47 1283 if (errno == ENOENT || errno == ENOTDIR) {
b2724c87 1284 char *fullname = xstrfmt("%s%s", prefix, filename);
009fee47
MM
1285
1286 if (!get_tree_entry(tree_sha1, fullname,
1287 sha1, &mode)) {
1288 die("Path '%s' exists, but not '%s'.\n"
b2981d06 1289 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
009fee47
MM
1290 fullname,
1291 filename,
b2981d06 1292 object_name_len, object_name,
e41d718c 1293 fullname,
b2981d06 1294 object_name_len, object_name,
e41d718c 1295 filename);
009fee47 1296 }
b2981d06
RS
1297 die("Path '%s' does not exist in '%.*s'",
1298 filename, object_name_len, object_name);
009fee47
MM
1299 }
1300}
1301
1302/* Must be called only when :stage:filename doesn't exist. */
1303static void diagnose_invalid_index_path(int stage,
1304 const char *prefix,
1305 const char *filename)
1306{
9c5e6c80 1307 const struct cache_entry *ce;
009fee47
MM
1308 int pos;
1309 unsigned namelen = strlen(filename);
43bb66ae 1310 struct strbuf fullname = STRBUF_INIT;
009fee47
MM
1311
1312 if (!prefix)
1313 prefix = "";
1314
1315 /* Wrong stage number? */
1316 pos = cache_name_pos(filename, namelen);
1317 if (pos < 0)
1318 pos = -pos - 1;
77e8466f
MH
1319 if (pos < active_nr) {
1320 ce = active_cache[pos];
1321 if (ce_namelen(ce) == namelen &&
1322 !memcmp(ce->name, filename, namelen))
1323 die("Path '%s' is in the index, but not at stage %d.\n"
1324 "Did you mean ':%d:%s'?",
1325 filename, stage,
1326 ce_stage(ce), filename);
1327 }
009fee47
MM
1328
1329 /* Confusion between relative and absolute filenames? */
43bb66ae
JK
1330 strbuf_addstr(&fullname, prefix);
1331 strbuf_addstr(&fullname, filename);
1332 pos = cache_name_pos(fullname.buf, fullname.len);
009fee47
MM
1333 if (pos < 0)
1334 pos = -pos - 1;
77e8466f
MH
1335 if (pos < active_nr) {
1336 ce = active_cache[pos];
43bb66ae
JK
1337 if (ce_namelen(ce) == fullname.len &&
1338 !memcmp(ce->name, fullname.buf, fullname.len))
77e8466f 1339 die("Path '%s' is in the index, but not '%s'.\n"
e41d718c 1340 "Did you mean ':%d:%s' aka ':%d:./%s'?",
43bb66ae
JK
1341 fullname.buf, filename,
1342 ce_stage(ce), fullname.buf,
e41d718c 1343 ce_stage(ce), filename);
77e8466f 1344 }
009fee47 1345
dbe44faa 1346 if (file_exists(filename))
009fee47
MM
1347 die("Path '%s' exists on disk, but not in the index.", filename);
1348 if (errno == ENOENT || errno == ENOTDIR)
1349 die("Path '%s' does not exist (neither on disk nor in the index).",
1350 filename);
1351
43bb66ae 1352 strbuf_release(&fullname);
009fee47
MM
1353}
1354
1355
979f7929
NTND
1356static char *resolve_relative_path(const char *rel)
1357{
59556548 1358 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
979f7929
NTND
1359 return NULL;
1360
979f7929
NTND
1361 if (!is_inside_work_tree())
1362 die("relative path syntax can't be used outside working tree.");
1363
1364 /* die() inside prefix_path() if resolved path is outside worktree */
1365 return prefix_path(startup_info->prefix,
1366 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1367 rel);
1368}
1369
33bd598c
JH
1370static int get_sha1_with_context_1(const char *name,
1371 unsigned flags,
1372 const char *prefix,
1373 unsigned char *sha1,
1374 struct object_context *oc)
a0cd87a5
MK
1375{
1376 int ret, bracket_depth;
73b0e5af
JH
1377 int namelen = strlen(name);
1378 const char *cp;
33bd598c 1379 int only_to_die = flags & GET_SHA1_ONLY_TO_DIE;
5119602a 1380
7243ffdd
JK
1381 if (only_to_die)
1382 flags |= GET_SHA1_QUIETLY;
1383
573285e5
CP
1384 memset(oc, 0, sizeof(*oc));
1385 oc->mode = S_IFINVALID;
33bd598c 1386 ret = get_sha1_1(name, namelen, sha1, flags);
73b0e5af
JH
1387 if (!ret)
1388 return ret;
33bd598c
JH
1389 /*
1390 * sha1:path --> object name of path in ent sha1
979f7929
NTND
1391 * :path -> object name of absolute path in index
1392 * :./path -> object name of path relative to cwd in index
73b0e5af 1393 * :[0-3]:path -> object name of path in index at stage
95ad6d2d 1394 * :/foo -> recent commit matching foo
73b0e5af
JH
1395 */
1396 if (name[0] == ':') {
1397 int stage = 0;
9c5e6c80 1398 const struct cache_entry *ce;
979f7929 1399 char *new_path = NULL;
73b0e5af 1400 int pos;
2e83b66c 1401 if (!only_to_die && namelen > 2 && name[1] == '/') {
84baa31b 1402 struct commit_list *list = NULL;
2b2a5be3 1403
84baa31b 1404 for_each_ref(handle_one_ref, &list);
e8d1dfe6 1405 commit_list_sort_by_date(&list);
84baa31b
NTND
1406 return get_sha1_oneline(name + 2, sha1, list);
1407 }
73b0e5af
JH
1408 if (namelen < 3 ||
1409 name[2] != ':' ||
1410 name[1] < '0' || '3' < name[1])
1411 cp = name + 1;
1412 else {
1413 stage = name[1] - '0';
1414 cp = name + 3;
5119602a 1415 }
3d6e0f74
JH
1416 new_path = resolve_relative_path(cp);
1417 if (!new_path) {
1418 namelen = namelen - (cp - name);
1419 } else {
1420 cp = new_path;
1421 namelen = strlen(cp);
1422 }
573285e5 1423
2ce63e9f 1424 strlcpy(oc->path, cp, sizeof(oc->path));
573285e5 1425
73b0e5af
JH
1426 if (!active_cache)
1427 read_cache();
73b0e5af
JH
1428 pos = cache_name_pos(cp, namelen);
1429 if (pos < 0)
1430 pos = -pos - 1;
1431 while (pos < active_nr) {
1432 ce = active_cache[pos];
1433 if (ce_namelen(ce) != namelen ||
1434 memcmp(ce->name, cp, namelen))
1435 break;
1436 if (ce_stage(ce) == stage) {
99d1a986 1437 hashcpy(sha1, ce->oid.hash);
90064710 1438 oc->mode = ce->ce_mode;
979f7929 1439 free(new_path);
73b0e5af
JH
1440 return 0;
1441 }
e7cef45f 1442 pos++;
73b0e5af 1443 }
2e83b66c 1444 if (only_to_die && name[1] && name[1] != '/')
009fee47 1445 diagnose_invalid_index_path(stage, prefix, cp);
979f7929 1446 free(new_path);
73b0e5af
JH
1447 return -1;
1448 }
cce91a2c
SP
1449 for (cp = name, bracket_depth = 0; *cp; cp++) {
1450 if (*cp == '{')
1451 bracket_depth++;
1452 else if (bracket_depth && *cp == '}')
1453 bracket_depth--;
1454 else if (!bracket_depth && *cp == ':')
1455 break;
1456 }
1457 if (*cp == ':') {
73b0e5af 1458 unsigned char tree_sha1[20];
b2981d06 1459 int len = cp - name;
8a10fea4
JK
1460 unsigned sub_flags = flags;
1461
1462 sub_flags &= ~GET_SHA1_DISAMBIGUATORS;
1463 sub_flags |= GET_SHA1_TREEISH;
1464
1465 if (!get_sha1_1(name, len, tree_sha1, sub_flags)) {
009fee47 1466 const char *filename = cp+1;
979f7929
NTND
1467 char *new_filename = NULL;
1468
1469 new_filename = resolve_relative_path(filename);
1470 if (new_filename)
1471 filename = new_filename;
c4ec9677
DT
1472 if (flags & GET_SHA1_FOLLOW_SYMLINKS) {
1473 ret = get_tree_entry_follow_symlinks(tree_sha1,
1474 filename, sha1, &oc->symlink_path,
1475 &oc->mode);
1476 } else {
1477 ret = get_tree_entry(tree_sha1, filename,
1478 sha1, &oc->mode);
1479 if (ret && only_to_die) {
1480 diagnose_invalid_sha1_path(prefix,
1481 filename,
1482 tree_sha1,
1483 name, len);
1484 }
009fee47 1485 }
573285e5 1486 hashcpy(oc->tree, tree_sha1);
2ce63e9f 1487 strlcpy(oc->path, filename, sizeof(oc->path));
573285e5 1488
979f7929 1489 free(new_filename);
009fee47
MM
1490 return ret;
1491 } else {
2e83b66c 1492 if (only_to_die)
b2981d06 1493 die("Invalid object name '%.*s'.", len, name);
009fee47 1494 }
5119602a
LT
1495 }
1496 return ret;
9938af6a 1497}
f01cc14c 1498
8c135ea2
JH
1499/*
1500 * Call this function when you know "name" given by the end user must
1501 * name an object but it doesn't; the function _may_ die with a better
1502 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1503 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1504 * you have a chance to diagnose the error further.
1505 */
1506void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
f01cc14c
JH
1507{
1508 struct object_context oc;
8c135ea2 1509 unsigned char sha1[20];
33bd598c 1510 get_sha1_with_context_1(name, GET_SHA1_ONLY_TO_DIE, prefix, sha1, &oc);
8c135ea2
JH
1511}
1512
33bd598c 1513int get_sha1_with_context(const char *str, unsigned flags, unsigned char *sha1, struct object_context *orc)
f01cc14c 1514{
c4ec9677
DT
1515 if (flags & GET_SHA1_FOLLOW_SYMLINKS && flags & GET_SHA1_ONLY_TO_DIE)
1516 die("BUG: incompatible flags for get_sha1_with_context");
33bd598c 1517 return get_sha1_with_context_1(str, flags, NULL, sha1, orc);
f01cc14c 1518}