use std::path::Path;
use super::readers::{INDEXED_FALLBACK_THEME, TRUECOLOR_FALLBACK_THEME};
pub(super) const REFERENCE_CONFIG_TOML: &str = include_str!("../../config/config.toml");
pub(super) fn ensure_default_files_in(dir: &Path, truecolor: bool) {
if let Err(e) = std::fs::create_dir_all(dir) {
tracing::warn!(error = %e, dir = %dir.display(), "failed to create config dir");
return;
}
let themes_dir = dir.join("themes");
if let Err(e) = std::fs::create_dir_all(&themes_dir) {
tracing::warn!(error = %e, dir = %themes_dir.display(), "failed to create themes dir");
return;
}
let export_dir = dir.join("export");
if let Err(e) = std::fs::create_dir_all(&export_dir) {
tracing::warn!(error = %e, dir = %export_dir.display(), "failed to create export dir");
return;
}
write_if_absent(&dir.join("config.toml"), &seed_config_toml(truecolor));
write_if_absent(
&dir.join("keybindings.toml"),
include_str!("../../config/keybindings.toml"),
);
write_if_absent(
&export_dir.join("default.css.example"),
include_str!("../../config/export/default.css"),
);
}
fn seed_config_toml(truecolor: bool) -> String {
if truecolor {
return REFERENCE_CONFIG_TOML.to_owned();
}
REFERENCE_CONFIG_TOML.replacen(
&format!("theme = \"{TRUECOLOR_FALLBACK_THEME}\""),
&format!("theme = \"{INDEXED_FALLBACK_THEME}\""),
1,
)
}
fn write_if_absent(path: &Path, contents: &str) {
if path.exists() {
return;
}
if let Err(e) = std::fs::write(path, contents) {
tracing::warn!(error = %e, path = %path.display(), "failed to write default file");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn seed_keeps_reference_verbatim_on_truecolor() {
assert_eq!(seed_config_toml(true), REFERENCE_CONFIG_TOML);
}
#[test]
fn seed_swaps_theme_for_indexed_terminals() {
assert!(REFERENCE_CONFIG_TOML.contains(&format!("theme = \"{TRUECOLOR_FALLBACK_THEME}\"")));
let seeded = seed_config_toml(false);
assert!(seeded.contains(&format!("theme = \"{INDEXED_FALLBACK_THEME}\"")));
assert!(!seeded.contains(&format!("theme = \"{TRUECOLOR_FALLBACK_THEME}\"")));
}
}