@@ -7,6 +7,7 @@ use crate::retry::{run_with_retry_sync, ErrorClass};
77use anyhow:: { anyhow, Context , Error , Result } ;
88use crates_index:: Crate ;
99use reqwest:: StatusCode ;
10+ use semver:: Version ;
1011use std:: { collections:: HashMap , time:: Duration } ;
1112use std:: { fs, path:: Path } ;
1213
@@ -31,6 +32,11 @@ impl CratesIndex {
3132 Self ( Inner :: Fake ( FakeIndex :: from_file ( path) ) )
3233 }
3334
35+ /// Returns a fake crates.io index from a hashmap
36+ pub fn fake_from_map ( versions : HashMap < String , Vec < String > > ) -> Self {
37+ Self ( Inner :: Fake ( FakeIndex { crates : versions } ) )
38+ }
39+
3440 /// Retrieves the published versions for the given crate name.
3541 pub fn published_versions ( & self , crate_name : & str ) -> Result < Vec < String > > {
3642 match & self . 0 {
@@ -46,6 +52,12 @@ impl CratesIndex {
4652 }
4753}
4854
55+ pub fn is_published ( index : & CratesIndex , crate_name : & str , version : & Version ) -> Result < bool > {
56+ let crate_name = crate_name. to_string ( ) ;
57+ let versions = index. published_versions ( & crate_name) ?;
58+ Ok ( versions. contains ( & version. to_string ( ) ) )
59+ }
60+
4961fn published_versions ( index : & crates_index:: SparseIndex , crate_name : & str ) -> Result < Vec < String > > {
5062 let url = index
5163 . crate_url ( crate_name)
@@ -106,3 +118,51 @@ impl FakeIndex {
106118 FakeIndex { crates }
107119 }
108120}
121+
122+ #[ cfg( test) ]
123+ mod test {
124+ use crate :: index:: { is_published, CratesIndex } ;
125+ use semver:: Version ;
126+ use std:: collections:: HashMap ;
127+ use std:: sync:: Arc ;
128+
129+ /// Ignored test against the real index
130+ #[ ignore]
131+ #[ test]
132+ fn test_known_published_versions ( ) {
133+ let index = Arc :: new ( CratesIndex :: real ( ) . unwrap ( ) ) ;
134+ let known_published = Version :: new ( 1 , 1 , 7 ) ;
135+ let known_never_published = Version :: new ( 999 , 999 , 999 ) ;
136+ assert_eq ! (
137+ is_published( & index, "aws-smithy-runtime-api" , & known_published) . unwrap( ) ,
138+ true
139+ ) ;
140+
141+ assert_eq ! (
142+ is_published( & index, "aws-smithy-runtime-api" , & known_never_published) . unwrap( ) ,
143+ false
144+ ) ;
145+ }
146+
147+ /// Ignored test against the real index
148+ #[ test]
149+ fn test_against_fake_index ( ) {
150+ let mut crates = HashMap :: new ( ) ;
151+ crates. insert (
152+ "aws-smithy-runtime-api" . to_string ( ) ,
153+ vec ! [ "1.1.7" . to_string( ) ] ,
154+ ) ;
155+ let index = Arc :: new ( CratesIndex :: fake_from_map ( crates) ) ;
156+ let known_published = Version :: new ( 1 , 1 , 7 ) ;
157+ let known_never_published = Version :: new ( 999 , 999 , 999 ) ;
158+ assert_eq ! (
159+ is_published( & index, "aws-smithy-runtime-api" , & known_published) . unwrap( ) ,
160+ true
161+ ) ;
162+
163+ assert_eq ! (
164+ is_published( & index, "aws-smithy-runtime-api" , & known_never_published) . unwrap( ) ,
165+ false
166+ ) ;
167+ }
168+ }
0 commit comments