use haest::mods::ApprovalRequest;
use crate::render::inert;
const LONG: usize = 500;
pub(super) fn question(req: &ApprovalRequest) -> String {
let asked = format!(
"Allow {}? {}",
shown(&req.tool_name),
shown(&req.description)
);
let answers = "[y]es / [a]lways / [N]o: ";
let preview = req.input_preview.trim();
if preview.is_empty() || preview == req.description.trim() {
return format!("{asked}\n{answers}");
}
let command = visible(&squeezed(&inert(preview)));
let (lines, chars) = (command.lines().count(), command.chars().count());
let above = match (lines, chars > LONG) {
(1, false) => String::new(),
(1, true) => format!(" (1 line, {chars} characters above)"),
(n, false) => format!(" ({n} lines above)"),
(n, true) => format!(" ({n} lines, {chars} characters above)"),
};
let command = command.replace('\n', "\n ");
format!(" {command}\n{asked}{above}\n{answers}")
}
fn shown(text: &str) -> String {
visible(&inert(text)).replace('\n', "\n ")
}
const TAB: &str = "⟨tab⟩";
fn visible(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'\t' => out.push_str(TAB),
c if (c.is_whitespace() && !c.is_ascii()) || blank(c) => {
out.extend(c.escape_unicode());
}
c => out.push(c),
}
}
out
}
fn blank(c: char) -> bool {
matches!(c,
'\u{00ad}' | '\u{034f}' | '\u{115f}' | '\u{1160}' | '\u{17b4}' | '\u{17b5}'
| '\u{180b}'..='\u{180f}' | '\u{206a}'..='\u{206f}' | '\u{2800}' | '\u{3164}'
| '\u{fe00}'..='\u{fe0f}' | '\u{ffa0}' | '\u{fff0}'..='\u{fff8}'
| '\u{1bca0}'..='\u{1bca3}' | '\u{1d159}' | '\u{1d173}'..='\u{1d17a}'
| '\u{e0000}'..='\u{e0fff}')
}
fn pads(c: char) -> bool {
c == ' ' || c == '\t'
}
fn squeezed(text: &str) -> String {
let mut out: Vec<String> = Vec::new();
let mut blank: Vec<&str> = Vec::new();
for line in text.split('\n') {
if line.chars().all(pads) {
blank.push(line);
continue;
}
blank_lines(&mut out, &mut blank);
out.push(counted_padding(line));
}
blank_lines(&mut out, &mut blank);
out.join("\n")
}
fn blank_lines(out: &mut Vec<String>, run: &mut Vec<&str>) {
if run.len() > 2 {
out.push(format!("⟨{} blank lines⟩", run.len()));
} else {
out.extend(run.iter().map(|l| counted_padding(l)));
}
run.clear();
}
const INDENT: usize = 40;
fn counted_padding(line: &str) -> String {
let body = line.trim_start_matches(pads);
let indent = &line[..line.len() - body.len()];
let tab = TAB.chars().count();
let width: usize = indent
.chars()
.map(|c| if c == '\t' { tab } else { 1 })
.sum();
let mut out = if width <= INDENT {
indent.to_owned()
} else {
counted(indent)
};
let mut run = String::new();
for c in body.chars() {
if pads(c) {
run.push(c);
} else {
out.push_str(&counted(&run));
run.clear();
out.push(c);
}
}
out + &counted(&run)
}
fn counted(run: &str) -> String {
let n = run.chars().count();
if n <= 8 {
run.to_owned()
} else if !run.contains('\t') {
format!("⟨{n} spaces⟩")
} else if !run.contains(' ') {
format!("⟨{n} tabs⟩")
} else {
format!("⟨{n} spaces and tabs⟩")
}
}
#[cfg(test)]
mod tests;