11 #include "sha1-array.h"
14 static int get_oid_oneline(const char *, struct object_id
*, struct commit_list
*);
16 typedef int (*disambiguate_hint_fn
)(const struct object_id
*, void *);
18 struct disambiguate_state
{
19 int len
; /* length of prefix in hex chars */
20 char hex_pfx
[GIT_MAX_HEXSZ
+ 1];
21 struct object_id bin_pfx
;
23 disambiguate_hint_fn fn
;
25 struct object_id candidate
;
26 unsigned candidate_exists
:1;
27 unsigned candidate_checked
:1;
28 unsigned candidate_ok
:1;
29 unsigned disambiguate_fn_used
:1;
31 unsigned always_call_fn
:1;
34 static void update_candidates(struct disambiguate_state
*ds
, const struct object_id
*current
)
36 if (ds
->always_call_fn
) {
37 ds
->ambiguous
= ds
->fn(current
, ds
->cb_data
) ? 1 : 0;
40 if (!ds
->candidate_exists
) {
41 /* this is the first candidate */
42 oidcpy(&ds
->candidate
, current
);
43 ds
->candidate_exists
= 1;
45 } else if (!oidcmp(&ds
->candidate
, current
)) {
46 /* the same as what we already have seen */
51 /* cannot disambiguate between ds->candidate and current */
56 if (!ds
->candidate_checked
) {
57 ds
->candidate_ok
= ds
->fn(&ds
->candidate
, ds
->cb_data
);
58 ds
->disambiguate_fn_used
= 1;
59 ds
->candidate_checked
= 1;
62 if (!ds
->candidate_ok
) {
63 /* discard the candidate; we know it does not satisfy fn */
64 oidcpy(&ds
->candidate
, current
);
65 ds
->candidate_checked
= 0;
69 /* if we reach this point, we know ds->candidate satisfies fn */
70 if (ds
->fn(current
, ds
->cb_data
)) {
72 * if both current and candidate satisfy fn, we cannot
79 /* otherwise, current can be discarded and candidate is still good */
82 static int append_loose_object(const struct object_id
*oid
, const char *path
,
85 oid_array_append(data
, oid
);
89 static int match_sha(unsigned, const unsigned char *, const unsigned char *);
91 static void find_short_object_filename(struct disambiguate_state
*ds
)
93 int subdir_nr
= ds
->bin_pfx
.hash
[0];
94 struct alternate_object_database
*alt
;
95 static struct alternate_object_database
*fakeent
;
99 * Create a "fake" alternate object database that
100 * points to our own object database, to make it
101 * easier to get a temporary working space in
102 * alt->name/alt->base while iterating over the
103 * object databases including our own.
105 fakeent
= alloc_alt_odb(get_object_directory());
107 fakeent
->next
= alt_odb_list
;
109 for (alt
= fakeent
; alt
&& !ds
->ambiguous
; alt
= alt
->next
) {
112 if (!alt
->loose_objects_subdir_seen
[subdir_nr
]) {
113 struct strbuf
*buf
= alt_scratch_buf(alt
);
114 for_each_file_in_obj_subdir(subdir_nr
, buf
,
117 &alt
->loose_objects_cache
);
118 alt
->loose_objects_subdir_seen
[subdir_nr
] = 1;
121 pos
= oid_array_lookup(&alt
->loose_objects_cache
, &ds
->bin_pfx
);
124 while (!ds
->ambiguous
&& pos
< alt
->loose_objects_cache
.nr
) {
125 const struct object_id
*oid
;
126 oid
= alt
->loose_objects_cache
.oid
+ pos
;
127 if (!match_sha(ds
->len
, ds
->bin_pfx
.hash
, oid
->hash
))
129 update_candidates(ds
, oid
);
135 static int match_sha(unsigned len
, const unsigned char *a
, const unsigned char *b
)
145 if ((*a
^ *b
) & 0xf0)
150 static void unique_in_pack(struct packed_git
*p
,
151 struct disambiguate_state
*ds
)
153 uint32_t num
, last
, i
, first
= 0;
154 const struct object_id
*current
= NULL
;
156 if (open_pack_index(p
) || !p
->num_objects
)
159 num
= p
->num_objects
;
161 while (first
< last
) {
162 uint32_t mid
= first
+ (last
- first
) / 2;
163 const unsigned char *current
;
166 current
= nth_packed_object_sha1(p
, mid
);
167 cmp
= hashcmp(ds
->bin_pfx
.hash
, current
);
180 * At this point, "first" is the location of the lowest object
181 * with an object name that could match "bin_pfx". See if we have
182 * 0, 1 or more objects that actually match(es).
184 for (i
= first
; i
< num
&& !ds
->ambiguous
; i
++) {
185 struct object_id oid
;
186 current
= nth_packed_object_oid(&oid
, p
, i
);
187 if (!match_sha(ds
->len
, ds
->bin_pfx
.hash
, current
->hash
))
189 update_candidates(ds
, current
);
193 static void find_short_packed_object(struct disambiguate_state
*ds
)
195 struct packed_git
*p
;
197 prepare_packed_git();
198 for (p
= packed_git
; p
&& !ds
->ambiguous
; p
= p
->next
)
199 unique_in_pack(p
, ds
);
202 #define SHORT_NAME_NOT_FOUND (-1)
203 #define SHORT_NAME_AMBIGUOUS (-2)
205 static int finish_object_disambiguation(struct disambiguate_state
*ds
,
206 struct object_id
*oid
)
209 return SHORT_NAME_AMBIGUOUS
;
211 if (!ds
->candidate_exists
)
212 return SHORT_NAME_NOT_FOUND
;
214 if (!ds
->candidate_checked
)
216 * If this is the only candidate, there is no point
217 * calling the disambiguation hint callback.
219 * On the other hand, if the current candidate
220 * replaced an earlier candidate that did _not_ pass
221 * the disambiguation hint callback, then we do have
222 * more than one objects that match the short name
223 * given, so we should make sure this one matches;
224 * otherwise, if we discovered this one and the one
225 * that we previously discarded in the reverse order,
226 * we would end up showing different results in the
229 ds
->candidate_ok
= (!ds
->disambiguate_fn_used
||
230 ds
->fn(&ds
->candidate
, ds
->cb_data
));
232 if (!ds
->candidate_ok
)
233 return SHORT_NAME_AMBIGUOUS
;
235 oidcpy(oid
, &ds
->candidate
);
239 static int disambiguate_commit_only(const struct object_id
*oid
, void *cb_data_unused
)
241 int kind
= sha1_object_info(oid
->hash
, NULL
);
242 return kind
== OBJ_COMMIT
;
245 static int disambiguate_committish_only(const struct object_id
*oid
, void *cb_data_unused
)
250 kind
= sha1_object_info(oid
->hash
, NULL
);
251 if (kind
== OBJ_COMMIT
)
256 /* We need to do this the hard way... */
257 obj
= deref_tag(parse_object(oid
), NULL
, 0);
258 if (obj
&& obj
->type
== OBJ_COMMIT
)
263 static int disambiguate_tree_only(const struct object_id
*oid
, void *cb_data_unused
)
265 int kind
= sha1_object_info(oid
->hash
, NULL
);
266 return kind
== OBJ_TREE
;
269 static int disambiguate_treeish_only(const struct object_id
*oid
, void *cb_data_unused
)
274 kind
= sha1_object_info(oid
->hash
, NULL
);
275 if (kind
== OBJ_TREE
|| kind
== OBJ_COMMIT
)
280 /* We need to do this the hard way... */
281 obj
= deref_tag(parse_object(oid
), NULL
, 0);
282 if (obj
&& (obj
->type
== OBJ_TREE
|| obj
->type
== OBJ_COMMIT
))
287 static int disambiguate_blob_only(const struct object_id
*oid
, void *cb_data_unused
)
289 int kind
= sha1_object_info(oid
->hash
, NULL
);
290 return kind
== OBJ_BLOB
;
293 static disambiguate_hint_fn default_disambiguate_hint
;
295 int set_disambiguate_hint_config(const char *var
, const char *value
)
297 static const struct {
299 disambiguate_hint_fn fn
;
302 { "commit", disambiguate_commit_only
},
303 { "committish", disambiguate_committish_only
},
304 { "tree", disambiguate_tree_only
},
305 { "treeish", disambiguate_treeish_only
},
306 { "blob", disambiguate_blob_only
}
311 return config_error_nonbool(var
);
313 for (i
= 0; i
< ARRAY_SIZE(hints
); i
++) {
314 if (!strcasecmp(value
, hints
[i
].name
)) {
315 default_disambiguate_hint
= hints
[i
].fn
;
320 return error("unknown hint type for '%s': %s", var
, value
);
323 static int init_object_disambiguation(const char *name
, int len
,
324 struct disambiguate_state
*ds
)
328 if (len
< MINIMUM_ABBREV
|| len
> GIT_SHA1_HEXSZ
)
331 memset(ds
, 0, sizeof(*ds
));
333 for (i
= 0; i
< len
;i
++) {
334 unsigned char c
= name
[i
];
336 if (c
>= '0' && c
<= '9')
338 else if (c
>= 'a' && c
<= 'f')
340 else if (c
>= 'A' && c
<='F') {
349 ds
->bin_pfx
.hash
[i
>> 1] |= val
;
353 ds
->hex_pfx
[len
] = '\0';
358 static int show_ambiguous_object(const struct object_id
*oid
, void *data
)
360 const struct disambiguate_state
*ds
= data
;
361 struct strbuf desc
= STRBUF_INIT
;
365 if (ds
->fn
&& !ds
->fn(oid
, ds
->cb_data
))
368 type
= sha1_object_info(oid
->hash
, NULL
);
369 if (type
== OBJ_COMMIT
) {
370 struct commit
*commit
= lookup_commit(oid
);
372 struct pretty_print_context pp
= {0};
373 pp
.date_mode
.type
= DATE_SHORT
;
374 format_commit_message(commit
, " %ad - %s", &desc
, &pp
);
376 } else if (type
== OBJ_TAG
) {
377 struct tag
*tag
= lookup_tag(oid
);
378 if (!parse_tag(tag
) && tag
->tag
)
379 strbuf_addf(&desc
, " %s", tag
->tag
);
383 find_unique_abbrev(oid
->hash
, DEFAULT_ABBREV
),
384 type_name(type
) ? type_name(type
) : "unknown type",
387 strbuf_release(&desc
);
391 static int get_short_oid(const char *name
, int len
, struct object_id
*oid
,
395 struct disambiguate_state ds
;
396 int quietly
= !!(flags
& GET_OID_QUIETLY
);
398 if (init_object_disambiguation(name
, len
, &ds
) < 0)
401 if (HAS_MULTI_BITS(flags
& GET_OID_DISAMBIGUATORS
))
402 die("BUG: multiple get_short_oid disambiguator flags");
404 if (flags
& GET_OID_COMMIT
)
405 ds
.fn
= disambiguate_commit_only
;
406 else if (flags
& GET_OID_COMMITTISH
)
407 ds
.fn
= disambiguate_committish_only
;
408 else if (flags
& GET_OID_TREE
)
409 ds
.fn
= disambiguate_tree_only
;
410 else if (flags
& GET_OID_TREEISH
)
411 ds
.fn
= disambiguate_treeish_only
;
412 else if (flags
& GET_OID_BLOB
)
413 ds
.fn
= disambiguate_blob_only
;
415 ds
.fn
= default_disambiguate_hint
;
417 find_short_object_filename(&ds
);
418 find_short_packed_object(&ds
);
419 status
= finish_object_disambiguation(&ds
, oid
);
421 if (!quietly
&& (status
== SHORT_NAME_AMBIGUOUS
)) {
422 error(_("short SHA1 %s is ambiguous"), ds
.hex_pfx
);
425 * We may still have ambiguity if we simply saw a series of
426 * candidates that did not satisfy our hint function. In
427 * that case, we still want to show them, so disable the hint
433 advise(_("The candidates are:"));
434 for_each_abbrev(ds
.hex_pfx
, show_ambiguous_object
, &ds
);
440 static int collect_ambiguous(const struct object_id
*oid
, void *data
)
442 oid_array_append(data
, oid
);
446 int for_each_abbrev(const char *prefix
, each_abbrev_fn fn
, void *cb_data
)
448 struct oid_array collect
= OID_ARRAY_INIT
;
449 struct disambiguate_state ds
;
452 if (init_object_disambiguation(prefix
, strlen(prefix
), &ds
) < 0)
455 ds
.always_call_fn
= 1;
456 ds
.fn
= collect_ambiguous
;
457 ds
.cb_data
= &collect
;
458 find_short_object_filename(&ds
);
459 find_short_packed_object(&ds
);
461 ret
= oid_array_for_each_unique(&collect
, fn
, cb_data
);
462 oid_array_clear(&collect
);
467 * Return the slot of the most-significant bit set in "val". There are various
468 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
469 * probably not a big deal here.
471 static unsigned msb(unsigned long val
)
479 struct min_abbrev_data
{
480 unsigned int init_len
;
481 unsigned int cur_len
;
483 const unsigned char *hash
;
486 static inline char get_hex_char_from_oid(const struct object_id
*oid
,
489 static const char hex
[] = "0123456789abcdef";
492 return hex
[oid
->hash
[pos
>> 1] >> 4];
494 return hex
[oid
->hash
[pos
>> 1] & 0xf];
497 static int extend_abbrev_len(const struct object_id
*oid
, void *cb_data
)
499 struct min_abbrev_data
*mad
= cb_data
;
501 unsigned int i
= mad
->init_len
;
502 while (mad
->hex
[i
] && mad
->hex
[i
] == get_hex_char_from_oid(oid
, i
))
505 if (i
< GIT_MAX_RAWSZ
&& i
>= mad
->cur_len
)
506 mad
->cur_len
= i
+ 1;
511 static void find_abbrev_len_for_pack(struct packed_git
*p
,
512 struct min_abbrev_data
*mad
)
515 uint32_t num
, last
, first
= 0;
516 struct object_id oid
;
518 if (open_pack_index(p
) || !p
->num_objects
)
521 num
= p
->num_objects
;
523 while (first
< last
) {
524 uint32_t mid
= first
+ (last
- first
) / 2;
525 const unsigned char *current
;
528 current
= nth_packed_object_sha1(p
, mid
);
529 cmp
= hashcmp(mad
->hash
, current
);
543 * first is now the position in the packfile where we would insert
544 * mad->hash if it does not exist (or the position of mad->hash if
545 * it does exist). Hence, we consider a maximum of three objects
546 * nearby for the abbreviation length.
550 nth_packed_object_oid(&oid
, p
, first
);
551 extend_abbrev_len(&oid
, mad
);
552 } else if (first
< num
- 1) {
553 nth_packed_object_oid(&oid
, p
, first
+ 1);
554 extend_abbrev_len(&oid
, mad
);
557 nth_packed_object_oid(&oid
, p
, first
- 1);
558 extend_abbrev_len(&oid
, mad
);
560 mad
->init_len
= mad
->cur_len
;
563 static void find_abbrev_len_packed(struct min_abbrev_data
*mad
)
565 struct packed_git
*p
;
567 prepare_packed_git();
568 for (p
= packed_git
; p
; p
= p
->next
)
569 find_abbrev_len_for_pack(p
, mad
);
572 int find_unique_abbrev_r(char *hex
, const unsigned char *sha1
, int len
)
574 struct disambiguate_state ds
;
575 struct min_abbrev_data mad
;
576 struct object_id oid_ret
;
578 unsigned long count
= approximate_object_count();
580 * Add one because the MSB only tells us the highest bit set,
581 * not including the value of all the _other_ bits (so "15"
582 * is only one off of 2^4, but the MSB is the 3rd bit.
584 len
= msb(count
) + 1;
586 * We now know we have on the order of 2^len objects, which
587 * expects a collision at 2^(len/2). But we also care about hex
588 * chars, not bits, and there are 4 bits per hex. So all
589 * together we need to divide by 2 and round up.
591 len
= DIV_ROUND_UP(len
, 2);
593 * For very small repos, we stick with our regular fallback.
595 if (len
< FALLBACK_DEFAULT_ABBREV
)
596 len
= FALLBACK_DEFAULT_ABBREV
;
599 sha1_to_hex_r(hex
, sha1
);
600 if (len
== GIT_SHA1_HEXSZ
|| !len
)
601 return GIT_SHA1_HEXSZ
;
608 find_abbrev_len_packed(&mad
);
610 if (init_object_disambiguation(hex
, mad
.cur_len
, &ds
) < 0)
613 ds
.fn
= extend_abbrev_len
;
614 ds
.always_call_fn
= 1;
615 ds
.cb_data
= (void *)&mad
;
617 find_short_object_filename(&ds
);
618 (void)finish_object_disambiguation(&ds
, &oid_ret
);
620 hex
[mad
.cur_len
] = 0;
624 const char *find_unique_abbrev(const unsigned char *sha1
, int len
)
627 static char hexbuffer
[4][GIT_MAX_HEXSZ
+ 1];
628 char *hex
= hexbuffer
[bufno
];
629 bufno
= (bufno
+ 1) % ARRAY_SIZE(hexbuffer
);
630 find_unique_abbrev_r(hex
, sha1
, len
);
634 static int ambiguous_path(const char *path
, int len
)
639 for (cnt
= 0; cnt
< len
; cnt
++) {
659 static inline int at_mark(const char *string
, int len
,
660 const char **suffix
, int nr
)
664 for (i
= 0; i
< nr
; i
++) {
665 int suffix_len
= strlen(suffix
[i
]);
666 if (suffix_len
<= len
667 && !strncasecmp(string
, suffix
[i
], suffix_len
))
673 static inline int upstream_mark(const char *string
, int len
)
675 const char *suffix
[] = { "@{upstream}", "@{u}" };
676 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
679 static inline int push_mark(const char *string
, int len
)
681 const char *suffix
[] = { "@{push}" };
682 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
685 static int get_oid_1(const char *name
, int len
, struct object_id
*oid
, unsigned lookup_flags
);
686 static int interpret_nth_prior_checkout(const char *name
, int namelen
, struct strbuf
*buf
);
688 static int get_oid_basic(const char *str
, int len
, struct object_id
*oid
,
691 static const char *warn_msg
= "refname '%.*s' is ambiguous.";
692 static const char *object_name_msg
= N_(
693 "Git normally never creates a ref that ends with 40 hex characters\n"
694 "because it will be ignored when you just specify 40-hex. These refs\n"
695 "may be created by mistake. For example,\n"
697 " git checkout -b $br $(git rev-parse ...)\n"
699 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
700 "examine these refs and maybe delete them. Turn this message off by\n"
701 "running \"git config advice.objectNameWarning false\"");
702 struct object_id tmp_oid
;
703 char *real_ref
= NULL
;
705 int at
, reflog_len
, nth_prior
= 0;
707 if (len
== GIT_SHA1_HEXSZ
&& !get_oid_hex(str
, oid
)) {
708 if (warn_ambiguous_refs
&& warn_on_object_refname_ambiguity
) {
709 refs_found
= dwim_ref(str
, len
, &tmp_oid
, &real_ref
);
710 if (refs_found
> 0) {
711 warning(warn_msg
, len
, str
);
712 if (advice_object_name_warning
)
713 fprintf(stderr
, "%s\n", _(object_name_msg
));
720 /* basic@{time or number or -number} format to query ref-log */
722 if (len
&& str
[len
-1] == '}') {
723 for (at
= len
-4; at
>= 0; at
--) {
724 if (str
[at
] == '@' && str
[at
+1] == '{') {
725 if (str
[at
+2] == '-') {
727 /* @{-N} not at start */
732 if (!upstream_mark(str
+ at
, len
- at
) &&
733 !push_mark(str
+ at
, len
- at
)) {
734 reflog_len
= (len
-1) - (at
+2);
742 /* Accept only unambiguous ref paths. */
743 if (len
&& ambiguous_path(str
, len
))
747 struct strbuf buf
= STRBUF_INIT
;
750 if (interpret_nth_prior_checkout(str
, len
, &buf
) > 0) {
751 detached
= (buf
.len
== GIT_SHA1_HEXSZ
&& !get_oid_hex(buf
.buf
, oid
));
752 strbuf_release(&buf
);
758 if (!len
&& reflog_len
)
759 /* allow "@{...}" to mean the current branch reflog */
760 refs_found
= dwim_ref("HEAD", 4, oid
, &real_ref
);
762 refs_found
= dwim_log(str
, len
, oid
, &real_ref
);
764 refs_found
= dwim_ref(str
, len
, oid
, &real_ref
);
769 if (warn_ambiguous_refs
&& !(flags
& GET_OID_QUIETLY
) &&
771 !get_short_oid(str
, len
, &tmp_oid
, GET_OID_QUIETLY
)))
772 warning(warn_msg
, len
, str
);
780 /* Is it asking for N-th entry, or approxidate? */
781 for (i
= nth
= 0; 0 <= nth
&& i
< reflog_len
; i
++) {
782 char ch
= str
[at
+2+i
];
783 if ('0' <= ch
&& ch
<= '9')
784 nth
= nth
* 10 + ch
- '0';
788 if (100000000 <= nth
) {
795 char *tmp
= xstrndup(str
+ at
+ 2, reflog_len
);
796 at_time
= approxidate_careful(tmp
, &errors
);
803 if (read_ref_at(real_ref
, flags
, at_time
, nth
, oid
, NULL
,
804 &co_time
, &co_tz
, &co_cnt
)) {
806 if (starts_with(real_ref
, "refs/heads/")) {
808 len
= strlen(real_ref
+ 11);
816 if (!(flags
& GET_OID_QUIETLY
)) {
817 warning("Log for '%.*s' only goes "
818 "back to %s.", len
, str
,
819 show_date(co_time
, co_tz
, DATE_MODE(RFC2822
)));
822 if (flags
& GET_OID_QUIETLY
) {
825 die("Log for '%.*s' only has %d entries.",
835 static int get_parent(const char *name
, int len
,
836 struct object_id
*result
, int idx
)
838 struct object_id oid
;
839 int ret
= get_oid_1(name
, len
, &oid
, GET_OID_COMMITTISH
);
840 struct commit
*commit
;
841 struct commit_list
*p
;
845 commit
= lookup_commit_reference(&oid
);
846 if (parse_commit(commit
))
849 oidcpy(result
, &commit
->object
.oid
);
855 oidcpy(result
, &p
->item
->object
.oid
);
863 static int get_nth_ancestor(const char *name
, int len
,
864 struct object_id
*result
, int generation
)
866 struct object_id oid
;
867 struct commit
*commit
;
870 ret
= get_oid_1(name
, len
, &oid
, GET_OID_COMMITTISH
);
873 commit
= lookup_commit_reference(&oid
);
877 while (generation
--) {
878 if (parse_commit(commit
) || !commit
->parents
)
880 commit
= commit
->parents
->item
;
882 oidcpy(result
, &commit
->object
.oid
);
886 struct object
*peel_to_type(const char *name
, int namelen
,
887 struct object
*o
, enum object_type expected_type
)
889 if (name
&& !namelen
)
890 namelen
= strlen(name
);
892 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
894 if (expected_type
== OBJ_ANY
|| o
->type
== expected_type
)
896 if (o
->type
== OBJ_TAG
)
897 o
= ((struct tag
*) o
)->tagged
;
898 else if (o
->type
== OBJ_COMMIT
)
899 o
= &(((struct commit
*) o
)->tree
->object
);
902 error("%.*s: expected %s type, but the object "
903 "dereferences to %s type",
904 namelen
, name
, type_name(expected_type
),
911 static int peel_onion(const char *name
, int len
, struct object_id
*oid
,
912 unsigned lookup_flags
)
914 struct object_id outer
;
916 unsigned int expected_type
= 0;
920 * "ref^{type}" dereferences ref repeatedly until you cannot
921 * dereference anymore, or you get an object of given type,
922 * whichever comes first. "ref^{}" means just dereference
923 * tags until you get a non-tag. "ref^0" is a shorthand for
924 * "ref^{commit}". "commit^{tree}" could be used to find the
925 * top-level tree of the given commit.
927 if (len
< 4 || name
[len
-1] != '}')
930 for (sp
= name
+ len
- 1; name
<= sp
; sp
--) {
932 if (ch
== '{' && name
< sp
&& sp
[-1] == '^')
938 sp
++; /* beginning of type name, or closing brace for empty */
939 if (starts_with(sp
, "commit}"))
940 expected_type
= OBJ_COMMIT
;
941 else if (starts_with(sp
, "tag}"))
942 expected_type
= OBJ_TAG
;
943 else if (starts_with(sp
, "tree}"))
944 expected_type
= OBJ_TREE
;
945 else if (starts_with(sp
, "blob}"))
946 expected_type
= OBJ_BLOB
;
947 else if (starts_with(sp
, "object}"))
948 expected_type
= OBJ_ANY
;
949 else if (sp
[0] == '}')
950 expected_type
= OBJ_NONE
;
951 else if (sp
[0] == '/')
952 expected_type
= OBJ_COMMIT
;
956 lookup_flags
&= ~GET_OID_DISAMBIGUATORS
;
957 if (expected_type
== OBJ_COMMIT
)
958 lookup_flags
|= GET_OID_COMMITTISH
;
959 else if (expected_type
== OBJ_TREE
)
960 lookup_flags
|= GET_OID_TREEISH
;
962 if (get_oid_1(name
, sp
- name
- 2, &outer
, lookup_flags
))
965 o
= parse_object(&outer
);
968 if (!expected_type
) {
969 o
= deref_tag(o
, name
, sp
- name
- 2);
970 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
972 oidcpy(oid
, &o
->oid
);
977 * At this point, the syntax look correct, so
978 * if we do not get the needed object, we should
981 o
= peel_to_type(name
, len
, o
, expected_type
);
985 oidcpy(oid
, &o
->oid
);
987 /* "$commit^{/foo}" */
990 struct commit_list
*list
= NULL
;
993 * $commit^{/}. Some regex implementation may reject.
994 * We don't need regex anyway. '' pattern always matches.
999 prefix
= xstrndup(sp
+ 1, name
+ len
- 1 - (sp
+ 1));
1000 commit_list_insert((struct commit
*)o
, &list
);
1001 ret
= get_oid_oneline(prefix
, oid
, list
);
1008 static int get_describe_name(const char *name
, int len
, struct object_id
*oid
)
1011 unsigned flags
= GET_OID_QUIETLY
| GET_OID_COMMIT
;
1013 for (cp
= name
+ len
- 1; name
+ 2 <= cp
; cp
--) {
1015 if (!isxdigit(ch
)) {
1016 /* We must be looking at g in "SOMETHING-g"
1017 * for it to be describe output.
1019 if (ch
== 'g' && cp
[-1] == '-') {
1022 return get_short_oid(cp
, len
, oid
, flags
);
1029 static int get_oid_1(const char *name
, int len
, struct object_id
*oid
, unsigned lookup_flags
)
1031 int ret
, has_suffix
;
1035 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
1038 for (cp
= name
+ len
- 1; name
<= cp
; cp
--) {
1040 if ('0' <= ch
&& ch
<= '9')
1042 if (ch
== '~' || ch
== '^')
1049 int len1
= cp
- name
;
1051 while (cp
< name
+ len
)
1052 num
= num
* 10 + *cp
++ - '0';
1053 if (!num
&& len1
== len
- 1)
1055 if (has_suffix
== '^')
1056 return get_parent(name
, len1
, oid
, num
);
1057 /* else if (has_suffix == '~') -- goes without saying */
1058 return get_nth_ancestor(name
, len1
, oid
, num
);
1061 ret
= peel_onion(name
, len
, oid
, lookup_flags
);
1065 ret
= get_oid_basic(name
, len
, oid
, lookup_flags
);
1069 /* It could be describe output that is "SOMETHING-gXXXX" */
1070 ret
= get_describe_name(name
, len
, oid
);
1074 return get_short_oid(name
, len
, oid
, lookup_flags
);
1078 * This interprets names like ':/Initial revision of "git"' by searching
1079 * through history and returning the first commit whose message starts
1080 * the given regular expression.
1082 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1084 * For a literal '!' character at the beginning of a pattern, you have to repeat
1085 * that, like: ':/!!foo'
1087 * For future extension, all other sequences beginning with ':/!' are reserved.
1090 /* Remember to update object flag allocation in object.h */
1091 #define ONELINE_SEEN (1u<<20)
1093 static int handle_one_ref(const char *path
, const struct object_id
*oid
,
1094 int flag
, void *cb_data
)
1096 struct commit_list
**list
= cb_data
;
1097 struct object
*object
= parse_object(oid
);
1100 if (object
->type
== OBJ_TAG
) {
1101 object
= deref_tag(object
, path
, strlen(path
));
1105 if (object
->type
!= OBJ_COMMIT
)
1107 commit_list_insert((struct commit
*)object
, list
);
1111 static int get_oid_oneline(const char *prefix
, struct object_id
*oid
,
1112 struct commit_list
*list
)
1114 struct commit_list
*backup
= NULL
, *l
;
1119 if (prefix
[0] == '!') {
1122 if (prefix
[0] == '-') {
1125 } else if (prefix
[0] != '!') {
1130 if (regcomp(®ex
, prefix
, REG_EXTENDED
))
1133 for (l
= list
; l
; l
= l
->next
) {
1134 l
->item
->object
.flags
|= ONELINE_SEEN
;
1135 commit_list_insert(l
->item
, &backup
);
1138 const char *p
, *buf
;
1139 struct commit
*commit
;
1142 commit
= pop_most_recent_commit(&list
, ONELINE_SEEN
);
1143 if (!parse_object(&commit
->object
.oid
))
1145 buf
= get_commit_buffer(commit
, NULL
);
1146 p
= strstr(buf
, "\n\n");
1147 matches
= negative
^ (p
&& !regexec(®ex
, p
+ 2, 0, NULL
, 0));
1148 unuse_commit_buffer(commit
, buf
);
1151 oidcpy(oid
, &commit
->object
.oid
);
1157 free_commit_list(list
);
1158 for (l
= backup
; l
; l
= l
->next
)
1159 clear_commit_marks(l
->item
, ONELINE_SEEN
);
1160 free_commit_list(backup
);
1161 return found
? 0 : -1;
1164 struct grab_nth_branch_switch_cbdata
{
1169 static int grab_nth_branch_switch(struct object_id
*ooid
, struct object_id
*noid
,
1170 const char *email
, timestamp_t timestamp
, int tz
,
1171 const char *message
, void *cb_data
)
1173 struct grab_nth_branch_switch_cbdata
*cb
= cb_data
;
1174 const char *match
= NULL
, *target
= NULL
;
1177 if (skip_prefix(message
, "checkout: moving from ", &match
))
1178 target
= strstr(match
, " to ");
1180 if (!match
|| !target
)
1182 if (--(cb
->remaining
) == 0) {
1183 len
= target
- match
;
1184 strbuf_reset(&cb
->buf
);
1185 strbuf_add(&cb
->buf
, match
, len
);
1186 return 1; /* we are done */
1192 * Parse @{-N} syntax, return the number of characters parsed
1193 * if successful; otherwise signal an error with negative value.
1195 static int interpret_nth_prior_checkout(const char *name
, int namelen
,
1200 struct grab_nth_branch_switch_cbdata cb
;
1206 if (name
[0] != '@' || name
[1] != '{' || name
[2] != '-')
1208 brace
= memchr(name
, '}', namelen
);
1211 nth
= strtol(name
+ 3, &num_end
, 10);
1212 if (num_end
!= brace
)
1217 strbuf_init(&cb
.buf
, 20);
1220 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch
, &cb
)) {
1222 strbuf_addbuf(buf
, &cb
.buf
);
1223 retval
= brace
- name
+ 1;
1226 strbuf_release(&cb
.buf
);
1230 int get_oid_mb(const char *name
, struct object_id
*oid
)
1232 struct commit
*one
, *two
;
1233 struct commit_list
*mbs
;
1234 struct object_id oid_tmp
;
1238 dots
= strstr(name
, "...");
1240 return get_oid(name
, oid
);
1242 st
= get_oid("HEAD", &oid_tmp
);
1245 strbuf_init(&sb
, dots
- name
);
1246 strbuf_add(&sb
, name
, dots
- name
);
1247 st
= get_oid_committish(sb
.buf
, &oid_tmp
);
1248 strbuf_release(&sb
);
1252 one
= lookup_commit_reference_gently(&oid_tmp
, 0);
1256 if (get_oid_committish(dots
[3] ? (dots
+ 3) : "HEAD", &oid_tmp
))
1258 two
= lookup_commit_reference_gently(&oid_tmp
, 0);
1261 mbs
= get_merge_bases(one
, two
);
1262 if (!mbs
|| mbs
->next
)
1266 oidcpy(oid
, &mbs
->item
->object
.oid
);
1268 free_commit_list(mbs
);
1272 /* parse @something syntax, when 'something' is not {.*} */
1273 static int interpret_empty_at(const char *name
, int namelen
, int len
, struct strbuf
*buf
)
1277 if (len
|| name
[1] == '{')
1280 /* make sure it's a single @, or @@{.*}, not @foo */
1281 next
= memchr(name
+ len
+ 1, '@', namelen
- len
- 1);
1282 if (next
&& next
[1] != '{')
1285 next
= name
+ namelen
;
1286 if (next
!= name
+ 1)
1290 strbuf_add(buf
, "HEAD", 4);
1294 static int reinterpret(const char *name
, int namelen
, int len
,
1295 struct strbuf
*buf
, unsigned allowed
)
1297 /* we have extra data, which might need further processing */
1298 struct strbuf tmp
= STRBUF_INIT
;
1299 int used
= buf
->len
;
1302 strbuf_add(buf
, name
+ len
, namelen
- len
);
1303 ret
= interpret_branch_name(buf
->buf
, buf
->len
, &tmp
, allowed
);
1304 /* that data was not interpreted, remove our cruft */
1306 strbuf_setlen(buf
, used
);
1310 strbuf_addbuf(buf
, &tmp
);
1311 strbuf_release(&tmp
);
1312 /* tweak for size of {-N} versus expanded ref name */
1313 return ret
- used
+ len
;
1316 static void set_shortened_ref(struct strbuf
*buf
, const char *ref
)
1318 char *s
= shorten_unambiguous_ref(ref
, 0);
1320 strbuf_addstr(buf
, s
);
1324 static int branch_interpret_allowed(const char *refname
, unsigned allowed
)
1329 if ((allowed
& INTERPRET_BRANCH_LOCAL
) &&
1330 starts_with(refname
, "refs/heads/"))
1332 if ((allowed
& INTERPRET_BRANCH_REMOTE
) &&
1333 starts_with(refname
, "refs/remotes/"))
1339 static int interpret_branch_mark(const char *name
, int namelen
,
1340 int at
, struct strbuf
*buf
,
1341 int (*get_mark
)(const char *, int),
1342 const char *(*get_data
)(struct branch
*,
1347 struct branch
*branch
;
1348 struct strbuf err
= STRBUF_INIT
;
1351 len
= get_mark(name
+ at
, namelen
- at
);
1355 if (memchr(name
, ':', at
))
1359 char *name_str
= xmemdupz(name
, at
);
1360 branch
= branch_get(name_str
);
1363 branch
= branch_get(NULL
);
1365 value
= get_data(branch
, &err
);
1369 if (!branch_interpret_allowed(value
, allowed
))
1372 set_shortened_ref(buf
, value
);
1376 int interpret_branch_name(const char *name
, int namelen
, struct strbuf
*buf
,
1384 namelen
= strlen(name
);
1386 if (!allowed
|| (allowed
& INTERPRET_BRANCH_LOCAL
)) {
1387 len
= interpret_nth_prior_checkout(name
, namelen
, buf
);
1389 return len
; /* syntax Ok, not enough switches */
1390 } else if (len
> 0) {
1392 return len
; /* consumed all */
1394 return reinterpret(name
, namelen
, len
, buf
, allowed
);
1399 (at
= memchr(start
, '@', namelen
- (start
- name
)));
1402 if (!allowed
|| (allowed
& INTERPRET_BRANCH_HEAD
)) {
1403 len
= interpret_empty_at(name
, namelen
, at
- name
, buf
);
1405 return reinterpret(name
, namelen
, len
, buf
,
1409 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1410 upstream_mark
, branch_get_upstream
,
1415 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1416 push_mark
, branch_get_push
,
1425 void strbuf_branchname(struct strbuf
*sb
, const char *name
, unsigned allowed
)
1427 int len
= strlen(name
);
1428 int used
= interpret_branch_name(name
, len
, sb
, allowed
);
1432 strbuf_add(sb
, name
+ used
, len
- used
);
1435 int strbuf_check_branch_ref(struct strbuf
*sb
, const char *name
)
1437 if (startup_info
->have_repository
)
1438 strbuf_branchname(sb
, name
, INTERPRET_BRANCH_LOCAL
);
1440 strbuf_addstr(sb
, name
);
1443 * This splice must be done even if we end up rejecting the
1444 * name; builtin/branch.c::copy_or_rename_branch() still wants
1445 * to see what the name expanded to so that "branch -m" can be
1446 * used as a tool to correct earlier mistakes.
1448 strbuf_splice(sb
, 0, 0, "refs/heads/", 11);
1451 !strcmp(sb
->buf
, "refs/heads/HEAD"))
1454 return check_refname_format(sb
->buf
, 0);
1458 * This is like "get_oid_basic()", except it allows "object ID expressions",
1459 * notably "xyz^" for "parent of xyz"
1461 int get_oid(const char *name
, struct object_id
*oid
)
1463 struct object_context unused
;
1464 return get_oid_with_context(name
, 0, oid
, &unused
);
1469 * Many callers know that the user meant to name a commit-ish by
1470 * syntactical positions where the object name appears. Calling this
1471 * function allows the machinery to disambiguate shorter-than-unique
1472 * abbreviated object names between commit-ish and others.
1474 * Note that this does NOT error out when the named object is not a
1475 * commit-ish. It is merely to give a hint to the disambiguation
1478 int get_oid_committish(const char *name
, struct object_id
*oid
)
1480 struct object_context unused
;
1481 return get_oid_with_context(name
, GET_OID_COMMITTISH
,
1485 int get_oid_treeish(const char *name
, struct object_id
*oid
)
1487 struct object_context unused
;
1488 return get_oid_with_context(name
, GET_OID_TREEISH
,
1492 int get_oid_commit(const char *name
, struct object_id
*oid
)
1494 struct object_context unused
;
1495 return get_oid_with_context(name
, GET_OID_COMMIT
,
1499 int get_oid_tree(const char *name
, struct object_id
*oid
)
1501 struct object_context unused
;
1502 return get_oid_with_context(name
, GET_OID_TREE
,
1506 int get_oid_blob(const char *name
, struct object_id
*oid
)
1508 struct object_context unused
;
1509 return get_oid_with_context(name
, GET_OID_BLOB
,
1513 /* Must be called only when object_name:filename doesn't exist. */
1514 static void diagnose_invalid_oid_path(const char *prefix
,
1515 const char *filename
,
1516 const struct object_id
*tree_oid
,
1517 const char *object_name
,
1518 int object_name_len
)
1520 struct object_id oid
;
1526 if (file_exists(filename
))
1527 die("Path '%s' exists on disk, but not in '%.*s'.",
1528 filename
, object_name_len
, object_name
);
1529 if (is_missing_file_error(errno
)) {
1530 char *fullname
= xstrfmt("%s%s", prefix
, filename
);
1532 if (!get_tree_entry(tree_oid
->hash
, fullname
,
1534 die("Path '%s' exists, but not '%s'.\n"
1535 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1538 object_name_len
, object_name
,
1540 object_name_len
, object_name
,
1543 die("Path '%s' does not exist in '%.*s'",
1544 filename
, object_name_len
, object_name
);
1548 /* Must be called only when :stage:filename doesn't exist. */
1549 static void diagnose_invalid_index_path(int stage
,
1551 const char *filename
)
1553 const struct cache_entry
*ce
;
1555 unsigned namelen
= strlen(filename
);
1556 struct strbuf fullname
= STRBUF_INIT
;
1561 /* Wrong stage number? */
1562 pos
= cache_name_pos(filename
, namelen
);
1565 if (pos
< active_nr
) {
1566 ce
= active_cache
[pos
];
1567 if (ce_namelen(ce
) == namelen
&&
1568 !memcmp(ce
->name
, filename
, namelen
))
1569 die("Path '%s' is in the index, but not at stage %d.\n"
1570 "Did you mean ':%d:%s'?",
1572 ce_stage(ce
), filename
);
1575 /* Confusion between relative and absolute filenames? */
1576 strbuf_addstr(&fullname
, prefix
);
1577 strbuf_addstr(&fullname
, filename
);
1578 pos
= cache_name_pos(fullname
.buf
, fullname
.len
);
1581 if (pos
< active_nr
) {
1582 ce
= active_cache
[pos
];
1583 if (ce_namelen(ce
) == fullname
.len
&&
1584 !memcmp(ce
->name
, fullname
.buf
, fullname
.len
))
1585 die("Path '%s' is in the index, but not '%s'.\n"
1586 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1587 fullname
.buf
, filename
,
1588 ce_stage(ce
), fullname
.buf
,
1589 ce_stage(ce
), filename
);
1592 if (file_exists(filename
))
1593 die("Path '%s' exists on disk, but not in the index.", filename
);
1594 if (is_missing_file_error(errno
))
1595 die("Path '%s' does not exist (neither on disk nor in the index).",
1598 strbuf_release(&fullname
);
1602 static char *resolve_relative_path(const char *rel
)
1604 if (!starts_with(rel
, "./") && !starts_with(rel
, "../"))
1607 if (!is_inside_work_tree())
1608 die("relative path syntax can't be used outside working tree.");
1610 /* die() inside prefix_path() if resolved path is outside worktree */
1611 return prefix_path(startup_info
->prefix
,
1612 startup_info
->prefix
? strlen(startup_info
->prefix
) : 0,
1616 static int get_oid_with_context_1(const char *name
,
1619 struct object_id
*oid
,
1620 struct object_context
*oc
)
1622 int ret
, bracket_depth
;
1623 int namelen
= strlen(name
);
1625 int only_to_die
= flags
& GET_OID_ONLY_TO_DIE
;
1628 flags
|= GET_OID_QUIETLY
;
1630 memset(oc
, 0, sizeof(*oc
));
1631 oc
->mode
= S_IFINVALID
;
1632 strbuf_init(&oc
->symlink_path
, 0);
1633 ret
= get_oid_1(name
, namelen
, oid
, flags
);
1637 * sha1:path --> object name of path in ent sha1
1638 * :path -> object name of absolute path in index
1639 * :./path -> object name of path relative to cwd in index
1640 * :[0-3]:path -> object name of path in index at stage
1641 * :/foo -> recent commit matching foo
1643 if (name
[0] == ':') {
1645 const struct cache_entry
*ce
;
1646 char *new_path
= NULL
;
1648 if (!only_to_die
&& namelen
> 2 && name
[1] == '/') {
1649 struct commit_list
*list
= NULL
;
1651 for_each_ref(handle_one_ref
, &list
);
1652 commit_list_sort_by_date(&list
);
1653 return get_oid_oneline(name
+ 2, oid
, list
);
1657 name
[1] < '0' || '3' < name
[1])
1660 stage
= name
[1] - '0';
1663 new_path
= resolve_relative_path(cp
);
1665 namelen
= namelen
- (cp
- name
);
1668 namelen
= strlen(cp
);
1671 if (flags
& GET_OID_RECORD_PATH
)
1672 oc
->path
= xstrdup(cp
);
1676 pos
= cache_name_pos(cp
, namelen
);
1679 while (pos
< active_nr
) {
1680 ce
= active_cache
[pos
];
1681 if (ce_namelen(ce
) != namelen
||
1682 memcmp(ce
->name
, cp
, namelen
))
1684 if (ce_stage(ce
) == stage
) {
1685 oidcpy(oid
, &ce
->oid
);
1686 oc
->mode
= ce
->ce_mode
;
1692 if (only_to_die
&& name
[1] && name
[1] != '/')
1693 diagnose_invalid_index_path(stage
, prefix
, cp
);
1697 for (cp
= name
, bracket_depth
= 0; *cp
; cp
++) {
1700 else if (bracket_depth
&& *cp
== '}')
1702 else if (!bracket_depth
&& *cp
== ':')
1706 struct object_id tree_oid
;
1707 int len
= cp
- name
;
1708 unsigned sub_flags
= flags
;
1710 sub_flags
&= ~GET_OID_DISAMBIGUATORS
;
1711 sub_flags
|= GET_OID_TREEISH
;
1713 if (!get_oid_1(name
, len
, &tree_oid
, sub_flags
)) {
1714 const char *filename
= cp
+1;
1715 char *new_filename
= NULL
;
1717 new_filename
= resolve_relative_path(filename
);
1719 filename
= new_filename
;
1720 if (flags
& GET_OID_FOLLOW_SYMLINKS
) {
1721 ret
= get_tree_entry_follow_symlinks(tree_oid
.hash
,
1722 filename
, oid
->hash
, &oc
->symlink_path
,
1725 ret
= get_tree_entry(tree_oid
.hash
, filename
,
1726 oid
->hash
, &oc
->mode
);
1727 if (ret
&& only_to_die
) {
1728 diagnose_invalid_oid_path(prefix
,
1734 hashcpy(oc
->tree
, tree_oid
.hash
);
1735 if (flags
& GET_OID_RECORD_PATH
)
1736 oc
->path
= xstrdup(filename
);
1742 die("Invalid object name '%.*s'.", len
, name
);
1749 * Call this function when you know "name" given by the end user must
1750 * name an object but it doesn't; the function _may_ die with a better
1751 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1752 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1753 * you have a chance to diagnose the error further.
1755 void maybe_die_on_misspelt_object_name(const char *name
, const char *prefix
)
1757 struct object_context oc
;
1758 struct object_id oid
;
1759 get_oid_with_context_1(name
, GET_OID_ONLY_TO_DIE
, prefix
, &oid
, &oc
);
1762 int get_oid_with_context(const char *str
, unsigned flags
, struct object_id
*oid
, struct object_context
*oc
)
1764 if (flags
& GET_OID_FOLLOW_SYMLINKS
&& flags
& GET_OID_ONLY_TO_DIE
)
1765 die("BUG: incompatible flags for get_sha1_with_context");
1766 return get_oid_with_context_1(str
, flags
, NULL
, oid
, oc
);