use std::io;
use std::path::Path;
use subspace_core::state::State;
use subspace_product::{ProductContext, ValidatedProduct};
use super::THEME_PREF;
use crate::product::ProductFiles;
pub fn record_new_install_theme(context: &ProductContext, theme: &str) -> Result<bool, String> {
let files = ProductFiles::for_context(context);
let new = is_new_install(&files).map_err(|error| file_error(&files, &error))?;
new.then(|| record(&context.product, &files, theme))
.transpose()
.map(|recorded| recorded.is_some())
}
fn record(product: &ValidatedProduct, files: &ProductFiles, theme: &str) -> Result<(), String> {
super::loader::require_catalogue_variant(product, "new install theme", theme)?;
save_theme(&files.state, theme).map_err(|error| file_error(files, &error))
}
fn save_theme(file: &Path, theme: &str) -> io::Result<()> {
let mut state = State::default();
state.set(THEME_PREF, theme);
state.save(file)
}
fn file_error(files: &ProductFiles, error: &io::Error) -> String {
format!(
"could not record the new install's theme in {}: {error}",
files.state.display()
)
}
fn is_new_install(files: &ProductFiles) -> io::Result<bool> {
Ok(absent(&files.config)? && absent(&files.state)?)
}
fn absent(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(_) => Ok(false),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(true),
Err(error) => Err(error),
}
}