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