11 #include "sha1-array.h"
13 #include "object-store.h"
14 #include "repository.h"
16 static int get_oid_oneline(const char *, struct object_id
*, struct commit_list
*);
18 typedef int (*disambiguate_hint_fn
)(const struct object_id
*, void *);
20 struct disambiguate_state
{
21 int len
; /* length of prefix in hex chars */
22 char hex_pfx
[GIT_MAX_HEXSZ
+ 1];
23 struct object_id bin_pfx
;
25 disambiguate_hint_fn fn
;
27 struct object_id candidate
;
28 unsigned candidate_exists
:1;
29 unsigned candidate_checked
:1;
30 unsigned candidate_ok
:1;
31 unsigned disambiguate_fn_used
:1;
33 unsigned always_call_fn
:1;
36 static void update_candidates(struct disambiguate_state
*ds
, const struct object_id
*current
)
38 if (ds
->always_call_fn
) {
39 ds
->ambiguous
= ds
->fn(current
, ds
->cb_data
) ? 1 : 0;
42 if (!ds
->candidate_exists
) {
43 /* this is the first candidate */
44 oidcpy(&ds
->candidate
, current
);
45 ds
->candidate_exists
= 1;
47 } else if (!oidcmp(&ds
->candidate
, current
)) {
48 /* the same as what we already have seen */
53 /* cannot disambiguate between ds->candidate and current */
58 if (!ds
->candidate_checked
) {
59 ds
->candidate_ok
= ds
->fn(&ds
->candidate
, ds
->cb_data
);
60 ds
->disambiguate_fn_used
= 1;
61 ds
->candidate_checked
= 1;
64 if (!ds
->candidate_ok
) {
65 /* discard the candidate; we know it does not satisfy fn */
66 oidcpy(&ds
->candidate
, current
);
67 ds
->candidate_checked
= 0;
71 /* if we reach this point, we know ds->candidate satisfies fn */
72 if (ds
->fn(current
, ds
->cb_data
)) {
74 * if both current and candidate satisfy fn, we cannot
81 /* otherwise, current can be discarded and candidate is still good */
84 static int append_loose_object(const struct object_id
*oid
, const char *path
,
87 oid_array_append(data
, oid
);
91 static int match_sha(unsigned, const unsigned char *, const unsigned char *);
93 static void find_short_object_filename(struct disambiguate_state
*ds
)
95 int subdir_nr
= ds
->bin_pfx
.hash
[0];
96 struct alternate_object_database
*alt
;
97 static struct alternate_object_database
*fakeent
;
101 * Create a "fake" alternate object database that
102 * points to our own object database, to make it
103 * easier to get a temporary working space in
104 * alt->name/alt->base while iterating over the
105 * object databases including our own.
107 fakeent
= alloc_alt_odb(get_object_directory());
109 fakeent
->next
= the_repository
->objects
->alt_odb_list
;
111 for (alt
= fakeent
; alt
&& !ds
->ambiguous
; alt
= alt
->next
) {
114 if (!alt
->loose_objects_subdir_seen
[subdir_nr
]) {
115 struct strbuf
*buf
= alt_scratch_buf(alt
);
116 for_each_file_in_obj_subdir(subdir_nr
, buf
,
119 &alt
->loose_objects_cache
);
120 alt
->loose_objects_subdir_seen
[subdir_nr
] = 1;
123 pos
= oid_array_lookup(&alt
->loose_objects_cache
, &ds
->bin_pfx
);
126 while (!ds
->ambiguous
&& pos
< alt
->loose_objects_cache
.nr
) {
127 const struct object_id
*oid
;
128 oid
= alt
->loose_objects_cache
.oid
+ pos
;
129 if (!match_sha(ds
->len
, ds
->bin_pfx
.hash
, oid
->hash
))
131 update_candidates(ds
, oid
);
137 static int match_sha(unsigned len
, const unsigned char *a
, const unsigned char *b
)
147 if ((*a
^ *b
) & 0xf0)
152 static void unique_in_pack(struct packed_git
*p
,
153 struct disambiguate_state
*ds
)
155 uint32_t num
, i
, first
= 0;
156 const struct object_id
*current
= NULL
;
158 if (open_pack_index(p
) || !p
->num_objects
)
161 num
= p
->num_objects
;
162 bsearch_pack(&ds
->bin_pfx
, p
, &first
);
165 * At this point, "first" is the location of the lowest object
166 * with an object name that could match "bin_pfx". See if we have
167 * 0, 1 or more objects that actually match(es).
169 for (i
= first
; i
< num
&& !ds
->ambiguous
; i
++) {
170 struct object_id oid
;
171 current
= nth_packed_object_oid(&oid
, p
, i
);
172 if (!match_sha(ds
->len
, ds
->bin_pfx
.hash
, current
->hash
))
174 update_candidates(ds
, current
);
178 static void find_short_packed_object(struct disambiguate_state
*ds
)
180 struct packed_git
*p
;
182 for (p
= get_packed_git(the_repository
); p
&& !ds
->ambiguous
;
184 unique_in_pack(p
, ds
);
187 #define SHORT_NAME_NOT_FOUND (-1)
188 #define SHORT_NAME_AMBIGUOUS (-2)
190 static int finish_object_disambiguation(struct disambiguate_state
*ds
,
191 struct object_id
*oid
)
194 return SHORT_NAME_AMBIGUOUS
;
196 if (!ds
->candidate_exists
)
197 return SHORT_NAME_NOT_FOUND
;
199 if (!ds
->candidate_checked
)
201 * If this is the only candidate, there is no point
202 * calling the disambiguation hint callback.
204 * On the other hand, if the current candidate
205 * replaced an earlier candidate that did _not_ pass
206 * the disambiguation hint callback, then we do have
207 * more than one objects that match the short name
208 * given, so we should make sure this one matches;
209 * otherwise, if we discovered this one and the one
210 * that we previously discarded in the reverse order,
211 * we would end up showing different results in the
214 ds
->candidate_ok
= (!ds
->disambiguate_fn_used
||
215 ds
->fn(&ds
->candidate
, ds
->cb_data
));
217 if (!ds
->candidate_ok
)
218 return SHORT_NAME_AMBIGUOUS
;
220 oidcpy(oid
, &ds
->candidate
);
224 static int disambiguate_commit_only(const struct object_id
*oid
, void *cb_data_unused
)
226 int kind
= oid_object_info(oid
, NULL
);
227 return kind
== OBJ_COMMIT
;
230 static int disambiguate_committish_only(const struct object_id
*oid
, void *cb_data_unused
)
235 kind
= oid_object_info(oid
, NULL
);
236 if (kind
== OBJ_COMMIT
)
241 /* We need to do this the hard way... */
242 obj
= deref_tag(parse_object(oid
), NULL
, 0);
243 if (obj
&& obj
->type
== OBJ_COMMIT
)
248 static int disambiguate_tree_only(const struct object_id
*oid
, void *cb_data_unused
)
250 int kind
= oid_object_info(oid
, NULL
);
251 return kind
== OBJ_TREE
;
254 static int disambiguate_treeish_only(const struct object_id
*oid
, void *cb_data_unused
)
259 kind
= oid_object_info(oid
, NULL
);
260 if (kind
== OBJ_TREE
|| kind
== OBJ_COMMIT
)
265 /* We need to do this the hard way... */
266 obj
= deref_tag(parse_object(oid
), NULL
, 0);
267 if (obj
&& (obj
->type
== OBJ_TREE
|| obj
->type
== OBJ_COMMIT
))
272 static int disambiguate_blob_only(const struct object_id
*oid
, void *cb_data_unused
)
274 int kind
= oid_object_info(oid
, NULL
);
275 return kind
== OBJ_BLOB
;
278 static disambiguate_hint_fn default_disambiguate_hint
;
280 int set_disambiguate_hint_config(const char *var
, const char *value
)
282 static const struct {
284 disambiguate_hint_fn fn
;
287 { "commit", disambiguate_commit_only
},
288 { "committish", disambiguate_committish_only
},
289 { "tree", disambiguate_tree_only
},
290 { "treeish", disambiguate_treeish_only
},
291 { "blob", disambiguate_blob_only
}
296 return config_error_nonbool(var
);
298 for (i
= 0; i
< ARRAY_SIZE(hints
); i
++) {
299 if (!strcasecmp(value
, hints
[i
].name
)) {
300 default_disambiguate_hint
= hints
[i
].fn
;
305 return error("unknown hint type for '%s': %s", var
, value
);
308 static int init_object_disambiguation(const char *name
, int len
,
309 struct disambiguate_state
*ds
)
313 if (len
< MINIMUM_ABBREV
|| len
> GIT_SHA1_HEXSZ
)
316 memset(ds
, 0, sizeof(*ds
));
318 for (i
= 0; i
< len
;i
++) {
319 unsigned char c
= name
[i
];
321 if (c
>= '0' && c
<= '9')
323 else if (c
>= 'a' && c
<= 'f')
325 else if (c
>= 'A' && c
<='F') {
334 ds
->bin_pfx
.hash
[i
>> 1] |= val
;
338 ds
->hex_pfx
[len
] = '\0';
339 prepare_alt_odb(the_repository
);
343 static int show_ambiguous_object(const struct object_id
*oid
, void *data
)
345 const struct disambiguate_state
*ds
= data
;
346 struct strbuf desc
= STRBUF_INIT
;
350 if (ds
->fn
&& !ds
->fn(oid
, ds
->cb_data
))
353 type
= oid_object_info(oid
, NULL
);
354 if (type
== OBJ_COMMIT
) {
355 struct commit
*commit
= lookup_commit(oid
);
357 struct pretty_print_context pp
= {0};
358 pp
.date_mode
.type
= DATE_SHORT
;
359 format_commit_message(commit
, " %ad - %s", &desc
, &pp
);
361 } else if (type
== OBJ_TAG
) {
362 struct tag
*tag
= lookup_tag(oid
);
363 if (!parse_tag(tag
) && tag
->tag
)
364 strbuf_addf(&desc
, " %s", tag
->tag
);
368 find_unique_abbrev(oid
, DEFAULT_ABBREV
),
369 type_name(type
) ? type_name(type
) : "unknown type",
372 strbuf_release(&desc
);
376 static int get_short_oid(const char *name
, int len
, struct object_id
*oid
,
380 struct disambiguate_state ds
;
381 int quietly
= !!(flags
& GET_OID_QUIETLY
);
383 if (init_object_disambiguation(name
, len
, &ds
) < 0)
386 if (HAS_MULTI_BITS(flags
& GET_OID_DISAMBIGUATORS
))
387 die("BUG: multiple get_short_oid disambiguator flags");
389 if (flags
& GET_OID_COMMIT
)
390 ds
.fn
= disambiguate_commit_only
;
391 else if (flags
& GET_OID_COMMITTISH
)
392 ds
.fn
= disambiguate_committish_only
;
393 else if (flags
& GET_OID_TREE
)
394 ds
.fn
= disambiguate_tree_only
;
395 else if (flags
& GET_OID_TREEISH
)
396 ds
.fn
= disambiguate_treeish_only
;
397 else if (flags
& GET_OID_BLOB
)
398 ds
.fn
= disambiguate_blob_only
;
400 ds
.fn
= default_disambiguate_hint
;
402 find_short_object_filename(&ds
);
403 find_short_packed_object(&ds
);
404 status
= finish_object_disambiguation(&ds
, oid
);
406 if (!quietly
&& (status
== SHORT_NAME_AMBIGUOUS
)) {
407 error(_("short SHA1 %s is ambiguous"), ds
.hex_pfx
);
410 * We may still have ambiguity if we simply saw a series of
411 * candidates that did not satisfy our hint function. In
412 * that case, we still want to show them, so disable the hint
418 advise(_("The candidates are:"));
419 for_each_abbrev(ds
.hex_pfx
, show_ambiguous_object
, &ds
);
425 static int collect_ambiguous(const struct object_id
*oid
, void *data
)
427 oid_array_append(data
, oid
);
431 int for_each_abbrev(const char *prefix
, each_abbrev_fn fn
, void *cb_data
)
433 struct oid_array collect
= OID_ARRAY_INIT
;
434 struct disambiguate_state ds
;
437 if (init_object_disambiguation(prefix
, strlen(prefix
), &ds
) < 0)
440 ds
.always_call_fn
= 1;
441 ds
.fn
= collect_ambiguous
;
442 ds
.cb_data
= &collect
;
443 find_short_object_filename(&ds
);
444 find_short_packed_object(&ds
);
446 ret
= oid_array_for_each_unique(&collect
, fn
, cb_data
);
447 oid_array_clear(&collect
);
452 * Return the slot of the most-significant bit set in "val". There are various
453 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
454 * probably not a big deal here.
456 static unsigned msb(unsigned long val
)
464 struct min_abbrev_data
{
465 unsigned int init_len
;
466 unsigned int cur_len
;
468 const struct object_id
*oid
;
471 static inline char get_hex_char_from_oid(const struct object_id
*oid
,
474 static const char hex
[] = "0123456789abcdef";
477 return hex
[oid
->hash
[pos
>> 1] >> 4];
479 return hex
[oid
->hash
[pos
>> 1] & 0xf];
482 static int extend_abbrev_len(const struct object_id
*oid
, void *cb_data
)
484 struct min_abbrev_data
*mad
= cb_data
;
486 unsigned int i
= mad
->init_len
;
487 while (mad
->hex
[i
] && mad
->hex
[i
] == get_hex_char_from_oid(oid
, i
))
490 if (i
< GIT_MAX_RAWSZ
&& i
>= mad
->cur_len
)
491 mad
->cur_len
= i
+ 1;
496 static void find_abbrev_len_for_pack(struct packed_git
*p
,
497 struct min_abbrev_data
*mad
)
500 uint32_t num
, first
= 0;
501 struct object_id oid
;
502 const struct object_id
*mad_oid
;
504 if (open_pack_index(p
) || !p
->num_objects
)
507 num
= p
->num_objects
;
509 match
= bsearch_pack(mad_oid
, p
, &first
);
512 * first is now the position in the packfile where we would insert
513 * mad->hash if it does not exist (or the position of mad->hash if
514 * it does exist). Hence, we consider a maximum of two objects
515 * nearby for the abbreviation length.
519 if (nth_packed_object_oid(&oid
, p
, first
))
520 extend_abbrev_len(&oid
, mad
);
521 } else if (first
< num
- 1) {
522 if (nth_packed_object_oid(&oid
, p
, first
+ 1))
523 extend_abbrev_len(&oid
, mad
);
526 if (nth_packed_object_oid(&oid
, p
, first
- 1))
527 extend_abbrev_len(&oid
, mad
);
529 mad
->init_len
= mad
->cur_len
;
532 static void find_abbrev_len_packed(struct min_abbrev_data
*mad
)
534 struct packed_git
*p
;
536 for (p
= get_packed_git(the_repository
); p
; p
= p
->next
)
537 find_abbrev_len_for_pack(p
, mad
);
540 int find_unique_abbrev_r(char *hex
, const struct object_id
*oid
, int len
)
542 struct disambiguate_state ds
;
543 struct min_abbrev_data mad
;
544 struct object_id oid_ret
;
546 unsigned long count
= approximate_object_count();
548 * Add one because the MSB only tells us the highest bit set,
549 * not including the value of all the _other_ bits (so "15"
550 * is only one off of 2^4, but the MSB is the 3rd bit.
552 len
= msb(count
) + 1;
554 * We now know we have on the order of 2^len objects, which
555 * expects a collision at 2^(len/2). But we also care about hex
556 * chars, not bits, and there are 4 bits per hex. So all
557 * together we need to divide by 2 and round up.
559 len
= DIV_ROUND_UP(len
, 2);
561 * For very small repos, we stick with our regular fallback.
563 if (len
< FALLBACK_DEFAULT_ABBREV
)
564 len
= FALLBACK_DEFAULT_ABBREV
;
567 oid_to_hex_r(hex
, oid
);
568 if (len
== GIT_SHA1_HEXSZ
|| !len
)
569 return GIT_SHA1_HEXSZ
;
576 find_abbrev_len_packed(&mad
);
578 if (init_object_disambiguation(hex
, mad
.cur_len
, &ds
) < 0)
581 ds
.fn
= extend_abbrev_len
;
582 ds
.always_call_fn
= 1;
583 ds
.cb_data
= (void *)&mad
;
585 find_short_object_filename(&ds
);
586 (void)finish_object_disambiguation(&ds
, &oid_ret
);
588 hex
[mad
.cur_len
] = 0;
592 const char *find_unique_abbrev(const struct object_id
*oid
, int len
)
595 static char hexbuffer
[4][GIT_MAX_HEXSZ
+ 1];
596 char *hex
= hexbuffer
[bufno
];
597 bufno
= (bufno
+ 1) % ARRAY_SIZE(hexbuffer
);
598 find_unique_abbrev_r(hex
, oid
, len
);
602 static int ambiguous_path(const char *path
, int len
)
607 for (cnt
= 0; cnt
< len
; cnt
++) {
627 static inline int at_mark(const char *string
, int len
,
628 const char **suffix
, int nr
)
632 for (i
= 0; i
< nr
; i
++) {
633 int suffix_len
= strlen(suffix
[i
]);
634 if (suffix_len
<= len
635 && !strncasecmp(string
, suffix
[i
], suffix_len
))
641 static inline int upstream_mark(const char *string
, int len
)
643 const char *suffix
[] = { "@{upstream}", "@{u}" };
644 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
647 static inline int push_mark(const char *string
, int len
)
649 const char *suffix
[] = { "@{push}" };
650 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
653 static int get_oid_1(const char *name
, int len
, struct object_id
*oid
, unsigned lookup_flags
);
654 static int interpret_nth_prior_checkout(const char *name
, int namelen
, struct strbuf
*buf
);
656 static int get_oid_basic(const char *str
, int len
, struct object_id
*oid
,
659 static const char *warn_msg
= "refname '%.*s' is ambiguous.";
660 static const char *object_name_msg
= N_(
661 "Git normally never creates a ref that ends with 40 hex characters\n"
662 "because it will be ignored when you just specify 40-hex. These refs\n"
663 "may be created by mistake. For example,\n"
665 " git checkout -b $br $(git rev-parse ...)\n"
667 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
668 "examine these refs and maybe delete them. Turn this message off by\n"
669 "running \"git config advice.objectNameWarning false\"");
670 struct object_id tmp_oid
;
671 char *real_ref
= NULL
;
673 int at
, reflog_len
, nth_prior
= 0;
675 if (len
== GIT_SHA1_HEXSZ
&& !get_oid_hex(str
, oid
)) {
676 if (warn_ambiguous_refs
&& warn_on_object_refname_ambiguity
) {
677 refs_found
= dwim_ref(str
, len
, &tmp_oid
, &real_ref
);
678 if (refs_found
> 0) {
679 warning(warn_msg
, len
, str
);
680 if (advice_object_name_warning
)
681 fprintf(stderr
, "%s\n", _(object_name_msg
));
688 /* basic@{time or number or -number} format to query ref-log */
690 if (len
&& str
[len
-1] == '}') {
691 for (at
= len
-4; at
>= 0; at
--) {
692 if (str
[at
] == '@' && str
[at
+1] == '{') {
693 if (str
[at
+2] == '-') {
695 /* @{-N} not at start */
700 if (!upstream_mark(str
+ at
, len
- at
) &&
701 !push_mark(str
+ at
, len
- at
)) {
702 reflog_len
= (len
-1) - (at
+2);
710 /* Accept only unambiguous ref paths. */
711 if (len
&& ambiguous_path(str
, len
))
715 struct strbuf buf
= STRBUF_INIT
;
718 if (interpret_nth_prior_checkout(str
, len
, &buf
) > 0) {
719 detached
= (buf
.len
== GIT_SHA1_HEXSZ
&& !get_oid_hex(buf
.buf
, oid
));
720 strbuf_release(&buf
);
726 if (!len
&& reflog_len
)
727 /* allow "@{...}" to mean the current branch reflog */
728 refs_found
= dwim_ref("HEAD", 4, oid
, &real_ref
);
730 refs_found
= dwim_log(str
, len
, oid
, &real_ref
);
732 refs_found
= dwim_ref(str
, len
, oid
, &real_ref
);
737 if (warn_ambiguous_refs
&& !(flags
& GET_OID_QUIETLY
) &&
739 !get_short_oid(str
, len
, &tmp_oid
, GET_OID_QUIETLY
)))
740 warning(warn_msg
, len
, str
);
748 /* Is it asking for N-th entry, or approxidate? */
749 for (i
= nth
= 0; 0 <= nth
&& i
< reflog_len
; i
++) {
750 char ch
= str
[at
+2+i
];
751 if ('0' <= ch
&& ch
<= '9')
752 nth
= nth
* 10 + ch
- '0';
756 if (100000000 <= nth
) {
763 char *tmp
= xstrndup(str
+ at
+ 2, reflog_len
);
764 at_time
= approxidate_careful(tmp
, &errors
);
771 if (read_ref_at(real_ref
, flags
, at_time
, nth
, oid
, NULL
,
772 &co_time
, &co_tz
, &co_cnt
)) {
774 if (starts_with(real_ref
, "refs/heads/")) {
776 len
= strlen(real_ref
+ 11);
784 if (!(flags
& GET_OID_QUIETLY
)) {
785 warning("Log for '%.*s' only goes "
786 "back to %s.", len
, str
,
787 show_date(co_time
, co_tz
, DATE_MODE(RFC2822
)));
790 if (flags
& GET_OID_QUIETLY
) {
793 die("Log for '%.*s' only has %d entries.",
803 static int get_parent(const char *name
, int len
,
804 struct object_id
*result
, int idx
)
806 struct object_id oid
;
807 int ret
= get_oid_1(name
, len
, &oid
, GET_OID_COMMITTISH
);
808 struct commit
*commit
;
809 struct commit_list
*p
;
813 commit
= lookup_commit_reference(&oid
);
814 if (parse_commit(commit
))
817 oidcpy(result
, &commit
->object
.oid
);
823 oidcpy(result
, &p
->item
->object
.oid
);
831 static int get_nth_ancestor(const char *name
, int len
,
832 struct object_id
*result
, int generation
)
834 struct object_id oid
;
835 struct commit
*commit
;
838 ret
= get_oid_1(name
, len
, &oid
, GET_OID_COMMITTISH
);
841 commit
= lookup_commit_reference(&oid
);
845 while (generation
--) {
846 if (parse_commit(commit
) || !commit
->parents
)
848 commit
= commit
->parents
->item
;
850 oidcpy(result
, &commit
->object
.oid
);
854 struct object
*peel_to_type(const char *name
, int namelen
,
855 struct object
*o
, enum object_type expected_type
)
857 if (name
&& !namelen
)
858 namelen
= strlen(name
);
860 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
862 if (expected_type
== OBJ_ANY
|| o
->type
== expected_type
)
864 if (o
->type
== OBJ_TAG
)
865 o
= ((struct tag
*) o
)->tagged
;
866 else if (o
->type
== OBJ_COMMIT
)
867 o
= &(((struct commit
*) o
)->tree
->object
);
870 error("%.*s: expected %s type, but the object "
871 "dereferences to %s type",
872 namelen
, name
, type_name(expected_type
),
879 static int peel_onion(const char *name
, int len
, struct object_id
*oid
,
880 unsigned lookup_flags
)
882 struct object_id outer
;
884 unsigned int expected_type
= 0;
888 * "ref^{type}" dereferences ref repeatedly until you cannot
889 * dereference anymore, or you get an object of given type,
890 * whichever comes first. "ref^{}" means just dereference
891 * tags until you get a non-tag. "ref^0" is a shorthand for
892 * "ref^{commit}". "commit^{tree}" could be used to find the
893 * top-level tree of the given commit.
895 if (len
< 4 || name
[len
-1] != '}')
898 for (sp
= name
+ len
- 1; name
<= sp
; sp
--) {
900 if (ch
== '{' && name
< sp
&& sp
[-1] == '^')
906 sp
++; /* beginning of type name, or closing brace for empty */
907 if (starts_with(sp
, "commit}"))
908 expected_type
= OBJ_COMMIT
;
909 else if (starts_with(sp
, "tag}"))
910 expected_type
= OBJ_TAG
;
911 else if (starts_with(sp
, "tree}"))
912 expected_type
= OBJ_TREE
;
913 else if (starts_with(sp
, "blob}"))
914 expected_type
= OBJ_BLOB
;
915 else if (starts_with(sp
, "object}"))
916 expected_type
= OBJ_ANY
;
917 else if (sp
[0] == '}')
918 expected_type
= OBJ_NONE
;
919 else if (sp
[0] == '/')
920 expected_type
= OBJ_COMMIT
;
924 lookup_flags
&= ~GET_OID_DISAMBIGUATORS
;
925 if (expected_type
== OBJ_COMMIT
)
926 lookup_flags
|= GET_OID_COMMITTISH
;
927 else if (expected_type
== OBJ_TREE
)
928 lookup_flags
|= GET_OID_TREEISH
;
930 if (get_oid_1(name
, sp
- name
- 2, &outer
, lookup_flags
))
933 o
= parse_object(&outer
);
936 if (!expected_type
) {
937 o
= deref_tag(o
, name
, sp
- name
- 2);
938 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
940 oidcpy(oid
, &o
->oid
);
945 * At this point, the syntax look correct, so
946 * if we do not get the needed object, we should
949 o
= peel_to_type(name
, len
, o
, expected_type
);
953 oidcpy(oid
, &o
->oid
);
955 /* "$commit^{/foo}" */
958 struct commit_list
*list
= NULL
;
961 * $commit^{/}. Some regex implementation may reject.
962 * We don't need regex anyway. '' pattern always matches.
967 prefix
= xstrndup(sp
+ 1, name
+ len
- 1 - (sp
+ 1));
968 commit_list_insert((struct commit
*)o
, &list
);
969 ret
= get_oid_oneline(prefix
, oid
, list
);
976 static int get_describe_name(const char *name
, int len
, struct object_id
*oid
)
979 unsigned flags
= GET_OID_QUIETLY
| GET_OID_COMMIT
;
981 for (cp
= name
+ len
- 1; name
+ 2 <= cp
; cp
--) {
984 /* We must be looking at g in "SOMETHING-g"
985 * for it to be describe output.
987 if (ch
== 'g' && cp
[-1] == '-') {
990 return get_short_oid(cp
, len
, oid
, flags
);
997 static int get_oid_1(const char *name
, int len
, struct object_id
*oid
, unsigned lookup_flags
)
1003 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1006 for (cp
= name
+ len
- 1; name
<= cp
; cp
--) {
1008 if ('0' <= ch
&& ch
<= '9')
1010 if (ch
== '~' || ch
== '^')
1017 int len1
= cp
- name
;
1019 while (cp
< name
+ len
)
1020 num
= num
* 10 + *cp
++ - '0';
1021 if (!num
&& len1
== len
- 1)
1023 if (has_suffix
== '^')
1024 return get_parent(name
, len1
, oid
, num
);
1025 /* else if (has_suffix == '~') -- goes without saying */
1026 return get_nth_ancestor(name
, len1
, oid
, num
);
1029 ret
= peel_onion(name
, len
, oid
, lookup_flags
);
1033 ret
= get_oid_basic(name
, len
, oid
, lookup_flags
);
1037 /* It could be describe output that is "SOMETHING-gXXXX" */
1038 ret
= get_describe_name(name
, len
, oid
);
1042 return get_short_oid(name
, len
, oid
, lookup_flags
);
1046 * This interprets names like ':/Initial revision of "git"' by searching
1047 * through history and returning the first commit whose message starts
1048 * the given regular expression.
1050 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1052 * For a literal '!' character at the beginning of a pattern, you have to repeat
1053 * that, like: ':/!!foo'
1055 * For future extension, all other sequences beginning with ':/!' are reserved.
1058 /* Remember to update object flag allocation in object.h */
1059 #define ONELINE_SEEN (1u<<20)
1061 static int handle_one_ref(const char *path
, const struct object_id
*oid
,
1062 int flag
, void *cb_data
)
1064 struct commit_list
**list
= cb_data
;
1065 struct object
*object
= parse_object(oid
);
1068 if (object
->type
== OBJ_TAG
) {
1069 object
= deref_tag(object
, path
, strlen(path
));
1073 if (object
->type
!= OBJ_COMMIT
)
1075 commit_list_insert((struct commit
*)object
, list
);
1079 static int get_oid_oneline(const char *prefix
, struct object_id
*oid
,
1080 struct commit_list
*list
)
1082 struct commit_list
*backup
= NULL
, *l
;
1087 if (prefix
[0] == '!') {
1090 if (prefix
[0] == '-') {
1093 } else if (prefix
[0] != '!') {
1098 if (regcomp(®ex
, prefix
, REG_EXTENDED
))
1101 for (l
= list
; l
; l
= l
->next
) {
1102 l
->item
->object
.flags
|= ONELINE_SEEN
;
1103 commit_list_insert(l
->item
, &backup
);
1106 const char *p
, *buf
;
1107 struct commit
*commit
;
1110 commit
= pop_most_recent_commit(&list
, ONELINE_SEEN
);
1111 if (!parse_object(&commit
->object
.oid
))
1113 buf
= get_commit_buffer(commit
, NULL
);
1114 p
= strstr(buf
, "\n\n");
1115 matches
= negative
^ (p
&& !regexec(®ex
, p
+ 2, 0, NULL
, 0));
1116 unuse_commit_buffer(commit
, buf
);
1119 oidcpy(oid
, &commit
->object
.oid
);
1125 free_commit_list(list
);
1126 for (l
= backup
; l
; l
= l
->next
)
1127 clear_commit_marks(l
->item
, ONELINE_SEEN
);
1128 free_commit_list(backup
);
1129 return found
? 0 : -1;
1132 struct grab_nth_branch_switch_cbdata
{
1137 static int grab_nth_branch_switch(struct object_id
*ooid
, struct object_id
*noid
,
1138 const char *email
, timestamp_t timestamp
, int tz
,
1139 const char *message
, void *cb_data
)
1141 struct grab_nth_branch_switch_cbdata
*cb
= cb_data
;
1142 const char *match
= NULL
, *target
= NULL
;
1145 if (skip_prefix(message
, "checkout: moving from ", &match
))
1146 target
= strstr(match
, " to ");
1148 if (!match
|| !target
)
1150 if (--(cb
->remaining
) == 0) {
1151 len
= target
- match
;
1152 strbuf_reset(&cb
->buf
);
1153 strbuf_add(&cb
->buf
, match
, len
);
1154 return 1; /* we are done */
1160 * Parse @{-N} syntax, return the number of characters parsed
1161 * if successful; otherwise signal an error with negative value.
1163 static int interpret_nth_prior_checkout(const char *name
, int namelen
,
1168 struct grab_nth_branch_switch_cbdata cb
;
1174 if (name
[0] != '@' || name
[1] != '{' || name
[2] != '-')
1176 brace
= memchr(name
, '}', namelen
);
1179 nth
= strtol(name
+ 3, &num_end
, 10);
1180 if (num_end
!= brace
)
1185 strbuf_init(&cb
.buf
, 20);
1188 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch
, &cb
)) {
1190 strbuf_addbuf(buf
, &cb
.buf
);
1191 retval
= brace
- name
+ 1;
1194 strbuf_release(&cb
.buf
);
1198 int get_oid_mb(const char *name
, struct object_id
*oid
)
1200 struct commit
*one
, *two
;
1201 struct commit_list
*mbs
;
1202 struct object_id oid_tmp
;
1206 dots
= strstr(name
, "...");
1208 return get_oid(name
, oid
);
1210 st
= get_oid("HEAD", &oid_tmp
);
1213 strbuf_init(&sb
, dots
- name
);
1214 strbuf_add(&sb
, name
, dots
- name
);
1215 st
= get_oid_committish(sb
.buf
, &oid_tmp
);
1216 strbuf_release(&sb
);
1220 one
= lookup_commit_reference_gently(&oid_tmp
, 0);
1224 if (get_oid_committish(dots
[3] ? (dots
+ 3) : "HEAD", &oid_tmp
))
1226 two
= lookup_commit_reference_gently(&oid_tmp
, 0);
1229 mbs
= get_merge_bases(one
, two
);
1230 if (!mbs
|| mbs
->next
)
1234 oidcpy(oid
, &mbs
->item
->object
.oid
);
1236 free_commit_list(mbs
);
1240 /* parse @something syntax, when 'something' is not {.*} */
1241 static int interpret_empty_at(const char *name
, int namelen
, int len
, struct strbuf
*buf
)
1245 if (len
|| name
[1] == '{')
1248 /* make sure it's a single @, or @@{.*}, not @foo */
1249 next
= memchr(name
+ len
+ 1, '@', namelen
- len
- 1);
1250 if (next
&& next
[1] != '{')
1253 next
= name
+ namelen
;
1254 if (next
!= name
+ 1)
1258 strbuf_add(buf
, "HEAD", 4);
1262 static int reinterpret(const char *name
, int namelen
, int len
,
1263 struct strbuf
*buf
, unsigned allowed
)
1265 /* we have extra data, which might need further processing */
1266 struct strbuf tmp
= STRBUF_INIT
;
1267 int used
= buf
->len
;
1270 strbuf_add(buf
, name
+ len
, namelen
- len
);
1271 ret
= interpret_branch_name(buf
->buf
, buf
->len
, &tmp
, allowed
);
1272 /* that data was not interpreted, remove our cruft */
1274 strbuf_setlen(buf
, used
);
1278 strbuf_addbuf(buf
, &tmp
);
1279 strbuf_release(&tmp
);
1280 /* tweak for size of {-N} versus expanded ref name */
1281 return ret
- used
+ len
;
1284 static void set_shortened_ref(struct strbuf
*buf
, const char *ref
)
1286 char *s
= shorten_unambiguous_ref(ref
, 0);
1288 strbuf_addstr(buf
, s
);
1292 static int branch_interpret_allowed(const char *refname
, unsigned allowed
)
1297 if ((allowed
& INTERPRET_BRANCH_LOCAL
) &&
1298 starts_with(refname
, "refs/heads/"))
1300 if ((allowed
& INTERPRET_BRANCH_REMOTE
) &&
1301 starts_with(refname
, "refs/remotes/"))
1307 static int interpret_branch_mark(const char *name
, int namelen
,
1308 int at
, struct strbuf
*buf
,
1309 int (*get_mark
)(const char *, int),
1310 const char *(*get_data
)(struct branch
*,
1315 struct branch
*branch
;
1316 struct strbuf err
= STRBUF_INIT
;
1319 len
= get_mark(name
+ at
, namelen
- at
);
1323 if (memchr(name
, ':', at
))
1327 char *name_str
= xmemdupz(name
, at
);
1328 branch
= branch_get(name_str
);
1331 branch
= branch_get(NULL
);
1333 value
= get_data(branch
, &err
);
1337 if (!branch_interpret_allowed(value
, allowed
))
1340 set_shortened_ref(buf
, value
);
1344 int interpret_branch_name(const char *name
, int namelen
, struct strbuf
*buf
,
1352 namelen
= strlen(name
);
1354 if (!allowed
|| (allowed
& INTERPRET_BRANCH_LOCAL
)) {
1355 len
= interpret_nth_prior_checkout(name
, namelen
, buf
);
1357 return len
; /* syntax Ok, not enough switches */
1358 } else if (len
> 0) {
1360 return len
; /* consumed all */
1362 return reinterpret(name
, namelen
, len
, buf
, allowed
);
1367 (at
= memchr(start
, '@', namelen
- (start
- name
)));
1370 if (!allowed
|| (allowed
& INTERPRET_BRANCH_HEAD
)) {
1371 len
= interpret_empty_at(name
, namelen
, at
- name
, buf
);
1373 return reinterpret(name
, namelen
, len
, buf
,
1377 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1378 upstream_mark
, branch_get_upstream
,
1383 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1384 push_mark
, branch_get_push
,
1393 void strbuf_branchname(struct strbuf
*sb
, const char *name
, unsigned allowed
)
1395 int len
= strlen(name
);
1396 int used
= interpret_branch_name(name
, len
, sb
, allowed
);
1400 strbuf_add(sb
, name
+ used
, len
- used
);
1403 int strbuf_check_branch_ref(struct strbuf
*sb
, const char *name
)
1405 if (startup_info
->have_repository
)
1406 strbuf_branchname(sb
, name
, INTERPRET_BRANCH_LOCAL
);
1408 strbuf_addstr(sb
, name
);
1411 * This splice must be done even if we end up rejecting the
1412 * name; builtin/branch.c::copy_or_rename_branch() still wants
1413 * to see what the name expanded to so that "branch -m" can be
1414 * used as a tool to correct earlier mistakes.
1416 strbuf_splice(sb
, 0, 0, "refs/heads/", 11);
1419 !strcmp(sb
->buf
, "refs/heads/HEAD"))
1422 return check_refname_format(sb
->buf
, 0);
1426 * This is like "get_oid_basic()", except it allows "object ID expressions",
1427 * notably "xyz^" for "parent of xyz"
1429 int get_oid(const char *name
, struct object_id
*oid
)
1431 struct object_context unused
;
1432 return get_oid_with_context(name
, 0, oid
, &unused
);
1437 * Many callers know that the user meant to name a commit-ish by
1438 * syntactical positions where the object name appears. Calling this
1439 * function allows the machinery to disambiguate shorter-than-unique
1440 * abbreviated object names between commit-ish and others.
1442 * Note that this does NOT error out when the named object is not a
1443 * commit-ish. It is merely to give a hint to the disambiguation
1446 int get_oid_committish(const char *name
, struct object_id
*oid
)
1448 struct object_context unused
;
1449 return get_oid_with_context(name
, GET_OID_COMMITTISH
,
1453 int get_oid_treeish(const char *name
, struct object_id
*oid
)
1455 struct object_context unused
;
1456 return get_oid_with_context(name
, GET_OID_TREEISH
,
1460 int get_oid_commit(const char *name
, struct object_id
*oid
)
1462 struct object_context unused
;
1463 return get_oid_with_context(name
, GET_OID_COMMIT
,
1467 int get_oid_tree(const char *name
, struct object_id
*oid
)
1469 struct object_context unused
;
1470 return get_oid_with_context(name
, GET_OID_TREE
,
1474 int get_oid_blob(const char *name
, struct object_id
*oid
)
1476 struct object_context unused
;
1477 return get_oid_with_context(name
, GET_OID_BLOB
,
1481 /* Must be called only when object_name:filename doesn't exist. */
1482 static void diagnose_invalid_oid_path(const char *prefix
,
1483 const char *filename
,
1484 const struct object_id
*tree_oid
,
1485 const char *object_name
,
1486 int object_name_len
)
1488 struct object_id oid
;
1494 if (file_exists(filename
))
1495 die("Path '%s' exists on disk, but not in '%.*s'.",
1496 filename
, object_name_len
, object_name
);
1497 if (is_missing_file_error(errno
)) {
1498 char *fullname
= xstrfmt("%s%s", prefix
, filename
);
1500 if (!get_tree_entry(tree_oid
, fullname
, &oid
, &mode
)) {
1501 die("Path '%s' exists, but not '%s'.\n"
1502 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1505 object_name_len
, object_name
,
1507 object_name_len
, object_name
,
1510 die("Path '%s' does not exist in '%.*s'",
1511 filename
, object_name_len
, object_name
);
1515 /* Must be called only when :stage:filename doesn't exist. */
1516 static void diagnose_invalid_index_path(int stage
,
1518 const char *filename
)
1520 const struct cache_entry
*ce
;
1522 unsigned namelen
= strlen(filename
);
1523 struct strbuf fullname
= STRBUF_INIT
;
1528 /* Wrong stage number? */
1529 pos
= cache_name_pos(filename
, namelen
);
1532 if (pos
< active_nr
) {
1533 ce
= active_cache
[pos
];
1534 if (ce_namelen(ce
) == namelen
&&
1535 !memcmp(ce
->name
, filename
, namelen
))
1536 die("Path '%s' is in the index, but not at stage %d.\n"
1537 "Did you mean ':%d:%s'?",
1539 ce_stage(ce
), filename
);
1542 /* Confusion between relative and absolute filenames? */
1543 strbuf_addstr(&fullname
, prefix
);
1544 strbuf_addstr(&fullname
, filename
);
1545 pos
= cache_name_pos(fullname
.buf
, fullname
.len
);
1548 if (pos
< active_nr
) {
1549 ce
= active_cache
[pos
];
1550 if (ce_namelen(ce
) == fullname
.len
&&
1551 !memcmp(ce
->name
, fullname
.buf
, fullname
.len
))
1552 die("Path '%s' is in the index, but not '%s'.\n"
1553 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1554 fullname
.buf
, filename
,
1555 ce_stage(ce
), fullname
.buf
,
1556 ce_stage(ce
), filename
);
1559 if (file_exists(filename
))
1560 die("Path '%s' exists on disk, but not in the index.", filename
);
1561 if (is_missing_file_error(errno
))
1562 die("Path '%s' does not exist (neither on disk nor in the index).",
1565 strbuf_release(&fullname
);
1569 static char *resolve_relative_path(const char *rel
)
1571 if (!starts_with(rel
, "./") && !starts_with(rel
, "../"))
1574 if (!is_inside_work_tree())
1575 die("relative path syntax can't be used outside working tree.");
1577 /* die() inside prefix_path() if resolved path is outside worktree */
1578 return prefix_path(startup_info
->prefix
,
1579 startup_info
->prefix
? strlen(startup_info
->prefix
) : 0,
1583 static int get_oid_with_context_1(const char *name
,
1586 struct object_id
*oid
,
1587 struct object_context
*oc
)
1589 int ret
, bracket_depth
;
1590 int namelen
= strlen(name
);
1592 int only_to_die
= flags
& GET_OID_ONLY_TO_DIE
;
1595 flags
|= GET_OID_QUIETLY
;
1597 memset(oc
, 0, sizeof(*oc
));
1598 oc
->mode
= S_IFINVALID
;
1599 strbuf_init(&oc
->symlink_path
, 0);
1600 ret
= get_oid_1(name
, namelen
, oid
, flags
);
1604 * sha1:path --> object name of path in ent sha1
1605 * :path -> object name of absolute path in index
1606 * :./path -> object name of path relative to cwd in index
1607 * :[0-3]:path -> object name of path in index at stage
1608 * :/foo -> recent commit matching foo
1610 if (name
[0] == ':') {
1612 const struct cache_entry
*ce
;
1613 char *new_path
= NULL
;
1615 if (!only_to_die
&& namelen
> 2 && name
[1] == '/') {
1616 struct commit_list
*list
= NULL
;
1618 for_each_ref(handle_one_ref
, &list
);
1619 commit_list_sort_by_date(&list
);
1620 return get_oid_oneline(name
+ 2, oid
, list
);
1624 name
[1] < '0' || '3' < name
[1])
1627 stage
= name
[1] - '0';
1630 new_path
= resolve_relative_path(cp
);
1632 namelen
= namelen
- (cp
- name
);
1635 namelen
= strlen(cp
);
1638 if (flags
& GET_OID_RECORD_PATH
)
1639 oc
->path
= xstrdup(cp
);
1643 pos
= cache_name_pos(cp
, namelen
);
1646 while (pos
< active_nr
) {
1647 ce
= active_cache
[pos
];
1648 if (ce_namelen(ce
) != namelen
||
1649 memcmp(ce
->name
, cp
, namelen
))
1651 if (ce_stage(ce
) == stage
) {
1652 oidcpy(oid
, &ce
->oid
);
1653 oc
->mode
= ce
->ce_mode
;
1659 if (only_to_die
&& name
[1] && name
[1] != '/')
1660 diagnose_invalid_index_path(stage
, prefix
, cp
);
1664 for (cp
= name
, bracket_depth
= 0; *cp
; cp
++) {
1667 else if (bracket_depth
&& *cp
== '}')
1669 else if (!bracket_depth
&& *cp
== ':')
1673 struct object_id tree_oid
;
1674 int len
= cp
- name
;
1675 unsigned sub_flags
= flags
;
1677 sub_flags
&= ~GET_OID_DISAMBIGUATORS
;
1678 sub_flags
|= GET_OID_TREEISH
;
1680 if (!get_oid_1(name
, len
, &tree_oid
, sub_flags
)) {
1681 const char *filename
= cp
+1;
1682 char *new_filename
= NULL
;
1684 new_filename
= resolve_relative_path(filename
);
1686 filename
= new_filename
;
1687 if (flags
& GET_OID_FOLLOW_SYMLINKS
) {
1688 ret
= get_tree_entry_follow_symlinks(&tree_oid
,
1689 filename
, oid
, &oc
->symlink_path
,
1692 ret
= get_tree_entry(&tree_oid
, filename
, oid
,
1694 if (ret
&& only_to_die
) {
1695 diagnose_invalid_oid_path(prefix
,
1701 if (flags
& GET_OID_RECORD_PATH
)
1702 oc
->path
= xstrdup(filename
);
1708 die("Invalid object name '%.*s'.", len
, name
);
1715 * Call this function when you know "name" given by the end user must
1716 * name an object but it doesn't; the function _may_ die with a better
1717 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1718 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1719 * you have a chance to diagnose the error further.
1721 void maybe_die_on_misspelt_object_name(const char *name
, const char *prefix
)
1723 struct object_context oc
;
1724 struct object_id oid
;
1725 get_oid_with_context_1(name
, GET_OID_ONLY_TO_DIE
, prefix
, &oid
, &oc
);
1728 int get_oid_with_context(const char *str
, unsigned flags
, struct object_id
*oid
, struct object_context
*oc
)
1730 if (flags
& GET_OID_FOLLOW_SYMLINKS
&& flags
& GET_OID_ONLY_TO_DIE
)
1731 die("BUG: incompatible flags for get_sha1_with_context");
1732 return get_oid_with_context_1(str
, flags
, NULL
, oid
, oc
);