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