use std::sync::OnceLock;
use regex::Regex;
use serde::{Deserialize, Serialize};
pub const SKIPPED: i32 = -1;
pub const STDERR_CAP: usize = 2048;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandRecord {
pub i: usize,
pub text: String,
#[serde(skip_serializing_if = "String::is_empty", default)]
pub bin: String,
pub status: i32,
#[serde(skip_serializing_if = "is_false", default)]
pub skipped: bool,
#[serde(skip_serializing_if = "is_false", default)]
pub timed_out: bool,
pub ms: i64,
#[serde(skip_serializing_if = "String::is_empty", default)]
pub stderr: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub pipeline: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub stage: Option<usize>,
#[serde(skip_serializing_if = "is_false", default)]
pub delegated: bool,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub inside: Option<usize>,
#[serde(skip_serializing_if = "is_false", default)]
pub inferred: bool,
#[serde(skip)]
pub handled: bool,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub substitution_of: Option<usize>,
}
impl CommandRecord {
pub fn simple(i: usize, text: String, bin: String, status: i32, ms: i64) -> Self {
Self {
i,
text,
bin,
status,
skipped: false,
timed_out: false,
ms,
stderr: String::new(),
pipeline: None,
stage: None,
delegated: false,
handled: false,
substitution_of: None,
inside: None,
inferred: false,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Report {
pub class: String,
pub exit: i32,
pub duration_ms: i64,
pub commands: Vec<CommandRecord>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub hidden_failures: Vec<usize>,
pub stdout: String,
pub stdout_bytes: usize,
#[serde(skip_serializing_if = "is_false", default)]
pub stdout_truncated: bool,
#[serde(skip_serializing_if = "is_false", default)]
pub opaque_substitution: bool,
#[serde(skip_serializing_if = "is_false", default)]
pub aborted: bool,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub stopped_at: Option<usize>,
#[serde(skip_serializing_if = "is_zero", default)]
pub inner_omitted: usize,
#[serde(skip_serializing_if = "String::is_empty", default)]
pub error: String,
}
const POWERSHELL_VERBS: &[&str] = &[
"Add", "Clear", "Compare", "Complete", "Convert", "Copy", "Disable", "Enable", "Enter",
"Export", "Find", "Format", "Get", "Group", "Import", "Invoke", "Join", "Measure", "Move",
"New", "Out", "Pop", "Push", "Read", "Receive", "Remove", "Rename", "Resolve", "Restart",
"Restore", "Resume", "Save", "Select", "Send", "Set", "Show", "Sort", "Split", "Start",
"Step", "Stop", "Submit", "Suspend", "Switch", "Tee", "Test", "Trace", "Unblock", "Undo",
"Uninstall", "Unprotect", "Unregister", "Update", "Use", "Wait", "Where", "Write",
];
fn missing_program(stderr: &str) -> Option<&str> {
let marker = "command not found: ";
let rest = &stderr[stderr.find(marker)? + marker.len()..];
let end = rest
.find(|c: char| c.is_whitespace())
.unwrap_or(rest.len());
(end > 0).then(|| &rest[..end])
}
fn looks_like_cmdlet(name: &str) -> bool {
let Some((verb, _)) = name.split_once('-') else {
return false;
};
POWERSHELL_VERBS.contains(&verb)
}
impl Report {
pub fn with_hints(&mut self) {
for command in &mut self.commands {
if command.status != 127 {
continue;
}
let Some(name) = missing_program(&command.stderr) else {
continue;
};
if !looks_like_cmdlet(name) {
continue;
}
command.stderr.push_str(&format!(
"hint: `{name}` is a PowerShell cmdlet, not a bash command. This shell is agshell \
(bash-compatible): run it as `pwsh -NoProfile -Command \"{name} ...\"`, or use the \
POSIX equivalent (Get-Content=cat, Get-ChildItem=ls, Select-Object=head/sed, \
Test-Path=test -e).\n"
));
}
}
pub fn parse_error(message: String, duration_ms: i64) -> Self {
Self {
class: "parse_error".to_string(),
exit: 2,
duration_ms,
commands: Vec::new(),
hidden_failures: Vec::new(),
stdout: String::new(),
stdout_bytes: 0,
stdout_truncated: false,
opaque_substitution: false,
aborted: false,
stopped_at: None,
inner_omitted: 0,
error: message,
}
}
}
pub fn classify(cmds: &[CommandRecord], exit: i32) -> String {
let timed_out = cmds.iter().any(|c| c.timed_out && !c.skipped);
let mut any_failed = false;
let mut stage_failed = false;
let mut substitution_failed = false;
for c in cmds.iter().filter(|c| !c.skipped && !c.handled) {
if c.status == 0 && !c.timed_out {
continue;
}
any_failed = true;
if c.substitution_of.is_some() {
substitution_failed = true;
}
if let (Some(pid), Some(stage)) = (c.pipeline, c.stage) {
let last = cmds
.iter()
.filter(|o| o.pipeline == Some(pid))
.map(|o| o.stage.unwrap_or(0))
.max()
.unwrap_or(0);
if stage < last {
stage_failed = true;
}
}
}
if timed_out {
"timeout".to_string()
} else if exit != 0 {
"failed".to_string()
} else if stage_failed {
"stage_failed".to_string()
} else if substitution_failed {
"substitution_failed".to_string()
} else if any_failed {
"chain_partial".to_string()
} else {
"ok".to_string()
}
}
pub fn hidden(cmds: &[CommandRecord], exit: i32) -> Vec<usize> {
if exit != 0 {
return Vec::new();
}
let last_run = cmds.iter().filter(|c| !c.skipped).map(|c| c.i).max();
cmds.iter()
.filter(|c| {
!c.skipped && !c.handled && (c.status != 0 || c.timed_out) && Some(c.i) != last_run
})
.map(|c| c.i)
.collect()
}
pub fn bin_of(text: &str) -> String {
let mut t = text.trim();
while let Some(i) = t.find([' ', '\t']) {
if i == 0 {
t = t.trim_start();
if t.is_empty() {
break;
}
continue;
}
if !t[..i].contains('=') {
break;
}
t = t[i..].trim_start();
}
let head = t.split([' ', '\t', '\n']).next().unwrap_or("");
if head.contains('=') {
String::new()
} else {
head.to_string()
}
}
pub fn looks_noisy(stdout: &str) -> bool {
static ERROR_LINE: OnceLock<Regex> = OnceLock::new();
let re = ERROR_LINE.get_or_init(|| {
Regex::new(
r"(?mi)^.*(?:\berror\s*:|\bERROR\b|Traceback \(most recent call last\)|\bpanic:|\bCannot (?:find|open|access|bind|start)|\bcommand not found\b|\bNo such file\b|\bFAILED\b|\bnot permitted\b|\bpermission denied\b|\bfatal:)",
)
.expect("static regex")
});
re.is_match(stdout)
}
fn is_zero(v: &usize) -> bool {
*v == 0
}
fn is_false(v: &bool) -> bool {
!*v
}