feat(configuration): Add global configuration

also update some error messages
This commit is contained in:
Alexander Navarro 2024-04-29 19:22:45 -04:00
parent 8cd4b4b10f
commit f0485abfbb
6 changed files with 67 additions and 22 deletions

View file

@ -6,6 +6,7 @@ edition = "2021"
[dependencies] [dependencies]
clap = { version = "4.5.4", features = ["derive"] } clap = { version = "4.5.4", features = ["derive"] }
ignore = "0.4.22" ignore = "0.4.22"
lazy_static = "1.4.0"
prost = "0.12.4" prost = "0.12.4"
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
tonic = "0.11.0" tonic = "0.11.0"

46
src/configuration.rs Normal file
View file

@ -0,0 +1,46 @@
use clap::Parser;
use lazy_static::lazy_static;
use std::env;
use std::path::PathBuf;
lazy_static! {
pub static ref CONFIG: Config = Config::new();
}
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Args {
#[arg(help = "Directory to scan for files")]
path: Option<PathBuf>,
}
#[derive(Debug)]
pub struct Config {
pub base_path: PathBuf,
}
impl Default for Config {
fn default() -> Self {
Config {
base_path: env::current_dir().expect("Current directory is not available."),
}
}
}
impl Config {
pub fn new() -> Self {
let mut config = Self::default();
let cli = Self::get_cli_args();
if let Some(path) = cli.path {
config.base_path = path;
}
config
}
fn get_cli_args() -> Args {
Args::parse()
}
}

View file

@ -1,8 +1,10 @@
use ignore::types::TypesBuilder; use ignore::types::TypesBuilder;
use ignore::WalkBuilder; use ignore::WalkBuilder;
use std::{io, path::PathBuf}; use std::path::PathBuf;
pub fn walk_dir(path: &PathBuf) -> io::Result<Vec<PathBuf>> { use crate::configuration::CONFIG;
pub fn walk_dir(path: &PathBuf) -> Result<Vec<PathBuf>, &str> {
let mut types_builder = TypesBuilder::new(); let mut types_builder = TypesBuilder::new();
types_builder.add_defaults(); types_builder.add_defaults();
@ -14,7 +16,19 @@ pub fn walk_dir(path: &PathBuf) -> io::Result<Vec<PathBuf>> {
types_builder.select("sound"); types_builder.select("sound");
let entries: Vec<PathBuf> = WalkBuilder::new(path) let search_path = CONFIG.base_path.join(path);
eprintln!(
"DEBUGPRINT[1]: file_explorer.rs:19: search_path={:#?}",
search_path
);
// PathBuf.join() can override the hole path, this ensure we're not accessing files outside
// base_dir
if !search_path.starts_with(&CONFIG.base_path) {
return Err("Tried to access file or directory outside of server `base_dir` config.");
}
let entries: Vec<PathBuf> = WalkBuilder::new(search_path)
.types(types_builder.build().unwrap()) .types(types_builder.build().unwrap())
.build() .build()
.filter_map(|entry| entry.ok()) .filter_map(|entry| entry.ok())

View file

@ -22,7 +22,7 @@ impl super::Connection for GRPCClient {
let mut client = JunoRequestClient::connect(format!("http://{}", self.address)).await?; let mut client = JunoRequestClient::connect(format!("http://{}", self.address)).await?;
let request = Request::new(GetFilesRequest { let request = Request::new(GetFilesRequest {
path: "/home/aleidk/Music/".to_string(), path: "/home/aleidk/Documents/".to_string(),
}); });
let response = client.get_files(request).await?.into_inner(); let response = client.get_files(request).await?.into_inner();

View file

@ -43,9 +43,8 @@ impl JunoRequest for GRPCServer {
let files = match file_explorer::walk_dir(&path) { let files = match file_explorer::walk_dir(&path) {
Ok(files) => files, Ok(files) => files,
Err(_err) => panic!("Error reading path: {:?}", path), Err(err) => return Err(Status::invalid_argument(err)),
}; };
eprintln!("DEBUGPRINT[2]: server.rs:44: files={:#?}", files);
let reply = GetFilesResponse { let reply = GetFilesResponse {
files: files.iter().map(|x| x.display().to_string()).collect(), files: files.iter().map(|x| x.display().to_string()).collect(),

View file

@ -1,26 +1,11 @@
use core::panic;
use std::{env, path::PathBuf};
use clap::Parser;
use std::error::Error; use std::error::Error;
mod configuration;
mod file_explorer; mod file_explorer;
mod grpc; mod grpc;
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Args {
#[arg(help = "Directory to scan for files")]
path: Option<PathBuf>,
}
#[tokio::main()] #[tokio::main()]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
let cli = Args::parse();
let path = cli
.path
.unwrap_or(env::current_dir().expect("Current directory is not available."));
let server = grpc::run()?; let server = grpc::run()?;
server.connect().await?; server.connect().await?;