1use serde_json::Value;
11
12pub const NON_ERROR_EXIT_1: &[(&str, &str)] = &[
14 ("grep", "No matches found"),
15 ("egrep", "No matches found"),
16 ("fgrep", "No matches found"),
17 ("rg", "No matches found"),
18 ("diff", "Files differ"),
19 ("cmp", "Files differ"),
20 ("test", "Condition is false"),
21 ("[", "Condition is false"),
22];
23
24pub fn exit_note(command: &str, exit_code: Option<i32>) -> Option<&'static str> {
28 if exit_code != Some(1) {
29 return None;
30 }
31 let last = pipeline_commands(command)?.pop()?;
32 let program = program_of(&last)?;
33 let name = program.rsplit('/').next().unwrap_or(&program);
34 NON_ERROR_EXIT_1
35 .iter()
36 .find(|(candidate, _)| *candidate == name)
37 .map(|(_, note)| *note)
38}
39
40fn pipeline_commands(command: &str) -> Option<Vec<String>> {
42 let mut parts = Vec::new();
43 let mut current = String::new();
44 let (mut in_single, mut in_double) = (false, false);
45 let mut characters = command.trim().chars().peekable();
46 while let Some(character) = characters.next() {
47 if in_single {
48 in_single = character != '\'';
49 current.push(character);
50 continue;
51 }
52 match character {
53 '\\' => {
54 current.push(character);
55 current.push(characters.next()?);
56 }
57 '\'' if !in_double => {
58 in_single = true;
59 current.push(character);
60 }
61 '"' => {
62 in_double = !in_double;
63 current.push(character);
64 }
65 '`' => return None,
67 '$' if characters.peek() == Some(&'(') => return None,
68 _ if in_double => current.push(character),
69 '&' if current.ends_with(['>', '<']) || characters.peek() == Some(&'>') => current.push(character),
71 '#' if !(current.is_empty() || current.ends_with(char::is_whitespace)) => current.push(character),
73 ';' | '&' | '\n' | '(' | ')' | '{' | '}' | '#' => return None,
74 '|' => {
75 match characters.peek() {
76 Some('|') => return None,
77 Some('&') => {
78 characters.next();
79 }
80 _ => {}
81 }
82 parts.push(std::mem::take(&mut current));
83 }
84 _ => current.push(character),
85 }
86 }
87 if in_single || in_double {
88 return None;
89 }
90 parts.push(current);
91 parts.iter().all(|part| !part.trim().is_empty()).then_some(parts)
92}
93
94fn program_of(command: &str) -> Option<String> {
97 let program = command.split_whitespace().find(|word| !is_assignment(word))?;
98 Some(program.trim_matches(|c| c == '\'' || c == '"').to_string())
99}
100
101fn is_assignment(word: &str) -> bool {
102 word.split_once('=').is_some_and(|(name, _)| {
103 !name.is_empty()
104 && !name.starts_with(|c: char| c.is_ascii_digit())
105 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
106 })
107}
108
109pub fn annotate(result: &mut Value, command: &str, policy: Option<&sandbox::Policy>) {
113 let Some(object) = result.as_object_mut() else {
114 return;
115 };
116 let flag = |key: &str| object.get(key).and_then(Value::as_bool) == Some(true);
117 if flag("running") || flag("cancelled") || flag("timed_out") {
118 return;
119 }
120 if object
121 .get("status")
122 .and_then(Value::as_str)
123 .is_some_and(|status| status != "completed")
124 {
125 return;
126 }
127 let exit_code = object
128 .get("exit_code")
129 .and_then(Value::as_i64)
130 .and_then(|code| i32::try_from(code).ok());
131 if let Some(note) = exit_note(command, exit_code) {
132 object.insert("exit_note".into(), note.into());
133 }
134 let Some(policy) = policy.filter(|_| exit_code.is_some_and(|code| code != 0)) else {
135 return;
136 };
137 let output = ["output", "text"]
138 .iter()
139 .find_map(|key| object.get(*key).and_then(Value::as_str))
140 .unwrap_or_default();
141 if let Some(note) = sandbox::refusal::refusal_note(policy, output) {
142 object.insert("sandbox_note".into(), note.into());
143 }
144}