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