use super::{cover, draft, survey};
use crate::judge::{Config, File, files};
use std::path::Path;
const CTRM: &str = ".ctrm";
#[derive(Debug, Clone, Copy)]
pub(crate) struct Ask {
pub print: bool,
pub keep: bool,
}
pub(crate) fn run(config: &Config, ask: Ask) -> Result<String, String> {
let print = ask.print;
let target = config.root.join(CTRM);
if !print && target.exists() {
return Err(format!(
"`{CTRM}` exists and init never overwrites it; \
`ctrm init --print` writes the draft to stdout instead"
));
}
let text = drafted(&config.root, ask.keep)?;
if print {
return Ok(text.trim_end().to_owned());
}
std::fs::write(&target, &text).map_err(|e| format!("{CTRM}: {e}"))?;
Ok(format!("wrote {CTRM}: review it, then `ctrm check`"))
}
fn drafted(root: &Path, keep: bool) -> Result<String, String> {
let mut found = survey::Survey::new(keep);
for file in files(root, &[])? {
let File { shown, text, .. } = file?;
match text {
Ok(text) => found.add(&shown, &text),
Err(_) => found.skipped = found.skipped.saturating_add(1),
}
}
Ok(draft::draft(&found, &cover::Candidates::builtin()))
}