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
Self::new()
- Primary API: Simple, infallible constructionSelf::try_new()
- Libraries: Fallible version for error handlingSelf::with_override()
- Deployment: Environment-configurable pathsSelf::path()
- Access: Get the resolved&Path
§Panics
Methods panic if executable location cannot be determined (extremely rare). After first successful call, methods never panic (uses cached result).
§Examples
use app_path::AppPath;
// Basic usage - most common pattern
let config = AppPath::new("config.toml");
let data = AppPath::new("data/users.db");
// Works like standard paths
if config.exists() {
let content = std::fs::read_to_string(&config);
}
data.create_dir_all(); // Creates data/ directory
// Mixed portable and system paths
let portable = AppPath::new("app.conf"); // → exe_dir/app.conf
let system = AppPath::new("/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(path: impl AsRef<Path>) -> Self
pub fn new(path: impl AsRef<Path>) -> Self
Creates file paths relative to the executable location.
Recommended for most applications. This is the simple, infallible API that handles the common case cleanly without error handling boilerplate.
§Path Resolution
- Relative paths:
"config.toml"
→exe_dir/config.toml
(portable) - Absolute paths:
"/etc/config"
→/etc/config
(system integration)
§Performance
- Static caching: Executable location determined once, reused forever
- Zero allocations: Efficient path resolution
- Thread-safe: Safe to call from multiple threads
§Panics
Panics if executable location cannot be determined (extremely rare):
std::env::current_exe()
fails- Executable path is empty (system corruption)
After first successful call, this method never panics (uses cached result).
§Examples
use app_path::AppPath;
// Most common usage
let config = AppPath::new("config.toml");
let data = AppPath::new("data/users.db");
let logs = AppPath::new("logs/app.log");
// Mixed portable and system paths
let app_config = AppPath::new("config.toml"); // → exe_dir/config.toml
let system_log = AppPath::new("/var/log/myapp.log"); // → /var/log/myapp.log
// Use like normal paths
if config.exists() {
let content = std::fs::read_to_string(&config);
}
data.create_dir_all(); // Creates data/ directory
§Panics
Panics on first use if the executable location cannot be determined.
This is extremely rare and indicates fundamental system issues.
See AppPathError
for details on the possible failure conditions.
After the first successful call, this method will never panic as it uses the cached result.
§Performance
This method is highly optimized:
- Static caching: Executable location determined once, reused forever
- Zero allocations: Uses
AsRef<Path>
to avoid unnecessary conversions - Minimal memory: Only stores the final resolved path
- Thread-safe: Safe to call from multiple threads concurrently
§Examples
use app_path::AppPath;
// Most common usage
let config = AppPath::new("config.toml");
let data = AppPath::new("data/users.db");
let logs = AppPath::new("logs/app.log");
// Mixed portable and system paths
let app_config = AppPath::new("config.toml"); // → exe_dir/config.toml
let system_log = AppPath::new("/var/log/myapp.log"); // → /var/log/myapp.log
// Use like normal paths
if config.exists() {
let content = std::fs::read_to_string(&config);
}
data.create_dir_all(); // Creates data/ directory
Sourcepub fn try_new(path: impl AsRef<Path>) -> Result<Self, AppPathError>
pub fn try_new(path: impl AsRef<Path>) -> 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_new("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!("{}/myapp/config.toml", dir)))
})
}
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 executable 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_new("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_new("config.toml")?;
let data = AppPath::try_new("data/app.db")?;
// Initialize application with these paths
println!("Config: {}", config.path().display());
println!("Data: {}", data.path().display());
Ok(())
}
Sourcepub fn path(&self) -> &Path
pub fn path(&self) -> &Path
Get the full resolved path.
This is the primary method for getting the actual filesystem path where your file or directory is located.
§Examples
use app_path::AppPath;
let config = AppPath::new("config.toml");
// Get the path for use with standard library functions
println!("Config path: {}", config.path().display());
// The path is always absolute
assert!(config.path().is_absolute());
Sourcepub fn exists(&self) -> bool
pub fn exists(&self) -> bool
Check if the path exists.
§Examples
use app_path::AppPath;
let config = AppPath::new("config.toml");
if config.exists() {
println!("Config file found!");
} else {
println!("Config file not found, using defaults.");
}
Sourcepub fn create_dir_all(&self) -> Result<()>
pub fn create_dir_all(&self) -> Result<()>
Create parent directories if they don’t exist.
This is equivalent to calling std::fs::create_dir_all
on the
parent directory of this path.
§Examples
use app_path::AppPath;
use std::env;
// Use a temporary directory for the example
let temp_dir = env::temp_dir().join("app_path_example");
let data_file_path = temp_dir.join("data/users/profile.json");
let data_file = AppPath::new(data_file_path);
// Ensure the "data/users" directory exists
data_file.create_dir_all()?;
// Verify the directory was created
assert!(data_file.path().parent().unwrap().exists());
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<F, P>(default: impl AsRef<Path>, override_fn: F) -> Self
pub fn with_override_fn<F, P>(default: impl AsRef<Path>, override_fn: F) -> 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))
}
Sourcepub fn try_with_override_fn<F, P>(
default: impl AsRef<Path>,
override_fn: F,
) -> Result<Self, AppPathError>
pub fn try_with_override_fn<F, P>( default: impl AsRef<Path>, override_fn: F, ) -> 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
}
})
}
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::new("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::new("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::new("config/app.toml");
let config_dir = config.parent().unwrap();
let logs_dir = AppPath::new("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::new("config");
let config_toml = config.with_extension("toml");
let config_json = config.with_extension("json");
let log_file = AppPath::new("app.log");
let backup_file = log_file.with_extension("bak");
Sourcepub fn file_name(&self) -> Option<&OsStr>
pub fn file_name(&self) -> Option<&OsStr>
Returns the file name of this path as an OsStr
, if it exists.
This is a convenience method that delegates to the underlying Path
.
§Examples
use app_path::AppPath;
let config = AppPath::new("config/app.toml");
assert_eq!(config.file_name().unwrap(), "app.toml");
Sourcepub fn file_stem(&self) -> Option<&OsStr>
pub fn file_stem(&self) -> Option<&OsStr>
Returns the file stem of this path as an OsStr
, if it exists.
This is a convenience method that delegates to the underlying Path
.
§Examples
use app_path::AppPath;
let config = AppPath::new("config/app.toml");
assert_eq!(config.file_stem().unwrap(), "app");
Sourcepub fn extension(&self) -> Option<&OsStr>
pub fn extension(&self) -> Option<&OsStr>
Returns the extension of this path as an OsStr
, if it exists.
This is a convenience method that delegates to the underlying Path
.
§Examples
use app_path::AppPath;
let config = AppPath::new("config/app.toml");
assert_eq!(config.extension().unwrap(), "toml");
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::new("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
impl Default for AppPath
Source§fn default() -> Self
fn default() -> Self
Creates an AppPath
pointing to the executable’s directory.
This is equivalent to calling AppPath::new("")
. The default instance
represents the directory containing the executable, which is useful as
a starting point for portable applications.
§Examples
use app_path::AppPath;
let exe_dir = AppPath::default();
let empty_path = AppPath::new("");
// Default should be equivalent to new("")
assert_eq!(exe_dir, empty_path);
// Both should point to the executable directory
assert_eq!(exe_dir.path(), app_path::exe_dir());
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::new("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()));
// Works with functions expecting &Path
fn process_path(path: &std::path::Path) {
println!("Processing: {}", path.display());
}
process_path(&app_path); // Automatic deref coercion
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::new("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::new("config.toml"));
paths.insert(AppPath::new("data.db"));
paths.insert(AppPath::new("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::new("config.toml");
let path2 = AppPath::new("config.toml");
let path3 = AppPath::new("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::new("a.txt");
let path2 = AppPath::new("b.txt");
assert!(path1 < path2);