This commit is contained in:
2025-04-04 18:38:53 +02:00
parent c9b4010089
commit bf5eb2f6fc
10 changed files with 198 additions and 29 deletions

View File

@@ -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))
}