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