multi-ssh/src/action.rs

84 lines
1.8 KiB
Rust

use crate::server::Server;
use std::ffi::{OsStr, OsString};
use std::fmt::{Display, Formatter};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct ServerActions<'a> {
pub server: &'a Server,
pub working_directory: PathBuf,
pub actions: Vec<FileAction>,
}
impl Display for ServerActions<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}: ({})",
self.server.get_name(),
self.working_directory.to_string_lossy()
)?;
for action in &self.actions {
write!(f, "\n{}", action)?;
}
Ok(())
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct FileAction {
pub file: PathBuf,
pub file_name: OsString,
pub kind: Action,
}
impl FileAction {
pub fn new<P>(file: P, kind: Action) -> Option<Self>
where
P: AsRef<Path>,
{
let file = PathBuf::from(file.as_ref());
let file_name = file.file_name()?.to_os_string();
Some(Self {
file,
file_name,
kind,
})
}
}
impl Display for FileAction {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.kind {
Action::Add => write!(f, "+ adding {}", self.file_name.to_string_lossy()),
Action::Replace => write!(f, "~ replacing {}", self.file_name.to_string_lossy()),
Action::Delete => write!(f, "- deleting {}", self.file_name.to_string_lossy()),
Action::Rename { new_name } => write!(
f,
"* renaming {} -> {}",
self.file_name.to_string_lossy(),
new_name.to_string_lossy()
),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Action {
Add,
Replace,
Delete,
Rename { new_name: OsString },
}
impl Action {
pub fn rename<S>(new_name: S) -> Self
where
S: AsRef<OsStr>,
{
Self::Rename {
new_name: new_name.as_ref().to_owned(),
}
}
}