feat: localize console output and add a run observer

Engine errors, integrity findings, and driver outcomes carry message
codes from senbei-i18n, with their English unchanged, so reports, logs,
and --json stay byte-identical. Verbose pipeline steps go through a
progress sink instead of println!, and an error chain is translated
through its first coded cause.

The CLI takes the display language from SENBEI_LANG, or else from the
system's preferred UI language, and translates console text: usage
errors, help, per-file lines, the run summary, and the summary lines of
the inspect report. Structural research evidence and saved logs stay
English. When a translation leaves out context the English chain has,
the English follows on a muted line.

A front end can attach a RunObserver and a CancelToken to the Collector
to follow a run input by input, receive verbose steps as events, and
stop before the next input. A cancelled report says so. The CLI never
cancels, so its JSON is unchanged.
This commit is contained in:
Momoko-Ayase committed 2026-11-08 02:41:04 +08:00
1 parent 9481b0ccf9
commit 4853fe22c0
39 files changed
+2016 -684

No files matched your search

+28 -10
View File
@@ -40,7 +40,9 @@ use sha2::{Digest, Sha256};
use zip::ZipArchive;
pub use crate::METADATA_FILE_NAME;
use crate::message::Coded;
use crate::report::{ContainerReport, ManifestReport};
use senbei_i18n::Msg;
/// Package extensions recognised as Android app packages. Packages are
/// *containers*: membership is decided by extension plus the ZIP magic, while
@@ -114,7 +116,9 @@ pub fn inspect_package(package: &Path, limits: &ResourceLimits) -> Result<Contai
continue;
}
let Some(name) = name else {
bail!("unsafe entry path in package `{}`", package.display());
bail!(Coded::new(Msg::UnsafePackageEntry {
package: package.display().to_string(),
}));
};
if bundle {
if name
@@ -642,7 +646,7 @@ pub(crate) fn restore_loose_metadata(
),
Err(ambiguity) => {
let provenance = context::provenance_for(modules.as_ref(), Some(&ambiguity));
bail!(provenance_error(&provenance));
bail!(provenance_error(&provenance, &ambiguity));
}
}
} else {
@@ -657,7 +661,7 @@ pub(crate) fn restore_loose_metadata(
if report.remapped > 0 {
write_metadata_blob(dest, &out)?;
if verbose {
println!("Write to {}", dest.display());
crate::ui::write_to(dest, false);
}
}
Ok(LooseMetadataOutcome {
@@ -995,7 +999,7 @@ pub(crate) fn restore_metadata_with_module(
// version" and could be mistaken for a clean skip. No module is a
// failed binding, not an unsupported layout.
let Some(module) = method_index_module else {
let error = anyhow::anyhow!("no module 0x0C for v24.1 metadata");
let error = anyhow::Error::new(Coded::new(Msg::NoModule0c));
return Err(fail(&mut facts, error));
};
let (out, report) = senbei_metadata::android::restore_method_indices_v24_1(data, module)
@@ -1335,7 +1339,9 @@ fn restore_package_pass<R: context::LibraryRestorer>(
continue;
}
let Some(name) = name else {
bail!("unsafe entry path in package `{}`", package.display());
bail!(Coded::new(Msg::UnsafePackageEntry {
package: package.display().to_string(),
}));
};
if bundle {
if name
@@ -1436,7 +1442,9 @@ fn restore_package_pass<R: context::LibraryRestorer>(
};
if !is_dir {
let Some(entry_name) = entry_name else {
bail!("unsafe entry path in `{}`", nested_label.display());
bail!(Coded::new(Msg::UnsafeNestedEntry {
path: nested_label.display().to_string(),
}));
};
if is_android_entry_name(&entry_name) {
entries.push((nested_index, entry_name));
@@ -1674,7 +1682,10 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
let provenance = context::provenance_for(modules.as_ref(), Some(&ambiguity));
return Ok(vec![outcome(
EntryKind::Metadata { remapped: 0 },
EntryStatus::Failed(anyhow::anyhow!(provenance_error(&provenance))),
EntryStatus::Failed(anyhow::Error::new(provenance_error(
&provenance,
&ambiguity,
))),
provenance_labels(&provenance),
)]);
}
@@ -1792,13 +1803,20 @@ fn provenance_labels(provenance: &context::MetadataProvenance) -> Vec<String> {
.collect()
}
fn provenance_error(provenance: &context::MetadataProvenance) -> String {
fn provenance_error(
provenance: &context::MetadataProvenance,
ambiguity: &context::ContextAmbiguity,
) -> Coded {
let msg = match ambiguity {
context::ContextAmbiguity::Missing => Msg::NoModule0c,
context::ContextAmbiguity::Conflicting { .. } => Msg::AmbiguousModule0c,
};
let why = provenance
.note
.clone()
.unwrap_or_else(|| "ambiguous module 0x0C binding".to_owned());
if provenance.sources.is_empty() {
return why;
return Coded::with_text(msg, why);
}
let sources = provenance
.sources
@@ -1806,7 +1824,7 @@ fn provenance_error(provenance: &context::MetadataProvenance) -> String {
.map(|source| source.label.as_str())
.collect::<Vec<_>>()
.join(", ");
format!("{why}; modules from {sources}")
Coded::with_text(msg, format!("{why}; modules from {sources}"))
}
/// Output path for a metadata blob unwrapped from a restored library: next to
+233 -115
View File
@@ -1,7 +1,10 @@
use std::path::{Path, PathBuf};
use std::time::Instant;
use senbei_i18n::{Cli, Lang, Localize, Message, Msg};
use crate::atomic::write_atomic;
use crate::message::{Coded, of_error};
pub use crate::report::{Collector, Mode, REPORT_FORMAT_VERSION, Report};
use crate::report::{
CompanionReport, CompanionState, ContainerReport, Digest, EntryKind, EntryReport, EntryStatus,
@@ -34,30 +37,31 @@ pub struct Summary {
}
impl Summary {
/// The plain summary line shared by CLI output and the log file.
/// The plain English summary line, as the log file records it.
pub fn line(&self) -> String {
self.line_with_palette(crate::ui::Palette::plain())
self.line_in(crate::ui::Palette::plain(), Lang::En)
}
/// Console rendering without adding presentation escapes to log data.
/// Console rendering in the process language, without adding
/// presentation escapes to log data.
pub fn line_with_palette(&self, palette: crate::ui::Palette) -> String {
use crate::ui::{Tone, count};
self.line_in(palette, senbei_i18n::current())
}
let mut line = format!(
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
count(palette, self.unpacked, Tone::Success),
count(palette, self.skipped, Tone::Muted),
count(palette, self.errors, Tone::Error),
count(palette, self.suspect, Tone::Warning),
count(palette, self.metadata, Tone::Success)
);
if self.packages > 0 {
line.push_str(&format!(
" · {} packages",
palette.paint(Tone::Value, self.packages)
));
}
line
/// The summary line in `lang`.
pub fn line_in(&self, palette: crate::ui::Palette, lang: Lang) -> String {
crate::ui::summary_line(
palette,
lang,
[
self.unpacked,
self.skipped,
self.errors,
self.suspect,
self.metadata,
self.packages,
],
)
}
}
@@ -176,7 +180,7 @@ pub fn run_folder_reported(
///
/// Used when a run cannot start at all (an unreadable input, a rejected
/// command line), so `--json` callers still receive one versioned document.
pub fn error_report(mode: Mode, message: &str) -> Report {
pub fn error_report(mode: Mode, message: impl Into<Message>) -> Report {
let mut collector = Collector::new(mode);
collector.push_error(message);
collector.finish()
@@ -188,6 +192,61 @@ pub fn error_report(mode: Mode, message: &str) -> Report {
/// [`run_folder_with_limits`]; the collector only observes.
#[allow(clippy::too_many_arguments)]
fn run_folder_inner(
root: &Path,
out_dir: Option<&Path>,
quiet: u8,
verbose: bool,
no_log: bool,
scan_all: bool,
limits: &senbei_engine::android::ResourceLimits,
reporter: Option<&mut Collector>,
) -> anyhow::Result<Summary> {
observed(reporter, |reporter| {
run_folder_body(
root, out_dir, quiet, verbose, no_log, scan_all, limits, reporter,
)
})
}
/// Run `body` with the pipelines' verbose progress sent to the collector's
/// observer, when it has one. Without an observer progress prints as before.
fn observed<R>(
reporter: Option<&mut Collector>,
body: impl FnOnce(Option<&mut Collector>) -> R,
) -> R {
match reporter.as_deref().and_then(Collector::observer).cloned() {
Some(observer) => senbei_engine::progress::with_sink(
move |event| observer.progress(event),
|| body(reporter),
),
None => body(reporter),
}
}
/// True once the run's front end asked it to stop. Checked before each input.
fn stop(reporter: &mut Option<&mut Collector>) -> bool {
reporter.as_deref_mut().is_some_and(Collector::should_stop)
}
/// Tell the run's observer that work on `path` began.
fn started(reporter: &Option<&mut Collector>, path: &Path) {
if let Some(observer) = reporter.as_deref().and_then(Collector::observer) {
observer.input_started(path);
}
}
/// Verbose pipeline steps are shown on an unquiet console, or sent to an
/// observer, which never prints them.
fn verbose_steps(verbose: bool, quiet: u8, reporter: &Option<&mut Collector>) -> bool {
verbose
&& (quiet == 0
|| reporter
.as_deref()
.is_some_and(|reporter| reporter.observer().is_some()))
}
#[allow(clippy::too_many_arguments)]
fn run_folder_body(
root: &Path,
out_dir: Option<&Path>,
quiet: u8,
@@ -229,10 +288,11 @@ fn run_folder_inner(
// fail the run (exit 1) rather than report "0 errors" over a partial scan.
let scan_failed = scan_stats.walk_errors + scan_stats.probe_errors;
if scan_failed > 0 && quiet == 0 {
let lang = senbei_i18n::current();
eprintln!(
"{}: {} file(s) could not be read during the scan and may be missed targets",
Palette::stderr().paint(Tone::Warning, "warning"),
scan_failed
"{}: {}",
Palette::stderr().paint(Tone::Warning, Cli::Warning.localize(lang)),
Cli::ScanUnreadable { count: scan_failed }.localize(lang)
);
}
if let Some(log) = &log {
@@ -252,7 +312,8 @@ fn run_folder_inner(
let suppress_file_lines = quiet >= 1;
// Quiet wins over verbose: step progress only when quiet == 0 (spec: verbose
// lines only when quiet == 0; quiet ≥ 2 must stay fully silent even with -v).
let verbose_steps = verbose && quiet == 0;
// An observer receives the steps instead of the console.
let verbose_steps = verbose_steps(verbose, quiet, &reporter);
// Verbose mode prints multi-line `[N/9]` step output per file straight to
// stdout; an active progress bar would be clobbered by it, so hide the bar
// (its per-file ok/err lines still print) when verbose is on.
@@ -277,9 +338,21 @@ fn run_folder_inner(
walk_errors: scan_stats.walk_errors,
probe_errors: scan_stats.probe_errors,
});
if let Some(observer) = reporter.observer() {
observer.scanned(
candidates.len()
+ scan.android_so.len()
+ scan.android_packages.len()
+ metas.len(),
);
}
}
for input in candidates {
if stop(&mut reporter) {
break;
}
started(&reporter, input);
let rel = rel_in_tree(root, input);
let dest = out_root.join(out_name(&rel));
let started = Instant::now();
@@ -346,7 +419,7 @@ fn run_folder_inner(
}
Err(panic) => {
s.errors += 1;
let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic));
let e = anyhow::Error::new(Coded::panic("", panic_payload(&panic)));
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!(
@@ -378,6 +451,10 @@ fn run_folder_inner(
.iter()
.any(|library| library == &scoped.path)
}) {
if stop(&mut reporter) {
break;
}
started(&reporter, &scoped.path);
let rel = rel_in_tree(root, &scoped.path);
let dest = out_root.join(out_name(&rel));
let input_owned = scoped.path.clone();
@@ -487,7 +564,7 @@ fn run_folder_inner(
}
Err(panic) => {
s.errors += 1;
let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic));
let e = anyhow::Error::new(Coded::panic("", panic_payload(&panic)));
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!(
@@ -516,7 +593,14 @@ fn run_folder_inner(
let package_groups =
crate::android::loose_apk_groups_cached(&scan.android_packages, &mut android_cache);
for group in &package_groups {
if stop(&mut reporter) {
break;
}
if group.len() > 1 {
// A split set restores as one unit and reports each member.
for package in group {
started(&reporter, package);
}
s.packages += group.len();
// Relative output paths are computed here, by the same helper the
// rest of the driver uses: they must stay relative so joining them
@@ -588,10 +672,10 @@ fn run_folder_inner(
}
}
Err(panic) => {
let e = anyhow::anyhow!(
"unexpected panic during package restore: {}",
panic_payload(&panic)
);
let e = anyhow::Error::new(Coded::panic(
" during package restore",
panic_payload(&panic),
));
s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
@@ -608,6 +692,10 @@ fn run_folder_inner(
continue;
}
for package in group {
if stop(&mut reporter) {
break;
}
started(&reporter, package);
let rel = rel_in_tree(root, package);
s.packages += 1;
let package_owned = package.clone();
@@ -648,7 +736,7 @@ fn run_folder_inner(
Err(panic) => {
// A panic may leave a partial module recorded. Keeping the cache
// preserves successful dedup; a conflict still fails closed.
let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic));
let e = anyhow::Error::new(Coded::panic("", panic_payload(&panic)));
s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
@@ -675,6 +763,10 @@ fn run_folder_inner(
.iter()
.filter(|scoped| metas.iter().any(|meta| meta == &scoped.path))
{
if stop(&mut reporter) {
break;
}
started(&reporter, &scoped.path);
let rel = rel_in_tree(root, &scoped.path);
let dest = out_root.join(out_name(&rel));
let meta_owned = scoped.path.clone();
@@ -740,9 +832,11 @@ fn run_folder_inner(
s.skipped += 1;
if !suppress_file_lines {
eprintln!(
"{} {} unsupported metadata version {v}, left untouched",
"{} {} {}",
Palette::stderr().paint(Tone::Warning, "-"),
rel.display()
rel.display(),
Cli::MetadataUnsupportedLine { version: v }
.localize(senbei_i18n::current())
);
}
if let Some(log) = &log {
@@ -768,10 +862,10 @@ fn run_folder_inner(
}
Err(panic) => {
s.errors += 1;
let e = anyhow::anyhow!(
"unexpected panic during de-obfuscation: {}",
panic_payload(&panic)
);
let e = anyhow::Error::new(Coded::panic(
" during de-obfuscation",
panic_payload(&panic),
));
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!(
@@ -847,6 +941,21 @@ pub fn run_file_reported(
#[allow(clippy::too_many_arguments)]
fn run_file_inner(
input: &Path,
out_dir: Option<&Path>,
quiet: u8,
verbose: bool,
no_log: bool,
limits: &senbei_engine::android::ResourceLimits,
reporter: Option<&mut Collector>,
) -> anyhow::Result<Summary> {
observed(reporter, |reporter| {
run_file_body(input, out_dir, quiet, verbose, no_log, limits, reporter)
})
}
#[allow(clippy::too_many_arguments)]
fn run_file_body(
input: &Path,
out_dir: Option<&Path>,
quiet: u8,
@@ -883,6 +992,11 @@ fn run_file_inner(
let research = reporter
.as_deref()
.is_some_and(|reporter| reporter.mode() == Mode::Inspect);
let verbose_steps = verbose_steps(verbose, quiet, &reporter);
if let Some(observer) = reporter.as_deref().and_then(Collector::observer) {
observer.scanned(1);
}
started(&reporter, input);
let prefix = {
use std::io::Read;
@@ -906,7 +1020,7 @@ fn run_file_inner(
let is_android_package = !is_android_so && crate::android::is_app_package(input, &prefix);
if is_meta {
match deobfuscate_metadata_researched(input, &dest, verbose && quiet == 0, research, None) {
match deobfuscate_metadata_researched(input, &dest, verbose_steps, research, None) {
Ok((report, layout, metadata_research)) if report.remapped > 0 => {
s.metadata = 1;
if let Some(log) = &log {
@@ -916,12 +1030,16 @@ fn run_file_inner(
));
}
if quiet == 0 {
let palette = Palette::stdout();
let line = Cli::MetadataVersionLine {
version: palette.paint(Tone::Value, report.version).to_string(),
dest: palette.paint(Tone::Value, format!("{dest:?}")).to_string(),
remapped: palette.paint(Tone::Value, report.remapped).to_string(),
};
println!(
"{} metadata v{} -> {} ({} method fields remapped)",
Palette::stdout().paint(Tone::Success, "✓"),
Palette::stdout().paint(Tone::Value, report.version),
Palette::stdout().paint(Tone::Value, format!("{dest:?}")),
Palette::stdout().paint(Tone::Value, report.remapped)
"{} {}",
palette.paint(Tone::Success, "✓"),
line.localize(senbei_i18n::current())
);
}
if let Some(reporter) = reporter.as_deref_mut() {
@@ -939,11 +1057,15 @@ fn run_file_inner(
));
}
if quiet == 0 {
let lang = senbei_i18n::current();
let palette = Palette::stdout();
let version = Cli::MetadataAlreadyClean {
version: palette.paint(Tone::Value, report.version).to_string(),
};
println!(
"metadata v{}: {}",
Palette::stdout().paint(Tone::Value, report.version),
Palette::stdout()
.paint(Tone::Muted, "already de-obfuscated, nothing to do")
"{} {}",
version.localize(lang),
palette.paint(Tone::Muted, Cli::MetadataNothingToDo.localize(lang))
);
}
if let Some(reporter) = reporter.as_deref_mut() {
@@ -960,7 +1082,7 @@ fn run_file_inner(
}
// Level 1 quiet: banner/summary/duration only (match folder mode).
if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
crate::ui::print_anyhow(&e);
}
if let Some(reporter) = reporter.as_deref_mut() {
let unsupported = unsupported_version(&e);
@@ -973,7 +1095,7 @@ fn run_file_inner(
crate::android::restore_so_file_researched(
input,
&dest,
verbose && quiet == 0,
verbose_steps,
limits,
research,
)
@@ -985,13 +1107,8 @@ fn run_file_inner(
)
})
} else {
crate::android::restore_so_file_with_diagnostics(
input,
&dest,
verbose && quiet == 0,
limits,
)
.map(|(embedded, validation)| (embedded, validation, None))
crate::android::restore_so_file_with_diagnostics(input, &dest, verbose_steps, limits)
.map(|(embedded, validation)| (embedded, validation, None))
};
match restore {
Ok((embedded, validation, android_research)) => {
@@ -1015,11 +1132,15 @@ fn run_file_inner(
log.step(&format!("META {:?} (embedded) -> {:?}", input, meta_dest));
}
if quiet == 0 {
let palette = Palette::stdout();
let line = Cli::EmbeddedMetadataLine {
input: palette.paint(Tone::Label, input.display()).to_string(),
dest: palette.paint(Tone::Value, meta_dest.display()).to_string(),
};
println!(
"{} metadata {} (embedded) -> {}",
Palette::stdout().paint(Tone::Success, "✓"),
Palette::stdout().paint(Tone::Label, input.display()),
Palette::stdout().paint(Tone::Value, meta_dest.display())
"{} {}",
palette.paint(Tone::Success, "✓"),
line.localize(senbei_i18n::current())
);
}
}
@@ -1030,10 +1151,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: embedded metadata: {e:#}", input));
}
if quiet == 0 {
eprintln!(
"{}: embedded metadata: {e:#}",
Palette::stderr().paint(Tone::Error, "error")
);
crate::ui::print_error_about(Cli::EmbeddedMetadataFailed, &e);
}
}
}
@@ -1050,7 +1168,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input));
}
if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
crate::ui::print_anyhow(&e);
}
if let Some(reporter) = reporter.as_deref_mut() {
let mut reported = android_library_input_with_error(
@@ -1082,7 +1200,7 @@ fn run_file_inner(
&rel,
&out_root,
&mut seen,
verbose && quiet == 0,
verbose_steps,
limits,
research,
) {
@@ -1104,7 +1222,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input));
}
if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
crate::ui::print_anyhow(&e);
}
if let Some(reporter) = reporter {
reporter.push(failed_input(input, &e, t0));
@@ -1118,14 +1236,10 @@ fn run_file_inner(
let (profile, observed, result) = match reporter.is_some() {
true => {
let (profile, observed, result) =
unpack_one_researched(input, &dest, verbose && quiet == 0, research);
unpack_one_researched(input, &dest, verbose_steps, research);
(Some(profile), observed, result)
}
false => (
None,
None,
unpack_one_v(input, &dest, verbose && quiet == 0),
),
false => (None, None, unpack_one_v(input, &dest, verbose_steps)),
};
match result {
Ok((kind, report)) => {
@@ -1151,13 +1265,14 @@ fn run_file_inner(
));
}
if quiet == 0 {
let lang = senbei_i18n::current();
eprintln!(
"{}: {}",
Palette::stderr().paint(
Tone::Warning,
"! integrity check failed (likely to crash at runtime)"
Cli::IntegrityFailedLikelyCrash.localize(lang)
),
report.issues.join("; ")
crate::ui::issues(&report, lang)
);
}
}
@@ -1173,7 +1288,7 @@ fn run_file_inner(
log.step(&format!("ERR {:?}: {e:#}", input));
}
if quiet == 0 {
eprintln!("{}: {e:#}", Palette::stderr().paint(Tone::Error, "error"));
crate::ui::print_anyhow(&e);
}
if let Some(reporter) = reporter {
let mut reported = match profile {
@@ -1321,10 +1436,7 @@ fn deobfuscate_metadata_researched(
}
write_atomic(dest, &out)?;
if verbose {
println!(
"Write to {}",
Palette::stdout().paint(Tone::Value, dest.display())
);
crate::ui::write_to(dest, true);
}
}
Ok((report, layout, metadata_research))
@@ -1676,7 +1788,7 @@ fn unpack_one_researched(
Err(error) => {
let mut profile = observed_profile(input);
profile.recovery = senbei_engine::RecoveryStatus::Blocked;
profile.push_error(format!("{error:#}"));
profile.push_error(of_error(&error));
return (profile, None, Err(error));
}
};
@@ -1755,10 +1867,7 @@ fn unpack_one_researched(
return (profile, observed, Err(error.into()));
}
if verbose {
println!(
"Write to {}",
Palette::stdout().paint(Tone::Value, dest.display())
);
crate::ui::write_to(dest, true);
}
(profile, observed, Ok((image.kind, image.integrity)))
}
@@ -1869,13 +1978,11 @@ pub(crate) fn companion_report(
_ => path.map(|path| path.display().to_string()),
},
detail: match state {
CompanionState::Unmatched => {
Some("a sibling `._` exists but is not this stub's payload".to_owned())
}
CompanionState::Unreadable => Some(match unreadable {
Some(reason) => format!("the sibling `._` could not be read: {reason}"),
None => "the sibling `._` could not be read".to_owned(),
}),
CompanionState::Unmatched => Some(Message::new(Msg::CompanionUnmatched)),
CompanionState::Unreadable => Some(Message::new(match unreadable {
Some(reason) => Msg::CompanionUnreadable { reason },
None => Msg::CompanionUnreadableUnknown,
})),
_ => None,
},
source,
@@ -1971,7 +2078,7 @@ fn failed_input(input: &Path, error: &anyhow::Error, started: Instant) -> InputR
let mut entry = InputReport::new(input, Role::Content);
entry.status = InputStatus::Error;
entry.analysis_incomplete = analysis_incomplete(error);
let detail = format!("{error:#}");
let detail = of_error(error);
entry.error(detail.clone());
entry.profile = Some(failure_profile(input, &detail));
entry
@@ -1994,7 +2101,7 @@ fn failed_input_with_profile(
let mut entry = InputReport::new(input, Role::Content);
entry.status = InputStatus::Error;
entry.analysis_incomplete = analysis_incomplete(error);
let detail = format!("{error:#}");
let detail = of_error(error);
entry.error(detail.clone());
entry.companion = crate::windows::is_pe_extension(input).then(|| {
let (state, source, unreadable) =
@@ -2055,13 +2162,13 @@ fn observed_profile(input: &Path) -> senbei_engine::ProtectionProfile {
}
/// Profile of an input whose recovery failed.
fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfile {
fn failure_profile(input: &Path, detail: &Message) -> senbei_engine::ProtectionProfile {
use senbei_engine::{AttemptOutcome, LayoutKind, ProtectionProfile, RecoveryStatus};
let Ok(prefix) = read_prefix(input) else {
let mut profile =
ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None));
profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned());
profile.push_error(detail.clone());
return profile;
};
if senbei_metadata::is_metadata(&prefix) {
@@ -2092,8 +2199,8 @@ fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfi
.find(|candidate| candidate.outcome == AttemptOutcome::NotAttempted)
.map(|candidate| candidate.layout)
{
Some(layout) => (layout, vec![detail.to_owned()]),
None => (LayoutKind::ExeStyle, vec![detail.to_owned()]),
Some(layout) => (layout, vec![detail.clone()]),
None => (LayoutKind::ExeStyle, vec![detail.clone()]),
};
if let Some(attempt) = profile.attempt_mut(layout) {
attempt.outcome = AttemptOutcome::Failed;
@@ -2107,7 +2214,7 @@ fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfi
});
}
profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned());
profile.push_error(detail.clone());
return profile;
}
if crate::android::is_elf64_aarch64(&prefix) {
@@ -2115,7 +2222,7 @@ fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfi
}
let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None));
profile.recovery = RecoveryStatus::Failed;
profile.push_error(detail.to_owned());
profile.push_error(detail.clone());
profile
}
@@ -2156,7 +2263,11 @@ fn android_library_input_with_error(
.push(StageReport::new(Stage::Recovery, StageStatus::Skipped));
}
_ => {
let detail = entry.errors.first().cloned().unwrap_or_default();
let detail = entry
.errors
.first()
.cloned()
.unwrap_or_else(|| Message::raw(""));
entry.profile = Some(crate::report::android_failed_profile(&detail));
entry
.stages
@@ -2190,8 +2301,12 @@ fn apply_android_validation(
} else {
senbei_engine::ValidationStatus::Warnings
};
profile.warnings.extend(validation.messages.iter().cloned());
report.warnings.extend(validation.messages.iter().cloned());
profile
.warnings
.extend(validation.messages.iter().cloned().map(Message::from));
report
.warnings
.extend(validation.messages.iter().cloned().map(Message::from));
// The stage itself succeeded — the restore validated the output. Findings
// are carried as detail and warnings, not as a failed stage.
let mut stage = StageReport::new(Stage::StaticValidation, StageStatus::Ok);
@@ -2265,8 +2380,7 @@ fn metadata_input(
None => crate::report::metadata_unchanged_profile(identity),
});
entry.stages.push(
StageReport::new(Stage::Recovery, StageStatus::Skipped)
.detail("the transform ran and validated; nothing needed rewriting"),
StageReport::new(Stage::Recovery, StageStatus::Skipped).detail(Msg::TransformNoop),
);
}
entry.duration_ms = crate::report::now_ms(started);
@@ -2346,14 +2460,12 @@ fn metadata_failure_input(
report.status = InputStatus::Skipped;
report.errors.clear();
report.profile = Some(crate::report::metadata_unchanged_profile(identity));
report.warning(format!(
"unsupported metadata version {version}, left untouched"
));
report.warning(Msg::MetadataLeftUntouched { version });
} else {
report.profile = Some(crate::report::metadata_failed_profile(
identity,
senbei_engine::LayoutKind::MetadataStructural,
&format!("{error:#}"),
&of_error(error),
));
}
report
@@ -2416,7 +2528,9 @@ fn package_input(
.flat_map(|validation| validation.messages.iter().cloned())
.collect();
if !diagnostics.is_empty() {
entry.warnings.extend(diagnostics.clone());
entry
.warnings
.extend(diagnostics.iter().cloned().map(Message::from));
entry.stages.push(
StageReport::new(Stage::StaticValidation, StageStatus::Ok)
.detail(diagnostics.join("; ")),
@@ -2475,7 +2589,7 @@ fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport {
report.output = Some(OutputFile::from_path(&outcome.dest));
}
if let crate::android::EntryStatus::Failed(error) = &outcome.status {
report.errors.push(format!("{error:#}"));
report.errors.push(of_error(error));
// A resource or I/O ceiling stopped this entry before its structure
// could be judged; a structural rejection is an observed finding.
report.analysis_incomplete = analysis_incomplete(error);
@@ -2485,7 +2599,9 @@ fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport {
if status == EntryStatus::Restored
&& let Some(validation) = &outcome.validation
{
report.warnings.extend(validation.messages.iter().cloned());
report
.warnings
.extend(validation.messages.iter().cloned().map(Message::from));
}
report
}
@@ -2814,7 +2930,7 @@ mod incomplete_analysis_tests {
std::fs::write(&path, b"not really an ELF").unwrap();
let mut input = InputReport::new(&path, Role::Content);
input.status = InputStatus::Error;
input.profile = Some(crate::report::android_failed_profile("limit"));
input.profile = Some(crate::report::android_failed_profile(&"limit".into()));
input.analysis_incomplete = true;
let reported = inspect_status(input);
assert_eq!(reported.status, InputStatus::Error);
@@ -2823,7 +2939,9 @@ mod incomplete_analysis_tests {
// The same target without an incompleteness marker is a finding.
let mut complete = InputReport::new(&path, Role::Content);
complete.status = InputStatus::Error;
complete.profile = Some(crate::report::android_failed_profile("layout rejected"));
complete.profile = Some(crate::report::android_failed_profile(
&"layout rejected".into(),
));
let reported = inspect_status(complete);
assert_eq!(reported.status, InputStatus::Recognized);
assert!(!reported.analysis_incomplete);
@@ -2834,7 +2952,7 @@ mod incomplete_analysis_tests {
fn a_container_inherits_an_incomplete_entry() {
let mut entry = EntryReport::new("app.apk::lib/arm64-v8a/libil2cpp.so", EntryStatus::Error);
entry.analysis_incomplete = true;
entry.errors.push("resource limit".to_owned());
entry.errors.push("resource limit".into());
let td = tempfile::tempdir().unwrap();
let path = td.path().join("app.apk");
std::fs::write(&path, b"PK").unwrap();
+3
View File
@@ -6,7 +6,10 @@ pub const METADATA_FILE_NAME: &str = "global-metadata.dat";
pub mod android;
mod atomic;
pub mod job;
pub mod locale;
pub mod logfile;
pub mod message;
pub mod observe;
pub mod pause;
pub mod report;
pub mod scan;
+89
View File
@@ -0,0 +1,89 @@
//! The display language for console output.
//!
//! Only console text follows it. Logs and `--json` reports are English in every
//! language, so their contents never depend on the machine they ran on.
use senbei_i18n::Lang;
/// Environment variable that overrides the system display language.
pub const LANG_VAR: &str = "SENBEI_LANG";
/// The display language: `SENBEI_LANG` when it is set, otherwise the system's
/// preferred UI language, otherwise English.
///
/// A `SENBEI_LANG` value that names no supported language selects English, so
/// `SENBEI_LANG=C` behaves as it does for other tools.
pub fn detect() -> Lang {
match std::env::var(LANG_VAR) {
Ok(value) if !value.trim().is_empty() => Lang::from_tag(&value).unwrap_or_default(),
_ => system().unwrap_or_default(),
}
}
/// The first supported language among the user's preferred UI languages.
#[cfg(windows)]
fn system() -> Option<Lang> {
use windows::Win32::Globalization::{GetUserPreferredUILanguages, MUI_LANGUAGE_NAME};
use windows::core::PWSTR;
let mut count = 0u32;
let mut len = 0u32;
// SAFETY: the first call only reports the buffer length; the second writes
// at most `len` UTF-16 units into a buffer of exactly that length.
unsafe { GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &mut count, None, &mut len) }.ok()?;
let mut buffer = vec![0u16; len as usize];
unsafe {
GetUserPreferredUILanguages(
MUI_LANGUAGE_NAME,
&mut count,
Some(PWSTR(buffer.as_mut_ptr())),
&mut len,
)
}
.ok()?;
first_supported(String::from_utf16_lossy(&buffer).split('\0'))
}
/// The language of the POSIX message locale. `LANGUAGE` is a GNU priority
/// list that applies unless the locale is `C` or `POSIX`.
#[cfg(all(not(windows), not(target_arch = "wasm32")))]
fn system() -> Option<Lang> {
let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty());
let locale = var("LC_ALL")
.or_else(|| var("LC_MESSAGES"))
.or_else(|| var("LANG"))?;
let base = locale.split(['.', '@']).next().unwrap_or_default();
if base == "C" || base == "POSIX" {
return Some(Lang::En);
}
var("LANGUAGE")
.and_then(|list| first_supported(list.split(':')))
.or_else(|| Lang::from_tag(&locale))
}
#[cfg(target_arch = "wasm32")]
fn system() -> Option<Lang> {
None
}
#[cfg(any(test, not(target_arch = "wasm32")))]
fn first_supported<'a>(tags: impl IntoIterator<Item = &'a str>) -> Option<Lang> {
tags.into_iter()
.filter(|tag| !tag.is_empty())
.find_map(Lang::from_tag)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_first_supported_preference_wins() {
assert_eq!(
first_supported(["fr-FR", "zh-TW", "en-US", ""]),
Some(Lang::ZhTw)
);
assert_eq!(first_supported(["fr-FR", "de-DE"]), None);
assert_eq!(first_supported([]), None);
}
}
+172
View File
@@ -0,0 +1,172 @@
//! Translatable messages for errors that reach the I/O layer.
//!
//! Reports, logs, and `--json` keep an error's English exactly as `{error:#}`
//! prints its chain. A front end showing another language translates the first
//! cause in the chain that has a message code, and keeps the English as detail.
use std::fmt;
use senbei_i18n::{Message, Msg};
/// An error raised by the I/O layer itself, carrying its message code.
#[derive(Debug)]
pub(crate) struct Coded(Message);
impl Coded {
pub(crate) fn new(msg: Msg) -> Self {
Self(Message::new(msg))
}
/// A panic caught while `context` ran (for example " during de-obfuscation",
/// or "" when nothing more specific is known).
pub(crate) fn panic(context: &str, payload: String) -> Self {
let text = format!("unexpected panic{context}: {payload}");
Self(Message::with_text(
Msg::UnexpectedPanic { message: payload },
text,
))
}
/// A message whose English differs from the catalog wording for `msg`.
pub(crate) fn with_text(msg: Msg, text: String) -> Self {
Self(Message::with_text(msg, text))
}
}
impl fmt::Display for Coded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.0.text())
}
}
impl std::error::Error for Coded {}
/// The message for `error`: its English chain, translated through the first
/// cause that has a message code.
pub fn of_error(error: &anyhow::Error) -> Message {
let text = format!("{error:#}");
match error.chain().find_map(code) {
Some(msg) => Message::with_text(msg, text),
None => Message::raw(text),
}
}
fn code(cause: &(dyn std::error::Error + 'static)) -> Option<Msg> {
use senbei_engine::android::{ExtractionError, LimitExceeded, RestoreError};
use senbei_metadata::android::{Error as TokenError, MethodIndexError};
if let Some(coded) = cause.downcast_ref::<Coded>() {
return coded.0.msg().cloned();
}
if let Some(error) = cause.downcast_ref::<senbei_engine::windows::UnpackError>() {
return error.message().msg().cloned();
}
let limit = cause.downcast_ref::<LimitExceeded>().or_else(|| {
match cause.downcast_ref::<ExtractionError>() {
Some(ExtractionError::Limit(limit)) => Some(limit),
_ => match cause.downcast_ref::<RestoreError>() {
Some(RestoreError::Limit(limit)) => Some(limit),
_ => None,
},
}
});
if let Some(limit) = limit {
return limit.message().msg().cloned();
}
if let Some(error) = cause.downcast_ref::<senbei_pe::Error>() {
return match error {
senbei_pe::Error::Invalid => Some(Msg::NotPe),
senbei_pe::Error::OutOfBounds => None,
};
}
if let Some(error) = cause.downcast_ref::<senbei_elf::Error>() {
return match error {
senbei_elf::Error::NotElf64 => Some(Msg::NotElf64),
senbei_elf::Error::NotAarch64 => Some(Msg::NotAarch64),
_ => None,
};
}
if let Some(error) = cause.downcast_ref::<senbei_metadata::Error>() {
return Some(match error {
senbei_metadata::Error::NotMetadata => Msg::NotMetadata,
senbei_metadata::Error::UnsupportedVersion(version) => {
Msg::UnsupportedMetadataVersion { version: *version }
}
senbei_metadata::Error::Malformed => Msg::MetadataTransformFailed,
});
}
if let Some(error) = cause.downcast_ref::<TokenError>() {
return Some(match error {
TokenError::NotMetadata => Msg::NotIl2cppMetadata,
TokenError::UnsupportedVersion(version) => {
Msg::UnsupportedMetadataVersion { version: *version }
}
TokenError::Malformed(_) | TokenError::Validation(_) => Msg::MetadataTransformFailed,
});
}
if let Some(error) = cause.downcast_ref::<MethodIndexError>() {
return Some(match error {
MethodIndexError::NotMetadata => Msg::NotIl2cppMetadata,
MethodIndexError::UnsupportedVersion(version) => {
Msg::UnsupportedMetadataVersion { version: *version }
}
_ => Msg::MetadataTransformFailed,
});
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use senbei_i18n::Lang;
#[test]
fn the_english_is_the_whole_chain_and_the_code_its_first_known_cause() {
let error = anyhow::Error::new(senbei_engine::android::LimitExceeded::Entry {
requested: 10,
limit: 4,
})
.context("extract `a.so`");
let message = of_error(&error);
assert_eq!(message.text(), format!("{error:#}"));
assert_eq!(
message.msg(),
Some(&Msg::LimitEntry {
requested: 10,
limit: 4
})
);
assert_eq!(message.detail(Lang::En), None);
assert_eq!(message.detail(Lang::Ko), Some(message.text()));
}
#[test]
fn unknown_chains_stay_raw_and_io_codes_survive_anyhow() {
let raw = of_error(&anyhow::anyhow!("couldn't read companion x"));
assert_eq!(raw.msg(), None);
assert_eq!(raw.text(), "couldn't read companion x");
let panic = anyhow::Error::new(Coded::panic(" during de-obfuscation", "boom".into()));
let message = of_error(&panic);
assert_eq!(
message.text(),
"unexpected panic during de-obfuscation: boom"
);
assert_eq!(
message.msg(),
Some(&Msg::UnexpectedPanic {
message: "boom".into()
})
);
let unpack = anyhow::Error::new(senbei_engine::windows::UnpackError::NotCrackProof);
assert_eq!(of_error(&unpack).msg(), Some(&Msg::NotProtected));
let metadata = anyhow::Error::new(senbei_metadata::Error::UnsupportedVersion(27))
.context("\"global-metadata.dat\"");
assert_eq!(
of_error(&metadata).msg(),
Some(&Msg::UnsupportedMetadataVersion { version: 27 })
);
}
}
+48
View File
@@ -0,0 +1,48 @@
//! Live progress and cancellation for front ends that show a run as it happens.
//!
//! The CLI prints its own lines and uses neither. A front end attaches both to
//! the [`Collector`](crate::report::Collector) it passes to a reporting run.
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::report::InputReport;
/// Receives a run's progress on the thread doing the work. Every method has an
/// empty default, so an observer implements only what it shows.
pub trait RunObserver: Send + Sync {
/// The scan finished: `inputs` targets were found and will be processed.
fn scanned(&self, _inputs: usize) {}
/// Work on `path` began.
fn input_started(&self, _path: &Path) {}
/// A verbose pipeline event for the input being processed. Sent only when
/// the run was started with `verbose`.
fn progress(&self, _event: &senbei_engine::progress::Event) {}
/// One input finished. This is the report the run keeps for it.
fn input_finished(&self, _input: &InputReport) {}
}
/// A request to stop a run, checked before each input.
///
/// Cancelling never interrupts an input mid-recovery: the input in progress
/// finishes and is reported, and no later input starts.
#[derive(Debug, Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);
impl CancelToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
}
+5 -1
View File
@@ -16,8 +16,12 @@ pub fn maybe_pause(force_skip: bool) {
if force_skip || !should_pause() {
return;
}
use senbei_i18n::Localize;
use std::io::Write;
eprint!("\nPress Enter to exit…");
eprint!(
"{}",
senbei_i18n::Cli::PressEnter.localize(senbei_i18n::current())
);
let _ = std::io::stderr().flush();
let mut buf = String::new();
let _ = std::io::stdin().read_line(&mut buf);
+114 -57
View File
@@ -24,11 +24,14 @@
//! mistaken for inspected protected content.
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;
use serde::Serialize;
use sha2::{Digest as _, Sha256};
use senbei_i18n::{Cli, Lang, Localize, Message, Msg};
use senbei_engine::{
AttemptOutcome, LayoutKind, ProtectionEvidence, ProtectionProfile, RecognitionStatus,
RecoveryStatus, ValidationStatus,
@@ -211,7 +214,7 @@ pub struct ScanReport {
pub struct CompanionReport {
pub state: CompanionState,
pub path: Option<String>,
pub detail: Option<String>,
pub detail: Option<Message>,
/// Identity of the physical companion, distinct from the spliced view.
pub source: Option<Digest>,
}
@@ -275,7 +278,7 @@ pub struct ContainerReport {
pub struct StageReport {
pub stage: Stage,
pub status: StageStatus,
pub detail: Option<String>,
pub detail: Option<Message>,
pub duration_ms: Option<u64>,
}
@@ -289,7 +292,7 @@ impl StageReport {
}
}
pub fn detail(mut self, detail: impl Into<String>) -> Self {
pub fn detail(mut self, detail: impl Into<Message>) -> Self {
self.detail = Some(detail.into());
self
}
@@ -318,8 +321,8 @@ pub struct EntryReport {
pub provenance: Vec<String>,
/// Where the restored bytes were written (absent in dry-run/inspect).
pub output: Option<OutputFile>,
pub warnings: Vec<String>,
pub errors: Vec<String>,
pub warnings: Vec<Message>,
pub errors: Vec<Message>,
}
impl EntryReport {
@@ -373,8 +376,8 @@ pub struct InputReport {
/// Libraries whose decoded module was paired with this metadata input.
pub provenance: Vec<String>,
pub stages: Vec<StageReport>,
pub warnings: Vec<String>,
pub errors: Vec<String>,
pub warnings: Vec<Message>,
pub errors: Vec<Message>,
pub duration_ms: u64,
}
@@ -405,11 +408,11 @@ impl InputReport {
}
}
pub fn warning(&mut self, message: impl Into<String>) {
pub fn warning(&mut self, message: impl Into<Message>) {
self.warnings.push(message.into());
}
pub fn error(&mut self, message: impl Into<String>) {
pub fn error(&mut self, message: impl Into<Message>) {
self.errors.push(message.into());
}
}
@@ -454,8 +457,12 @@ pub struct Report {
pub inputs: Vec<InputReport>,
pub summary: SummaryReport,
/// Run-level failures that are not attributable to one input.
pub errors: Vec<String>,
pub errors: Vec<Message>,
pub duration_ms: u64,
/// The run was cancelled before every input was processed. Only a front
/// end can cancel, so the CLI's JSON never carries this field.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub cancelled: bool,
}
impl Report {
@@ -469,64 +476,75 @@ impl Report {
})
}
/// Plain summary in the same shape as [`crate::job::Summary::line`].
/// Plain English summary in the same shape as [`crate::job::Summary::line`].
pub fn summary_line(&self) -> String {
self.summary_line_with_palette(crate::ui::Palette::plain())
self.summary_line_in(crate::ui::Palette::plain(), Lang::En)
}
/// Console summary with colors for actual nonzero outcomes.
/// Console summary in the process language, with colors for actual
/// nonzero outcomes.
pub fn summary_line_with_palette(&self, palette: crate::ui::Palette) -> String {
use crate::ui::{Tone, count};
self.summary_line_in(palette, senbei_i18n::current())
}
/// The summary line in `lang`.
pub fn summary_line_in(&self, palette: crate::ui::Palette, lang: Lang) -> String {
let s = &self.summary;
let mut line = format!(
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
count(palette, s.recovered, Tone::Success),
count(palette, s.skipped, Tone::Muted),
count(palette, s.errors, Tone::Error),
count(palette, s.suspect, Tone::Warning),
count(palette, s.metadata, Tone::Success)
);
if s.packages > 0 {
line.push_str(&format!(
" · {} packages",
palette.paint(Tone::Value, s.packages)
));
}
line
crate::ui::summary_line(
palette,
lang,
[
s.recovered,
s.skipped,
s.errors,
s.suspect,
s.metadata,
s.packages,
],
)
}
/// Plain human-readable rendering, independent of the destination terminal.
/// Plain English rendering, independent of the destination terminal.
pub fn render_text(&self) -> String {
self.render_text_with_palette(crate::ui::Palette::plain())
self.render_text_in(crate::ui::Palette::plain(), Lang::En)
}
/// Human-readable rendering with an explicit console palette. Report data
/// and JSON remain unstyled; callers select the destination's color policy.
/// Console rendering in the process language. Report data and JSON remain
/// unstyled; callers select the destination's color policy.
pub fn render_text_with_palette(&self, palette: crate::ui::Palette) -> String {
self.render_text_in(palette, senbei_i18n::current())
}
/// Human-readable rendering in `lang`. Only the summary lines are
/// translated; structural research evidence stays English.
pub fn render_text_in(&self, palette: crate::ui::Palette, lang: Lang) -> String {
use crate::ui::Tone;
let mut text = String::new();
if let Some(scan) = self.scan {
text.push_str(&format!(
"{}: {} probed non-targets · {} walk errors · {} probe errors\n",
palette.paint(Tone::Heading, "scan"),
scan.non_target_skipped,
scan.walk_errors,
scan.probe_errors
"{}: {}\n",
palette.paint(Tone::Heading, Cli::ReportScanHeading.localize(lang)),
Cli::ReportScan {
skipped: scan.non_target_skipped,
walk_errors: scan.walk_errors,
probe_errors: scan.probe_errors,
}
.localize(lang)
));
if scan.walk_errors > 0 || scan.probe_errors > 0 {
text.push_str(&format!("{}: analysis is incomplete; some directory entries or selected files could not be examined\n", palette.paint(Tone::Warning, "warning")));
text.push_str(&format!(
"{}: {}\n",
palette.paint(Tone::Warning, Cli::Warning.localize(lang)),
Cli::ReportScanIncomplete.localize(lang)
));
}
}
for input in &self.inputs {
text.push_str(&text::render_input(input, palette));
text.push_str(&text::render_input(input, palette, lang));
}
for error in &self.errors {
text.push_str(&format!(
"{}: {error}\n",
palette.paint(Tone::Error, "error")
));
text.push_str(&crate::ui::error_lines(palette, lang, error));
}
text
}
@@ -539,7 +557,10 @@ pub struct Collector {
scan: Option<ScanReport>,
inputs: Vec<InputReport>,
summary: SummaryReport,
errors: Vec<String>,
errors: Vec<Message>,
observer: Option<Arc<dyn crate::observe::RunObserver>>,
cancel: Option<crate::observe::CancelToken>,
cancelled: bool,
}
impl Collector {
@@ -551,9 +572,41 @@ impl Collector {
inputs: Vec::new(),
summary: SummaryReport::default(),
errors: Vec::new(),
observer: None,
cancel: None,
cancelled: false,
}
}
/// Tell `observer` about each input as the run reaches and finishes it.
pub fn with_observer(mut self, observer: Arc<dyn crate::observe::RunObserver>) -> Self {
self.observer = Some(observer);
self
}
/// Stop the run at the next input once `cancel` is set.
pub fn with_cancel(mut self, cancel: crate::observe::CancelToken) -> Self {
self.cancel = Some(cancel);
self
}
pub(crate) fn observer(&self) -> Option<&Arc<dyn crate::observe::RunObserver>> {
self.observer.as_ref()
}
/// True once cancellation was requested. The report then records that the
/// run stopped early.
pub(crate) fn should_stop(&mut self) -> bool {
if self
.cancel
.as_ref()
.is_some_and(crate::observe::CancelToken::is_cancelled)
{
self.cancelled = true;
}
self.cancelled
}
pub fn mode(&self) -> Mode {
self.mode
}
@@ -585,9 +638,9 @@ impl Collector {
// Research inspection and dry runs keep their actual recovery
// outcomes, but never advertise temporary artifacts as outputs.
let discarded = if self.mode == Mode::Inspect {
"research inspection: no output file was retained"
Msg::OutputNotRetained
} else {
"dry run: the produced output was discarded"
Msg::DryRunDiscarded
};
if !input.outputs.is_empty() {
// The produced byte count is a real result of the attempt even
@@ -605,7 +658,7 @@ impl Collector {
for stage in &mut input.stages {
if stage.stage == Stage::OutputWrite {
stage.status = StageStatus::Skipped;
stage.detail = Some(discarded.to_owned());
stage.detail = Some(Message::new(discarded.clone()));
}
}
if !input
@@ -650,6 +703,9 @@ impl Collector {
InputStatus::Skipped => self.summary.skipped += 1,
InputStatus::Error => self.summary.errors += 1,
}
if let Some(observer) = &self.observer {
observer.input_finished(&input);
}
self.inputs.push(input);
}
@@ -658,7 +714,7 @@ impl Collector {
}
/// Record a run-level failure that is not attributable to one input.
pub fn push_error(&mut self, message: impl Into<String>) {
pub fn push_error(&mut self, message: impl Into<Message>) {
self.errors.push(message.into());
}
@@ -675,6 +731,7 @@ impl Collector {
summary: self.summary,
errors: self.errors,
duration_ms: self.started.elapsed().as_millis() as u64,
cancelled: self.cancelled,
}
}
}
@@ -715,17 +772,17 @@ pub(crate) fn android_recovered_profile() -> ProtectionProfile {
///
/// Recognition is inherited from the scan probe that selected the file; the
/// route is recorded as failed with the error that stopped it.
pub(crate) fn android_failed_profile(error: &str) -> ProtectionProfile {
pub(crate) fn android_failed_profile(error: &Message) -> ProtectionProfile {
let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::android(None));
profile.recognition = RecognitionStatus::Recognized;
profile.candidates = vec![senbei_engine::LayoutAttempt {
layout: LayoutKind::AndroidStaged,
outcome: AttemptOutcome::Failed,
warnings: Vec::new(),
errors: vec![error.to_owned()],
errors: vec![error.clone()],
}];
profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_owned());
profile.push_error(error.clone());
profile
}
@@ -773,7 +830,7 @@ pub(crate) fn metadata_unchanged_profile(
pub(crate) fn metadata_failed_profile(
identity: Option<senbei_metadata::MetadataIdentity>,
route: LayoutKind,
error: &str,
error: &Message,
) -> ProtectionProfile {
let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata(
identity.map(|identity| identity.raw_version),
@@ -785,10 +842,10 @@ pub(crate) fn metadata_failed_profile(
layout: route,
outcome: AttemptOutcome::Failed,
warnings: Vec::new(),
errors: vec![error.to_owned()],
errors: vec![error.clone()],
}];
profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_owned());
profile.push_error(error.clone());
profile.static_validation = ValidationStatus::NotRun;
profile
}
@@ -812,7 +869,7 @@ mod tests {
let profile = metadata_failed_profile(
senbei_metadata::identify(&header),
LayoutKind::MetadataStructural,
"transform did not validate",
&"transform did not validate".into(),
);
assert_eq!(profile.observed.metadata_version, Some(version));
assert_eq!(profile.recognition, RecognitionStatus::Blocked);
@@ -932,7 +989,7 @@ mod tests {
entry.analysis_incomplete = true;
entry
.errors
.push("resource ceiling prevented restoration".to_owned());
.push("resource ceiling prevented restoration".into());
input.entries.push(entry);
let mut collector = Collector::new(Mode::Inspect);
collector.push(input);
+264 -165
View File
@@ -1,8 +1,14 @@
//! Human-readable research reports. JSON retains the same underlying evidence.
//!
//! The summary lines of an input (target, recognition, routes, stages, and
//! findings) follow the reader's language. The structural research sections
//! (PE layout, recovery trace, Android and metadata evidence) are technical
//! dumps and stay English, like the JSON they mirror.
use std::fmt::{self, Write};
use senbei_engine::windows::{ResearchTrace, TraceValue, WindowsInspection};
use senbei_i18n::{Cli, Lang, Localize, Message, Term};
use serde::Serialize;
use serde_json::Value;
@@ -12,15 +18,26 @@ use crate::ui::{Painted, Palette, Tone};
struct Text {
contents: String,
palette: Palette,
lang: Lang,
}
impl Text {
#[cfg(test)]
fn new(palette: Palette) -> Self {
Self::in_language(palette, Lang::En)
}
fn in_language(palette: Palette, lang: Lang) -> Self {
Self {
contents: String::new(),
palette,
lang,
}
}
fn say(&self, line: Cli) -> String {
line.localize(self.lang).into_owned()
}
}
impl Write for Text {
@@ -34,8 +51,12 @@ fn status(palette: Palette, value: &impl Serialize) -> Painted<String> {
}
fn status_text(palette: Palette, value: String) -> Painted<String> {
let normalized = value.replace('_', " ");
let tone = match normalized.as_str() {
palette.paint(tone_of(&value), value)
}
/// The tone of a report value, judged by its English meaning.
fn tone_of(value: &str) -> Tone {
match value.replace('_', " ").as_str() {
"ok" | "clean" | "succeeded" | "restored" | "unchanged" | "accepted" | "matched"
| "validated" => Tone::Success,
"error" | "failed" | "unreadable" | "rejected" => Tone::Error,
@@ -45,8 +66,7 @@ fn status_text(palette: Palette, value: String) -> Painted<String> {
"skipped" | "not run" | "not attempted" | "unavailable" | "absent" | "duplicate"
| "not recognized" => Tone::Muted,
_ => Tone::Value,
};
palette.paint(tone, value)
}
}
fn label(value: &impl Serialize) -> String {
@@ -57,6 +77,23 @@ fn label(value: &impl Serialize) -> String {
}
}
/// [`label`] in `lang`, for the values the catalog names.
fn term(lang: Lang, value: &impl Serialize) -> String {
if let Ok(Value::String(wire)) = serde_json::to_value(value)
&& let Some(term) = Term::from_value(&wire)
{
return term.localize(lang).into_owned();
}
label(value)
}
/// [`status`] in the reader's language: toned by the English value.
fn term_status(text: &Text, value: &impl Serialize) -> String {
text.palette
.paint(tone_of(&label(value)), term(text.lang, value))
.to_string()
}
fn hex<T: Into<u64>>(palette: Palette, value: Option<T>) -> Painted<String> {
let tone = if value.is_some() {
Tone::Value
@@ -83,22 +120,72 @@ fn diagnostic(text: &mut Text, indent: &str, kind: &str, message: &str) {
}
}
pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
let mut text = Text::new(palette);
let _ = writeln!(text, "{}", palette.paint(Tone::Heading, &input.path));
if input.analysis_incomplete {
/// How a finding is labelled in the summary part of a report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Finding {
Warning,
Error,
Reason,
Detail,
}
impl Finding {
fn label(self) -> Cli {
match self {
Self::Warning => Cli::DiagnosticWarning,
Self::Error => Cli::DiagnosticError,
Self::Reason => Cli::DiagnosticReason,
Self::Detail => Cli::DiagnosticDetail,
}
}
fn tone(self) -> Tone {
match self {
Self::Error => Tone::Error,
Self::Warning | Self::Reason => Tone::Warning,
Self::Detail => Tone::Muted,
}
}
}
/// A finding in the reader's language. When the translation does not show
/// everything the English said, the English follows on its own muted line.
fn finding(text: &mut Text, indent: &str, kind: Finding, message: &Message) {
let palette = text.palette;
let label = text.say(kind.label());
for line in message.localized(text.lang).lines() {
let _ = writeln!(
text,
" {}: I/O, resource limits or infrastructure prevented the requested work",
palette.paint(Tone::Error, "analysis incomplete")
"{indent}{}: {line}",
palette.paint(kind.tone(), &label)
);
}
if let Some(source) = &input.source {
let _ = writeln!(
text,
" source: {} bytes (0x{:X})",
source.size, source.size
if let Some(english) = message.detail(text.lang) {
let label = text.say(Cli::DiagnosticEnglish);
for line in english.lines() {
let _ = writeln!(
text,
"{indent} {}",
palette.paint(Tone::Muted, format!("{label}: {line}"))
);
}
}
}
pub(super) fn render_input(input: &InputReport, palette: Palette, lang: Lang) -> String {
let mut text = Text::in_language(palette, lang);
let _ = writeln!(text, "{}", palette.paint(Tone::Heading, &input.path));
if input.analysis_incomplete {
let line = format!(
" {}: {}",
palette.paint(Tone::Error, text.say(Cli::AnalysisIncomplete)),
text.say(Cli::AnalysisIncompleteInput)
);
let _ = writeln!(text, "{line}");
}
if let Some(source) = &input.source {
let line = text.say(Cli::Source { size: source.size });
let _ = writeln!(text, " {line}");
let _ = writeln!(
text,
" SHA-256: {}",
@@ -107,72 +194,73 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
}
if let Some(profile) = &input.profile {
let target = &profile.observed;
let _ = writeln!(
text,
" target: {} · {} · {}",
label(&target.platform),
target
let line = text.say(Cli::Target {
platform: term(lang, &target.platform),
format: target
.format
.as_ref()
.map(label)
.unwrap_or_else(|| "format unavailable".to_owned()),
target
.map(|format| term(lang, format))
.unwrap_or_else(|| text.say(Cli::FormatUnavailable)),
kind: target
.kind
.as_ref()
.map(label)
.unwrap_or_else(|| "kind not applicable or unavailable".to_owned())
);
let _ = writeln!(
text,
" protection recognition: {}",
status(palette, &profile.recognition)
);
.map(|kind| term(lang, kind))
.unwrap_or_else(|| text.say(Cli::KindUnavailable)),
});
let _ = writeln!(text, " {line}");
let line = text.say(Cli::ProtectionRecognition {
status: term_status(&text, &profile.recognition),
});
let _ = writeln!(text, " {line}");
if !profile.evidence.is_empty() {
let evidence = profile
.evidence
.iter()
.map(label)
.map(|evidence| term(lang, evidence))
.collect::<Vec<_>>()
.join(", ");
let _ = writeln!(text, " evidence: {evidence}");
let line = text.say(Cli::Evidence { evidence });
let _ = writeln!(text, " {line}");
}
for candidate in &profile.candidates {
let _ = writeln!(
text,
" route {}: {}",
palette.paint(Tone::Label, label(&candidate.layout)),
status(palette, &candidate.outcome)
);
let line = text.say(Cli::Route {
route: palette
.paint(Tone::Label, term(lang, &candidate.layout))
.to_string(),
outcome: term_status(&text, &candidate.outcome),
});
let _ = writeln!(text, " {line}");
for message in &candidate.warnings {
diagnostic(&mut text, " ", "warning", message);
finding(&mut text, " ", Finding::Warning, message);
}
for message in &candidate.errors {
diagnostic(&mut text, " ", "reason", message);
finding(&mut text, " ", Finding::Reason, message);
}
}
if let Some(selected) = profile.selected {
let _ = writeln!(
text,
" selected route: {}",
palette.paint(Tone::Success, label(&selected))
);
let line = text.say(Cli::SelectedRoute {
route: palette
.paint(Tone::Success, term(lang, &selected))
.to_string(),
});
let _ = writeln!(text, " {line}");
}
let _ = writeln!(
text,
" static recovery: {}",
status(palette, &profile.recovery)
);
let _ = writeln!(
text,
" output static validation: {}",
status(palette, &profile.static_validation)
);
let line = text.say(Cli::StaticRecovery {
status: term_status(&text, &profile.recovery),
});
let _ = writeln!(text, " {line}");
let line = text.say(Cli::OutputValidation {
status: term_status(&text, &profile.static_validation),
});
let _ = writeln!(text, " {line}");
}
if let Some(companion) = &input.companion {
let line = text.say(Cli::Companion {
state: term_status(&text, &companion.state),
});
let _ = writeln!(
text,
" companion: {}{}",
status(palette, &companion.state),
" {line}{}",
companion
.path
.as_ref()
@@ -180,27 +268,24 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
.unwrap_or_default()
);
if let Some(source) = &companion.source {
let _ = writeln!(
text,
" {} bytes · SHA-256 {}",
source.size, source.sha256
);
let line = text.say(Cli::CompanionIdentity {
size: source.size,
sha256: source.sha256.clone(),
});
let _ = writeln!(text, " {line}");
}
if let Some(detail) = &companion.detail {
diagnostic(&mut text, " ", "detail", detail);
finding(&mut text, " ", Finding::Detail, detail);
}
}
if let Some(research) = &input.research {
let _ = writeln!(
text,
" analysis input view: {}",
label(&research.input_view)
);
let line = text.say(Cli::InputView {
view: term(lang, &research.input_view),
});
let _ = writeln!(text, " {line}");
if research.input_view == super::ResearchInputView::SplicedCompanion {
let _ = writeln!(
text,
" file offsets below 0x1000 address the stub; offsets at/above 0x1000 address companion offset (file offset - 0x1000)"
);
let line = text.say(Cli::InputViewSplicedNote);
let _ = writeln!(text, " {line}");
}
render_windows(&mut text, "protected input", &research.input);
render_trace(&mut text, &research.trace);
@@ -227,67 +312,69 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
}
}
if let Some(metadata) = &input.metadata {
let _ = writeln!(
text,
" IL2CPP metadata version: {} · layout definition {}",
metadata.raw_version,
label(&metadata.layout)
);
let _ = writeln!(
text,
" seeded method tokens: {}",
metadata.capabilities.seeded_method_tokens
);
let _ = writeln!(
text,
" structural method tokens: {}",
metadata.capabilities.structural_method_tokens
);
let _ = writeln!(
text,
" method-index restoration: {} · application context required: {}",
metadata.capabilities.method_index_restore,
metadata.capabilities.method_index_requires_context
);
let identity = text.say(Cli::MetadataIdentity {
version: metadata.raw_version,
layout: term(lang, &metadata.layout),
});
let _ = writeln!(text, " {identity}");
let capabilities = &metadata.capabilities;
for line in [
Cli::SeededTokens {
value: capabilities.seeded_method_tokens,
},
Cli::StructuralTokens {
value: capabilities.structural_method_tokens,
},
Cli::MethodIndexRestore {
value: capabilities.method_index_restore,
context: capabilities.method_index_requires_context,
},
] {
let line = text.say(line);
let _ = writeln!(text, " {line}");
}
}
if let Some(container) = &input.container {
let _ = writeln!(
text,
" container: {} · {} entries · {} manifests",
container.kind,
container.entry_count,
container.manifests.len()
);
let line = text.say(Cli::Container {
kind: container.kind.clone(),
entries: container.entry_count,
manifests: container.manifests.len(),
});
let _ = writeln!(text, " {line}");
for manifest in &container.manifests {
let _ = writeln!(
text,
" manifest {} → {} {}",
manifest.source,
manifest.package.as_deref().unwrap_or("<unnamed>"),
manifest.version.as_deref().unwrap_or("")
);
let line = text.say(Cli::Manifest {
source: manifest.source.clone(),
package: manifest
.package
.clone()
.unwrap_or_else(|| text.say(Cli::Unnamed)),
version: manifest.version.clone().unwrap_or_default(),
});
let _ = writeln!(text, " {line}");
}
for entry in &container.candidate_entries {
let _ = writeln!(text, " candidate: {entry}");
let line = text.say(Cli::Candidate {
entry: entry.clone(),
});
let _ = writeln!(text, " {line}");
}
}
if let Some(research) = &input.android_research {
render_android(&mut text, " ", research);
}
if let Some(research) = &input.metadata_research {
let _ = writeln!(
text,
" {}:",
palette.paint(Tone::Heading, "metadata transform evidence")
);
let heading = text.say(Cli::MetadataEvidence);
let _ = writeln!(text, " {}:", palette.paint(Tone::Heading, heading));
render_tree(&mut text, " ", research);
}
for entry in &input.entries {
let line = text.say(Cli::Entry {
name: palette.paint(Tone::Label, &entry.name).to_string(),
status: term_status(&text, &entry.status),
});
let _ = writeln!(
text,
" entry {}: {}{}",
palette.paint(Tone::Label, &entry.name),
status(palette, &entry.status),
" {line}{}",
entry
.output
.as_ref()
@@ -295,90 +382,102 @@ pub(super) fn render_input(input: &InputReport, palette: Palette) -> String {
.unwrap_or_default()
);
if entry.analysis_incomplete {
let _ = writeln!(
text,
" {}: requested entry analysis could not finish",
palette.paint(Tone::Error, "analysis incomplete")
let line = format!(
" {}: {}",
palette.paint(Tone::Error, text.say(Cli::AnalysisIncomplete)),
text.say(Cli::AnalysisIncompleteEntry)
);
let _ = writeln!(text, "{line}");
}
if let Some(layout) = entry.layout {
let _ = writeln!(text, " route: {}", label(&layout));
let line = text.say(Cli::EntryRoute {
route: term(lang, &layout),
});
let _ = writeln!(text, " {line}");
}
if let Some(version) = entry.metadata_version {
let _ = writeln!(text, " metadata version: {version}");
let line = text.say(Cli::EntryMetadataVersion { version });
let _ = writeln!(text, " {line}");
}
if let Some(remapped) = entry.remapped {
let _ = writeln!(text, " remapped method fields: {remapped}");
let line = text.say(Cli::EntryRemapped { remapped });
let _ = writeln!(text, " {line}");
}
for source in &entry.provenance {
let _ = writeln!(text, " module context source: {source}");
let line = text.say(Cli::ModuleContextSource {
source: source.clone(),
});
let _ = writeln!(text, " {line}");
}
for message in &entry.warnings {
diagnostic(&mut text, " ", "warning", message);
finding(&mut text, " ", Finding::Warning, message);
}
for message in &entry.errors {
diagnostic(&mut text, " ", "error", message);
finding(&mut text, " ", Finding::Error, message);
}
if let Some(research) = &entry.android_research {
render_android(&mut text, " ", research);
}
if let Some(research) = &entry.metadata_research {
let _ = writeln!(
text,
" {}:",
palette.paint(Tone::Heading, "metadata transform evidence")
);
let heading = text.say(Cli::MetadataEvidence);
let _ = writeln!(text, " {}:", palette.paint(Tone::Heading, heading));
render_tree(&mut text, " ", research);
}
}
for source in &input.provenance {
let _ = writeln!(text, " module context source: {source}");
let line = text.say(Cli::ModuleContextSource {
source: source.clone(),
});
let _ = writeln!(text, " {line}");
}
for stage in &input.stages {
let line = text.say(Cli::StageLine {
stage: palette
.paint(Tone::Label, term(lang, &stage.stage))
.to_string(),
status: term_status(&text, &stage.status),
});
let _ = writeln!(
text,
" stage {}: {}{}",
palette.paint(Tone::Label, label(&stage.stage)),
status(palette, &stage.status),
" {line}{}",
stage
.duration_ms
.map(|elapsed| format!(" · {elapsed} ms"))
.unwrap_or_default()
);
if let Some(detail) = &stage.detail {
diagnostic(&mut text, " ", "detail", detail);
finding(&mut text, " ", Finding::Detail, detail);
}
}
// The profile repeats input-level findings; each is shown once.
let mut seen = std::collections::BTreeSet::new();
for (kind, messages) in [("warning", &input.warnings), ("error", &input.errors)] {
for message in messages {
if seen.insert((kind, message.as_str())) {
diagnostic(&mut text, " ", kind, message);
}
}
}
let mut findings = vec![
(Finding::Warning, &input.warnings),
(Finding::Error, &input.errors),
];
if let Some(profile) = &input.profile {
for (kind, messages) in [("warning", &profile.warnings), ("error", &profile.errors)] {
for message in messages {
if seen.insert((kind, message.as_str())) {
diagnostic(&mut text, " ", kind, message);
}
findings.push((Finding::Warning, &profile.warnings));
findings.push((Finding::Error, &profile.errors));
}
for (kind, messages) in findings {
for message in messages {
if seen.insert((kind, message.text())) {
finding(&mut text, " ", kind, message);
}
}
}
if let Some(recovered) = &input.recovered {
let _ = writeln!(
text,
" recovered: {} bytes · SHA-256 {}",
recovered.size, recovered.sha256
);
let line = text.say(Cli::Recovered {
size: recovered.size,
sha256: recovered.sha256.clone(),
});
let _ = writeln!(text, " {line}");
}
let _ = writeln!(
text,
" inspection status: {} · {} ms",
status(palette, &input.status),
input.duration_ms
);
let line = text.say(Cli::InspectionStatus {
status: term_status(&text, &input.status),
ms: input.duration_ms,
});
let _ = writeln!(text, " {line}");
text.contents
}
@@ -921,8 +1020,8 @@ mod tests {
StageReport::new(Stage::Recovery, StageStatus::Failed)
.detail("parameters were unavailable"),
);
let text = render_input(&input, Palette::plain());
let colored = render_input(&input, Palette::colored());
let text = render_input(&input, Palette::plain(), Lang::En);
let colored = render_input(&input, Palette::colored(), Lang::En);
assert!(colored.contains('\x1b'));
assert_eq!(strip_styles(&colored), text);
for fact in [
@@ -991,8 +1090,8 @@ mod tests {
});
input.metadata_research =
Some(serde_json::json!({"tried_seeds": [0x5678], "route": "seeded"}));
let text = render_input(&input, Palette::plain());
let colored = render_input(&input, Palette::colored());
let text = render_input(&input, Palette::plain(), Lang::En);
let colored = render_input(&input, Palette::colored(), Lang::En);
assert!(colored.contains('\x1b'));
assert_eq!(strip_styles(&colored), text);
for fact in [
+135 -9
View File
@@ -1,6 +1,7 @@
use indicatif::{ProgressBar, ProgressStyle};
use owo_colors::Style;
use senbei_engine::{IntegrityReport, Kind};
use senbei_i18n::{Cli, Lang, Localize, Message, Step};
use std::cell::Cell;
use std::fmt::{self, Display};
use std::io::IsTerminal;
@@ -101,6 +102,111 @@ pub(crate) fn count(palette: Palette, value: usize, nonzero: Tone) -> Painted<us
palette.paint(if value == 0 { Tone::Muted } else { nonzero }, value)
}
/// The run summary in `lang`: unpacked, skipped, errors, suspect, metadata,
/// and packages (shown only when nonzero), each colored when nonzero.
pub(crate) fn summary_line(
palette: Palette,
lang: Lang,
[unpacked, skipped, errors, suspect, metadata, packages]: [usize; 6],
) -> String {
let mut line = Cli::Summary {
unpacked: count(palette, unpacked, Tone::Success).to_string(),
skipped: count(palette, skipped, Tone::Muted).to_string(),
errors: count(palette, errors, Tone::Error).to_string(),
suspect: count(palette, suspect, Tone::Warning).to_string(),
metadata: count(palette, metadata, Tone::Success).to_string(),
}
.localize(lang)
.into_owned();
if packages > 0 {
line.push_str(
&Cli::SummaryPackages {
packages: palette.paint(Tone::Value, packages).to_string(),
}
.localize(lang),
);
}
line
}
/// The muted line that shows the English a translated message came from.
fn english_line(palette: Palette, lang: Lang, english: &str) -> String {
palette
.paint(
Tone::Muted,
format!("{}: {english}", Cli::DiagnosticEnglish.localize(lang)),
)
.to_string()
}
/// `error: <message>` in `lang`, newline-terminated. When the translation
/// does not show everything the English said, the English follows.
pub(crate) fn error_lines(palette: Palette, lang: Lang, message: &Message) -> String {
let mut lines = format!(
"{}: {}\n",
palette.paint(Tone::Error, Cli::Error.localize(lang)),
message.localized(lang)
);
if let Some(english) = message.detail(lang) {
lines.push_str(&format!(" {}\n", english_line(palette, lang, english)));
}
lines
}
/// Print `error: <message>` to stderr in the process language.
pub fn print_error(message: &Message) {
eprint!(
"{}",
error_lines(Palette::stderr(), senbei_i18n::current(), message)
);
}
/// Print `error: <error chain>` to stderr in the process language.
pub fn print_anyhow(error: &anyhow::Error) {
print_error(&crate::message::of_error(error));
}
/// Print `error: <what>: <error chain>` to stderr in the process language.
pub(crate) fn print_error_about(what: Cli, error: &anyhow::Error) {
let lang = senbei_i18n::current();
let palette = Palette::stderr();
let message = crate::message::of_error(error);
eprintln!(
"{}: {}: {}",
palette.paint(Tone::Error, Cli::Error.localize(lang)),
what.localize(lang),
message.localized(lang)
);
if let Some(english) = message.detail(lang) {
eprintln!(" {}", english_line(palette, lang, english));
}
}
/// The verbose `Write to <dest>` line after an output was written, with the
/// destination colored when `painted`. A run with an observer receives it as
/// a progress event instead.
pub(crate) fn write_to(dest: &Path, painted: bool) {
let event = senbei_engine::progress::Event::Step {
step: Step::WriteTo {
dest: dest.display().to_string(),
},
position: None,
};
if !senbei_engine::progress::emit(&event) {
let dest = if painted {
Palette::stdout()
.paint(Tone::Value, dest.display())
.to_string()
} else {
dest.display().to_string()
};
println!(
"{}",
Step::WriteTo { dest }.localize(senbei_i18n::current())
);
}
}
fn color_enabled(mode: ColorMode, terminal: bool, no_color: bool, dumb: bool) -> bool {
match mode {
ColorMode::Auto => terminal && !no_color && !dumb,
@@ -220,12 +326,15 @@ pub fn metadata(bar: &ProgressBar, quiet: bool, rel: &Path, remapped: usize, des
return;
}
let palette = Palette::stdout();
let line = Cli::MetadataLine {
rel: palette.paint(Tone::Label, rel.display()).to_string(),
dest: palette.paint(Tone::Value, dest.display()).to_string(),
remapped: palette.paint(Tone::Value, remapped).to_string(),
};
let msg = format!(
"{} metadata {} -> {} ({} method fields remapped)",
"{} {}",
palette.paint(Tone::Success, "✓"),
palette.paint(Tone::Label, rel.display()),
palette.paint(Tone::Value, dest.display()),
palette.paint(Tone::Value, remapped)
line.localize(senbei_i18n::current())
);
bar.suspend(|| println!("{msg}"));
}
@@ -236,11 +345,17 @@ pub fn err(bar: &ProgressBar, quiet: bool, rel: &Path, e: &anyhow::Error) {
return;
}
let palette = Palette::stderr();
let msg = format!(
"{} {} {e:#}",
let lang = senbei_i18n::current();
let message = crate::message::of_error(e);
let mut msg = format!(
"{} {} {}",
palette.paint(Tone::Error, "✗"),
palette.paint(Tone::Label, rel.display())
palette.paint(Tone::Label, rel.display()),
message.localized(lang)
);
if let Some(english) = message.detail(lang) {
msg.push_str(&format!("\n {}", english_line(palette, lang, english)));
}
bar.suspend(|| eprintln!("{msg}"));
}
@@ -251,16 +366,27 @@ pub fn suspect(bar: &ProgressBar, quiet: bool, rel: &Path, report: &IntegrityRep
return;
}
let palette = Palette::stderr();
let lang = senbei_i18n::current();
let msg = format!(
"{} {} {}: {}",
palette.paint(Tone::Warning, "!"),
palette.paint(Tone::Label, rel.display()),
palette.paint(Tone::Warning, "integrity check failed"),
report.issues.join("; ")
palette.paint(Tone::Warning, Cli::IntegrityFailed.localize(lang)),
issues(report, lang)
);
bar.suspend(|| eprintln!("{msg}"));
}
/// The static check's findings in `lang`, separated as in the log.
pub(crate) fn issues(report: &IntegrityReport, lang: Lang) -> String {
report
.issues
.iter()
.map(|issue| issue.localized(lang))
.collect::<Vec<_>>()
.join("; ")
}
#[cfg(test)]
mod tests {
use super::*;
+1 -1
View File
@@ -672,7 +672,7 @@ pub fn unpack_one_v(
}
write_atomic(dest, &out)?;
if verbose {
println!("Write to {}", dest.display());
crate::ui::write_to(dest, false);
}
Ok((kind, report))
}