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