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