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