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 unsigned char *, void *);
16 struct disambiguate_state
{
17 int len
; /* length of prefix in hex chars */
18 char hex_pfx
[GIT_SHA1_HEXSZ
+ 1];
19 unsigned char bin_pfx
[GIT_SHA1_RAWSZ
];
21 disambiguate_hint_fn fn
;
23 unsigned char candidate
[GIT_SHA1_RAWSZ
];
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 unsigned char *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 hashcpy(ds
->candidate
, current
);
41 ds
->candidate_exists
= 1;
43 } else if (!hashcmp(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 hashcpy(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_SHA1_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 unsigned char sha1
[20];
112 if (strlen(de
->d_name
) != 38)
114 if (memcmp(de
->d_name
, ds
->hex_pfx
+ 2, ds
->len
- 2))
116 memcpy(hex
+ 2, de
->d_name
, 38);
117 if (!get_sha1_hex(hex
, sha1
))
118 update_candidates(ds
, sha1
);
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 unsigned char *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
, 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 current
= nth_packed_object_sha1(p
, i
);
173 if (!match_sha(ds
->len
, ds
->bin_pfx
, current
))
175 update_candidates(ds
, current
);
179 static void find_short_packed_object(struct disambiguate_state
*ds
)
181 struct packed_git
*p
;
183 prepare_packed_git();
184 for (p
= packed_git
; p
&& !ds
->ambiguous
; p
= p
->next
)
185 unique_in_pack(p
, ds
);
188 #define SHORT_NAME_NOT_FOUND (-1)
189 #define SHORT_NAME_AMBIGUOUS (-2)
191 static int finish_object_disambiguation(struct disambiguate_state
*ds
,
195 return SHORT_NAME_AMBIGUOUS
;
197 if (!ds
->candidate_exists
)
198 return SHORT_NAME_NOT_FOUND
;
200 if (!ds
->candidate_checked
)
202 * If this is the only candidate, there is no point
203 * calling the disambiguation hint callback.
205 * On the other hand, if the current candidate
206 * replaced an earlier candidate that did _not_ pass
207 * the disambiguation hint callback, then we do have
208 * more than one objects that match the short name
209 * given, so we should make sure this one matches;
210 * otherwise, if we discovered this one and the one
211 * that we previously discarded in the reverse order,
212 * we would end up showing different results in the
215 ds
->candidate_ok
= (!ds
->disambiguate_fn_used
||
216 ds
->fn(ds
->candidate
, ds
->cb_data
));
218 if (!ds
->candidate_ok
)
219 return SHORT_NAME_AMBIGUOUS
;
221 hashcpy(sha1
, ds
->candidate
);
225 static int disambiguate_commit_only(const unsigned char *sha1
, void *cb_data_unused
)
227 int kind
= sha1_object_info(sha1
, NULL
);
228 return kind
== OBJ_COMMIT
;
231 static int disambiguate_committish_only(const unsigned char *sha1
, void *cb_data_unused
)
236 kind
= sha1_object_info(sha1
, NULL
);
237 if (kind
== OBJ_COMMIT
)
242 /* We need to do this the hard way... */
243 obj
= deref_tag(parse_object(sha1
), NULL
, 0);
244 if (obj
&& obj
->type
== OBJ_COMMIT
)
249 static int disambiguate_tree_only(const unsigned char *sha1
, void *cb_data_unused
)
251 int kind
= sha1_object_info(sha1
, NULL
);
252 return kind
== OBJ_TREE
;
255 static int disambiguate_treeish_only(const unsigned char *sha1
, void *cb_data_unused
)
260 kind
= sha1_object_info(sha1
, NULL
);
261 if (kind
== OBJ_TREE
|| kind
== OBJ_COMMIT
)
266 /* We need to do this the hard way... */
267 obj
= deref_tag(parse_object(sha1
), NULL
, 0);
268 if (obj
&& (obj
->type
== OBJ_TREE
|| obj
->type
== OBJ_COMMIT
))
273 static int disambiguate_blob_only(const unsigned char *sha1
, void *cb_data_unused
)
275 int kind
= sha1_object_info(sha1
, NULL
);
276 return kind
== OBJ_BLOB
;
279 static disambiguate_hint_fn default_disambiguate_hint
;
281 int set_disambiguate_hint_config(const char *var
, const char *value
)
283 static const struct {
285 disambiguate_hint_fn fn
;
288 { "commit", disambiguate_commit_only
},
289 { "committish", disambiguate_committish_only
},
290 { "tree", disambiguate_tree_only
},
291 { "treeish", disambiguate_treeish_only
},
292 { "blob", disambiguate_blob_only
}
297 return config_error_nonbool(var
);
299 for (i
= 0; i
< ARRAY_SIZE(hints
); i
++) {
300 if (!strcasecmp(value
, hints
[i
].name
)) {
301 default_disambiguate_hint
= hints
[i
].fn
;
306 return error("unknown hint type for '%s': %s", var
, value
);
309 static int init_object_disambiguation(const char *name
, int len
,
310 struct disambiguate_state
*ds
)
314 if (len
< MINIMUM_ABBREV
|| len
> GIT_SHA1_HEXSZ
)
317 memset(ds
, 0, sizeof(*ds
));
319 for (i
= 0; i
< len
;i
++) {
320 unsigned char c
= name
[i
];
322 if (c
>= '0' && c
<= '9')
324 else if (c
>= 'a' && c
<= 'f')
326 else if (c
>= 'A' && c
<='F') {
335 ds
->bin_pfx
[i
>> 1] |= val
;
339 ds
->hex_pfx
[len
] = '\0';
344 static int show_ambiguous_object(const unsigned char *sha1
, void *data
)
346 const struct disambiguate_state
*ds
= data
;
347 struct strbuf desc
= STRBUF_INIT
;
350 if (ds
->fn
&& !ds
->fn(sha1
, ds
->cb_data
))
353 type
= sha1_object_info(sha1
, NULL
);
354 if (type
== OBJ_COMMIT
) {
355 struct commit
*commit
= lookup_commit(sha1
);
357 struct pretty_print_context pp
= {0};
358 pp
.date_mode
.type
= DATE_SHORT
;
359 format_commit_message(commit
, " %ad - %s", &desc
, &pp
);
361 } else if (type
== OBJ_TAG
) {
362 struct tag
*tag
= lookup_tag(sha1
);
363 if (!parse_tag(tag
) && tag
->tag
)
364 strbuf_addf(&desc
, " %s", tag
->tag
);
368 find_unique_abbrev(sha1
, DEFAULT_ABBREV
),
369 typename(type
) ? typename(type
) : "unknown type",
372 strbuf_release(&desc
);
376 static int get_short_sha1(const char *name
, int len
, unsigned char *sha1
,
380 struct disambiguate_state ds
;
381 int quietly
= !!(flags
& GET_SHA1_QUIETLY
);
383 if (init_object_disambiguation(name
, len
, &ds
) < 0)
386 if (HAS_MULTI_BITS(flags
& GET_SHA1_DISAMBIGUATORS
))
387 die("BUG: multiple get_short_sha1 disambiguator flags");
389 if (flags
& GET_SHA1_COMMIT
)
390 ds
.fn
= disambiguate_commit_only
;
391 else if (flags
& GET_SHA1_COMMITTISH
)
392 ds
.fn
= disambiguate_committish_only
;
393 else if (flags
& GET_SHA1_TREE
)
394 ds
.fn
= disambiguate_tree_only
;
395 else if (flags
& GET_SHA1_TREEISH
)
396 ds
.fn
= disambiguate_treeish_only
;
397 else if (flags
& GET_SHA1_BLOB
)
398 ds
.fn
= disambiguate_blob_only
;
400 ds
.fn
= default_disambiguate_hint
;
402 find_short_object_filename(&ds
);
403 find_short_packed_object(&ds
);
404 status
= finish_object_disambiguation(&ds
, sha1
);
406 if (!quietly
&& (status
== SHORT_NAME_AMBIGUOUS
)) {
407 error(_("short SHA1 %s is ambiguous"), ds
.hex_pfx
);
410 * We may still have ambiguity if we simply saw a series of
411 * candidates that did not satisfy our hint function. In
412 * that case, we still want to show them, so disable the hint
418 advise(_("The candidates are:"));
419 for_each_abbrev(ds
.hex_pfx
, show_ambiguous_object
, &ds
);
425 static int collect_ambiguous(const unsigned char *sha1
, void *data
)
427 sha1_array_append(data
, sha1
);
431 int for_each_abbrev(const char *prefix
, each_abbrev_fn fn
, void *cb_data
)
433 struct sha1_array collect
= SHA1_ARRAY_INIT
;
434 struct disambiguate_state ds
;
437 if (init_object_disambiguation(prefix
, strlen(prefix
), &ds
) < 0)
440 ds
.always_call_fn
= 1;
441 ds
.fn
= collect_ambiguous
;
442 ds
.cb_data
= &collect
;
443 find_short_object_filename(&ds
);
444 find_short_packed_object(&ds
);
446 ret
= sha1_array_for_each_unique(&collect
, fn
, cb_data
);
447 sha1_array_clear(&collect
);
452 * Return the slot of the most-significant bit set in "val". There are various
453 * ways to do this quickly with fls() or __builtin_clzl(), but speed is
454 * probably not a big deal here.
456 static unsigned msb(unsigned long val
)
464 int find_unique_abbrev_r(char *hex
, const unsigned char *sha1
, int len
)
469 unsigned long count
= approximate_object_count();
471 * Add one because the MSB only tells us the highest bit set,
472 * not including the value of all the _other_ bits (so "15"
473 * is only one off of 2^4, but the MSB is the 3rd bit.
475 len
= msb(count
) + 1;
477 * We now know we have on the order of 2^len objects, which
478 * expects a collision at 2^(len/2). But we also care about hex
479 * chars, not bits, and there are 4 bits per hex. So all
480 * together we need to divide by 2; but we also want to round
481 * odd numbers up, hence adding one before dividing.
485 * For very small repos, we stick with our regular fallback.
487 if (len
< FALLBACK_DEFAULT_ABBREV
)
488 len
= FALLBACK_DEFAULT_ABBREV
;
491 sha1_to_hex_r(hex
, sha1
);
492 if (len
== 40 || !len
)
494 exists
= has_sha1_file(sha1
);
496 unsigned char sha1_ret
[20];
497 status
= get_short_sha1(hex
, len
, sha1_ret
, GET_SHA1_QUIETLY
);
500 : status
== SHORT_NAME_NOT_FOUND
) {
509 const char *find_unique_abbrev(const unsigned char *sha1
, int len
)
512 static char hexbuffer
[4][GIT_SHA1_HEXSZ
+ 1];
513 char *hex
= hexbuffer
[bufno
];
514 bufno
= (bufno
+ 1) % ARRAY_SIZE(hexbuffer
);
515 find_unique_abbrev_r(hex
, sha1
, len
);
519 static int ambiguous_path(const char *path
, int len
)
524 for (cnt
= 0; cnt
< len
; cnt
++) {
544 static inline int at_mark(const char *string
, int len
,
545 const char **suffix
, int nr
)
549 for (i
= 0; i
< nr
; i
++) {
550 int suffix_len
= strlen(suffix
[i
]);
551 if (suffix_len
<= len
552 && !memcmp(string
, suffix
[i
], suffix_len
))
558 static inline int upstream_mark(const char *string
, int len
)
560 const char *suffix
[] = { "@{upstream}", "@{u}" };
561 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
564 static inline int push_mark(const char *string
, int len
)
566 const char *suffix
[] = { "@{push}" };
567 return at_mark(string
, len
, suffix
, ARRAY_SIZE(suffix
));
570 static int get_sha1_1(const char *name
, int len
, unsigned char *sha1
, unsigned lookup_flags
);
571 static int interpret_nth_prior_checkout(const char *name
, int namelen
, struct strbuf
*buf
);
573 static int get_sha1_basic(const char *str
, int len
, unsigned char *sha1
,
576 static const char *warn_msg
= "refname '%.*s' is ambiguous.";
577 static const char *object_name_msg
= N_(
578 "Git normally never creates a ref that ends with 40 hex characters\n"
579 "because it will be ignored when you just specify 40-hex. These refs\n"
580 "may be created by mistake. For example,\n"
582 " git checkout -b $br $(git rev-parse ...)\n"
584 "where \"$br\" is somehow empty and a 40-hex ref is created. Please\n"
585 "examine these refs and maybe delete them. Turn this message off by\n"
586 "running \"git config advice.objectNameWarning false\"");
587 unsigned char tmp_sha1
[20];
588 char *real_ref
= NULL
;
590 int at
, reflog_len
, nth_prior
= 0;
592 if (len
== 40 && !get_sha1_hex(str
, sha1
)) {
593 if (warn_ambiguous_refs
&& warn_on_object_refname_ambiguity
) {
594 refs_found
= dwim_ref(str
, len
, tmp_sha1
, &real_ref
);
595 if (refs_found
> 0) {
596 warning(warn_msg
, len
, str
);
597 if (advice_object_name_warning
)
598 fprintf(stderr
, "%s\n", _(object_name_msg
));
605 /* basic@{time or number or -number} format to query ref-log */
607 if (len
&& str
[len
-1] == '}') {
608 for (at
= len
-4; at
>= 0; at
--) {
609 if (str
[at
] == '@' && str
[at
+1] == '{') {
610 if (str
[at
+2] == '-') {
612 /* @{-N} not at start */
617 if (!upstream_mark(str
+ at
, len
- at
) &&
618 !push_mark(str
+ at
, len
- at
)) {
619 reflog_len
= (len
-1) - (at
+2);
627 /* Accept only unambiguous ref paths. */
628 if (len
&& ambiguous_path(str
, len
))
632 struct strbuf buf
= STRBUF_INIT
;
635 if (interpret_nth_prior_checkout(str
, len
, &buf
) > 0) {
636 detached
= (buf
.len
== 40 && !get_sha1_hex(buf
.buf
, sha1
));
637 strbuf_release(&buf
);
643 if (!len
&& reflog_len
)
644 /* allow "@{...}" to mean the current branch reflog */
645 refs_found
= dwim_ref("HEAD", 4, sha1
, &real_ref
);
647 refs_found
= dwim_log(str
, len
, sha1
, &real_ref
);
649 refs_found
= dwim_ref(str
, len
, sha1
, &real_ref
);
654 if (warn_ambiguous_refs
&& !(flags
& GET_SHA1_QUIETLY
) &&
656 !get_short_sha1(str
, len
, tmp_sha1
, GET_SHA1_QUIETLY
)))
657 warning(warn_msg
, len
, str
);
661 unsigned long at_time
;
662 unsigned long co_time
;
665 /* Is it asking for N-th entry, or approxidate? */
666 for (i
= nth
= 0; 0 <= nth
&& i
< reflog_len
; i
++) {
667 char ch
= str
[at
+2+i
];
668 if ('0' <= ch
&& ch
<= '9')
669 nth
= nth
* 10 + ch
- '0';
673 if (100000000 <= nth
) {
680 char *tmp
= xstrndup(str
+ at
+ 2, reflog_len
);
681 at_time
= approxidate_careful(tmp
, &errors
);
688 if (read_ref_at(real_ref
, flags
, at_time
, nth
, sha1
, NULL
,
689 &co_time
, &co_tz
, &co_cnt
)) {
691 if (starts_with(real_ref
, "refs/heads/")) {
693 len
= strlen(real_ref
+ 11);
701 if (!(flags
& GET_SHA1_QUIETLY
)) {
702 warning("Log for '%.*s' only goes "
703 "back to %s.", len
, str
,
704 show_date(co_time
, co_tz
, DATE_MODE(RFC2822
)));
707 if (flags
& GET_SHA1_QUIETLY
) {
710 die("Log for '%.*s' only has %d entries.",
720 static int get_parent(const char *name
, int len
,
721 unsigned char *result
, int idx
)
723 unsigned char sha1
[20];
724 int ret
= get_sha1_1(name
, len
, sha1
, GET_SHA1_COMMITTISH
);
725 struct commit
*commit
;
726 struct commit_list
*p
;
730 commit
= lookup_commit_reference(sha1
);
731 if (parse_commit(commit
))
734 hashcpy(result
, commit
->object
.oid
.hash
);
740 hashcpy(result
, p
->item
->object
.oid
.hash
);
748 static int get_nth_ancestor(const char *name
, int len
,
749 unsigned char *result
, int generation
)
751 unsigned char sha1
[20];
752 struct commit
*commit
;
755 ret
= get_sha1_1(name
, len
, sha1
, GET_SHA1_COMMITTISH
);
758 commit
= lookup_commit_reference(sha1
);
762 while (generation
--) {
763 if (parse_commit(commit
) || !commit
->parents
)
765 commit
= commit
->parents
->item
;
767 hashcpy(result
, commit
->object
.oid
.hash
);
771 struct object
*peel_to_type(const char *name
, int namelen
,
772 struct object
*o
, enum object_type expected_type
)
774 if (name
&& !namelen
)
775 namelen
= strlen(name
);
777 if (!o
|| (!o
->parsed
&& !parse_object(o
->oid
.hash
)))
779 if (expected_type
== OBJ_ANY
|| o
->type
== expected_type
)
781 if (o
->type
== OBJ_TAG
)
782 o
= ((struct tag
*) o
)->tagged
;
783 else if (o
->type
== OBJ_COMMIT
)
784 o
= &(((struct commit
*) o
)->tree
->object
);
787 error("%.*s: expected %s type, but the object "
788 "dereferences to %s type",
789 namelen
, name
, typename(expected_type
),
796 static int peel_onion(const char *name
, int len
, unsigned char *sha1
,
797 unsigned lookup_flags
)
799 unsigned char outer
[20];
801 unsigned int expected_type
= 0;
805 * "ref^{type}" dereferences ref repeatedly until you cannot
806 * dereference anymore, or you get an object of given type,
807 * whichever comes first. "ref^{}" means just dereference
808 * tags until you get a non-tag. "ref^0" is a shorthand for
809 * "ref^{commit}". "commit^{tree}" could be used to find the
810 * top-level tree of the given commit.
812 if (len
< 4 || name
[len
-1] != '}')
815 for (sp
= name
+ len
- 1; name
<= sp
; sp
--) {
817 if (ch
== '{' && name
< sp
&& sp
[-1] == '^')
823 sp
++; /* beginning of type name, or closing brace for empty */
824 if (starts_with(sp
, "commit}"))
825 expected_type
= OBJ_COMMIT
;
826 else if (starts_with(sp
, "tag}"))
827 expected_type
= OBJ_TAG
;
828 else if (starts_with(sp
, "tree}"))
829 expected_type
= OBJ_TREE
;
830 else if (starts_with(sp
, "blob}"))
831 expected_type
= OBJ_BLOB
;
832 else if (starts_with(sp
, "object}"))
833 expected_type
= OBJ_ANY
;
834 else if (sp
[0] == '}')
835 expected_type
= OBJ_NONE
;
836 else if (sp
[0] == '/')
837 expected_type
= OBJ_COMMIT
;
841 lookup_flags
&= ~GET_SHA1_DISAMBIGUATORS
;
842 if (expected_type
== OBJ_COMMIT
)
843 lookup_flags
|= GET_SHA1_COMMITTISH
;
844 else if (expected_type
== OBJ_TREE
)
845 lookup_flags
|= GET_SHA1_TREEISH
;
847 if (get_sha1_1(name
, sp
- name
- 2, outer
, lookup_flags
))
850 o
= parse_object(outer
);
853 if (!expected_type
) {
854 o
= deref_tag(o
, name
, sp
- name
- 2);
855 if (!o
|| (!o
->parsed
&& !parse_object(o
->oid
.hash
)))
857 hashcpy(sha1
, o
->oid
.hash
);
862 * At this point, the syntax look correct, so
863 * if we do not get the needed object, we should
866 o
= peel_to_type(name
, len
, o
, expected_type
);
870 hashcpy(sha1
, o
->oid
.hash
);
872 /* "$commit^{/foo}" */
875 struct commit_list
*list
= NULL
;
878 * $commit^{/}. Some regex implementation may reject.
879 * We don't need regex anyway. '' pattern always matches.
884 prefix
= xstrndup(sp
+ 1, name
+ len
- 1 - (sp
+ 1));
885 commit_list_insert((struct commit
*)o
, &list
);
886 ret
= get_sha1_oneline(prefix
, sha1
, list
);
893 static int get_describe_name(const char *name
, int len
, unsigned char *sha1
)
896 unsigned flags
= GET_SHA1_QUIETLY
| GET_SHA1_COMMIT
;
898 for (cp
= name
+ len
- 1; name
+ 2 <= cp
; cp
--) {
901 /* We must be looking at g in "SOMETHING-g"
902 * for it to be describe output.
904 if (ch
== 'g' && cp
[-1] == '-') {
907 return get_short_sha1(cp
, len
, sha1
, flags
);
914 static int get_sha1_1(const char *name
, int len
, unsigned char *sha1
, unsigned lookup_flags
)
920 * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
923 for (cp
= name
+ len
- 1; name
<= cp
; cp
--) {
925 if ('0' <= ch
&& ch
<= '9')
927 if (ch
== '~' || ch
== '^')
934 int len1
= cp
- name
;
936 while (cp
< name
+ len
)
937 num
= num
* 10 + *cp
++ - '0';
938 if (!num
&& len1
== len
- 1)
940 if (has_suffix
== '^')
941 return get_parent(name
, len1
, sha1
, num
);
942 /* else if (has_suffix == '~') -- goes without saying */
943 return get_nth_ancestor(name
, len1
, sha1
, num
);
946 ret
= peel_onion(name
, len
, sha1
, lookup_flags
);
950 ret
= get_sha1_basic(name
, len
, sha1
, lookup_flags
);
954 /* It could be describe output that is "SOMETHING-gXXXX" */
955 ret
= get_describe_name(name
, len
, sha1
);
959 return get_short_sha1(name
, len
, sha1
, lookup_flags
);
963 * This interprets names like ':/Initial revision of "git"' by searching
964 * through history and returning the first commit whose message starts
965 * the given regular expression.
967 * For negative-matching, prefix the pattern-part with '!-', like: ':/!-WIP'.
969 * For a literal '!' character at the beginning of a pattern, you have to repeat
970 * that, like: ':/!!foo'
972 * For future extension, all other sequences beginning with ':/!' are reserved.
975 /* Remember to update object flag allocation in object.h */
976 #define ONELINE_SEEN (1u<<20)
978 static int handle_one_ref(const char *path
, const struct object_id
*oid
,
979 int flag
, void *cb_data
)
981 struct commit_list
**list
= cb_data
;
982 struct object
*object
= parse_object(oid
->hash
);
985 if (object
->type
== OBJ_TAG
) {
986 object
= deref_tag(object
, path
, strlen(path
));
990 if (object
->type
!= OBJ_COMMIT
)
992 commit_list_insert((struct commit
*)object
, list
);
996 static int get_sha1_oneline(const char *prefix
, unsigned char *sha1
,
997 struct commit_list
*list
)
999 struct commit_list
*backup
= NULL
, *l
;
1004 if (prefix
[0] == '!') {
1007 if (prefix
[0] == '-') {
1010 } else if (prefix
[0] != '!') {
1015 if (regcomp(®ex
, prefix
, REG_EXTENDED
))
1018 for (l
= list
; l
; l
= l
->next
) {
1019 l
->item
->object
.flags
|= ONELINE_SEEN
;
1020 commit_list_insert(l
->item
, &backup
);
1023 const char *p
, *buf
;
1024 struct commit
*commit
;
1027 commit
= pop_most_recent_commit(&list
, ONELINE_SEEN
);
1028 if (!parse_object(commit
->object
.oid
.hash
))
1030 buf
= get_commit_buffer(commit
, NULL
);
1031 p
= strstr(buf
, "\n\n");
1032 matches
= negative
^ (p
&& !regexec(®ex
, p
+ 2, 0, NULL
, 0));
1033 unuse_commit_buffer(commit
, buf
);
1036 hashcpy(sha1
, commit
->object
.oid
.hash
);
1042 free_commit_list(list
);
1043 for (l
= backup
; l
; l
= l
->next
)
1044 clear_commit_marks(l
->item
, ONELINE_SEEN
);
1045 free_commit_list(backup
);
1046 return found
? 0 : -1;
1049 struct grab_nth_branch_switch_cbdata
{
1054 static int grab_nth_branch_switch(unsigned char *osha1
, unsigned char *nsha1
,
1055 const char *email
, unsigned long timestamp
, int tz
,
1056 const char *message
, void *cb_data
)
1058 struct grab_nth_branch_switch_cbdata
*cb
= cb_data
;
1059 const char *match
= NULL
, *target
= NULL
;
1062 if (skip_prefix(message
, "checkout: moving from ", &match
))
1063 target
= strstr(match
, " to ");
1065 if (!match
|| !target
)
1067 if (--(cb
->remaining
) == 0) {
1068 len
= target
- match
;
1069 strbuf_reset(&cb
->buf
);
1070 strbuf_add(&cb
->buf
, match
, len
);
1071 return 1; /* we are done */
1077 * Parse @{-N} syntax, return the number of characters parsed
1078 * if successful; otherwise signal an error with negative value.
1080 static int interpret_nth_prior_checkout(const char *name
, int namelen
,
1085 struct grab_nth_branch_switch_cbdata cb
;
1091 if (name
[0] != '@' || name
[1] != '{' || name
[2] != '-')
1093 brace
= memchr(name
, '}', namelen
);
1096 nth
= strtol(name
+ 3, &num_end
, 10);
1097 if (num_end
!= brace
)
1102 strbuf_init(&cb
.buf
, 20);
1105 if (0 < for_each_reflog_ent_reverse("HEAD", grab_nth_branch_switch
, &cb
)) {
1107 strbuf_addbuf(buf
, &cb
.buf
);
1108 retval
= brace
- name
+ 1;
1111 strbuf_release(&cb
.buf
);
1115 int get_oid_mb(const char *name
, struct object_id
*oid
)
1117 struct commit
*one
, *two
;
1118 struct commit_list
*mbs
;
1119 struct object_id oid_tmp
;
1123 dots
= strstr(name
, "...");
1125 return get_oid(name
, oid
);
1127 st
= get_oid("HEAD", &oid_tmp
);
1130 strbuf_init(&sb
, dots
- name
);
1131 strbuf_add(&sb
, name
, dots
- name
);
1132 st
= get_sha1_committish(sb
.buf
, oid_tmp
.hash
);
1133 strbuf_release(&sb
);
1137 one
= lookup_commit_reference_gently(oid_tmp
.hash
, 0);
1141 if (get_sha1_committish(dots
[3] ? (dots
+ 3) : "HEAD", oid_tmp
.hash
))
1143 two
= lookup_commit_reference_gently(oid_tmp
.hash
, 0);
1146 mbs
= get_merge_bases(one
, two
);
1147 if (!mbs
|| mbs
->next
)
1151 oidcpy(oid
, &mbs
->item
->object
.oid
);
1153 free_commit_list(mbs
);
1157 /* parse @something syntax, when 'something' is not {.*} */
1158 static int interpret_empty_at(const char *name
, int namelen
, int len
, struct strbuf
*buf
)
1162 if (len
|| name
[1] == '{')
1165 /* make sure it's a single @, or @@{.*}, not @foo */
1166 next
= memchr(name
+ len
+ 1, '@', namelen
- len
- 1);
1167 if (next
&& next
[1] != '{')
1170 next
= name
+ namelen
;
1171 if (next
!= name
+ 1)
1175 strbuf_add(buf
, "HEAD", 4);
1179 static int reinterpret(const char *name
, int namelen
, int len
, struct strbuf
*buf
)
1181 /* we have extra data, which might need further processing */
1182 struct strbuf tmp
= STRBUF_INIT
;
1183 int used
= buf
->len
;
1186 strbuf_add(buf
, name
+ len
, namelen
- len
);
1187 ret
= interpret_branch_name(buf
->buf
, buf
->len
, &tmp
);
1188 /* that data was not interpreted, remove our cruft */
1190 strbuf_setlen(buf
, used
);
1194 strbuf_addbuf(buf
, &tmp
);
1195 strbuf_release(&tmp
);
1196 /* tweak for size of {-N} versus expanded ref name */
1197 return ret
- used
+ len
;
1200 static void set_shortened_ref(struct strbuf
*buf
, const char *ref
)
1202 char *s
= shorten_unambiguous_ref(ref
, 0);
1204 strbuf_addstr(buf
, s
);
1208 static int interpret_branch_mark(const char *name
, int namelen
,
1209 int at
, struct strbuf
*buf
,
1210 int (*get_mark
)(const char *, int),
1211 const char *(*get_data
)(struct branch
*,
1215 struct branch
*branch
;
1216 struct strbuf err
= STRBUF_INIT
;
1219 len
= get_mark(name
+ at
, namelen
- at
);
1223 if (memchr(name
, ':', at
))
1227 char *name_str
= xmemdupz(name
, at
);
1228 branch
= branch_get(name_str
);
1231 branch
= branch_get(NULL
);
1233 value
= get_data(branch
, &err
);
1237 set_shortened_ref(buf
, value
);
1242 * This reads short-hand syntax that not only evaluates to a commit
1243 * object name, but also can act as if the end user spelled the name
1244 * of the branch from the command line.
1246 * - "@{-N}" finds the name of the Nth previous branch we were on, and
1247 * places the name of the branch in the given buf and returns the
1248 * number of characters parsed if successful.
1250 * - "<branch>@{upstream}" finds the name of the other ref that
1251 * <branch> is configured to merge with (missing <branch> defaults
1252 * to the current branch), and places the name of the branch in the
1253 * given buf and returns the number of characters parsed if
1256 * If the input is not of the accepted format, it returns a negative
1257 * number to signal an error.
1259 * If the input was ok but there are not N branch switches in the
1260 * reflog, it returns 0.
1262 int interpret_branch_name(const char *name
, int namelen
, struct strbuf
*buf
)
1266 int len
= interpret_nth_prior_checkout(name
, namelen
, buf
);
1269 namelen
= strlen(name
);
1272 return len
; /* syntax Ok, not enough switches */
1273 } else if (len
> 0) {
1275 return len
; /* consumed all */
1277 return reinterpret(name
, namelen
, len
, buf
);
1281 (at
= memchr(start
, '@', namelen
- (start
- name
)));
1284 len
= interpret_empty_at(name
, namelen
, at
- name
, buf
);
1286 return reinterpret(name
, namelen
, len
, buf
);
1288 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1289 upstream_mark
, branch_get_upstream
);
1293 len
= interpret_branch_mark(name
, namelen
, at
- name
, buf
,
1294 push_mark
, branch_get_push
);
1302 int strbuf_branchname(struct strbuf
*sb
, const char *name
)
1304 int len
= strlen(name
);
1305 int used
= interpret_branch_name(name
, len
, sb
);
1311 strbuf_add(sb
, name
+ used
, len
- used
);
1315 int strbuf_check_branch_ref(struct strbuf
*sb
, const char *name
)
1317 strbuf_branchname(sb
, name
);
1320 strbuf_splice(sb
, 0, 0, "refs/heads/", 11);
1321 return check_refname_format(sb
->buf
, 0);
1325 * This is like "get_sha1_basic()", except it allows "sha1 expressions",
1326 * notably "xyz^" for "parent of xyz"
1328 int get_sha1(const char *name
, unsigned char *sha1
)
1330 struct object_context unused
;
1331 return get_sha1_with_context(name
, 0, sha1
, &unused
);
1335 * This is like "get_sha1()", but for struct object_id.
1337 int get_oid(const char *name
, struct object_id
*oid
)
1339 return get_sha1(name
, oid
->hash
);
1344 * Many callers know that the user meant to name a commit-ish by
1345 * syntactical positions where the object name appears. Calling this
1346 * function allows the machinery to disambiguate shorter-than-unique
1347 * abbreviated object names between commit-ish and others.
1349 * Note that this does NOT error out when the named object is not a
1350 * commit-ish. It is merely to give a hint to the disambiguation
1353 int get_sha1_committish(const char *name
, unsigned char *sha1
)
1355 struct object_context unused
;
1356 return get_sha1_with_context(name
, GET_SHA1_COMMITTISH
,
1360 int get_sha1_treeish(const char *name
, unsigned char *sha1
)
1362 struct object_context unused
;
1363 return get_sha1_with_context(name
, GET_SHA1_TREEISH
,
1367 int get_sha1_commit(const char *name
, unsigned char *sha1
)
1369 struct object_context unused
;
1370 return get_sha1_with_context(name
, GET_SHA1_COMMIT
,
1374 int get_sha1_tree(const char *name
, unsigned char *sha1
)
1376 struct object_context unused
;
1377 return get_sha1_with_context(name
, GET_SHA1_TREE
,
1381 int get_sha1_blob(const char *name
, unsigned char *sha1
)
1383 struct object_context unused
;
1384 return get_sha1_with_context(name
, GET_SHA1_BLOB
,
1388 /* Must be called only when object_name:filename doesn't exist. */
1389 static void diagnose_invalid_sha1_path(const char *prefix
,
1390 const char *filename
,
1391 const unsigned char *tree_sha1
,
1392 const char *object_name
,
1393 int object_name_len
)
1395 unsigned char sha1
[20];
1401 if (file_exists(filename
))
1402 die("Path '%s' exists on disk, but not in '%.*s'.",
1403 filename
, object_name_len
, object_name
);
1404 if (errno
== ENOENT
|| errno
== ENOTDIR
) {
1405 char *fullname
= xstrfmt("%s%s", prefix
, filename
);
1407 if (!get_tree_entry(tree_sha1
, fullname
,
1409 die("Path '%s' exists, but not '%s'.\n"
1410 "Did you mean '%.*s:%s' aka '%.*s:./%s'?",
1413 object_name_len
, object_name
,
1415 object_name_len
, object_name
,
1418 die("Path '%s' does not exist in '%.*s'",
1419 filename
, object_name_len
, object_name
);
1423 /* Must be called only when :stage:filename doesn't exist. */
1424 static void diagnose_invalid_index_path(int stage
,
1426 const char *filename
)
1428 const struct cache_entry
*ce
;
1430 unsigned namelen
= strlen(filename
);
1431 struct strbuf fullname
= STRBUF_INIT
;
1436 /* Wrong stage number? */
1437 pos
= cache_name_pos(filename
, namelen
);
1440 if (pos
< active_nr
) {
1441 ce
= active_cache
[pos
];
1442 if (ce_namelen(ce
) == namelen
&&
1443 !memcmp(ce
->name
, filename
, namelen
))
1444 die("Path '%s' is in the index, but not at stage %d.\n"
1445 "Did you mean ':%d:%s'?",
1447 ce_stage(ce
), filename
);
1450 /* Confusion between relative and absolute filenames? */
1451 strbuf_addstr(&fullname
, prefix
);
1452 strbuf_addstr(&fullname
, filename
);
1453 pos
= cache_name_pos(fullname
.buf
, fullname
.len
);
1456 if (pos
< active_nr
) {
1457 ce
= active_cache
[pos
];
1458 if (ce_namelen(ce
) == fullname
.len
&&
1459 !memcmp(ce
->name
, fullname
.buf
, fullname
.len
))
1460 die("Path '%s' is in the index, but not '%s'.\n"
1461 "Did you mean ':%d:%s' aka ':%d:./%s'?",
1462 fullname
.buf
, filename
,
1463 ce_stage(ce
), fullname
.buf
,
1464 ce_stage(ce
), filename
);
1467 if (file_exists(filename
))
1468 die("Path '%s' exists on disk, but not in the index.", filename
);
1469 if (errno
== ENOENT
|| errno
== ENOTDIR
)
1470 die("Path '%s' does not exist (neither on disk nor in the index).",
1473 strbuf_release(&fullname
);
1477 static char *resolve_relative_path(const char *rel
)
1479 if (!starts_with(rel
, "./") && !starts_with(rel
, "../"))
1482 if (!is_inside_work_tree())
1483 die("relative path syntax can't be used outside working tree.");
1485 /* die() inside prefix_path() if resolved path is outside worktree */
1486 return prefix_path(startup_info
->prefix
,
1487 startup_info
->prefix
? strlen(startup_info
->prefix
) : 0,
1491 static int get_sha1_with_context_1(const char *name
,
1494 unsigned char *sha1
,
1495 struct object_context
*oc
)
1497 int ret
, bracket_depth
;
1498 int namelen
= strlen(name
);
1500 int only_to_die
= flags
& GET_SHA1_ONLY_TO_DIE
;
1503 flags
|= GET_SHA1_QUIETLY
;
1505 memset(oc
, 0, sizeof(*oc
));
1506 oc
->mode
= S_IFINVALID
;
1507 ret
= get_sha1_1(name
, namelen
, sha1
, flags
);
1511 * sha1:path --> object name of path in ent sha1
1512 * :path -> object name of absolute path in index
1513 * :./path -> object name of path relative to cwd in index
1514 * :[0-3]:path -> object name of path in index at stage
1515 * :/foo -> recent commit matching foo
1517 if (name
[0] == ':') {
1519 const struct cache_entry
*ce
;
1520 char *new_path
= NULL
;
1522 if (!only_to_die
&& namelen
> 2 && name
[1] == '/') {
1523 struct commit_list
*list
= NULL
;
1525 for_each_ref(handle_one_ref
, &list
);
1526 commit_list_sort_by_date(&list
);
1527 return get_sha1_oneline(name
+ 2, sha1
, list
);
1531 name
[1] < '0' || '3' < name
[1])
1534 stage
= name
[1] - '0';
1537 new_path
= resolve_relative_path(cp
);
1539 namelen
= namelen
- (cp
- name
);
1542 namelen
= strlen(cp
);
1545 strlcpy(oc
->path
, cp
, sizeof(oc
->path
));
1549 pos
= cache_name_pos(cp
, namelen
);
1552 while (pos
< active_nr
) {
1553 ce
= active_cache
[pos
];
1554 if (ce_namelen(ce
) != namelen
||
1555 memcmp(ce
->name
, cp
, namelen
))
1557 if (ce_stage(ce
) == stage
) {
1558 hashcpy(sha1
, ce
->oid
.hash
);
1559 oc
->mode
= ce
->ce_mode
;
1565 if (only_to_die
&& name
[1] && name
[1] != '/')
1566 diagnose_invalid_index_path(stage
, prefix
, cp
);
1570 for (cp
= name
, bracket_depth
= 0; *cp
; cp
++) {
1573 else if (bracket_depth
&& *cp
== '}')
1575 else if (!bracket_depth
&& *cp
== ':')
1579 unsigned char tree_sha1
[20];
1580 int len
= cp
- name
;
1581 unsigned sub_flags
= flags
;
1583 sub_flags
&= ~GET_SHA1_DISAMBIGUATORS
;
1584 sub_flags
|= GET_SHA1_TREEISH
;
1586 if (!get_sha1_1(name
, len
, tree_sha1
, sub_flags
)) {
1587 const char *filename
= cp
+1;
1588 char *new_filename
= NULL
;
1590 new_filename
= resolve_relative_path(filename
);
1592 filename
= new_filename
;
1593 if (flags
& GET_SHA1_FOLLOW_SYMLINKS
) {
1594 ret
= get_tree_entry_follow_symlinks(tree_sha1
,
1595 filename
, sha1
, &oc
->symlink_path
,
1598 ret
= get_tree_entry(tree_sha1
, filename
,
1600 if (ret
&& only_to_die
) {
1601 diagnose_invalid_sha1_path(prefix
,
1607 hashcpy(oc
->tree
, tree_sha1
);
1608 strlcpy(oc
->path
, filename
, sizeof(oc
->path
));
1614 die("Invalid object name '%.*s'.", len
, name
);
1621 * Call this function when you know "name" given by the end user must
1622 * name an object but it doesn't; the function _may_ die with a better
1623 * diagnostic message than "no such object 'name'", e.g. "Path 'doc' does not
1624 * exist in 'HEAD'" when given "HEAD:doc", or it may return in which case
1625 * you have a chance to diagnose the error further.
1627 void maybe_die_on_misspelt_object_name(const char *name
, const char *prefix
)
1629 struct object_context oc
;
1630 unsigned char sha1
[20];
1631 get_sha1_with_context_1(name
, GET_SHA1_ONLY_TO_DIE
, prefix
, sha1
, &oc
);
1634 int get_sha1_with_context(const char *str
, unsigned flags
, unsigned char *sha1
, struct object_context
*orc
)
1636 if (flags
& GET_SHA1_FOLLOW_SYMLINKS
&& flags
& GET_SHA1_ONLY_TO_DIE
)
1637 die("BUG: incompatible flags for get_sha1_with_context");
1638 return get_sha1_with_context_1(str
, flags
, NULL
, sha1
, orc
);