The thirteenth batch
[git.git] / object-name.c
blob0bfa29dbbfe9b489e454c03b419092294427425d
1 #include "git-compat-util.h"
2 #include "object-name.h"
3 #include "advice.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "tag.h"
9 #include "commit.h"
10 #include "tree.h"
11 #include "blob.h"
12 #include "tree-walk.h"
13 #include "refs.h"
14 #include "remote.h"
15 #include "dir.h"
16 #include "oid-array.h"
17 #include "oidtree.h"
18 #include "packfile.h"
19 #include "pretty.h"
20 #include "object-store-ll.h"
21 #include "read-cache-ll.h"
22 #include "repository.h"
23 #include "setup.h"
24 #include "submodule.h"
25 #include "midx.h"
26 #include "commit-reach.h"
27 #include "date.h"
29 static int get_oid_oneline(struct repository *r, const char *, struct object_id *, struct commit_list *);
31 typedef int (*disambiguate_hint_fn)(struct repository *, const struct object_id *, void *);
33 struct disambiguate_state {
34 int len; /* length of prefix in hex chars */
35 char hex_pfx[GIT_MAX_HEXSZ + 1];
36 struct object_id bin_pfx;
38 struct repository *repo;
39 disambiguate_hint_fn fn;
40 void *cb_data;
41 struct object_id candidate;
42 unsigned candidate_exists:1;
43 unsigned candidate_checked:1;
44 unsigned candidate_ok:1;
45 unsigned disambiguate_fn_used:1;
46 unsigned ambiguous:1;
47 unsigned always_call_fn:1;
50 static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
52 if (ds->always_call_fn) {
53 ds->ambiguous = ds->fn(ds->repo, current, ds->cb_data) ? 1 : 0;
54 return;
56 if (!ds->candidate_exists) {
57 /* this is the first candidate */
58 oidcpy(&ds->candidate, current);
59 ds->candidate_exists = 1;
60 return;
61 } else if (oideq(&ds->candidate, current)) {
62 /* the same as what we already have seen */
63 return;
66 if (!ds->fn) {
67 /* cannot disambiguate between ds->candidate and current */
68 ds->ambiguous = 1;
69 return;
72 if (!ds->candidate_checked) {
73 ds->candidate_ok = ds->fn(ds->repo, &ds->candidate, ds->cb_data);
74 ds->disambiguate_fn_used = 1;
75 ds->candidate_checked = 1;
78 if (!ds->candidate_ok) {
79 /* discard the candidate; we know it does not satisfy fn */
80 oidcpy(&ds->candidate, current);
81 ds->candidate_checked = 0;
82 return;
85 /* if we reach this point, we know ds->candidate satisfies fn */
86 if (ds->fn(ds->repo, current, ds->cb_data)) {
88 * if both current and candidate satisfy fn, we cannot
89 * disambiguate.
91 ds->candidate_ok = 0;
92 ds->ambiguous = 1;
95 /* otherwise, current can be discarded and candidate is still good */
98 static int match_hash(unsigned, const unsigned char *, const unsigned char *);
100 static enum cb_next match_prefix(const struct object_id *oid, void *arg)
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;
108 static void find_short_object_filename(struct disambiguate_state *ds)
110 struct object_directory *odb;
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);
117 static int match_hash(unsigned len, const unsigned char *a, const unsigned char *b)
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;
132 static void unique_in_midx(struct multi_pack_index *m,
133 struct disambiguate_state *ds)
135 uint32_t num, i, first = 0;
136 const struct object_id *current = NULL;
137 num = m->num_objects;
139 if (!num)
140 return;
142 bsearch_midx(&ds->bin_pfx, m, &first);
145 * At this point, "first" is the location of the lowest object
146 * with an object name that could match "bin_pfx". See if we have
147 * 0, 1 or more objects that actually match(es).
149 for (i = first; i < num && !ds->ambiguous; i++) {
150 struct object_id oid;
151 current = nth_midxed_object_oid(&oid, m, i);
152 if (!match_hash(ds->len, ds->bin_pfx.hash, current->hash))
153 break;
154 update_candidates(ds, current);
158 static void unique_in_pack(struct packed_git *p,
159 struct disambiguate_state *ds)
161 uint32_t num, i, first = 0;
163 if (p->multi_pack_index)
164 return;
166 if (open_pack_index(p) || !p->num_objects)
167 return;
169 num = p->num_objects;
170 bsearch_pack(&ds->bin_pfx, p, &first);
173 * At this point, "first" is the location of the lowest object
174 * with an object name that could match "bin_pfx". See if we have
175 * 0, 1 or more objects that actually match(es).
177 for (i = first; i < num && !ds->ambiguous; i++) {
178 struct object_id oid;
179 nth_packed_object_id(&oid, p, i);
180 if (!match_hash(ds->len, ds->bin_pfx.hash, oid.hash))
181 break;
182 update_candidates(ds, &oid);
186 static void find_short_packed_object(struct disambiguate_state *ds)
188 struct multi_pack_index *m;
189 struct packed_git *p;
191 for (m = get_multi_pack_index(ds->repo); m && !ds->ambiguous;
192 m = m->next)
193 unique_in_midx(m, ds);
194 for (p = get_packed_git(ds->repo); p && !ds->ambiguous;
195 p = p->next)
196 unique_in_pack(p, ds);
199 static int finish_object_disambiguation(struct disambiguate_state *ds,
200 struct object_id *oid)
202 if (ds->ambiguous)
203 return SHORT_NAME_AMBIGUOUS;
205 if (!ds->candidate_exists)
206 return MISSING_OBJECT;
208 if (!ds->candidate_checked)
210 * If this is the only candidate, there is no point
211 * calling the disambiguation hint callback.
213 * On the other hand, if the current candidate
214 * replaced an earlier candidate that did _not_ pass
215 * the disambiguation hint callback, then we do have
216 * more than one objects that match the short name
217 * given, so we should make sure this one matches;
218 * otherwise, if we discovered this one and the one
219 * that we previously discarded in the reverse order,
220 * we would end up showing different results in the
221 * same repository!
223 ds->candidate_ok = (!ds->disambiguate_fn_used ||
224 ds->fn(ds->repo, &ds->candidate, ds->cb_data));
226 if (!ds->candidate_ok)
227 return SHORT_NAME_AMBIGUOUS;
229 oidcpy(oid, &ds->candidate);
230 return 0;
233 static int disambiguate_commit_only(struct repository *r,
234 const struct object_id *oid,
235 void *cb_data UNUSED)
237 int kind = oid_object_info(r, oid, NULL);
238 return kind == OBJ_COMMIT;
241 static int disambiguate_committish_only(struct repository *r,
242 const struct object_id *oid,
243 void *cb_data UNUSED)
245 struct object *obj;
246 int kind;
248 kind = oid_object_info(r, oid, NULL);
249 if (kind == OBJ_COMMIT)
250 return 1;
251 if (kind != OBJ_TAG)
252 return 0;
254 /* We need to do this the hard way... */
255 obj = deref_tag(r, parse_object(r, oid), NULL, 0);
256 if (obj && obj->type == OBJ_COMMIT)
257 return 1;
258 return 0;
261 static int disambiguate_tree_only(struct repository *r,
262 const struct object_id *oid,
263 void *cb_data UNUSED)
265 int kind = oid_object_info(r, oid, NULL);
266 return kind == OBJ_TREE;
269 static int disambiguate_treeish_only(struct repository *r,
270 const struct object_id *oid,
271 void *cb_data UNUSED)
273 struct object *obj;
274 int kind;
276 kind = oid_object_info(r, oid, NULL);
277 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
278 return 1;
279 if (kind != OBJ_TAG)
280 return 0;
282 /* We need to do this the hard way... */
283 obj = deref_tag(r, parse_object(r, oid), NULL, 0);
284 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
285 return 1;
286 return 0;
289 static int disambiguate_blob_only(struct repository *r,
290 const struct object_id *oid,
291 void *cb_data UNUSED)
293 int kind = oid_object_info(r, oid, NULL);
294 return kind == OBJ_BLOB;
297 static disambiguate_hint_fn default_disambiguate_hint;
299 int set_disambiguate_hint_config(const char *var, const char *value)
301 static const struct {
302 const char *name;
303 disambiguate_hint_fn fn;
304 } hints[] = {
305 { "none", NULL },
306 { "commit", disambiguate_commit_only },
307 { "committish", disambiguate_committish_only },
308 { "tree", disambiguate_tree_only },
309 { "treeish", disambiguate_treeish_only },
310 { "blob", disambiguate_blob_only }
312 int i;
314 if (!value)
315 return config_error_nonbool(var);
317 for (i = 0; i < ARRAY_SIZE(hints); i++) {
318 if (!strcasecmp(value, hints[i].name)) {
319 default_disambiguate_hint = hints[i].fn;
320 return 0;
324 return error("unknown hint type for '%s': %s", var, value);
327 static int init_object_disambiguation(struct repository *r,
328 const char *name, int len,
329 struct disambiguate_state *ds)
331 int i;
333 if (len < MINIMUM_ABBREV || len > the_hash_algo->hexsz)
334 return -1;
336 memset(ds, 0, sizeof(*ds));
338 for (i = 0; i < len ;i++) {
339 unsigned char c = name[i];
340 unsigned char val;
341 if (c >= '0' && c <= '9')
342 val = c - '0';
343 else if (c >= 'a' && c <= 'f')
344 val = c - 'a' + 10;
345 else if (c >= 'A' && c <='F') {
346 val = c - 'A' + 10;
347 c -= 'A' - 'a';
349 else
350 return -1;
351 ds->hex_pfx[i] = c;
352 if (!(i & 1))
353 val <<= 4;
354 ds->bin_pfx.hash[i >> 1] |= val;
357 ds->len = len;
358 ds->hex_pfx[len] = '\0';
359 ds->repo = r;
360 prepare_alt_odb(r);
361 return 0;
364 struct ambiguous_output {
365 const struct disambiguate_state *ds;
366 struct strbuf advice;
367 struct strbuf sb;
370 static int show_ambiguous_object(const struct object_id *oid, void *data)
372 struct ambiguous_output *state = data;
373 const struct disambiguate_state *ds = state->ds;
374 struct strbuf *advice = &state->advice;
375 struct strbuf *sb = &state->sb;
376 int type;
377 const char *hash;
379 if (ds->fn && !ds->fn(ds->repo, oid, ds->cb_data))
380 return 0;
382 hash = repo_find_unique_abbrev(ds->repo, oid, DEFAULT_ABBREV);
383 type = oid_object_info(ds->repo, oid, NULL);
385 if (type < 0) {
387 * TRANSLATORS: This is a line of ambiguous object
388 * output shown when we cannot look up or parse the
389 * object in question. E.g. "deadbeef [bad object]".
391 strbuf_addf(sb, _("%s [bad object]"), hash);
392 goto out;
395 assert(type == OBJ_TREE || type == OBJ_COMMIT ||
396 type == OBJ_BLOB || type == OBJ_TAG);
398 if (type == OBJ_COMMIT) {
399 struct strbuf date = STRBUF_INIT;
400 struct strbuf msg = STRBUF_INIT;
401 struct commit *commit = lookup_commit(ds->repo, oid);
403 if (commit) {
404 struct pretty_print_context pp = {0};
405 pp.date_mode.type = DATE_SHORT;
406 repo_format_commit_message(the_repository, commit,
407 "%ad", &date, &pp);
408 repo_format_commit_message(the_repository, commit,
409 "%s", &msg, &pp);
413 * TRANSLATORS: This is a line of ambiguous commit
414 * object output. E.g.:
416 * "deadbeef commit 2021-01-01 - Some Commit Message"
418 strbuf_addf(sb, _("%s commit %s - %s"), hash, date.buf,
419 msg.buf);
421 strbuf_release(&date);
422 strbuf_release(&msg);
423 } else if (type == OBJ_TAG) {
424 struct tag *tag = lookup_tag(ds->repo, oid);
426 if (!parse_tag(tag) && tag->tag) {
428 * TRANSLATORS: This is a line of ambiguous
429 * tag object output. E.g.:
431 * "deadbeef tag 2022-01-01 - Some Tag Message"
433 * The second argument is the YYYY-MM-DD found
434 * in the tag.
436 * The third argument is the "tag" string
437 * from object.c.
439 strbuf_addf(sb, _("%s tag %s - %s"), hash,
440 show_date(tag->date, 0, DATE_MODE(SHORT)),
441 tag->tag);
442 } else {
444 * TRANSLATORS: This is a line of ambiguous
445 * tag object output where we couldn't parse
446 * the tag itself. E.g.:
448 * "deadbeef [bad tag, could not parse it]"
450 strbuf_addf(sb, _("%s [bad tag, could not parse it]"),
451 hash);
453 } else if (type == OBJ_TREE) {
455 * TRANSLATORS: This is a line of ambiguous <type>
456 * object output. E.g. "deadbeef tree".
458 strbuf_addf(sb, _("%s tree"), hash);
459 } else if (type == OBJ_BLOB) {
461 * TRANSLATORS: This is a line of ambiguous <type>
462 * object output. E.g. "deadbeef blob".
464 strbuf_addf(sb, _("%s blob"), hash);
468 out:
470 * TRANSLATORS: This is line item of ambiguous object output
471 * from describe_ambiguous_object() above. For RTL languages
472 * you'll probably want to swap the "%s" and leading " " space
473 * around.
475 strbuf_addf(advice, _(" %s\n"), sb->buf);
477 strbuf_reset(sb);
478 return 0;
481 static int collect_ambiguous(const struct object_id *oid, void *data)
483 oid_array_append(data, oid);
484 return 0;
487 static int repo_collect_ambiguous(struct repository *r UNUSED,
488 const struct object_id *oid,
489 void *data)
491 return collect_ambiguous(oid, data);
494 static int sort_ambiguous(const void *a, const void *b, void *ctx)
496 struct repository *sort_ambiguous_repo = ctx;
497 int a_type = oid_object_info(sort_ambiguous_repo, a, NULL);
498 int b_type = oid_object_info(sort_ambiguous_repo, b, NULL);
499 int a_type_sort;
500 int b_type_sort;
503 * Sorts by hash within the same object type, just as
504 * oid_array_for_each_unique() would do.
506 if (a_type == b_type)
507 return oidcmp(a, b);
510 * Between object types show tags, then commits, and finally
511 * trees and blobs.
513 * The object_type enum is commit, tree, blob, tag, but we
514 * want tag, commit, tree blob. Cleverly (perhaps too
515 * cleverly) do that with modulus, since the enum assigns 1 to
516 * commit, so tag becomes 0.
518 a_type_sort = a_type % 4;
519 b_type_sort = b_type % 4;
520 return a_type_sort > b_type_sort ? 1 : -1;
523 static void sort_ambiguous_oid_array(struct repository *r, struct oid_array *a)
525 QSORT_S(a->oid, a->nr, sort_ambiguous, r);
528 static enum get_oid_result get_short_oid(struct repository *r,
529 const char *name, int len,
530 struct object_id *oid,
531 unsigned flags)
533 int status;
534 struct disambiguate_state ds;
535 int quietly = !!(flags & GET_OID_QUIETLY);
537 if (init_object_disambiguation(r, name, len, &ds) < 0)
538 return -1;
540 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
541 BUG("multiple get_short_oid disambiguator flags");
543 if (flags & GET_OID_COMMIT)
544 ds.fn = disambiguate_commit_only;
545 else if (flags & GET_OID_COMMITTISH)
546 ds.fn = disambiguate_committish_only;
547 else if (flags & GET_OID_TREE)
548 ds.fn = disambiguate_tree_only;
549 else if (flags & GET_OID_TREEISH)
550 ds.fn = disambiguate_treeish_only;
551 else if (flags & GET_OID_BLOB)
552 ds.fn = disambiguate_blob_only;
553 else
554 ds.fn = default_disambiguate_hint;
556 find_short_object_filename(&ds);
557 find_short_packed_object(&ds);
558 status = finish_object_disambiguation(&ds, oid);
561 * If we didn't find it, do the usual reprepare() slow-path,
562 * since the object may have recently been added to the repository
563 * or migrated from loose to packed.
565 if (status == MISSING_OBJECT) {
566 reprepare_packed_git(r);
567 find_short_object_filename(&ds);
568 find_short_packed_object(&ds);
569 status = finish_object_disambiguation(&ds, oid);
572 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
573 struct oid_array collect = OID_ARRAY_INIT;
574 struct ambiguous_output out = {
575 .ds = &ds,
576 .sb = STRBUF_INIT,
577 .advice = STRBUF_INIT,
580 error(_("short object ID %s is ambiguous"), ds.hex_pfx);
583 * We may still have ambiguity if we simply saw a series of
584 * candidates that did not satisfy our hint function. In
585 * that case, we still want to show them, so disable the hint
586 * function entirely.
588 if (!ds.ambiguous)
589 ds.fn = NULL;
591 repo_for_each_abbrev(r, ds.hex_pfx, collect_ambiguous, &collect);
592 sort_ambiguous_oid_array(r, &collect);
594 if (oid_array_for_each(&collect, show_ambiguous_object, &out))
595 BUG("show_ambiguous_object shouldn't return non-zero");
598 * TRANSLATORS: The argument is the list of ambiguous
599 * objects composed in show_ambiguous_object(). See
600 * its "TRANSLATORS" comments for details.
602 advise(_("The candidates are:\n%s"), out.advice.buf);
604 oid_array_clear(&collect);
605 strbuf_release(&out.advice);
606 strbuf_release(&out.sb);
609 return status;
612 int repo_for_each_abbrev(struct repository *r, const char *prefix,
613 each_abbrev_fn fn, void *cb_data)
615 struct oid_array collect = OID_ARRAY_INIT;
616 struct disambiguate_state ds;
617 int ret;
619 if (init_object_disambiguation(r, prefix, strlen(prefix), &ds) < 0)
620 return -1;
622 ds.always_call_fn = 1;
623 ds.fn = repo_collect_ambiguous;
624 ds.cb_data = &collect;
625 find_short_object_filename(&ds);
626 find_short_packed_object(&ds);
628 ret = oid_array_for_each_unique(&collect, fn, cb_data);
629 oid_array_clear(&collect);
630 return ret;
634 * Return the slot of the most-significant bit set in "val". There are various
635 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
636 * probably not a big deal here.
638 static unsigned msb(unsigned long val)
640 unsigned r = 0;
641 while (val >>= 1)
642 r++;
643 return r;
646 struct min_abbrev_data {
647 unsigned int init_len;
648 unsigned int cur_len;
649 char *hex;
650 struct repository *repo;
651 const struct object_id *oid;
654 static inline char get_hex_char_from_oid(const struct object_id *oid,
655 unsigned int pos)
657 static const char hex[] = "0123456789abcdef";
659 if ((pos & 1) == 0)
660 return hex[oid->hash[pos >> 1] >> 4];
661 else
662 return hex[oid->hash[pos >> 1] & 0xf];
665 static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
667 struct min_abbrev_data *mad = cb_data;
669 unsigned int i = mad->init_len;
670 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
671 i++;
673 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
674 mad->cur_len = i + 1;
676 return 0;
679 static int repo_extend_abbrev_len(struct repository *r UNUSED,
680 const struct object_id *oid,
681 void *cb_data)
683 return extend_abbrev_len(oid, cb_data);
686 static void find_abbrev_len_for_midx(struct multi_pack_index *m,
687 struct min_abbrev_data *mad)
689 int match = 0;
690 uint32_t num, first = 0;
691 struct object_id oid;
692 const struct object_id *mad_oid;
694 if (!m->num_objects)
695 return;
697 num = m->num_objects;
698 mad_oid = mad->oid;
699 match = bsearch_midx(mad_oid, m, &first);
702 * first is now the position in the packfile where we would insert
703 * mad->hash if it does not exist (or the position of mad->hash if
704 * it does exist). Hence, we consider a maximum of two objects
705 * nearby for the abbreviation length.
707 mad->init_len = 0;
708 if (!match) {
709 if (nth_midxed_object_oid(&oid, m, first))
710 extend_abbrev_len(&oid, mad);
711 } else if (first < num - 1) {
712 if (nth_midxed_object_oid(&oid, m, first + 1))
713 extend_abbrev_len(&oid, mad);
715 if (first > 0) {
716 if (nth_midxed_object_oid(&oid, m, first - 1))
717 extend_abbrev_len(&oid, mad);
719 mad->init_len = mad->cur_len;
722 static void find_abbrev_len_for_pack(struct packed_git *p,
723 struct min_abbrev_data *mad)
725 int match = 0;
726 uint32_t num, first = 0;
727 struct object_id oid;
728 const struct object_id *mad_oid;
730 if (p->multi_pack_index)
731 return;
733 if (open_pack_index(p) || !p->num_objects)
734 return;
736 num = p->num_objects;
737 mad_oid = mad->oid;
738 match = bsearch_pack(mad_oid, p, &first);
741 * first is now the position in the packfile where we would insert
742 * mad->hash if it does not exist (or the position of mad->hash if
743 * it does exist). Hence, we consider a maximum of two objects
744 * nearby for the abbreviation length.
746 mad->init_len = 0;
747 if (!match) {
748 if (!nth_packed_object_id(&oid, p, first))
749 extend_abbrev_len(&oid, mad);
750 } else if (first < num - 1) {
751 if (!nth_packed_object_id(&oid, p, first + 1))
752 extend_abbrev_len(&oid, mad);
754 if (first > 0) {
755 if (!nth_packed_object_id(&oid, p, first - 1))
756 extend_abbrev_len(&oid, mad);
758 mad->init_len = mad->cur_len;
761 static void find_abbrev_len_packed(struct min_abbrev_data *mad)
763 struct multi_pack_index *m;
764 struct packed_git *p;
766 for (m = get_multi_pack_index(mad->repo); m; m = m->next)
767 find_abbrev_len_for_midx(m, mad);
768 for (p = get_packed_git(mad->repo); p; p = p->next)
769 find_abbrev_len_for_pack(p, mad);
772 void strbuf_repo_add_unique_abbrev(struct strbuf *sb, struct repository *repo,
773 const struct object_id *oid, int abbrev_len)
775 int r;
776 strbuf_grow(sb, GIT_MAX_HEXSZ + 1);
777 r = repo_find_unique_abbrev_r(repo, sb->buf + sb->len, oid, abbrev_len);
778 strbuf_setlen(sb, sb->len + r);
781 void strbuf_add_unique_abbrev(struct strbuf *sb, const struct object_id *oid,
782 int abbrev_len)
784 strbuf_repo_add_unique_abbrev(sb, the_repository, oid, abbrev_len);
787 int repo_find_unique_abbrev_r(struct repository *r, char *hex,
788 const struct object_id *oid, int len)
790 struct disambiguate_state ds;
791 struct min_abbrev_data mad;
792 struct object_id oid_ret;
793 const unsigned hexsz = r->hash_algo->hexsz;
795 if (len < 0) {
796 unsigned long count = repo_approximate_object_count(r);
798 * Add one because the MSB only tells us the highest bit set,
799 * not including the value of all the _other_ bits (so "15"
800 * is only one off of 2^4, but the MSB is the 3rd bit.
802 len = msb(count) + 1;
804 * We now know we have on the order of 2^len objects, which
805 * expects a collision at 2^(len/2). But we also care about hex
806 * chars, not bits, and there are 4 bits per hex. So all
807 * together we need to divide by 2 and round up.
809 len = DIV_ROUND_UP(len, 2);
811 * For very small repos, we stick with our regular fallback.
813 if (len < FALLBACK_DEFAULT_ABBREV)
814 len = FALLBACK_DEFAULT_ABBREV;
817 oid_to_hex_r(hex, oid);
818 if (len == hexsz || !len)
819 return hexsz;
821 mad.repo = r;
822 mad.init_len = len;
823 mad.cur_len = len;
824 mad.hex = hex;
825 mad.oid = oid;
827 find_abbrev_len_packed(&mad);
829 if (init_object_disambiguation(r, hex, mad.cur_len, &ds) < 0)
830 return -1;
832 ds.fn = repo_extend_abbrev_len;
833 ds.always_call_fn = 1;
834 ds.cb_data = (void *)&mad;
836 find_short_object_filename(&ds);
837 (void)finish_object_disambiguation(&ds, &oid_ret);
839 hex[mad.cur_len] = 0;
840 return mad.cur_len;
843 const char *repo_find_unique_abbrev(struct repository *r,
844 const struct object_id *oid,
845 int len)
847 static int bufno;
848 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
849 char *hex = hexbuffer[bufno];
850 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
851 repo_find_unique_abbrev_r(r, hex, oid, len);
852 return hex;
855 static int ambiguous_path(const char *path, int len)
857 int slash = 1;
858 int cnt;
860 for (cnt = 0; cnt < len; cnt++) {
861 switch (*path++) {
862 case '\0':
863 break;
864 case '/':
865 if (slash)
866 break;
867 slash = 1;
868 continue;
869 case '.':
870 continue;
871 default:
872 slash = 0;
873 continue;
875 break;
877 return slash;
880 static inline int at_mark(const char *string, int len,
881 const char **suffix, int nr)
883 int i;
885 for (i = 0; i < nr; i++) {
886 int suffix_len = strlen(suffix[i]);
887 if (suffix_len <= len
888 && !strncasecmp(string, suffix[i], suffix_len))
889 return suffix_len;
891 return 0;
894 static inline int upstream_mark(const char *string, int len)
896 const char *suffix[] = { "@{upstream}", "@{u}" };
897 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
900 static inline int push_mark(const char *string, int len)
902 const char *suffix[] = { "@{push}" };
903 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
906 static enum get_oid_result get_oid_1(struct repository *r, const char *name, int len, struct object_id *oid, unsigned lookup_flags);
907 static int interpret_nth_prior_checkout(struct repository *r, const char *name, int namelen, struct strbuf *buf);
909 static int get_oid_basic(struct repository *r, const char *str, int len,
910 struct object_id *oid, unsigned int flags)
912 static const char *warn_msg = "refname '%.*s' is ambiguous.";
913 static const char *object_name_msg = N_(
914 "Git normally never creates a ref that ends with 40 hex characters\n"
915 "because it will be ignored when you just specify 40-hex. These refs\n"
916 "may be created by mistake. For example,\n"
917 "\n"
918 " git switch -c $br $(git rev-parse ...)\n"
919 "\n"
920 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
921 "examine these refs and maybe delete them. Turn this message off by\n"
922 "running \"git config advice.objectNameWarning false\"");
923 struct object_id tmp_oid;
924 char *real_ref = NULL;
925 int refs_found = 0;
926 int at, reflog_len, nth_prior = 0;
927 int fatal = !(flags & GET_OID_QUIETLY);
929 if (len == r->hash_algo->hexsz && !get_oid_hex(str, oid)) {
930 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
931 refs_found = repo_dwim_ref(r, str, len, &tmp_oid, &real_ref, 0);
932 if (refs_found > 0) {
933 warning(warn_msg, len, str);
934 if (advice_enabled(ADVICE_OBJECT_NAME_WARNING))
935 fprintf(stderr, "%s\n", _(object_name_msg));
937 free(real_ref);
939 return 0;
942 /* basic@{time or number or -number} format to query ref-log */
943 reflog_len = at = 0;
944 if (len && str[len-1] == '}') {
945 for (at = len-4; at >= 0; at--) {
946 if (str[at] == '@' && str[at+1] == '{') {
947 if (str[at+2] == '-') {
948 if (at != 0)
949 /* @{-N} not at start */
950 return -1;
951 nth_prior = 1;
952 continue;
954 if (!upstream_mark(str + at, len - at) &&
955 !push_mark(str + at, len - at)) {
956 reflog_len = (len-1) - (at+2);
957 len = at;
959 break;
964 /* Accept only unambiguous ref paths. */
965 if (len && ambiguous_path(str, len))
966 return -1;
968 if (nth_prior) {
969 struct strbuf buf = STRBUF_INIT;
970 int detached;
972 if (interpret_nth_prior_checkout(r, str, len, &buf) > 0) {
973 detached = (buf.len == r->hash_algo->hexsz && !get_oid_hex(buf.buf, oid));
974 strbuf_release(&buf);
975 if (detached)
976 return 0;
980 if (!len && reflog_len)
981 /* allow "@{...}" to mean the current branch reflog */
982 refs_found = repo_dwim_ref(r, "HEAD", 4, oid, &real_ref, !fatal);
983 else if (reflog_len)
984 refs_found = repo_dwim_log(r, str, len, oid, &real_ref);
985 else
986 refs_found = repo_dwim_ref(r, str, len, oid, &real_ref, !fatal);
988 if (!refs_found)
989 return -1;
991 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
992 (refs_found > 1 ||
993 !get_short_oid(r, str, len, &tmp_oid, GET_OID_QUIETLY)))
994 warning(warn_msg, len, str);
996 if (reflog_len) {
997 int nth, i;
998 timestamp_t at_time;
999 timestamp_t co_time;
1000 int co_tz, co_cnt;
1002 /* Is it asking for N-th entry, or approxidate? */
1003 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
1004 char ch = str[at+2+i];
1005 if ('0' <= ch && ch <= '9')
1006 nth = nth * 10 + ch - '0';
1007 else
1008 nth = -1;
1010 if (100000000 <= nth) {
1011 at_time = nth;
1012 nth = -1;
1013 } else if (0 <= nth)
1014 at_time = 0;
1015 else {
1016 int errors = 0;
1017 char *tmp = xstrndup(str + at + 2, reflog_len);
1018 at_time = approxidate_careful(tmp, &errors);
1019 free(tmp);
1020 if (errors) {
1021 free(real_ref);
1022 return -1;
1025 if (read_ref_at(get_main_ref_store(r),
1026 real_ref, flags, at_time, nth, oid, NULL,
1027 &co_time, &co_tz, &co_cnt)) {
1028 if (!len) {
1029 if (!skip_prefix(real_ref, "refs/heads/", &str))
1030 str = "HEAD";
1031 len = strlen(str);
1033 if (at_time) {
1034 if (!(flags & GET_OID_QUIETLY)) {
1035 warning(_("log for '%.*s' only goes back to %s"),
1036 len, str,
1037 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
1039 } else {
1040 if (flags & GET_OID_QUIETLY) {
1041 exit(128);
1043 die(_("log for '%.*s' only has %d entries"),
1044 len, str, co_cnt);
1049 free(real_ref);
1050 return 0;
1053 static enum get_oid_result get_parent(struct repository *r,
1054 const char *name, int len,
1055 struct object_id *result, int idx)
1057 struct object_id oid;
1058 enum get_oid_result ret = get_oid_1(r, name, len, &oid,
1059 GET_OID_COMMITTISH);
1060 struct commit *commit;
1061 struct commit_list *p;
1063 if (ret)
1064 return ret;
1065 commit = lookup_commit_reference(r, &oid);
1066 if (repo_parse_commit(r, commit))
1067 return MISSING_OBJECT;
1068 if (!idx) {
1069 oidcpy(result, &commit->object.oid);
1070 return FOUND;
1072 p = commit->parents;
1073 while (p) {
1074 if (!--idx) {
1075 oidcpy(result, &p->item->object.oid);
1076 return FOUND;
1078 p = p->next;
1080 return MISSING_OBJECT;
1083 static enum get_oid_result get_nth_ancestor(struct repository *r,
1084 const char *name, int len,
1085 struct object_id *result,
1086 int generation)
1088 struct object_id oid;
1089 struct commit *commit;
1090 int ret;
1092 ret = get_oid_1(r, name, len, &oid, GET_OID_COMMITTISH);
1093 if (ret)
1094 return ret;
1095 commit = lookup_commit_reference(r, &oid);
1096 if (!commit)
1097 return MISSING_OBJECT;
1099 while (generation--) {
1100 if (repo_parse_commit(r, commit) || !commit->parents)
1101 return MISSING_OBJECT;
1102 commit = commit->parents->item;
1104 oidcpy(result, &commit->object.oid);
1105 return FOUND;
1108 struct object *repo_peel_to_type(struct repository *r, const char *name, int namelen,
1109 struct object *o, enum object_type expected_type)
1111 if (name && !namelen)
1112 namelen = strlen(name);
1113 while (1) {
1114 if (!o || (!o->parsed && !parse_object(r, &o->oid)))
1115 return NULL;
1116 if (expected_type == OBJ_ANY || o->type == expected_type)
1117 return o;
1118 if (o->type == OBJ_TAG)
1119 o = ((struct tag*) o)->tagged;
1120 else if (o->type == OBJ_COMMIT)
1121 o = &(repo_get_commit_tree(r, ((struct commit *)o))->object);
1122 else {
1123 if (name)
1124 error("%.*s: expected %s type, but the object "
1125 "dereferences to %s type",
1126 namelen, name, type_name(expected_type),
1127 type_name(o->type));
1128 return NULL;
1133 static int peel_onion(struct repository *r, const char *name, int len,
1134 struct object_id *oid, unsigned lookup_flags)
1136 struct object_id outer;
1137 const char *sp;
1138 unsigned int expected_type = 0;
1139 struct object *o;
1142 * "ref^{type}" dereferences ref repeatedly until you cannot
1143 * dereference anymore, or you get an object of given type,
1144 * whichever comes first. "ref^{}" means just dereference
1145 * tags until you get a non-tag. "ref^0" is a shorthand for
1146 * "ref^{commit}". "commit^{tree}" could be used to find the
1147 * top-level tree of the given commit.
1149 if (len < 4 || name[len-1] != '}')
1150 return -1;
1152 for (sp = name + len - 1; name <= sp; sp--) {
1153 int ch = *sp;
1154 if (ch == '{' && name < sp && sp[-1] == '^')
1155 break;
1157 if (sp <= name)
1158 return -1;
1160 sp++; /* beginning of type name, or closing brace for empty */
1161 if (starts_with(sp, "commit}"))
1162 expected_type = OBJ_COMMIT;
1163 else if (starts_with(sp, "tag}"))
1164 expected_type = OBJ_TAG;
1165 else if (starts_with(sp, "tree}"))
1166 expected_type = OBJ_TREE;
1167 else if (starts_with(sp, "blob}"))
1168 expected_type = OBJ_BLOB;
1169 else if (starts_with(sp, "object}"))
1170 expected_type = OBJ_ANY;
1171 else if (sp[0] == '}')
1172 expected_type = OBJ_NONE;
1173 else if (sp[0] == '/')
1174 expected_type = OBJ_COMMIT;
1175 else
1176 return -1;
1178 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
1179 if (expected_type == OBJ_COMMIT)
1180 lookup_flags |= GET_OID_COMMITTISH;
1181 else if (expected_type == OBJ_TREE)
1182 lookup_flags |= GET_OID_TREEISH;
1184 if (get_oid_1(r, name, sp - name - 2, &outer, lookup_flags))
1185 return -1;
1187 o = parse_object(r, &outer);
1188 if (!o)
1189 return -1;
1190 if (!expected_type) {
1191 o = deref_tag(r, o, name, sp - name - 2);
1192 if (!o || (!o->parsed && !parse_object(r, &o->oid)))
1193 return -1;
1194 oidcpy(oid, &o->oid);
1195 return 0;
1199 * At this point, the syntax look correct, so
1200 * if we do not get the needed object, we should
1201 * barf.
1203 o = repo_peel_to_type(r, name, len, o, expected_type);
1204 if (!o)
1205 return -1;
1207 oidcpy(oid, &o->oid);
1208 if (sp[0] == '/') {
1209 /* "$commit^{/foo}" */
1210 char *prefix;
1211 int ret;
1212 struct commit_list *list = NULL;
1215 * $commit^{/}. Some regex implementation may reject.
1216 * We don't need regex anyway. '' pattern always matches.
1218 if (sp[1] == '}')
1219 return 0;
1221 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
1222 commit_list_insert((struct commit *)o, &list);
1223 ret = get_oid_oneline(r, prefix, oid, list);
1224 free(prefix);
1225 return ret;
1227 return 0;
1230 static int get_describe_name(struct repository *r,
1231 const char *name, int len,
1232 struct object_id *oid)
1234 const char *cp;
1235 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
1237 for (cp = name + len - 1; name + 2 <= cp; cp--) {
1238 char ch = *cp;
1239 if (!isxdigit(ch)) {
1240 /* We must be looking at g in "SOMETHING-g"
1241 * for it to be describe output.
1243 if (ch == 'g' && cp[-1] == '-') {
1244 cp++;
1245 len -= cp - name;
1246 return get_short_oid(r,
1247 cp, len, oid, flags);
1251 return -1;
1254 static enum get_oid_result get_oid_1(struct repository *r,
1255 const char *name, int len,
1256 struct object_id *oid,
1257 unsigned lookup_flags)
1259 int ret, has_suffix;
1260 const char *cp;
1263 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1265 has_suffix = 0;
1266 for (cp = name + len - 1; name <= cp; cp--) {
1267 int ch = *cp;
1268 if ('0' <= ch && ch <= '9')
1269 continue;
1270 if (ch == '~' || ch == '^')
1271 has_suffix = ch;
1272 break;
1275 if (has_suffix) {
1276 unsigned int num = 0;
1277 int len1 = cp - name;
1278 cp++;
1279 while (cp < name + len) {
1280 unsigned int digit = *cp++ - '0';
1281 if (unsigned_mult_overflows(num, 10))
1282 return MISSING_OBJECT;
1283 num *= 10;
1284 if (unsigned_add_overflows(num, digit))
1285 return MISSING_OBJECT;
1286 num += digit;
1288 if (!num && len1 == len - 1)
1289 num = 1;
1290 else if (num > INT_MAX)
1291 return MISSING_OBJECT;
1292 if (has_suffix == '^')
1293 return get_parent(r, name, len1, oid, num);
1294 /* else if (has_suffix == '~') -- goes without saying */
1295 return get_nth_ancestor(r, name, len1, oid, num);
1298 ret = peel_onion(r, name, len, oid, lookup_flags);
1299 if (!ret)
1300 return FOUND;
1302 ret = get_oid_basic(r, name, len, oid, lookup_flags);
1303 if (!ret)
1304 return FOUND;
1306 /* It could be describe output that is "SOMETHING-gXXXX" */
1307 ret = get_describe_name(r, name, len, oid);
1308 if (!ret)
1309 return FOUND;
1311 return get_short_oid(r, name, len, oid, lookup_flags);
1315 * This interprets names like ':/Initial revision of "git"' by searching
1316 * through history and returning the first commit whose message starts
1317 * the given regular expression.
1319 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1321 * For a literal '!' character at the beginning of a pattern, you have to repeat
1322 * that, like: ':/!!foo'
1324 * For future extension, all other sequences beginning with ':/!' are reserved.
1327 /* Remember to update object flag allocation in object.h */
1328 #define ONELINE_SEEN (1u<<20)
1330 struct handle_one_ref_cb {
1331 struct repository *repo;
1332 struct commit_list **list;
1335 static int handle_one_ref(const char *path, const struct object_id *oid,
1336 int flag UNUSED,
1337 void *cb_data)
1339 struct handle_one_ref_cb *cb = cb_data;
1340 struct commit_list **list = cb->list;
1341 struct object *object = parse_object(cb->repo, oid);
1342 if (!object)
1343 return 0;
1344 if (object->type == OBJ_TAG) {
1345 object = deref_tag(cb->repo, object, path,
1346 strlen(path));
1347 if (!object)
1348 return 0;
1350 if (object->type != OBJ_COMMIT)
1351 return 0;
1352 commit_list_insert((struct commit *)object, list);
1353 return 0;
1356 static int get_oid_oneline(struct repository *r,
1357 const char *prefix, struct object_id *oid,
1358 struct commit_list *list)
1360 struct commit_list *backup = NULL, *l;
1361 int found = 0;
1362 int negative = 0;
1363 regex_t regex;
1365 if (prefix[0] == '!') {
1366 prefix++;
1368 if (prefix[0] == '-') {
1369 prefix++;
1370 negative = 1;
1371 } else if (prefix[0] != '!') {
1372 return -1;
1376 if (regcomp(&regex, prefix, REG_EXTENDED))
1377 return -1;
1379 for (l = list; l; l = l->next) {
1380 l->item->object.flags |= ONELINE_SEEN;
1381 commit_list_insert(l->item, &backup);
1383 while (list) {
1384 const char *p, *buf;
1385 struct commit *commit;
1386 int matches;
1388 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
1389 if (!parse_object(r, &commit->object.oid))
1390 continue;
1391 buf = repo_get_commit_buffer(r, commit, NULL);
1392 p = strstr(buf, "\n\n");
1393 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
1394 repo_unuse_commit_buffer(r, commit, buf);
1396 if (matches) {
1397 oidcpy(oid, &commit->object.oid);
1398 found = 1;
1399 break;
1402 regfree(&regex);
1403 free_commit_list(list);
1404 for (l = backup; l; l = l->next)
1405 clear_commit_marks(l->item, ONELINE_SEEN);
1406 free_commit_list(backup);
1407 return found ? 0 : -1;
1410 struct grab_nth_branch_switch_cbdata {
1411 int remaining;
1412 struct strbuf *sb;
1415 static int grab_nth_branch_switch(struct object_id *ooid UNUSED,
1416 struct object_id *noid UNUSED,
1417 const char *email UNUSED,
1418 timestamp_t timestamp UNUSED,
1419 int tz UNUSED,
1420 const char *message, void *cb_data)
1422 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1423 const char *match = NULL, *target = NULL;
1424 size_t len;
1426 if (skip_prefix(message, "checkout: moving from ", &match))
1427 target = strstr(match, " to ");
1429 if (!match || !target)
1430 return 0;
1431 if (--(cb->remaining) == 0) {
1432 len = target - match;
1433 strbuf_reset(cb->sb);
1434 strbuf_add(cb->sb, match, len);
1435 return 1; /* we are done */
1437 return 0;
1441 * Parse @{-N} syntax, return the number of characters parsed
1442 * if successful; otherwise signal an error with negative value.
1444 static int interpret_nth_prior_checkout(struct repository *r,
1445 const char *name, int namelen,
1446 struct strbuf *buf)
1448 long nth;
1449 int retval;
1450 struct grab_nth_branch_switch_cbdata cb;
1451 const char *brace;
1452 char *num_end;
1454 if (namelen < 4)
1455 return -1;
1456 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1457 return -1;
1458 brace = memchr(name, '}', namelen);
1459 if (!brace)
1460 return -1;
1461 nth = strtol(name + 3, &num_end, 10);
1462 if (num_end != brace)
1463 return -1;
1464 if (nth <= 0)
1465 return -1;
1466 cb.remaining = nth;
1467 cb.sb = buf;
1469 retval = refs_for_each_reflog_ent_reverse(get_main_ref_store(r),
1470 "HEAD", grab_nth_branch_switch, &cb);
1471 if (0 < retval) {
1472 retval = brace - name + 1;
1473 } else
1474 retval = 0;
1476 return retval;
1479 int repo_get_oid_mb(struct repository *r,
1480 const char *name,
1481 struct object_id *oid)
1483 struct commit *one, *two;
1484 struct commit_list *mbs;
1485 struct object_id oid_tmp;
1486 const char *dots;
1487 int st;
1489 dots = strstr(name, "...");
1490 if (!dots)
1491 return repo_get_oid(r, name, oid);
1492 if (dots == name)
1493 st = repo_get_oid(r, "HEAD", &oid_tmp);
1494 else {
1495 struct strbuf sb;
1496 strbuf_init(&sb, dots - name);
1497 strbuf_add(&sb, name, dots - name);
1498 st = repo_get_oid_committish(r, sb.buf, &oid_tmp);
1499 strbuf_release(&sb);
1501 if (st)
1502 return st;
1503 one = lookup_commit_reference_gently(r, &oid_tmp, 0);
1504 if (!one)
1505 return -1;
1507 if (repo_get_oid_committish(r, dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1508 return -1;
1509 two = lookup_commit_reference_gently(r, &oid_tmp, 0);
1510 if (!two)
1511 return -1;
1512 mbs = repo_get_merge_bases(r, one, two);
1513 if (!mbs || mbs->next)
1514 st = -1;
1515 else {
1516 st = 0;
1517 oidcpy(oid, &mbs->item->object.oid);
1519 free_commit_list(mbs);
1520 return st;
1523 /* parse @something syntax, when 'something' is not {.*} */
1524 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1526 const char *next;
1528 if (len || name[1] == '{')
1529 return -1;
1531 /* make sure it's a single @, or @@{.*}, not @foo */
1532 next = memchr(name + len + 1, '@', namelen - len - 1);
1533 if (next && next[1] != '{')
1534 return -1;
1535 if (!next)
1536 next = name + namelen;
1537 if (next != name + 1)
1538 return -1;
1540 strbuf_reset(buf);
1541 strbuf_add(buf, "HEAD", 4);
1542 return 1;
1545 static int reinterpret(struct repository *r,
1546 const char *name, int namelen, int len,
1547 struct strbuf *buf, unsigned allowed)
1549 /* we have extra data, which might need further processing */
1550 struct strbuf tmp = STRBUF_INIT;
1551 int used = buf->len;
1552 int ret;
1553 struct interpret_branch_name_options options = {
1554 .allowed = allowed
1557 strbuf_add(buf, name + len, namelen - len);
1558 ret = repo_interpret_branch_name(r, buf->buf, buf->len, &tmp, &options);
1559 /* that data was not interpreted, remove our cruft */
1560 if (ret < 0) {
1561 strbuf_setlen(buf, used);
1562 return len;
1564 strbuf_reset(buf);
1565 strbuf_addbuf(buf, &tmp);
1566 strbuf_release(&tmp);
1567 /* tweak for size of {-N} versus expanded ref name */
1568 return ret - used + len;
1571 static void set_shortened_ref(struct repository *r, struct strbuf *buf, const char *ref)
1573 char *s = refs_shorten_unambiguous_ref(get_main_ref_store(r), ref, 0);
1574 strbuf_reset(buf);
1575 strbuf_addstr(buf, s);
1576 free(s);
1579 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1581 if (!allowed)
1582 return 1;
1584 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1585 starts_with(refname, "refs/heads/"))
1586 return 1;
1587 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1588 starts_with(refname, "refs/remotes/"))
1589 return 1;
1591 return 0;
1594 static int interpret_branch_mark(struct repository *r,
1595 const char *name, int namelen,
1596 int at, struct strbuf *buf,
1597 int (*get_mark)(const char *, int),
1598 const char *(*get_data)(struct branch *,
1599 struct strbuf *),
1600 const struct interpret_branch_name_options *options)
1602 int len;
1603 struct branch *branch;
1604 struct strbuf err = STRBUF_INIT;
1605 const char *value;
1607 len = get_mark(name + at, namelen - at);
1608 if (!len)
1609 return -1;
1611 if (memchr(name, ':', at))
1612 return -1;
1614 if (at) {
1615 char *name_str = xmemdupz(name, at);
1616 branch = branch_get(name_str);
1617 free(name_str);
1618 } else
1619 branch = branch_get(NULL);
1621 value = get_data(branch, &err);
1622 if (!value) {
1623 if (options->nonfatal_dangling_mark) {
1624 strbuf_release(&err);
1625 return -1;
1626 } else {
1627 die("%s", err.buf);
1631 if (!branch_interpret_allowed(value, options->allowed))
1632 return -1;
1634 set_shortened_ref(r, buf, value);
1635 return len + at;
1638 int repo_interpret_branch_name(struct repository *r,
1639 const char *name, int namelen,
1640 struct strbuf *buf,
1641 const struct interpret_branch_name_options *options)
1643 char *at;
1644 const char *start;
1645 int len;
1647 if (!namelen)
1648 namelen = strlen(name);
1650 if (!options->allowed || (options->allowed & INTERPRET_BRANCH_LOCAL)) {
1651 len = interpret_nth_prior_checkout(r, name, namelen, buf);
1652 if (!len) {
1653 return len; /* syntax Ok, not enough switches */
1654 } else if (len > 0) {
1655 if (len == namelen)
1656 return len; /* consumed all */
1657 else
1658 return reinterpret(r, name, namelen, len, buf,
1659 options->allowed);
1663 for (start = name;
1664 (at = memchr(start, '@', namelen - (start - name)));
1665 start = at + 1) {
1667 if (!options->allowed || (options->allowed & INTERPRET_BRANCH_HEAD)) {
1668 len = interpret_empty_at(name, namelen, at - name, buf);
1669 if (len > 0)
1670 return reinterpret(r, name, namelen, len, buf,
1671 options->allowed);
1674 len = interpret_branch_mark(r, name, namelen, at - name, buf,
1675 upstream_mark, branch_get_upstream,
1676 options);
1677 if (len > 0)
1678 return len;
1680 len = interpret_branch_mark(r, name, namelen, at - name, buf,
1681 push_mark, branch_get_push,
1682 options);
1683 if (len > 0)
1684 return len;
1687 return -1;
1690 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1692 int len = strlen(name);
1693 struct interpret_branch_name_options options = {
1694 .allowed = allowed
1696 int used = repo_interpret_branch_name(the_repository, name, len, sb,
1697 &options);
1699 if (used < 0)
1700 used = 0;
1701 strbuf_add(sb, name + used, len - used);
1704 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1706 if (startup_info->have_repository)
1707 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1708 else
1709 strbuf_addstr(sb, name);
1712 * This splice must be done even if we end up rejecting the
1713 * name; builtin/branch.c::copy_or_rename_branch() still wants
1714 * to see what the name expanded to so that "branch -m" can be
1715 * used as a tool to correct earlier mistakes.
1717 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1719 if (*name == '-' ||
1720 !strcmp(sb->buf, "refs/heads/HEAD"))
1721 return -1;
1723 return check_refname_format(sb->buf, 0);
1727 * This is like "get_oid_basic()", except it allows "object ID expressions",
1728 * notably "xyz^" for "parent of xyz"
1730 int repo_get_oid(struct repository *r, const char *name, struct object_id *oid)
1732 struct object_context unused;
1733 return get_oid_with_context(r, name, 0, oid, &unused);
1737 * This returns a non-zero value if the string (built using printf
1738 * format and the given arguments) is not a valid object.
1740 int get_oidf(struct object_id *oid, const char *fmt, ...)
1742 va_list ap;
1743 int ret;
1744 struct strbuf sb = STRBUF_INIT;
1746 va_start(ap, fmt);
1747 strbuf_vaddf(&sb, fmt, ap);
1748 va_end(ap);
1750 ret = repo_get_oid(the_repository, sb.buf, oid);
1751 strbuf_release(&sb);
1753 return ret;
1757 * Many callers know that the user meant to name a commit-ish by
1758 * syntactical positions where the object name appears. Calling this
1759 * function allows the machinery to disambiguate shorter-than-unique
1760 * abbreviated object names between commit-ish and others.
1762 * Note that this does NOT error out when the named object is not a
1763 * commit-ish. It is merely to give a hint to the disambiguation
1764 * machinery.
1766 int repo_get_oid_committish(struct repository *r,
1767 const char *name,
1768 struct object_id *oid)
1770 struct object_context unused;
1771 return get_oid_with_context(r, name, GET_OID_COMMITTISH,
1772 oid, &unused);
1775 int repo_get_oid_treeish(struct repository *r,
1776 const char *name,
1777 struct object_id *oid)
1779 struct object_context unused;
1780 return get_oid_with_context(r, name, GET_OID_TREEISH,
1781 oid, &unused);
1784 int repo_get_oid_commit(struct repository *r,
1785 const char *name,
1786 struct object_id *oid)
1788 struct object_context unused;
1789 return get_oid_with_context(r, name, GET_OID_COMMIT,
1790 oid, &unused);
1793 int repo_get_oid_tree(struct repository *r,
1794 const char *name,
1795 struct object_id *oid)
1797 struct object_context unused;
1798 return get_oid_with_context(r, name, GET_OID_TREE,
1799 oid, &unused);
1802 int repo_get_oid_blob(struct repository *r,
1803 const char *name,
1804 struct object_id *oid)
1806 struct object_context unused;
1807 return get_oid_with_context(r, name, GET_OID_BLOB,
1808 oid, &unused);
1811 /* Must be called only when object_name:filename doesn't exist. */
1812 static void diagnose_invalid_oid_path(struct repository *r,
1813 const char *prefix,
1814 const char *filename,
1815 const struct object_id *tree_oid,
1816 const char *object_name,
1817 int object_name_len)
1819 struct object_id oid;
1820 unsigned short mode;
1822 if (!prefix)
1823 prefix = "";
1825 if (file_exists(filename))
1826 die(_("path '%s' exists on disk, but not in '%.*s'"),
1827 filename, object_name_len, object_name);
1828 if (is_missing_file_error(errno)) {
1829 char *fullname = xstrfmt("%s%s", prefix, filename);
1831 if (!get_tree_entry(r, tree_oid, fullname, &oid, &mode)) {
1832 die(_("path '%s' exists, but not '%s'\n"
1833 "hint: Did you mean '%.*s:%s' aka '%.*s:./%s'?"),
1834 fullname,
1835 filename,
1836 object_name_len, object_name,
1837 fullname,
1838 object_name_len, object_name,
1839 filename);
1841 die(_("path '%s' does not exist in '%.*s'"),
1842 filename, object_name_len, object_name);
1846 /* Must be called only when :stage:filename doesn't exist. */
1847 static void diagnose_invalid_index_path(struct repository *r,
1848 int stage,
1849 const char *prefix,
1850 const char *filename)
1852 struct index_state *istate = r->index;
1853 const struct cache_entry *ce;
1854 int pos;
1855 unsigned namelen = strlen(filename);
1856 struct strbuf fullname = STRBUF_INIT;
1858 if (!prefix)
1859 prefix = "";
1861 /* Wrong stage number? */
1862 pos = index_name_pos(istate, filename, namelen);
1863 if (pos < 0)
1864 pos = -pos - 1;
1865 if (pos < istate->cache_nr) {
1866 ce = istate->cache[pos];
1867 if (!S_ISSPARSEDIR(ce->ce_mode) &&
1868 ce_namelen(ce) == namelen &&
1869 !memcmp(ce->name, filename, namelen))
1870 die(_("path '%s' is in the index, but not at stage %d\n"
1871 "hint: Did you mean ':%d:%s'?"),
1872 filename, stage,
1873 ce_stage(ce), filename);
1876 /* Confusion between relative and absolute filenames? */
1877 strbuf_addstr(&fullname, prefix);
1878 strbuf_addstr(&fullname, filename);
1879 pos = index_name_pos(istate, fullname.buf, fullname.len);
1880 if (pos < 0)
1881 pos = -pos - 1;
1882 if (pos < istate->cache_nr) {
1883 ce = istate->cache[pos];
1884 if (!S_ISSPARSEDIR(ce->ce_mode) &&
1885 ce_namelen(ce) == fullname.len &&
1886 !memcmp(ce->name, fullname.buf, fullname.len))
1887 die(_("path '%s' is in the index, but not '%s'\n"
1888 "hint: Did you mean ':%d:%s' aka ':%d:./%s'?"),
1889 fullname.buf, filename,
1890 ce_stage(ce), fullname.buf,
1891 ce_stage(ce), filename);
1894 if (repo_file_exists(r, filename))
1895 die(_("path '%s' exists on disk, but not in the index"), filename);
1896 if (is_missing_file_error(errno))
1897 die(_("path '%s' does not exist (neither on disk nor in the index)"),
1898 filename);
1900 strbuf_release(&fullname);
1904 static char *resolve_relative_path(struct repository *r, const char *rel)
1906 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1907 return NULL;
1909 if (r != the_repository || !is_inside_work_tree())
1910 die(_("relative path syntax can't be used outside working tree"));
1912 /* die() inside prefix_path() if resolved path is outside worktree */
1913 return prefix_path(startup_info->prefix,
1914 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1915 rel);
1918 static int reject_tree_in_index(struct repository *repo,
1919 int only_to_die,
1920 const struct cache_entry *ce,
1921 int stage,
1922 const char *prefix,
1923 const char *cp)
1925 if (!S_ISSPARSEDIR(ce->ce_mode))
1926 return 0;
1927 if (only_to_die)
1928 diagnose_invalid_index_path(repo, stage, prefix, cp);
1929 return -1;
1932 static enum get_oid_result get_oid_with_context_1(struct repository *repo,
1933 const char *name,
1934 unsigned flags,
1935 const char *prefix,
1936 struct object_id *oid,
1937 struct object_context *oc)
1939 int ret, bracket_depth;
1940 int namelen = strlen(name);
1941 const char *cp;
1942 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
1944 memset(oc, 0, sizeof(*oc));
1945 oc->mode = S_IFINVALID;
1946 strbuf_init(&oc->symlink_path, 0);
1947 ret = get_oid_1(repo, name, namelen, oid, flags);
1948 if (!ret && flags & GET_OID_REQUIRE_PATH)
1949 die(_("<object>:<path> required, only <object> '%s' given"),
1950 name);
1951 if (!ret)
1952 return ret;
1954 * tree:path --> object name of path in tree
1955 * :path -> object name of absolute path in index
1956 * :./path -> object name of path relative to cwd in index
1957 * :[0-3]:path -> object name of path in index at stage
1958 * :/foo -> recent commit matching foo
1960 if (name[0] == ':') {
1961 int stage = 0;
1962 const struct cache_entry *ce;
1963 char *new_path = NULL;
1964 int pos;
1965 if (!only_to_die && namelen > 2 && name[1] == '/') {
1966 struct handle_one_ref_cb cb;
1967 struct commit_list *list = NULL;
1969 cb.repo = repo;
1970 cb.list = &list;
1971 refs_for_each_ref(get_main_ref_store(repo), handle_one_ref, &cb);
1972 refs_head_ref(get_main_ref_store(repo), handle_one_ref, &cb);
1973 commit_list_sort_by_date(&list);
1974 return get_oid_oneline(repo, name + 2, oid, list);
1976 if (namelen < 3 ||
1977 name[2] != ':' ||
1978 name[1] < '0' || '3' < name[1])
1979 cp = name + 1;
1980 else {
1981 stage = name[1] - '0';
1982 cp = name + 3;
1984 new_path = resolve_relative_path(repo, cp);
1985 if (!new_path) {
1986 namelen = namelen - (cp - name);
1987 } else {
1988 cp = new_path;
1989 namelen = strlen(cp);
1992 if (flags & GET_OID_RECORD_PATH)
1993 oc->path = xstrdup(cp);
1995 if (!repo->index || !repo->index->cache)
1996 repo_read_index(repo);
1997 pos = index_name_pos(repo->index, cp, namelen);
1998 if (pos < 0)
1999 pos = -pos - 1;
2000 while (pos < repo->index->cache_nr) {
2001 ce = repo->index->cache[pos];
2002 if (ce_namelen(ce) != namelen ||
2003 memcmp(ce->name, cp, namelen))
2004 break;
2005 if (ce_stage(ce) == stage) {
2006 free(new_path);
2007 if (reject_tree_in_index(repo, only_to_die, ce,
2008 stage, prefix, cp))
2009 return -1;
2010 oidcpy(oid, &ce->oid);
2011 oc->mode = ce->ce_mode;
2012 return 0;
2014 pos++;
2016 if (only_to_die && name[1] && name[1] != '/')
2017 diagnose_invalid_index_path(repo, stage, prefix, cp);
2018 free(new_path);
2019 return -1;
2021 for (cp = name, bracket_depth = 0; *cp; cp++) {
2022 if (*cp == '{')
2023 bracket_depth++;
2024 else if (bracket_depth && *cp == '}')
2025 bracket_depth--;
2026 else if (!bracket_depth && *cp == ':')
2027 break;
2029 if (*cp == ':') {
2030 struct object_id tree_oid;
2031 int len = cp - name;
2032 unsigned sub_flags = flags;
2034 sub_flags &= ~GET_OID_DISAMBIGUATORS;
2035 sub_flags |= GET_OID_TREEISH;
2037 if (!get_oid_1(repo, name, len, &tree_oid, sub_flags)) {
2038 const char *filename = cp+1;
2039 char *new_filename = NULL;
2041 new_filename = resolve_relative_path(repo, filename);
2042 if (new_filename)
2043 filename = new_filename;
2044 if (flags & GET_OID_FOLLOW_SYMLINKS) {
2045 ret = get_tree_entry_follow_symlinks(repo, &tree_oid,
2046 filename, oid, &oc->symlink_path,
2047 &oc->mode);
2048 } else {
2049 ret = get_tree_entry(repo, &tree_oid, filename, oid,
2050 &oc->mode);
2051 if (ret && only_to_die) {
2052 diagnose_invalid_oid_path(repo, prefix,
2053 filename,
2054 &tree_oid,
2055 name, len);
2058 if (flags & GET_OID_RECORD_PATH)
2059 oc->path = xstrdup(filename);
2061 free(new_filename);
2062 return ret;
2063 } else {
2064 if (only_to_die)
2065 die(_("invalid object name '%.*s'."), len, name);
2068 return ret;
2072 * Call this function when you know "name" given by the end user must
2073 * name an object but it doesn't; the function _may_ die with a better
2074 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
2075 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
2076 * you have a chance to diagnose the error further.
2078 void maybe_die_on_misspelt_object_name(struct repository *r,
2079 const char *name,
2080 const char *prefix)
2082 struct object_context oc;
2083 struct object_id oid;
2084 get_oid_with_context_1(r, name, GET_OID_ONLY_TO_DIE | GET_OID_QUIETLY,
2085 prefix, &oid, &oc);
2088 enum get_oid_result get_oid_with_context(struct repository *repo,
2089 const char *str,
2090 unsigned flags,
2091 struct object_id *oid,
2092 struct object_context *oc)
2094 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
2095 BUG("incompatible flags for get_oid_with_context");
2096 return get_oid_with_context_1(repo, str, flags, NULL, oid, oc);