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