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