10 #include "sha1-array.h"
12 static int get_sha1_oneline(const char *, unsigned char *, struct commit_list
*);
14 typedef int (*disambiguate_hint_fn
)(const struct object_id
*, void *);
16 struct disambiguate_state
{
17 int len
; /* length of prefix in hex chars */
18 char hex_pfx
[GIT_MAX_HEXSZ
+ 1];
19 struct object_id bin_pfx
;
21 disambiguate_hint_fn fn
;
23 struct object_id candidate
;
24 unsigned candidate_exists
:1;
25 unsigned candidate_checked
:1;
26 unsigned candidate_ok
:1;
27 unsigned disambiguate_fn_used
:1;
29 unsigned always_call_fn
:1;
32 static void update_candidates(struct disambiguate_state
*ds
, const struct object_id
*current
)
34 if (ds
->always_call_fn
) {
35 ds
->ambiguous
= ds
->fn(current
, ds
->cb_data
) ? 1 : 0;
38 if (!ds
->candidate_exists
) {
39 /* this is the first candidate */
40 oidcpy(&ds
->candidate
, current
);
41 ds
->candidate_exists
= 1;
43 } else if (!oidcmp(&ds
->candidate
, current
)) {
44 /* the same as what we already have seen */
49 /* cannot disambiguate between ds->candidate and current */
54 if (!ds
->candidate_checked
) {
55 ds
->candidate_ok
= ds
->fn(&ds
->candidate
, ds
->cb_data
);
56 ds
->disambiguate_fn_used
= 1;
57 ds
->candidate_checked
= 1;
60 if (!ds
->candidate_ok
) {
61 /* discard the candidate; we know it does not satisfy fn */
62 oidcpy(&ds
->candidate
, current
);
63 ds
->candidate_checked
= 0;
67 /* if we reach this point, we know ds->candidate satisfies fn */
68 if (ds
->fn(current
, ds
->cb_data
)) {
70 * if both current and candidate satisfy fn, we cannot
77 /* otherwise, current can be discarded and candidate is still good */
80 static void find_short_object_filename(struct disambiguate_state
*ds
)
82 struct alternate_object_database
*alt
;
83 char hex
[GIT_MAX_HEXSZ
];
84 static struct alternate_object_database
*fakeent
;
88 * Create a "fake" alternate object database that
89 * points to our own object database, to make it
90 * easier to get a temporary working space in
91 * alt->name/alt->base while iterating over the
92 * object databases including our own.
94 fakeent
= alloc_alt_odb(get_object_directory());
96 fakeent
->next
= alt_odb_list
;
98 xsnprintf(hex
, sizeof(hex
), "%.2s", ds
->hex_pfx
);
99 for (alt
= fakeent
; alt
&& !ds
->ambiguous
; alt
= alt
->next
) {
100 struct strbuf
*buf
= alt_scratch_buf(alt
);
104 strbuf_addf(buf
, "%.2s/", ds
->hex_pfx
);
105 dir
= opendir(buf
->buf
);
109 while (!ds
->ambiguous
&& (de
= readdir(dir
)) != NULL
) {
110 struct object_id oid
;
112 if (strlen(de
->d_name
) != GIT_SHA1_HEXSZ
- 2)
114 if (memcmp(de
->d_name
, ds
->hex_pfx
+ 2, ds
->len
- 2))
116 memcpy(hex
+ 2, de
->d_name
, GIT_SHA1_HEXSZ
- 2);
117 if (!get_oid_hex(hex
, &oid
))
118 update_candidates(ds
, &oid
);
124 static int match_sha(unsigned len
, const unsigned char *a
, const unsigned char *b
)
134 if ((*a
^ *b
) & 0xf0)
139 static void unique_in_pack(struct packed_git
*p
,
140 struct disambiguate_state
*ds
)
142 uint32_t num
, last
, i
, first
= 0;
143 const struct object_id
*current
= NULL
;
146 num
= p
->num_objects
;
148 while (first
< last
) {
149 uint32_t mid
= (first
+ last
) / 2;
150 const unsigned char *current
;
153 current
= nth_packed_object_sha1(p
, mid
);
154 cmp
= hashcmp(ds
->bin_pfx
.hash
, current
);
167 * At this point, "first" is the location of the lowest object
168 * with an object name that could match "bin_pfx". See if we have
169 * 0, 1 or more objects that actually match(es).
171 for (i
= first
; i
< num
&& !ds
->ambiguous
; i
++) {
172 struct object_id oid
;
173 current
= nth_packed_object_oid(&oid
, p
, i
);
174 if (!match_sha(ds
->len
, ds
->bin_pfx
.hash
, current
->hash
))
176 update_candidates(ds
, current
);
180 static void find_short_packed_object(struct disambiguate_state
*ds
)
182 struct packed_git
*p
;
184 prepare_packed_git();
185 for (p
= packed_git
; p
&& !ds
->ambiguous
; p
= p
->next
)
186 unique_in_pack(p
, ds
);
189 #define SHORT_NAME_NOT_FOUND (-1)
190 #define SHORT_NAME_AMBIGUOUS (-2)
192 static int finish_object_disambiguation(struct disambiguate_state
*ds
,
196 return SHORT_NAME_AMBIGUOUS
;
198 if (!ds
->candidate_exists
)
199 return SHORT_NAME_NOT_FOUND
;
201 if (!ds
->candidate_checked
)
203 * If this is the only candidate, there is no point
204 * calling the disambiguation hint callback.
206 * On the other hand, if the current candidate
207 * replaced an earlier candidate that did _not_ pass
208 * the disambiguation hint callback, then we do have
209 * more than one objects that match the short name
210 * given, so we should make sure this one matches;
211 * otherwise, if we discovered this one and the one
212 * that we previously discarded in the reverse order,
213 * we would end up showing different results in the
216 ds
->candidate_ok
= (!ds
->disambiguate_fn_used
||
217 ds
->fn(&ds
->candidate
, ds
->cb_data
));
219 if (!ds
->candidate_ok
)
220 return SHORT_NAME_AMBIGUOUS
;
222 hashcpy(sha1
, ds
->candidate
.hash
);
226 static int disambiguate_commit_only(const struct object_id
*oid
, void *cb_data_unused
)
228 int kind
= sha1_object_info(oid
->hash
, NULL
);
229 return kind
== OBJ_COMMIT
;
232 static int disambiguate_committish_only(const struct object_id
*oid
, void *cb_data_unused
)
237 kind
= sha1_object_info(oid
->hash
, NULL
);
238 if (kind
== OBJ_COMMIT
)
243 /* We need to do this the hard way... */
244 obj
= deref_tag(parse_object(oid
), NULL
, 0);
245 if (obj
&& obj
->type
== OBJ_COMMIT
)
250 static int disambiguate_tree_only(const struct object_id
*oid
, void *cb_data_unused
)
252 int kind
= sha1_object_info(oid
->hash
, NULL
);
253 return kind
== OBJ_TREE
;
256 static int disambiguate_treeish_only(const struct object_id
*oid
, void *cb_data_unused
)
261 kind
= sha1_object_info(oid
->hash
, NULL
);
262 if (kind
== OBJ_TREE
|| kind
== OBJ_COMMIT
)
267 /* We need to do this the hard way... */
268 obj
= deref_tag(parse_object(oid
), NULL
, 0);
269 if (obj
&& (obj
->type
== OBJ_TREE
|| obj
->type
== OBJ_COMMIT
))
274 static int disambiguate_blob_only(const struct object_id
*oid
, void *cb_data_unused
)
276 int kind
= sha1_object_info(oid
->hash
, NULL
);
277 return kind
== OBJ_BLOB
;
280 static disambiguate_hint_fn default_disambiguate_hint
;
282 int set_disambiguate_hint_config(const char *var
, const char *value
)
284 static const struct {
286 disambiguate_hint_fn fn
;
289 { "commit", disambiguate_commit_only
},
290 { "committish", disambiguate_committish_only
},
291 { "tree", disambiguate_tree_only
},
292 { "treeish", disambiguate_treeish_only
},
293 { "blob", disambiguate_blob_only
}
298 return config_error_nonbool(var
);
300 for (i
= 0; i
< ARRAY_SIZE(hints
); i
++) {
301 if (!strcasecmp(value
, hints
[i
].name
)) {
302 default_disambiguate_hint
= hints
[i
].fn
;
307 return error("unknown hint type for '%s': %s", var
, value
);
310 static int init_object_disambiguation(const char *name
, int len
,
311 struct disambiguate_state
*ds
)
315 if (len
< MINIMUM_ABBREV
|| len
> GIT_SHA1_HEXSZ
)
318 memset(ds
, 0, sizeof(*ds
));
320 for (i
= 0; i
< len
;i
++) {
321 unsigned char c
= name
[i
];
323 if (c
>= '0' && c
<= '9')
325 else if (c
>= 'a' && c
<= 'f')
327 else if (c
>= 'A' && c
<='F') {
336 ds
->bin_pfx
.hash
[i
>> 1] |= val
;
340 ds
->hex_pfx
[len
] = '\0';
345 static int show_ambiguous_object(const struct object_id
*oid
, void *data
)
347 const struct disambiguate_state
*ds
= data
;
348 struct strbuf desc
= STRBUF_INIT
;
352 if (ds
->fn
&& !ds
->fn(oid
, ds
->cb_data
))
355 type
= sha1_object_info(oid
->hash
, NULL
);
356 if (type
== OBJ_COMMIT
) {
357 struct commit
*commit
= lookup_commit(oid
);
359 struct pretty_print_context pp
= {0};
360 pp
.date_mode
.type
= DATE_SHORT
;
361 format_commit_message(commit
, " %ad - %s", &desc
, &pp
);
363 } else if (type
== OBJ_TAG
) {
364 struct tag
*tag
= lookup_tag(oid
);
365 if (!parse_tag(tag
) && tag
->tag
)
366 strbuf_addf(&desc
, " %s", tag
->tag
);
370 find_unique_abbrev(oid
->hash
, DEFAULT_ABBREV
),
371 typename(type
) ? typename(type
) : "unknown type",
374 strbuf_release(&desc
);
378 static int get_short_sha1(const char *name
, int len
, unsigned char *sha1
,
382 struct disambiguate_state ds
;
383 int quietly
= !!(flags
& GET_SHA1_QUIETLY
);
385 if (init_object_disambiguation(name
, len
, &ds
) < 0)
388 if (HAS_MULTI_BITS(flags
& GET_SHA1_DISAMBIGUATORS
))
389 die("BUG: multiple get_short_sha1 disambiguator flags");
391 if (flags
& GET_SHA1_COMMIT
)
392 ds
.fn
= disambiguate_commit_only
;
393 else if (flags
& GET_SHA1_COMMITTISH
)
394 ds
.fn
= disambiguate_committish_only
;
395 else if (flags
& GET_SHA1_TREE
)
396 ds
.fn
= disambiguate_tree_only
;
397 else if (flags
& GET_SHA1_TREEISH
)
398 ds
.fn
= disambiguate_treeish_only
;
399 else if (flags
& GET_SHA1_BLOB
)
400 ds
.fn
= disambiguate_blob_only
;
402 ds
.fn
= default_disambiguate_hint
;
404 find_short_object_filename(&ds
);
405 find_short_packed_object(&ds
);
406 status
= finish_object_disambiguation(&ds
, sha1
);
408 if (!quietly
&& (status
== SHORT_NAME_AMBIGUOUS
)) {
409 error(_("short SHA1 %s is ambiguous"), ds
.hex_pfx
);
412 * We may still have ambiguity if we simply saw a series of
413 * candidates that did not satisfy our hint function. In
414 * that case, we still want to show them, so disable the hint
420 advise(_("The candidates are:"));
421 for_each_abbrev(ds
.hex_pfx
, show_ambiguous_object
, &ds
);
427 static int collect_ambiguous(const struct object_id
*oid
, void *data
)
429 oid_array_append(data
, oid
);
433 int for_each_abbrev(const char *prefix
, each_abbrev_fn fn
, void *cb_data
)
435 struct oid_array collect
= OID_ARRAY_INIT
;
436 struct disambiguate_state ds
;
439 if (init_object_disambiguation(prefix
, strlen(prefix
), &ds
) < 0)
442 ds
.always_call_fn
= 1;
443 ds
.fn
= collect_ambiguous
;
444 ds
.cb_data
= &collect
;
445 find_short_object_filename(&ds
);
446 find_short_packed_object(&ds
);
448 ret
= oid_array_for_each_unique(&collect
, fn
, cb_data
);
449 oid_array_clear(&collect
);
454 * Return the slot of the most-significant bit set in "val". There are various
455 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
456 * probably not a big deal here.
458 static unsigned msb(unsigned long val
)
466 int find_unique_abbrev_r(char *hex
, const unsigned char *sha1
, int len
)
471 unsigned long count
= approximate_object_count();
473 * Add one because the MSB only tells us the highest bit set,
474 * not including the value of all the _other_ bits (so "15"
475 * is only one off of 2^4, but the MSB is the 3rd bit.
477 len
= msb(count
) + 1;
479 * We now know we have on the order of 2^len objects, which
480 * expects a collision at 2^(len/2). But we also care about hex
481 * chars, not bits, and there are 4 bits per hex. So all
482 * together we need to divide by 2; but we also want to round
483 * odd numbers up, hence adding one before dividing.
487 * For very small repos, we stick with our regular fallback.
489 if (len
< FALLBACK_DEFAULT_ABBREV
)
490 len
= FALLBACK_DEFAULT_ABBREV
;
493 sha1_to_hex_r(hex
, sha1
);
494 if (len
== 40 || !len
)
496 exists
= has_sha1_file(sha1
);
498 unsigned char sha1_ret
[20];
499 status
= get_short_sha1(hex
, len
, sha1_ret
, GET_SHA1_QUIETLY
);
502 : status
== SHORT_NAME_NOT_FOUND
) {
511 const char *find_unique_abbrev(const unsigned char *sha1
, int len
)
514 static char hexbuffer
[4][GIT_MAX_HEXSZ
+ 1];
515 char *hex
= hexbuffer
[bufno
];
516 bufno
= (bufno
+ 1) % ARRAY_SIZE(hexbuffer
);
517 find_unique_abbrev_r(hex
, sha1
, len
);
521 static int ambiguous_path(const char *path
, int len
)
526 for (cnt
= 0; cnt
< len
; cnt
++) {
546 static inline int at_mark(const char *string
, int len
,
547 const char **suffix
, int nr
)
551 for (i
= 0; i
< nr
; i
++) {
552 int suffix_len
= strlen(suffix
[i
]);
553 if (suffix_len
<= len
554 && !strncasecmp(string
, suffix
[i
], suffix_len
))
560 static inline int upstream_mark(const char *string
, int len
)
562 const char *suffix
[] = { "@{upstream}", "@{u}" };
563 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
566 static inline int push_mark(const char *string
, int len
)
568 const char *suffix
[] = { "@{push}" };
569 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
572 static int get_sha1_1(const char *name
, int len
, unsigned char *sha1
, unsigned lookup_flags
);
573 static int interpret_nth_prior_checkout(const char *name
, int namelen
, struct strbuf
*buf
);
575 static int get_sha1_basic(const char *str
, int len
, unsigned char *sha1
,
578 static const char *warn_msg
= "refname '%.*s' is ambiguous.";
579 static const char *object_name_msg
= N_(
580 "Git normally never creates a ref that ends with 40 hex characters\n"
581 "because it will be ignored when you just specify 40-hex. These refs\n"
582 "may be created by mistake. For example,\n"
584 " git checkout -b $br $(git rev-parse ...)\n"
586 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
587 "examine these refs and maybe delete them. Turn this message off by\n"
588 "running \"git config advice.objectNameWarning false\"");
589 unsigned char tmp_sha1
[20];
590 char *real_ref
= NULL
;
592 int at
, reflog_len
, nth_prior
= 0;
594 if (len
== 40 && !get_sha1_hex(str
, sha1
)) {
595 if (warn_ambiguous_refs
&& warn_on_object_refname_ambiguity
) {
596 refs_found
= dwim_ref(str
, len
, tmp_sha1
, &real_ref
);
597 if (refs_found
> 0) {
598 warning(warn_msg
, len
, str
);
599 if (advice_object_name_warning
)
600 fprintf(stderr
, "%s\n", _(object_name_msg
));
607 /* basic@{time or number or -number} format to query ref-log */
609 if (len
&& str
[len
-1] == '}') {
610 for (at
= len
-4; at
>= 0; at
--) {
611 if (str
[at
] == '@' && str
[at
+1] == '{') {
612 if (str
[at
+2] == '-') {
614 /* @{-N} not at start */
619 if (!upstream_mark(str
+ at
, len
- at
) &&
620 !push_mark(str
+ at
, len
- at
)) {
621 reflog_len
= (len
-1) - (at
+2);
629 /* Accept only unambiguous ref paths. */
630 if (len
&& ambiguous_path(str
, len
))
634 struct strbuf buf
= STRBUF_INIT
;
637 if (interpret_nth_prior_checkout(str
, len
, &buf
) > 0) {
638 detached
= (buf
.len
== 40 && !get_sha1_hex(buf
.buf
, sha1
));
639 strbuf_release(&buf
);
645 if (!len
&& reflog_len
)
646 /* allow "@{...}" to mean the current branch reflog */
647 refs_found
= dwim_ref("HEAD", 4, sha1
, &real_ref
);
649 refs_found
= dwim_log(str
, len
, sha1
, &real_ref
);
651 refs_found
= dwim_ref(str
, len
, sha1
, &real_ref
);
656 if (warn_ambiguous_refs
&& !(flags
& GET_SHA1_QUIETLY
) &&
658 !get_short_sha1(str
, len
, tmp_sha1
, GET_SHA1_QUIETLY
)))
659 warning(warn_msg
, len
, str
);
667 /* Is it asking for N-th entry, or approxidate? */
668 for (i
= nth
= 0; 0 <= nth
&& i
< reflog_len
; i
++) {
669 char ch
= str
[at
+2+i
];
670 if ('0' <= ch
&& ch
<= '9')
671 nth
= nth
* 10 + ch
- '0';
675 if (100000000 <= nth
) {
682 char *tmp
= xstrndup(str
+ at
+ 2, reflog_len
);
683 at_time
= approxidate_careful(tmp
, &errors
);
690 if (read_ref_at(real_ref
, flags
, at_time
, nth
, sha1
, NULL
,
691 &co_time
, &co_tz
, &co_cnt
)) {
693 if (starts_with(real_ref
, "refs/heads/")) {
695 len
= strlen(real_ref
+ 11);
703 if (!(flags
& GET_SHA1_QUIETLY
)) {
704 warning("Log for '%.*s' only goes "
705 "back to %s.", len
, str
,
706 show_date(co_time
, co_tz
, DATE_MODE(RFC2822
)));
709 if (flags
& GET_SHA1_QUIETLY
) {
712 die("Log for '%.*s' only has %d entries.",
722 static int get_parent(const char *name
, int len
,
723 unsigned char *result
, int idx
)
725 struct object_id oid
;
726 int ret
= get_sha1_1(name
, len
, oid
.hash
, GET_SHA1_COMMITTISH
);
727 struct commit
*commit
;
728 struct commit_list
*p
;
732 commit
= lookup_commit_reference(&oid
);
733 if (parse_commit(commit
))
736 hashcpy(result
, commit
->object
.oid
.hash
);
742 hashcpy(result
, p
->item
->object
.oid
.hash
);
750 static int get_nth_ancestor(const char *name
, int len
,
751 unsigned char *result
, int generation
)
753 struct object_id oid
;
754 struct commit
*commit
;
757 ret
= get_sha1_1(name
, len
, oid
.hash
, GET_SHA1_COMMITTISH
);
760 commit
= lookup_commit_reference(&oid
);
764 while (generation
--) {
765 if (parse_commit(commit
) || !commit
->parents
)
767 commit
= commit
->parents
->item
;
769 hashcpy(result
, commit
->object
.oid
.hash
);
773 struct object
*peel_to_type(const char *name
, int namelen
,
774 struct object
*o
, enum object_type expected_type
)
776 if (name
&& !namelen
)
777 namelen
= strlen(name
);
779 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
781 if (expected_type
== OBJ_ANY
|| o
->type
== expected_type
)
783 if (o
->type
== OBJ_TAG
)
784 o
= ((struct tag
*) o
)->tagged
;
785 else if (o
->type
== OBJ_COMMIT
)
786 o
= &(((struct commit
*) o
)->tree
->object
);
789 error("%.*s: expected %s type, but the object "
790 "dereferences to %s type",
791 namelen
, name
, typename(expected_type
),
798 static int peel_onion(const char *name
, int len
, unsigned char *sha1
,
799 unsigned lookup_flags
)
801 struct object_id outer
;
803 unsigned int expected_type
= 0;
807 * "ref^{type}" dereferences ref repeatedly until you cannot
808 * dereference anymore, or you get an object of given type,
809 * whichever comes first. "ref^{}" means just dereference
810 * tags until you get a non-tag. "ref^0" is a shorthand for
811 * "ref^{commit}". "commit^{tree}" could be used to find the
812 * top-level tree of the given commit.
814 if (len
< 4 || name
[len
-1] != '}')
817 for (sp
= name
+ len
- 1; name
<= sp
; sp
--) {
819 if (ch
== '{' && name
< sp
&& sp
[-1] == '^')
825 sp
++; /* beginning of type name, or closing brace for empty */
826 if (starts_with(sp
, "commit}"))
827 expected_type
= OBJ_COMMIT
;
828 else if (starts_with(sp
, "tag}"))
829 expected_type
= OBJ_TAG
;
830 else if (starts_with(sp
, "tree}"))
831 expected_type
= OBJ_TREE
;
832 else if (starts_with(sp
, "blob}"))
833 expected_type
= OBJ_BLOB
;
834 else if (starts_with(sp
, "object}"))
835 expected_type
= OBJ_ANY
;
836 else if (sp
[0] == '}')
837 expected_type
= OBJ_NONE
;
838 else if (sp
[0] == '/')
839 expected_type
= OBJ_COMMIT
;
843 lookup_flags
&= ~GET_SHA1_DISAMBIGUATORS
;
844 if (expected_type
== OBJ_COMMIT
)
845 lookup_flags
|= GET_SHA1_COMMITTISH
;
846 else if (expected_type
== OBJ_TREE
)
847 lookup_flags
|= GET_SHA1_TREEISH
;
849 if (get_sha1_1(name
, sp
- name
- 2, outer
.hash
, lookup_flags
))
852 o
= parse_object(&outer
);
855 if (!expected_type
) {
856 o
= deref_tag(o
, name
, sp
- name
- 2);
857 if (!o
|| (!o
->parsed
&& !parse_object(&o
->oid
)))
859 hashcpy(sha1
, o
->oid
.hash
);
864 * At this point, the syntax look correct, so
865 * if we do not get the needed object, we should
868 o
= peel_to_type(name
, len
, o
, expected_type
);
872 hashcpy(sha1
, o
->oid
.hash
);
874 /* "$commit^{/foo}" */
877 struct commit_list
*list
= NULL
;
880 * $commit^{/}. Some regex implementation may reject.
881 * We don't need regex anyway. '' pattern always matches.
886 prefix
= xstrndup(sp
+ 1, name
+ len
- 1 - (sp
+ 1));
887 commit_list_insert((struct commit
*)o
, &list
);
888 ret
= get_sha1_oneline(prefix
, sha1
, list
);
895 static int get_describe_name(const char *name
, int len
, unsigned char *sha1
)
898 unsigned flags
= GET_SHA1_QUIETLY
| GET_SHA1_COMMIT
;
900 for (cp
= name
+ len
- 1; name
+ 2 <= cp
; cp
--) {
903 /* We must be looking at g in "SOMETHING-g"
904 * for it to be describe output.
906 if (ch
== 'g' && cp
[-1] == '-') {
909 return get_short_sha1(cp
, len
, sha1
, flags
);
916 static int get_sha1_1(const char *name
, int len
, unsigned char *sha1
, unsigned lookup_flags
)
922 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
925 for (cp
= name
+ len
- 1; name
<= cp
; cp
--) {
927 if ('0' <= ch
&& ch
<= '9')
929 if (ch
== '~' || ch
== '^')
936 int len1
= cp
- name
;
938 while (cp
< name
+ len
)
939 num
= num
* 10 + *cp
++ - '0';
940 if (!num
&& len1
== len
- 1)
942 if (has_suffix
== '^')
943 return get_parent(name
, len1
, sha1
, num
);
944 /* else if (has_suffix == '~') -- goes without saying */
945 return get_nth_ancestor(name
, len1
, sha1
, num
);
948 ret
= peel_onion(name
, len
, sha1
, lookup_flags
);
952 ret
= get_sha1_basic(name
, len
, sha1
, lookup_flags
);
956 /* It could be describe output that is "SOMETHING-gXXXX" */
957 ret
= get_describe_name(name
, len
, sha1
);
961 return get_short_sha1(name
, len
, sha1
, lookup_flags
);
965 * This interprets names like ':/Initial revision of "git"' by searching
966 * through history and returning the first commit whose message starts
967 * the given regular expression.
969 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
971 * For a literal '!' character at the beginning of a pattern, you have to repeat
972 * that, like: ':/!!foo'
974 * For future extension, all other sequences beginning with ':/!' are reserved.
977 /* Remember to update object flag allocation in object.h */
978 #define ONELINE_SEEN (1u<<20)
980 static int handle_one_ref(const char *path
, const struct object_id
*oid
,
981 int flag
, void *cb_data
)
983 struct commit_list
**list
= cb_data
;
984 struct object
*object
= parse_object(oid
);
987 if (object
->type
== OBJ_TAG
) {
988 object
= deref_tag(object
, path
, strlen(path
));
992 if (object
->type
!= OBJ_COMMIT
)
994 commit_list_insert((struct commit
*)object
, list
);
998 static int get_sha1_oneline(const char *prefix
, unsigned char *sha1
,
999 struct commit_list
*list
)
1001 struct commit_list
*backup
= NULL
, *l
;
1006 if (prefix
[0] == '!') {
1009 if (prefix
[0] == '-') {
1012 } else if (prefix
[0] != '!') {
1017 if (regcomp(®ex
, prefix
, REG_EXTENDED
))
1020 for (l
= list
; l
; l
= l
->next
) {
1021 l
->item
->object
.flags
|= ONELINE_SEEN
;
1022 commit_list_insert(l
->item
, &backup
);
1025 const char *p
, *buf
;
1026 struct commit
*commit
;
1029 commit
= pop_most_recent_commit(&list
, ONELINE_SEEN
);
1030 if (!parse_object(&commit
->object
.oid
))
1032 buf
= get_commit_buffer(commit
, NULL
);
1033 p
= strstr(buf
, "\n\n");
1034 matches
= negative
^ (p
&& !regexec(®ex
, p
+ 2, 0, NULL
, 0));
1035 unuse_commit_buffer(commit
, buf
);
1038 hashcpy(sha1
, commit
->object
.oid
.hash
);
1044 free_commit_list(list
);
1045 for (l
= backup
; l
; l
= l
->next
)
1046 clear_commit_marks(l
->item
, ONELINE_SEEN
);
1047 free_commit_list(backup
);
1048 return found
? 0 : -1;
1051 struct grab_nth_branch_switch_cbdata
{
1056 static int grab_nth_branch_switch(struct object_id
*ooid
, struct object_id
*noid
,
1057 const char *email
, timestamp_t timestamp
, int tz
,
1058 const char *message
, void *cb_data
)
1060 struct grab_nth_branch_switch_cbdata
*cb
= cb_data
;
1061 const char *match
= NULL
, *target
= NULL
;
1064 if (skip_prefix(message
, "checkout: moving from ", &match
))
1065 target
= strstr(match
, " to ");
1067 if (!match
|| !target
)
1069 if (--(cb
->remaining
) == 0) {
1070 len
= target
- match
;
1071 strbuf_reset(&cb
->buf
);
1072 strbuf_add(&cb
->buf
, match
, len
);
1073 return 1; /* we are done */
1079 * Parse @{-N} syntax, return the number of characters parsed
1080 * if successful; otherwise signal an error with negative value.
1082 static int interpret_nth_prior_checkout(const char *name
, int namelen
,
1087 struct grab_nth_branch_switch_cbdata cb
;
1093 if (name
[0] != '@' || name
[1] != '{' || name
[2] != '-')
1095 brace
= memchr(name
, '}', namelen
);
1098 nth
= strtol(name
+ 3, &num_end
, 10);
1099 if (num_end
!= brace
)
1104 strbuf_init(&cb
.buf
, 20);
1107 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch
, &cb
)) {
1109 strbuf_addbuf(buf
, &cb
.buf
);
1110 retval
= brace
- name
+ 1;
1113 strbuf_release(&cb
.buf
);
1117 int get_oid_mb(const char *name
, struct object_id
*oid
)
1119 struct commit
*one
, *two
;
1120 struct commit_list
*mbs
;
1121 struct object_id oid_tmp
;
1125 dots
= strstr(name
, "...");
1127 return get_oid(name
, oid
);
1129 st
= get_oid("HEAD", &oid_tmp
);
1132 strbuf_init(&sb
, dots
- name
);
1133 strbuf_add(&sb
, name
, dots
- name
);
1134 st
= get_sha1_committish(sb
.buf
, oid_tmp
.hash
);
1135 strbuf_release(&sb
);
1139 one
= lookup_commit_reference_gently(&oid_tmp
, 0);
1143 if (get_sha1_committish(dots
[3] ? (dots
+ 3) : "HEAD", oid_tmp
.hash
))
1145 two
= lookup_commit_reference_gently(&oid_tmp
, 0);
1148 mbs
= get_merge_bases(one
, two
);
1149 if (!mbs
|| mbs
->next
)
1153 oidcpy(oid
, &mbs
->item
->object
.oid
);
1155 free_commit_list(mbs
);
1159 /* parse @something syntax, when 'something' is not {.*} */
1160 static int interpret_empty_at(const char *name
, int namelen
, int len
, struct strbuf
*buf
)
1164 if (len
|| name
[1] == '{')
1167 /* make sure it's a single @, or @@{.*}, not @foo */
1168 next
= memchr(name
+ len
+ 1, '@', namelen
- len
- 1);
1169 if (next
&& next
[1] != '{')
1172 next
= name
+ namelen
;
1173 if (next
!= name
+ 1)
1177 strbuf_add(buf
, "HEAD", 4);
1181 static int reinterpret(const char *name
, int namelen
, int len
,
1182 struct strbuf
*buf
, unsigned allowed
)
1184 /* we have extra data, which might need further processing */
1185 struct strbuf tmp
= STRBUF_INIT
;
1186 int used
= buf
->len
;
1189 strbuf_add(buf
, name
+ len
, namelen
- len
);
1190 ret
= interpret_branch_name(buf
->buf
, buf
->len
, &tmp
, allowed
);
1191 /* that data was not interpreted, remove our cruft */
1193 strbuf_setlen(buf
, used
);
1197 strbuf_addbuf(buf
, &tmp
);
1198 strbuf_release(&tmp
);
1199 /* tweak for size of {-N} versus expanded ref name */
1200 return ret
- used
+ len
;
1203 static void set_shortened_ref(struct strbuf
*buf
, const char *ref
)
1205 char *s
= shorten_unambiguous_ref(ref
, 0);
1207 strbuf_addstr(buf
, s
);
1211 static int branch_interpret_allowed(const char *refname
, unsigned allowed
)
1216 if ((allowed
& INTERPRET_BRANCH_LOCAL
) &&
1217 starts_with(refname
, "refs/heads/"))
1219 if ((allowed
& INTERPRET_BRANCH_REMOTE
) &&
1220 starts_with(refname
, "refs/remotes/"))
1226 static int interpret_branch_mark(const char *name
, int namelen
,
1227 int at
, struct strbuf
*buf
,
1228 int (*get_mark
)(const char *, int),
1229 const char *(*get_data
)(struct branch
*,
1234 struct branch
*branch
;
1235 struct strbuf err
= STRBUF_INIT
;
1238 len
= get_mark(name
+ at
, namelen
- at
);
1242 if (memchr(name
, ':', at
))
1246 char *name_str
= xmemdupz(name
, at
);
1247 branch
= branch_get(name_str
);
1250 branch
= branch_get(NULL
);
1252 value
= get_data(branch
, &err
);
1256 if (!branch_interpret_allowed(value
, allowed
))
1259 set_shortened_ref(buf
, value
);
1263 int interpret_branch_name(const char *name
, int namelen
, struct strbuf
*buf
,
1271 namelen
= strlen(name
);
1273 if (!allowed
|| (allowed
& INTERPRET_BRANCH_LOCAL
)) {
1274 len
= interpret_nth_prior_checkout(name
, namelen
, buf
);
1276 return len
; /* syntax Ok, not enough switches */
1277 } else if (len
> 0) {
1279 return len
; /* consumed all */
1281 return reinterpret(name
, namelen
, len
, buf
, allowed
);
1286 (at
= memchr(start
, '@', namelen
- (start
- name
)));
1289 if (!allowed
|| (allowed
& INTERPRET_BRANCH_HEAD
)) {
1290 len
= interpret_empty_at(name
, namelen
, at
- name
, buf
);
1292 return reinterpret(name
, namelen
, len
, buf
,
1296 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1297 upstream_mark
, branch_get_upstream
,
1302 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1303 push_mark
, branch_get_push
,
1312 void strbuf_branchname(struct strbuf
*sb
, const char *name
, unsigned allowed
)
1314 int len
= strlen(name
);
1315 int used
= interpret_branch_name(name
, len
, sb
, allowed
);
1319 strbuf_add(sb
, name
+ used
, len
- used
);
1322 int strbuf_check_branch_ref(struct strbuf
*sb
, const char *name
)
1324 strbuf_branchname(sb
, name
, INTERPRET_BRANCH_LOCAL
);
1327 strbuf_splice(sb
, 0, 0, "refs/heads/", 11);
1328 return check_refname_format(sb
->buf
, 0);
1332 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1333 * notably "xyz^" for "parent of xyz"
1335 int get_sha1(const char *name
, unsigned char *sha1
)
1337 struct object_context unused
;
1338 return get_sha1_with_context(name
, 0, sha1
, &unused
);
1342 * This is like "get_sha1()", but for struct object_id.
1344 int get_oid(const char *name
, struct object_id
*oid
)
1346 return get_sha1(name
, oid
->hash
);
1351 * Many callers know that the user meant to name a commit-ish by
1352 * syntactical positions where the object name appears. Calling this
1353 * function allows the machinery to disambiguate shorter-than-unique
1354 * abbreviated object names between commit-ish and others.
1356 * Note that this does NOT error out when the named object is not a
1357 * commit-ish. It is merely to give a hint to the disambiguation
1360 int get_sha1_committish(const char *name
, unsigned char *sha1
)
1362 struct object_context unused
;
1363 return get_sha1_with_context(name
, GET_SHA1_COMMITTISH
,
1367 int get_sha1_treeish(const char *name
, unsigned char *sha1
)
1369 struct object_context unused
;
1370 return get_sha1_with_context(name
, GET_SHA1_TREEISH
,
1374 int get_sha1_commit(const char *name
, unsigned char *sha1
)
1376 struct object_context unused
;
1377 return get_sha1_with_context(name
, GET_SHA1_COMMIT
,
1381 int get_sha1_tree(const char *name
, unsigned char *sha1
)
1383 struct object_context unused
;
1384 return get_sha1_with_context(name
, GET_SHA1_TREE
,
1388 int get_sha1_blob(const char *name
, unsigned char *sha1
)
1390 struct object_context unused
;
1391 return get_sha1_with_context(name
, GET_SHA1_BLOB
,
1395 /* Must be called only when object_name:filename doesn't exist. */
1396 static void diagnose_invalid_sha1_path(const char *prefix
,
1397 const char *filename
,
1398 const unsigned char *tree_sha1
,
1399 const char *object_name
,
1400 int object_name_len
)
1402 unsigned char sha1
[20];
1408 if (file_exists(filename
))
1409 die("Path '%s' exists on disk, but not in '%.*s'.",
1410 filename
, object_name_len
, object_name
);
1411 if (errno
== ENOENT
|| errno
== ENOTDIR
) {
1412 char *fullname
= xstrfmt("%s%s", prefix
, filename
);
1414 if (!get_tree_entry(tree_sha1
, fullname
,
1416 die("Path '%s' exists, but not '%s'.\n"
1417 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1420 object_name_len
, object_name
,
1422 object_name_len
, object_name
,
1425 die("Path '%s' does not exist in '%.*s'",
1426 filename
, object_name_len
, object_name
);
1430 /* Must be called only when :stage:filename doesn't exist. */
1431 static void diagnose_invalid_index_path(int stage
,
1433 const char *filename
)
1435 const struct cache_entry
*ce
;
1437 unsigned namelen
= strlen(filename
);
1438 struct strbuf fullname
= STRBUF_INIT
;
1443 /* Wrong stage number? */
1444 pos
= cache_name_pos(filename
, namelen
);
1447 if (pos
< active_nr
) {
1448 ce
= active_cache
[pos
];
1449 if (ce_namelen(ce
) == namelen
&&
1450 !memcmp(ce
->name
, filename
, namelen
))
1451 die("Path '%s' is in the index, but not at stage %d.\n"
1452 "Did you mean ':%d:%s'?",
1454 ce_stage(ce
), filename
);
1457 /* Confusion between relative and absolute filenames? */
1458 strbuf_addstr(&fullname
, prefix
);
1459 strbuf_addstr(&fullname
, filename
);
1460 pos
= cache_name_pos(fullname
.buf
, fullname
.len
);
1463 if (pos
< active_nr
) {
1464 ce
= active_cache
[pos
];
1465 if (ce_namelen(ce
) == fullname
.len
&&
1466 !memcmp(ce
->name
, fullname
.buf
, fullname
.len
))
1467 die("Path '%s' is in the index, but not '%s'.\n"
1468 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1469 fullname
.buf
, filename
,
1470 ce_stage(ce
), fullname
.buf
,
1471 ce_stage(ce
), filename
);
1474 if (file_exists(filename
))
1475 die("Path '%s' exists on disk, but not in the index.", filename
);
1476 if (errno
== ENOENT
|| errno
== ENOTDIR
)
1477 die("Path '%s' does not exist (neither on disk nor in the index).",
1480 strbuf_release(&fullname
);
1484 static char *resolve_relative_path(const char *rel
)
1486 if (!starts_with(rel
, "./") && !starts_with(rel
, "../"))
1489 if (!is_inside_work_tree())
1490 die("relative path syntax can't be used outside working tree.");
1492 /* die() inside prefix_path() if resolved path is outside worktree */
1493 return prefix_path(startup_info
->prefix
,
1494 startup_info
->prefix
? strlen(startup_info
->prefix
) : 0,
1498 static int get_sha1_with_context_1(const char *name
,
1501 unsigned char *sha1
,
1502 struct object_context
*oc
)
1504 int ret
, bracket_depth
;
1505 int namelen
= strlen(name
);
1507 int only_to_die
= flags
& GET_SHA1_ONLY_TO_DIE
;
1510 flags
|= GET_SHA1_QUIETLY
;
1512 memset(oc
, 0, sizeof(*oc
));
1513 oc
->mode
= S_IFINVALID
;
1514 strbuf_init(&oc
->symlink_path
, 0);
1515 ret
= get_sha1_1(name
, namelen
, sha1
, flags
);
1519 * sha1:path --> object name of path in ent sha1
1520 * :path -> object name of absolute path in index
1521 * :./path -> object name of path relative to cwd in index
1522 * :[0-3]:path -> object name of path in index at stage
1523 * :/foo -> recent commit matching foo
1525 if (name
[0] == ':') {
1527 const struct cache_entry
*ce
;
1528 char *new_path
= NULL
;
1530 if (!only_to_die
&& namelen
> 2 && name
[1] == '/') {
1531 struct commit_list
*list
= NULL
;
1533 for_each_ref(handle_one_ref
, &list
);
1534 commit_list_sort_by_date(&list
);
1535 return get_sha1_oneline(name
+ 2, sha1
, list
);
1539 name
[1] < '0' || '3' < name
[1])
1542 stage
= name
[1] - '0';
1545 new_path
= resolve_relative_path(cp
);
1547 namelen
= namelen
- (cp
- name
);
1550 namelen
= strlen(cp
);
1553 if (flags
& GET_SHA1_RECORD_PATH
)
1554 oc
->path
= xstrdup(cp
);
1558 pos
= cache_name_pos(cp
, namelen
);
1561 while (pos
< active_nr
) {
1562 ce
= active_cache
[pos
];
1563 if (ce_namelen(ce
) != namelen
||
1564 memcmp(ce
->name
, cp
, namelen
))
1566 if (ce_stage(ce
) == stage
) {
1567 hashcpy(sha1
, ce
->oid
.hash
);
1568 oc
->mode
= ce
->ce_mode
;
1574 if (only_to_die
&& name
[1] && name
[1] != '/')
1575 diagnose_invalid_index_path(stage
, prefix
, cp
);
1579 for (cp
= name
, bracket_depth
= 0; *cp
; cp
++) {
1582 else if (bracket_depth
&& *cp
== '}')
1584 else if (!bracket_depth
&& *cp
== ':')
1588 unsigned char tree_sha1
[20];
1589 int len
= cp
- name
;
1590 unsigned sub_flags
= flags
;
1592 sub_flags
&= ~GET_SHA1_DISAMBIGUATORS
;
1593 sub_flags
|= GET_SHA1_TREEISH
;
1595 if (!get_sha1_1(name
, len
, tree_sha1
, sub_flags
)) {
1596 const char *filename
= cp
+1;
1597 char *new_filename
= NULL
;
1599 new_filename
= resolve_relative_path(filename
);
1601 filename
= new_filename
;
1602 if (flags
& GET_SHA1_FOLLOW_SYMLINKS
) {
1603 ret
= get_tree_entry_follow_symlinks(tree_sha1
,
1604 filename
, sha1
, &oc
->symlink_path
,
1607 ret
= get_tree_entry(tree_sha1
, filename
,
1609 if (ret
&& only_to_die
) {
1610 diagnose_invalid_sha1_path(prefix
,
1616 hashcpy(oc
->tree
, tree_sha1
);
1617 if (flags
& GET_SHA1_RECORD_PATH
)
1618 oc
->path
= xstrdup(filename
);
1624 die("Invalid object name '%.*s'.", len
, name
);
1631 * Call this function when you know "name" given by the end user must
1632 * name an object but it doesn't; the function _may_ die with a better
1633 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1634 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1635 * you have a chance to diagnose the error further.
1637 void maybe_die_on_misspelt_object_name(const char *name
, const char *prefix
)
1639 struct object_context oc
;
1640 unsigned char sha1
[20];
1641 get_sha1_with_context_1(name
, GET_SHA1_ONLY_TO_DIE
, prefix
, sha1
, &oc
);
1644 int get_sha1_with_context(const char *str
, unsigned flags
, unsigned char *sha1
, struct object_context
*oc
)
1646 if (flags
& GET_SHA1_FOLLOW_SYMLINKS
&& flags
& GET_SHA1_ONLY_TO_DIE
)
1647 die("BUG: incompatible flags for get_sha1_with_context");
1648 return get_sha1_with_context_1(str
, flags
, NULL
, sha1
, oc
);