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