1use std::collections::{BTreeMap, BTreeSet};
17use std::sync::OnceLock;
18
19use sha2::{Digest, Sha256};
20
21use crate::cst::{self, Cmd, Script, SimpleCmd, Word, WordPart};
22use crate::registry;
23
24const DEFAULT_LEVEL: &str = "SafeWrite";
28
29#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct GeneratedEntry {
38 pub name: String,
39 pub standalone: Vec<String>,
42 pub max_positional: usize,
45 pub level: String,
46 pub subs: Vec<GeneratedSub>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct GeneratedSub {
53 pub name: String,
54 pub standalone: Vec<String>,
55 pub max_positional: usize,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Outcome {
61 AlreadyAllowed,
63 Unparseable,
65 RecognizedButDenied { names: Vec<String> },
68 Generated { entries: Vec<GeneratedEntry>, also_recognized: Vec<String> },
71}
72
73pub fn analyze(command: &str) -> Outcome {
75 if cst::command_verdict(command).is_allowed() {
76 return Outcome::AlreadyAllowed;
77 }
78 let Some(script) = cst::parse(command) else {
79 return Outcome::Unparseable;
80 };
81
82 let mut simples: Vec<&SimpleCmd> = Vec::new();
83 collect_script(&script, &mut simples);
84
85 let mut unknown: BTreeMap<String, Vec<Observed>> = BTreeMap::new();
86 let mut recognized: BTreeSet<String> = BTreeSet::new();
87 for sc in simples {
88 let Some(name) = command_basename(sc) else {
89 continue;
90 };
91 if is_known(&name) {
92 recognized.insert(name);
93 continue;
94 }
95 unknown.entry(name).or_default().push(observed_shape(sc));
96 }
97
98 if unknown.is_empty() {
99 return Outcome::RecognizedButDenied { names: recognized.into_iter().collect() };
100 }
101 let entries = unknown.into_iter().map(|(name, uses)| entry_for(name, &uses)).collect();
102 Outcome::Generated { entries, also_recognized: recognized.into_iter().collect() }
103}
104
105struct Observed {
107 flags: Vec<String>,
108 positionals: Vec<String>,
109 leads_with_word: bool,
111}
112
113fn entry_for(name: String, uses: &[Observed]) -> GeneratedEntry {
114 let level = DEFAULT_LEVEL.to_string();
115 let every_use_starts_with_a_word = uses.iter().all(|u| u.leads_with_word);
116 if !every_use_starts_with_a_word {
117 let standalone: BTreeSet<String> = uses.iter().flat_map(|u| u.flags.iter().cloned()).collect();
118 let max_positional = uses.iter().map(|u| u.positionals.len()).max().unwrap_or(0);
119 return GeneratedEntry { name, standalone: standalone.into_iter().collect(), max_positional, level, subs: Vec::new() };
120 }
121 let mut subs: BTreeMap<String, (BTreeSet<String>, usize)> = BTreeMap::new();
122 for u in uses {
123 let Some((sub, rest)) = u.positionals.split_first() else { continue };
124 let shape = subs.entry(sub.clone()).or_default();
125 shape.0.extend(u.flags.iter().cloned());
126 shape.1 = shape.1.max(rest.len());
127 }
128 let subs = subs
129 .into_iter()
130 .map(|(name, (flags, max_positional))| GeneratedSub { name, standalone: flags.into_iter().collect(), max_positional })
131 .collect();
132 GeneratedEntry { name, standalone: Vec::new(), max_positional: 0, level, subs }
133}
134
135pub(crate) fn is_sub_word(word: &str) -> bool {
138 word.len() <= 40
139 && word.starts_with(|c: char| c.is_ascii_lowercase())
140 && word.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '_' | ':'))
141}
142
143fn command_basename(sc: &SimpleCmd) -> Option<String> {
146 let raw = sc.words.first()?.eval();
147 if raw.is_empty() {
148 return None;
149 }
150 Some(crate::parse::Token::from_raw(raw).command_name().to_string())
151}
152
153fn observed_shape(sc: &SimpleCmd) -> Observed {
157 let mut flags = Vec::new();
158 let mut positionals = Vec::new();
159 for word in sc.words.iter().skip(1) {
160 let s = word.eval();
161 if s.starts_with('-') && s != "-" {
162 flags.push(s);
163 } else {
164 positionals.push(s);
165 }
166 }
167 let leads_with_word = sc.words.get(1).is_some_and(|w| is_sub_word(&w.eval()));
168 Observed { flags, positionals, leads_with_word }
169}
170
171fn collect_script<'a>(script: &'a Script, out: &mut Vec<&'a SimpleCmd>) {
172 for stmt in &script.0 {
173 for cmd in &stmt.pipeline.commands {
174 collect_cmd(cmd, out);
175 }
176 }
177}
178
179fn collect_cmd<'a>(cmd: &'a Cmd, out: &mut Vec<&'a SimpleCmd>) {
180 match cmd {
181 Cmd::Simple(sc) => {
182 out.push(sc);
183 for word in &sc.words {
184 collect_word(word, out);
185 }
186 }
187 Cmd::Subshell { body, .. } | Cmd::BraceGroup { body, .. } => collect_script(body, out),
188 Cmd::For { items, body, .. } => {
189 for word in items {
190 collect_word(word, out);
191 }
192 collect_script(body, out);
193 }
194 Cmd::While { cond, body, .. } | Cmd::Until { cond, body, .. } => {
195 collect_script(cond, out);
196 collect_script(body, out);
197 }
198 Cmd::If { branches, else_body, .. } => {
199 for branch in branches {
200 collect_script(&branch.cond, out);
201 collect_script(&branch.body, out);
202 }
203 if let Some(body) = else_body {
204 collect_script(body, out);
205 }
206 }
207 Cmd::DoubleBracket { words, .. } => {
208 for word in words {
209 collect_word(word, out);
210 }
211 }
212 Cmd::Case { subject, arms, .. } => {
213 collect_word(subject, out);
214 for arm in arms {
215 collect_script(&arm.body, out);
216 }
217 }
218 Cmd::FunctionDef { body, .. } => collect_script(body, out),
219 }
220}
221
222fn collect_word<'a>(word: &'a Word, out: &mut Vec<&'a SimpleCmd>) {
228 for part in &word.0 {
229 match part {
230 WordPart::CmdSub(s) | WordPart::ProcSub(s) => collect_script(s, out),
231 WordPart::DQuote(w) => collect_word(w, out),
232 _ => {}
233 }
234 }
235}
236
237pub(crate) fn is_known(name: &str) -> bool {
241 known_names().contains(registry::canonical_name(name)) || crate::handlers::is_built_in(name)
242}
243
244fn known_names() -> &'static BTreeSet<String> {
245 static KNOWN: OnceLock<BTreeSet<String>> = OnceLock::new();
246 KNOWN.get_or_init(|| {
247 let mut set: BTreeSet<String> = crate::docs::all_command_docs().into_iter().map(|d| d.name).collect();
248 for name in registry::toml_command_names() {
249 set.insert(name.to_string());
250 }
251 set
252 })
253}
254
255pub fn render_toml(entries: &[GeneratedEntry]) -> String {
258 let mut out = String::new();
259 for (i, entry) in entries.iter().enumerate() {
260 if i > 0 {
261 out.push('\n');
262 }
263 out.push_str("[[command]]\n");
264 out.push_str(&format!("name = {}\n", toml_str(&entry.name)));
265 if entry.subs.is_empty() {
266 push_shape(&mut out, &entry.standalone, entry.max_positional, &entry.level);
267 }
268 for sub in &entry.subs {
269 out.push_str("\n[[command.sub]]\n");
270 out.push_str(&format!("name = {}\n", toml_str(&sub.name)));
271 push_shape(&mut out, &sub.standalone, sub.max_positional, &entry.level);
272 }
273 }
274 out
275}
276
277fn push_shape(out: &mut String, standalone: &[String], max_positional: usize, level: &str) {
278 if !standalone.is_empty() {
279 let items: Vec<String> = standalone.iter().map(|f| toml_str(f)).collect();
280 out.push_str(&format!("standalone = [{}]\n", items.join(", ")));
281 }
282 out.push_str(&format!("max_positional = {max_positional}\n"));
283 out.push_str(&format!("level = {}\n", toml_str(level)));
284}
285
286pub(crate) fn toml_str(s: &str) -> String {
289 let mut out = String::from("\"");
290 for c in s.chars() {
291 match c {
292 '"' => out.push_str("\\\""),
293 '\\' => out.push_str("\\\\"),
294 '\n' => out.push_str("\\n"),
295 '\r' => out.push_str("\\r"),
296 '\t' => out.push_str("\\t"),
297 c if (c as u32) < 0x20 || c == '\u{7f}' => {
298 out.push_str(&format!("\\u{:04X}", c as u32));
299 }
300 c => out.push(c),
301 }
302 }
303 out.push('"');
304 out
305}
306
307pub fn config_hash(bytes: &[u8]) -> String {
310 Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
311}
312
313pub fn merged_content(existing: &str, entries: &[GeneratedEntry]) -> String {
316 let block = render_toml(entries);
317 if existing.trim().is_empty() {
318 return block;
319 }
320 let mut content = existing.to_string();
321 if !content.ends_with('\n') {
322 content.push('\n');
323 }
324 content.push('\n');
325 content.push_str(&block);
326 content
327}
328
329pub fn pin_block(canonical_dir: &str, hash: &str) -> String {
331 format!("[[trusted]]\npath = {}\nsha256 = {}\n", toml_str(canonical_dir), toml_str(hash),)
332}
333
334#[cfg(test)]
335mod tests;