use std::fs;
use std::io::Write;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::config::constants::{APP_NAME, CONFIG_FILE_NAME};
use crate::config::path_source::{PathSource, resolve_config_dir_with_source};
use crate::error::{AppError, AppResult, ErrorDetail, IoOp, io_at};
use crate::platform::{restrict_private_dir, restrict_private_file};
use super::template::default_config_toml;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ConfigInitResult {
pub path: String,
pub config_dir: String,
pub target_source: PathSource,
pub created: bool,
pub overwritten: bool,
}
pub fn init_config_toml(
config_dir_override: Option<PathBuf>,
force: bool,
) -> AppResult<ConfigInitResult> {
let (dir, source) = resolve_config_dir_with_source(config_dir_override);
let dir = dir.ok_or_else(|| AppError::of(ErrorDetail::ConfigDirUnresolved))?;
fs::create_dir_all(&dir).map_err(io_at(IoOp::CreateDir, &dir))?;
restrict_private_dir(&dir);
let path = dir.join(CONFIG_FILE_NAME);
let existed = path.is_file();
if existed && !force {
return Err(AppError::of(ErrorDetail::ConfigAlreadyExists {
path: path.display().to_string(),
}));
}
let tmp = dir.join(format!("{CONFIG_FILE_NAME}.{APP_NAME}.tmp"));
let template = default_config_toml();
{
let mut f = fs::File::create(&tmp).map_err(io_at(IoOp::CreateTemp, &tmp))?;
f.write_all(template.as_bytes())
.map_err(io_at(IoOp::Write, &tmp))?;
f.sync_all().map_err(io_at(IoOp::Sync, &tmp))?;
}
restrict_private_file(&tmp);
fs::rename(&tmp, &path).map_err(|e| {
let _ = fs::remove_file(&tmp);
io_at(IoOp::Install, &path)(e)
})?;
restrict_private_file(&path);
Ok(ConfigInitResult {
path: path.display().to_string(),
config_dir: dir.display().to_string(),
target_source: source,
created: true,
overwritten: existed,
})
}