use crate::cli::format_result;
use crate::core::MAX_EXPR_LEN;
use crate::core::evaluate;
use crate::core::{EvalContext, EvalResult};
use crate::i18n::I18n;
use rayon::prelude::*;
use std::io::{self, BufRead, Read};
use std::time::Instant;
const MAX_BATCH_COUNT: usize = 1000;
pub struct BatchProcessor;
impl BatchProcessor {
#[allow(dead_code)] pub fn run(path: &str, ctx: &EvalContext, json: bool, i18n: &I18n) -> i32 {
Self::run_with_cache(path, ctx, json, i18n, crate::CacheManager::new())
}
pub fn run_with_cache(
path: &str,
ctx: &EvalContext,
json: bool,
i18n: &I18n,
cache: crate::CacheManager,
) -> i32 {
let start = Instant::now();
let entries = match read_and_validate_entries(path, i18n) {
Ok(e) => e,
Err(code) => return code,
};
let results = evaluate_entries(&entries, ctx, &cache);
output_results(&results, json, i18n);
print_summary(&results, start.elapsed(), i18n);
let err_count = results.iter().filter(|r| r.result.is_err()).count();
if err_count > 0 { 1 } else { 0 }
}
}
fn read_and_validate_entries(path: &str, i18n: &I18n) -> Result<Vec<BatchEntry>, i32> {
let lines = match read_lines(path) {
Ok(lines) => lines,
Err(e) => {
eprintln!(
"{}",
i18n.tf("batch.read_failed", &[("error", &e.to_string())])
);
return Err(2);
}
};
let mut entries: Vec<BatchEntry> = Vec::new();
for (line_no, raw) in lines.iter() {
let trimmed = raw.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if trimmed.len() > MAX_EXPR_LEN {
eprintln!(
"{}",
i18n.tf(
"batch.line_too_long",
&[
("line", &line_no.to_string()),
("max", &MAX_EXPR_LEN.to_string()),
("actual", &trimmed.len().to_string())
]
)
);
return Err(2);
}
entries.push(BatchEntry {
line_no: *line_no,
expr: trimmed.to_string(),
});
}
if entries.is_empty() {
eprintln!("{}", i18n.t("batch.no_expressions"));
return Err(2);
}
if entries.len() > MAX_BATCH_COUNT {
eprintln!(
"{}",
i18n.tf(
"batch.count_exceeds",
&[
("count", &entries.len().to_string()),
("max", &MAX_BATCH_COUNT.to_string())
]
)
);
return Err(2);
}
Ok(entries)
}
fn evaluate_entries(
entries: &[BatchEntry],
ctx: &EvalContext,
cache: &crate::CacheManager,
) -> Vec<BatchResult> {
entries
.par_iter()
.map(|entry| {
let result = evaluate(&entry.expr, ctx, None, cache);
BatchResult {
line_no: entry.line_no,
expr: entry.expr.clone(),
result,
}
})
.collect()
}
fn output_results(results: &[BatchResult], json: bool, i18n: &I18n) {
if json {
let mut items: Vec<String> = Vec::with_capacity(results.len());
for r in results {
let entry = match &r.result {
Ok((result, domain, hit, fmt_prec)) => {
let value = format_result(result, *fmt_prec);
serde_json::json!({
"line": r.line_no,
"expr": r.expr,
"result": value,
"domain": domain,
"cache": if *hit { "hit" } else { "miss" },
})
}
Err(e) => serde_json::json!({
"line": r.line_no,
"expr": r.expr,
"error": e.to_string(),
}),
};
items.push(entry.to_string());
}
println!("[");
println!("{}", items.join(",\n"));
println!("]");
} else {
for r in results {
match &r.result {
Ok((result, domain, hit, fmt_prec)) => {
let value = format_result(result, *fmt_prec);
let cached_str = if *hit {
i18n.t("label.cached_suffix").to_string()
} else {
String::new()
};
println!(
"{}",
i18n.tf(
"batch.text_result",
&[
("line", &r.line_no.to_string()),
("expr", &r.expr),
("value", &value),
("domain", domain),
("cached", &cached_str)
]
)
);
}
Err(e) => {
eprintln!(
"{}",
i18n.tf(
"batch.text_error",
&[
("line", &r.line_no.to_string()),
("expr", &r.expr),
("error", &e.localized_display(i18n))
]
)
);
}
}
}
}
}
fn print_summary(results: &[BatchResult], elapsed: std::time::Duration, i18n: &I18n) {
let total = results.len();
let ok_count = results.iter().filter(|r| r.result.is_ok()).count();
let err_count = total - ok_count;
let cache_hits = results
.iter()
.filter(|r| {
r.result
.as_ref()
.map(|(_, _, hit, _)| *hit)
.unwrap_or(false)
})
.count();
eprintln!(
"{}",
i18n.tf(
"batch.summary",
&[
("total", &total.to_string()),
("ok", &ok_count.to_string()),
("errors", &err_count.to_string()),
("hits", &cache_hits.to_string()),
("elapsed", &format!("{:?}", elapsed))
]
)
);
}
struct BatchEntry {
line_no: usize,
expr: String,
}
struct BatchResult {
line_no: usize,
expr: String,
result: Result<(EvalResult, String, bool, Option<usize>), crate::CalcError>,
}
fn read_lines(path: &str) -> io::Result<Vec<(usize, String)>> {
let mut lines: Vec<(usize, String)> = Vec::new();
if path == "-" {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
for (i, line) in input.lines().enumerate() {
let line = if i == 0 {
line.strip_prefix('\u{FEFF}').unwrap_or(line)
} else {
line
};
lines.push((i + 1, line.to_string()));
}
} else {
let file = std::fs::File::open(path)?;
let reader = io::BufReader::new(file);
for (i, line) in reader.lines().enumerate() {
let line = line?;
let line = if i == 0 {
line.strip_prefix('\u{FEFF}').unwrap_or(&line).to_string()
} else {
line
};
lines.push((i + 1, line));
}
}
Ok(lines)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn test_read_lines_from_file() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "2+3").unwrap();
writeln!(tmp, "# comment").unwrap();
writeln!(tmp, "sin(0)").unwrap();
tmp.flush().unwrap();
let lines = read_lines(tmp.path().to_str().unwrap()).unwrap();
assert_eq!(lines.len(), 3);
assert_eq!(lines[0].0, 1);
assert_eq!(lines[0].1, "2+3");
assert_eq!(lines[2].1, "sin(0)");
}
#[test]
fn test_batch_json_output_is_valid_json() {
let sample = serde_json::json!({
"line": 1,
"expr": "a\u{0001}b\"c",
"result": "1",
"domain": "arithmetic",
"cache": "miss",
});
let serialized = sample.to_string();
let round: serde_json::Value =
serde_json::from_str(&serialized).expect("序列化后必须可反序列化");
assert_eq!(round["expr"], "a\u{0001}b\"c", "控制字符与引号应无损往返");
}
#[test]
fn test_batch_run_basic_expressions() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "2+3").unwrap();
writeln!(tmp, "4*5").unwrap();
tmp.flush().unwrap();
let ctx = EvalContext::new();
let code = BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, false, &I18n::default());
assert_eq!(code, 0);
}
#[test]
fn test_batch_run_comment_skipped() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "# this is a comment").unwrap();
writeln!(tmp).unwrap();
writeln!(tmp, "1+1").unwrap();
tmp.flush().unwrap();
let ctx = EvalContext::new();
let code = BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, false, &I18n::default());
assert_eq!(code, 0);
}
#[test]
fn test_batch_run_empty_file_rejected() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "# only comment").unwrap();
tmp.flush().unwrap();
let ctx = EvalContext::new();
let code = BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, false, &I18n::default());
assert_eq!(code, 2);
}
#[test]
fn test_batch_run_with_error() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "2+3").unwrap();
writeln!(tmp, "2++3").unwrap(); writeln!(tmp, "4*5").unwrap();
tmp.flush().unwrap();
let ctx = EvalContext::new();
let code = BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, false, &I18n::default());
assert_eq!(code, 1);
}
#[test]
fn test_batch_run_json_output() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "2+3").unwrap();
tmp.flush().unwrap();
let ctx = EvalContext::new();
let code = BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, true, &I18n::default());
assert_eq!(code, 0);
}
#[test]
fn test_batch_run_order_preserved() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "1").unwrap();
writeln!(tmp, "2").unwrap();
writeln!(tmp, "3").unwrap();
tmp.flush().unwrap();
let ctx = EvalContext::new();
let _code =
BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, false, &I18n::default());
}
#[test]
fn test_batch_nonexistent_file() {
let ctx = EvalContext::new();
let code = BatchProcessor::run(
"/nonexistent/path/to/file.txt",
&ctx,
false,
&I18n::default(),
);
assert_eq!(code, 2);
}
#[test]
fn test_batch_line_exceeds_max_length() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
let long_line = "1+".repeat(2049); writeln!(tmp, "{}", long_line).unwrap();
tmp.flush().unwrap();
let ctx = EvalContext::new();
let code = BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, false, &I18n::default());
assert_eq!(code, 2);
}
#[test]
fn test_batch_count_exceeds_maximum() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
for _ in 0..1001 {
writeln!(tmp, "1+1").unwrap();
}
tmp.flush().unwrap();
let ctx = EvalContext::new();
let code = BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, false, &I18n::default());
assert_eq!(code, 2);
}
#[test]
fn test_batch_json_output_with_error() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
writeln!(tmp, "2+3").unwrap();
writeln!(tmp, "2++3").unwrap(); tmp.flush().unwrap();
let ctx = EvalContext::new();
let code = BatchProcessor::run(tmp.path().to_str().unwrap(), &ctx, true, &I18n::default());
assert_eq!(code, 1);
}
}