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