fix(cli): color unpack and inspect terminal output

Share a scoped terminal palette across unpack progress, summaries and rich research reports. Add auto, always and never color modes with stream-specific terminal checks, NO_COLOR handling and Windows virtual-terminal support.

Keep report data, redirected auto output, JSON and saved run logs plain. Test color roles, quiet behavior, policy restoration and escape-free artifacts.
This commit is contained in:
Momoko-Ayase committed 2026-11-06 03:16:18 +08:00
1 parent 1ee4344c1e
commit 7fde1809c7
6 files changed
+1074 -149

No files matched your search

+66 -14
View File
@@ -1,5 +1,8 @@
use senbei_engine::android::ResourceLimits;
use senbei_io::{job, pause, scan};
use senbei_io::{
job, pause, scan,
ui::{self, ColorMode, Palette, Tone},
};
use std::num::NonZeroUsize;
use std::path::Path;
@@ -8,14 +11,22 @@ fn main() -> std::process::ExitCode {
Ok(Outcome::Run(options)) => options,
Ok(Outcome::Handled(code)) => return code,
Err(message) => {
eprintln!("error: {message}");
eprintln!(
"{}: {message}",
Palette::stderr().paint(Tone::Error, "error")
);
return std::process::ExitCode::from(2);
}
};
let code = match options.threads {
let color = if options.machine {
ColorMode::Never
} else {
options.color
};
let code = ui::with_color_mode(color, || match options.threads {
Some(count) => senbei_engine::with_thread_cap(count, || execute(&mut options)),
None => execute(&mut options),
};
});
if !options.machine {
pause::maybe_pause(options.no_pause);
}
@@ -42,6 +53,7 @@ struct Options {
scan_all: bool,
strict_integrity: bool,
threads: Option<NonZeroUsize>,
color: ColorMode,
limits: ResourceLimits,
/// Machine-readable output on stdout and nothing else.
machine: bool,
@@ -68,6 +80,7 @@ impl Options {
let mut scan_all = false;
let mut strict_integrity = false;
let mut threads = None;
let mut color = ColorMode::Auto;
let mut machine = false;
let mut dry_run = false;
let mut limits = ResourceLimits::default();
@@ -91,6 +104,10 @@ impl Options {
"--json" => machine = true,
"--dry-run" => dry_run = true,
"--threads" => threads = Some(parse_thread_cap(args.next().as_deref())?),
"--color" => color = parse_color(args.next().as_deref())?,
flag if flag.starts_with("--color=") => {
color = parse_color(flag.strip_prefix("--color="))?
}
flag
@ ("--max-entry-mib" | "--max-total-mib" | "--max-entries" | "--max-depth") => {
set_resource_limit(&mut limits, flag, args.next().as_deref())?;
@@ -176,6 +193,7 @@ impl Options {
scan_all,
strict_integrity,
threads,
color,
limits,
machine,
dry_run,
@@ -183,6 +201,15 @@ impl Options {
}
}
fn parse_color(value: Option<&str>) -> Result<ColorMode, String> {
match value {
Some("auto") => Ok(ColorMode::Auto),
Some("always") => Ok(ColorMode::Always),
Some("never") => Ok(ColorMode::Never),
_ => Err("--color requires auto, always, or never".to_owned()),
}
}
fn parse_thread_cap(value: Option<&str>) -> Result<NonZeroUsize, String> {
value
.filter(|text| !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit()))
@@ -213,7 +240,7 @@ fn execute_inspect(options: &Options, path: &Path, scan_all: bool) -> u8 {
if options.machine {
println!("{}", report.to_json());
} else if options.quiet < 2 {
print!("{}", report.render_text());
print!("{}", report.render_text_with_palette(Palette::stdout()));
}
code
}
@@ -222,7 +249,10 @@ fn execute_inspect(options: &Options, path: &Path, scan_all: bool) -> u8 {
let report = job::error_report(job::Mode::Inspect, &format!("{error:#}"));
println!("{}", report.to_json());
} else if options.quiet < 2 {
eprintln!("error: {error:#}");
eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
}
1
}
@@ -236,8 +266,8 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
if options.machine {
println!("{}", report.to_json());
} else if options.quiet < 2 {
print!("{}", report.render_text());
println!("{}", report.summary_line());
print!("{}", report.render_text_with_palette(Palette::stdout()));
println!("{}", report.summary_line_with_palette(Palette::stdout()));
}
code
}
@@ -246,7 +276,10 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
let report = job::error_report(job::Mode::DryRun, &format!("{error:#}"));
println!("{}", report.to_json());
} else if options.quiet < 2 {
eprintln!("error: {error:#}");
eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
}
1
}
@@ -255,7 +288,13 @@ fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 {
fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
if options.quiet < 2 && !options.machine {
println!("Senbei {}", env!("CARGO_PKG_VERSION"));
println!(
"{}",
Palette::stdout().paint(
Tone::Heading,
format!("Senbei {}", env!("CARGO_PKG_VERSION"))
)
);
}
let out_path = options.out.as_deref().map(Path::new);
// A machine run goes through the same drivers with an observer attached;
@@ -310,8 +349,12 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
if options.machine {
println!("{}", collector.finish().to_json());
} else if options.quiet < 2 {
println!("{}", summary.line());
println!("done in {} ms", summary.duration_ms);
println!("{}", summary.line_with_palette(Palette::stdout()));
println!(
"{}",
Palette::stdout()
.paint(Tone::Muted, format!("done in {} ms", summary.duration_ms))
);
}
exit_code(&summary, options.strict_integrity)
}
@@ -321,7 +364,10 @@ fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 {
failed.push_error(format!("{error:#}"));
println!("{}", failed.finish().to_json());
} else if options.quiet < 2 {
eprintln!("error: {error:#}");
eprintln!(
"{}: {error:#}",
Palette::stderr().paint(Tone::Error, "error")
);
}
1
}
@@ -383,7 +429,7 @@ fn set_resource_limit(
fn print_help() {
println!(
"senbei [inspect|unpack] <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--json] [--dry-run] [--threads N] [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]"
"senbei [inspect|unpack] <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--json] [--dry-run] [--threads N] [--color auto|always|never] [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]"
);
println!(
" <file|folder>\n\
@@ -416,6 +462,12 @@ fn print_help() {
" --threads N positive worker cap for this run. Overrides SENBEI_THREADS;\n\
\x20 1 selects the sequential path. The environment is unchanged."
);
println!(
" --color MODE auto (default), always, or never; --color=MODE also works.\n\
\x20 Auto colors terminal stdout/stderr separately, unless\n\
\x20 NO_COLOR is nonempty or TERM=dumb. Explicit always/never\n\
\x20 override these variables. JSON and saved logs stay plain."
);
println!(
" --scan-all probe selected .exe/.dll/.so/metadata names below the\n\
\x20 size floor; other filenames remain excluded."
+269
View File
@@ -0,0 +1,269 @@
//! Terminal presentation is opt-in for pipes and never enters stored data.
#[path = "support/fixtures.rs"]
mod fixtures;
use std::path::Path;
use std::process::{Command, Output};
fn senbei() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_senbei"));
command
.arg("--no-pause")
.env_remove("NO_COLOR")
.env("TERM", "xterm-256color");
command
}
fn fixture(root: &Path) -> std::path::PathBuf {
let path = root.join("global-metadata.dat");
std::fs::write(&path, fixtures::obfuscated_metadata()).unwrap();
path
}
fn text(bytes: &[u8]) -> &str {
std::str::from_utf8(bytes).expect("UTF-8 console output")
}
fn assert_plain(output: &Output) {
for bytes in [&output.stdout, &output.stderr] {
assert!(!bytes.contains(&0x1b), "unexpected ANSI: {}", text(bytes));
assert!(!text(bytes).to_ascii_lowercase().contains("\\u001b"));
}
}
fn strip_styles(value: &str) -> String {
let mut chars = value.chars();
let mut plain = String::new();
while let Some(ch) = chars.next() {
if ch == '\x1b' {
assert_eq!(chars.next(), Some('['));
for code in chars.by_ref() {
if code == 'm' {
break;
}
assert!(code.is_ascii_digit() || code == ';');
}
} else {
plain.push(ch);
}
}
plain
}
#[test]
fn inspect_colors_preserve_report_content() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
let plain = senbei()
.arg("inspect")
.arg(&path)
.args(["--color", "never"])
.output()
.unwrap();
let colored = senbei()
.arg("inspect")
.arg(&path)
.arg("--color=always")
.output()
.unwrap();
assert!(plain.status.success());
assert!(colored.status.success());
assert_plain(&plain);
assert!(colored.stdout.contains(&0x1b));
assert!(colored.stderr.is_empty());
let strip_time = |value: &str| {
value
.lines()
.filter(|line| !line.ends_with(" ms"))
.collect::<Vec<_>>()
.join("\n")
};
assert_eq!(
strip_time(&strip_styles(text(&colored.stdout))),
strip_time(text(&plain.stdout))
);
assert!(text(&colored.stdout).contains("\x1b[32msucceeded\x1b[0m"));
assert!(!temp.path().join("unpack").exists());
}
#[test]
fn ordinary_unpack_colors_results_but_not_saved_logs() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
let out = temp.path().join("out");
let output = senbei()
.arg("unpack")
.arg(&path)
.arg("--out")
.arg(&out)
.args(["--color", "always"])
.output()
.unwrap();
assert!(output.status.success(), "{}", text(&output.stderr));
assert!(output.stdout.contains(&0x1b));
assert!(text(&output.stdout).contains("\x1b[32m✓\x1b[0m"));
assert!(out.join("global-metadata.unpack.dat").is_file());
let logs: Vec<_> = std::fs::read_dir(&out)
.unwrap()
.flatten()
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|value| value == "log"))
.collect();
assert_eq!(logs.len(), 1);
let log = std::fs::read_to_string(&logs[0]).unwrap();
assert!(!log.contains('\x1b'));
assert!(!log.contains("\\u001b"));
assert!(log.contains("summary:"));
assert!(log.contains("method fields"));
}
#[test]
fn folder_unpack_uses_the_same_palette_and_plain_logs() {
let temp = tempfile::tempdir().unwrap();
fixture(temp.path());
let output = senbei()
.arg("unpack")
.arg(temp.path())
.args(["--color=always", "--scan-all"])
.output()
.unwrap();
assert!(output.status.success(), "{}", text(&output.stderr));
assert!(text(&output.stdout).contains("\x1b[32m✓\x1b[0m"));
assert!(text(&output.stdout).contains("metadata"));
for entry in std::fs::read_dir(temp.path().join("unpack"))
.unwrap()
.flatten()
{
if entry.path().extension().is_some_and(|value| value == "log") {
assert!(!std::fs::read(entry.path()).unwrap().contains(&0x1b));
}
}
}
#[test]
fn redirected_auto_and_never_are_plain_for_both_commands() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
for operation in ["inspect", "unpack"] {
for args in [vec![], vec!["--color", "auto"], vec!["--color=never"]] {
let output = senbei()
.arg(operation)
.arg(&path)
.args(args)
.arg("--no-log")
.output()
.unwrap();
assert!(output.status.success());
assert_plain(&output);
}
}
}
#[test]
fn explicit_color_overrides_no_color_and_dumb_terminal() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
for operation in ["inspect", "unpack"] {
let forced = senbei()
.env("NO_COLOR", "1")
.env("TERM", "dumb")
.arg(operation)
.arg(&path)
.args(["--color=always", "--no-log"])
.output()
.unwrap();
assert!(forced.status.success());
assert!(forced.stdout.contains(&0x1b));
let plain = senbei()
.env("NO_COLOR", "1")
.env("TERM", "dumb")
.arg(operation)
.arg(&path)
.args(["--color=auto", "--no-log"])
.output()
.unwrap();
assert!(plain.status.success());
assert_plain(&plain);
}
}
#[test]
fn json_stays_plain_even_with_forced_color_and_verbose() {
let temp = tempfile::tempdir().unwrap();
let path = fixture(temp.path());
for operation in ["inspect", "unpack"] {
let out = temp.path().join(format!("json-{operation}"));
let mut command = senbei();
command
.arg(operation)
.arg(&path)
.args(["--json", "--verbose", "--color", "always"]);
if operation == "unpack" {
command.arg("--out").arg(&out);
}
let output = command.output().unwrap();
assert!(output.status.success(), "{}", text(&output.stderr));
assert_plain(&output);
assert!(output.stderr.is_empty());
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(report["inputs"][0]["profile"]["recovery"], "succeeded");
if out.exists() {
assert!(
std::fs::read_dir(&out)
.unwrap()
.flatten()
.all(|entry| entry.path().extension().is_none_or(|value| value != "log"))
);
}
}
}
#[test]
fn forced_color_diagnostics_use_stderr_and_quiet_still_wins() {
let temp = tempfile::tempdir().unwrap();
let invalid = temp.path().join("invalid.exe");
std::fs::write(&invalid, b"not a protected image").unwrap();
let failed = senbei()
.arg(&invalid)
.args(["--color=always", "--no-log"])
.output()
.unwrap();
assert_eq!(failed.status.code(), Some(1));
assert!(text(&failed.stderr).contains("\x1b[31merror\x1b[0m"));
for operation in ["inspect", "unpack"] {
let output = senbei()
.arg(operation)
.arg(&invalid)
.args(["--color=always", "--no-log", "-q", "-q"])
.output()
.unwrap();
assert!(output.stdout.is_empty());
assert!(output.stderr.is_empty());
}
}
#[test]
fn invalid_color_arguments_are_usage_errors_and_help_explains_policy() {
for args in [
vec!["--color"],
vec!["--color="],
vec!["--color=bright"],
vec!["--color", "bright"],
] {
let output = senbei().args(args).output().unwrap();
assert_eq!(output.status.code(), Some(2));
assert!(text(&output.stderr).contains("--color requires auto, always, or never"));
assert_plain(&output);
}
let help = senbei().arg("--help").output().unwrap();
let help = text(&help.stdout);
for fact in [
"--color",
"NO_COLOR",
"TERM=dumb",
"JSON and saved logs stay plain",
] {
assert!(help.contains(fact), "missing {fact}: {help}");
}
}