Skip to content

Commit

Permalink
refactor: move from PathBuf, to Path
Browse files Browse the repository at this point in the history
  • Loading branch information
da2ce7 committed Nov 23, 2022
1 parent 40c7ffd commit 879cee7
Show file tree
Hide file tree
Showing 9 changed files with 64 additions and 72 deletions.
6 changes: 3 additions & 3 deletions src/databases/sqlite.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::Path;
use std::str::FromStr;

use async_trait::async_trait;
Expand All @@ -17,7 +17,7 @@ use crate::tracker::key::AuthKey;

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Sqlite3DatabaseSettings {
pub database_file_path: PathBuf,
pub database_file_path: Box<Path>,
}

impl TryFrom<&DatabaseSettings> for Sqlite3DatabaseSettings {
Expand All @@ -44,7 +44,7 @@ pub struct SqliteDatabase {

impl SqliteDatabase {
pub fn new(settings: &Sqlite3DatabaseSettings) -> Result<SqliteDatabase, r2d2::Error> {
let cm = SqliteConnectionManager::file(settings.database_file_path.as_path());
let cm = SqliteConnectionManager::file(&settings.database_file_path);
let pool = Pool::new(cm).expect("Failed to create r2d2 SQLite connection pool.");
Ok(SqliteDatabase { pool })
}
Expand Down
12 changes: 9 additions & 3 deletions src/errors/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::Path;
use std::sync::Arc;

use thiserror::Error;
Expand Down Expand Up @@ -49,8 +49,14 @@ impl Reject for ServerError {}
#[derive(Error, Clone, Debug, Eq, Hash, PartialEq)]
pub enum FilePathError {
#[error("File Path failed to Canonicalize: {input} : {source}.")]
FilePathIsUnresolvable { input: PathBuf, source: Arc<wrappers::IoError> },
FilePathIsUnresolvable {
input: Box<Path>,
source: Arc<wrappers::IoError>,
},

#[error("File Path destination is not a file: {input} : {source}.")]
FilePathIsNotAvailable { input: PathBuf, source: Arc<wrappers::IoError> },
FilePathIsNotAvailable {
input: Box<Path>,
source: Arc<wrappers::IoError>,
},
}
18 changes: 9 additions & 9 deletions src/errors/settings_manager.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::Path;
use std::sync::Arc;

use thiserror::Error;
Expand All @@ -16,24 +16,24 @@ pub enum SettingsManagerError {
FailedToCreateNewFile { source: FilePathError },

#[error("Unable to resolve path at: \"{at}\"!")]
FailedToResolvePath { at: PathBuf, source: Arc<wrappers::IoError> },
FailedToResolvePath { at: Box<Path>, source: Arc<wrappers::IoError> },

#[error("Unable to prepare directory at: \"{at}\" : {source}!")]
FailedToPrepareDirectory { at: PathBuf, source: Arc<wrappers::IoError> },
FailedToPrepareDirectory { at: Box<Path>, source: Arc<wrappers::IoError> },

#[error("Unable to resolve a directory at: \"{at}\"!")]
FailedToResolveDirectory { at: PathBuf },
FailedToResolveDirectory { at: Box<Path> },

#[error("Unable to read file, {message}: \"{from}\" : {source}.")]
FailedToReadFromFile {
message: String,
from: PathBuf,
from: Box<Path>,
source: Box<Self>,
},
#[error("Unable to write file, {message}: \"{to}\": {source}.")]
FailedToWriteToFile {
message: String,
to: PathBuf,
to: Box<Path>,
source: Box<Self>,
},

Expand Down Expand Up @@ -64,14 +64,14 @@ pub enum SettingsManagerError {

#[error("Unable to import old settings from: \"{from}\" : \"{source}\"")]
FailedToImportOldSettings {
from: PathBuf,
from: Box<Path>,
source: Box<settings::SettingsError>,
},

#[error("Unable to successfully move file from: {from} to: {to} \"{source}\"")]
FailedToMoveFile {
from: PathBuf,
to: PathBuf,
from: Box<Path>,
to: Box<Path>,
source: Arc<IoError>,
},
}
10 changes: 5 additions & 5 deletions src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
use std::path::Path;

use crate::errors::wrappers::IoError;
use crate::errors::FilePathError;

pub fn get_file_at(at: &Path, mode: &OpenOptions) -> Result<(File, PathBuf), FilePathError> {
pub fn get_file_at(at: &Path, mode: &OpenOptions) -> Result<(File, Box<Path>), FilePathError> {
let file = mode.open(at).map_err(|error| FilePathError::FilePathIsNotAvailable {
input: at.to_owned(),
input: at.into(),
source: IoError::from(error).into(),
})?;

let at = Path::new(at)
.canonicalize()
.map_err(|error| FilePathError::FilePathIsUnresolvable {
input: at.to_owned(),
input: at.into(),
source: IoError::from(error).into(),
})?;

Ok((file, at))
Ok((file, at.into_boxed_path()))
}
14 changes: 7 additions & 7 deletions src/http/server.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::net::SocketAddr;
use std::path::PathBuf;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;

Expand Down Expand Up @@ -62,8 +62,8 @@ pub struct TlsServiceSettings {
pub enabled: bool,
pub display_name: String,
pub socket: SocketAddr,
pub certificate_file_path: PathBuf,
pub key_file_path: PathBuf,
pub certificate_file_path: Box<Path>,
pub key_file_path: Box<Path>,
}

impl Default for TlsServiceSettings {
Expand All @@ -73,8 +73,8 @@ impl Default for TlsServiceSettings {
enabled: false,
display_name: "HTTP (default)".to_string(),
socket: SocketAddr::from_str("0.0.0.0:6969").unwrap(),
certificate_file_path: Default::default(),
key_file_path: Default::default(),
certificate_file_path: Path::new("").into(),
key_file_path: Path::new("").into(),
}
}
}
Expand Down Expand Up @@ -149,8 +149,8 @@ impl HttpServer {
pub fn start_tls(
&self,
socket_addr: SocketAddr,
ssl_cert_path: PathBuf,
ssl_key_path: PathBuf,
ssl_cert_path: &Path,
ssl_key_path: &Path,
) -> impl warp::Future<Output = ()> {
let (_addr, server) = warp::serve(routes(self.tracker.clone()))
.tls()
Expand Down
2 changes: 1 addition & 1 deletion src/jobs/tls_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub fn start_tls_job(settings: &TlsServiceSettings, tracker: Arc<TorrentTracker>
settings.display_name, settings.socket
);
http_tracker
.start_tls(settings.socket, settings.certificate_file_path, settings.key_file_path)
.start_tls(settings.socket, &settings.certificate_file_path, &settings.key_file_path)
.await;
})
}
28 changes: 14 additions & 14 deletions src/settings/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::ffi::OsString;
use std::fs::{self, OpenOptions};
use std::hash::{Hash, Hasher};
use std::io::{Cursor, Read, Write};
use std::path::{Path, PathBuf};
use std::path::Path;

use log::{info, warn};

Expand Down Expand Up @@ -78,7 +78,7 @@ impl SettingsManager {
Self::write_default(default.as_path())?;
let manager = Self::load(old.as_path(), local.as_path(), backup, error)?;

manager.save(local.as_path(), &Some(backup.to_path_buf()))?;
manager.save(local.as_path(), &Some(backup.into()))?;

Ok(manager)
}
Expand Down Expand Up @@ -110,7 +110,7 @@ impl SettingsManager {
Ok(Default::default())
}

pub fn save(&self, to: &Path, archive_folder: &Option<PathBuf>) -> Result<(), SettingsManagerError> {
pub fn save(&self, to: &Path, archive_folder: &Option<Box<Path>>) -> Result<(), SettingsManagerError> {
// lets backup the previous configuration, if we have any...
let existing = get_file_at(to, OpenOptions::new().read(true)).ok();

Expand Down Expand Up @@ -204,7 +204,7 @@ impl SettingsManager {
}
}

fn backup(&self, to: &Path, folder: PathBuf) -> Result<(), SettingsManagerError> {
fn backup(&self, to: &Path, folder: &Path) -> Result<(), SettingsManagerError> {
let ext = match to.extension().map(|f| f.to_os_string()) {
Some(mut ext) => {
ext.push(".json");
Expand All @@ -218,12 +218,12 @@ impl SettingsManager {
self.write_json(data.by_ref())
.map_err(|err| SettingsManagerError::FailedToWriteToFile {
message: "(backup)".to_string(),
to: to.to_path_buf(),
to: to.into(),

source: err.into(),
})?;

Self::archive(Cursor::new(data), &to.with_extension(ext), &folder)?;
Self::archive(Cursor::new(data), &to.with_extension(ext), folder)?;
Ok(())
}

Expand All @@ -233,7 +233,7 @@ impl SettingsManager {
let to_folder = to_folder
.canonicalize()
.map_err(|err| SettingsManagerError::FailedToResolvePath {
at: to_folder.to_owned(),
at: to_folder.into(),
source: IoError::from(err).into(),
})?;

Expand All @@ -248,7 +248,7 @@ impl SettingsManager {
})
.map_err(|err| SettingsManagerError::FailedToReadFromFile {
message: "(archive, read into)".to_string(),
from: from.to_owned(),
from: from.into(),
source: err.into(),
})?;

Expand Down Expand Up @@ -348,7 +348,7 @@ impl SettingsManager {
None => OsString::from(test.to_lowercase()),
};

broken.backup(&file.1.with_extension(ext), import_error_folder.to_owned())?;
broken.backup(&file.1.with_extension(ext), import_error_folder.as_path())?;
}

// Replace broken with default, and remove everything else.
Expand Down Expand Up @@ -381,7 +381,7 @@ impl SettingsManager {
None => OsString::from(test.to_lowercase()),
};

broken.backup(&file.1.with_extension(ext), import_error_folder.to_owned())?;
broken.backup(&file.1.with_extension(ext), import_error_folder.as_path())?;
}

builder = test_builder.tracker_settings.clean().into();
Expand Down Expand Up @@ -415,7 +415,7 @@ impl SettingsManager {
None => OsString::from(test.to_lowercase()),
};

broken.backup(&file.1.with_extension(ext), import_error_folder)?;
broken.backup(&file.1.with_extension(ext), import_error_folder.as_path())?;

return Err(SettingsManagerError::FailedToImportOldSettings {
from: file.1,
Expand Down Expand Up @@ -448,7 +448,7 @@ impl SettingsManager {
}
Err(err) => Err(SettingsManagerError::FailedToMoveFile {
from: file.1,
to: backup,
to: backup.into_boxed_path(),
source: IoError::from(err).into(),
}),
}
Expand All @@ -459,13 +459,13 @@ impl SettingsManager {
if path.is_dir() {
return Ok(());
} else {
return Err(SettingsManagerError::FailedToResolveDirectory { at: folder.to_owned() });
return Err(SettingsManagerError::FailedToResolveDirectory { at: folder.into() });
}
}
match fs::create_dir(folder) {
Ok(_) => Ok(()),
Err(err) => Err(SettingsManagerError::FailedToPrepareDirectory {
at: folder.to_owned(),
at: folder.into(),
source: IoError::from(err).into(),
}),
}
Expand Down
30 changes: 13 additions & 17 deletions src/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::hash_map::RandomState;
use std::collections::{BTreeMap, HashSet};
use std::fs::OpenOptions;
use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;

Expand Down Expand Up @@ -407,9 +407,7 @@ impl TrackerSettingsBuilder {
if let Some(val) = old_settings.db_path.as_ref() {
match driver {
DatabaseDriversOld::Sqlite3 => {
if let Ok(path) = PathBuf::from_str(val) {
self.tracker_settings.database.as_mut().unwrap().sql_lite_3_db_file_path = Some(path);
}
self.tracker_settings.database.as_mut().unwrap().sql_lite_3_db_file_path = Some(Path::new(val).into());
}
DatabaseDriversOld::MySQL => {
self.tracker_settings.database.as_mut().unwrap().my_sql_connection_url = Some(val.to_owned())
Expand Down Expand Up @@ -700,15 +698,15 @@ impl CommonSettingsBuilder {
#[derive(Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Debug, Clone, Hash)]
pub struct DatabaseSettings {
driver: Option<DatabaseDrivers>,
sql_lite_3_db_file_path: Option<PathBuf>,
sql_lite_3_db_file_path: Option<Box<Path>>,
my_sql_connection_url: Option<String>,
}

impl Default for DatabaseSettings {
fn default() -> Self {
Self {
driver: Some(Default::default()),
sql_lite_3_db_file_path: Some(PathBuf::from_str("data.db").unwrap()),
sql_lite_3_db_file_path: Some(Path::new("data.db").into()),
my_sql_connection_url: None,
}
}
Expand Down Expand Up @@ -744,11 +742,11 @@ impl DatabaseSettings {
Ok(self.driver.unwrap())
}

pub fn get_slq_lite_3_file_path(&self) -> Result<PathBuf, DatabaseSettingsError> {
check_field_is_not_empty!(self.to_owned() => DatabaseSettingsError; sql_lite_3_db_file_path: PathBuf);
pub fn get_slq_lite_3_file_path(&self) -> Result<Box<Path>, DatabaseSettingsError> {
check_field_is_not_none!(self.to_owned() => DatabaseSettingsError; sql_lite_3_db_file_path);

// todo: more checks here.
Ok(Path::new(self.sql_lite_3_db_file_path.as_ref().unwrap()).to_path_buf())
Ok(self.sql_lite_3_db_file_path.as_deref().unwrap().into())
}

pub fn get_my_sql_connection_url(&self) -> Result<String, DatabaseSettingsError> {
Expand Down Expand Up @@ -1077,8 +1075,8 @@ impl ServicesBuilder {

#[derive(Serialize, Deserialize, PartialEq, PartialOrd, Ord, Eq, Debug, Clone, Hash)]
pub struct TlsSettings {
pub certificate_file_path: Option<PathBuf>,
pub key_file_path: Option<PathBuf>,
pub certificate_file_path: Option<Box<Path>>,
pub key_file_path: Option<Box<Path>>,
}

impl Empty for TlsSettings {
Expand All @@ -1098,9 +1096,8 @@ impl TlsSettings {
Ok(())
}

pub fn get_certificate_file_path(&self) -> Result<PathBuf, TlsSettingsError> {
check_field_is_not_empty!(self.to_owned() => TlsSettingsError;
certificate_file_path: PathBuf);
pub fn get_certificate_file_path(&self) -> Result<Box<Path>, TlsSettingsError> {
check_field_is_not_none!(self.to_owned() => TlsSettingsError; certificate_file_path);

get_file_at(self.certificate_file_path.as_ref().unwrap(), OpenOptions::new().read(true))
.map(|at| at.1)
Expand All @@ -1110,9 +1107,8 @@ impl TlsSettings {
})
}

pub fn get_key_file_path(&self) -> Result<PathBuf, TlsSettingsError> {
check_field_is_not_empty!(self.to_owned() => TlsSettingsError;
key_file_path: PathBuf);
pub fn get_key_file_path(&self) -> Result<Box<Path>, TlsSettingsError> {
check_field_is_not_none!(self.to_owned() => TlsSettingsError; key_file_path);

get_file_at(self.key_file_path.as_ref().unwrap(), OpenOptions::new().read(true))
.map(|at| at.1)
Expand Down
Loading

0 comments on commit 879cee7

Please sign in to comment.