From 353fdc5b539aae0479c7404d0ed6404f82bf633a Mon Sep 17 00:00:00 2001 From: 魏曹先生 <1992414357@qq.com> Date: Sat, 27 Jun 2026 18:52:49 +0800 Subject: feat(mingling): add directory environment resources and setup Add four new resource types for common directory paths and a convenience setup struct that registers all of them at once. --- mingling/src/res/dirs/current_dir.rs | 82 ++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 mingling/src/res/dirs/current_dir.rs (limited to 'mingling/src/res/dirs/current_dir.rs') diff --git a/mingling/src/res/dirs/current_dir.rs b/mingling/src/res/dirs/current_dir.rs new file mode 100644 index 0000000..1de84e0 --- /dev/null +++ b/mingling/src/res/dirs/current_dir.rs @@ -0,0 +1,82 @@ +use std::{ + env::current_dir, + path::{Path, PathBuf}, +}; + +/// A global resource for the Mingling library that provides the current working directory. +/// +/// This struct wraps a `PathBuf` representing the current working directory at the time of +/// creation. It is used as a shared resource in the Mingling framework so that multiple +/// components can access the same base directory without repeatedly querying the OS. +/// +/// # Default behavior +/// +/// The `Default` implementation calls `std::env::current_dir().unwrap()` internally, which will +/// **panic** if the current directory cannot be determined (e.g., if it has been deleted). If +/// you want to handle this error gracefully, use [`ResCurrentDir::new`] instead, which returns +/// a `Result`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResCurrentDir { + cwd: PathBuf +} + +impl ResCurrentDir { + /// Creates a new `ResCurrentDir` by querying the OS for the current working directory. + /// + /// Returns `Err` if the current directory cannot be determined (e.g., the directory has been + /// deleted or permissions are insufficient). Unlike the `Default` implementation, this + /// method does not panic on failure. + pub fn new() -> Result { + Ok(Self { cwd: current_dir()? }) + } +} + +impl Default for ResCurrentDir { + fn default() -> Self { + Self { cwd: current_dir().unwrap() } + } +} + +impl From for ResCurrentDir { + fn from(path: PathBuf) -> Self { + Self { cwd: path } + } +} + +impl From<&Path> for ResCurrentDir { + fn from(path: &Path) -> Self { + Self { cwd: path.to_path_buf() } + } +} + +impl From<&PathBuf> for ResCurrentDir { + fn from(path: &PathBuf) -> Self { + Self { cwd: path.clone() } + } +} + +impl From for PathBuf { + fn from(res: ResCurrentDir) -> Self { + res.cwd + } +} + +impl AsRef for ResCurrentDir { + fn as_ref(&self) -> &Path { + self.cwd.as_path() + } +} + +impl std::ops::Deref for ResCurrentDir { + type Target = PathBuf; + + fn deref(&self) -> &Self::Target { + &self.cwd + } +} + +impl std::ops::DerefMut for ResCurrentDir { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.cwd + } +} -- cgit