mod shell;
use crate::error::PathmanError;
use crate::error::PathmanError::{
UnableToCreateExportCommand, UnableToReadShellConfigFile, UnableToWriteShellConfigFile,
};
use crate::platform::unix::shell::CurrentShell;
use crate::platform::{PathUpdater, UpdateType};
use std::path::{Path, PathBuf};
pub struct UnixPathUpdater;
impl UnixPathUpdater {
fn write_to_shell_config_file(
config_file_path: PathBuf,
export_line: &str,
comment: Option<&str>,
) -> Result<UpdateType, PathmanError> {
let mut content = match std::fs::read_to_string(&config_file_path) {
Ok(content) => content,
Err(_) => {
return Err(UnableToReadShellConfigFile(
config_file_path.to_string_lossy().to_string(),
));
}
};
if content.contains(export_line) {
return Ok(UpdateType::AlreadyInPath);
}
let comment = match comment {
Some(comment) => format!("\n# {comment}"),
None => String::new(),
};
content.push_str(&format!("{comment}\n{export_line}"));
if std::fs::write(&config_file_path, content).is_err() {
return Err(UnableToWriteShellConfigFile(
config_file_path.to_string_lossy().to_string(),
));
}
Ok(UpdateType::Success)
}
}
impl PathUpdater for UnixPathUpdater {
fn prepend<P: AsRef<Path>>(path: P, comment: Option<&str>) -> Result<UpdateType, PathmanError> {
let shell = CurrentShell::detect()?;
let export_command = match shell.get_prepend_command(path) {
Ok(line) => line,
Err(_) => return Err(UnableToCreateExportCommand),
};
Self::write_to_shell_config_file(shell.config_file_path()?, &export_command, comment)
}
fn append<P: AsRef<Path>>(path: P, comment: Option<&str>) -> Result<UpdateType, PathmanError> {
let shell = CurrentShell::detect()?;
let export_command = match shell.get_append_command(path) {
Ok(line) => line,
Err(_) => return Err(UnableToCreateExportCommand),
};
Self::write_to_shell_config_file(shell.config_file_path()?, &export_command, comment)
}
}