use std::sync::OnceLock;
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::scan;
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)
}
fn powershell_parse_error(stderr: &str) -> bool {
[
"ParserError",
"Unexpected token",
"The string is missing the terminator",
]
.iter()
.any(|marker| stderr.contains(marker))
}
const MANGLED_SCRIPT_HINT: &str = "hint: agshell is bash, so it expanded the `$…` inside that \
double-quoted -Command argument before pwsh saw the script (`$_` is bash's *last argument of \
the previous command*, `$env:X` becomes empty). Single-quote the whole argument and use \
PowerShell double quotes inside: pwsh -NoProfile -Command 'Get-Process | Where-Object { \
$_.Name -eq \"x\" }' — or pass the script as base64 with -EncodedCommand.\n";
impl Report {
pub fn with_hints(&mut self) {
for command in &mut self.commands {
if command.status == 127 {
if let Some(name) = missing_program(&command.stderr) {
if looks_like_cmdlet(name) {
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} ...'` (single-quoted, so bash does not expand its `$…`), or \
use the POSIX equivalent (Get-Content=cat, Get-ChildItem=ls, \
Select-Object=head/sed, Test-Path=test -e).\n"
));
}
}
}
if command.status != 0
&& !command.timed_out
&& powershell_parse_error(&command.stderr)
&& scan::foreign_script_expansion(&command.text).is_some()
{
if !command.stderr.ends_with('\n') && !command.stderr.is_empty() {
command.stderr.push('\n');
}
command.stderr.push_str(MANGLED_SCRIPT_HINT);
}
}
}
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
}
#[cfg(test)]
mod tests {
use super::*;
fn failed_command(text: &str, stderr: &str) -> Report {
let mut report = Report::parse_error(String::new(), 0);
let mut record = CommandRecord::simple(0, text.to_string(), String::new(), 1, 1);
record.stderr = stderr.to_string();
report.commands.push(record);
report
}
const PARSE_ERROR: &str = "ParserError: \nLine |\n 1 | . | Select-Object @{e={\
[math]::Round(agshell. .\n | ~\n | Missing ')' in method call.";
#[test]
fn explains_a_script_bash_expanded() {
let mut report = failed_command(
r#"pwsh -NoProfile -Command "Get-X | Select-Object @{e={$_.Name}}""#,
PARSE_ERROR,
);
report.with_hints();
let stderr = &report.commands[0].stderr;
assert!(stderr.contains("hint:"), "{stderr}");
assert!(stderr.contains("Single-quote"), "{stderr}");
assert!(stderr.contains("EncodedCommand"), "{stderr}");
}
#[test]
fn leaves_a_genuine_powershell_error_alone() {
let mut report = failed_command(r#"pwsh -Command 'Get-X $_.Name'"#, PARSE_ERROR);
report.with_hints();
assert!(!report.commands[0].stderr.contains("hint:"), "{:?}", report.commands[0]);
}
#[test]
fn a_mangled_script_outranks_nothing_else() {
let mut report = failed_command(
r#"pwsh -Command "echo $x""#,
"ParserError: The string is missing the terminator: \".",
);
report.with_hints();
assert!(report.commands[0].stderr.ends_with('\n'), "hint ends the block");
assert!(report.commands[0].stderr.contains("hint:"), "{:?}", report.commands[0]);
}
}