diff --git a/Cargo.toml b/Cargo.toml index 86de97b..329a080 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,6 @@ once_cell = "1.4" slog = { version = "2", features = ["max_level_trace", "release_max_level_trace"] } slog-term = "2.5" slog-async = "2.7" -nonzero_ext = "0.3.0" [dev-dependencies] tempfile = "3" diff --git a/src/artifacts/mod.rs b/src/artifacts/mod.rs index 74c21c7..20ed4fa 100644 --- a/src/artifacts/mod.rs +++ b/src/artifacts/mod.rs @@ -1,24 +1,13 @@ -use std::path::{self, PathBuf}; -use std::rc::Rc; +use std::path::{Path as ActualPath, PathBuf}; #[derive(Clone, Debug)] -pub struct Path(Rc); +pub struct Path(PathBuf); -impl Path { - pub(crate) fn clone_rc(&self) -> Rc { - Rc::clone(&self.0) - } - - pub fn join(&self, path: impl AsRef) -> Self { - Self::from(self.0.join(path)) - } -} - -// FIXME: This is a specialization since with Path: AsRef +// FIXME: This is a specialization since with Path: Into // it would overwrite impl From for T -//impl> From for Path { +//impl> From for Path { // fn from(v: T) -> Self { -// Self(v.as_ref().into()) +// Path(v.into()) // } //} @@ -26,8 +15,7 @@ macro_rules! path_from { ( $t:ty ) => { impl From<$t> for Path { fn from(v: $t) -> Self { - let path: &path::Path = v.as_ref(); - Self(path.into()) + Self(v.into()) } } }; @@ -37,35 +25,23 @@ path_from!(String); path_from!(&str); path_from!(PathBuf); -impl From> for Path { - fn from(v: Rc) -> Self { - Self(v) - } -} - -impl AsRef for Path { - fn as_ref(&self) -> &path::Path { - &self.0 - } -} - -impl From for Rc { +impl From for PathBuf { fn from(v: Path) -> Self { v.0 } } -impl From<&Path> for Rc { - fn from(v: &Path) -> Self { - v.0.clone() +impl AsRef for Path { + fn as_ref(&self) -> &ActualPath { + &self.0 } } #[derive(Clone, Debug)] -pub struct UserName(pub Rc); +pub struct UserName(pub String); #[derive(Clone, Debug)] -pub struct ServiceName(pub Rc); +pub struct ServiceName(pub String); #[derive(Clone, Debug)] -pub struct DatabaseName(pub Rc); +pub struct DatabaseName(pub String); diff --git a/src/bin.rs b/src/bin.rs index 3618616..91b66e9 100644 --- a/src/bin.rs +++ b/src/bin.rs @@ -2,7 +2,7 @@ use std::env; use std::process::exit; pub fn schematics_main(run: &dyn Fn(bool) -> Result<(), ()>) { - let args: Box<[String]> = env::args().collect(); + let args: Vec = env::args().collect(); let dry_run = match args.len() { 1 => false, 2 => { diff --git a/src/build.rs b/src/build.rs index 3ba1ccc..772339c 100644 --- a/src/build.rs +++ b/src/build.rs @@ -15,8 +15,7 @@ pub fn create_static_output( .to_str() .ok_or("Filename is not valid unicode")? .to_uppercase(); - let file = read_file(source_path)?; - let content = std::str::from_utf8(&file)?; + let content = String::from_utf8(read_file(source_path)?)?; let fence = content.chars().filter(|&c| c == '#').collect::() + "#"; writeln!( diff --git a/src/builder.rs b/src/builder.rs index 3230844..394d3d1 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -41,8 +41,7 @@ use crate::templates::systemd::{ }; use crate::to_artifact::ToArtifact; use std::fmt::Display; -use std::path::Path; -use std::rc::Rc; +use std::path::{Path, PathBuf}; pub trait ImplementationBuilder { type Prerequisites: ToArtifact; @@ -65,13 +64,13 @@ impl ImplementationBuilder> for DefaultBuilder { type Prerequisites = (); fn prerequisites(_resource: &Key) -> Self::Prerequisites {} - type Implementation = KeySymbol>; + type Implementation = KeySymbol; fn create( _resource: &Key, target: & as Resource>::Artifact, (): ::Artifact, ) -> Self::Implementation { - KeySymbol::new(StdCommandRunner, target.clone_rc()) + KeySymbol::new(StdCommandRunner, target.clone().into()) } } @@ -81,7 +80,7 @@ impl ImplementationBuilder> for DefaultBuilder { Key(resource.0.clone()) } - type Implementation = CsrSymbol, Rc>; + type Implementation = CsrSymbol; fn create( resource: &Csr, target: & as Resource>::Artifact, @@ -90,8 +89,8 @@ impl ImplementationBuilder> for DefaultBuilder { CsrSymbol::new( StdCommandRunner, resource.0.clone(), - key.clone_rc(), - target.clone_rc(), + key.into(), + target.clone().into(), ) } } @@ -117,7 +116,7 @@ impl ImplementationBuilder> for DefaultBuilder { } type Implementation = - CertSymbol>, SetuidCommandRunner>, D, Rc>; + CertSymbol, SetuidCommandRunner, D, PathBuf>; fn create( resource: &Cert, target: & as Resource>::Artifact, @@ -126,11 +125,11 @@ impl ImplementationBuilder> for DefaultBuilder { CertSymbol::new( resource.0.clone(), SetuidCommandRunner::new(user_name.0), - root_cert.clone_rc(), - account_key.clone_rc(), - challenges_dir.clone_rc(), - csr.clone_rc(), - target.clone_rc(), + root_cert.into(), + account_key.into(), + challenges_dir.into(), + csr.into(), + target.clone().into(), ) } } @@ -141,13 +140,13 @@ impl ImplementationBuilder> for DefaultBuilder { (Cert(resource.0.clone()), AcmeRootCert) } - type Implementation = ConcatSymbol<[Rc; 2], Rc, Rc>; + type Implementation = ConcatSymbol<[PathBuf; 2], PathBuf, PathBuf>; fn create( _resource: &CertChain, target: & as Resource>::Artifact, (cert, root_cert): ::Artifact, ) -> Self::Implementation { - ConcatSymbol::new([cert.clone_rc(), root_cert.clone_rc()], target.clone_rc()) + ConcatSymbol::new([cert.into(), root_cert.into()], target.clone().into()) } } @@ -157,13 +156,13 @@ impl ImplementationBuilder> for DefaultBuilder { (CertChain(resource.0.clone()), Key(resource.0.clone())) } - type Implementation = ConcatSymbol<[Rc; 2], Rc, Rc>; + type Implementation = ConcatSymbol<[PathBuf; 2], PathBuf, PathBuf>; fn create( _resource: &KeyAndCertBundle, target: & as Resource>::Artifact, (cert_chain, key): ::Artifact, ) -> Self::Implementation { - ConcatSymbol::new([key.clone_rc(), cert_chain.clone_rc()], target.clone_rc()) + ConcatSymbol::new([key.into(), cert_chain.into()], target.clone().into()) } } @@ -171,7 +170,7 @@ impl + Clone> ImplementationBuilder> for DefaultBuilder { type Prerequisites = (); fn prerequisites(_resource: &File

) -> Self::Prerequisites {} - type Implementation = FileSymbol>; + type Implementation = FileSymbol; fn create( resource: &File

, _target: & as Resource>::Artifact, @@ -202,7 +201,7 @@ impl ImplementationBuilder for DefaultBuilder { } type Implementation = ( - FileSymbol, Box>, + FileSymbol, ReloadServiceSymbol, ); fn create( @@ -212,8 +211,8 @@ impl ImplementationBuilder for DefaultBuilder { ) -> Self::Implementation { ( FileSymbol::new( - target.clone_rc(), - nginx::default_server(challenges_snippet_path).into(), + target.clone().into(), + nginx::default_server(challenges_snippet_path), ), ReloadServiceSymbol::new(StdCommandRunner, "nginx"), ) @@ -231,7 +230,7 @@ impl + Clone + Display> ImplementationBuilder> for } type Implementation = ( - FileSymbol, Box>, + FileSymbol, ReloadServiceSymbol, ); fn create( @@ -241,8 +240,8 @@ impl + Clone + Display> ImplementationBuilder> for ) -> Self::Implementation { ( FileSymbol::new( - target.clone_rc(), - nginx::server_config(&resource.0, cert, key, &resource.1, challenges_snippet_path).into(), + target.clone().into(), + nginx::server_config(&resource.0, cert, key, &resource.1, challenges_snippet_path), ), ReloadServiceSymbol::new(StdCommandRunner, "nginx"), ) @@ -268,7 +267,7 @@ impl, C: Clone + Into> } type Implementation = ( - FileSymbol, Box>, + FileSymbol, ReloadServiceSymbol, ); fn create( @@ -278,15 +277,14 @@ impl, C: Clone + Into> ) -> Self::Implementation { ( FileSymbol::new( - target.clone_rc(), + target.clone().into(), nginx::server_config( &resource.0, cert, key, nginx::php_snippet(resource.2, pool.0, &resource.1) + &resource.3, challenges_snippet_path, - ) - .into(), + ), ), ReloadServiceSymbol::new(StdCommandRunner, "nginx"), ) @@ -318,7 +316,7 @@ impl> ImplementationBuilder, Box>, + FileSymbol, ReloadServiceSymbol, ); fn create( @@ -328,15 +326,14 @@ impl> ImplementationBuilder Self::Implementation { ( FileSymbol::new( - target.clone_rc(), + target.clone().into(), nginx::server_config( &resource.0, cert, key, nginx::proxy_snippet(&socket.0, &resource.3), challenges_snippet_path, - ) - .into(), + ), ), ReloadServiceSymbol::new(StdCommandRunner, "nginx"), ) @@ -354,7 +351,7 @@ impl + Clone + Display> ImplementationBuilder> for D } type Implementation = ( - FileSymbol, Box>, + FileSymbol, ReloadServiceSymbol, ); fn create( @@ -364,15 +361,14 @@ impl + Clone + Display> ImplementationBuilder> for D ) -> Self::Implementation { ( FileSymbol::new( - target.clone_rc(), + target.clone().into(), nginx::server_config( &resource.0, cert, key, nginx::redir_snippet(resource.1.as_ref()), challenges_snippet_path, - ) - .into(), + ), ), ReloadServiceSymbol::new(StdCommandRunner, "nginx"), ) @@ -392,7 +388,7 @@ impl + Clone + Display, P: AsRef> ImplementationBuilder, Box>, + FileSymbol, ReloadServiceSymbol, ); fn create( @@ -402,15 +398,14 @@ impl + Clone + Display, P: AsRef> ImplementationBuilder Self::Implementation { ( FileSymbol::new( - target.clone_rc(), + target.clone().into(), nginx::server_config( &resource.0, cert, key, nginx::static_snippet(resource.1.as_ref()), challenges_snippet_path, - ) - .into(), + ), ), ReloadServiceSymbol::new(StdCommandRunner, "nginx"), ) @@ -422,8 +417,8 @@ impl ImplementationBuilder> for DefaultBuilder { fn prerequisites(_resource: &PhpFpmPool) -> Self::Prerequisites {} type Implementation = ( - FileSymbol, Box>, - ReloadServiceSymbol>, + FileSymbol, + ReloadServiceSymbol, ); fn create( resource: &PhpFpmPool, @@ -432,8 +427,8 @@ impl ImplementationBuilder> for DefaultBuilder { ) -> Self::Implementation { ( FileSymbol::new( - conf_path.clone_rc(), - php_fpm_pool_config(&user_name.0, socket_path, &resource.1).into(), + conf_path.clone().into(), + php_fpm_pool_config(&user_name.0, socket_path, &resource.1), ), ReloadServiceSymbol::new(StdCommandRunner, service_name.0.clone()), ) @@ -446,10 +441,10 @@ impl> ImplementationBuilder> for De type Implementation = ( // First three could be parallel - FileSymbol, Box>, - SystemdUserSessionSymbol<'static, Rc, StdCommandRunner>, - OwnerSymbol, Rc>, - UserServiceSymbol<'static, Rc, Rc>, + FileSymbol, + SystemdUserSessionSymbol<'static, String, StdCommandRunner>, + OwnerSymbol, + UserServiceSymbol<'static, PathBuf, String>, ); fn create( resource: &SystemdSocketService, @@ -458,7 +453,7 @@ impl> ImplementationBuilder> for De ) -> Self::Implementation { ( FileSymbol::new( - conf_path.clone_rc(), + conf_path.clone().into(), if resource.4 { systemd_nodejs_service(&resource.2, socket_path, &resource.3) } else { @@ -468,16 +463,15 @@ impl> ImplementationBuilder> for De &resource.3, "", ) - } - .into(), + }, ), SystemdUserSessionSymbol::new(user_name.0.clone(), &StdCommandRunner), OwnerSymbol::new( - conf_path.as_ref().parent().unwrap().into(), + conf_path.as_ref().parent().unwrap().to_path_buf(), user_name.0.clone(), StdCommandRunner, ), - UserServiceSymbol::new(socket_path.clone_rc(), user_name.0.clone(), resource.1), + UserServiceSymbol::new(socket_path.clone().into(), user_name.0.clone(), resource.1), ) } } @@ -522,7 +516,7 @@ impl> ImplementationBuilder> for Defau ) -> Self::Implementation { SavedDirectorySymbol::new( resource.1.clone(), - SimpleStorage::new(target.clone_rc()), + SimpleStorage::new(target.clone().into()), StorageDirection::Store, StdCommandRunner, ) @@ -541,7 +535,7 @@ impl> ImplementationBuilder> for Defau ) -> Self::Implementation { SavedDirectorySymbol::new( resource.1.clone(), - SimpleStorage::new(target.clone_rc()), + SimpleStorage::new(target.clone().into()), StorageDirection::Load, StdCommandRunner, ) @@ -552,7 +546,7 @@ impl ImplementationBuilder> for DefaultBuilder { type Prerequisites = (); fn prerequisites(_resource: &UserForDomain) -> Self::Prerequisites {} - type Implementation = UserSymbol, StdCommandRunner>; + type Implementation = UserSymbol; fn create( _resource: &UserForDomain, (user_name, _home_path): & as Resource>::Artifact, @@ -566,7 +560,7 @@ impl ImplementationBuilder for DefaultBuilder { type Prerequisites = (); fn prerequisites(_resource: &User) -> Self::Prerequisites {} - type Implementation = UserSymbol, StdCommandRunner>; + type Implementation = UserSymbol; fn create( resource: &User, (): &::Artifact, @@ -580,7 +574,7 @@ impl + Clone> ImplementationBuilder> for DefaultBuilder type Prerequisites = (); fn prerequisites(_resource: &Owner

) -> Self::Prerequisites {} - type Implementation = OwnerSymbol>; + type Implementation = OwnerSymbol; fn create( resource: &Owner

, (): & as Resource>::Artifact, @@ -594,7 +588,7 @@ impl ImplementationBuilder for DefaultBuilder { type Prerequisites = (); fn prerequisites(_resource: &AcmeUser) -> Self::Prerequisites {} - type Implementation = UserSymbol, StdCommandRunner>; + type Implementation = UserSymbol; fn create( _resource: &AcmeUser, user_name: &::Artifact, @@ -611,8 +605,8 @@ impl ImplementationBuilder for DefaultBuilder { } type Implementation = ( - DirSymbol>, - OwnerSymbol, Rc>, + DirSymbol, + OwnerSymbol, ); fn create( _resource: &AcmeChallengesDir, @@ -620,8 +614,8 @@ impl ImplementationBuilder for DefaultBuilder { user_name: ::Artifact, ) -> Self::Implementation { ( - DirSymbol::new(target.clone_rc()), - OwnerSymbol::new(target.clone_rc(), user_name.0, StdCommandRunner), + DirSymbol::new(target.clone().into()), + OwnerSymbol::new(target.clone().into(), user_name.0, StdCommandRunner), ) } } @@ -632,15 +626,15 @@ impl ImplementationBuilder for DefaultBuilder { AcmeChallengesDir } - type Implementation = FileSymbol, Box>; + type Implementation = FileSymbol; fn create( _resource: &AcmeChallengesNginxSnippet, target: &::Artifact, challenges_dir: ::Artifact, ) -> Self::Implementation { FileSymbol::new( - target.clone_rc(), - nginx::acme_challenges_snippet(challenges_dir).into(), + target.clone().into(), + nginx::acme_challenges_snippet(challenges_dir), ) } } @@ -652,8 +646,8 @@ impl ImplementationBuilder for DefaultBuilder { } type Implementation = ( - KeySymbol>, - OwnerSymbol, Rc>, + KeySymbol, + OwnerSymbol, ); fn create( _resource: &AcmeAccountKey, @@ -661,8 +655,8 @@ impl ImplementationBuilder for DefaultBuilder { user_name: ::Artifact, ) -> Self::Implementation { ( - KeySymbol::new(StdCommandRunner, target.clone_rc()), - OwnerSymbol::new(target.clone_rc(), user_name.0, StdCommandRunner), + KeySymbol::new(StdCommandRunner, target.clone().into()), + OwnerSymbol::new(target.clone().into(), user_name.0, StdCommandRunner), ) } } @@ -671,13 +665,13 @@ impl ImplementationBuilder for DefaultBuilder { type Prerequisites = (); fn prerequisites(_resource: &AcmeRootCert) -> Self::Prerequisites {} - type Implementation = FileSymbol, &'static str>; + type Implementation = FileSymbol; fn create( _resource: &AcmeRootCert, target: &::Artifact, (): ::Artifact, ) -> Self::Implementation { - FileSymbol::new(target.clone_rc(), LETS_ENCRYPT_R3) + FileSymbol::new(target.clone().into(), LETS_ENCRYPT_R3) } } @@ -685,7 +679,7 @@ impl ImplementationBuilder> for DefaultBuilder { type Prerequisites = (); fn prerequisites(_resource: &MariaDbUser) -> Self::Prerequisites {} - type Implementation = MariaDbUserSymbol<'static, Rc, StdCommandRunner>; + type Implementation = MariaDbUserSymbol<'static, String, StdCommandRunner>; fn create( _resource: &MariaDbUser, user_name: & as Resource>::Artifact, @@ -702,15 +696,15 @@ impl ImplementationBuilder> for DefaultBuilder { } type Implementation = ( - MariaDbDatabaseSymbol<'static, Rc, SimpleStorage, StdCommandRunner>, - MariaDbDumpSymbol<'static, Rc, StdCommandRunner, SimpleStorage>, + MariaDbDatabaseSymbol<'static, String, SimpleStorage, StdCommandRunner>, + MariaDbDumpSymbol<'static, String, StdCommandRunner, SimpleStorage>, ); fn create( _resource: &MariaDbDatabase, (db_name, _, data_path): & as Resource>::Artifact, _: ::Artifact, ) -> Self::Implementation { - let db_dump = SimpleStorage::new(data_path.clone_rc()); + let db_dump = SimpleStorage::new(data_path.clone().into()); ( MariaDbDatabaseSymbol::new(db_name.0.clone(), db_dump.clone(), &StdCommandRunner), MariaDbDumpSymbol::new(db_name.0.clone(), db_dump, &StdCommandRunner), @@ -722,13 +716,13 @@ impl ImplementationBuilder> for DefaultBuilder { type Prerequisites = (); fn prerequisites(_: &PostgresqlDatabase) -> Self::Prerequisites {} - type Implementation = (PostgreSQLDatabaseSymbol<'static, Rc, Rc, StdCommandRunner>,); + type Implementation = (PostgreSQLDatabaseSymbol<'static, String, String, StdCommandRunner>,); fn create( _resource: &PostgresqlDatabase, (db_name, data_path): & as Resource>::Artifact, _: ::Artifact, ) -> Self::Implementation { - let db_dump = SimpleStorage::new(data_path.clone_rc()); + let db_dump = SimpleStorage::new(data_path.clone().into()); (PostgreSQLDatabaseSymbol::new( db_name.0.clone(), db_dump.read_filename().unwrap().to_str().unwrap().into(), @@ -738,9 +732,9 @@ impl ImplementationBuilder> for DefaultBuilder { } impl> ImplementationBuilder> for DefaultBuilder { - type Prerequisites = Dir>; + type Prerequisites = Dir; fn prerequisites(resource: &WordpressPlugin

) -> Self::Prerequisites { - Dir::new(resource.0.as_ref().join("wp-content/plugins")) + Dir(resource.0.as_ref().join("wp-content/plugins")) } type Implementation = WordpressPluginSymbol<'static, P, &'static str, StdCommandRunner>; @@ -753,21 +747,21 @@ impl> ImplementationBuilder> for Defau } } -impl> ImplementationBuilder> for DefaultBuilder { - type Prerequisites = Dir>; +impl> ImplementationBuilder> for DefaultBuilder { + type Prerequisites = Dir; fn prerequisites(resource: &WordpressTranslation

) -> Self::Prerequisites { - Dir::new(resource.0.as_ref().join("wp-content/languages")) + Dir(resource.0.as_ref().join("wp-content/languages")) } type Implementation = - WordpressTranslationSymbol<'static, &'static str, Box, StdCommandRunner>; + WordpressTranslationSymbol<'static, &'static str, PathBuf, StdCommandRunner>; fn create( resource: &WordpressTranslation

, (): & as Resource>::Artifact, _: ::Artifact, ) -> Self::Implementation { WordpressTranslationSymbol::new( - (*resource.0.as_ref().join("wp-content/languages")).into(), + resource.0.as_ref().join("wp-content/languages"), resource.1, resource.2, &StdCommandRunner, @@ -781,7 +775,7 @@ impl ImplementationBuilder> for DefaultBuilder { UserForDomain(resource.0.clone()) } - type Implementation = CronSymbol<'static, Box, Rc, StdCommandRunner>; + type Implementation = CronSymbol<'static, String, String, StdCommandRunner>; fn create( resource: &Cron, (): & as Resource>::Artifact, diff --git a/src/command_runner.rs b/src/command_runner.rs index ec10437..70418d8 100644 --- a/src/command_runner.rs +++ b/src/command_runner.rs @@ -19,7 +19,7 @@ fn check_success(output: Output) -> Result> { if output.status.success() { Ok(output) } else { - Err(std::str::from_utf8(&output.stderr)?.into()) + Err(String::from_utf8(output.stderr)?.into()) } } @@ -93,7 +93,7 @@ struct TempSetEnv<'a> { } impl<'a> TempSetEnv<'a> { - fn new(name: &'a str, new_value: impl AsRef) -> TempSetEnv<'a> { + fn new(name: &'a str, new_value: String) -> TempSetEnv<'a> { let old_value = env::var(name); env::set_var(name, new_value); TempSetEnv { diff --git a/src/locator.rs b/src/locator.rs index 2591253..3322baa 100644 --- a/src/locator.rs +++ b/src/locator.rs @@ -12,8 +12,7 @@ use crate::resources::{ use crate::to_artifact::ToArtifact; use std::fmt::Display; use std::marker::PhantomData; -use std::path::Path; -use std::rc::Rc; +use std::path::{Path, PathBuf}; pub trait Policy { #[must_use] @@ -22,13 +21,13 @@ pub trait Policy { } #[must_use] - fn user_home(user_name: &str) -> Rc { - Path::new("/home").join(user_name).into() + fn user_home(user_name: &str) -> PathBuf { + Path::new("/home").join(user_name) } #[must_use] - fn user_name_for_domain(domain_name: &'_ str) -> Rc { - domain_name.split('.').rev().fold(String::new(), |result, part| if result.is_empty() { result } else { result + "_" } + part).into() + fn user_name_for_domain(domain_name: &'_ str) -> String { + domain_name.split('.').rev().fold(String::new(), |result, part| if result.is_empty() { result } else { result + "_" } + part) } #[must_use] @@ -37,8 +36,8 @@ pub trait Policy { } #[must_use] - fn path_for_data(name: impl Display) -> Rc { - Path::new("/root/data").join(format!("_{name}")).into() + fn path_for_data(name: impl Display) -> PathBuf { + Path::new("/root/data").join(format!("_{name}")) } } @@ -60,37 +59,37 @@ pub struct DefaultLocator

{ } impl> ResourceLocator> for DefaultLocator

{ - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate(resource: &Key) -> ( as Resource>::Artifact, Self::Prerequisites) { ( PathArtifact::from(format!("/etc/ssl/private/{}.key", resource.0.as_ref())), - Dir::new("/etc/ssl/private"), + Dir("/etc/ssl/private".into()), ) } } impl> ResourceLocator> for DefaultLocator

{ - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate(resource: &Csr) -> ( as Resource>::Artifact, Self::Prerequisites) { ( PathArtifact::from(format!("/etc/ssl/local_certs/{}.csr", resource.0.as_ref())), - Dir::new("/etc/ssl/local_certs"), + Dir("/etc/ssl/local_certs".into()), ) } } impl> ResourceLocator> for DefaultLocator

{ - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate(resource: &Cert) -> ( as Resource>::Artifact, Self::Prerequisites) { ( PathArtifact::from(format!("/etc/ssl/local_certs/{}.crt", resource.0.as_ref())), - Dir::new("/etc/ssl/local_certs"), + Dir("/etc/ssl/local_certs".into()), ) } } impl> ResourceLocator> for DefaultLocator

{ - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate( resource: &CertChain, ) -> ( as Resource>::Artifact, Self::Prerequisites) { @@ -99,13 +98,13 @@ impl> ResourceLocator> for DefaultLocator

{ "/etc/ssl/local_certs/{}.chained.crt", resource.0.as_ref() )), - Dir::new("/etc/ssl/local_certs"), + Dir("/etc/ssl/local_certs".into()), ) } } impl> ResourceLocator> for DefaultLocator

{ - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate( resource: &KeyAndCertBundle, ) -> ( @@ -117,34 +116,34 @@ impl> ResourceLocator> for DefaultLocator

> ResourceLocator> for DefaultLocator { - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate(resource: &File

) -> ( as Resource>::Artifact, Self::Prerequisites) { - ((), Dir::new(resource.0.as_ref().parent().unwrap())) + ((), Dir(resource.0.as_ref().parent().unwrap().into())) } } impl<'a, POLICY, P: AsRef> ResourceLocator> for DefaultLocator { - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate( resource: &GitCheckout<'a, P>, ) -> ( as Resource>::Artifact, Self::Prerequisites, ) { - ((), Dir::new(resource.0.as_ref().parent().unwrap())) + ((), Dir(resource.0.as_ref().parent().unwrap().into())) } } impl> ResourceLocator> for DefaultLocator { - type Prerequisites = Option>>; + type Prerequisites = Option>; fn locate(resource: &Dir

) -> ( as Resource>::Artifact, Self::Prerequisites) { - ((), resource.0.as_ref().parent().map(Dir::new)) + ((), resource.0.as_ref().parent().map(|p| Dir(p.into()))) } } @@ -174,7 +173,7 @@ impl> ResourceLocator> impl> ResourceLocator> for DefaultLocator { - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate( resource: &LoadedDirectory

, ) -> ( @@ -183,13 +182,13 @@ impl> ResourceLocator> ) { ( PathArtifact::from(POLICY::path_for_data(resource.0)), - Dir::new(resource.1.as_ref().parent().unwrap()), + Dir(resource.1.as_ref().parent().unwrap().into()), ) } } impl ResourceLocator for DefaultLocator

{ - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate( _resource: &AcmeAccountKey, ) -> (::Artifact, Self::Prerequisites) { @@ -208,7 +207,7 @@ impl ResourceLocator for DefaultLocator

{ } impl ResourceLocator for DefaultLocator

{ - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate( _resource: &AcmeChallengesDir, ) -> ( @@ -237,7 +236,7 @@ impl ResourceLocator for DefaultLocator

ResourceLocator for DefaultLocator

{ - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate( _resource: &AcmeRootCert, ) -> (::Artifact, Self::Prerequisites) { @@ -371,7 +370,7 @@ impl, P: Policy> ResourceLocator> for Defaul php_version, user.0 )), user, - ServiceNameArtifact(format!("php{php_version}-fpm").into()), + ServiceNameArtifact(format!("php{php_version}-fpm")), ), (), ) @@ -381,7 +380,7 @@ impl, P: Policy> ResourceLocator> for Defaul impl, P, POLICY: Policy> ResourceLocator> for DefaultLocator { - type Prerequisites = Dir>; + type Prerequisites = Dir; fn locate( resource: &SystemdSocketService, ) -> ( @@ -397,7 +396,7 @@ impl, P, POLICY: Policy> ResourceLocator Resource for KeyAndCertBundle { } #[derive(Debug, Hash, PartialEq, Eq)] -pub struct File

(pub P, pub Rc); +pub struct File

(pub P, pub String); impl

Resource for File

{ type Artifact = (); } -impl File> { - pub fn new(p: impl Into>, content: impl AsRef) -> Self { - Self(p.into(), content.as_ref().into()) - } -} - #[derive(Debug, Hash, PartialEq, Eq)] pub struct GitCheckout<'a, P>(pub P, pub &'a str, pub &'a str); impl<'a, P> Resource for GitCheckout<'a, P> { type Artifact = (); } -impl<'a> GitCheckout<'a, Rc> { - pub fn new(target: impl Into>, src: &'a str, head: &'a str) -> Self { - Self(target.into(), src, head) - } -} - #[derive(Debug, Hash, PartialEq, Eq)] pub struct Dir

(pub P); impl

Resource for Dir

{ type Artifact = (); } -impl Dir> { - pub fn new(p: impl AsRef) -> Self { - Self(p.as_ref().into()) - } -} - #[derive(Debug, Hash, PartialEq, Eq)] pub struct UserForDomain(pub D); impl Resource for UserForDomain { @@ -124,11 +106,10 @@ impl

Resource for LoadedDirectory

{ type Artifact = PathArtifact; } -pub fn get_saved_directory( +pub fn get_saved_directory( storage_name: &'static str, - target: impl Into>, -) -> (StoredDirectory>, LoadedDirectory>) { - let target = target.into(); + target: P, +) -> (StoredDirectory

, LoadedDirectory

) { ( StoredDirectory(storage_name, target.clone()), LoadedDirectory(storage_name, target), @@ -136,7 +117,7 @@ pub fn get_saved_directory( } #[derive(Debug, Hash, PartialEq, Eq)] -pub struct User(pub Rc); +pub struct User(pub String); impl Resource for User { type Artifact = (); } @@ -153,32 +134,20 @@ impl

Resource for NpmInstall

{ type Artifact = (); } -impl NpmInstall> { - pub fn new(path: impl Into>) -> Self { - Self(path.into()) - } -} - #[derive(Debug, Hash, PartialEq, Eq)] -pub struct Owner

(pub Rc, pub P); +pub struct Owner

(pub String, pub P); impl

Resource for Owner

{ type Artifact = (); } -impl Owner> { - pub fn new(user: &UserNameArtifact, p: impl Into>) -> Self { - Self(user.0.clone(), p.into()) - } -} - #[derive(Debug, Hash, PartialEq, Eq)] -pub struct ServeCustom(pub D, pub Rc); +pub struct ServeCustom(pub D, pub String); impl Resource for ServeCustom { type Artifact = PathArtifact; } #[derive(Debug, Hash, PartialEq, Eq)] -pub struct ServePhp(pub D, pub P, pub &'static str, pub Rc, pub C); +pub struct ServePhp(pub D, pub P, pub &'static str, pub String, pub C); impl Resource for ServePhp { type Artifact = PathArtifact; } @@ -189,25 +158,6 @@ pub struct ServeService(pub D, pub &'static str, pub P, pub P, pub P, pub impl Resource for ServeService { type Artifact = PathArtifact; } -impl ServeService> { - pub fn new( - domain: D, - service_name: &'static str, - exec: impl Into>, - static_path: impl Into>, - working_directory: impl Into>, - is_nodejs: bool, - ) -> Self { - Self( - domain, - service_name, - exec.into(), - static_path.into(), - working_directory.into(), - is_nodejs, - ) - } -} #[derive(Debug, Hash, PartialEq, Eq)] pub struct ServeRedir(pub D, pub D); @@ -221,12 +171,6 @@ impl Resource for ServeStatic { type Artifact = PathArtifact; } -impl ServeStatic> { - pub fn new(domain: D, path: impl Into>) -> Self { - Self(domain, path.into()) - } -} - #[derive(Debug, Hash, PartialEq, Eq)] pub struct DefaultServer; impl Resource for DefaultServer { @@ -269,26 +213,14 @@ impl

Resource for WordpressPlugin

{ type Artifact = (); } -impl WordpressPlugin> { - pub fn new(path: impl Into>, name: &'static str) -> Self { - Self(path.into(), name) - } -} - #[derive(Debug, Hash, PartialEq, Eq)] pub struct WordpressTranslation

(pub P, pub &'static str, pub &'static str); impl

Resource for WordpressTranslation

{ type Artifact = (); } -impl WordpressTranslation> { - pub fn new(path: impl Into>, version: &'static str, lang: &'static str) -> Self { - Self(path.into(), version, lang) - } -} - #[derive(Debug, Hash, PartialEq, Eq)] -pub struct Cron(pub D, pub Rc); +pub struct Cron(pub D, pub String); impl Resource for Cron { type Artifact = (); } @@ -355,38 +287,38 @@ default_resources!( Cron: Cron, Csr: Csr, DefaultServer: DefaultServer, - Dir: Dir>, - File: File>, - GitCheckout: GitCheckout<'a, Rc>, + Dir: Dir, + File: File, + GitCheckout: GitCheckout<'a, PathBuf>, Key: Key, KeyAndCertBundle: KeyAndCertBundle, - LoadedDirectory: LoadedDirectory>, + LoadedDirectory: LoadedDirectory, MariaDbDatabase: MariaDbDatabase, MariaDbUser: MariaDbUser, PostgresqlDatabase: PostgresqlDatabase, - SystemdSocketService: SystemdSocketService>, - NpmInstall: NpmInstall>, - Owner: Owner>, + SystemdSocketService: SystemdSocketService, + NpmInstall: NpmInstall, + Owner: Owner, PhpFpmPool: PhpFpmPool, ServeCustom: ServeCustom, - ServeService: ServeService>, - ServePhp: ServePhp, FpmPoolConfig>, + ServeService: ServeService, + ServePhp: ServePhp, ServeRedir: ServeRedir, - ServeStatic: ServeStatic>, - StoredDirectory: StoredDirectory>, + ServeStatic: ServeStatic, + StoredDirectory: StoredDirectory, User: User, UserForDomain: UserForDomain, - WordpressPlugin: WordpressPlugin>, - WordpressTranslation: WordpressTranslation>, + WordpressPlugin: WordpressPlugin, + WordpressTranslation: WordpressTranslation, ); -pub fn serve_php>( +pub fn serve_php, C: Into>( domain: D, - path: impl Into>, + path: P, root_filename: &'static str, - nginx_config: impl Into>, + nginx_config: impl Into, pool_config: C, -) -> ServePhp, FpmPoolConfig> { +) -> ServePhp { ServePhp( domain, path.into(), diff --git a/src/setup/mod.rs b/src/setup/mod.rs index e90ebf0..8302d77 100644 --- a/src/setup/mod.rs +++ b/src/setup/mod.rs @@ -169,7 +169,7 @@ impl< #[cfg(test)] mod test { - use super::symbol_runner::TestSymbolRunner; + use super::SymbolRunner; use crate::async_utils::run; use crate::loggers::{Entry, StoringLogger}; use crate::resources::{FromArtifact, FromResource, Resource}; @@ -178,11 +178,33 @@ mod test { use crate::{ImplementationBuilder, ResourceLocator, Setup}; use async_trait::async_trait; use regex::Regex; + use slog::{info, Logger}; use std::cell::RefCell; use std::error::Error; use std::fmt::Debug; use std::rc::{Rc, Weak}; + struct TestSymbolRunner { + count: Rc>, + } + + #[async_trait(?Send)] + impl SymbolRunner for TestSymbolRunner { + async fn run_symbol( + &self, + symbol: &S, + logger: &Logger, + force: bool, + ) -> Result> { + info!(logger, "run"); + let run = force || !symbol.target_reached().await?; + if run { + *self.count.borrow_mut() += 1; + } + Ok(run) + } + } + #[derive(Debug, PartialEq, Eq, Hash)] struct TestResource(&'static str, T); impl Resource for TestResource { @@ -286,7 +308,10 @@ mod test { >, StoringLogger, ) { - let (count, runner) = TestSymbolRunner::new(); + let count = Rc::new(RefCell::new(0)); + let runner = TestSymbolRunner { + count: Rc::clone(&count), + }; let logger = StoringLogger::new(); (count, Setup::new_with(runner, logger.clone()), logger) } diff --git a/src/setup/runnable.rs b/src/setup/runnable.rs index 4cf27af..092ea0f 100644 --- a/src/setup/runnable.rs +++ b/src/setup/runnable.rs @@ -53,10 +53,10 @@ for_each_tuple!(runnable_for_tuple); #[cfg(test)] mod test { - use super::super::symbol_runner::TestSymbolRunner; use super::Runnable; use crate::async_utils::run; use crate::symbols::Symbol; + use crate::SymbolRunner; use async_trait::async_trait; use slog::{o, Discard, Logger}; use std::cell::RefCell; @@ -103,11 +103,39 @@ mod test { } } + struct TestSymbolRunner { + count: Rc>, + } + + fn get_runner() -> (Rc>, TestSymbolRunner) { + let count = Rc::new(RefCell::new(0)); + let runner = TestSymbolRunner { + count: Rc::clone(&count), + }; + (count, runner) + } + + #[async_trait(?Send)] + impl SymbolRunner for TestSymbolRunner { + async fn run_symbol( + &self, + symbol: &S, + _logger: &Logger, + force: bool, + ) -> Result> { + let run = force || !symbol.target_reached().await?; + if run { + *self.count.borrow_mut() += 1; + } + Ok(run) + } + } + fn run_symbol( runnable: impl Runnable, force: bool, ) -> (Rc>, Result>) { - let (count, runner) = TestSymbolRunner::new(); + let (count, runner) = get_runner(); let res = run(runnable.run(&runner, &Logger::root(Discard, o!()), force)); (count, res) } diff --git a/src/setup/symbol_runner.rs b/src/setup/symbol_runner.rs index fc64a9b..ea628a3 100644 --- a/src/setup/symbol_runner.rs +++ b/src/setup/symbol_runner.rs @@ -2,13 +2,9 @@ use crate::async_utils::sleep; use crate::symbols::Symbol; use async_trait::async_trait; use slog::{debug, info, o, trace, Logger}; -#[cfg(test)] -use std::cell::RefCell; use std::error::Error; use std::fmt; use std::fmt::Debug; -#[cfg(test)] -use std::rc::Rc; use std::time::Duration; #[async_trait(?Send)] @@ -202,40 +198,6 @@ where } } -#[cfg(test)] -pub struct TestSymbolRunner { - count: Rc>, -} - -#[cfg(test)] -impl TestSymbolRunner { - pub fn new() -> (Rc>, Self) { - let count = Rc::new(RefCell::new(0)); - let runner = TestSymbolRunner { - count: Rc::clone(&count), - }; - (count, runner) - } -} - -#[cfg(test)] -#[async_trait(?Send)] -impl SymbolRunner for TestSymbolRunner { - async fn run_symbol( - &self, - symbol: &S, - logger: &Logger, - force: bool, - ) -> Result> { - info!(logger, "run"); - let run = force || !symbol.target_reached().await?; - if run { - *self.count.borrow_mut() += 1; - } - Ok(run) - } -} - #[cfg(test)] mod test { use super::{DrySymbolRunner, InitializingSymbolRunner, ReportingSymbolRunner, SymbolRunner}; diff --git a/src/storage.rs b/src/storage.rs index 61609bd..aa4ce9d 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -1,46 +1,49 @@ use std::error::Error; use std::fs::read_dir; -use std::path::Path; -use std::rc::Rc; +use std::path::PathBuf; use std::str::FromStr; use std::time::{SystemTime, UNIX_EPOCH}; pub trait Storage { - fn write_filename(&self) -> Box; - fn read_filename(&self) -> Result, Box>; + fn write_filename(&self) -> PathBuf; + fn read_filename(&self) -> Result>; fn recent_date(&self) -> Result>; } #[derive(Debug, Clone)] -pub struct SimpleStorage(Rc); +pub struct SimpleStorage(PathBuf); impl SimpleStorage { #[must_use] - pub const fn new(base: Rc) -> Self { + pub const fn new(base: PathBuf) -> Self { Self(base) } - fn get_path(&self, date: u64) -> Box { - self.0.join(date.to_string()).into() + fn get_path(&self, date: Option) -> PathBuf { + match date { + Some(d) => self.0.join(d.to_string()), + None => self.0.clone(), + } } } impl Storage for SimpleStorage { - fn write_filename(&self) -> Box { - self.get_path( + fn write_filename(&self) -> PathBuf { + self.get_path(Some( SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs(), - ) + )) } - fn read_filename(&self) -> Result, Box> { - Ok(self.get_path(self.recent_date()?)) + fn read_filename(&self) -> Result> { + Ok(self.get_path(Some(self.recent_date()?))) } fn recent_date(&self) -> Result> { - read_dir(&self.0)? + let dir = self.get_path(None); + read_dir(dir)? .map(|entry| { entry .ok() diff --git a/src/symbols/acme/cert.rs b/src/symbols/acme/cert.rs index 9055c85..e54f70a 100644 --- a/src/symbols/acme/cert.rs +++ b/src/symbols/acme/cert.rs @@ -102,7 +102,7 @@ impl<_C: CommandRunner, C: Borrow<_C>, D: AsRef, P: AsRef> Symbol for { Ok(false) } else { - Err(std::str::from_utf8(&output.stderr)?.into()) + Err(String::from_utf8(output.stderr)?.into()) } } diff --git a/src/symbols/cron.rs b/src/symbols/cron.rs index c0d7008..45571ed 100644 --- a/src/symbols/cron.rs +++ b/src/symbols/cron.rs @@ -10,11 +10,11 @@ pub struct Cron<'r, C, U, R> { command_runner: &'r R, } -impl<'r, U, R> Cron<'r, Box, U, R> { +impl<'r, U, R> Cron<'r, String, U, R> { pub fn new>(user: U, content: C, command_runner: &'r R) -> Self { Self { user, - content: (String::from(content.as_ref()) + "\n").into(), + content: String::from(content.as_ref()) + "\n", command_runner, } } diff --git a/src/symbols/git/submodules.rs b/src/symbols/git/submodules.rs index ec3fd6d..5413b8d 100644 --- a/src/symbols/git/submodules.rs +++ b/src/symbols/git/submodules.rs @@ -42,14 +42,15 @@ impl, C: CommandRunner> Symbol for GitSubmodules<'_, P, C> { if !self.target.as_ref().exists() { return Ok(false); } + let output = String::from_utf8( + self + ._run_in_target_repo(args!["submodule", "status"]) + .await?, + )?; Ok( - std::str::from_utf8( - &self - ._run_in_target_repo(args!["submodule", "status"]) - .await?, - )? - .lines() - .all(|line| line.is_empty() || line.starts_with(' ')), + output + .lines() + .all(|line| line.is_empty() || line.starts_with(' ')), ) } diff --git a/src/symbols/mariadb/database.rs b/src/symbols/mariadb/database.rs index 03d3d11..95ae693 100644 --- a/src/symbols/mariadb/database.rs +++ b/src/symbols/mariadb/database.rs @@ -11,7 +11,7 @@ pub struct Database<'a, D, S, C> { command_runner: &'a C, } -impl<'a, D, S, C> Database<'a, D, S, C> { +impl<'a, D, S, C: CommandRunner> Database<'a, D, S, C> { pub const fn new(db_name: D, seed_file: S, command_runner: &'a C) -> Self { Self { db_name, @@ -19,9 +19,7 @@ impl<'a, D, S, C> Database<'a, D, S, C> { command_runner, } } -} -impl<'a, D, S, C: CommandRunner> Database<'a, D, S, C> { async fn run_sql(&self, sql: &str) -> Result> { let b = self .command_runner diff --git a/src/symbols/mariadb/dump.rs b/src/symbols/mariadb/dump.rs index 50aae92..7503ad1 100644 --- a/src/symbols/mariadb/dump.rs +++ b/src/symbols/mariadb/dump.rs @@ -12,7 +12,7 @@ pub struct Dump<'a, N, C, S> { command_runner: &'a C, } -impl<'a, N, C, S> Dump<'a, N, C, S> { +impl<'a, N, C: CommandRunner, S> Dump<'a, N, C, S> { pub const fn new(db_name: N, storage: S, command_runner: &'a C) -> Self { Self { db_name, @@ -20,9 +20,7 @@ impl<'a, N, C, S> Dump<'a, N, C, S> { command_runner, } } -} -impl<'a, N, C: CommandRunner, S> Dump<'a, N, C, S> { async fn run_sql(&self, sql: &str) -> Result> { let b = self .command_runner diff --git a/src/symbols/mariadb/user.rs b/src/symbols/mariadb/user.rs index 8a09d45..9fb3730 100644 --- a/src/symbols/mariadb/user.rs +++ b/src/symbols/mariadb/user.rs @@ -9,16 +9,14 @@ pub struct User<'a, U, C> { command_runner: &'a C, } -impl<'a, U: AsRef, C> User<'a, U, C> { +impl<'a, U: AsRef, C: CommandRunner> User<'a, U, C> { pub const fn new(user_name: U, command_runner: &'a C) -> Self { Self { user_name, command_runner, } } -} -impl<'a, U: AsRef, C: CommandRunner> User<'a, U, C> { async fn run_sql(&self, sql: &str) -> Result> { let b = self .command_runner diff --git a/src/symbols/npm.rs b/src/symbols/npm.rs index 59ca7dc..5275d64 100644 --- a/src/symbols/npm.rs +++ b/src/symbols/npm.rs @@ -6,12 +6,12 @@ use std::fmt; use std::path::Path; #[derive(Debug)] -pub struct Install<'a, T: AsRef, C> { +pub struct Install<'a, T: AsRef, C: CommandRunner> { target: T, command_runner: &'a C, } -impl<'a, T: AsRef, C> Install<'a, T, C> { +impl<'a, T: AsRef, C: CommandRunner> Install<'a, T, C> { pub const fn new(target: T, command_runner: &'a C) -> Self { Self { target, @@ -51,7 +51,7 @@ impl, C: CommandRunner> Symbol for Install<'_, T, C> { .await?; Ok( result.status.success() - && !std::str::from_utf8(&result.stdout) + && !String::from_utf8(result.stdout) .unwrap() .contains("(empty)"), ) diff --git a/src/symbols/postgresql/database.rs b/src/symbols/postgresql/database.rs index f815e55..3b825fd 100644 --- a/src/symbols/postgresql/database.rs +++ b/src/symbols/postgresql/database.rs @@ -5,23 +5,21 @@ use std::error::Error; use std::fmt; #[derive(Debug)] -pub struct PostgreSQLDatabase<'a, N, S, C> { +pub struct PostgreSQLDatabase<'a, N: AsRef, S: AsRef, C: CommandRunner> { name: N, seed_file: S, command_runner: &'a C, } -impl<'a, N, S, C> PostgreSQLDatabase<'a, N, S, C> { +impl<'a, N: AsRef, S: AsRef, C: CommandRunner> PostgreSQLDatabase<'a, N, S, C> { pub const fn new(name: N, seed_file: S, command_runner: &'a C) -> Self { - Self { + PostgreSQLDatabase { name, seed_file, command_runner, } } -} -impl<'a, N: AsRef, S: AsRef, C: CommandRunner> PostgreSQLDatabase<'a, N, S, C> { async fn run_sql(&self, sql: &str) -> Result> { let b = self .command_runner diff --git a/src/symbols/saved_directory.rs b/src/symbols/saved_directory.rs index 50467d4..6e45c89 100644 --- a/src/symbols/saved_directory.rs +++ b/src/symbols/saved_directory.rs @@ -73,7 +73,7 @@ impl<_C: CommandRunner, C: Borrow<_C>, P: AsRef, S: Storage> Symbol ], ) .await?; - let modified_date = u64::from_str(std::str::from_utf8(&output)?.trim_end())?; + let modified_date = u64::from_str(String::from_utf8(output)?.trim_end())?; if if self.dir == StorageDirection::Store { modified_date > dump_date } else { @@ -84,17 +84,13 @@ impl<_C: CommandRunner, C: Borrow<_C>, P: AsRef, S: Storage> Symbol .borrow() .run_with_args( "diff", - args![ - "-rq", - self.storage.read_filename()?.as_os_str(), - self.path.as_ref() - ], + args!["-rq", self.storage.read_filename()?, self.path.as_ref()], ) .await?; match output.status.code() { Some(0) => Ok(true), Some(1) => Ok(false), - _ => Err(std::str::from_utf8(&output.stderr)?.into()), + _ => Err(String::from_utf8(output.stderr)?.into()), } } else { Ok(true) @@ -113,11 +109,7 @@ impl<_C: CommandRunner, C: Borrow<_C>, P: AsRef, S: Storage> Symbol .borrow() .run_successfully( "cp", - args![ - "-a", - self.storage.read_filename()?.as_os_str(), - self.path.as_ref() - ], + args!["-a", self.storage.read_filename()?, self.path.as_ref()], ) .await } else { @@ -126,11 +118,7 @@ impl<_C: CommandRunner, C: Borrow<_C>, P: AsRef, S: Storage> Symbol .borrow() .run_successfully( "cp", - args![ - "-a", - self.path.as_ref(), - self.storage.write_filename().as_os_str() - ], + args!["-a", self.path.as_ref(), self.storage.write_filename()], ) .await } diff --git a/src/symbols/systemd/user_service.rs b/src/symbols/systemd/user_service.rs index fef5692..67ed3b2 100644 --- a/src/symbols/systemd/user_service.rs +++ b/src/symbols/systemd/user_service.rs @@ -30,9 +30,9 @@ impl, U: AsRef> UserService<'_, S, U> { loop { let result = self.command_runner.run_with_args("systemctl", args).await?; if result.status.success() { - return Ok(std::str::from_utf8(&result.stdout)?.trim_end().to_string()); + return Ok(String::from_utf8(result.stdout)?.trim_end().to_string()); } - let raw_stderr = std::str::from_utf8(&result.stderr)?; + let raw_stderr = String::from_utf8(result.stderr)?; let stderr = raw_stderr.trim_end(); if stderr != "Failed to connect to bus: No such file or directory" { return Err(stderr.into()); @@ -61,8 +61,8 @@ impl, U: AsRef> UserService<'_, S, U> { "ActiveState=active" => return Ok(true), "ActiveState=failed" => { return Err( - std::str::from_utf8( - &self + String::from_utf8( + self .command_runner .get_output( "journalctl", diff --git a/src/symbols/tls/key.rs b/src/symbols/tls/key.rs index acbb8cc..be2ea9f 100644 --- a/src/symbols/tls/key.rs +++ b/src/symbols/tls/key.rs @@ -1,16 +1,14 @@ use crate::command_runner::CommandRunner; use crate::symbols::Symbol; use async_trait::async_trait; -use nonzero_ext::nonzero; use std::error::Error; -use std::num::NonZeroU32; use std::path::Path; #[derive(Debug)] pub struct Key { file_path: P, command_runner: C, - bits: NonZeroU32, + bits: u32, } impl Key { @@ -18,7 +16,7 @@ impl Key { Self { file_path, command_runner, - bits: nonzero!(4096u32), // FIXME: Policy + bits: 4096, } } } diff --git a/src/symbols/wordpress/plugin.rs b/src/symbols/wordpress/plugin.rs index 514234a..6ac40e2 100644 --- a/src/symbols/wordpress/plugin.rs +++ b/src/symbols/wordpress/plugin.rs @@ -6,7 +6,7 @@ use std::error::Error; use std::fs::File as FsFile; use std::io; use std::io::{BufRead, BufReader}; -use std::path::Path; +use std::path::{Path, PathBuf}; #[derive(Debug)] pub struct Plugin<'a, P, N, R> { @@ -15,7 +15,7 @@ pub struct Plugin<'a, P, N, R> { command_runner: &'a R, } -impl<'a, P: AsRef, N: AsRef, R> Plugin<'a, P, N, R> { +impl<'a, P: AsRef, N: AsRef, R: CommandRunner> Plugin<'a, P, N, R> { pub const fn new(base: P, name: N, command_runner: &'a R) -> Self { Self { base, @@ -24,13 +24,12 @@ impl<'a, P: AsRef, N: AsRef, R> Plugin<'a, P, N, R> { } } - fn get_path(&self) -> Box { + fn get_path(&self) -> PathBuf { self .base .as_ref() .join("wp-content/plugins") .join(self.name.as_ref()) - .into() } } @@ -42,8 +41,8 @@ impl, N: AsRef, R: CommandRunner> Symbol for Plugin<'_, P, N return Ok(false); } let path = base_path.join(self.name.as_ref().to_owned() + ".php"); - let mut version: Option> = None; - let mut plugin_uri: Option> = None; + let mut version = String::new(); + let mut plugin_uri = String::new(); match FsFile::open(path) { Err(e) => { // Check if file exists @@ -57,12 +56,11 @@ impl, N: AsRef, R: CommandRunner> Symbol for Plugin<'_, P, N let reader = BufReader::new(file); let regex = Regex::new("(?m)^(Plugin URI|Version): (.+)$")?; for content in reader.lines() { - let content = content?; - for matches in regex.captures_iter(&content) { + for matches in regex.captures_iter(&(content?)) { if &matches[1] == "Plugin URI" { - plugin_uri = Some(matches[2].into()); + plugin_uri = matches[2].to_string(); } else { - version = Some(matches[2].into()); + version = matches[2].to_string(); } } } @@ -77,14 +75,14 @@ impl, N: AsRef, R: CommandRunner> Symbol for Plugin<'_, P, N format!( r###"plugins={{"plugins":{{"{0}/{0}.php":{{"Version":"{1}", "PluginURI":"{2}"}}}}}}"###, self.name.as_ref(), - version.as_deref().unwrap_or_default(), - plugin_uri.as_deref().unwrap_or_default() + version, + plugin_uri ), "https://api.wordpress.org/plugins/update-check/1.1/", ], ) .await?; - Ok(std::str::from_utf8(&upstream)?.contains(r###""plugins":[]"###)) + Ok(String::from_utf8(upstream)?.contains(r###""plugins":[]"###)) } async fn execute(&self) -> Result<(), Box> { @@ -99,7 +97,7 @@ impl, N: AsRef, R: CommandRunner> Symbol for Plugin<'_, P, N .await?; self .command_runner - .run_successfully("rm", args!["-rf", self.get_path().as_os_str()]) + .run_successfully("rm", args!["-rf", self.get_path()]) .await?; self .command_runner diff --git a/src/symbols/wordpress/translation.rs b/src/symbols/wordpress/translation.rs index 3531f90..ac16ec3 100644 --- a/src/symbols/wordpress/translation.rs +++ b/src/symbols/wordpress/translation.rs @@ -8,6 +8,7 @@ use std::fs::File as FsFile; use std::io; use std::io::{BufRead, BufReader}; use std::path::Path; +use std::path::PathBuf; #[derive(Debug)] pub struct Translation<'a, C, D, R> { @@ -17,7 +18,7 @@ pub struct Translation<'a, C, D, R> { command_runner: &'a R, } -impl<'a, D, C: AsRef, R> Translation<'a, C, D, R> { +impl<'a, D, C: AsRef, R: CommandRunner> Translation<'a, C, D, R> { pub const fn new(path: D, version: &'a str, locale: C, command_runner: &'a R) -> Self { Self { path, @@ -29,7 +30,7 @@ impl<'a, D, C: AsRef, R> Translation<'a, C, D, R> { } impl, D: AsRef, R: CommandRunner> Translation<'_, C, D, R> { - fn get_pairs(&self) -> impl Iterator, Box)> + '_ { + fn get_pairs(&self) -> Vec<(String, PathBuf)> { let version_x = self .version .trim_end_matches(|c: char| c.is_ascii_digit()) @@ -41,19 +42,21 @@ impl, D: AsRef, R: CommandRunner> Translation<'_, C, D, R> { } else { locale.to_lowercase().replace('_', "-") }; - [ + let mut res = vec![]; + for &(in_slug, out_slug) in &[ ("", ""), ("cc/", "continents-cities-"), ("admin/", "admin-"), ("admin/network/", "admin-network-"), - ].into_iter().flat_map(move |(in_slug, out_slug)|{ - ["po", "mo"].map(|format| - ( - format!("https://translate.wordpress.org/projects/wp/{version_x}/{in_slug}{path_locale}/default/export-translations?format={format}").into(), - self.path.as_ref().join(format!("{}{}.{}", out_slug, self.locale.as_ref(), format)).into() - )) + ] { + for format in &["po", "mo"] { + res.push(( + format!("https://translate.wordpress.org/projects/wp/{version_x}/{in_slug}{path_locale}/default/export-translations?format={format}"), + [self.path.as_ref(), format!("{}{}.{}", out_slug, self.locale.as_ref(), format).as_ref()].iter().collect() + )); } - ) + } + res } } @@ -77,7 +80,7 @@ impl, D: AsRef, R: CommandRunner> Symbol for Translation<'_, let reader = BufReader::new(file); for content in reader.lines() { if let Some(match_result) = match_date.captures(&content?) { - newest = max(newest, match_result[1].into()); + newest = max(newest, match_result[1].to_string()); break; } } @@ -96,7 +99,7 @@ impl, D: AsRef, R: CommandRunner> Symbol for Translation<'_, )], ) .await?; - Ok(std::str::from_utf8(&upstream)?.contains(&format!( + Ok(String::from_utf8(upstream)?.contains(&format!( r###"language":"{}","version":"{}","updated":"{}"###, self.locale.as_ref(), self.version, @@ -108,10 +111,7 @@ impl, D: AsRef, R: CommandRunner> Symbol for Translation<'_, for (source, target) in self.get_pairs() { self .command_runner - .run_successfully( - "curl", - args!["--compressed", "-o", target.as_os_str(), source.as_ref(),], - ) + .run_successfully("curl", args!["--compressed", "-o", target, source,]) .await?; } Ok(()) diff --git a/src/templates/nginx/server.rs b/src/templates/nginx/server.rs index 4e35b2d..dd28bc4 100644 --- a/src/templates/nginx/server.rs +++ b/src/templates/nginx/server.rs @@ -1,5 +1,4 @@ use std::fmt::Display; -use std::num::NonZeroUsize; use std::path::Path; #[must_use] @@ -102,11 +101,11 @@ impl> SocketSpec for T { } #[derive(Debug)] -pub struct LocalTcpSocket(NonZeroUsize); +pub struct LocalTcpSocket(usize); impl LocalTcpSocket { #[must_use] - pub const fn new(x: NonZeroUsize) -> Self { + pub const fn new(x: usize) -> Self { Self(x) } } diff --git a/src/templates/php.rs b/src/templates/php.rs index 3fa0ac9..6e47e28 100644 --- a/src/templates/php.rs +++ b/src/templates/php.rs @@ -1,11 +1,10 @@ use std::fmt::{Display, Error, Formatter}; -use std::num::NonZeroUsize; use std::path::Path; #[derive(Clone, Debug, PartialEq, Hash, Eq)] pub struct FpmPoolConfig { - max_children: NonZeroUsize, - custom: Option>, + max_children: usize, + custom: Option, } impl Display for FpmPoolConfig { @@ -20,14 +19,14 @@ impl Display for FpmPoolConfig { impl From for FpmPoolConfig { fn from(max_children: usize) -> Self { Self { - max_children: NonZeroUsize::try_from(max_children).unwrap(), + max_children, custom: None, } } } impl FpmPoolConfig { - pub fn new(max_children: NonZeroUsize, custom: impl Into>) -> Self { + pub fn new(max_children: usize, custom: impl Into) -> Self { Self { max_children, custom: Some(custom.into()), diff --git a/tests/file.rs b/tests/file.rs index 62fa620..3043cdc 100644 --- a/tests/file.rs +++ b/tests/file.rs @@ -3,7 +3,7 @@ use schematics::symbols::file::File as FileSymbol; use schematics::symbols::Symbol; use std::fs::File; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; use tempfile::{tempdir, TempDir}; fn get_dir(content: Option<&str>) -> TempDir { @@ -19,8 +19,8 @@ fn get_dir(content: Option<&str>) -> TempDir { tmp_dir } -fn get_symbol(path: &Path) -> FileSymbol, &str> { - FileSymbol::new(path.join("filename").into(), "target content") +fn get_symbol(path: &Path) -> FileSymbol { + FileSymbol::new(path.join("filename"), "target content") } // Normal cases diff --git a/tests/setup.rs b/tests/setup.rs index 1603f86..e30520f 100644 --- a/tests/setup.rs +++ b/tests/setup.rs @@ -9,7 +9,6 @@ use schematics::SymbolRunner; use slog::{info, Logger as SlogLogger}; use std::error::Error; use std::fmt::Debug; -use std::path::Path; use std::time::Duration; #[derive(Clone, Debug)] @@ -61,7 +60,7 @@ fn test( #[test] fn can_create_an_acme_user() { let mut result = test(1, |setup| { - assert_eq!(&*(run(setup.add(AcmeUser)).unwrap().0).0, "acme"); + assert_eq!((run(setup.add(AcmeUser)).unwrap().0).0, "acme"); }); let entry = result .pop() @@ -134,8 +133,8 @@ fn can_create_an_acme_cert() { #[test] fn can_create_a_git_checkout() { let mut result = test(1, |setup| { - run(setup.add(GitCheckout::new( - "/tmp/somepath".as_ref() as &Path, + run(setup.add(GitCheckout( + "/tmp/somepath".into(), "/tmp/some_src_repo", "master", ))) diff --git a/tests/storage.rs b/tests/storage.rs index 10bc176..04f2bf5 100644 --- a/tests/storage.rs +++ b/tests/storage.rs @@ -16,7 +16,7 @@ fn get_dir<'a, I: IntoIterator>(content: I) -> TempDir { } fn get_storage(path: &Path) -> SimpleStorage { - SimpleStorage::new(path.join("_filename").into()) + SimpleStorage::new(path.join("_filename")) } // Normal cases @@ -33,7 +33,7 @@ fn single_file() { ); assert_eq!( dir.path().join("_filename").join("12345"), - Path::new(&*storage.read_filename().unwrap()) + Path::new(&storage.read_filename().unwrap()) ); assert_eq!(storage.recent_date().unwrap(), 12345); } @@ -50,7 +50,7 @@ fn two_files() { ); assert_eq!( dir.path().join("_filename").join("23456"), - Path::new(&*storage.read_filename().unwrap()) + Path::new(&storage.read_filename().unwrap()) ); assert_eq!(storage.recent_date().unwrap(), 23456); } @@ -67,7 +67,7 @@ fn another_two_files() { ); assert_eq!( dir.path().join("_filename").join("23456"), - Path::new(&*storage.read_filename().unwrap()) + Path::new(&storage.read_filename().unwrap()) ); assert_eq!(storage.recent_date().unwrap(), 23456); } @@ -84,7 +84,7 @@ fn three_files() { ); assert_eq!( dir.path().join("_filename").join("23456"), - Path::new(&*storage.read_filename().unwrap()) + Path::new(&storage.read_filename().unwrap()) ); assert_eq!(storage.recent_date().unwrap(), 23456); }