use std::path::PathBuf;
pub struct SftpSession {
current_dir: PathBuf,
home_dir: PathBuf,
username: String,
}
impl Default for SftpSession {
fn default() -> Self {
Self::new()
}
}
impl SftpSession {
pub fn new() -> Self {
let home_dir = std::env::var("HOME")
.unwrap_or_else(|_| "/tmp".to_string());
let username = std::env::var("USER")
.unwrap_or_else(|_| "unknown".to_string());
SftpSession {
current_dir: PathBuf::from(&home_dir),
home_dir: PathBuf::from(home_dir),
username,
}
}
pub fn for_user(username: String, home_dir: PathBuf) -> Self {
SftpSession {
current_dir: home_dir.clone(),
home_dir,
username,
}
}
pub fn current_dir(&self) -> &PathBuf {
&self.current_dir
}
pub fn change_dir(&mut self, path: PathBuf) {
self.current_dir = path;
}
pub fn home_dir(&self) -> &PathBuf {
&self.home_dir
}
pub fn username(&self) -> &str {
&self.username
}
pub fn resolve_path(&self, path: &str) -> PathBuf {
if path.starts_with('/') {
PathBuf::from(path)
} else if path == "~" || path.starts_with("~/") {
if path == "~" {
self.home_dir.clone()
} else {
self.home_dir.join(&path[2..])
}
} else if path == "." {
self.current_dir.clone()
} else if path == ".." {
self.current_dir.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| self.current_dir.clone())
} else {
self.current_dir.join(path)
}
}
}