use std::path::PathBuf;
use super::TOOLS_DIR;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::local_settings::LocalSettings;
use crate::paths::SurjectionHome;
const DIR: &str = "snyk-agent-scan";
pub const SETTINGS_KEY: &str = "snyk_agent_scan";
pub fn install_dir(home: &SurjectionHome) -> PathBuf {
home.path.join(TOOLS_DIR).join(DIR)
}
pub fn present(fs: &dyn Fs, home: &SurjectionHome) -> Result<bool, CoreError> {
let settings = LocalSettings::load(fs, &home.state_dir())?;
Ok(settings.extra.contains_key(SETTINGS_KEY) || install_dir(home).exists())
}
pub fn remove(fs: &dyn Fs, home: &SurjectionHome) -> Result<bool, CoreError> {
let dir = install_dir(home);
let folder = dir.exists();
if folder {
std::fs::remove_dir_all(&dir).map_err(|err| {
CoreError::new(ErrorCode::IoError, format!("cannot remove folder: {err}"))
.with_path(&dir)
})?;
}
let state = home.state_dir();
let mut settings = LocalSettings::load(fs, &state)?;
let table = settings.extra.remove(SETTINGS_KEY).is_some();
if table {
settings.save(fs, &state)?;
}
Ok(folder || table)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fs::RealFs;
use crate::paths::HomeSource;
#[test]
fn removes_the_folder_and_only_its_settings_table() {
let temp = surjection_testkit::TempHome::new();
let home = SurjectionHome {
path: temp.root().join("lh"),
source: HomeSource::Flag,
sync_root: None,
};
assert!(!present(&RealFs, &home).unwrap());
assert!(!remove(&RealFs, &home).unwrap());
let version = install_dir(&home).join("0.7.1");
std::fs::create_dir_all(&version).unwrap();
std::fs::write(version.join("installed.json"), "{}").unwrap();
std::fs::create_dir_all(home.state_dir()).unwrap();
std::fs::write(
home.state_dir()
.join(crate::local_settings::LOCAL_SETTINGS_FILE),
"schema = 1\nonline_catalogs = true\n\n[snyk_agent_scan]\nenabled = true\ntoken = \
\"keyring://surjection/snyk\"\n",
)
.unwrap();
assert!(present(&RealFs, &home).unwrap());
assert!(remove(&RealFs, &home).unwrap());
assert!(!install_dir(&home).exists());
assert!(home.path.join(TOOLS_DIR).exists(), "other tools stay");
let settings = LocalSettings::load(&RealFs, &home.state_dir()).unwrap();
assert!(!settings.extra.contains_key(SETTINGS_KEY));
assert_eq!(settings.online_catalogs, Some(true));
assert!(!present(&RealFs, &home).unwrap());
let mut settings = settings;
settings.extra.insert(
SETTINGS_KEY.to_owned(),
toml::Value::Table(toml::Table::new()),
);
settings.save(&RealFs, &home.state_dir()).unwrap();
assert!(present(&RealFs, &home).unwrap());
assert!(remove(&RealFs, &home).unwrap());
assert!(!present(&RealFs, &home).unwrap());
}
}