use std::{
fs::{create_dir_all, File},
path::{Path, PathBuf},
process::Command,
};
use crate::cli::Cli;
pub struct Workspace {
pub root: PathBuf,
}
impl Workspace {
pub fn new(session: &str, cli: &Cli) -> Self {
let root = match std::env::var("RINEX_WORKSPACE") {
Ok(path) => Path::new(&path).join(session).to_path_buf(),
_ => match cli.matches.get_one::<PathBuf>("workspace") {
Some(path) => Path::new(path).join(session).to_path_buf(),
None => Path::new("WORKSPACE").join(session).to_path_buf(),
},
};
create_dir_all(&root).unwrap_or_else(|e| {
panic!(
"failed to create session workspace \"{}\": {}",
root.display(),
e
)
});
info!("session workspace is \"{}\"", root.to_string_lossy());
Self {
root: root.to_path_buf(),
}
}
pub fn create_subdir(&self, dir: &str) {
create_dir_all(self.root.join(dir)).unwrap_or_else(|e| {
panic!("failed to create directory {} within workspace: {}", dir, e)
});
}
pub fn create_file(&self, filename: &str) -> File {
let fullpath = self.root.join(filename).to_string_lossy().to_string();
let fd = File::create(&fullpath)
.unwrap_or_else(|e| panic!("failed to create new file {}: {}", filename, e));
info!("{} has been generated", fullpath);
fd
}
#[cfg(target_os = "linux")]
pub fn open_with_web_browser(&self) {
let fullpath = self.root.to_string_lossy().to_string();
let web_browsers = vec!["firefox", "chromium"];
for browser in web_browsers {
let child = Command::new(browser).arg(fullpath.clone()).spawn();
if child.is_ok() {
return;
}
}
}
#[cfg(target_os = "macos")]
pub fn open_with_web_browser(&self) {
let fullpath = self.root.to_string_lossy().to_string();
Command::new("open")
.args(&[fullpath])
.output()
.expect("open() failed, can't open HTML content automatically");
}
#[cfg(target_os = "windows")]
pub fn open_with_web_browser(&self) {
let fullpath = self.root.to_string_lossy().to_string();
Command::new("cmd")
.arg("/C")
.arg(format!(r#"start {}"#, fullpath))
.output()
.expect("failed to open generated HTML content");
}
}