interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / object-name.c

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