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
;
157 num
= p
->num_objects
;
159 while (first
< last
) {
160 uint32_t mid
= (first
+ last
) / 2;
161 const unsigned char *current
;
164 current
= nth_packed_object_sha1(p
, mid
);
165 cmp
= hashcmp(ds
->bin_pfx
.hash
, current
);
178 * At this point, "first" is the location of the lowest object
179 * with an object name that could match "bin_pfx". See if we have
180 * 0, 1 or more objects that actually match(es).
182 for (i
= first
; i
< num
&& !ds
->ambiguous
; i
++) {
183 struct object_id oid
;
184 current
= nth_packed_object_oid(&oid
, p
, i
);
185 if (!match_sha(ds
->len
, ds
->bin_pfx
.hash
, current
->hash
))
187 update_candidates(ds
, current
);
191 static void find_short_packed_object(struct disambiguate_state
*ds
)
193 struct packed_git
*p
;
195 prepare_packed_git();
196 for (p
= packed_git
; p
&& !ds
->ambiguous
; p
= p
->next
)
197 unique_in_pack(p
, ds
);
200 #define SHORT_NAME_NOT_FOUND (-1)
201 #define SHORT_NAME_AMBIGUOUS (-2)
203 static int finish_object_disambiguation(struct disambiguate_state
*ds
,
204 struct object_id
*oid
)
207 return SHORT_NAME_AMBIGUOUS
;
209 if (!ds
->candidate_exists
)
210 return SHORT_NAME_NOT_FOUND
;
212 if (!ds
->candidate_checked
)
214 * If this is the only candidate, there is no point
215 * calling the disambiguation hint callback.
217 * On the other hand, if the current candidate
218 * replaced an earlier candidate that did _not_ pass
219 * the disambiguation hint callback, then we do have
220 * more than one objects that match the short name
221 * given, so we should make sure this one matches;
222 * otherwise, if we discovered this one and the one
223 * that we previously discarded in the reverse order,
224 * we would end up showing different results in the
227 ds
->candidate_ok
= (!ds
->disambiguate_fn_used
||
228 ds
->fn(&ds
->candidate
, ds
->cb_data
));
230 if (!ds
->candidate_ok
)
231 return SHORT_NAME_AMBIGUOUS
;
233 oidcpy(oid
, &ds
->candidate
);
237 static int disambiguate_commit_only(const struct object_id
*oid
, void *cb_data_unused
)
239 int kind
= sha1_object_info(oid
->hash
, NULL
);
240 return kind
== OBJ_COMMIT
;
243 static int disambiguate_committish_only(const struct object_id
*oid
, void *cb_data_unused
)
248 kind
= sha1_object_info(oid
->hash
, NULL
);
249 if (kind
== OBJ_COMMIT
)
254 /* We need to do this the hard way... */
255 obj
= deref_tag(parse_object(oid
), NULL
, 0);
256 if (obj
&& obj
->type
== OBJ_COMMIT
)
261 static int disambiguate_tree_only(const struct object_id
*oid
, void *cb_data_unused
)
263 int kind
= sha1_object_info(oid
->hash
, NULL
);
264 return kind
== OBJ_TREE
;
267 static int disambiguate_treeish_only(const struct object_id
*oid
, void *cb_data_unused
)
272 kind
= sha1_object_info(oid
->hash
, NULL
);
273 if (kind
== OBJ_TREE
|| kind
== OBJ_COMMIT
)
278 /* We need to do this the hard way... */
279 obj
= deref_tag(parse_object(oid
), NULL
, 0);
280 if (obj
&& (obj
->type
== OBJ_TREE
|| obj
->type
== OBJ_COMMIT
))
285 static int disambiguate_blob_only(const struct object_id
*oid
, void *cb_data_unused
)
287 int kind
= sha1_object_info(oid
->hash
, NULL
);
288 return kind
== OBJ_BLOB
;
291 static disambiguate_hint_fn default_disambiguate_hint
;
293 int set_disambiguate_hint_config(const char *var
, const char *value
)
295 static const struct {
297 disambiguate_hint_fn fn
;
300 { "commit", disambiguate_commit_only
},
301 { "committish", disambiguate_committish_only
},
302 { "tree", disambiguate_tree_only
},
303 { "treeish", disambiguate_treeish_only
},
304 { "blob", disambiguate_blob_only
}
309 return config_error_nonbool(var
);
311 for (i
= 0; i
< ARRAY_SIZE(hints
); i
++) {
312 if (!strcasecmp(value
, hints
[i
].name
)) {
313 default_disambiguate_hint
= hints
[i
].fn
;
318 return error("unknown hint type for '%s': %s", var
, value
);
321 static int init_object_disambiguation(const char *name
, int len
,
322 struct disambiguate_state
*ds
)
326 if (len
< MINIMUM_ABBREV
|| len
> GIT_SHA1_HEXSZ
)
329 memset(ds
, 0, sizeof(*ds
));
331 for (i
= 0; i
< len
;i
++) {
332 unsigned char c
= name
[i
];
334 if (c
>= '0' && c
<= '9')
336 else if (c
>= 'a' && c
<= 'f')
338 else if (c
>= 'A' && c
<='F') {
347 ds
->bin_pfx
.hash
[i
>> 1] |= val
;
351 ds
->hex_pfx
[len
] = '\0';
356 static int show_ambiguous_object(const struct object_id
*oid
, void *data
)
358 const struct disambiguate_state
*ds
= data
;
359 struct strbuf desc
= STRBUF_INIT
;
363 if (ds
->fn
&& !ds
->fn(oid
, ds
->cb_data
))
366 type
= sha1_object_info(oid
->hash
, NULL
);
367 if (type
== OBJ_COMMIT
) {
368 struct commit
*commit
= lookup_commit(oid
);
370 struct pretty_print_context pp
= {0};
371 pp
.date_mode
.type
= DATE_SHORT
;
372 format_commit_message(commit
, " %ad - %s", &desc
, &pp
);
374 } else if (type
== OBJ_TAG
) {
375 struct tag
*tag
= lookup_tag(oid
);
376 if (!parse_tag(tag
) && tag
->tag
)
377 strbuf_addf(&desc
, " %s", tag
->tag
);
381 find_unique_abbrev(oid
->hash
, DEFAULT_ABBREV
),
382 typename(type
) ? typename(type
) : "unknown type",
385 strbuf_release(&desc
);
389 static int get_short_oid(const char *name
, int len
, struct object_id
*oid
,
393 struct disambiguate_state ds
;
394 int quietly
= !!(flags
& GET_OID_QUIETLY
);
396 if (init_object_disambiguation(name
, len
, &ds
) < 0)
399 if (HAS_MULTI_BITS(flags
& GET_OID_DISAMBIGUATORS
))
400 die("BUG: multiple get_short_oid disambiguator flags");
402 if (flags
& GET_OID_COMMIT
)
403 ds
.fn
= disambiguate_commit_only
;
404 else if (flags
& GET_OID_COMMITTISH
)
405 ds
.fn
= disambiguate_committish_only
;
406 else if (flags
& GET_OID_TREE
)
407 ds
.fn
= disambiguate_tree_only
;
408 else if (flags
& GET_OID_TREEISH
)
409 ds
.fn
= disambiguate_treeish_only
;
410 else if (flags
& GET_OID_BLOB
)
411 ds
.fn
= disambiguate_blob_only
;
413 ds
.fn
= default_disambiguate_hint
;
415 find_short_object_filename(&ds
);
416 find_short_packed_object(&ds
);
417 status
= finish_object_disambiguation(&ds
, oid
);
419 if (!quietly
&& (status
== SHORT_NAME_AMBIGUOUS
)) {
420 error(_("short SHA1 %s is ambiguous"), ds
.hex_pfx
);
423 * We may still have ambiguity if we simply saw a series of
424 * candidates that did not satisfy our hint function. In
425 * that case, we still want to show them, so disable the hint
431 advise(_("The candidates are:"));
432 for_each_abbrev(ds
.hex_pfx
, show_ambiguous_object
, &ds
);
438 static int collect_ambiguous(const struct object_id
*oid
, void *data
)
440 oid_array_append(data
, oid
);
444 int for_each_abbrev(const char *prefix
, each_abbrev_fn fn
, void *cb_data
)
446 struct oid_array collect
= OID_ARRAY_INIT
;
447 struct disambiguate_state ds
;
450 if (init_object_disambiguation(prefix
, strlen(prefix
), &ds
) < 0)
453 ds
.always_call_fn
= 1;
454 ds
.fn
= collect_ambiguous
;
455 ds
.cb_data
= &collect
;
456 find_short_object_filename(&ds
);
457 find_short_packed_object(&ds
);
459 ret
= oid_array_for_each_unique(&collect
, fn
, cb_data
);
460 oid_array_clear(&collect
);
465 * Return the slot of the most-significant bit set in "val". There are various
466 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
467 * probably not a big deal here.
469 static unsigned msb(unsigned long val
)
477 struct min_abbrev_data
{
478 unsigned int init_len
;
479 unsigned int cur_len
;
483 static inline char get_hex_char_from_oid(const struct object_id
*oid
,
486 static const char hex
[] = "0123456789abcdef";
489 return hex
[oid
->hash
[pos
>> 1] >> 4];
491 return hex
[oid
->hash
[pos
>> 1] & 0xf];
494 static int extend_abbrev_len(const struct object_id
*oid
, void *cb_data
)
496 struct min_abbrev_data
*mad
= cb_data
;
498 unsigned int i
= mad
->init_len
;
499 while (mad
->hex
[i
] && mad
->hex
[i
] == get_hex_char_from_oid(oid
, i
))
502 if (i
< GIT_MAX_RAWSZ
&& i
>= mad
->cur_len
)
503 mad
->cur_len
= i
+ 1;
508 int find_unique_abbrev_r(char *hex
, const unsigned char *sha1
, int len
)
510 struct disambiguate_state ds
;
511 struct min_abbrev_data mad
;
512 struct object_id oid_ret
;
514 unsigned long count
= approximate_object_count();
516 * Add one because the MSB only tells us the highest bit set,
517 * not including the value of all the _other_ bits (so "15"
518 * is only one off of 2^4, but the MSB is the 3rd bit.
520 len
= msb(count
) + 1;
522 * We now know we have on the order of 2^len objects, which
523 * expects a collision at 2^(len/2). But we also care about hex
524 * chars, not bits, and there are 4 bits per hex. So all
525 * together we need to divide by 2 and round up.
527 len
= DIV_ROUND_UP(len
, 2);
529 * For very small repos, we stick with our regular fallback.
531 if (len
< FALLBACK_DEFAULT_ABBREV
)
532 len
= FALLBACK_DEFAULT_ABBREV
;
535 sha1_to_hex_r(hex
, sha1
);
536 if (len
== GIT_SHA1_HEXSZ
|| !len
)
537 return GIT_SHA1_HEXSZ
;
539 if (init_object_disambiguation(hex
, len
, &ds
) < 0)
546 ds
.fn
= extend_abbrev_len
;
547 ds
.always_call_fn
= 1;
548 ds
.cb_data
= (void *)&mad
;
550 find_short_object_filename(&ds
);
551 find_short_packed_object(&ds
);
552 (void)finish_object_disambiguation(&ds
, &oid_ret
);
554 hex
[mad
.cur_len
] = 0;
558 const char *find_unique_abbrev(const unsigned char *sha1
, int len
)
561 static char hexbuffer
[4][GIT_MAX_HEXSZ
+ 1];
562 char *hex
= hexbuffer
[bufno
];
563 bufno
= (bufno
+ 1) % ARRAY_SIZE(hexbuffer
);
564 find_unique_abbrev_r(hex
, sha1
, len
);
568 static int ambiguous_path(const char *path
, int len
)
573 for (cnt
= 0; cnt
< len
; cnt
++) {
593 static inline int at_mark(const char *string
, int len
,
594 const char **suffix
, int nr
)
598 for (i
= 0; i
< nr
; i
++) {
599 int suffix_len
= strlen(suffix
[i
]);
600 if (suffix_len
<= len
601 && !strncasecmp(string
, suffix
[i
], suffix_len
))
607 static inline int upstream_mark(const char *string
, int len
)
609 const char *suffix
[] = { "@{upstream}", "@{u}" };
610 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
613 static inline int push_mark(const char *string
, int len
)
615 const char *suffix
[] = { "@{push}" };
616 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
619 static int get_oid_1(const char *name
, int len
, struct object_id
*oid
, unsigned lookup_flags
);
620 static int interpret_nth_prior_checkout(const char *name
, int namelen
, struct strbuf
*buf
);
622 static int get_oid_basic(const char *str
, int len
, struct object_id
*oid
,
625 static const char *warn_msg
= "refname '%.*s' is ambiguous.";
626 static const char *object_name_msg
= N_(
627 "Git normally never creates a ref that ends with 40 hex characters\n"
628 "because it will be ignored when you just specify 40-hex. These refs\n"
629 "may be created by mistake. For example,\n"
631 " git checkout -b $br $(git rev-parse ...)\n"
633 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
634 "examine these refs and maybe delete them. Turn this message off by\n"
635 "running \"git config advice.objectNameWarning false\"");
636 struct object_id tmp_oid
;
637 char *real_ref
= NULL
;
639 int at
, reflog_len
, nth_prior
= 0;
641 if (len
== GIT_SHA1_HEXSZ
&& !get_oid_hex(str
, oid
)) {
642 if (warn_ambiguous_refs
&& warn_on_object_refname_ambiguity
) {
643 refs_found
= dwim_ref(str
, len
, tmp_oid
.hash
, &real_ref
);
644 if (refs_found
> 0) {
645 warning(warn_msg
, len
, str
);
646 if (advice_object_name_warning
)
647 fprintf(stderr
, "%s\n", _(object_name_msg
));
654 /* basic@{time or number or -number} format to query ref-log */
656 if (len
&& str
[len
-1] == '}') {
657 for (at
= len
-4; at
>= 0; at
--) {
658 if (str
[at
] == '@' && str
[at
+1] == '{') {
659 if (str
[at
+2] == '-') {
661 /* @{-N} not at start */
666 if (!upstream_mark(str
+ at
, len
- at
) &&
667 !push_mark(str
+ at
, len
- at
)) {
668 reflog_len
= (len
-1) - (at
+2);
676 /* Accept only unambiguous ref paths. */
677 if (len
&& ambiguous_path(str
, len
))
681 struct strbuf buf
= STRBUF_INIT
;
684 if (interpret_nth_prior_checkout(str
, len
, &buf
) > 0) {
685 detached
= (buf
.len
== GIT_SHA1_HEXSZ
&& !get_oid_hex(buf
.buf
, oid
));
686 strbuf_release(&buf
);
692 if (!len
&& reflog_len
)
693 /* allow "@{...}" to mean the current branch reflog */
694 refs_found
= dwim_ref("HEAD", 4, oid
->hash
, &real_ref
);
696 refs_found
= dwim_log(str
, len
, oid
->hash
, &real_ref
);
698 refs_found
= dwim_ref(str
, len
, oid
->hash
, &real_ref
);
703 if (warn_ambiguous_refs
&& !(flags
& GET_OID_QUIETLY
) &&
705 !get_short_oid(str
, len
, &tmp_oid
, GET_OID_QUIETLY
)))
706 warning(warn_msg
, len
, str
);
714 /* Is it asking for N-th entry, or approxidate? */
715 for (i
= nth
= 0; 0 <= nth
&& i
< reflog_len
; i
++) {
716 char ch
= str
[at
+2+i
];
717 if ('0' <= ch
&& ch
<= '9')
718 nth
= nth
* 10 + ch
- '0';
722 if (100000000 <= nth
) {
729 char *tmp
= xstrndup(str
+ at
+ 2, reflog_len
);
730 at_time
= approxidate_careful(tmp
, &errors
);
737 if (read_ref_at(real_ref
, flags
, at_time
, nth
, oid
->hash
, NULL
,
738 &co_time
, &co_tz
, &co_cnt
)) {
740 if (starts_with(real_ref
, "refs/heads/")) {
742 len
= strlen(real_ref
+ 11);
750 if (!(flags
& GET_OID_QUIETLY
)) {
751 warning("Log for '%.*s' only goes "
752 "back to %s.", len
, str
,
753 show_date(co_time
, co_tz
, DATE_MODE(RFC2822
)));
756 if (flags
& GET_OID_QUIETLY
) {
759 die("Log for '%.*s' only has %d entries.",
769 static int get_parent(const char *name
, int len
,
770 struct object_id
*result
, int idx
)
772 struct object_id oid
;
773 int ret
= get_oid_1(name
, len
, &oid
, GET_OID_COMMITTISH
);
774 struct commit
*commit
;
775 struct commit_list
*p
;
779 commit
= lookup_commit_reference(&oid
);
780 if (parse_commit(commit
))
783 oidcpy(result
, &commit
->object
.oid
);
789 oidcpy(result
, &p
->item
->object
.oid
);
797 static int get_nth_ancestor(const char *name
, int len
,
798 struct object_id
*result
, int generation
)
800 struct object_id oid
;
801 struct commit
*commit
;
804 ret
= get_oid_1(name
, len
, &oid
, GET_OID_COMMITTISH
);
807 commit
= lookup_commit_reference(&oid
);
811 while (generation
--) {
812 if (parse_commit(commit
) || !commit
->parents
)
814 commit
= commit
->parents
->item
;
816 oidcpy(result
, &commit
->object
.oid
);
820 struct object
*peel_to_type(const char *name
, int namelen
,
821 struct object
*o
, enum object_type expected_type
)
823 if (name
&& !namelen
)
824 namelen
= strlen(name
);
826 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
828 if (expected_type
== OBJ_ANY
|| o
->type
== expected_type
)
830 if (o
->type
== OBJ_TAG
)
831 o
= ((struct tag
*) o
)->tagged
;
832 else if (o
->type
== OBJ_COMMIT
)
833 o
= &(((struct commit
*) o
)->tree
->object
);
836 error("%.*s: expected %s type, but the object "
837 "dereferences to %s type",
838 namelen
, name
, typename(expected_type
),
845 static int peel_onion(const char *name
, int len
, struct object_id
*oid
,
846 unsigned lookup_flags
)
848 struct object_id outer
;
850 unsigned int expected_type
= 0;
854 * "ref^{type}" dereferences ref repeatedly until you cannot
855 * dereference anymore, or you get an object of given type,
856 * whichever comes first. "ref^{}" means just dereference
857 * tags until you get a non-tag. "ref^0" is a shorthand for
858 * "ref^{commit}". "commit^{tree}" could be used to find the
859 * top-level tree of the given commit.
861 if (len
< 4 || name
[len
-1] != '}')
864 for (sp
= name
+ len
- 1; name
<= sp
; sp
--) {
866 if (ch
== '{' && name
< sp
&& sp
[-1] == '^')
872 sp
++; /* beginning of type name, or closing brace for empty */
873 if (starts_with(sp
, "commit}"))
874 expected_type
= OBJ_COMMIT
;
875 else if (starts_with(sp
, "tag}"))
876 expected_type
= OBJ_TAG
;
877 else if (starts_with(sp
, "tree}"))
878 expected_type
= OBJ_TREE
;
879 else if (starts_with(sp
, "blob}"))
880 expected_type
= OBJ_BLOB
;
881 else if (starts_with(sp
, "object}"))
882 expected_type
= OBJ_ANY
;
883 else if (sp
[0] == '}')
884 expected_type
= OBJ_NONE
;
885 else if (sp
[0] == '/')
886 expected_type
= OBJ_COMMIT
;
890 lookup_flags
&= ~GET_OID_DISAMBIGUATORS
;
891 if (expected_type
== OBJ_COMMIT
)
892 lookup_flags
|= GET_OID_COMMITTISH
;
893 else if (expected_type
== OBJ_TREE
)
894 lookup_flags
|= GET_OID_TREEISH
;
896 if (get_oid_1(name
, sp
- name
- 2, &outer
, lookup_flags
))
899 o
= parse_object(&outer
);
902 if (!expected_type
) {
903 o
= deref_tag(o
, name
, sp
- name
- 2);
904 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
906 oidcpy(oid
, &o
->oid
);
911 * At this point, the syntax look correct, so
912 * if we do not get the needed object, we should
915 o
= peel_to_type(name
, len
, o
, expected_type
);
919 oidcpy(oid
, &o
->oid
);
921 /* "$commit^{/foo}" */
924 struct commit_list
*list
= NULL
;
927 * $commit^{/}. Some regex implementation may reject.
928 * We don't need regex anyway. '' pattern always matches.
933 prefix
= xstrndup(sp
+ 1, name
+ len
- 1 - (sp
+ 1));
934 commit_list_insert((struct commit
*)o
, &list
);
935 ret
= get_oid_oneline(prefix
, oid
, list
);
942 static int get_describe_name(const char *name
, int len
, struct object_id
*oid
)
945 unsigned flags
= GET_OID_QUIETLY
| GET_OID_COMMIT
;
947 for (cp
= name
+ len
- 1; name
+ 2 <= cp
; cp
--) {
950 /* We must be looking at g in "SOMETHING-g"
951 * for it to be describe output.
953 if (ch
== 'g' && cp
[-1] == '-') {
956 return get_short_oid(cp
, len
, oid
, flags
);
963 static int get_oid_1(const char *name
, int len
, struct object_id
*oid
, unsigned lookup_flags
)
969 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
972 for (cp
= name
+ len
- 1; name
<= cp
; cp
--) {
974 if ('0' <= ch
&& ch
<= '9')
976 if (ch
== '~' || ch
== '^')
983 int len1
= cp
- name
;
985 while (cp
< name
+ len
)
986 num
= num
* 10 + *cp
++ - '0';
987 if (!num
&& len1
== len
- 1)
989 if (has_suffix
== '^')
990 return get_parent(name
, len1
, oid
, num
);
991 /* else if (has_suffix == '~') -- goes without saying */
992 return get_nth_ancestor(name
, len1
, oid
, num
);
995 ret
= peel_onion(name
, len
, oid
, lookup_flags
);
999 ret
= get_oid_basic(name
, len
, oid
, lookup_flags
);
1003 /* It could be describe output that is "SOMETHING-gXXXX" */
1004 ret
= get_describe_name(name
, len
, oid
);
1008 return get_short_oid(name
, len
, oid
, lookup_flags
);
1012 * This interprets names like ':/Initial revision of "git"' by searching
1013 * through history and returning the first commit whose message starts
1014 * the given regular expression.
1016 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
1018 * For a literal '!' character at the beginning of a pattern, you have to repeat
1019 * that, like: ':/!!foo'
1021 * For future extension, all other sequences beginning with ':/!' are reserved.
1024 /* Remember to update object flag allocation in object.h */
1025 #define ONELINE_SEEN (1u<<20)
1027 static int handle_one_ref(const char *path
, const struct object_id
*oid
,
1028 int flag
, void *cb_data
)
1030 struct commit_list
**list
= cb_data
;
1031 struct object
*object
= parse_object(oid
);
1034 if (object
->type
== OBJ_TAG
) {
1035 object
= deref_tag(object
, path
, strlen(path
));
1039 if (object
->type
!= OBJ_COMMIT
)
1041 commit_list_insert((struct commit
*)object
, list
);
1045 static int get_oid_oneline(const char *prefix
, struct object_id
*oid
,
1046 struct commit_list
*list
)
1048 struct commit_list
*backup
= NULL
, *l
;
1053 if (prefix
[0] == '!') {
1056 if (prefix
[0] == '-') {
1059 } else if (prefix
[0] != '!') {
1064 if (regcomp(®ex
, prefix
, REG_EXTENDED
))
1067 for (l
= list
; l
; l
= l
->next
) {
1068 l
->item
->object
.flags
|= ONELINE_SEEN
;
1069 commit_list_insert(l
->item
, &backup
);
1072 const char *p
, *buf
;
1073 struct commit
*commit
;
1076 commit
= pop_most_recent_commit(&list
, ONELINE_SEEN
);
1077 if (!parse_object(&commit
->object
.oid
))
1079 buf
= get_commit_buffer(commit
, NULL
);
1080 p
= strstr(buf
, "\n\n");
1081 matches
= negative
^ (p
&& !regexec(®ex
, p
+ 2, 0, NULL
, 0));
1082 unuse_commit_buffer(commit
, buf
);
1085 oidcpy(oid
, &commit
->object
.oid
);
1091 free_commit_list(list
);
1092 for (l
= backup
; l
; l
= l
->next
)
1093 clear_commit_marks(l
->item
, ONELINE_SEEN
);
1094 free_commit_list(backup
);
1095 return found
? 0 : -1;
1098 struct grab_nth_branch_switch_cbdata
{
1103 static int grab_nth_branch_switch(struct object_id
*ooid
, struct object_id
*noid
,
1104 const char *email
, timestamp_t timestamp
, int tz
,
1105 const char *message
, void *cb_data
)
1107 struct grab_nth_branch_switch_cbdata
*cb
= cb_data
;
1108 const char *match
= NULL
, *target
= NULL
;
1111 if (skip_prefix(message
, "checkout: moving from ", &match
))
1112 target
= strstr(match
, " to ");
1114 if (!match
|| !target
)
1116 if (--(cb
->remaining
) == 0) {
1117 len
= target
- match
;
1118 strbuf_reset(&cb
->buf
);
1119 strbuf_add(&cb
->buf
, match
, len
);
1120 return 1; /* we are done */
1126 * Parse @{-N} syntax, return the number of characters parsed
1127 * if successful; otherwise signal an error with negative value.
1129 static int interpret_nth_prior_checkout(const char *name
, int namelen
,
1134 struct grab_nth_branch_switch_cbdata cb
;
1140 if (name
[0] != '@' || name
[1] != '{' || name
[2] != '-')
1142 brace
= memchr(name
, '}', namelen
);
1145 nth
= strtol(name
+ 3, &num_end
, 10);
1146 if (num_end
!= brace
)
1151 strbuf_init(&cb
.buf
, 20);
1154 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch
, &cb
)) {
1156 strbuf_addbuf(buf
, &cb
.buf
);
1157 retval
= brace
- name
+ 1;
1160 strbuf_release(&cb
.buf
);
1164 int get_oid_mb(const char *name
, struct object_id
*oid
)
1166 struct commit
*one
, *two
;
1167 struct commit_list
*mbs
;
1168 struct object_id oid_tmp
;
1172 dots
= strstr(name
, "...");
1174 return get_oid(name
, oid
);
1176 st
= get_oid("HEAD", &oid_tmp
);
1179 strbuf_init(&sb
, dots
- name
);
1180 strbuf_add(&sb
, name
, dots
- name
);
1181 st
= get_oid_committish(sb
.buf
, &oid_tmp
);
1182 strbuf_release(&sb
);
1186 one
= lookup_commit_reference_gently(&oid_tmp
, 0);
1190 if (get_oid_committish(dots
[3] ? (dots
+ 3) : "HEAD", &oid_tmp
))
1192 two
= lookup_commit_reference_gently(&oid_tmp
, 0);
1195 mbs
= get_merge_bases(one
, two
);
1196 if (!mbs
|| mbs
->next
)
1200 oidcpy(oid
, &mbs
->item
->object
.oid
);
1202 free_commit_list(mbs
);
1206 /* parse @something syntax, when 'something' is not {.*} */
1207 static int interpret_empty_at(const char *name
, int namelen
, int len
, struct strbuf
*buf
)
1211 if (len
|| name
[1] == '{')
1214 /* make sure it's a single @, or @@{.*}, not @foo */
1215 next
= memchr(name
+ len
+ 1, '@', namelen
- len
- 1);
1216 if (next
&& next
[1] != '{')
1219 next
= name
+ namelen
;
1220 if (next
!= name
+ 1)
1224 strbuf_add(buf
, "HEAD", 4);
1228 static int reinterpret(const char *name
, int namelen
, int len
,
1229 struct strbuf
*buf
, unsigned allowed
)
1231 /* we have extra data, which might need further processing */
1232 struct strbuf tmp
= STRBUF_INIT
;
1233 int used
= buf
->len
;
1236 strbuf_add(buf
, name
+ len
, namelen
- len
);
1237 ret
= interpret_branch_name(buf
->buf
, buf
->len
, &tmp
, allowed
);
1238 /* that data was not interpreted, remove our cruft */
1240 strbuf_setlen(buf
, used
);
1244 strbuf_addbuf(buf
, &tmp
);
1245 strbuf_release(&tmp
);
1246 /* tweak for size of {-N} versus expanded ref name */
1247 return ret
- used
+ len
;
1250 static void set_shortened_ref(struct strbuf
*buf
, const char *ref
)
1252 char *s
= shorten_unambiguous_ref(ref
, 0);
1254 strbuf_addstr(buf
, s
);
1258 static int branch_interpret_allowed(const char *refname
, unsigned allowed
)
1263 if ((allowed
& INTERPRET_BRANCH_LOCAL
) &&
1264 starts_with(refname
, "refs/heads/"))
1266 if ((allowed
& INTERPRET_BRANCH_REMOTE
) &&
1267 starts_with(refname
, "refs/remotes/"))
1273 static int interpret_branch_mark(const char *name
, int namelen
,
1274 int at
, struct strbuf
*buf
,
1275 int (*get_mark
)(const char *, int),
1276 const char *(*get_data
)(struct branch
*,
1281 struct branch
*branch
;
1282 struct strbuf err
= STRBUF_INIT
;
1285 len
= get_mark(name
+ at
, namelen
- at
);
1289 if (memchr(name
, ':', at
))
1293 char *name_str
= xmemdupz(name
, at
);
1294 branch
= branch_get(name_str
);
1297 branch
= branch_get(NULL
);
1299 value
= get_data(branch
, &err
);
1303 if (!branch_interpret_allowed(value
, allowed
))
1306 set_shortened_ref(buf
, value
);
1310 int interpret_branch_name(const char *name
, int namelen
, struct strbuf
*buf
,
1318 namelen
= strlen(name
);
1320 if (!allowed
|| (allowed
& INTERPRET_BRANCH_LOCAL
)) {
1321 len
= interpret_nth_prior_checkout(name
, namelen
, buf
);
1323 return len
; /* syntax Ok, not enough switches */
1324 } else if (len
> 0) {
1326 return len
; /* consumed all */
1328 return reinterpret(name
, namelen
, len
, buf
, allowed
);
1333 (at
= memchr(start
, '@', namelen
- (start
- name
)));
1336 if (!allowed
|| (allowed
& INTERPRET_BRANCH_HEAD
)) {
1337 len
= interpret_empty_at(name
, namelen
, at
- name
, buf
);
1339 return reinterpret(name
, namelen
, len
, buf
,
1343 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1344 upstream_mark
, branch_get_upstream
,
1349 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1350 push_mark
, branch_get_push
,
1359 void strbuf_branchname(struct strbuf
*sb
, const char *name
, unsigned allowed
)
1361 int len
= strlen(name
);
1362 int used
= interpret_branch_name(name
, len
, sb
, allowed
);
1366 strbuf_add(sb
, name
+ used
, len
- used
);
1369 int strbuf_check_branch_ref(struct strbuf
*sb
, const char *name
)
1371 strbuf_branchname(sb
, name
, INTERPRET_BRANCH_LOCAL
);
1374 strbuf_splice(sb
, 0, 0, "refs/heads/", 11);
1375 return check_refname_format(sb
->buf
, 0);
1379 * This is like "get_oid_basic()", except it allows "object ID expressions",
1380 * notably "xyz^" for "parent of xyz"
1382 int get_oid(const char *name
, struct object_id
*oid
)
1384 struct object_context unused
;
1385 return get_oid_with_context(name
, 0, oid
, &unused
);
1390 * Many callers know that the user meant to name a commit-ish by
1391 * syntactical positions where the object name appears. Calling this
1392 * function allows the machinery to disambiguate shorter-than-unique
1393 * abbreviated object names between commit-ish and others.
1395 * Note that this does NOT error out when the named object is not a
1396 * commit-ish. It is merely to give a hint to the disambiguation
1399 int get_oid_committish(const char *name
, struct object_id
*oid
)
1401 struct object_context unused
;
1402 return get_oid_with_context(name
, GET_OID_COMMITTISH
,
1406 int get_oid_treeish(const char *name
, struct object_id
*oid
)
1408 struct object_context unused
;
1409 return get_oid_with_context(name
, GET_OID_TREEISH
,
1413 int get_oid_commit(const char *name
, struct object_id
*oid
)
1415 struct object_context unused
;
1416 return get_oid_with_context(name
, GET_OID_COMMIT
,
1420 int get_oid_tree(const char *name
, struct object_id
*oid
)
1422 struct object_context unused
;
1423 return get_oid_with_context(name
, GET_OID_TREE
,
1427 int get_oid_blob(const char *name
, struct object_id
*oid
)
1429 struct object_context unused
;
1430 return get_oid_with_context(name
, GET_OID_BLOB
,
1434 /* Must be called only when object_name:filename doesn't exist. */
1435 static void diagnose_invalid_oid_path(const char *prefix
,
1436 const char *filename
,
1437 const struct object_id
*tree_oid
,
1438 const char *object_name
,
1439 int object_name_len
)
1441 struct object_id oid
;
1447 if (file_exists(filename
))
1448 die("Path '%s' exists on disk, but not in '%.*s'.",
1449 filename
, object_name_len
, object_name
);
1450 if (is_missing_file_error(errno
)) {
1451 char *fullname
= xstrfmt("%s%s", prefix
, filename
);
1453 if (!get_tree_entry(tree_oid
->hash
, fullname
,
1455 die("Path '%s' exists, but not '%s'.\n"
1456 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1459 object_name_len
, object_name
,
1461 object_name_len
, object_name
,
1464 die("Path '%s' does not exist in '%.*s'",
1465 filename
, object_name_len
, object_name
);
1469 /* Must be called only when :stage:filename doesn't exist. */
1470 static void diagnose_invalid_index_path(int stage
,
1472 const char *filename
)
1474 const struct cache_entry
*ce
;
1476 unsigned namelen
= strlen(filename
);
1477 struct strbuf fullname
= STRBUF_INIT
;
1482 /* Wrong stage number? */
1483 pos
= cache_name_pos(filename
, namelen
);
1486 if (pos
< active_nr
) {
1487 ce
= active_cache
[pos
];
1488 if (ce_namelen(ce
) == namelen
&&
1489 !memcmp(ce
->name
, filename
, namelen
))
1490 die("Path '%s' is in the index, but not at stage %d.\n"
1491 "Did you mean ':%d:%s'?",
1493 ce_stage(ce
), filename
);
1496 /* Confusion between relative and absolute filenames? */
1497 strbuf_addstr(&fullname
, prefix
);
1498 strbuf_addstr(&fullname
, filename
);
1499 pos
= cache_name_pos(fullname
.buf
, fullname
.len
);
1502 if (pos
< active_nr
) {
1503 ce
= active_cache
[pos
];
1504 if (ce_namelen(ce
) == fullname
.len
&&
1505 !memcmp(ce
->name
, fullname
.buf
, fullname
.len
))
1506 die("Path '%s' is in the index, but not '%s'.\n"
1507 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1508 fullname
.buf
, filename
,
1509 ce_stage(ce
), fullname
.buf
,
1510 ce_stage(ce
), filename
);
1513 if (file_exists(filename
))
1514 die("Path '%s' exists on disk, but not in the index.", filename
);
1515 if (is_missing_file_error(errno
))
1516 die("Path '%s' does not exist (neither on disk nor in the index).",
1519 strbuf_release(&fullname
);
1523 static char *resolve_relative_path(const char *rel
)
1525 if (!starts_with(rel
, "./") && !starts_with(rel
, "../"))
1528 if (!is_inside_work_tree())
1529 die("relative path syntax can't be used outside working tree.");
1531 /* die() inside prefix_path() if resolved path is outside worktree */
1532 return prefix_path(startup_info
->prefix
,
1533 startup_info
->prefix
? strlen(startup_info
->prefix
) : 0,
1537 static int get_oid_with_context_1(const char *name
,
1540 struct object_id
*oid
,
1541 struct object_context
*oc
)
1543 int ret
, bracket_depth
;
1544 int namelen
= strlen(name
);
1546 int only_to_die
= flags
& GET_OID_ONLY_TO_DIE
;
1549 flags
|= GET_OID_QUIETLY
;
1551 memset(oc
, 0, sizeof(*oc
));
1552 oc
->mode
= S_IFINVALID
;
1553 strbuf_init(&oc
->symlink_path
, 0);
1554 ret
= get_oid_1(name
, namelen
, oid
, flags
);
1558 * sha1:path --> object name of path in ent sha1
1559 * :path -> object name of absolute path in index
1560 * :./path -> object name of path relative to cwd in index
1561 * :[0-3]:path -> object name of path in index at stage
1562 * :/foo -> recent commit matching foo
1564 if (name
[0] == ':') {
1566 const struct cache_entry
*ce
;
1567 char *new_path
= NULL
;
1569 if (!only_to_die
&& namelen
> 2 && name
[1] == '/') {
1570 struct commit_list
*list
= NULL
;
1572 for_each_ref(handle_one_ref
, &list
);
1573 commit_list_sort_by_date(&list
);
1574 return get_oid_oneline(name
+ 2, oid
, list
);
1578 name
[1] < '0' || '3' < name
[1])
1581 stage
= name
[1] - '0';
1584 new_path
= resolve_relative_path(cp
);
1586 namelen
= namelen
- (cp
- name
);
1589 namelen
= strlen(cp
);
1592 if (flags
& GET_OID_RECORD_PATH
)
1593 oc
->path
= xstrdup(cp
);
1597 pos
= cache_name_pos(cp
, namelen
);
1600 while (pos
< active_nr
) {
1601 ce
= active_cache
[pos
];
1602 if (ce_namelen(ce
) != namelen
||
1603 memcmp(ce
->name
, cp
, namelen
))
1605 if (ce_stage(ce
) == stage
) {
1606 oidcpy(oid
, &ce
->oid
);
1607 oc
->mode
= ce
->ce_mode
;
1613 if (only_to_die
&& name
[1] && name
[1] != '/')
1614 diagnose_invalid_index_path(stage
, prefix
, cp
);
1618 for (cp
= name
, bracket_depth
= 0; *cp
; cp
++) {
1621 else if (bracket_depth
&& *cp
== '}')
1623 else if (!bracket_depth
&& *cp
== ':')
1627 struct object_id tree_oid
;
1628 int len
= cp
- name
;
1629 unsigned sub_flags
= flags
;
1631 sub_flags
&= ~GET_OID_DISAMBIGUATORS
;
1632 sub_flags
|= GET_OID_TREEISH
;
1634 if (!get_oid_1(name
, len
, &tree_oid
, sub_flags
)) {
1635 const char *filename
= cp
+1;
1636 char *new_filename
= NULL
;
1638 new_filename
= resolve_relative_path(filename
);
1640 filename
= new_filename
;
1641 if (flags
& GET_OID_FOLLOW_SYMLINKS
) {
1642 ret
= get_tree_entry_follow_symlinks(tree_oid
.hash
,
1643 filename
, oid
->hash
, &oc
->symlink_path
,
1646 ret
= get_tree_entry(tree_oid
.hash
, filename
,
1647 oid
->hash
, &oc
->mode
);
1648 if (ret
&& only_to_die
) {
1649 diagnose_invalid_oid_path(prefix
,
1655 hashcpy(oc
->tree
, tree_oid
.hash
);
1656 if (flags
& GET_OID_RECORD_PATH
)
1657 oc
->path
= xstrdup(filename
);
1663 die("Invalid object name '%.*s'.", len
, name
);
1670 * Call this function when you know "name" given by the end user must
1671 * name an object but it doesn't; the function _may_ die with a better
1672 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1673 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1674 * you have a chance to diagnose the error further.
1676 void maybe_die_on_misspelt_object_name(const char *name
, const char *prefix
)
1678 struct object_context oc
;
1679 struct object_id oid
;
1680 get_oid_with_context_1(name
, GET_OID_ONLY_TO_DIE
, prefix
, &oid
, &oc
);
1683 int get_oid_with_context(const char *str
, unsigned flags
, struct object_id
*oid
, struct object_context
*oc
)
1685 if (flags
& GET_OID_FOLLOW_SYMLINKS
&& flags
& GET_OID_ONLY_TO_DIE
)
1686 die("BUG: incompatible flags for get_sha1_with_context");
1687 return get_oid_with_context_1(str
, flags
, NULL
, oid
, oc
);