use super::cover::{Candidates, Grant};
use super::survey::{Kind, Survey};
use crate::render::codepoint;
const HEADER: &str = "\
# Drafted by `ctrm init` from the tracked files. Review it before you
# commit it: every grant is a decision. A pattern with no `/` matches a
# file name at any depth; the last matching line wins; a path no line
# matches gets `ascii`. `ctrm explain <path>` says which line decides.";
pub(super) fn draft(survey: &Survey, candidates: &Candidates) -> String {
let mut out = vec![String::from(HEADER), summary(survey)];
for (pattern, kind) in &survey.kinds {
if !is_ascii(kind) {
out.push(section(pattern, kind, candidates));
}
}
let mut text = out.join("\n\n");
text.push('\n');
text
}
fn is_ascii(kind: &Kind) -> bool {
kind.needed.is_empty()
&& kind.fixable().is_empty()
&& kind.hazards.is_empty()
&& !kind.sequences
}
fn summary(survey: &Survey) -> String {
let files: usize = survey.kinds.values().map(|kind| kind.files).sum();
let plain: Vec<String> = survey
.kinds
.iter()
.filter(|(_, kind)| is_ascii(kind))
.map(|(pattern, kind)| format!("{pattern} ({})", kind.files))
.collect();
let mut lines = vec![format!(
"# {files} text files read, {} skipped (binary or not UTF-8).",
survey.skipped
)];
lines.extend(wrapped("Pure ASCII, no line needed:", &plain));
lines.join("\n")
}
fn section(pattern: &str, kind: &Kind, candidates: &Candidates) -> String {
let mut lines = vec![format!("# {pattern}, files: {}.", kind.files)];
let grant =
(!kind.needed.is_empty()).then(|| candidates.cover(&kind.needed));
let rule = if let Some(grant) = &grant {
Some(granted(pattern, grant, &mut lines))
} else {
lines.push(String::from("# Needs no grant."));
None
};
let allowed = |c| grant.as_ref().is_some_and(|g| candidates.allows(g, c));
lines.extend(notes(kind, &allowed));
lines.extend(rule);
lines.join("\n")
}
fn granted(pattern: &str, grant: &Grant, lines: &mut Vec<String>) -> String {
match grant {
Grant::Sets(sets) => {
for (name, covers) in sets {
lines.extend(wrapped(&format!("{name} for"), &points(covers)));
}
let names: Vec<&str> =
sets.iter().map(|(n, _)| n.as_str()).collect();
format!("{pattern} ascii+{}", names.join("+"))
}
Grant::Any(left) => {
lines.extend(wrapped("No preset or locale covers", &points(left)));
lines.push(String::from(ANY));
format!("{pattern} any")
}
}
}
const ANY: &str = "# so `any`, which grants everything (hazards still fire).\n\
# A set of your own in `.ctrm-sets` is tighter.";
fn notes(kind: &Kind, allowed: &dyn Fn(char) -> bool) -> Vec<String> {
let mut lines = rewritten(kind, allowed);
if kind.sequences {
lines.push(String::from(
"# Emoji sequences: `ctrm fix` compresses them to one emoji.",
));
}
let hazards: Vec<String> = kind
.hazards
.iter()
.map(|(c, (lint, path))| format!("{} {lint} in {path}", codepoint(*c)))
.collect();
lines.extend(wrapped("Hazards, never granted -- fix these:", &hazards));
lines
}
fn rewritten(kind: &Kind, allowed: &dyn Fn(char) -> bool) -> Vec<String> {
let (kept, fixed): (Vec<char>, Vec<char>) =
kind.fixable().into_iter().partition(|c| allowed(*c));
let mut lines = wrapped(&until_fix(kind.unfixed(allowed)), &points(&fixed));
let lead = "The builtin map rewrites these, but this line grants them:";
lines.extend(wrapped(lead, &points(&kept)));
lines
}
fn until_fix((findings, files): (usize, usize)) -> String {
format!(
"`ctrm fix` rewrites these; until it runs, check reports \
{} in {} (`init --print --keep-fixable` drafts them granted):",
counted(findings, "finding"),
counted(files, "file")
)
}
fn counted(n: usize, noun: &str) -> String {
if n == 1 {
format!("1 {noun}")
} else {
format!("{n} {noun}s")
}
}
fn points(chars: &[char]) -> Vec<String> {
chars.iter().map(|c| codepoint(*c)).collect()
}
fn wrapped(lead: &str, items: &[String]) -> Vec<String> {
if items.is_empty() {
return Vec::new();
}
let mut words = lead.split(' ');
let mut lines = vec![format!("# {}", words.next().unwrap_or_default())];
for item in words.chain(items.iter().map(String::as_str)) {
appended(&mut lines, item);
}
lines
}
fn appended(lines: &mut Vec<String>, item: &str) {
match lines.last_mut() {
Some(line) if line.len().saturating_add(item.len()) < 72 => {
line.push(' ');
line.push_str(item);
}
_ => lines.push(format!("# {item}")),
}
}