...
This commit is contained in:
41
src/os/fs.rs
41
src/os/fs.rs
@@ -20,6 +20,7 @@ pub enum FsError {
|
||||
NotAFile(String),
|
||||
UnknownFileType(String),
|
||||
MetadataError(io::Error),
|
||||
ChangeDirFailed(io::Error),
|
||||
}
|
||||
|
||||
// Implement Display for FsError
|
||||
@@ -38,6 +39,7 @@ impl fmt::Display for FsError {
|
||||
FsError::NotAFile(path) => write!(f, "Path '{}' is not a regular file", path),
|
||||
FsError::UnknownFileType(path) => write!(f, "Unknown file type at '{}'", path),
|
||||
FsError::MetadataError(e) => write!(f, "Failed to get file metadata: {}", e),
|
||||
FsError::ChangeDirFailed(e) => write!(f, "Failed to change directory: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,6 +54,7 @@ impl Error for FsError {
|
||||
FsError::CommandExecutionError(e) => Some(e),
|
||||
FsError::InvalidGlobPattern(e) => Some(e),
|
||||
FsError::MetadataError(e) => Some(e),
|
||||
FsError::ChangeDirFailed(e) => Some(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -578,3 +581,41 @@ pub fn rsync(src: &str, dest: &str) -> Result<String, FsError> {
|
||||
Err(e) => Err(FsError::CommandExecutionError(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the current working directory.
|
||||
*
|
||||
* # Arguments
|
||||
*
|
||||
* * `path` - The path to change to
|
||||
*
|
||||
* # Returns
|
||||
*
|
||||
* * `Ok(String)` - A success message indicating the directory was changed
|
||||
* * `Err(FsError)` - An error if the directory change failed
|
||||
*
|
||||
* # Examples
|
||||
*
|
||||
* ```
|
||||
* let result = chdir("/path/to/directory")?;
|
||||
* println!("{}", result);
|
||||
* ```
|
||||
*/
|
||||
pub fn chdir(path: &str) -> Result<String, FsError> {
|
||||
let path_obj = Path::new(path);
|
||||
|
||||
// Check if directory exists
|
||||
if !path_obj.exists() {
|
||||
return Err(FsError::DirectoryNotFound(path.to_string()));
|
||||
}
|
||||
|
||||
// Check if it's a directory
|
||||
if !path_obj.is_dir() {
|
||||
return Err(FsError::NotADirectory(path.to_string()));
|
||||
}
|
||||
|
||||
// Change directory
|
||||
std::env::set_current_dir(path_obj).map_err(FsError::ChangeDirFailed)?;
|
||||
|
||||
Ok(format!("Successfully changed directory to '{}'", path))
|
||||
}
|
||||
|
Reference in New Issue
Block a user