setup: merge configuration of repository formats
[git/gitster.git] / object-name.c
blob240a93e7cef52f45c6354a7019417c7946b6b27a
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "object-name.h"
5 #include "advice.h"
6 #include "config.h"
7 #include "environment.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "tag.h"
11 #include "commit.h"
12 #include "tree.h"
13 #include "tree-walk.h"
14 #include "refs.h"
15 #include "remote.h"
16 #include "dir.h"
17 #include "oid-array.h"
18 #include "oidtree.h"
19 #include "packfile.h"
20 #include "pretty.h"
21 #include "object-store-ll.h"
22 #include "read-cache-ll.h"
23 #include "repository.h"
24 #include "setup.h"
25 #include "midx.h"
26 #include "commit-reach.h"
27 #include "date.h"
28 #include "object-file-convert.h"
30 static int get_oid_oneline(struct repository *r, const char *, struct object_id *,
31 const struct commit_list *);
33 typedef int (*disambiguate_hint_fn)(struct repository *, const struct object_id *, void *);
35 struct disambiguate_state {
36 int len; /* length of prefix in hex chars */
37 char hex_pfx[GIT_MAX_HEXSZ + 1];
38 struct object_id bin_pfx;
40 struct repository *repo;
41 disambiguate_hint_fn fn;
42 void *cb_data;
43 struct object_id candidate;
44 unsigned candidate_exists:1;
45 unsigned candidate_checked:1;
46 unsigned candidate_ok:1;
47 unsigned disambiguate_fn_used:1;
48 unsigned ambiguous:1;
49 unsigned always_call_fn:1;
52 static void update_candidates(struct disambiguate_state *ds, const struct object_id *current)
54 /* The hash algorithm of current has already been filtered */
55 if (ds->always_call_fn) {
56 ds->ambiguous = ds->fn(ds->repo, current, ds->cb_data) ? 1 : 0;
57 return;
59 if (!ds->candidate_exists) {
60 /* this is the first candidate */
61 oidcpy(&ds->candidate, current);
62 ds->candidate_exists = 1;
63 return;
64 } else if (oideq(&ds->candidate, current)) {
65 /* the same as what we already have seen */
66 return;
69 if (!ds->fn) {
70 /* cannot disambiguate between ds->candidate and current */
71 ds->ambiguous = 1;
72 return;
75 if (!ds->candidate_checked) {
76 ds->candidate_ok = ds->fn(ds->repo, &ds->candidate, ds->cb_data);
77 ds->disambiguate_fn_used = 1;
78 ds->candidate_checked = 1;
81 if (!ds->candidate_ok) {
82 /* discard the candidate; we know it does not satisfy fn */
83 oidcpy(&ds->candidate, current);
84 ds->candidate_checked = 0;
85 return;
88 /* if we reach this point, we know ds->candidate satisfies fn */
89 if (ds->fn(ds->repo, current, ds->cb_data)) {
91 * if both current and candidate satisfy fn, we cannot
92 * disambiguate.
94 ds->candidate_ok = 0;
95 ds->ambiguous = 1;
98 /* otherwise, current can be discarded and candidate is still good */
101 static int match_hash(unsigned, const unsigned char *, const unsigned char *);
103 static enum cb_next match_prefix(const struct object_id *oid, void *arg)
105 struct disambiguate_state *ds = arg;
106 /* no need to call match_hash, oidtree_each did prefix match */
107 update_candidates(ds, oid);
108 return ds->ambiguous ? CB_BREAK : CB_CONTINUE;
111 static void find_short_object_filename(struct disambiguate_state *ds)
113 struct object_directory *odb;
115 for (odb = ds->repo->objects->odb; odb && !ds->ambiguous; odb = odb->next)
116 oidtree_each(odb_loose_cache(odb, &ds->bin_pfx),
117 &ds->bin_pfx, ds->len, match_prefix, ds);
120 static int match_hash(unsigned len, const unsigned char *a, const unsigned char *b)
122 do {
123 if (*a != *b)
124 return 0;
125 a++;
126 b++;
127 len -= 2;
128 } while (len > 1);
129 if (len)
130 if ((*a ^ *b) & 0xf0)
131 return 0;
132 return 1;
135 static void unique_in_midx(struct multi_pack_index *m,
136 struct disambiguate_state *ds)
138 uint32_t num, i, first = 0;
139 const struct object_id *current = NULL;
140 int len = ds->len > ds->repo->hash_algo->hexsz ?
141 ds->repo->hash_algo->hexsz : ds->len;
142 num = m->num_objects;
144 if (!num)
145 return;
147 bsearch_midx(&ds->bin_pfx, m, &first);
150 * At this point, "first" is the location of the lowest object
151 * with an object name that could match "bin_pfx". See if we have
152 * 0, 1 or more objects that actually match(es).
154 for (i = first; i < num && !ds->ambiguous; i++) {
155 struct object_id oid;
156 current = nth_midxed_object_oid(&oid, m, i);
157 if (!match_hash(len, ds->bin_pfx.hash, current->hash))
158 break;
159 update_candidates(ds, current);
163 static void unique_in_pack(struct packed_git *p,
164 struct disambiguate_state *ds)
166 uint32_t num, i, first = 0;
167 int len = ds->len > ds->repo->hash_algo->hexsz ?
168 ds->repo->hash_algo->hexsz : ds->len;
170 if (p->multi_pack_index)
171 return;
173 if (open_pack_index(p) || !p->num_objects)
174 return;
176 num = p->num_objects;
177 bsearch_pack(&ds->bin_pfx, p, &first);
180 * At this point, "first" is the location of the lowest object
181 * with an object name that could match "bin_pfx". See if we have
182 * 0, 1 or more objects that actually match(es).
184 for (i = first; i < num && !ds->ambiguous; i++) {
185 struct object_id oid;
186 nth_packed_object_id(&oid, p, i);
187 if (!match_hash(len, ds->bin_pfx.hash, oid.hash))
188 break;
189 update_candidates(ds, &oid);
193 static void find_short_packed_object(struct disambiguate_state *ds)
195 struct multi_pack_index *m;
196 struct packed_git *p;
198 /* Skip, unless oids from the storage hash algorithm are wanted */
199 if (ds->bin_pfx.algo && (&hash_algos[ds->bin_pfx.algo] != ds->repo->hash_algo))
200 return;
202 for (m = get_multi_pack_index(ds->repo); m && !ds->ambiguous;
203 m = m->next)
204 unique_in_midx(m, ds);
205 for (p = get_packed_git(ds->repo); p && !ds->ambiguous;
206 p = p->next)
207 unique_in_pack(p, ds);
210 static int finish_object_disambiguation(struct disambiguate_state *ds,
211 struct object_id *oid)
213 if (ds->ambiguous)
214 return SHORT_NAME_AMBIGUOUS;
216 if (!ds->candidate_exists)
217 return MISSING_OBJECT;
219 if (!ds->candidate_checked)
221 * If this is the only candidate, there is no point
222 * calling the disambiguation hint callback.
224 * On the other hand, if the current candidate
225 * replaced an earlier candidate that did _not_ pass
226 * the disambiguation hint callback, then we do have
227 * more than one objects that match the short name
228 * given, so we should make sure this one matches;
229 * otherwise, if we discovered this one and the one
230 * that we previously discarded in the reverse order,
231 * we would end up showing different results in the
232 * same repository!
234 ds->candidate_ok = (!ds->disambiguate_fn_used ||
235 ds->fn(ds->repo, &ds->candidate, ds->cb_data));
237 if (!ds->candidate_ok)
238 return SHORT_NAME_AMBIGUOUS;
240 oidcpy(oid, &ds->candidate);
241 return 0;
244 static int disambiguate_commit_only(struct repository *r,
245 const struct object_id *oid,
246 void *cb_data UNUSED)
248 int kind = oid_object_info(r, oid, NULL);
249 return kind == OBJ_COMMIT;
252 static int disambiguate_committish_only(struct repository *r,
253 const struct object_id *oid,
254 void *cb_data UNUSED)
256 struct object *obj;
257 int kind;
259 kind = oid_object_info(r, oid, NULL);
260 if (kind == OBJ_COMMIT)
261 return 1;
262 if (kind != OBJ_TAG)
263 return 0;
265 /* We need to do this the hard way... */
266 obj = deref_tag(r, parse_object(r, oid), NULL, 0);
267 if (obj && obj->type == OBJ_COMMIT)
268 return 1;
269 return 0;
272 static int disambiguate_tree_only(struct repository *r,
273 const struct object_id *oid,
274 void *cb_data UNUSED)
276 int kind = oid_object_info(r, oid, NULL);
277 return kind == OBJ_TREE;
280 static int disambiguate_treeish_only(struct repository *r,
281 const struct object_id *oid,
282 void *cb_data UNUSED)
284 struct object *obj;
285 int kind;
287 kind = oid_object_info(r, oid, NULL);
288 if (kind == OBJ_TREE || kind == OBJ_COMMIT)
289 return 1;
290 if (kind != OBJ_TAG)
291 return 0;
293 /* We need to do this the hard way... */
294 obj = deref_tag(r, parse_object(r, oid), NULL, 0);
295 if (obj && (obj->type == OBJ_TREE || obj->type == OBJ_COMMIT))
296 return 1;
297 return 0;
300 static int disambiguate_blob_only(struct repository *r,
301 const struct object_id *oid,
302 void *cb_data UNUSED)
304 int kind = oid_object_info(r, oid, NULL);
305 return kind == OBJ_BLOB;
308 static disambiguate_hint_fn default_disambiguate_hint;
310 int set_disambiguate_hint_config(const char *var, const char *value)
312 static const struct {
313 const char *name;
314 disambiguate_hint_fn fn;
315 } hints[] = {
316 { "none", NULL },
317 { "commit", disambiguate_commit_only },
318 { "committish", disambiguate_committish_only },
319 { "tree", disambiguate_tree_only },
320 { "treeish", disambiguate_treeish_only },
321 { "blob", disambiguate_blob_only }
323 int i;
325 if (!value)
326 return config_error_nonbool(var);
328 for (i = 0; i < ARRAY_SIZE(hints); i++) {
329 if (!strcasecmp(value, hints[i].name)) {
330 default_disambiguate_hint = hints[i].fn;
331 return 0;
335 return error("unknown hint type for '%s': %s", var, value);
338 static int init_object_disambiguation(struct repository *r,
339 const char *name, int len,
340 const struct git_hash_algo *algo,
341 struct disambiguate_state *ds)
343 int i;
345 if (len < MINIMUM_ABBREV || len > GIT_MAX_HEXSZ)
346 return -1;
348 memset(ds, 0, sizeof(*ds));
350 for (i = 0; i < len ;i++) {
351 unsigned char c = name[i];
352 unsigned char val;
353 if (c >= '0' && c <= '9')
354 val = c - '0';
355 else if (c >= 'a' && c <= 'f')
356 val = c - 'a' + 10;
357 else if (c >= 'A' && c <='F') {
358 val = c - 'A' + 10;
359 c -= 'A' - 'a';
361 else
362 return -1;
363 ds->hex_pfx[i] = c;
364 if (!(i & 1))
365 val <<= 4;
366 ds->bin_pfx.hash[i >> 1] |= val;
369 ds->len = len;
370 ds->hex_pfx[len] = '\0';
371 ds->repo = r;
372 ds->bin_pfx.algo = algo ? hash_algo_by_ptr(algo) : GIT_HASH_UNKNOWN;
373 prepare_alt_odb(r);
374 return 0;
377 struct ambiguous_output {
378 const struct disambiguate_state *ds;
379 struct strbuf advice;
380 struct strbuf sb;
383 static int show_ambiguous_object(const struct object_id *oid, void *data)
385 struct ambiguous_output *state = data;
386 const struct disambiguate_state *ds = state->ds;
387 struct strbuf *advice = &state->advice;
388 struct strbuf *sb = &state->sb;
389 int type;
390 const char *hash;
392 if (ds->fn && !ds->fn(ds->repo, oid, ds->cb_data))
393 return 0;
395 hash = repo_find_unique_abbrev(ds->repo, oid, DEFAULT_ABBREV);
396 type = oid_object_info(ds->repo, oid, NULL);
398 if (type < 0) {
400 * TRANSLATORS: This is a line of ambiguous object
401 * output shown when we cannot look up or parse the
402 * object in question. E.g. "deadbeef [bad object]".
404 strbuf_addf(sb, _("%s [bad object]"), hash);
405 goto out;
408 assert(type == OBJ_TREE || type == OBJ_COMMIT ||
409 type == OBJ_BLOB || type == OBJ_TAG);
411 if (type == OBJ_COMMIT) {
412 struct strbuf date = STRBUF_INIT;
413 struct strbuf msg = STRBUF_INIT;
414 struct commit *commit = lookup_commit(ds->repo, oid);
416 if (commit) {
417 struct pretty_print_context pp = {0};
418 pp.date_mode.type = DATE_SHORT;
419 repo_format_commit_message(the_repository, commit,
420 "%ad", &date, &pp);
421 repo_format_commit_message(the_repository, commit,
422 "%s", &msg, &pp);
426 * TRANSLATORS: This is a line of ambiguous commit
427 * object output. E.g.:
429 * "deadbeef commit 2021-01-01 - Some Commit Message"
431 strbuf_addf(sb, _("%s commit %s - %s"), hash, date.buf,
432 msg.buf);
434 strbuf_release(&date);
435 strbuf_release(&msg);
436 } else if (type == OBJ_TAG) {
437 struct tag *tag = lookup_tag(ds->repo, oid);
439 if (!parse_tag(tag) && tag->tag) {
441 * TRANSLATORS: This is a line of ambiguous
442 * tag object output. E.g.:
444 * "deadbeef tag 2022-01-01 - Some Tag Message"
446 * The second argument is the YYYY-MM-DD found
447 * in the tag.
449 * The third argument is the "tag" string
450 * from object.c.
452 strbuf_addf(sb, _("%s tag %s - %s"), hash,
453 show_date(tag->date, 0, DATE_MODE(SHORT)),
454 tag->tag);
455 } else {
457 * TRANSLATORS: This is a line of ambiguous
458 * tag object output where we couldn't parse
459 * the tag itself. E.g.:
461 * "deadbeef [bad tag, could not parse it]"
463 strbuf_addf(sb, _("%s [bad tag, could not parse it]"),
464 hash);
466 } else if (type == OBJ_TREE) {
468 * TRANSLATORS: This is a line of ambiguous <type>
469 * object output. E.g. "deadbeef tree".
471 strbuf_addf(sb, _("%s tree"), hash);
472 } else if (type == OBJ_BLOB) {
474 * TRANSLATORS: This is a line of ambiguous <type>
475 * object output. E.g. "deadbeef blob".
477 strbuf_addf(sb, _("%s blob"), hash);
481 out:
483 * TRANSLATORS: This is line item of ambiguous object output
484 * from describe_ambiguous_object() above. For RTL languages
485 * you'll probably want to swap the "%s" and leading " " space
486 * around.
488 strbuf_addf(advice, _(" %s\n"), sb->buf);
490 strbuf_reset(sb);
491 return 0;
494 static int collect_ambiguous(const struct object_id *oid, void *data)
496 oid_array_append(data, oid);
497 return 0;
500 static int repo_collect_ambiguous(struct repository *r UNUSED,
501 const struct object_id *oid,
502 void *data)
504 return collect_ambiguous(oid, data);
507 static int sort_ambiguous(const void *va, const void *vb, void *ctx)
509 struct repository *sort_ambiguous_repo = ctx;
510 const struct object_id *a = va, *b = vb;
511 int a_type = oid_object_info(sort_ambiguous_repo, a, NULL);
512 int b_type = oid_object_info(sort_ambiguous_repo, b, NULL);
513 int a_type_sort;
514 int b_type_sort;
517 * Sorts by hash within the same object type, just as
518 * oid_array_for_each_unique() would do.
520 if (a_type == b_type) {
521 if (a->algo == b->algo)
522 return oidcmp(a, b);
523 else
524 return a->algo > b->algo ? 1 : -1;
528 * Between object types show tags, then commits, and finally
529 * trees and blobs.
531 * The object_type enum is commit, tree, blob, tag, but we
532 * want tag, commit, tree blob. Cleverly (perhaps too
533 * cleverly) do that with modulus, since the enum assigns 1 to
534 * commit, so tag becomes 0.
536 a_type_sort = a_type % 4;
537 b_type_sort = b_type % 4;
538 return a_type_sort > b_type_sort ? 1 : -1;
541 static void sort_ambiguous_oid_array(struct repository *r, struct oid_array *a)
543 QSORT_S(a->oid, a->nr, sort_ambiguous, r);
546 static enum get_oid_result get_short_oid(struct repository *r,
547 const char *name, int len,
548 struct object_id *oid,
549 unsigned flags)
551 int status;
552 struct disambiguate_state ds;
553 int quietly = !!(flags & GET_OID_QUIETLY);
554 const struct git_hash_algo *algo = r->hash_algo;
556 if (flags & GET_OID_HASH_ANY)
557 algo = NULL;
559 if (init_object_disambiguation(r, name, len, algo, &ds) < 0)
560 return -1;
562 if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
563 BUG("multiple get_short_oid disambiguator flags");
565 if (flags & GET_OID_COMMIT)
566 ds.fn = disambiguate_commit_only;
567 else if (flags & GET_OID_COMMITTISH)
568 ds.fn = disambiguate_committish_only;
569 else if (flags & GET_OID_TREE)
570 ds.fn = disambiguate_tree_only;
571 else if (flags & GET_OID_TREEISH)
572 ds.fn = disambiguate_treeish_only;
573 else if (flags & GET_OID_BLOB)
574 ds.fn = disambiguate_blob_only;
575 else
576 ds.fn = default_disambiguate_hint;
578 find_short_object_filename(&ds);
579 find_short_packed_object(&ds);
580 status = finish_object_disambiguation(&ds, oid);
583 * If we didn't find it, do the usual reprepare() slow-path,
584 * since the object may have recently been added to the repository
585 * or migrated from loose to packed.
587 if (status == MISSING_OBJECT) {
588 reprepare_packed_git(r);
589 find_short_object_filename(&ds);
590 find_short_packed_object(&ds);
591 status = finish_object_disambiguation(&ds, oid);
594 if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
595 struct oid_array collect = OID_ARRAY_INIT;
596 struct ambiguous_output out = {
597 .ds = &ds,
598 .sb = STRBUF_INIT,
599 .advice = STRBUF_INIT,
602 error(_("short object ID %s is ambiguous"), ds.hex_pfx);
605 * We may still have ambiguity if we simply saw a series of
606 * candidates that did not satisfy our hint function. In
607 * that case, we still want to show them, so disable the hint
608 * function entirely.
610 if (!ds.ambiguous)
611 ds.fn = NULL;
613 repo_for_each_abbrev(r, ds.hex_pfx, algo, collect_ambiguous, &collect);
614 sort_ambiguous_oid_array(r, &collect);
616 if (oid_array_for_each(&collect, show_ambiguous_object, &out))
617 BUG("show_ambiguous_object shouldn't return non-zero");
620 * TRANSLATORS: The argument is the list of ambiguous
621 * objects composed in show_ambiguous_object(). See
622 * its "TRANSLATORS" comments for details.
624 advise(_("The candidates are:\n%s"), out.advice.buf);
626 oid_array_clear(&collect);
627 strbuf_release(&out.advice);
628 strbuf_release(&out.sb);
631 return status;
634 int repo_for_each_abbrev(struct repository *r, const char *prefix,
635 const struct git_hash_algo *algo,
636 each_abbrev_fn fn, void *cb_data)
638 struct oid_array collect = OID_ARRAY_INIT;
639 struct disambiguate_state ds;
640 int ret;
642 if (init_object_disambiguation(r, prefix, strlen(prefix), algo, &ds) < 0)
643 return -1;
645 ds.always_call_fn = 1;
646 ds.fn = repo_collect_ambiguous;
647 ds.cb_data = &collect;
648 find_short_object_filename(&ds);
649 find_short_packed_object(&ds);
651 ret = oid_array_for_each_unique(&collect, fn, cb_data);
652 oid_array_clear(&collect);
653 return ret;
657 * Return the slot of the most-significant bit set in "val". There are various
658 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
659 * probably not a big deal here.
661 static unsigned msb(unsigned long val)
663 unsigned r = 0;
664 while (val >>= 1)
665 r++;
666 return r;
669 struct min_abbrev_data {
670 unsigned int init_len;
671 unsigned int cur_len;
672 char *hex;
673 struct repository *repo;
674 const struct object_id *oid;
677 static inline char get_hex_char_from_oid(const struct object_id *oid,
678 unsigned int pos)
680 static const char hex[] = "0123456789abcdef";
682 if ((pos & 1) == 0)
683 return hex[oid->hash[pos >> 1] >> 4];
684 else
685 return hex[oid->hash[pos >> 1] & 0xf];
688 static int extend_abbrev_len(const struct object_id *oid, void *cb_data)
690 struct min_abbrev_data *mad = cb_data;
692 unsigned int i = mad->init_len;
693 while (mad->hex[i] && mad->hex[i] == get_hex_char_from_oid(oid, i))
694 i++;
696 if (i < GIT_MAX_RAWSZ && i >= mad->cur_len)
697 mad->cur_len = i + 1;
699 return 0;
702 static int repo_extend_abbrev_len(struct repository *r UNUSED,
703 const struct object_id *oid,
704 void *cb_data)
706 return extend_abbrev_len(oid, cb_data);
709 static void find_abbrev_len_for_midx(struct multi_pack_index *m,
710 struct min_abbrev_data *mad)
712 int match = 0;
713 uint32_t num, first = 0;
714 struct object_id oid;
715 const struct object_id *mad_oid;
717 if (!m->num_objects)
718 return;
720 num = m->num_objects;
721 mad_oid = mad->oid;
722 match = bsearch_midx(mad_oid, m, &first);
725 * first is now the position in the packfile where we would insert
726 * mad->hash if it does not exist (or the position of mad->hash if
727 * it does exist). Hence, we consider a maximum of two objects
728 * nearby for the abbreviation length.
730 mad->init_len = 0;
731 if (!match) {
732 if (nth_midxed_object_oid(&oid, m, first))
733 extend_abbrev_len(&oid, mad);
734 } else if (first < num - 1) {
735 if (nth_midxed_object_oid(&oid, m, first + 1))
736 extend_abbrev_len(&oid, mad);
738 if (first > 0) {
739 if (nth_midxed_object_oid(&oid, m, first - 1))
740 extend_abbrev_len(&oid, mad);
742 mad->init_len = mad->cur_len;
745 static void find_abbrev_len_for_pack(struct packed_git *p,
746 struct min_abbrev_data *mad)
748 int match = 0;
749 uint32_t num, first = 0;
750 struct object_id oid;
751 const struct object_id *mad_oid;
753 if (p->multi_pack_index)
754 return;
756 if (open_pack_index(p) || !p->num_objects)
757 return;
759 num = p->num_objects;
760 mad_oid = mad->oid;
761 match = bsearch_pack(mad_oid, p, &first);
764 * first is now the position in the packfile where we would insert
765 * mad->hash if it does not exist (or the position of mad->hash if
766 * it does exist). Hence, we consider a maximum of two objects
767 * nearby for the abbreviation length.
769 mad->init_len = 0;
770 if (!match) {
771 if (!nth_packed_object_id(&oid, p, first))
772 extend_abbrev_len(&oid, mad);
773 } else if (first < num - 1) {
774 if (!nth_packed_object_id(&oid, p, first + 1))
775 extend_abbrev_len(&oid, mad);
777 if (first > 0) {
778 if (!nth_packed_object_id(&oid, p, first - 1))
779 extend_abbrev_len(&oid, mad);
781 mad->init_len = mad->cur_len;
784 static void find_abbrev_len_packed(struct min_abbrev_data *mad)
786 struct multi_pack_index *m;
787 struct packed_git *p;
789 for (m = get_multi_pack_index(mad->repo); m; m = m->next)
790 find_abbrev_len_for_midx(m, mad);
791 for (p = get_packed_git(mad->repo); p; p = p->next)
792 find_abbrev_len_for_pack(p, mad);
795 void strbuf_repo_add_unique_abbrev(struct strbuf *sb, struct repository *repo,
796 const struct object_id *oid, int abbrev_len)
798 int r;
799 strbuf_grow(sb, GIT_MAX_HEXSZ + 1);
800 r = repo_find_unique_abbrev_r(repo, sb->buf + sb->len, oid, abbrev_len);
801 strbuf_setlen(sb, sb->len + r);
804 void strbuf_add_unique_abbrev(struct strbuf *sb, const struct object_id *oid,
805 int abbrev_len)
807 strbuf_repo_add_unique_abbrev(sb, the_repository, oid, abbrev_len);
810 int repo_find_unique_abbrev_r(struct repository *r, char *hex,
811 const struct object_id *oid, int len)
813 const struct git_hash_algo *algo =
814 oid->algo ? &hash_algos[oid->algo] : r->hash_algo;
815 struct disambiguate_state ds;
816 struct min_abbrev_data mad;
817 struct object_id oid_ret;
818 const unsigned hexsz = algo->hexsz;
820 if (len < 0) {
821 unsigned long count = repo_approximate_object_count(r);
823 * Add one because the MSB only tells us the highest bit set,
824 * not including the value of all the _other_ bits (so "15"
825 * is only one off of 2^4, but the MSB is the 3rd bit.
827 len = msb(count) + 1;
829 * We now know we have on the order of 2^len objects, which
830 * expects a collision at 2^(len/2). But we also care about hex
831 * chars, not bits, and there are 4 bits per hex. So all
832 * together we need to divide by 2 and round up.
834 len = DIV_ROUND_UP(len, 2);
836 * For very small repos, we stick with our regular fallback.
838 if (len < FALLBACK_DEFAULT_ABBREV)
839 len = FALLBACK_DEFAULT_ABBREV;
842 oid_to_hex_r(hex, oid);
843 if (len >= hexsz || !len)
844 return hexsz;
846 mad.repo = r;
847 mad.init_len = len;
848 mad.cur_len = len;
849 mad.hex = hex;
850 mad.oid = oid;
852 find_abbrev_len_packed(&mad);
854 if (init_object_disambiguation(r, hex, mad.cur_len, algo, &ds) < 0)
855 return -1;
857 ds.fn = repo_extend_abbrev_len;
858 ds.always_call_fn = 1;
859 ds.cb_data = (void *)&mad;
861 find_short_object_filename(&ds);
862 (void)finish_object_disambiguation(&ds, &oid_ret);
864 hex[mad.cur_len] = 0;
865 return mad.cur_len;
868 const char *repo_find_unique_abbrev(struct repository *r,
869 const struct object_id *oid,
870 int len)
872 static int bufno;
873 static char hexbuffer[4][GIT_MAX_HEXSZ + 1];
874 char *hex = hexbuffer[bufno];
875 bufno = (bufno + 1) % ARRAY_SIZE(hexbuffer);
876 repo_find_unique_abbrev_r(r, hex, oid, len);
877 return hex;
880 static int ambiguous_path(const char *path, int len)
882 int slash = 1;
883 int cnt;
885 for (cnt = 0; cnt < len; cnt++) {
886 switch (*path++) {
887 case '\0':
888 break;
889 case '/':
890 if (slash)
891 break;
892 slash = 1;
893 continue;
894 case '.':
895 continue;
896 default:
897 slash = 0;
898 continue;
900 break;
902 return slash;
905 static inline int at_mark(const char *string, int len,
906 const char **suffix, int nr)
908 int i;
910 for (i = 0; i < nr; i++) {
911 int suffix_len = strlen(suffix[i]);
912 if (suffix_len <= len
913 && !strncasecmp(string, suffix[i], suffix_len))
914 return suffix_len;
916 return 0;
919 static inline int upstream_mark(const char *string, int len)
921 const char *suffix[] = { "@{upstream}", "@{u}" };
922 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
925 static inline int push_mark(const char *string, int len)
927 const char *suffix[] = { "@{push}" };
928 return at_mark(string, len, suffix, ARRAY_SIZE(suffix));
931 static enum get_oid_result get_oid_1(struct repository *r, const char *name, int len, struct object_id *oid, unsigned lookup_flags);
932 static int interpret_nth_prior_checkout(struct repository *r, const char *name, int namelen, struct strbuf *buf);
934 static int get_oid_basic(struct repository *r, const char *str, int len,
935 struct object_id *oid, unsigned int flags)
937 static const char *warn_msg = "refname '%.*s' is ambiguous.";
938 static const char *object_name_msg = N_(
939 "Git normally never creates a ref that ends with 40 hex characters\n"
940 "because it will be ignored when you just specify 40-hex. These refs\n"
941 "may be created by mistake. For example,\n"
942 "\n"
943 " git switch -c $br $(git rev-parse ...)\n"
944 "\n"
945 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
946 "examine these refs and maybe delete them. Turn this message off by\n"
947 "running \"git config advice.objectNameWarning false\"");
948 struct object_id tmp_oid;
949 char *real_ref = NULL;
950 int refs_found = 0;
951 int at, reflog_len, nth_prior = 0;
952 int fatal = !(flags & GET_OID_QUIETLY);
954 if (len == r->hash_algo->hexsz && !get_oid_hex(str, oid)) {
955 if (warn_ambiguous_refs && warn_on_object_refname_ambiguity) {
956 refs_found = repo_dwim_ref(r, str, len, &tmp_oid, &real_ref, 0);
957 if (refs_found > 0) {
958 warning(warn_msg, len, str);
959 if (advice_enabled(ADVICE_OBJECT_NAME_WARNING))
960 fprintf(stderr, "%s\n", _(object_name_msg));
962 free(real_ref);
964 return 0;
967 /* basic@{time or number or -number} format to query ref-log */
968 reflog_len = at = 0;
969 if (len && str[len-1] == '}') {
970 for (at = len-4; at >= 0; at--) {
971 if (str[at] == '@' && str[at+1] == '{') {
972 if (str[at+2] == '-') {
973 if (at != 0)
974 /* @{-N} not at start */
975 return -1;
976 nth_prior = 1;
977 continue;
979 if (!upstream_mark(str + at, len - at) &&
980 !push_mark(str + at, len - at)) {
981 reflog_len = (len-1) - (at+2);
982 len = at;
984 break;
989 /* Accept only unambiguous ref paths. */
990 if (len && ambiguous_path(str, len))
991 return -1;
993 if (nth_prior) {
994 struct strbuf buf = STRBUF_INIT;
995 int detached;
997 if (interpret_nth_prior_checkout(r, str, len, &buf) > 0) {
998 detached = (buf.len == r->hash_algo->hexsz && !get_oid_hex(buf.buf, oid));
999 strbuf_release(&buf);
1000 if (detached)
1001 return 0;
1005 if (!len && reflog_len)
1006 /* allow "@{...}" to mean the current branch reflog */
1007 refs_found = repo_dwim_ref(r, "HEAD", 4, oid, &real_ref, !fatal);
1008 else if (reflog_len)
1009 refs_found = repo_dwim_log(r, str, len, oid, &real_ref);
1010 else
1011 refs_found = repo_dwim_ref(r, str, len, oid, &real_ref, !fatal);
1013 if (!refs_found)
1014 return -1;
1016 if (warn_ambiguous_refs && !(flags & GET_OID_QUIETLY) &&
1017 (refs_found > 1 ||
1018 !get_short_oid(r, str, len, &tmp_oid, GET_OID_QUIETLY)))
1019 warning(warn_msg, len, str);
1021 if (reflog_len) {
1022 int nth, i;
1023 timestamp_t at_time;
1024 timestamp_t co_time;
1025 int co_tz, co_cnt;
1027 /* Is it asking for N-th entry, or approxidate? */
1028 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
1029 char ch = str[at+2+i];
1030 if ('0' <= ch && ch <= '9')
1031 nth = nth * 10 + ch - '0';
1032 else
1033 nth = -1;
1035 if (100000000 <= nth) {
1036 at_time = nth;
1037 nth = -1;
1038 } else if (0 <= nth)
1039 at_time = 0;
1040 else {
1041 int errors = 0;
1042 char *tmp = xstrndup(str + at + 2, reflog_len);
1043 at_time = approxidate_careful(tmp, &errors);
1044 free(tmp);
1045 if (errors) {
1046 free(real_ref);
1047 return -1;
1050 if (read_ref_at(get_main_ref_store(r),
1051 real_ref, flags, at_time, nth, oid, NULL,
1052 &co_time, &co_tz, &co_cnt)) {
1053 if (!len) {
1054 if (!skip_prefix(real_ref, "refs/heads/", &str))
1055 str = "HEAD";
1056 len = strlen(str);
1058 if (at_time) {
1059 if (!(flags & GET_OID_QUIETLY)) {
1060 warning(_("log for '%.*s' only goes back to %s"),
1061 len, str,
1062 show_date(co_time, co_tz, DATE_MODE(RFC2822)));
1064 } else if (nth == co_cnt && !is_null_oid(oid)) {
1066 * We were asked for the Nth reflog (counting
1067 * from 0), but there were only N entries.
1068 * read_ref_at() will have returned "1" to tell
1069 * us it did not find an entry, but it did
1070 * still fill in the oid with the "old" value,
1071 * which we can use.
1073 } else {
1074 if (flags & GET_OID_QUIETLY) {
1075 exit(128);
1077 die(_("log for '%.*s' only has %d entries"),
1078 len, str, co_cnt);
1083 free(real_ref);
1084 return 0;
1087 static enum get_oid_result get_parent(struct repository *r,
1088 const char *name, int len,
1089 struct object_id *result, int idx)
1091 struct object_id oid;
1092 enum get_oid_result ret = get_oid_1(r, name, len, &oid,
1093 GET_OID_COMMITTISH);
1094 struct commit *commit;
1095 struct commit_list *p;
1097 if (ret)
1098 return ret;
1099 commit = lookup_commit_reference(r, &oid);
1100 if (repo_parse_commit(r, commit))
1101 return MISSING_OBJECT;
1102 if (!idx) {
1103 oidcpy(result, &commit->object.oid);
1104 return FOUND;
1106 p = commit->parents;
1107 while (p) {
1108 if (!--idx) {
1109 oidcpy(result, &p->item->object.oid);
1110 return FOUND;
1112 p = p->next;
1114 return MISSING_OBJECT;
1117 static enum get_oid_result get_nth_ancestor(struct repository *r,
1118 const char *name, int len,
1119 struct object_id *result,
1120 int generation)
1122 struct object_id oid;
1123 struct commit *commit;
1124 int ret;
1126 ret = get_oid_1(r, name, len, &oid, GET_OID_COMMITTISH);
1127 if (ret)
1128 return ret;
1129 commit = lookup_commit_reference(r, &oid);
1130 if (!commit)
1131 return MISSING_OBJECT;
1133 while (generation--) {
1134 if (repo_parse_commit(r, commit) || !commit->parents)
1135 return MISSING_OBJECT;
1136 commit = commit->parents->item;
1138 oidcpy(result, &commit->object.oid);
1139 return FOUND;
1142 struct object *repo_peel_to_type(struct repository *r, const char *name, int namelen,
1143 struct object *o, enum object_type expected_type)
1145 if (name && !namelen)
1146 namelen = strlen(name);
1147 while (1) {
1148 if (!o || (!o->parsed && !parse_object(r, &o->oid)))
1149 return NULL;
1150 if (expected_type == OBJ_ANY || o->type == expected_type)
1151 return o;
1152 if (o->type == OBJ_TAG)
1153 o = ((struct tag*) o)->tagged;
1154 else if (o->type == OBJ_COMMIT)
1155 o = &(repo_get_commit_tree(r, ((struct commit *)o))->object);
1156 else {
1157 if (name)
1158 error("%.*s: expected %s type, but the object "
1159 "dereferences to %s type",
1160 namelen, name, type_name(expected_type),
1161 type_name(o->type));
1162 return NULL;
1167 static int peel_onion(struct repository *r, const char *name, int len,
1168 struct object_id *oid, unsigned lookup_flags)
1170 struct object_id outer;
1171 const char *sp;
1172 unsigned int expected_type = 0;
1173 struct object *o;
1176 * "ref^{type}" dereferences ref repeatedly until you cannot
1177 * dereference anymore, or you get an object of given type,
1178 * whichever comes first. "ref^{}" means just dereference
1179 * tags until you get a non-tag. "ref^0" is a shorthand for
1180 * "ref^{commit}". "commit^{tree}" could be used to find the
1181 * top-level tree of the given commit.
1183 if (len < 4 || name[len-1] != '}')
1184 return -1;
1186 for (sp = name + len - 1; name <= sp; sp--) {
1187 int ch = *sp;
1188 if (ch == '{' && name < sp && sp[-1] == '^')
1189 break;
1191 if (sp <= name)
1192 return -1;
1194 sp++; /* beginning of type name, or closing brace for empty */
1195 if (starts_with(sp, "commit}"))
1196 expected_type = OBJ_COMMIT;
1197 else if (starts_with(sp, "tag}"))
1198 expected_type = OBJ_TAG;
1199 else if (starts_with(sp, "tree}"))
1200 expected_type = OBJ_TREE;
1201 else if (starts_with(sp, "blob}"))
1202 expected_type = OBJ_BLOB;
1203 else if (starts_with(sp, "object}"))
1204 expected_type = OBJ_ANY;
1205 else if (sp[0] == '}')
1206 expected_type = OBJ_NONE;
1207 else if (sp[0] == '/')
1208 expected_type = OBJ_COMMIT;
1209 else
1210 return -1;
1212 lookup_flags &= ~GET_OID_DISAMBIGUATORS;
1213 if (expected_type == OBJ_COMMIT)
1214 lookup_flags |= GET_OID_COMMITTISH;
1215 else if (expected_type == OBJ_TREE)
1216 lookup_flags |= GET_OID_TREEISH;
1218 if (get_oid_1(r, name, sp - name - 2, &outer, lookup_flags))
1219 return -1;
1221 o = parse_object(r, &outer);
1222 if (!o)
1223 return -1;
1224 if (!expected_type) {
1225 o = deref_tag(r, o, name, sp - name - 2);
1226 if (!o || (!o->parsed && !parse_object(r, &o->oid)))
1227 return -1;
1228 oidcpy(oid, &o->oid);
1229 return 0;
1233 * At this point, the syntax look correct, so
1234 * if we do not get the needed object, we should
1235 * barf.
1237 o = repo_peel_to_type(r, name, len, o, expected_type);
1238 if (!o)
1239 return -1;
1241 oidcpy(oid, &o->oid);
1242 if (sp[0] == '/') {
1243 /* "$commit^{/foo}" */
1244 char *prefix;
1245 int ret;
1246 struct commit_list *list = NULL;
1249 * $commit^{/}. Some regex implementation may reject.
1250 * We don't need regex anyway. '' pattern always matches.
1252 if (sp[1] == '}')
1253 return 0;
1255 prefix = xstrndup(sp + 1, name + len - 1 - (sp + 1));
1256 commit_list_insert((struct commit *)o, &list);
1257 ret = get_oid_oneline(r, prefix, oid, list);
1259 free_commit_list(list);
1260 free(prefix);
1261 return ret;
1263 return 0;
1266 static int get_describe_name(struct repository *r,
1267 const char *name, int len,
1268 struct object_id *oid)
1270 const char *cp;
1271 unsigned flags = GET_OID_QUIETLY | GET_OID_COMMIT;
1273 for (cp = name + len - 1; name + 2 <= cp; cp--) {
1274 char ch = *cp;
1275 if (!isxdigit(ch)) {
1276 /* We must be looking at g in "SOMETHING-g"
1277 * for it to be describe output.
1279 if (ch == 'g' && cp[-1] == '-') {
1280 cp++;
1281 len -= cp - name;
1282 return get_short_oid(r,
1283 cp, len, oid, flags);
1287 return -1;
1290 static enum get_oid_result get_oid_1(struct repository *r,
1291 const char *name, int len,
1292 struct object_id *oid,
1293 unsigned lookup_flags)
1295 int ret, has_suffix;
1296 const char *cp;
1299 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1301 has_suffix = 0;
1302 for (cp = name + len - 1; name <= cp; cp--) {
1303 int ch = *cp;
1304 if ('0' <= ch && ch <= '9')
1305 continue;
1306 if (ch == '~' || ch == '^')
1307 has_suffix = ch;
1308 break;
1311 if (has_suffix) {
1312 unsigned int num = 0;
1313 int len1 = cp - name;
1314 cp++;
1315 while (cp < name + len) {
1316 unsigned int digit = *cp++ - '0';
1317 if (unsigned_mult_overflows(num, 10))
1318 return MISSING_OBJECT;
1319 num *= 10;
1320 if (unsigned_add_overflows(num, digit))
1321 return MISSING_OBJECT;
1322 num += digit;
1324 if (!num && len1 == len - 1)
1325 num = 1;
1326 else if (num > INT_MAX)
1327 return MISSING_OBJECT;
1328 if (has_suffix == '^')
1329 return get_parent(r, name, len1, oid, num);
1330 /* else if (has_suffix == '~') -- goes without saying */
1331 return get_nth_ancestor(r, name, len1, oid, num);
1334 ret = peel_onion(r, name, len, oid, lookup_flags);
1335 if (!ret)
1336 return FOUND;
1338 ret = get_oid_basic(r, name, len, oid, lookup_flags);
1339 if (!ret)
1340 return FOUND;
1342 /* It could be describe output that is "SOMETHING-gXXXX" */
1343 ret = get_describe_name(r, name, len, oid);
1344 if (!ret)
1345 return FOUND;
1347 return get_short_oid(r, name, len, oid, lookup_flags);
1351 * This interprets names like ':/Initial revision of "git"' by searching
1352 * through history and returning the first commit whose message starts
1353 * the given regular expression.
1355 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1357 * For a literal '!' character at the beginning of a pattern, you have to repeat
1358 * that, like: ':/!!foo'
1360 * For future extension, all other sequences beginning with ':/!' are reserved.
1363 /* Remember to update object flag allocation in object.h */
1364 #define ONELINE_SEEN (1u<<20)
1366 struct handle_one_ref_cb {
1367 struct repository *repo;
1368 struct commit_list **list;
1371 static int handle_one_ref(const char *path, const struct object_id *oid,
1372 int flag UNUSED,
1373 void *cb_data)
1375 struct handle_one_ref_cb *cb = cb_data;
1376 struct commit_list **list = cb->list;
1377 struct object *object = parse_object(cb->repo, oid);
1378 if (!object)
1379 return 0;
1380 if (object->type == OBJ_TAG) {
1381 object = deref_tag(cb->repo, object, path,
1382 strlen(path));
1383 if (!object)
1384 return 0;
1386 if (object->type != OBJ_COMMIT)
1387 return 0;
1388 commit_list_insert((struct commit *)object, list);
1389 return 0;
1392 static int get_oid_oneline(struct repository *r,
1393 const char *prefix, struct object_id *oid,
1394 const struct commit_list *list)
1396 struct commit_list *copy = NULL;
1397 const struct commit_list *l;
1398 int found = 0;
1399 int negative = 0;
1400 regex_t regex;
1402 if (prefix[0] == '!') {
1403 prefix++;
1405 if (prefix[0] == '-') {
1406 prefix++;
1407 negative = 1;
1408 } else if (prefix[0] != '!') {
1409 return -1;
1413 if (regcomp(&regex, prefix, REG_EXTENDED))
1414 return -1;
1416 for (l = list; l; l = l->next) {
1417 l->item->object.flags |= ONELINE_SEEN;
1418 commit_list_insert(l->item, &copy);
1420 while (copy) {
1421 const char *p, *buf;
1422 struct commit *commit;
1423 int matches;
1425 commit = pop_most_recent_commit(&copy, ONELINE_SEEN);
1426 if (!parse_object(r, &commit->object.oid))
1427 continue;
1428 buf = repo_get_commit_buffer(r, commit, NULL);
1429 p = strstr(buf, "\n\n");
1430 matches = negative ^ (p && !regexec(&regex, p + 2, 0, NULL, 0));
1431 repo_unuse_commit_buffer(r, commit, buf);
1433 if (matches) {
1434 oidcpy(oid, &commit->object.oid);
1435 found = 1;
1436 break;
1439 regfree(&regex);
1440 for (l = list; l; l = l->next)
1441 clear_commit_marks(l->item, ONELINE_SEEN);
1442 free_commit_list(copy);
1443 return found ? 0 : -1;
1446 struct grab_nth_branch_switch_cbdata {
1447 int remaining;
1448 struct strbuf *sb;
1451 static int grab_nth_branch_switch(struct object_id *ooid UNUSED,
1452 struct object_id *noid UNUSED,
1453 const char *email UNUSED,
1454 timestamp_t timestamp UNUSED,
1455 int tz UNUSED,
1456 const char *message, void *cb_data)
1458 struct grab_nth_branch_switch_cbdata *cb = cb_data;
1459 const char *match = NULL, *target = NULL;
1460 size_t len;
1462 if (skip_prefix(message, "checkout: moving from ", &match))
1463 target = strstr(match, " to ");
1465 if (!match || !target)
1466 return 0;
1467 if (--(cb->remaining) == 0) {
1468 len = target - match;
1469 strbuf_reset(cb->sb);
1470 strbuf_add(cb->sb, match, len);
1471 return 1; /* we are done */
1473 return 0;
1477 * Parse @{-N} syntax, return the number of characters parsed
1478 * if successful; otherwise signal an error with negative value.
1480 static int interpret_nth_prior_checkout(struct repository *r,
1481 const char *name, int namelen,
1482 struct strbuf *buf)
1484 long nth;
1485 int retval;
1486 struct grab_nth_branch_switch_cbdata cb;
1487 const char *brace;
1488 char *num_end;
1490 if (namelen < 4)
1491 return -1;
1492 if (name[0] != '@' || name[1] != '{' || name[2] != '-')
1493 return -1;
1494 brace = memchr(name, '}', namelen);
1495 if (!brace)
1496 return -1;
1497 nth = strtol(name + 3, &num_end, 10);
1498 if (num_end != brace)
1499 return -1;
1500 if (nth <= 0)
1501 return -1;
1502 cb.remaining = nth;
1503 cb.sb = buf;
1505 retval = refs_for_each_reflog_ent_reverse(get_main_ref_store(r),
1506 "HEAD", grab_nth_branch_switch, &cb);
1507 if (0 < retval) {
1508 retval = brace - name + 1;
1509 } else
1510 retval = 0;
1512 return retval;
1515 int repo_get_oid_mb(struct repository *r,
1516 const char *name,
1517 struct object_id *oid)
1519 struct commit *one, *two;
1520 struct commit_list *mbs = NULL;
1521 struct object_id oid_tmp;
1522 const char *dots;
1523 int st;
1525 dots = strstr(name, "...");
1526 if (!dots)
1527 return repo_get_oid(r, name, oid);
1528 if (dots == name)
1529 st = repo_get_oid(r, "HEAD", &oid_tmp);
1530 else {
1531 struct strbuf sb;
1532 strbuf_init(&sb, dots - name);
1533 strbuf_add(&sb, name, dots - name);
1534 st = repo_get_oid_committish(r, sb.buf, &oid_tmp);
1535 strbuf_release(&sb);
1537 if (st)
1538 return st;
1539 one = lookup_commit_reference_gently(r, &oid_tmp, 0);
1540 if (!one)
1541 return -1;
1543 if (repo_get_oid_committish(r, dots[3] ? (dots + 3) : "HEAD", &oid_tmp))
1544 return -1;
1545 two = lookup_commit_reference_gently(r, &oid_tmp, 0);
1546 if (!two)
1547 return -1;
1548 if (repo_get_merge_bases(r, one, two, &mbs) < 0) {
1549 free_commit_list(mbs);
1550 return -1;
1552 if (!mbs || mbs->next)
1553 st = -1;
1554 else {
1555 st = 0;
1556 oidcpy(oid, &mbs->item->object.oid);
1558 free_commit_list(mbs);
1559 return st;
1562 /* parse @something syntax, when 'something' is not {.*} */
1563 static int interpret_empty_at(const char *name, int namelen, int len, struct strbuf *buf)
1565 const char *next;
1567 if (len || name[1] == '{')
1568 return -1;
1570 /* make sure it's a single @, or @@{.*}, not @foo */
1571 next = memchr(name + len + 1, '@', namelen - len - 1);
1572 if (next && next[1] != '{')
1573 return -1;
1574 if (!next)
1575 next = name + namelen;
1576 if (next != name + 1)
1577 return -1;
1579 strbuf_reset(buf);
1580 strbuf_add(buf, "HEAD", 4);
1581 return 1;
1584 static int reinterpret(struct repository *r,
1585 const char *name, int namelen, int len,
1586 struct strbuf *buf, unsigned allowed)
1588 /* we have extra data, which might need further processing */
1589 struct strbuf tmp = STRBUF_INIT;
1590 int used = buf->len;
1591 int ret;
1592 struct interpret_branch_name_options options = {
1593 .allowed = allowed
1596 strbuf_add(buf, name + len, namelen - len);
1597 ret = repo_interpret_branch_name(r, buf->buf, buf->len, &tmp, &options);
1598 /* that data was not interpreted, remove our cruft */
1599 if (ret < 0) {
1600 strbuf_setlen(buf, used);
1601 return len;
1603 strbuf_reset(buf);
1604 strbuf_addbuf(buf, &tmp);
1605 strbuf_release(&tmp);
1606 /* tweak for size of {-N} versus expanded ref name */
1607 return ret - used + len;
1610 static void set_shortened_ref(struct repository *r, struct strbuf *buf, const char *ref)
1612 char *s = refs_shorten_unambiguous_ref(get_main_ref_store(r), ref, 0);
1613 strbuf_reset(buf);
1614 strbuf_addstr(buf, s);
1615 free(s);
1618 static int branch_interpret_allowed(const char *refname, unsigned allowed)
1620 if (!allowed)
1621 return 1;
1623 if ((allowed & INTERPRET_BRANCH_LOCAL) &&
1624 starts_with(refname, "refs/heads/"))
1625 return 1;
1626 if ((allowed & INTERPRET_BRANCH_REMOTE) &&
1627 starts_with(refname, "refs/remotes/"))
1628 return 1;
1630 return 0;
1633 static int interpret_branch_mark(struct repository *r,
1634 const char *name, int namelen,
1635 int at, struct strbuf *buf,
1636 int (*get_mark)(const char *, int),
1637 const char *(*get_data)(struct branch *,
1638 struct strbuf *),
1639 const struct interpret_branch_name_options *options)
1641 int len;
1642 struct branch *branch;
1643 struct strbuf err = STRBUF_INIT;
1644 const char *value;
1646 len = get_mark(name + at, namelen - at);
1647 if (!len)
1648 return -1;
1650 if (memchr(name, ':', at))
1651 return -1;
1653 if (at) {
1654 char *name_str = xmemdupz(name, at);
1655 branch = branch_get(name_str);
1656 free(name_str);
1657 } else
1658 branch = branch_get(NULL);
1660 value = get_data(branch, &err);
1661 if (!value) {
1662 if (options->nonfatal_dangling_mark) {
1663 strbuf_release(&err);
1664 return -1;
1665 } else {
1666 die("%s", err.buf);
1670 if (!branch_interpret_allowed(value, options->allowed))
1671 return -1;
1673 set_shortened_ref(r, buf, value);
1674 return len + at;
1677 int repo_interpret_branch_name(struct repository *r,
1678 const char *name, int namelen,
1679 struct strbuf *buf,
1680 const struct interpret_branch_name_options *options)
1682 char *at;
1683 const char *start;
1684 int len;
1686 if (!namelen)
1687 namelen = strlen(name);
1689 if (!options->allowed || (options->allowed & INTERPRET_BRANCH_LOCAL)) {
1690 len = interpret_nth_prior_checkout(r, name, namelen, buf);
1691 if (!len) {
1692 return len; /* syntax Ok, not enough switches */
1693 } else if (len > 0) {
1694 if (len == namelen)
1695 return len; /* consumed all */
1696 else
1697 return reinterpret(r, name, namelen, len, buf,
1698 options->allowed);
1702 for (start = name;
1703 (at = memchr(start, '@', namelen - (start - name)));
1704 start = at + 1) {
1706 if (!options->allowed || (options->allowed & INTERPRET_BRANCH_HEAD)) {
1707 len = interpret_empty_at(name, namelen, at - name, buf);
1708 if (len > 0)
1709 return reinterpret(r, name, namelen, len, buf,
1710 options->allowed);
1713 len = interpret_branch_mark(r, name, namelen, at - name, buf,
1714 upstream_mark, branch_get_upstream,
1715 options);
1716 if (len > 0)
1717 return len;
1719 len = interpret_branch_mark(r, name, namelen, at - name, buf,
1720 push_mark, branch_get_push,
1721 options);
1722 if (len > 0)
1723 return len;
1726 return -1;
1729 void strbuf_branchname(struct strbuf *sb, const char *name, unsigned allowed)
1731 int len = strlen(name);
1732 struct interpret_branch_name_options options = {
1733 .allowed = allowed
1735 int used = repo_interpret_branch_name(the_repository, name, len, sb,
1736 &options);
1738 if (used < 0)
1739 used = 0;
1740 strbuf_add(sb, name + used, len - used);
1743 int strbuf_check_branch_ref(struct strbuf *sb, const char *name)
1745 if (startup_info->have_repository)
1746 strbuf_branchname(sb, name, INTERPRET_BRANCH_LOCAL);
1747 else
1748 strbuf_addstr(sb, name);
1751 * This splice must be done even if we end up rejecting the
1752 * name; builtin/branch.c::copy_or_rename_branch() still wants
1753 * to see what the name expanded to so that "branch -m" can be
1754 * used as a tool to correct earlier mistakes.
1756 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
1758 if (*name == '-' ||
1759 !strcmp(sb->buf, "refs/heads/HEAD"))
1760 return -1;
1762 return check_refname_format(sb->buf, 0);
1765 void object_context_release(struct object_context *ctx)
1767 free(ctx->path);
1771 * This is like "get_oid_basic()", except it allows "object ID expressions",
1772 * notably "xyz^" for "parent of xyz"
1774 int repo_get_oid(struct repository *r, const char *name, struct object_id *oid)
1776 struct object_context unused;
1777 int ret = get_oid_with_context(r, name, 0, oid, &unused);
1778 object_context_release(&unused);
1779 return ret;
1783 * This returns a non-zero value if the string (built using printf
1784 * format and the given arguments) is not a valid object.
1786 int get_oidf(struct object_id *oid, const char *fmt, ...)
1788 va_list ap;
1789 int ret;
1790 struct strbuf sb = STRBUF_INIT;
1792 va_start(ap, fmt);
1793 strbuf_vaddf(&sb, fmt, ap);
1794 va_end(ap);
1796 ret = repo_get_oid(the_repository, sb.buf, oid);
1797 strbuf_release(&sb);
1799 return ret;
1803 * Many callers know that the user meant to name a commit-ish by
1804 * syntactical positions where the object name appears. Calling this
1805 * function allows the machinery to disambiguate shorter-than-unique
1806 * abbreviated object names between commit-ish and others.
1808 * Note that this does NOT error out when the named object is not a
1809 * commit-ish. It is merely to give a hint to the disambiguation
1810 * machinery.
1812 int repo_get_oid_committish(struct repository *r,
1813 const char *name,
1814 struct object_id *oid)
1816 struct object_context unused;
1817 int ret = get_oid_with_context(r, name, GET_OID_COMMITTISH,
1818 oid, &unused);
1819 object_context_release(&unused);
1820 return ret;
1823 int repo_get_oid_treeish(struct repository *r,
1824 const char *name,
1825 struct object_id *oid)
1827 struct object_context unused;
1828 int ret = get_oid_with_context(r, name, GET_OID_TREEISH,
1829 oid, &unused);
1830 object_context_release(&unused);
1831 return ret;
1834 int repo_get_oid_commit(struct repository *r,
1835 const char *name,
1836 struct object_id *oid)
1838 struct object_context unused;
1839 int ret = get_oid_with_context(r, name, GET_OID_COMMIT,
1840 oid, &unused);
1841 object_context_release(&unused);
1842 return ret;
1845 int repo_get_oid_tree(struct repository *r,
1846 const char *name,
1847 struct object_id *oid)
1849 struct object_context unused;
1850 int ret = get_oid_with_context(r, name, GET_OID_TREE,
1851 oid, &unused);
1852 object_context_release(&unused);
1853 return ret;
1856 int repo_get_oid_blob(struct repository *r,
1857 const char *name,
1858 struct object_id *oid)
1860 struct object_context unused;
1861 int ret = get_oid_with_context(r, name, GET_OID_BLOB,
1862 oid, &unused);
1863 object_context_release(&unused);
1864 return ret;
1867 /* Must be called only when object_name:filename doesn't exist. */
1868 static void diagnose_invalid_oid_path(struct repository *r,
1869 const char *prefix,
1870 const char *filename,
1871 const struct object_id *tree_oid,
1872 const char *object_name,
1873 int object_name_len)
1875 struct object_id oid;
1876 unsigned short mode;
1878 if (!prefix)
1879 prefix = "";
1881 if (file_exists(filename))
1882 die(_("path '%s' exists on disk, but not in '%.*s'"),
1883 filename, object_name_len, object_name);
1884 if (is_missing_file_error(errno)) {
1885 char *fullname = xstrfmt("%s%s", prefix, filename);
1887 if (!get_tree_entry(r, tree_oid, fullname, &oid, &mode)) {
1888 die(_("path '%s' exists, but not '%s'\n"
1889 "hint: Did you mean '%.*s:%s' aka '%.*s:./%s'?"),
1890 fullname,
1891 filename,
1892 object_name_len, object_name,
1893 fullname,
1894 object_name_len, object_name,
1895 filename);
1897 die(_("path '%s' does not exist in '%.*s'"),
1898 filename, object_name_len, object_name);
1902 /* Must be called only when :stage:filename doesn't exist. */
1903 static void diagnose_invalid_index_path(struct repository *r,
1904 int stage,
1905 const char *prefix,
1906 const char *filename)
1908 struct index_state *istate = r->index;
1909 const struct cache_entry *ce;
1910 int pos;
1911 unsigned namelen = strlen(filename);
1912 struct strbuf fullname = STRBUF_INIT;
1914 if (!prefix)
1915 prefix = "";
1917 /* Wrong stage number? */
1918 pos = index_name_pos(istate, filename, namelen);
1919 if (pos < 0)
1920 pos = -pos - 1;
1921 if (pos < istate->cache_nr) {
1922 ce = istate->cache[pos];
1923 if (!S_ISSPARSEDIR(ce->ce_mode) &&
1924 ce_namelen(ce) == namelen &&
1925 !memcmp(ce->name, filename, namelen))
1926 die(_("path '%s' is in the index, but not at stage %d\n"
1927 "hint: Did you mean ':%d:%s'?"),
1928 filename, stage,
1929 ce_stage(ce), filename);
1932 /* Confusion between relative and absolute filenames? */
1933 strbuf_addstr(&fullname, prefix);
1934 strbuf_addstr(&fullname, filename);
1935 pos = index_name_pos(istate, fullname.buf, fullname.len);
1936 if (pos < 0)
1937 pos = -pos - 1;
1938 if (pos < istate->cache_nr) {
1939 ce = istate->cache[pos];
1940 if (!S_ISSPARSEDIR(ce->ce_mode) &&
1941 ce_namelen(ce) == fullname.len &&
1942 !memcmp(ce->name, fullname.buf, fullname.len))
1943 die(_("path '%s' is in the index, but not '%s'\n"
1944 "hint: Did you mean ':%d:%s' aka ':%d:./%s'?"),
1945 fullname.buf, filename,
1946 ce_stage(ce), fullname.buf,
1947 ce_stage(ce), filename);
1950 if (repo_file_exists(r, filename))
1951 die(_("path '%s' exists on disk, but not in the index"), filename);
1952 if (is_missing_file_error(errno))
1953 die(_("path '%s' does not exist (neither on disk nor in the index)"),
1954 filename);
1956 strbuf_release(&fullname);
1960 static char *resolve_relative_path(struct repository *r, const char *rel)
1962 if (!starts_with(rel, "./") && !starts_with(rel, "../"))
1963 return NULL;
1965 if (r != the_repository || !is_inside_work_tree())
1966 die(_("relative path syntax can't be used outside working tree"));
1968 /* die() inside prefix_path() if resolved path is outside worktree */
1969 return prefix_path(startup_info->prefix,
1970 startup_info->prefix ? strlen(startup_info->prefix) : 0,
1971 rel);
1974 static int reject_tree_in_index(struct repository *repo,
1975 int only_to_die,
1976 const struct cache_entry *ce,
1977 int stage,
1978 const char *prefix,
1979 const char *cp)
1981 if (!S_ISSPARSEDIR(ce->ce_mode))
1982 return 0;
1983 if (only_to_die)
1984 diagnose_invalid_index_path(repo, stage, prefix, cp);
1985 return -1;
1988 static enum get_oid_result get_oid_with_context_1(struct repository *repo,
1989 const char *name,
1990 unsigned flags,
1991 const char *prefix,
1992 struct object_id *oid,
1993 struct object_context *oc)
1995 int ret, bracket_depth;
1996 int namelen = strlen(name);
1997 const char *cp;
1998 int only_to_die = flags & GET_OID_ONLY_TO_DIE;
2000 memset(oc, 0, sizeof(*oc));
2001 oc->mode = S_IFINVALID;
2002 strbuf_init(&oc->symlink_path, 0);
2003 ret = get_oid_1(repo, name, namelen, oid, flags);
2004 if (!ret && flags & GET_OID_REQUIRE_PATH)
2005 die(_("<object>:<path> required, only <object> '%s' given"),
2006 name);
2007 if (!ret)
2008 return ret;
2010 * tree:path --> object name of path in tree
2011 * :path -> object name of absolute path in index
2012 * :./path -> object name of path relative to cwd in index
2013 * :[0-3]:path -> object name of path in index at stage
2014 * :/foo -> recent commit matching foo
2016 if (name[0] == ':') {
2017 int stage = 0;
2018 const struct cache_entry *ce;
2019 char *new_path = NULL;
2020 int pos;
2021 if (!only_to_die && namelen > 2 && name[1] == '/') {
2022 struct handle_one_ref_cb cb;
2023 struct commit_list *list = NULL;
2025 cb.repo = repo;
2026 cb.list = &list;
2027 refs_for_each_ref(get_main_ref_store(repo), handle_one_ref, &cb);
2028 refs_head_ref(get_main_ref_store(repo), handle_one_ref, &cb);
2029 commit_list_sort_by_date(&list);
2030 ret = get_oid_oneline(repo, name + 2, oid, list);
2032 free_commit_list(list);
2033 return ret;
2035 if (namelen < 3 ||
2036 name[2] != ':' ||
2037 name[1] < '0' || '3' < name[1])
2038 cp = name + 1;
2039 else {
2040 stage = name[1] - '0';
2041 cp = name + 3;
2043 new_path = resolve_relative_path(repo, cp);
2044 if (!new_path) {
2045 namelen = namelen - (cp - name);
2046 } else {
2047 cp = new_path;
2048 namelen = strlen(cp);
2051 if (flags & GET_OID_RECORD_PATH)
2052 oc->path = xstrdup(cp);
2054 if (!repo->index || !repo->index->cache)
2055 repo_read_index(repo);
2056 pos = index_name_pos(repo->index, cp, namelen);
2057 if (pos < 0)
2058 pos = -pos - 1;
2059 while (pos < repo->index->cache_nr) {
2060 ce = repo->index->cache[pos];
2061 if (ce_namelen(ce) != namelen ||
2062 memcmp(ce->name, cp, namelen))
2063 break;
2064 if (ce_stage(ce) == stage) {
2065 free(new_path);
2066 if (reject_tree_in_index(repo, only_to_die, ce,
2067 stage, prefix, cp))
2068 return -1;
2069 oidcpy(oid, &ce->oid);
2070 oc->mode = ce->ce_mode;
2071 return 0;
2073 pos++;
2075 if (only_to_die && name[1] && name[1] != '/')
2076 diagnose_invalid_index_path(repo, stage, prefix, cp);
2077 free(new_path);
2078 return -1;
2080 for (cp = name, bracket_depth = 0; *cp; cp++) {
2081 if (*cp == '{')
2082 bracket_depth++;
2083 else if (bracket_depth && *cp == '}')
2084 bracket_depth--;
2085 else if (!bracket_depth && *cp == ':')
2086 break;
2088 if (*cp == ':') {
2089 struct object_id tree_oid;
2090 int len = cp - name;
2091 unsigned sub_flags = flags;
2093 sub_flags &= ~GET_OID_DISAMBIGUATORS;
2094 sub_flags |= GET_OID_TREEISH;
2096 if (!get_oid_1(repo, name, len, &tree_oid, sub_flags)) {
2097 const char *filename = cp+1;
2098 char *new_filename = NULL;
2100 new_filename = resolve_relative_path(repo, filename);
2101 if (new_filename)
2102 filename = new_filename;
2103 if (flags & GET_OID_FOLLOW_SYMLINKS) {
2104 ret = get_tree_entry_follow_symlinks(repo, &tree_oid,
2105 filename, oid, &oc->symlink_path,
2106 &oc->mode);
2107 } else {
2108 ret = get_tree_entry(repo, &tree_oid, filename, oid,
2109 &oc->mode);
2110 if (ret && only_to_die) {
2111 diagnose_invalid_oid_path(repo, prefix,
2112 filename,
2113 &tree_oid,
2114 name, len);
2117 if (flags & GET_OID_RECORD_PATH)
2118 oc->path = xstrdup(filename);
2120 free(new_filename);
2121 return ret;
2122 } else {
2123 if (only_to_die)
2124 die(_("invalid object name '%.*s'."), len, name);
2127 return ret;
2131 * Call this function when you know "name" given by the end user must
2132 * name an object but it doesn't; the function _may_ die with a better
2133 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
2134 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
2135 * you have a chance to diagnose the error further.
2137 void maybe_die_on_misspelt_object_name(struct repository *r,
2138 const char *name,
2139 const char *prefix)
2141 struct object_context oc;
2142 struct object_id oid;
2143 get_oid_with_context_1(r, name, GET_OID_ONLY_TO_DIE | GET_OID_QUIETLY,
2144 prefix, &oid, &oc);
2145 object_context_release(&oc);
2148 enum get_oid_result get_oid_with_context(struct repository *repo,
2149 const char *str,
2150 unsigned flags,
2151 struct object_id *oid,
2152 struct object_context *oc)
2154 if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
2155 BUG("incompatible flags for get_oid_with_context");
2156 return get_oid_with_context_1(repo, str, flags, NULL, oid, oc);