use serde_json::Value;
pub const NON_ERROR_EXIT_1: &[(&str, &str)] = &[
("grep", "No matches found"),
("egrep", "No matches found"),
("fgrep", "No matches found"),
("rg", "No matches found"),
("diff", "Files differ"),
("cmp", "Files differ"),
("test", "Condition is false"),
("[", "Condition is false"),
];
pub fn exit_note(command: &str, exit_code: Option<i32>) -> Option<&'static str> {
if exit_code != Some(1) {
return None;
}
let last = pipeline_commands(command)?.pop()?;
let program = program_of(&last)?;
let name = program.rsplit('/').next().unwrap_or(&program);
NON_ERROR_EXIT_1
.iter()
.find(|(candidate, _)| *candidate == name)
.map(|(_, note)| *note)
}
fn pipeline_commands(command: &str) -> Option<Vec<String>> {
let mut parts = Vec::new();
let mut current = String::new();
let (mut in_single, mut in_double) = (false, false);
let mut characters = command.trim().chars().peekable();
while let Some(character) = characters.next() {
if in_single {
in_single = character != '\'';
current.push(character);
continue;
}
match character {
'\\' => {
current.push(character);
current.push(characters.next()?);
}
'\'' if !in_double => {
in_single = true;
current.push(character);
}
'"' => {
in_double = !in_double;
current.push(character);
}
'`' => return None,
'$' if characters.peek() == Some(&'(') => return None,
_ if in_double => current.push(character),
'&' if current.ends_with(['>', '<']) || characters.peek() == Some(&'>') => current.push(character),
'#' if !(current.is_empty() || current.ends_with(char::is_whitespace)) => current.push(character),
';' | '&' | '\n' | '(' | ')' | '{' | '}' | '#' => return None,
'|' => {
match characters.peek() {
Some('|') => return None,
Some('&') => {
characters.next();
}
_ => {}
}
parts.push(std::mem::take(&mut current));
}
_ => current.push(character),
}
}
if in_single || in_double {
return None;
}
parts.push(current);
parts.iter().all(|part| !part.trim().is_empty()).then_some(parts)
}
fn program_of(command: &str) -> Option<String> {
let program = command.split_whitespace().find(|word| !is_assignment(word))?;
Some(program.trim_matches(|c| c == '\'' || c == '"').to_string())
}
fn is_assignment(word: &str) -> bool {
word.split_once('=').is_some_and(|(name, _)| {
!name.is_empty()
&& !name.starts_with(|c: char| c.is_ascii_digit())
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
})
}
pub fn annotate(result: &mut Value, command: &str, policy: Option<&sandbox::Policy>) {
let Some(object) = result.as_object_mut() else {
return;
};
let flag = |key: &str| object.get(key).and_then(Value::as_bool) == Some(true);
if flag("running") || flag("cancelled") || flag("timed_out") {
return;
}
if object
.get("status")
.and_then(Value::as_str)
.is_some_and(|status| status != "completed")
{
return;
}
let exit_code = object
.get("exit_code")
.and_then(Value::as_i64)
.and_then(|code| i32::try_from(code).ok());
if let Some(note) = exit_note(command, exit_code) {
object.insert("exit_note".into(), note.into());
}
let Some(policy) = policy.filter(|_| exit_code.is_some_and(|code| code != 0)) else {
return;
};
let output = ["output", "text"]
.iter()
.find_map(|key| object.get(*key).and_then(Value::as_str))
.unwrap_or_default();
if let Some(note) = sandbox::refusal::refusal_note(policy, output) {
object.insert("sandbox_note".into(), note.into());
}
}