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