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
, last
, i
, first
= 0;
156 const struct object_id
*current
= NULL
;
158 if (open_pack_index(p
) || !p
->num_objects
)
161 num
= p
->num_objects
;
163 while (first
< last
) {
164 uint32_t mid
= first
+ (last
- first
) / 2;
165 const unsigned char *current
;
168 current
= nth_packed_object_sha1(p
, mid
);
169 cmp
= hashcmp(ds
->bin_pfx
.hash
, current
);
182 * At this point, "first" is the location of the lowest object
183 * with an object name that could match "bin_pfx". See if we have
184 * 0, 1 or more objects that actually match(es).
186 for (i
= first
; i
< num
&& !ds
->ambiguous
; i
++) {
187 struct object_id oid
;
188 current
= nth_packed_object_oid(&oid
, p
, i
);
189 if (!match_sha(ds
->len
, ds
->bin_pfx
.hash
, current
->hash
))
191 update_candidates(ds
, current
);
195 static void find_short_packed_object(struct disambiguate_state
*ds
)
197 struct packed_git
*p
;
199 prepare_packed_git();
200 for (p
= get_packed_git(the_repository
); p
&& !ds
->ambiguous
;
202 unique_in_pack(p
, ds
);
205 #define SHORT_NAME_NOT_FOUND (-1)
206 #define SHORT_NAME_AMBIGUOUS (-2)
208 static int finish_object_disambiguation(struct disambiguate_state
*ds
,
209 struct object_id
*oid
)
212 return SHORT_NAME_AMBIGUOUS
;
214 if (!ds
->candidate_exists
)
215 return SHORT_NAME_NOT_FOUND
;
217 if (!ds
->candidate_checked
)
219 * If this is the only candidate, there is no point
220 * calling the disambiguation hint callback.
222 * On the other hand, if the current candidate
223 * replaced an earlier candidate that did _not_ pass
224 * the disambiguation hint callback, then we do have
225 * more than one objects that match the short name
226 * given, so we should make sure this one matches;
227 * otherwise, if we discovered this one and the one
228 * that we previously discarded in the reverse order,
229 * we would end up showing different results in the
232 ds
->candidate_ok
= (!ds
->disambiguate_fn_used
||
233 ds
->fn(&ds
->candidate
, ds
->cb_data
));
235 if (!ds
->candidate_ok
)
236 return SHORT_NAME_AMBIGUOUS
;
238 oidcpy(oid
, &ds
->candidate
);
242 static int disambiguate_commit_only(const struct object_id
*oid
, void *cb_data_unused
)
244 int kind
= sha1_object_info(oid
->hash
, NULL
);
245 return kind
== OBJ_COMMIT
;
248 static int disambiguate_committish_only(const struct object_id
*oid
, void *cb_data_unused
)
253 kind
= sha1_object_info(oid
->hash
, NULL
);
254 if (kind
== OBJ_COMMIT
)
259 /* We need to do this the hard way... */
260 obj
= deref_tag(parse_object(oid
), NULL
, 0);
261 if (obj
&& obj
->type
== OBJ_COMMIT
)
266 static int disambiguate_tree_only(const struct object_id
*oid
, void *cb_data_unused
)
268 int kind
= sha1_object_info(oid
->hash
, NULL
);
269 return kind
== OBJ_TREE
;
272 static int disambiguate_treeish_only(const struct object_id
*oid
, void *cb_data_unused
)
277 kind
= sha1_object_info(oid
->hash
, NULL
);
278 if (kind
== OBJ_TREE
|| kind
== OBJ_COMMIT
)
283 /* We need to do this the hard way... */
284 obj
= deref_tag(parse_object(oid
), NULL
, 0);
285 if (obj
&& (obj
->type
== OBJ_TREE
|| obj
->type
== OBJ_COMMIT
))
290 static int disambiguate_blob_only(const struct object_id
*oid
, void *cb_data_unused
)
292 int kind
= sha1_object_info(oid
->hash
, NULL
);
293 return kind
== OBJ_BLOB
;
296 static disambiguate_hint_fn default_disambiguate_hint
;
298 int set_disambiguate_hint_config(const char *var
, const char *value
)
300 static const struct {
302 disambiguate_hint_fn fn
;
305 { "commit", disambiguate_commit_only
},
306 { "committish", disambiguate_committish_only
},
307 { "tree", disambiguate_tree_only
},
308 { "treeish", disambiguate_treeish_only
},
309 { "blob", disambiguate_blob_only
}
314 return config_error_nonbool(var
);
316 for (i
= 0; i
< ARRAY_SIZE(hints
); i
++) {
317 if (!strcasecmp(value
, hints
[i
].name
)) {
318 default_disambiguate_hint
= hints
[i
].fn
;
323 return error("unknown hint type for '%s': %s", var
, value
);
326 static int init_object_disambiguation(const char *name
, int len
,
327 struct disambiguate_state
*ds
)
331 if (len
< MINIMUM_ABBREV
|| len
> GIT_SHA1_HEXSZ
)
334 memset(ds
, 0, sizeof(*ds
));
336 for (i
= 0; i
< len
;i
++) {
337 unsigned char c
= name
[i
];
339 if (c
>= '0' && c
<= '9')
341 else if (c
>= 'a' && c
<= 'f')
343 else if (c
>= 'A' && c
<='F') {
352 ds
->bin_pfx
.hash
[i
>> 1] |= val
;
356 ds
->hex_pfx
[len
] = '\0';
361 static int show_ambiguous_object(const struct object_id
*oid
, void *data
)
363 const struct disambiguate_state
*ds
= data
;
364 struct strbuf desc
= STRBUF_INIT
;
368 if (ds
->fn
&& !ds
->fn(oid
, ds
->cb_data
))
371 type
= sha1_object_info(oid
->hash
, NULL
);
372 if (type
== OBJ_COMMIT
) {
373 struct commit
*commit
= lookup_commit(oid
);
375 struct pretty_print_context pp
= {0};
376 pp
.date_mode
.type
= DATE_SHORT
;
377 format_commit_message(commit
, " %ad - %s", &desc
, &pp
);
379 } else if (type
== OBJ_TAG
) {
380 struct tag
*tag
= lookup_tag(oid
);
381 if (!parse_tag(tag
) && tag
->tag
)
382 strbuf_addf(&desc
, " %s", tag
->tag
);
386 find_unique_abbrev(oid
->hash
, DEFAULT_ABBREV
),
387 typename(type
) ? typename(type
) : "unknown type",
390 strbuf_release(&desc
);
394 static int get_short_oid(const char *name
, int len
, struct object_id
*oid
,
398 struct disambiguate_state ds
;
399 int quietly
= !!(flags
& GET_OID_QUIETLY
);
401 if (init_object_disambiguation(name
, len
, &ds
) < 0)
404 if (HAS_MULTI_BITS(flags
& GET_OID_DISAMBIGUATORS
))
405 die("BUG: multiple get_short_oid disambiguator flags");
407 if (flags
& GET_OID_COMMIT
)
408 ds
.fn
= disambiguate_commit_only
;
409 else if (flags
& GET_OID_COMMITTISH
)
410 ds
.fn
= disambiguate_committish_only
;
411 else if (flags
& GET_OID_TREE
)
412 ds
.fn
= disambiguate_tree_only
;
413 else if (flags
& GET_OID_TREEISH
)
414 ds
.fn
= disambiguate_treeish_only
;
415 else if (flags
& GET_OID_BLOB
)
416 ds
.fn
= disambiguate_blob_only
;
418 ds
.fn
= default_disambiguate_hint
;
420 find_short_object_filename(&ds
);
421 find_short_packed_object(&ds
);
422 status
= finish_object_disambiguation(&ds
, oid
);
424 if (!quietly
&& (status
== SHORT_NAME_AMBIGUOUS
)) {
425 error(_("short SHA1 %s is ambiguous"), ds
.hex_pfx
);
428 * We may still have ambiguity if we simply saw a series of
429 * candidates that did not satisfy our hint function. In
430 * that case, we still want to show them, so disable the hint
436 advise(_("The candidates are:"));
437 for_each_abbrev(ds
.hex_pfx
, show_ambiguous_object
, &ds
);
443 static int collect_ambiguous(const struct object_id
*oid
, void *data
)
445 oid_array_append(data
, oid
);
449 int for_each_abbrev(const char *prefix
, each_abbrev_fn fn
, void *cb_data
)
451 struct oid_array collect
= OID_ARRAY_INIT
;
452 struct disambiguate_state ds
;
455 if (init_object_disambiguation(prefix
, strlen(prefix
), &ds
) < 0)
458 ds
.always_call_fn
= 1;
459 ds
.fn
= collect_ambiguous
;
460 ds
.cb_data
= &collect
;
461 find_short_object_filename(&ds
);
462 find_short_packed_object(&ds
);
464 ret
= oid_array_for_each_unique(&collect
, fn
, cb_data
);
465 oid_array_clear(&collect
);
470 * Return the slot of the most-significant bit set in "val". There are various
471 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
472 * probably not a big deal here.
474 static unsigned msb(unsigned long val
)
482 struct min_abbrev_data
{
483 unsigned int init_len
;
484 unsigned int cur_len
;
486 const unsigned char *hash
;
489 static inline char get_hex_char_from_oid(const struct object_id
*oid
,
492 static const char hex
[] = "0123456789abcdef";
495 return hex
[oid
->hash
[pos
>> 1] >> 4];
497 return hex
[oid
->hash
[pos
>> 1] & 0xf];
500 static int extend_abbrev_len(const struct object_id
*oid
, void *cb_data
)
502 struct min_abbrev_data
*mad
= cb_data
;
504 unsigned int i
= mad
->init_len
;
505 while (mad
->hex
[i
] && mad
->hex
[i
] == get_hex_char_from_oid(oid
, i
))
508 if (i
< GIT_MAX_RAWSZ
&& i
>= mad
->cur_len
)
509 mad
->cur_len
= i
+ 1;
514 static void find_abbrev_len_for_pack(struct packed_git
*p
,
515 struct min_abbrev_data
*mad
)
518 uint32_t num
, last
, first
= 0;
519 struct object_id oid
;
521 if (open_pack_index(p
) || !p
->num_objects
)
524 num
= p
->num_objects
;
526 while (first
< last
) {
527 uint32_t mid
= first
+ (last
- first
) / 2;
528 const unsigned char *current
;
531 current
= nth_packed_object_sha1(p
, mid
);
532 cmp
= hashcmp(mad
->hash
, current
);
546 * first is now the position in the packfile where we would insert
547 * mad->hash if it does not exist (or the position of mad->hash if
548 * it does exist). Hence, we consider a maximum of three objects
549 * nearby for the abbreviation length.
553 nth_packed_object_oid(&oid
, p
, first
);
554 extend_abbrev_len(&oid
, mad
);
555 } else if (first
< num
- 1) {
556 nth_packed_object_oid(&oid
, p
, first
+ 1);
557 extend_abbrev_len(&oid
, mad
);
560 nth_packed_object_oid(&oid
, p
, first
- 1);
561 extend_abbrev_len(&oid
, mad
);
563 mad
->init_len
= mad
->cur_len
;
566 static void find_abbrev_len_packed(struct min_abbrev_data
*mad
)
568 struct packed_git
*p
;
570 prepare_packed_git();
571 for (p
= get_packed_git(the_repository
); p
; p
= p
->next
)
572 find_abbrev_len_for_pack(p
, mad
);
575 int find_unique_abbrev_r(char *hex
, const unsigned char *sha1
, int len
)
577 struct disambiguate_state ds
;
578 struct min_abbrev_data mad
;
579 struct object_id oid_ret
;
581 unsigned long count
= approximate_object_count();
583 * Add one because the MSB only tells us the highest bit set,
584 * not including the value of all the _other_ bits (so "15"
585 * is only one off of 2^4, but the MSB is the 3rd bit.
587 len
= msb(count
) + 1;
589 * We now know we have on the order of 2^len objects, which
590 * expects a collision at 2^(len/2). But we also care about hex
591 * chars, not bits, and there are 4 bits per hex. So all
592 * together we need to divide by 2 and round up.
594 len
= DIV_ROUND_UP(len
, 2);
596 * For very small repos, we stick with our regular fallback.
598 if (len
< FALLBACK_DEFAULT_ABBREV
)
599 len
= FALLBACK_DEFAULT_ABBREV
;
602 sha1_to_hex_r(hex
, sha1
);
603 if (len
== GIT_SHA1_HEXSZ
|| !len
)
604 return GIT_SHA1_HEXSZ
;
611 find_abbrev_len_packed(&mad
);
613 if (init_object_disambiguation(hex
, mad
.cur_len
, &ds
) < 0)
616 ds
.fn
= extend_abbrev_len
;
617 ds
.always_call_fn
= 1;
618 ds
.cb_data
= (void *)&mad
;
620 find_short_object_filename(&ds
);
621 (void)finish_object_disambiguation(&ds
, &oid_ret
);
623 hex
[mad
.cur_len
] = 0;
627 const char *find_unique_abbrev(const unsigned char *sha1
, int len
)
630 static char hexbuffer
[4][GIT_MAX_HEXSZ
+ 1];
631 char *hex
= hexbuffer
[bufno
];
632 bufno
= (bufno
+ 1) % ARRAY_SIZE(hexbuffer
);
633 find_unique_abbrev_r(hex
, sha1
, len
);
637 static int ambiguous_path(const char *path
, int len
)
642 for (cnt
= 0; cnt
< len
; cnt
++) {
662 static inline int at_mark(const char *string
, int len
,
663 const char **suffix
, int nr
)
667 for (i
= 0; i
< nr
; i
++) {
668 int suffix_len
= strlen(suffix
[i
]);
669 if (suffix_len
<= len
670 && !strncasecmp(string
, suffix
[i
], suffix_len
))
676 static inline int upstream_mark(const char *string
, int len
)
678 const char *suffix
[] = { "@{upstream}", "@{u}" };
679 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
682 static inline int push_mark(const char *string
, int len
)
684 const char *suffix
[] = { "@{push}" };
685 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
688 static int get_oid_1(const char *name
, int len
, struct object_id
*oid
, unsigned lookup_flags
);
689 static int interpret_nth_prior_checkout(const char *name
, int namelen
, struct strbuf
*buf
);
691 static int get_oid_basic(const char *str
, int len
, struct object_id
*oid
,
694 static const char *warn_msg
= "refname '%.*s' is ambiguous.";
695 static const char *object_name_msg
= N_(
696 "Git normally never creates a ref that ends with 40 hex characters\n"
697 "because it will be ignored when you just specify 40-hex. These refs\n"
698 "may be created by mistake. For example,\n"
700 " git checkout -b $br $(git rev-parse ...)\n"
702 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
703 "examine these refs and maybe delete them. Turn this message off by\n"
704 "running \"git config advice.objectNameWarning false\"");
705 struct object_id tmp_oid
;
706 char *real_ref
= NULL
;
708 int at
, reflog_len
, nth_prior
= 0;
710 if (len
== GIT_SHA1_HEXSZ
&& !get_oid_hex(str
, oid
)) {
711 if (warn_ambiguous_refs
&& warn_on_object_refname_ambiguity
) {
712 refs_found
= dwim_ref(str
, len
, &tmp_oid
, &real_ref
);
713 if (refs_found
> 0) {
714 warning(warn_msg
, len
, str
);
715 if (advice_object_name_warning
)
716 fprintf(stderr
, "%s\n", _(object_name_msg
));
723 /* basic@{time or number or -number} format to query ref-log */
725 if (len
&& str
[len
-1] == '}') {
726 for (at
= len
-4; at
>= 0; at
--) {
727 if (str
[at
] == '@' && str
[at
+1] == '{') {
728 if (str
[at
+2] == '-') {
730 /* @{-N} not at start */
735 if (!upstream_mark(str
+ at
, len
- at
) &&
736 !push_mark(str
+ at
, len
- at
)) {
737 reflog_len
= (len
-1) - (at
+2);
745 /* Accept only unambiguous ref paths. */
746 if (len
&& ambiguous_path(str
, len
))
750 struct strbuf buf
= STRBUF_INIT
;
753 if (interpret_nth_prior_checkout(str
, len
, &buf
) > 0) {
754 detached
= (buf
.len
== GIT_SHA1_HEXSZ
&& !get_oid_hex(buf
.buf
, oid
));
755 strbuf_release(&buf
);
761 if (!len
&& reflog_len
)
762 /* allow "@{...}" to mean the current branch reflog */
763 refs_found
= dwim_ref("HEAD", 4, oid
, &real_ref
);
765 refs_found
= dwim_log(str
, len
, oid
, &real_ref
);
767 refs_found
= dwim_ref(str
, len
, oid
, &real_ref
);
772 if (warn_ambiguous_refs
&& !(flags
& GET_OID_QUIETLY
) &&
774 !get_short_oid(str
, len
, &tmp_oid
, GET_OID_QUIETLY
)))
775 warning(warn_msg
, len
, str
);
783 /* Is it asking for N-th entry, or approxidate? */
784 for (i
= nth
= 0; 0 <= nth
&& i
< reflog_len
; i
++) {
785 char ch
= str
[at
+2+i
];
786 if ('0' <= ch
&& ch
<= '9')
787 nth
= nth
* 10 + ch
- '0';
791 if (100000000 <= nth
) {
798 char *tmp
= xstrndup(str
+ at
+ 2, reflog_len
);
799 at_time
= approxidate_careful(tmp
, &errors
);
806 if (read_ref_at(real_ref
, flags
, at_time
, nth
, oid
, NULL
,
807 &co_time
, &co_tz
, &co_cnt
)) {
809 if (starts_with(real_ref
, "refs/heads/")) {
811 len
= strlen(real_ref
+ 11);
819 if (!(flags
& GET_OID_QUIETLY
)) {
820 warning("Log for '%.*s' only goes "
821 "back to %s.", len
, str
,
822 show_date(co_time
, co_tz
, DATE_MODE(RFC2822
)));
825 if (flags
& GET_OID_QUIETLY
) {
828 die("Log for '%.*s' only has %d entries.",
838 static int get_parent(const char *name
, int len
,
839 struct object_id
*result
, int idx
)
841 struct object_id oid
;
842 int ret
= get_oid_1(name
, len
, &oid
, GET_OID_COMMITTISH
);
843 struct commit
*commit
;
844 struct commit_list
*p
;
848 commit
= lookup_commit_reference(&oid
);
849 if (parse_commit(commit
))
852 oidcpy(result
, &commit
->object
.oid
);
858 oidcpy(result
, &p
->item
->object
.oid
);
866 static int get_nth_ancestor(const char *name
, int len
,
867 struct object_id
*result
, int generation
)
869 struct object_id oid
;
870 struct commit
*commit
;
873 ret
= get_oid_1(name
, len
, &oid
, GET_OID_COMMITTISH
);
876 commit
= lookup_commit_reference(&oid
);
880 while (generation
--) {
881 if (parse_commit(commit
) || !commit
->parents
)
883 commit
= commit
->parents
->item
;
885 oidcpy(result
, &commit
->object
.oid
);
889 struct object
*peel_to_type(const char *name
, int namelen
,
890 struct object
*o
, enum object_type expected_type
)
892 if (name
&& !namelen
)
893 namelen
= strlen(name
);
895 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
897 if (expected_type
== OBJ_ANY
|| o
->type
== expected_type
)
899 if (o
->type
== OBJ_TAG
)
900 o
= ((struct tag
*) o
)->tagged
;
901 else if (o
->type
== OBJ_COMMIT
)
902 o
= &(((struct commit
*) o
)->tree
->object
);
905 error("%.*s: expected %s type, but the object "
906 "dereferences to %s type",
907 namelen
, name
, typename(expected_type
),
914 static int peel_onion(const char *name
, int len
, struct object_id
*oid
,
915 unsigned lookup_flags
)
917 struct object_id outer
;
919 unsigned int expected_type
= 0;
923 * "ref^{type}" dereferences ref repeatedly until you cannot
924 * dereference anymore, or you get an object of given type,
925 * whichever comes first. "ref^{}" means just dereference
926 * tags until you get a non-tag. "ref^0" is a shorthand for
927 * "ref^{commit}". "commit^{tree}" could be used to find the
928 * top-level tree of the given commit.
930 if (len
< 4 || name
[len
-1] != '}')
933 for (sp
= name
+ len
- 1; name
<= sp
; sp
--) {
935 if (ch
== '{' && name
< sp
&& sp
[-1] == '^')
941 sp
++; /* beginning of type name, or closing brace for empty */
942 if (starts_with(sp
, "commit}"))
943 expected_type
= OBJ_COMMIT
;
944 else if (starts_with(sp
, "tag}"))
945 expected_type
= OBJ_TAG
;
946 else if (starts_with(sp
, "tree}"))
947 expected_type
= OBJ_TREE
;
948 else if (starts_with(sp
, "blob}"))
949 expected_type
= OBJ_BLOB
;
950 else if (starts_with(sp
, "object}"))
951 expected_type
= OBJ_ANY
;
952 else if (sp
[0] == '}')
953 expected_type
= OBJ_NONE
;
954 else if (sp
[0] == '/')
955 expected_type
= OBJ_COMMIT
;
959 lookup_flags
&= ~GET_OID_DISAMBIGUATORS
;
960 if (expected_type
== OBJ_COMMIT
)
961 lookup_flags
|= GET_OID_COMMITTISH
;
962 else if (expected_type
== OBJ_TREE
)
963 lookup_flags
|= GET_OID_TREEISH
;
965 if (get_oid_1(name
, sp
- name
- 2, &outer
, lookup_flags
))
968 o
= parse_object(&outer
);
971 if (!expected_type
) {
972 o
= deref_tag(o
, name
, sp
- name
- 2);
973 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
975 oidcpy(oid
, &o
->oid
);
980 * At this point, the syntax look correct, so
981 * if we do not get the needed object, we should
984 o
= peel_to_type(name
, len
, o
, expected_type
);
988 oidcpy(oid
, &o
->oid
);
990 /* "$commit^{/foo}" */
993 struct commit_list
*list
= NULL
;
996 * $commit^{/}. Some regex implementation may reject.
997 * We don't need regex anyway. '' pattern always matches.
1002 prefix
= xstrndup(sp
+ 1, name
+ len
- 1 - (sp
+ 1));
1003 commit_list_insert((struct commit
*)o
, &list
);
1004 ret
= get_oid_oneline(prefix
, oid
, list
);
1011 static int get_describe_name(const char *name
, int len
, struct object_id
*oid
)
1014 unsigned flags
= GET_OID_QUIETLY
| GET_OID_COMMIT
;
1016 for (cp
= name
+ len
- 1; name
+ 2 <= cp
; cp
--) {
1018 if (!isxdigit(ch
)) {
1019 /* We must be looking at g in "SOMETHING-g"
1020 * for it to be describe output.
1022 if (ch
== 'g' && cp
[-1] == '-') {
1025 return get_short_oid(cp
, len
, oid
, flags
);
1032 static int get_oid_1(const char *name
, int len
, struct object_id
*oid
, unsigned lookup_flags
)
1034 int ret
, has_suffix
;
1038 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1041 for (cp
= name
+ len
- 1; name
<= cp
; cp
--) {
1043 if ('0' <= ch
&& ch
<= '9')
1045 if (ch
== '~' || ch
== '^')
1052 int len1
= cp
- name
;
1054 while (cp
< name
+ len
)
1055 num
= num
* 10 + *cp
++ - '0';
1056 if (!num
&& len1
== len
- 1)
1058 if (has_suffix
== '^')
1059 return get_parent(name
, len1
, oid
, num
);
1060 /* else if (has_suffix == '~') -- goes without saying */
1061 return get_nth_ancestor(name
, len1
, oid
, num
);
1064 ret
= peel_onion(name
, len
, oid
, lookup_flags
);
1068 ret
= get_oid_basic(name
, len
, oid
, lookup_flags
);
1072 /* It could be describe output that is "SOMETHING-gXXXX" */
1073 ret
= get_describe_name(name
, len
, oid
);
1077 return get_short_oid(name
, len
, oid
, lookup_flags
);
1081 * This interprets names like ':/Initial revision of "git"' by searching
1082 * through history and returning the first commit whose message starts
1083 * the given regular expression.
1085 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1087 * For a literal '!' character at the beginning of a pattern, you have to repeat
1088 * that, like: ':/!!foo'
1090 * For future extension, all other sequences beginning with ':/!' are reserved.
1093 /* Remember to update object flag allocation in object.h */
1094 #define ONELINE_SEEN (1u<<20)
1096 static int handle_one_ref(const char *path
, const struct object_id
*oid
,
1097 int flag
, void *cb_data
)
1099 struct commit_list
**list
= cb_data
;
1100 struct object
*object
= parse_object(oid
);
1103 if (object
->type
== OBJ_TAG
) {
1104 object
= deref_tag(object
, path
, strlen(path
));
1108 if (object
->type
!= OBJ_COMMIT
)
1110 commit_list_insert((struct commit
*)object
, list
);
1114 static int get_oid_oneline(const char *prefix
, struct object_id
*oid
,
1115 struct commit_list
*list
)
1117 struct commit_list
*backup
= NULL
, *l
;
1122 if (prefix
[0] == '!') {
1125 if (prefix
[0] == '-') {
1128 } else if (prefix
[0] != '!') {
1133 if (regcomp(®ex
, prefix
, REG_EXTENDED
))
1136 for (l
= list
; l
; l
= l
->next
) {
1137 l
->item
->object
.flags
|= ONELINE_SEEN
;
1138 commit_list_insert(l
->item
, &backup
);
1141 const char *p
, *buf
;
1142 struct commit
*commit
;
1145 commit
= pop_most_recent_commit(&list
, ONELINE_SEEN
);
1146 if (!parse_object(&commit
->object
.oid
))
1148 buf
= get_commit_buffer(commit
, NULL
);
1149 p
= strstr(buf
, "\n\n");
1150 matches
= negative
^ (p
&& !regexec(®ex
, p
+ 2, 0, NULL
, 0));
1151 unuse_commit_buffer(commit
, buf
);
1154 oidcpy(oid
, &commit
->object
.oid
);
1160 free_commit_list(list
);
1161 for (l
= backup
; l
; l
= l
->next
)
1162 clear_commit_marks(l
->item
, ONELINE_SEEN
);
1163 free_commit_list(backup
);
1164 return found
? 0 : -1;
1167 struct grab_nth_branch_switch_cbdata
{
1172 static int grab_nth_branch_switch(struct object_id
*ooid
, struct object_id
*noid
,
1173 const char *email
, timestamp_t timestamp
, int tz
,
1174 const char *message
, void *cb_data
)
1176 struct grab_nth_branch_switch_cbdata
*cb
= cb_data
;
1177 const char *match
= NULL
, *target
= NULL
;
1180 if (skip_prefix(message
, "checkout: moving from ", &match
))
1181 target
= strstr(match
, " to ");
1183 if (!match
|| !target
)
1185 if (--(cb
->remaining
) == 0) {
1186 len
= target
- match
;
1187 strbuf_reset(&cb
->buf
);
1188 strbuf_add(&cb
->buf
, match
, len
);
1189 return 1; /* we are done */
1195 * Parse @{-N} syntax, return the number of characters parsed
1196 * if successful; otherwise signal an error with negative value.
1198 static int interpret_nth_prior_checkout(const char *name
, int namelen
,
1203 struct grab_nth_branch_switch_cbdata cb
;
1209 if (name
[0] != '@' || name
[1] != '{' || name
[2] != '-')
1211 brace
= memchr(name
, '}', namelen
);
1214 nth
= strtol(name
+ 3, &num_end
, 10);
1215 if (num_end
!= brace
)
1220 strbuf_init(&cb
.buf
, 20);
1223 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch
, &cb
)) {
1225 strbuf_addbuf(buf
, &cb
.buf
);
1226 retval
= brace
- name
+ 1;
1229 strbuf_release(&cb
.buf
);
1233 int get_oid_mb(const char *name
, struct object_id
*oid
)
1235 struct commit
*one
, *two
;
1236 struct commit_list
*mbs
;
1237 struct object_id oid_tmp
;
1241 dots
= strstr(name
, "...");
1243 return get_oid(name
, oid
);
1245 st
= get_oid("HEAD", &oid_tmp
);
1248 strbuf_init(&sb
, dots
- name
);
1249 strbuf_add(&sb
, name
, dots
- name
);
1250 st
= get_oid_committish(sb
.buf
, &oid_tmp
);
1251 strbuf_release(&sb
);
1255 one
= lookup_commit_reference_gently(&oid_tmp
, 0);
1259 if (get_oid_committish(dots
[3] ? (dots
+ 3) : "HEAD", &oid_tmp
))
1261 two
= lookup_commit_reference_gently(&oid_tmp
, 0);
1264 mbs
= get_merge_bases(one
, two
);
1265 if (!mbs
|| mbs
->next
)
1269 oidcpy(oid
, &mbs
->item
->object
.oid
);
1271 free_commit_list(mbs
);
1275 /* parse @something syntax, when 'something' is not {.*} */
1276 static int interpret_empty_at(const char *name
, int namelen
, int len
, struct strbuf
*buf
)
1280 if (len
|| name
[1] == '{')
1283 /* make sure it's a single @, or @@{.*}, not @foo */
1284 next
= memchr(name
+ len
+ 1, '@', namelen
- len
- 1);
1285 if (next
&& next
[1] != '{')
1288 next
= name
+ namelen
;
1289 if (next
!= name
+ 1)
1293 strbuf_add(buf
, "HEAD", 4);
1297 static int reinterpret(const char *name
, int namelen
, int len
,
1298 struct strbuf
*buf
, unsigned allowed
)
1300 /* we have extra data, which might need further processing */
1301 struct strbuf tmp
= STRBUF_INIT
;
1302 int used
= buf
->len
;
1305 strbuf_add(buf
, name
+ len
, namelen
- len
);
1306 ret
= interpret_branch_name(buf
->buf
, buf
->len
, &tmp
, allowed
);
1307 /* that data was not interpreted, remove our cruft */
1309 strbuf_setlen(buf
, used
);
1313 strbuf_addbuf(buf
, &tmp
);
1314 strbuf_release(&tmp
);
1315 /* tweak for size of {-N} versus expanded ref name */
1316 return ret
- used
+ len
;
1319 static void set_shortened_ref(struct strbuf
*buf
, const char *ref
)
1321 char *s
= shorten_unambiguous_ref(ref
, 0);
1323 strbuf_addstr(buf
, s
);
1327 static int branch_interpret_allowed(const char *refname
, unsigned allowed
)
1332 if ((allowed
& INTERPRET_BRANCH_LOCAL
) &&
1333 starts_with(refname
, "refs/heads/"))
1335 if ((allowed
& INTERPRET_BRANCH_REMOTE
) &&
1336 starts_with(refname
, "refs/remotes/"))
1342 static int interpret_branch_mark(const char *name
, int namelen
,
1343 int at
, struct strbuf
*buf
,
1344 int (*get_mark
)(const char *, int),
1345 const char *(*get_data
)(struct branch
*,
1350 struct branch
*branch
;
1351 struct strbuf err
= STRBUF_INIT
;
1354 len
= get_mark(name
+ at
, namelen
- at
);
1358 if (memchr(name
, ':', at
))
1362 char *name_str
= xmemdupz(name
, at
);
1363 branch
= branch_get(name_str
);
1366 branch
= branch_get(NULL
);
1368 value
= get_data(branch
, &err
);
1372 if (!branch_interpret_allowed(value
, allowed
))
1375 set_shortened_ref(buf
, value
);
1379 int interpret_branch_name(const char *name
, int namelen
, struct strbuf
*buf
,
1387 namelen
= strlen(name
);
1389 if (!allowed
|| (allowed
& INTERPRET_BRANCH_LOCAL
)) {
1390 len
= interpret_nth_prior_checkout(name
, namelen
, buf
);
1392 return len
; /* syntax Ok, not enough switches */
1393 } else if (len
> 0) {
1395 return len
; /* consumed all */
1397 return reinterpret(name
, namelen
, len
, buf
, allowed
);
1402 (at
= memchr(start
, '@', namelen
- (start
- name
)));
1405 if (!allowed
|| (allowed
& INTERPRET_BRANCH_HEAD
)) {
1406 len
= interpret_empty_at(name
, namelen
, at
- name
, buf
);
1408 return reinterpret(name
, namelen
, len
, buf
,
1412 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1413 upstream_mark
, branch_get_upstream
,
1418 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1419 push_mark
, branch_get_push
,
1428 void strbuf_branchname(struct strbuf
*sb
, const char *name
, unsigned allowed
)
1430 int len
= strlen(name
);
1431 int used
= interpret_branch_name(name
, len
, sb
, allowed
);
1435 strbuf_add(sb
, name
+ used
, len
- used
);
1438 int strbuf_check_branch_ref(struct strbuf
*sb
, const char *name
)
1440 if (startup_info
->have_repository
)
1441 strbuf_branchname(sb
, name
, INTERPRET_BRANCH_LOCAL
);
1443 strbuf_addstr(sb
, name
);
1446 * This splice must be done even if we end up rejecting the
1447 * name; builtin/branch.c::copy_or_rename_branch() still wants
1448 * to see what the name expanded to so that "branch -m" can be
1449 * used as a tool to correct earlier mistakes.
1451 strbuf_splice(sb
, 0, 0, "refs/heads/", 11);
1454 !strcmp(sb
->buf
, "refs/heads/HEAD"))
1457 return check_refname_format(sb
->buf
, 0);
1461 * This is like "get_oid_basic()", except it allows "object ID expressions",
1462 * notably "xyz^" for "parent of xyz"
1464 int get_oid(const char *name
, struct object_id
*oid
)
1466 struct object_context unused
;
1467 return get_oid_with_context(name
, 0, oid
, &unused
);
1472 * Many callers know that the user meant to name a commit-ish by
1473 * syntactical positions where the object name appears. Calling this
1474 * function allows the machinery to disambiguate shorter-than-unique
1475 * abbreviated object names between commit-ish and others.
1477 * Note that this does NOT error out when the named object is not a
1478 * commit-ish. It is merely to give a hint to the disambiguation
1481 int get_oid_committish(const char *name
, struct object_id
*oid
)
1483 struct object_context unused
;
1484 return get_oid_with_context(name
, GET_OID_COMMITTISH
,
1488 int get_oid_treeish(const char *name
, struct object_id
*oid
)
1490 struct object_context unused
;
1491 return get_oid_with_context(name
, GET_OID_TREEISH
,
1495 int get_oid_commit(const char *name
, struct object_id
*oid
)
1497 struct object_context unused
;
1498 return get_oid_with_context(name
, GET_OID_COMMIT
,
1502 int get_oid_tree(const char *name
, struct object_id
*oid
)
1504 struct object_context unused
;
1505 return get_oid_with_context(name
, GET_OID_TREE
,
1509 int get_oid_blob(const char *name
, struct object_id
*oid
)
1511 struct object_context unused
;
1512 return get_oid_with_context(name
, GET_OID_BLOB
,
1516 /* Must be called only when object_name:filename doesn't exist. */
1517 static void diagnose_invalid_oid_path(const char *prefix
,
1518 const char *filename
,
1519 const struct object_id
*tree_oid
,
1520 const char *object_name
,
1521 int object_name_len
)
1523 struct object_id oid
;
1529 if (file_exists(filename
))
1530 die("Path '%s' exists on disk, but not in '%.*s'.",
1531 filename
, object_name_len
, object_name
);
1532 if (is_missing_file_error(errno
)) {
1533 char *fullname
= xstrfmt("%s%s", prefix
, filename
);
1535 if (!get_tree_entry(tree_oid
->hash
, fullname
,
1537 die("Path '%s' exists, but not '%s'.\n"
1538 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1541 object_name_len
, object_name
,
1543 object_name_len
, object_name
,
1546 die("Path '%s' does not exist in '%.*s'",
1547 filename
, object_name_len
, object_name
);
1551 /* Must be called only when :stage:filename doesn't exist. */
1552 static void diagnose_invalid_index_path(int stage
,
1554 const char *filename
)
1556 const struct cache_entry
*ce
;
1558 unsigned namelen
= strlen(filename
);
1559 struct strbuf fullname
= STRBUF_INIT
;
1564 /* Wrong stage number? */
1565 pos
= cache_name_pos(filename
, namelen
);
1568 if (pos
< active_nr
) {
1569 ce
= active_cache
[pos
];
1570 if (ce_namelen(ce
) == namelen
&&
1571 !memcmp(ce
->name
, filename
, namelen
))
1572 die("Path '%s' is in the index, but not at stage %d.\n"
1573 "Did you mean ':%d:%s'?",
1575 ce_stage(ce
), filename
);
1578 /* Confusion between relative and absolute filenames? */
1579 strbuf_addstr(&fullname
, prefix
);
1580 strbuf_addstr(&fullname
, filename
);
1581 pos
= cache_name_pos(fullname
.buf
, fullname
.len
);
1584 if (pos
< active_nr
) {
1585 ce
= active_cache
[pos
];
1586 if (ce_namelen(ce
) == fullname
.len
&&
1587 !memcmp(ce
->name
, fullname
.buf
, fullname
.len
))
1588 die("Path '%s' is in the index, but not '%s'.\n"
1589 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1590 fullname
.buf
, filename
,
1591 ce_stage(ce
), fullname
.buf
,
1592 ce_stage(ce
), filename
);
1595 if (file_exists(filename
))
1596 die("Path '%s' exists on disk, but not in the index.", filename
);
1597 if (is_missing_file_error(errno
))
1598 die("Path '%s' does not exist (neither on disk nor in the index).",
1601 strbuf_release(&fullname
);
1605 static char *resolve_relative_path(const char *rel
)
1607 if (!starts_with(rel
, "./") && !starts_with(rel
, "../"))
1610 if (!is_inside_work_tree())
1611 die("relative path syntax can't be used outside working tree.");
1613 /* die() inside prefix_path() if resolved path is outside worktree */
1614 return prefix_path(startup_info
->prefix
,
1615 startup_info
->prefix
? strlen(startup_info
->prefix
) : 0,
1619 static int get_oid_with_context_1(const char *name
,
1622 struct object_id
*oid
,
1623 struct object_context
*oc
)
1625 int ret
, bracket_depth
;
1626 int namelen
= strlen(name
);
1628 int only_to_die
= flags
& GET_OID_ONLY_TO_DIE
;
1631 flags
|= GET_OID_QUIETLY
;
1633 memset(oc
, 0, sizeof(*oc
));
1634 oc
->mode
= S_IFINVALID
;
1635 strbuf_init(&oc
->symlink_path
, 0);
1636 ret
= get_oid_1(name
, namelen
, oid
, flags
);
1640 * sha1:path --> object name of path in ent sha1
1641 * :path -> object name of absolute path in index
1642 * :./path -> object name of path relative to cwd in index
1643 * :[0-3]:path -> object name of path in index at stage
1644 * :/foo -> recent commit matching foo
1646 if (name
[0] == ':') {
1648 const struct cache_entry
*ce
;
1649 char *new_path
= NULL
;
1651 if (!only_to_die
&& namelen
> 2 && name
[1] == '/') {
1652 struct commit_list
*list
= NULL
;
1654 for_each_ref(handle_one_ref
, &list
);
1655 commit_list_sort_by_date(&list
);
1656 return get_oid_oneline(name
+ 2, oid
, list
);
1660 name
[1] < '0' || '3' < name
[1])
1663 stage
= name
[1] - '0';
1666 new_path
= resolve_relative_path(cp
);
1668 namelen
= namelen
- (cp
- name
);
1671 namelen
= strlen(cp
);
1674 if (flags
& GET_OID_RECORD_PATH
)
1675 oc
->path
= xstrdup(cp
);
1679 pos
= cache_name_pos(cp
, namelen
);
1682 while (pos
< active_nr
) {
1683 ce
= active_cache
[pos
];
1684 if (ce_namelen(ce
) != namelen
||
1685 memcmp(ce
->name
, cp
, namelen
))
1687 if (ce_stage(ce
) == stage
) {
1688 oidcpy(oid
, &ce
->oid
);
1689 oc
->mode
= ce
->ce_mode
;
1695 if (only_to_die
&& name
[1] && name
[1] != '/')
1696 diagnose_invalid_index_path(stage
, prefix
, cp
);
1700 for (cp
= name
, bracket_depth
= 0; *cp
; cp
++) {
1703 else if (bracket_depth
&& *cp
== '}')
1705 else if (!bracket_depth
&& *cp
== ':')
1709 struct object_id tree_oid
;
1710 int len
= cp
- name
;
1711 unsigned sub_flags
= flags
;
1713 sub_flags
&= ~GET_OID_DISAMBIGUATORS
;
1714 sub_flags
|= GET_OID_TREEISH
;
1716 if (!get_oid_1(name
, len
, &tree_oid
, sub_flags
)) {
1717 const char *filename
= cp
+1;
1718 char *new_filename
= NULL
;
1720 new_filename
= resolve_relative_path(filename
);
1722 filename
= new_filename
;
1723 if (flags
& GET_OID_FOLLOW_SYMLINKS
) {
1724 ret
= get_tree_entry_follow_symlinks(tree_oid
.hash
,
1725 filename
, oid
->hash
, &oc
->symlink_path
,
1728 ret
= get_tree_entry(tree_oid
.hash
, filename
,
1729 oid
->hash
, &oc
->mode
);
1730 if (ret
&& only_to_die
) {
1731 diagnose_invalid_oid_path(prefix
,
1737 hashcpy(oc
->tree
, tree_oid
.hash
);
1738 if (flags
& GET_OID_RECORD_PATH
)
1739 oc
->path
= xstrdup(filename
);
1745 die("Invalid object name '%.*s'.", len
, name
);
1752 * Call this function when you know "name" given by the end user must
1753 * name an object but it doesn't; the function _may_ die with a better
1754 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1755 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1756 * you have a chance to diagnose the error further.
1758 void maybe_die_on_misspelt_object_name(const char *name
, const char *prefix
)
1760 struct object_context oc
;
1761 struct object_id oid
;
1762 get_oid_with_context_1(name
, GET_OID_ONLY_TO_DIE
, prefix
, &oid
, &oc
);
1765 int get_oid_with_context(const char *str
, unsigned flags
, struct object_id
*oid
, struct object_context
*oc
)
1767 if (flags
& GET_OID_FOLLOW_SYMLINKS
&& flags
& GET_OID_ONLY_TO_DIE
)
1768 die("BUG: incompatible flags for get_sha1_with_context");
1769 return get_oid_with_context_1(str
, flags
, NULL
, oid
, oc
);