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