pub struct AppPath { /* private fields */ }
Expand description
Creates paths relative to the executable location for portable applications.
AppPath enables building truly portable applications where configuration, data, and executable stay together as a deployable unit. Perfect for USB drives, network shares, or any directory without installation.
§Key Features
- Portable: Relative paths resolve to executable directory
- System integration: Absolute paths work as-is
- Zero-cost: Implements
Deref<Target=Path>
and all path traits - Thread-safe: Static caching with proper synchronization
- Memory efficient: Only stores the final resolved path
§API Overview
§Constructors
Self::new()
- Application base directory: Returns the directory containing the executableSelf::with()
- Primary API: Create paths relative to application base directorySelf::try_new()
- Libraries: Fallible version for getting application base directorySelf::try_with()
- Libraries: Fallible version for creating relative pathsSelf::with_override()
- Deployment: Environment-configurable pathsSelf::try_with_override()
- Deployment (Fallible): Fallible environment-configurable pathsSelf::with_override_fn()
- Advanced: Function-based override logicSelf::try_with_override_fn()
- Advanced (Fallible): Fallible function-based override logic
§Directory Creation
Self::create_parents()
- Files: Creates parent directories for filesSelf::create_dir()
- Directories: Creates directories (and parents)
§Path Operations & Traits
- All
Path
methods: Available directly viaDeref<Target=Path>
(e.g.,exists()
,is_file()
,file_name()
,extension()
) Self::into_path_buf()
- Conversion: Extract ownedPathBuf
from wrapperSelf::into_inner()
- Conversion: Alias forinto_path_buf()
following Rust patternsSelf::to_bytes()
- Ecosystem: Raw bytes for specialized librariesSelf::into_bytes()
- Ecosystem: Owned bytes for specialized libraries
§Panics
Constructor methods panic if the executable location cannot be determined (an extremely rare condition). After the first successful call, these methods never panic because the result is cached.
§Examples
use app_path::AppPath;
// Get the executable directory itself
let exe_dir = AppPath::new();
let exe_dir = AppPath::default(); // Same thing
// Create paths relative to executable
let config = AppPath::with("config.toml");
let data = AppPath::with("data/users.db");
// Chainable with join (since AppPath implements all Path methods)
let log_file = AppPath::new().join("logs").join("app.log");
let nested = AppPath::with("data").join("cache").join("temp.txt");
// Works like standard paths - all Path methods available
if config.exists() {
let content = std::fs::read_to_string(&config); // &config works directly
}
data.create_parents(); // Creates data/ directory for the file
// Mixed portable and system paths
let portable = AppPath::with("app.conf"); // → exe_dir/app.conf
let system = AppPath::with("/var/log/app.log"); // → /var/log/app.log
// Override for deployment flexibility
let config = AppPath::with_override(
"config.toml",
std::env::var("CONFIG_PATH").ok()
);
Implementations§
Source§impl AppPath
impl AppPath
Sourcepub fn new() -> Self
pub fn new() -> Self
Returns the application’s base directory as an AppPath.
This is the primary method for getting the application’s base directory. It provides clean, idiomatic code for the common case of needing the application’s base location.
By default, the application’s base directory is the executable’s directory, but this can
be overridden through environment variables or other configuration mechanisms using the
override methods like Self::with_override()
.
Use this when you need the application’s base directory itself, then use join()
to build paths relative to it, or use Self::with()
directly for one-step creation.
§Global Caching Behavior
The application’s base directory is determined once on first call and cached globally. All subsequent calls use the cached value for maximum performance.
§Panics
Panics only if the application’s base directory cannot be determined, which is extremely rare and typically indicates fundamental system issues (corrupted installation, permission problems). After the first successful call, this method never panics.
§Examples
§Basic Usage
use app_path::AppPath;
// Get the application's base directory (defaults to executable directory)
let app_base = AppPath::new();
// Build paths relative to it
let config = app_base.join("config.toml");
let data_dir = app_base.join("data");
// Or chain operations
let log_file = AppPath::new().join("logs").join("app.log");
§Real Application Examples
use app_path::AppPath;
use std::fs;
// Get application base directory for setup operations
let app_base = AppPath::new();
println!("Application base directory: {}", app_base.display());
// Create application directory structure
app_base.join("data").create_dir()?;
app_base.join("logs").create_dir()?;
app_base.join("config").create_dir()?;
§Portable Directory Access
use app_path::AppPath;
// Get application base directory regardless of installation location:
// - C:\Program Files\MyApp\ (Windows)
// - /usr/local/bin/ (Linux)
// - /Applications/MyApp.app/Contents/MacOS/ (macOS)
// - .\target\debug\ (development)
let exe_dir = AppPath::new();
let readme = exe_dir.join("README.txt");
let license = exe_dir.join("LICENSE");
Sourcepub fn try_new() -> Result<Self, AppPathError>
pub fn try_new() -> Result<Self, AppPathError>
Creates file paths relative to the executable location (fallible).
Use this only for libraries or specialized applications requiring explicit error handling.
Most applications should use Self::new()
instead for simpler, cleaner code.
§When to Use
Use try_new()
for:
- Reusable libraries that shouldn’t panic
- System tools with fallback strategies
- Applications running in unusual environments
Use Self::new()
for:
- Desktop, web, server, CLI applications
- When you want simple, clean code (recommended)
§Examples
use app_path::{AppPath, AppPathError};
// Library with graceful error handling
fn load_config() -> Result<String, AppPathError> {
let config_path = AppPath::try_with("config.toml")?;
// Load configuration...
Ok("config loaded".to_string())
}
// Better: Use override API for environment variables
fn load_config_with_override() -> Result<String, AppPathError> {
let config_path = AppPath::try_with_override(
"config.toml",
std::env::var("APP_CONFIG").ok()
)?;
// Load configuration...
Ok("config loaded".to_string())
}
// Multiple environment variable fallback (better approach)
fn get_config_with_fallback() -> Result<AppPath, AppPathError> {
AppPath::try_with_override_fn("config.toml", || {
std::env::var("APP_CONFIG").ok()
.or_else(|| std::env::var("CONFIG_FILE").ok())
.or_else(|| std::env::var("XDG_CONFIG_HOME").ok().map(|dir| format!("{dir}/myapp/config.toml")))
})
}
Reality check: Executable location determination failing is extremely rare:
- It requires fundamental system issues or unusual deployment scenarios
- When it happens, it usually indicates unrecoverable system problems
- Most applications can’t meaningfully continue without knowing their location
- The error handling overhead isn’t worth it for typical applications
Better approaches for most applications:
use app_path::AppPath;
use std::env;
// Use our override API for environment variables (recommended)
fn get_config_path() -> AppPath {
AppPath::with_override("config.toml", env::var("MYAPP_CONFIG_DIR").ok())
}
// Or fallible version for libraries
fn try_get_config_path() -> Result<AppPath, app_path::AppPathError> {
AppPath::try_with_override("config.toml", env::var("MYAPP_CONFIG_DIR").ok())
}
§Global Caching Behavior
Once the application’s base directory is successfully determined by either this method or AppPath::new()
,
the result is cached globally and all subsequent calls to both methods will use the cached value.
This means that after the first successful call, try_new()
will never return an error.
§Arguments
path
- A path that will be resolved according to AppPath’s resolution strategy. Accepts any type implementingAsRef<Path>
.
§Returns
Ok(AppPath)
- Successfully created AppPath with resolved pathErr(AppPathError)
- Failed to determine executable location (extremely rare)
§Examples
§Library Error Handling
use app_path::{AppPath, AppPathError};
// Library function that returns Result instead of panicking
pub fn create_config_manager() -> Result<ConfigManager, AppPathError> {
let config_path = AppPath::try_with("config.toml")?;
Ok(ConfigManager::new(config_path))
}
pub struct ConfigManager {
config_path: AppPath,
}
impl ConfigManager {
fn new(config_path: AppPath) -> Self {
Self { config_path }
}
}
§Error Propagation Pattern
use app_path::{AppPath, AppPathError};
fn initialize_app() -> Result<(), Box<dyn std::error::Error>> {
let config = AppPath::try_with("config.toml")?;
let data = AppPath::try_with("data/app.db")?;
// Initialize application with these paths
println!("Config: {}", config.display());
println!("Data: {}", data.display());
Ok(())
}
§Errors
Returns AppPathError
if the executable location cannot be determined:
AppPathError::ExecutableNotFound
-std::env::current_exe()
fails (extremely rare)AppPathError::InvalidExecutablePath
- Executable path is empty (system corruption)
These errors represent unrecoverable system failures that occur at application startup. After the first successful call, the application’s base directory is cached and this method will never return an error.
Sourcepub fn try_with(path: impl AsRef<Path>) -> Result<Self, AppPathError>
pub fn try_with(path: impl AsRef<Path>) -> Result<Self, AppPathError>
Creates file paths relative to the application’s base directory (fallible).
Use this only for libraries or specialized applications requiring explicit error handling.
Most applications should use Self::with()
instead for simpler, cleaner code.
§When to Use
Use try_with()
for:
- Reusable libraries that shouldn’t panic
- System tools with fallback strategies
- Applications running in unusual environments
Use Self::with()
for:
- Desktop, web, server, CLI applications
- When you want simple, clean code (recommended)
§Examples
use app_path::{AppPath, AppPathError};
// Library with graceful error handling
fn load_config() -> Result<String, AppPathError> {
let config_path = AppPath::try_with("config.toml")?;
// Load configuration...
Ok("config loaded".to_string())
}
// Better: Use override API for environment variables
fn load_config_with_override() -> Result<String, AppPathError> {
let config_path = AppPath::try_with_override(
"config.toml",
std::env::var("APP_CONFIG").ok()
)?;
// Load configuration...
Ok("config loaded".to_string())
}
After the first successful call, the application’s base directory is cached and this method will never return an error.
Sourcepub fn with(path: impl AsRef<Path>) -> Self
pub fn with(path: impl AsRef<Path>) -> Self
Creates file paths relative to the application’s base directory.
This is the primary method for creating paths relative to your application’s base directory. It provides clean, idiomatic code for the 99% of applications that don’t need explicit error handling.
AppPath automatically resolves relative paths based on your application’s base directory, making file access portable and predictable across different deployment scenarios.
§When to Use
Use with()
for:
- Desktop, web, server, CLI applications (recommended)
- When you want simple, clean code
- When application location issues should halt the application
Use Self::try_with()
for:
- Reusable libraries that shouldn’t panic
- System tools with fallback strategies
- Applications running in unusual environments
§Path Resolution
- Relative paths: Resolved relative to application’s base directory
- Absolute paths: Used as-is (not recommended - defeats portability)
- Path separators: Automatically normalized for current platform
§Global Caching Behavior
The application’s base directory is determined once on first call and cached globally. All subsequent calls use the cached value for maximum performance.
§Panics
Panics only if the application’s base directory cannot be determined, which is extremely rare and typically indicates fundamental system issues (corrupted installation, permission problems). After the first successful call, this method never panics.
§Arguments
path
- A path that will be resolved according to AppPath’s resolution strategy. Accepts any type implementingAsRef<Path>
(strings, Path, PathBuf, etc.).
§Examples
§Basic Usage
use app_path::AppPath;
// Configuration file next to application
let config = AppPath::with("config.toml");
// Data directory relative to application
let data_dir = AppPath::with("data");
// Nested paths work naturally
let user_profile = AppPath::with("data/users/profile.json");
let log_file = AppPath::with("logs/app.log");
§Real Application Examples
use app_path::AppPath;
use std::fs;
// Load configuration with fallback to defaults
let config_path = AppPath::with("config.toml");
let config = if config_path.exists() {
fs::read_to_string(&config_path)?
} else {
"default_config = true".to_string() // Use defaults
};
// Set up application data directory
let data_dir = AppPath::with("data");
data_dir.create_dir()?; // Creates directory if needed
// Prepare for log file creation
let log_file = AppPath::with("logs/app.log");
log_file.create_parents()?; // Ensures logs/ directory exists
§Portable File Access
use app_path::AppPath;
use std::fs;
// These paths work regardless of where the application is installed:
// - C:\Program Files\MyApp\config.toml (Windows)
// - /usr/local/bin/config.toml (Linux)
// - /Applications/MyApp.app/Contents/MacOS/config.toml (macOS)
// - .\myapp\config.toml (development)
let settings = AppPath::with("settings.json");
let cache = AppPath::with("cache");
let templates = AppPath::with("templates/default.html");
// Use with standard library functions
if settings.exists() {
let content = fs::read_to_string(&settings)?;
}
cache.create_dir()?; // Creates cache/ directory
Sourcepub fn with_override(
default: impl AsRef<Path>,
override_option: Option<impl AsRef<Path>>,
) -> Self
pub fn with_override( default: impl AsRef<Path>, override_option: Option<impl AsRef<Path>>, ) -> Self
Creates a path with override support (infallible).
This method provides a one-line solution for creating paths that can be overridden by external configuration. If an override is provided, it takes precedence over the default path. Otherwise, the default path is used with normal AppPath resolution.
This is the primary method for implementing configurable paths in applications.
It combines the simplicity of AppPath::new()
with the flexibility of external
configuration overrides.
§Common Use Cases
- Environment variable overrides: Allow users to customize file locations
- Command-line argument overrides: CLI tools with configurable paths
§How It Works
If override is provided: Use the override path directly (can be relative or absolute)
If override is None
: Use the default path with normal AppPath resolution
§Examples
use app_path::AppPath;
use std::env;
// Environment variable override
let config = AppPath::with_override(
"config.toml",
env::var("APP_CONFIG").ok()
);
// CLI argument override
fn get_config(cli_override: Option<&str>) -> AppPath {
AppPath::with_override("config.toml", cli_override)
}
// Configuration file override
struct Config {
data_dir: Option<String>,
}
let config = load_config();
let data_dir = AppPath::with_override("data", config.data_dir.as_deref());
Sourcepub fn with_override_fn<P: AsRef<Path>>(
default: impl AsRef<Path>,
override_fn: impl FnOnce() -> Option<P>,
) -> Self
pub fn with_override_fn<P: AsRef<Path>>( default: impl AsRef<Path>, override_fn: impl FnOnce() -> Option<P>, ) -> Self
Creates a path with dynamic override support.
Use this for complex override logic or lazy evaluation. The closure is called once to determine if an override should be applied.
§Examples
use app_path::AppPath;
use std::env;
// Multiple fallback sources
let config = AppPath::with_override_fn("config.toml", || {
env::var("APP_CONFIG").ok()
.or_else(|| env::var("CONFIG_FILE").ok())
.or_else(|| {
// Only check expensive operations if needed
if env::var("USE_SYSTEM_CONFIG").is_ok() {
Some("/etc/myapp/config.toml".to_string())
} else {
None
}
})
});
// Development mode override
let data_dir = AppPath::with_override_fn("data", || {
if env::var("DEVELOPMENT").is_ok() {
Some("dev_data".to_string())
} else {
None
}
});
Sourcepub fn try_with_override(
default: impl AsRef<Path>,
override_option: Option<impl AsRef<Path>>,
) -> Result<Self, AppPathError>
pub fn try_with_override( default: impl AsRef<Path>, override_option: Option<impl AsRef<Path>>, ) -> Result<Self, AppPathError>
Creates a path with override support (fallible).
Fallible version of Self::with_override()
. Most applications should use the
infallible version instead for cleaner code.
§Examples
use app_path::{AppPath, AppPathError};
use std::env;
fn get_config() -> Result<AppPath, AppPathError> {
AppPath::try_with_override("config.toml", env::var("CONFIG").ok())
}
cleaner, more idiomatic code.
§When to Use This Method
- Reusable libraries that should handle errors gracefully
- System-level tools that need to handle broken environments
- Applications with custom fallback strategies for rare edge cases
See AppPath::try_new()
for detailed guidance on when to use fallible APIs.
§Arguments
default
- The default path to use if no override is providedoverride_option
- Optional override path that takes precedence if provided
§Returns
Ok(AppPath)
- Successfully created AppPath with resolved pathErr(AppPathError)
- Failed to determine executable location
§Examples
§Library with Error Handling
use app_path::{AppPath, AppPathError};
use std::env;
fn create_config_path() -> Result<AppPath, AppPathError> {
let config_override = env::var("MYAPP_CONFIG").ok();
AppPath::try_with_override("config.toml", config_override.as_deref())
}
§Error Propagation
use app_path::{AppPath, AppPathError};
fn setup_paths(config_override: Option<&str>) -> Result<(AppPath, AppPath), AppPathError> {
let config = AppPath::try_with_override("config.toml", config_override)?;
let data = AppPath::try_with_override("data", None::<&str>)?;
Ok((config, data))
}
§Errors
Returns AppPathError
if the executable location cannot be determined:
AppPathError::ExecutableNotFound
-std::env::current_exe()
fails (extremely rare)AppPathError::InvalidExecutablePath
- Executable path is empty (system corruption)
See AppPath::try_new()
for detailed error conditions. After the first successful call
to any AppPath method, this method will never return an error (uses cached result).
Sourcepub fn try_with_override_fn<P: AsRef<Path>>(
default: impl AsRef<Path>,
override_fn: impl FnOnce() -> Option<P>,
) -> Result<Self, AppPathError>
pub fn try_with_override_fn<P: AsRef<Path>>( default: impl AsRef<Path>, override_fn: impl FnOnce() -> Option<P>, ) -> Result<Self, AppPathError>
Creates a path with dynamic override support (fallible).
This is the fallible version of AppPath::with_override_fn()
. Use this method
when you need explicit error handling combined with dynamic override logic.
Most applications should use AppPath::with_override_fn()
instead for
cleaner, more idiomatic code.
§When to Use This Method
- Reusable libraries with complex override logic that should handle errors gracefully
- System-level tools with dynamic configuration that need to handle broken environments
- Applications with custom fallback strategies for rare edge cases
See AppPath::try_new()
for detailed guidance on when to use fallible APIs.
§Arguments
default
- The default path to use if the override function returnsNone
override_fn
- A function that returns an optional override path
§Returns
Ok(AppPath)
- Successfully created AppPath with resolved pathErr(AppPathError)
- Failed to determine executable location
§Examples
§Library with Complex Override Logic
use app_path::{AppPath, AppPathError};
use std::env;
fn create_data_path() -> Result<AppPath, AppPathError> {
AppPath::try_with_override_fn("data", || {
// Complex override logic with multiple sources
env::var("DATA_DIR").ok()
.or_else(|| env::var("MYAPP_DATA_DIR").ok())
.or_else(|| {
if env::var("DEVELOPMENT").is_ok() {
Some("dev_data".to_string())
} else {
None
}
})
})
}
§Error Propagation with Dynamic Logic
use app_path::{AppPath, AppPathError};
fn setup_logging() -> Result<AppPath, AppPathError> {
AppPath::try_with_override_fn("logs/app.log", || {
// Dynamic override based on multiple conditions
if std::env::var("SYSLOG").is_ok() {
Some("/var/log/myapp.log".to_string())
} else if std::env::var("LOG_TO_TEMP").is_ok() {
Some(std::env::temp_dir().join("myapp.log").to_string_lossy().into_owned())
} else {
None
}
})
}
§Errors
Returns AppPathError
if the executable location cannot be determined:
AppPathError::ExecutableNotFound
-std::env::current_exe()
fails (extremely rare)AppPathError::InvalidExecutablePath
- Executable path is empty (system corruption)
See AppPath::try_new()
for detailed error conditions. After the first successful call
to any AppPath method, this method will never return an error (uses cached result).
Source§impl AppPath
impl AppPath
Sourcepub fn create_parents(&self) -> Result<(), AppPathError>
pub fn create_parents(&self) -> Result<(), AppPathError>
Creates parent directories needed for this file path.
This method creates all parent directories for a file path, making it ready for file creation. It does not create the file itself.
Use this when you know the path represents a file and you want to prepare the directory structure for writing the file.
§Examples
use app_path::AppPath;
use std::fs;
// Prepare directories for a log file relative to your app
let log_file = AppPath::with("logs/2024/app.log");
log_file.create_parents()?; // Creates logs/2024/ directories
// Parent directories exist, but file does not
let logs_dir = AppPath::with("logs");
let year_dir = AppPath::with("logs/2024");
assert!(logs_dir.exists());
assert!(year_dir.exists());
assert!(!log_file.exists()); // File not created, only parent dirs
// Now you can write the file
fs::write(&log_file, "Log entry")?;
assert!(log_file.exists());
§Complex Directory Structures
use app_path::AppPath;
use std::fs;
// Create parents for config file
let config_file = AppPath::with("config/database/settings.toml");
config_file.create_parents()?; // Creates config/database/ directories
// Create parents for data file
let data_file = AppPath::with("data/users/profiles.db");
data_file.create_parents()?; // Creates data/users/ directories
// All parent directories exist
assert!(AppPath::with("config").exists());
assert!(AppPath::with("config/database").exists());
assert!(AppPath::with("data").exists());
assert!(AppPath::with("data/users").exists());
§Errors
Returns AppPathError::IoError
if directory creation fails:
- Insufficient permissions - Cannot create directories due to filesystem permissions
- Disk space exhausted - Not enough space to create directory entries
- Invalid path characters - Path contains characters invalid for the target filesystem
- Network filesystem issues - Problems with remote/networked filesystems
- Filesystem corruption - Underlying filesystem errors
The operation is not atomic - some parent directories may be created even if the operation ultimately fails.
Sourcepub fn create_dir(&self) -> Result<(), AppPathError>
pub fn create_dir(&self) -> Result<(), AppPathError>
Creates this path as a directory, including all parent directories.
This method treats the path as a directory and creates it along with all necessary parent directories. The created directory will exist after this call succeeds.
Use this when you know the path represents a directory that should be created.
§Behavior
- Creates the directory itself: Unlike
create_parents()
, this creates the full path as a directory - Creates all parents: Any missing parent directories are created automatically
- Idempotent: Safe to call multiple times - won’t fail if directory already exists
- Atomic-like: Either all directories are created or the operation fails
§Examples
§Basic Directory Creation
use app_path::AppPath;
// Create a cache directory relative to your app
let cache_dir = AppPath::with("cache");
cache_dir.create_dir()?; // Creates cache/ directory
assert!(cache_dir.exists());
assert!(cache_dir.is_dir());
§Nested Directory Structures
use app_path::AppPath;
// Create deeply nested directories
let deep_dir = AppPath::with("data/backups/daily");
deep_dir.create_dir()?; // Creates data/backups/daily/ directories
assert!(deep_dir.exists());
assert!(deep_dir.is_dir());
// All parent directories are also created
let backups_dir = AppPath::with("data/backups");
assert!(backups_dir.exists());
assert!(backups_dir.is_dir());
§Practical Application Setup
use app_path::AppPath;
// Set up application directory structure
let config_dir = AppPath::with("config");
let data_dir = AppPath::with("data");
let cache_dir = AppPath::with("cache");
let logs_dir = AppPath::with("logs");
// Create all directories
config_dir.create_dir()?;
data_dir.create_dir()?;
cache_dir.create_dir()?;
logs_dir.create_dir()?;
// Now create subdirectories
let daily_logs = logs_dir.join("daily");
daily_logs.create_dir()?;
// Verify structure
assert!(config_dir.is_dir());
assert!(data_dir.is_dir());
assert!(cache_dir.is_dir());
assert!(logs_dir.is_dir());
assert!(daily_logs.is_dir());
§Comparison with create_parents()
use app_path::AppPath;
let file_path = AppPath::with("logs/app.log");
let dir_path = AppPath::with("logs");
// For files: prepare parent directories
file_path.create_parents()?; // Creates logs/ directory
assert!(dir_path.exists()); // logs/ directory exists
assert!(!file_path.exists()); // app.log file does NOT exist
// For directories: create the directory itself
dir_path.create_dir()?; // Creates logs/ directory (idempotent)
assert!(dir_path.exists()); // logs/ directory exists
assert!(dir_path.is_dir()); // and it's definitely a directory
§Errors
Returns AppPathError::IoError
if directory creation fails:
- Insufficient permissions - Cannot create directories due to filesystem permissions
- Disk space exhausted - Not enough space to create directory entries
- Invalid path characters - Path contains characters invalid for the target filesystem
- Network filesystem issues - Problems with remote/networked filesystems
- Path already exists as file - A file already exists at this path (not a directory)
- Filesystem corruption - Underlying filesystem errors
The operation creates parent directories as needed, but is not atomic - some parent directories may be created even if the final directory creation fails.
Source§impl AppPath
impl AppPath
Sourcepub fn join(&self, path: impl AsRef<Path>) -> Self
pub fn join(&self, path: impl AsRef<Path>) -> Self
Joins additional path segments to create a new AppPath.
This creates a new AppPath
by joining the current path with additional segments.
The new path inherits the same resolution behavior as the original.
§Examples
use app_path::AppPath;
let data_dir = AppPath::with("data");
let users_db = data_dir.join("users.db");
let backups = data_dir.join("backups").join("daily");
// Chain operations for complex paths
let log_file = AppPath::with("logs")
.join("2024")
.join("app.log");
Sourcepub fn parent(&self) -> Option<Self>
pub fn parent(&self) -> Option<Self>
Returns the parent directory as an AppPath, if it exists.
Returns None
if this path is a root directory or has no parent.
§Examples
use app_path::AppPath;
let config = AppPath::with("config/app.toml");
let config_dir = config.parent().unwrap();
let logs_dir = AppPath::with("logs");
let _app_dir = logs_dir.parent(); // Points to exe directory
Sourcepub fn with_extension(&self, ext: &str) -> Self
pub fn with_extension(&self, ext: &str) -> Self
Creates a new AppPath with the specified file extension.
If the path has an existing extension, it will be replaced. If no extension exists, the new extension will be added.
§Examples
use app_path::AppPath;
let config = AppPath::with("config");
let config_toml = config.with_extension("toml");
let config_json = config.with_extension("json");
let log_file = AppPath::with("app.log");
let backup_file = log_file.with_extension("bak");
Sourcepub fn into_path_buf(self) -> PathBuf
pub fn into_path_buf(self) -> PathBuf
Consumes the AppPath
and returns the internal PathBuf
.
This provides zero-cost extraction of the underlying PathBuf
by moving
it out of the wrapper. This is useful when you need owned access to the
path for operations that consume PathBuf
.
§Examples
use app_path::AppPath;
use std::path::PathBuf;
let app_path = AppPath::with("config.toml");
let path_buf: PathBuf = app_path.into_path_buf();
// Now you have a regular PathBuf for operations that need ownership
assert!(path_buf.is_absolute());
Sourcepub fn into_inner(self) -> PathBuf
pub fn into_inner(self) -> PathBuf
Consumes the AppPath
and returns the internal PathBuf
.
This is an alias for into_path_buf()
following
the standard Rust pattern for extracting wrapped values.
§Examples
use app_path::AppPath;
use std::path::PathBuf;
let app_path = AppPath::with("config.toml");
let path_buf: PathBuf = app_path.into_inner();
// Now you have a regular PathBuf for operations that need ownership
assert!(path_buf.is_absolute());
Sourcepub fn to_bytes(&self) -> Vec<u8> ⓘ
pub fn to_bytes(&self) -> Vec<u8> ⓘ
Returns the path as encoded bytes for low-level path operations.
This provides access to the platform-specific byte representation of the path. The returned bytes use platform-specific encoding and are only valid within the same Rust version and target platform.
Safety Note: These bytes should not be sent over networks, stored in files, or used across different platforms, as the encoding is implementation-specific.
Use cases include:
- Platform-specific path parsing with precise byte-level control
- Custom path validation that works with raw path bytes
- Integration with platform APIs that expect encoded path bytes
§Examples
use app_path::AppPath;
let config = AppPath::with("config.toml");
let bytes = config.to_bytes();
// Platform-specific byte operations
assert!(!bytes.is_empty());
Sourcepub fn into_bytes(self) -> Vec<u8> ⓘ
pub fn into_bytes(self) -> Vec<u8> ⓘ
Returns the path as owned encoded bytes.
This consumes the AppPath and returns owned bytes using the same platform-specific
encoding as to_bytes()
. The returned bytes are only valid within the same
Rust version and target platform.
Safety Note: These bytes should not be sent over networks, stored in files, or used across different platforms, as the encoding is implementation-specific.
Use cases include:
- Moving path data across ownership boundaries
- Temporary storage of path bytes during processing
- Platform-specific algorithms requiring owned byte data
§Examples
use app_path::AppPath;
let config = AppPath::with("config.toml");
let owned_bytes = config.into_bytes();
// Owned bytes can be moved and stored
assert!(!owned_bytes.is_empty());
Methods from Deref<Target = Path>§
1.0.0 · Sourcepub fn to_str(&self) -> Option<&str>
pub fn to_str(&self) -> Option<&str>
Yields a &str
slice if the Path
is valid unicode.
This conversion may entail doing a check for UTF-8 validity. Note that validation is performed because non-UTF-8 strings are perfectly valid for some OS.
§Examples
use std::path::Path;
let path = Path::new("foo.txt");
assert_eq!(path.to_str(), Some("foo.txt"));
1.0.0 · Sourcepub fn to_string_lossy(&self) -> Cow<'_, str>
pub fn to_string_lossy(&self) -> Cow<'_, str>
Converts a Path
to a Cow<str>
.
Any non-UTF-8 sequences are replaced with
U+FFFD REPLACEMENT CHARACTER
.
§Examples
Calling to_string_lossy
on a Path
with valid unicode:
use std::path::Path;
let path = Path::new("foo.txt");
assert_eq!(path.to_string_lossy(), "foo.txt");
Had path
contained invalid unicode, the to_string_lossy
call might
have returned "fo�.txt"
.
1.0.0 · Sourcepub fn to_path_buf(&self) -> PathBuf
pub fn to_path_buf(&self) -> PathBuf
1.0.0 · Sourcepub fn is_absolute(&self) -> bool
pub fn is_absolute(&self) -> bool
Returns true
if the Path
is absolute, i.e., if it is independent of
the current directory.
-
On Unix, a path is absolute if it starts with the root, so
is_absolute
andhas_root
are equivalent. -
On Windows, a path is absolute if it has a prefix and starts with the root:
c:\windows
is absolute, whilec:temp
and\temp
are not.
§Examples
use std::path::Path;
assert!(!Path::new("foo.txt").is_absolute());
1.0.0 · Sourcepub fn is_relative(&self) -> bool
pub fn is_relative(&self) -> bool
Returns true
if the Path
is relative, i.e., not absolute.
See is_absolute
’s documentation for more details.
§Examples
use std::path::Path;
assert!(Path::new("foo.txt").is_relative());
1.0.0 · Sourcepub fn has_root(&self) -> bool
pub fn has_root(&self) -> bool
Returns true
if the Path
has a root.
-
On Unix, a path has a root if it begins with
/
. -
On Windows, a path has a root if it:
- has no prefix and begins with a separator, e.g.,
\windows
- has a prefix followed by a separator, e.g.,
c:\windows
but notc:windows
- has any non-disk prefix, e.g.,
\\server\share
- has no prefix and begins with a separator, e.g.,
§Examples
use std::path::Path;
assert!(Path::new("/etc/passwd").has_root());
1.0.0 · Sourcepub fn parent(&self) -> Option<&Path>
pub fn parent(&self) -> Option<&Path>
Returns the Path
without its final component, if there is one.
This means it returns Some("")
for relative paths with one component.
Returns None
if the path terminates in a root or prefix, or if it’s
the empty string.
§Examples
use std::path::Path;
let path = Path::new("/foo/bar");
let parent = path.parent().unwrap();
assert_eq!(parent, Path::new("/foo"));
let grand_parent = parent.parent().unwrap();
assert_eq!(grand_parent, Path::new("/"));
assert_eq!(grand_parent.parent(), None);
let relative_path = Path::new("foo/bar");
let parent = relative_path.parent();
assert_eq!(parent, Some(Path::new("foo")));
let grand_parent = parent.and_then(Path::parent);
assert_eq!(grand_parent, Some(Path::new("")));
let great_grand_parent = grand_parent.and_then(Path::parent);
assert_eq!(great_grand_parent, None);
1.28.0 · Sourcepub fn ancestors(&self) -> Ancestors<'_>
pub fn ancestors(&self) -> Ancestors<'_>
Produces an iterator over Path
and its ancestors.
The iterator will yield the Path
that is returned if the parent
method is used zero
or more times. If the parent
method returns None
, the iterator will do likewise.
The iterator will always yield at least one value, namely Some(&self)
. Next it will yield
&self.parent()
, &self.parent().and_then(Path::parent)
and so on.
§Examples
use std::path::Path;
let mut ancestors = Path::new("/foo/bar").ancestors();
assert_eq!(ancestors.next(), Some(Path::new("/foo/bar")));
assert_eq!(ancestors.next(), Some(Path::new("/foo")));
assert_eq!(ancestors.next(), Some(Path::new("/")));
assert_eq!(ancestors.next(), None);
let mut ancestors = Path::new("../foo/bar").ancestors();
assert_eq!(ancestors.next(), Some(Path::new("../foo/bar")));
assert_eq!(ancestors.next(), Some(Path::new("../foo")));
assert_eq!(ancestors.next(), Some(Path::new("..")));
assert_eq!(ancestors.next(), Some(Path::new("")));
assert_eq!(ancestors.next(), None);
1.0.0 · Sourcepub fn file_name(&self) -> Option<&OsStr>
pub fn file_name(&self) -> Option<&OsStr>
Returns the final component of the Path
, if there is one.
If the path is a normal file, this is the file name. If it’s the path of a directory, this is the directory name.
Returns None
if the path terminates in ..
.
§Examples
use std::path::Path;
use std::ffi::OsStr;
assert_eq!(Some(OsStr::new("bin")), Path::new("/usr/bin/").file_name());
assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name());
assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name());
assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name());
assert_eq!(None, Path::new("foo.txt/..").file_name());
assert_eq!(None, Path::new("/").file_name());
1.7.0 · Sourcepub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
Returns a path that, when joined onto base
, yields self
.
§Errors
If base
is not a prefix of self
(i.e., starts_with
returns false
), returns Err
.
§Examples
use std::path::{Path, PathBuf};
let path = Path::new("/test/haha/foo.txt");
assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));
assert!(path.strip_prefix("test").is_err());
assert!(path.strip_prefix("/te").is_err());
assert!(path.strip_prefix("/haha").is_err());
let prefix = PathBuf::from("/test/");
assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
1.0.0 · Sourcepub fn starts_with<P>(&self, base: P) -> bool
pub fn starts_with<P>(&self, base: P) -> bool
Determines whether base
is a prefix of self
.
Only considers whole path components to match.
§Examples
use std::path::Path;
let path = Path::new("/etc/passwd");
assert!(path.starts_with("/etc"));
assert!(path.starts_with("/etc/"));
assert!(path.starts_with("/etc/passwd"));
assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
assert!(!path.starts_with("/e"));
assert!(!path.starts_with("/etc/passwd.txt"));
assert!(!Path::new("/etc/foo.rs").starts_with("/etc/foo"));
1.0.0 · Sourcepub fn ends_with<P>(&self, child: P) -> bool
pub fn ends_with<P>(&self, child: P) -> bool
Determines whether child
is a suffix of self
.
Only considers whole path components to match.
§Examples
use std::path::Path;
let path = Path::new("/etc/resolv.conf");
assert!(path.ends_with("resolv.conf"));
assert!(path.ends_with("etc/resolv.conf"));
assert!(path.ends_with("/etc/resolv.conf"));
assert!(!path.ends_with("/resolv.conf"));
assert!(!path.ends_with("conf")); // use .extension() instead
1.0.0 · Sourcepub fn file_stem(&self) -> Option<&OsStr>
pub fn file_stem(&self) -> Option<&OsStr>
Extracts the stem (non-extension) portion of self.file_name
.
The stem is:
None
, if there is no file name;- The entire file name if there is no embedded
.
; - The entire file name if the file name begins with
.
and has no other.
s within; - Otherwise, the portion of the file name before the final
.
§Examples
use std::path::Path;
assert_eq!("foo", Path::new("foo.rs").file_stem().unwrap());
assert_eq!("foo.tar", Path::new("foo.tar.gz").file_stem().unwrap());
§See Also
This method is similar to Path::file_prefix
, which extracts the portion of the file name
before the first .
Sourcepub fn file_prefix(&self) -> Option<&OsStr>
🔬This is a nightly-only experimental API. (path_file_prefix
)
pub fn file_prefix(&self) -> Option<&OsStr>
path_file_prefix
)Extracts the prefix of self.file_name
.
The prefix is:
None
, if there is no file name;- The entire file name if there is no embedded
.
; - The portion of the file name before the first non-beginning
.
; - The entire file name if the file name begins with
.
and has no other.
s within; - The portion of the file name before the second
.
if the file name begins with.
§Examples
use std::path::Path;
assert_eq!("foo", Path::new("foo.rs").file_prefix().unwrap());
assert_eq!("foo", Path::new("foo.tar.gz").file_prefix().unwrap());
§See Also
This method is similar to Path::file_stem
, which extracts the portion of the file name
before the last .
1.0.0 · Sourcepub fn extension(&self) -> Option<&OsStr>
pub fn extension(&self) -> Option<&OsStr>
Extracts the extension (without the leading dot) of self.file_name
, if possible.
The extension is:
None
, if there is no file name;None
, if there is no embedded.
;None
, if the file name begins with.
and has no other.
s within;- Otherwise, the portion of the file name after the final
.
§Examples
use std::path::Path;
assert_eq!("rs", Path::new("foo.rs").extension().unwrap());
assert_eq!("gz", Path::new("foo.tar.gz").extension().unwrap());
1.0.0 · Sourcepub fn join<P>(&self, path: P) -> PathBuf
pub fn join<P>(&self, path: P) -> PathBuf
Creates an owned PathBuf
with path
adjoined to self
.
If path
is absolute, it replaces the current path.
See PathBuf::push
for more details on what it means to adjoin a path.
§Examples
use std::path::{Path, PathBuf};
assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd"));
assert_eq!(Path::new("/etc").join("/bin/sh"), PathBuf::from("/bin/sh"));
1.0.0 · Sourcepub fn with_file_name<S>(&self, file_name: S) -> PathBuf
pub fn with_file_name<S>(&self, file_name: S) -> PathBuf
Creates an owned PathBuf
like self
but with the given file name.
See PathBuf::set_file_name
for more details.
§Examples
use std::path::{Path, PathBuf};
let path = Path::new("/tmp/foo.png");
assert_eq!(path.with_file_name("bar"), PathBuf::from("/tmp/bar"));
assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt"));
let path = Path::new("/tmp");
assert_eq!(path.with_file_name("var"), PathBuf::from("/var"));
1.0.0 · Sourcepub fn with_extension<S>(&self, extension: S) -> PathBuf
pub fn with_extension<S>(&self, extension: S) -> PathBuf
Creates an owned PathBuf
like self
but with the given extension.
See PathBuf::set_extension
for more details.
§Examples
use std::path::Path;
let path = Path::new("foo.rs");
assert_eq!(path.with_extension("txt"), Path::new("foo.txt"));
assert_eq!(path.with_extension(""), Path::new("foo"));
Handling multiple extensions:
use std::path::Path;
let path = Path::new("foo.tar.gz");
assert_eq!(path.with_extension("xz"), Path::new("foo.tar.xz"));
assert_eq!(path.with_extension("").with_extension("txt"), Path::new("foo.txt"));
Adding an extension where one did not exist:
use std::path::Path;
let path = Path::new("foo");
assert_eq!(path.with_extension("rs"), Path::new("foo.rs"));
Sourcepub fn with_added_extension<S>(&self, extension: S) -> PathBuf
🔬This is a nightly-only experimental API. (path_add_extension
)
pub fn with_added_extension<S>(&self, extension: S) -> PathBuf
path_add_extension
)Creates an owned PathBuf
like self
but with the extension added.
See PathBuf::add_extension
for more details.
§Examples
#![feature(path_add_extension)]
use std::path::{Path, PathBuf};
let path = Path::new("foo.rs");
assert_eq!(path.with_added_extension("txt"), PathBuf::from("foo.rs.txt"));
let path = Path::new("foo.tar.gz");
assert_eq!(path.with_added_extension(""), PathBuf::from("foo.tar.gz"));
assert_eq!(path.with_added_extension("xz"), PathBuf::from("foo.tar.gz.xz"));
assert_eq!(path.with_added_extension("").with_added_extension("txt"), PathBuf::from("foo.tar.gz.txt"));
1.0.0 · Sourcepub fn components(&self) -> Components<'_>
pub fn components(&self) -> Components<'_>
Produces an iterator over the Component
s of the path.
When parsing the path, there is a small amount of normalization:
-
Repeated separators are ignored, so
a/b
anda//b
both havea
andb
as components. -
Occurrences of
.
are normalized away, except if they are at the beginning of the path. For example,a/./b
,a/b/
,a/b/.
anda/b
all havea
andb
as components, but./a/b
starts with an additionalCurDir
component. -
A trailing slash is normalized away,
/a/b
and/a/b/
are equivalent.
Note that no other normalization takes place; in particular, a/c
and a/b/../c
are distinct, to account for the possibility that b
is a symbolic link (so its parent isn’t a
).
§Examples
use std::path::{Path, Component};
use std::ffi::OsStr;
let mut components = Path::new("/tmp/foo.txt").components();
assert_eq!(components.next(), Some(Component::RootDir));
assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp"))));
assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt"))));
assert_eq!(components.next(), None)
1.0.0 · Sourcepub fn iter(&self) -> Iter<'_>
pub fn iter(&self) -> Iter<'_>
Produces an iterator over the path’s components viewed as OsStr
slices.
For more information about the particulars of how the path is separated
into components, see components
.
§Examples
use std::path::{self, Path};
use std::ffi::OsStr;
let mut it = Path::new("/tmp/foo.txt").iter();
assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string())));
assert_eq!(it.next(), Some(OsStr::new("tmp")));
assert_eq!(it.next(), Some(OsStr::new("foo.txt")));
assert_eq!(it.next(), None)
1.0.0 · Sourcepub fn display(&self) -> Display<'_>
pub fn display(&self) -> Display<'_>
Returns an object that implements Display
for safely printing paths
that may contain non-Unicode data. This may perform lossy conversion,
depending on the platform. If you would like an implementation which
escapes the path please use Debug
instead.
§Examples
use std::path::Path;
let path = Path::new("/tmp/foo.rs");
println!("{}", path.display());
1.5.0 · Sourcepub fn metadata(&self) -> Result<Metadata, Error>
pub fn metadata(&self) -> Result<Metadata, Error>
Queries the file system to get information about a file, directory, etc.
This function will traverse symbolic links to query information about the destination file.
This is an alias to fs::metadata
.
§Examples
use std::path::Path;
let path = Path::new("/Minas/tirith");
let metadata = path.metadata().expect("metadata call failed");
println!("{:?}", metadata.file_type());
1.5.0 · Sourcepub fn symlink_metadata(&self) -> Result<Metadata, Error>
pub fn symlink_metadata(&self) -> Result<Metadata, Error>
Queries the metadata about a file without following symlinks.
This is an alias to fs::symlink_metadata
.
§Examples
use std::path::Path;
let path = Path::new("/Minas/tirith");
let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
println!("{:?}", metadata.file_type());
1.5.0 · Sourcepub fn canonicalize(&self) -> Result<PathBuf, Error>
pub fn canonicalize(&self) -> Result<PathBuf, Error>
Returns the canonical, absolute form of the path with all intermediate components normalized and symbolic links resolved.
This is an alias to fs::canonicalize
.
§Examples
use std::path::{Path, PathBuf};
let path = Path::new("/foo/test/../test/bar.rs");
assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
Sourcepub fn normalize_lexically(&self) -> Result<PathBuf, NormalizeError>
🔬This is a nightly-only experimental API. (normalize_lexically
)
pub fn normalize_lexically(&self) -> Result<PathBuf, NormalizeError>
normalize_lexically
)Normalize a path, including ..
without traversing the filesystem.
Returns an error if normalization would leave leading ..
components.
This function always resolves ..
to the “lexical” parent.
That is “a/b/../c” will always resolve to a/c
which can change the meaning of the path.
In particular, a/c
and a/b/../c
are distinct on many systems because b
may be a symbolic link, so its parent isn’t a
.
path::absolute
is an alternative that preserves ..
.
Or Path::canonicalize
can be used to resolve any ..
by querying the filesystem.
1.5.0 · Sourcepub fn read_link(&self) -> Result<PathBuf, Error>
pub fn read_link(&self) -> Result<PathBuf, Error>
Reads a symbolic link, returning the file that the link points to.
This is an alias to fs::read_link
.
§Examples
use std::path::Path;
let path = Path::new("/laputa/sky_castle.rs");
let path_link = path.read_link().expect("read_link call failed");
1.5.0 · Sourcepub fn read_dir(&self) -> Result<ReadDir, Error>
pub fn read_dir(&self) -> Result<ReadDir, Error>
Returns an iterator over the entries within a directory.
The iterator will yield instances of io::Result<fs::DirEntry>
. New
errors may be encountered after an iterator is initially constructed.
This is an alias to fs::read_dir
.
§Examples
use std::path::Path;
let path = Path::new("/laputa");
for entry in path.read_dir().expect("read_dir call failed") {
if let Ok(entry) = entry {
println!("{:?}", entry.path());
}
}
1.5.0 · Sourcepub fn exists(&self) -> bool
pub fn exists(&self) -> bool
Returns true
if the path points at an existing entity.
Warning: this method may be error-prone, consider using try_exists()
instead!
It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs.
This function will traverse symbolic links to query information about the destination file.
If you cannot access the metadata of the file, e.g. because of a
permission error or broken symbolic links, this will return false
.
§Examples
use std::path::Path;
assert!(!Path::new("does_not_exist.txt").exists());
§See Also
This is a convenience function that coerces errors to false. If you want to
check errors, call Path::try_exists
.
1.63.0 · Sourcepub fn try_exists(&self) -> Result<bool, Error>
pub fn try_exists(&self) -> Result<bool, Error>
Returns Ok(true)
if the path points at an existing entity.
This function will traverse symbolic links to query information about the
destination file. In case of broken symbolic links this will return Ok(false)
.
Path::exists()
only checks whether or not a path was both found and readable. By
contrast, try_exists
will return Ok(true)
or Ok(false)
, respectively, if the path
was verified to exist or not exist. If its existence can neither be confirmed nor
denied, it will propagate an Err(_)
instead. This can be the case if e.g. listing
permission is denied on one of the parent directories.
Note that while this avoids some pitfalls of the exists()
method, it still can not
prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
where those bugs are not an issue.
This is an alias for std::fs::exists
.
§Examples
use std::path::Path;
assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
1.5.0 · Sourcepub fn is_file(&self) -> bool
pub fn is_file(&self) -> bool
Returns true
if the path exists on disk and is pointing at a regular file.
This function will traverse symbolic links to query information about the destination file.
If you cannot access the metadata of the file, e.g. because of a
permission error or broken symbolic links, this will return false
.
§Examples
use std::path::Path;
assert_eq!(Path::new("./is_a_directory/").is_file(), false);
assert_eq!(Path::new("a_file.txt").is_file(), true);
§See Also
This is a convenience function that coerces errors to false. If you want to
check errors, call fs::metadata
and handle its Result
. Then call
fs::Metadata::is_file
if it was Ok
.
When the goal is simply to read from (or write to) the source, the most
reliable way to test the source can be read (or written to) is to open
it. Only using is_file
can break workflows like diff <( prog_a )
on
a Unix-like system for example. See fs::File::open
or
fs::OpenOptions::open
for more information.
1.5.0 · Sourcepub fn is_dir(&self) -> bool
pub fn is_dir(&self) -> bool
Returns true
if the path exists on disk and is pointing at a directory.
This function will traverse symbolic links to query information about the destination file.
If you cannot access the metadata of the file, e.g. because of a
permission error or broken symbolic links, this will return false
.
§Examples
use std::path::Path;
assert_eq!(Path::new("./is_a_directory/").is_dir(), true);
assert_eq!(Path::new("a_file.txt").is_dir(), false);
§See Also
This is a convenience function that coerces errors to false. If you want to
check errors, call fs::metadata
and handle its Result
. Then call
fs::Metadata::is_dir
if it was Ok
.
1.58.0 · Sourcepub fn is_symlink(&self) -> bool
pub fn is_symlink(&self) -> bool
Returns true
if the path exists on disk and is pointing at a symbolic link.
This function will not traverse symbolic links. In case of a broken symbolic link this will also return true.
If you cannot access the directory containing the file, e.g., because of a permission error, this will return false.
§Examples
use std::path::Path;
use std::os::unix::fs::symlink;
let link_path = Path::new("link");
symlink("/origin_does_not_exist/", link_path).unwrap();
assert_eq!(link_path.is_symlink(), true);
assert_eq!(link_path.exists(), false);
§See Also
This is a convenience function that coerces errors to false. If you want to
check errors, call fs::symlink_metadata
and handle its Result
. Then call
fs::Metadata::is_symlink
if it was Ok
.
Trait Implementations§
Source§impl Borrow<Path> for AppPath
impl Borrow<Path> for AppPath
Source§fn borrow(&self) -> &Path
fn borrow(&self) -> &Path
Allows AppPath
to be borrowed as a Path
.
This enables AppPath
to be used seamlessly in collections that are
keyed by Path
, and allows for efficient lookups using &Path
values.
§Examples
use app_path::AppPath;
use std::collections::HashMap;
use std::path::Path;
let mut path_map = HashMap::new();
let app_path = AppPath::with("config.toml");
path_map.insert(app_path, "config data");
// Can look up using a &Path
let lookup_path = Path::new("relative/to/exe/config.toml");
// Note: This would only work if the paths actually match
Source§impl Default for AppPath
Default implementation returns the executable’s directory.
impl Default for AppPath
Default implementation returns the executable’s directory.
This provides a natural default for AppPath - the directory where the executable is located.
§Examples
use app_path::AppPath;
use std::path::Path;
let exe_dir = AppPath::default();
let explicit = AppPath::new();
assert_eq!(exe_dir.as_ref() as &Path, explicit.as_ref() as &Path);
Source§impl Deref for AppPath
impl Deref for AppPath
Source§fn deref(&self) -> &Self::Target
fn deref(&self) -> &Self::Target
Provides direct access to the underlying Path
through deref coercion.
This allows AppPath
to be used directly with any API that expects a &Path
,
making it a zero-cost abstraction in many contexts. All Path
methods become
directly available on AppPath
instances.
§Examples
use app_path::AppPath;
let app_path = AppPath::with("config.toml");
// Direct access to Path methods through deref
assert_eq!(app_path.extension(), Some("toml".as_ref()));
assert_eq!(app_path.file_name(), Some("config.toml".as_ref()));
assert!(app_path.is_absolute());
// Works with functions expecting &Path
fn process_path(path: &std::path::Path) {
println!("Processing: {}", path.display());
}
process_path(&app_path); // Automatic deref coercion
// For explicit &Path reference when needed
let path_ref: &std::path::Path = &app_path; // Via deref
let path_ref2: &std::path::Path = app_path.as_ref(); // Via AsRef
Source§impl From<AppPath> for PathBuf
impl From<AppPath> for PathBuf
Source§fn from(app_path: AppPath) -> Self
fn from(app_path: AppPath) -> Self
Converts AppPath
to PathBuf
for owned path operations.
This moves the internal PathBuf
out of the AppPath
, providing
efficient conversion without cloning.
§Examples
use app_path::AppPath;
use std::path::PathBuf;
let config = AppPath::with("config.toml");
let path_buf: PathBuf = config.into();
Source§impl Hash for AppPath
impl Hash for AppPath
Source§fn hash<H: Hasher>(&self, state: &mut H)
fn hash<H: Hasher>(&self, state: &mut H)
Computes a hash for the AppPath
based on its resolved path.
This enables AppPath
to be used as keys in hash-based collections
like HashMap
and HashSet
. The hash is computed from the full
resolved path, ensuring consistent behavior.
§Examples
use app_path::AppPath;
use std::collections::HashMap;
let mut config_map = HashMap::new();
let config_path = AppPath::with("config.toml");
config_map.insert(config_path, "Configuration file");
Source§impl Ord for AppPath
impl Ord for AppPath
Source§fn cmp(&self, other: &Self) -> Ordering
fn cmp(&self, other: &Self) -> Ordering
Compares two AppPath
instances lexicographically based on their resolved paths.
This provides a total ordering that enables AppPath
to be used in sorted
collections like BTreeMap
and BTreeSet
.
§Examples
use app_path::AppPath;
use std::collections::BTreeSet;
let mut paths = BTreeSet::new();
paths.insert(AppPath::with("config.toml"));
paths.insert(AppPath::with("data.db"));
paths.insert(AppPath::with("app.log"));
// Paths are automatically sorted lexicographically
let sorted: Vec<_> = paths.into_iter().collect();
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl PartialEq for AppPath
impl PartialEq for AppPath
Source§fn eq(&self, other: &Self) -> bool
fn eq(&self, other: &Self) -> bool
Compares two AppPath
instances for equality based on their resolved paths.
Two AppPath
instances are considered equal if their full resolved paths
are identical, regardless of how they were constructed.
§Examples
use app_path::AppPath;
let path1 = AppPath::with("config.toml");
let path2 = AppPath::with("config.toml");
let path3 = AppPath::with("other.toml");
assert_eq!(path1, path2);
assert_ne!(path1, path3);
Source§impl PartialOrd for AppPath
impl PartialOrd for AppPath
Source§fn partial_cmp(&self, other: &Self) -> Option<Ordering>
fn partial_cmp(&self, other: &Self) -> Option<Ordering>
Compares two AppPath
instances lexicographically based on their resolved paths.
The comparison is performed on the full resolved paths, providing consistent ordering for sorting and collection operations.
§Examples
use app_path::AppPath;
let path1 = AppPath::with("a.txt");
let path2 = AppPath::with("b.txt");
assert!(path1 < path2);