use std::path::{Path, PathBuf};
use crate::tools::shell::{ProgramOutcome, Stop, run_internal_program_outcome};
mod install;
pub(crate) const MAX_ANSWER_BYTES: usize = crate::util::TOOL_OUTPUT_BUDGET_BYTES;
const NOTE_ROOM: usize = 96;
const MAX_FAILURE_BYTES: usize = 2_000;
pub(crate) struct Step {
pub(crate) command: String,
pub(crate) params: Option<serde_json::Value>,
}
#[derive(Debug)]
pub(crate) struct BatchReport {
pub(crate) answer: String,
pub(crate) partial: bool,
}
pub use install::install_on_start;
pub(crate) async fn run_chain(
input: Option<&Path>,
canvas: Option<&serde_json::Value>,
chain: &[Step],
output: &Path,
) -> anyhow::Result<String> {
drive(&chain_args(input, canvas, chain, output)).await
}
pub(crate) async fn inspect(input: &Path) -> anyhow::Result<String> {
let answer = drive(&inspect_args(input)).await?;
Ok(inspection_answer(&answer, input))
}
fn format_field(input: &Path) -> String {
match crate::util::extension_of(input) {
Some(format) => format!("{format} (from the file name)"),
None => "unknown (the file name has no extension)".to_string(),
}
}
fn inspection_answer(answer: &str, input: &Path) -> String {
let format = format_field(input);
let (value, beside) = first_json(answer);
let Some(serde_json::Value::Object(mut fields)) = value else {
if answer.contains(crate::util::TRUNCATED_MIDDLE) {
return format!("… the inspection was too large to capture whole; format: {format}");
}
let line = format!("format: {format}");
let text = capped_lines(
answer.trim_end(),
MAX_ANSWER_BYTES.saturating_sub(line.len() + 1),
"line",
"",
);
return if text.is_empty() {
line
} else {
format!("{text}\n{line}")
};
};
fields.insert("format".to_string(), serde_json::Value::String(format));
let beside = capped_lines(beside, MAX_ANSWER_BYTES / 4, "line", "");
let room = MAX_ANSWER_BYTES.saturating_sub(beside.len() + 1);
let document = capped_document(fields, room);
if beside.is_empty() {
document
} else {
format!("{document}\n{beside}")
}
}
fn capped_document(fields: serde_json::Map<String, serde_json::Value>, room: usize) -> String {
let total = fields.len();
if let Ok(text) = serde_json::to_string(&fields)
&& text.len() <= room
{
return text;
}
let mut facts = serde_json::Map::new();
let mut arrays: Vec<(String, Vec<serde_json::Value>)> = Vec::new();
for (name, value) in fields {
match value {
serde_json::Value::Array(entries) => arrays.push((name, entries)),
fact => {
facts.insert(name, fact);
}
}
}
if !fits(&facts, room) {
return crowded_document(&facts, total);
}
arrays.sort_by_key(|(_, entries)| json_len(entries));
for (index, (name, entries)) in arrays.iter().enumerate() {
let kept = kept_entries(&facts, name, entries, &arrays[index + 1..], room);
facts.insert(name.clone(), serde_json::Value::Array(kept));
}
match serde_json::to_string(&facts) {
Ok(text) if text.len() <= room => text,
_ => crowded_document(&facts, total),
}
}
fn kept_entries(
facts: &serde_json::Map<String, serde_json::Value>,
name: &str,
entries: &[serde_json::Value],
later: &[(String, Vec<serde_json::Value>)],
room: usize,
) -> Vec<serde_json::Value> {
let (mut fits_count, mut too_many) = (0, entries.len() + 1);
while too_many - fits_count > 1 {
let middle = fits_count + (too_many - fits_count) / 2;
if measured(facts, name, entries, middle, later, room) {
fits_count = middle;
} else {
too_many = middle;
}
}
kept(entries, fits_count)
}
fn measured(
facts: &serde_json::Map<String, serde_json::Value>,
name: &str,
entries: &[serde_json::Value],
count: usize,
later: &[(String, Vec<serde_json::Value>)],
room: usize,
) -> bool {
let mut candidate = facts.clone();
candidate.insert(
name.to_string(),
serde_json::Value::Array(kept(entries, count)),
);
for (name, entries) in later {
candidate.insert(name.clone(), serde_json::Value::Array(kept(entries, 0)));
}
fits(&candidate, room)
}
fn kept(entries: &[serde_json::Value], count: usize) -> Vec<serde_json::Value> {
let mut shown = entries[..count].to_vec();
if count < entries.len() {
shown.push(serde_json::Value::String(count_note(
entries.len() - count,
entries.len(),
)));
}
shown
}
fn fits(document: &serde_json::Map<String, serde_json::Value>, room: usize) -> bool {
serde_json::to_string(document).is_ok_and(|text| text.len() <= room)
}
fn json_len(entries: &[serde_json::Value]) -> usize {
serde_json::to_string(entries).map_or(0, |json| json.len())
}
fn count_note(left_out: usize, total: usize) -> String {
format!("… {left_out} of {total} further entries not shown")
}
fn crowded_document(facts: &serde_json::Map<String, serde_json::Value>, total: usize) -> String {
let mut answer = serde_json::Map::new();
let mut omitted = total;
if let Some(format) = facts.get("format") {
answer.insert("format".to_string(), format.clone());
omitted -= 1;
}
answer.insert(
"omitted".to_string(),
serde_json::Value::String(format!("… {omitted} further member(s) not shown")),
);
serde_json::Value::Object(answer).to_string()
}
fn first_json(text: &str) -> (Option<serde_json::Value>, &str) {
let text = text.trim_start();
let mut values = serde_json::Deserializer::from_str(text).into_iter::<serde_json::Value>();
match values.next() {
Some(Ok(value)) => (Some(value), text[values.byte_offset()..].trim()),
_ => (None, text.trim()),
}
}
pub(crate) async fn listing(filter: Option<&str>) -> anyhow::Result<String> {
let output = drive(&listing_args(filter)).await?;
if is_empty_listing(&output) {
return Ok(no_commands(filter));
}
Ok(registry_answer(filter, &output))
}
fn registry_answer(filter: Option<&str>, output: &str) -> String {
let output = output.trim_start();
if output.contains(crate::util::TRUNCATED_MIDDLE) {
return format!("… the registry answer was too large to capture whole; {NARROWER}");
}
if output.len() <= MAX_ANSWER_BYTES {
return output.to_string();
}
match filter {
Some(_) => capped_rows(output),
None => capped_listing(output),
}
}
fn is_empty_listing(output: &str) -> bool {
let trimmed = output.trim();
trimmed.is_empty()
|| (trimmed.len() >= 2
&& trimmed.starts_with('[')
&& trimmed.ends_with(']')
&& trimmed[1..trimmed.len() - 1].trim().is_empty())
}
fn no_commands(filter: Option<&str>) -> String {
match filter {
Some(filter) => format!("no command matches {filter:?}"),
None => "the vendor's command registry is empty".to_string(),
}
}
pub(crate) async fn batch(
chain: &[Step],
input: &Path,
output: &Path,
format: Option<&str>,
quality: Option<u32>,
tiff_layers: bool,
) -> anyhow::Result<BatchReport> {
let (_recipe_dir, recipe) = recipe_file(chain)?;
let argv = batch_args(&recipe, input, output, format, quality, tiff_layers);
let outcome = run(&argv).await?;
let written = files_written(output).await;
batch_outcome(&outcome, &written, output).map_err(anyhow::Error::msg)
}
fn batch_outcome(
outcome: &ProgramOutcome,
written: &FilesWritten,
output_dir: &Path,
) -> Result<BatchReport, String> {
if outcome.success || outcome.output.lines().any(is_summary) {
Ok(BatchReport {
answer: batch_answer(&outcome.output, written, output_dir),
partial: failed_some(&outcome.output),
})
} else {
Err(failure("batch", outcome))
}
}
fn batch_answer(output: &str, written: &FilesWritten, output_dir: &Path) -> String {
let header = written.written_into(output_dir);
let text = output.trim();
if text.is_empty() {
return header;
}
let lines: Vec<&str> = text.lines().collect();
let summary: Vec<&str> = lines
.iter()
.copied()
.filter(|line| is_summary(line))
.collect();
let failures: Vec<&str> = lines
.iter()
.copied()
.filter(|line| is_failure(line))
.collect();
let warnings = collapsed_warnings(lines.iter().copied().filter(|line| is_warning(line)));
let results: Vec<&str> = lines
.iter()
.copied()
.filter(|line| !is_summary(line) && !is_failure(line) && !is_warning(line))
.collect();
let mut answer = header.clone();
for line in &results {
crate::util::push_line(&mut answer, line);
}
for line in &warnings {
crate::util::push_line(&mut answer, line);
}
for line in &failures {
crate::util::push_line(&mut answer, line);
}
for line in &summary {
crate::util::push_line(&mut answer, line);
}
if answer.len() <= MAX_ANSWER_BYTES {
return answer;
}
let mut notes = 0;
loop {
let (answer, used) =
capped_batch_answer(&header, &results, &warnings, &failures, &summary, notes);
if used <= notes {
return answer;
}
notes = used;
}
}
fn capped_batch_answer(
header: &str,
results: &[&str],
warnings: &[String],
failures: &[&str],
summary: &[&str],
notes: usize,
) -> (String, usize) {
let mut used = 0;
let mut left = MAX_ANSWER_BYTES
.saturating_sub(header.len() + 1 + lines_bytes(summary) + notes * NOTE_ROOM);
let kept_failures = lines_within(failures.iter().copied(), left);
if kept_failures < failures.len() {
used += 1;
}
left = left.saturating_sub(lines_bytes(&failures[..kept_failures]));
let side = left / 2;
let head = lines_within(results.iter().copied(), side);
let tail = lines_within(results[head..].iter().rev().copied(), side);
let omitted = results.len() - head - tail;
if omitted > 0 {
used += 1;
}
left = left.saturating_sub(
lines_bytes(&results[..head]) + lines_bytes(&results[results.len() - tail..]),
);
let kept_warnings = lines_within(warnings.iter().map(String::as_str), left);
if kept_warnings < warnings.len() {
used += 1;
}
let mut answer = header.to_string();
for line in &results[..head] {
crate::util::push_line(&mut answer, line);
}
if omitted > 0 {
crate::util::push_line(
&mut answer,
&format!("… {omitted} further result lines not shown"),
);
}
for line in &results[results.len() - tail..] {
crate::util::push_line(&mut answer, line);
}
for line in &warnings[..kept_warnings] {
crate::util::push_line(&mut answer, line);
}
if kept_warnings < warnings.len() {
crate::util::push_line(
&mut answer,
&format!(
"… {} further warning kinds not shown",
warnings.len() - kept_warnings
),
);
}
if kept_failures < failures.len() {
crate::util::push_line(
&mut answer,
&format!(
"… {} further failures not shown",
failures.len() - kept_failures
),
);
}
for line in &failures[..kept_failures] {
crate::util::push_line(&mut answer, line);
}
for line in summary {
crate::util::push_line(&mut answer, line);
}
(answer, used)
}
fn collapsed_warnings<'a>(warnings: impl Iterator<Item = &'a str>) -> Vec<String> {
let mut kinds: Vec<WarningKind> = Vec::new();
for line in warnings {
let parts = warning_parts(line.trim_end().strip_prefix(WARNING_PREFIX).unwrap_or(line));
match kinds.iter_mut().find(|kind| kind.same_as(&parts)) {
Some(kind) => kind.merge(&parts),
None => kinds.push(WarningKind::new(parts)),
}
}
kinds
.into_iter()
.map(|kind| {
let lines = if kind.count == 1 { "line" } else { "lines" };
format!("warning ({} {lines}): {}", kind.count, kind.wording())
})
.collect()
}
struct WarningKind {
parts: Vec<WarningPart>,
count: usize,
}
enum WarningPart {
Text(String),
Number { value: String, varies: bool },
}
impl WarningKind {
fn new(parts: Vec<WarningPart>) -> Self {
Self { parts, count: 1 }
}
fn same_as(&self, parts: &[WarningPart]) -> bool {
self.parts.len() == parts.len()
&& self
.parts
.iter()
.zip(parts)
.all(|(known, part)| match (known, part) {
(WarningPart::Text(known), WarningPart::Text(text)) => known == text,
(WarningPart::Number { .. }, WarningPart::Number { .. }) => true,
_ => false,
})
}
fn merge(&mut self, parts: &[WarningPart]) {
self.count += 1;
for (known, part) in self.parts.iter_mut().zip(parts) {
if let (WarningPart::Number { value, varies }, WarningPart::Number { value: seen, .. }) =
(known, part)
&& !*varies
&& value != seen
{
*varies = true;
}
}
}
fn wording(&self) -> String {
let mut wording = String::new();
for part in &self.parts {
match part {
WarningPart::Text(text) => wording.push_str(text),
WarningPart::Number {
value,
varies: false,
} => wording.push_str(value),
WarningPart::Number { varies: true, .. } => wording.push('N'),
}
}
wording
}
}
fn warning_parts(message: &str) -> Vec<WarningPart> {
let mut parts = Vec::new();
let mut text = String::new();
let mut number = String::new();
for character in message.chars() {
if character.is_ascii_digit() {
if !text.is_empty() {
parts.push(WarningPart::Text(std::mem::take(&mut text)));
}
number.push(character);
} else {
if !number.is_empty() {
parts.push(WarningPart::Number {
value: std::mem::take(&mut number),
varies: false,
});
}
text.push(character);
}
}
if !number.is_empty() {
parts.push(WarningPart::Number {
value: number,
varies: false,
});
}
if !text.is_empty() {
parts.push(WarningPart::Text(text));
}
parts
}
fn summary_counts(line: &str) -> Option<(u64, u64)> {
let words: Vec<&str> = line
.split(|c: char| !c.is_ascii_alphanumeric())
.filter(|word| !word.is_empty())
.collect();
match words.as_slice() {
[succeeded, "succeeded", failed, "failed", ..] => {
Some((succeeded.parse().ok()?, failed.parse().ok()?))
}
_ => None,
}
}
fn is_summary(line: &str) -> bool {
summary_counts(line).is_some()
}
fn failed_some(output: &str) -> bool {
output
.lines()
.any(|line| is_failure(line) || summary_counts(line).is_some_and(|(_, failed)| failed > 0))
}
fn is_failure(line: &str) -> bool {
line.starts_with("FAIL ")
}
const WARNING_PREFIX: &str = "warning: ";
fn is_warning(line: &str) -> bool {
line.starts_with(WARNING_PREFIX)
}
fn lines_bytes(lines: &[&str]) -> usize {
lines.iter().map(|line| line.len() + 1).sum()
}
pub(crate) async fn files_written(dir: &Path) -> FilesWritten {
let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
return FilesWritten {
count: 0,
whole: false,
};
};
let mut written = FilesWritten {
count: 0,
whole: true,
};
loop {
match entries.next_entry().await {
Ok(Some(entry)) => match entry.file_type().await {
Ok(kind) if kind.is_file() => written.count += 1,
Ok(_) => {}
Err(_) => written.whole = false,
},
Ok(None) => return written,
Err(_) => {
written.whole = false;
return written;
}
}
}
}
pub(crate) struct FilesWritten {
pub(crate) count: usize,
pub(crate) whole: bool,
}
impl FilesWritten {
pub(crate) fn written_into(&self, dir: &Path) -> String {
let dir = dir.display();
match (self.whole, self.count) {
(true, 0) => format!("no file was written into {dir}"),
(true, count) => format!("{count} file(s) written to {dir}"),
(false, 0) => format!("the files in {dir} could not be counted"),
(false, count) => format!(
"at least {count} file(s) written to {dir} (the folder could not be read in full)"
),
}
}
}
fn lines_within<'a>(lines: impl Iterator<Item = &'a str>, budget: usize) -> usize {
let mut used = 0;
let mut count = 0;
for line in lines {
used += line.len() + 1;
if used > budget {
break;
}
count += 1;
}
count
}
async fn run(argv: &[String]) -> anyhow::Result<ProgramOutcome> {
let what = argv.first().map_or("", String::as_str);
let (_held, cwd, program) = install::hold_for_run().await.map_err(anyhow::Error::msg)?;
let outcome = run_internal_program_outcome(&cwd, &program, argv, &[], None).await;
if outcome.stopped() {
return Err(anyhow::Error::msg(failure(what, &outcome)));
}
Ok(outcome)
}
async fn drive(argv: &[String]) -> anyhow::Result<String> {
let what = argv.first().map_or("", String::as_str);
let outcome = run(argv).await?;
if !outcome.success {
return Err(anyhow::Error::msg(failure(what, &outcome)));
}
Ok(outcome.output)
}
fn is_tiff(format: &str) -> bool {
format.eq_ignore_ascii_case("tif") || format.eq_ignore_ascii_case("tiff")
}
const APPROVE_HIGH_MEMORY: &str = "--approve-high-memory";
fn chain_args(
input: Option<&Path>,
canvas: Option<&serde_json::Value>,
chain: &[Step],
output: &Path,
) -> Vec<String> {
let tiff = crate::util::extension_of(output).is_some_and(|extension| is_tiff(&extension));
let output_arg = path_arg(output);
if let (Some(input), None) = (input, canvas)
&& chain.is_empty()
{
let mut args = vec!["convert".to_string(), path_arg(input), output_arg];
args.push(APPROVE_HIGH_MEMORY.to_string());
if tiff {
args.push("--tiff-layers".to_string());
}
return args;
}
let mut args = match (input, canvas) {
(Some(input), None) => vec!["run".to_string(), path_arg(input)],
(_, Some(canvas)) => vec!["run".to_string(), "--new".to_string(), canvas.to_string()],
(None, None) => vec!["run".to_string()],
};
for step in chain {
args.push("--cmd".to_string());
args.push(step.command.clone());
if let Some(params) = &step.params {
args.push("--params".to_string());
args.push(params.to_string());
}
}
args.push("--out".to_string());
args.push(output_arg);
args.push(APPROVE_HIGH_MEMORY.to_string());
if tiff {
args.push("--tiff-layers".to_string());
}
args
}
fn inspect_args(input: &Path) -> Vec<String> {
vec![
"info".to_string(),
path_arg(input),
"--compact".to_string(),
APPROVE_HIGH_MEMORY.to_string(),
]
}
fn listing_args(filter: Option<&str>) -> Vec<String> {
let mut args = vec!["commands".to_string()];
if let Some(filter) = filter {
args.push("--filter".to_string());
args.push(filter.to_string());
args.push("--json".to_string());
}
args
}
fn batch_args(
recipe: &Path,
input: &Path,
output: &Path,
format: Option<&str>,
quality: Option<u32>,
tiff_layers: bool,
) -> Vec<String> {
let mut args = vec![
"batch".to_string(),
"--actions".to_string(),
path_arg(recipe),
"--in".to_string(),
path_arg(input),
"--out".to_string(),
path_arg(output),
];
if let Some(format) = format {
args.push("--format".to_string());
args.push(format.to_string());
}
if let Some(quality) = quality {
args.push("--quality".to_string());
args.push(quality.to_string());
}
if tiff_layers || format.is_some_and(is_tiff) {
args.push("--tiff-layers".to_string());
}
args.push(APPROVE_HIGH_MEMORY.to_string());
args
}
fn path_arg(path: &Path) -> String {
path.to_string_lossy().into_owned()
}
fn recipe_file(chain: &[Step]) -> anyhow::Result<(tempfile::TempDir, PathBuf)> {
use anyhow::Context as _;
let dir = tempfile::Builder::new()
.prefix("photocraft-")
.tempdir_in(crate::temp::shell_tmpdir())
.context("the batch recipe's temporary directory could not be created")?;
let path = dir.path().join("recipe.json");
std::fs::write(&path, recipe_json(chain)).context("the batch recipe could not be written")?;
Ok((dir, path))
}
fn recipe_json(chain: &[Step]) -> String {
let steps: Vec<serde_json::Value> = chain
.iter()
.map(|step| match &step.params {
Some(params) => serde_json::json!({"command": step.command, "params": params}),
None => serde_json::json!({"command": step.command}),
})
.collect();
serde_json::Value::Array(steps).to_string()
}
const NARROWER: &str = "a narrower filter shows the rest";
fn capped_rows(text: &str) -> String {
let Some(rows) = registry_rows(text) else {
return capped_listing(text);
};
let room = MAX_ANSWER_BYTES.saturating_sub(NOTE_ROOM);
let total = rows.len();
let mut kept: Vec<String> = Vec::new();
let mut used = 2; for row in &rows {
let row = row.to_string();
let separator = if kept.is_empty() { 0 } else { 2 }; if used + separator + row.len() > room {
break;
}
used += separator + row.len();
kept.push(row);
}
if kept.is_empty() && !rows.is_empty() {
return format!(
"[]\n… all {total} matching command(s) not shown: each one's own documentation is longer \
than a whole answer"
);
}
let answer = format!("[{}]", kept.join(",\n"));
if kept.len() == total {
return answer;
}
let left_out = total - kept.len();
format!("{answer}\n… {left_out} of {total} matching commands not shown; {NARROWER}")
}
fn registry_rows(text: &str) -> Option<Vec<serde_json::Value>> {
match first_json(text).0 {
Some(serde_json::Value::Array(rows)) => Some(rows),
_ => None,
}
}
fn capped_listing(text: &str) -> String {
capped_lines(text, MAX_ANSWER_BYTES, "command", NARROWER)
}
pub(crate) fn capped_lines(text: &str, budget: usize, noun: &str, remedy: &str) -> String {
let text = text.trim_start();
if text.is_empty() {
return String::new();
}
let room = budget.saturating_sub(NOTE_ROOM);
let total = text.lines().count();
let mut kept = String::new();
let mut kept_lines = 0;
for line in text.split_inclusive('\n') {
if kept.len() + line.len() > room {
break;
}
kept.push_str(line);
kept_lines += 1;
}
let withheld = total - kept_lines;
let note = if withheld == 0 {
String::new()
} else {
let plural = if withheld == 1 { "" } else { "s" };
if remedy.is_empty() {
format!("… {withheld} further {noun}{plural} not shown")
} else {
format!("… {withheld} further {noun}{plural} not shown; {remedy}")
}
};
match (kept_lines, note.is_empty()) {
(0, _) => note,
(_, true) => kept.trim_end().to_string(),
(_, false) => format!("{}\n{note}", kept.trim_end()),
}
}
fn failure(what: &str, outcome: &ProgramOutcome) -> String {
let detail = match outcome.stop {
Some(Stop::Spawn) => "the program could not be started on this machine".to_string(),
Some(Stop::Memory) => format!(
"the product's memory watchdog stopped it: {}",
outcome.stop_reason()
),
Some(Stop::Timeout) | None => outcome.detail.trim().to_string(),
};
let detail = if detail.is_empty() {
"no reason was reported".to_string()
} else {
detail
};
let output =
crate::util::truncate_sandwich(outcome.output.trim(), MAX_FAILURE_BYTES, "vendor output");
if output.is_empty() {
return format!("photocraft {what} failed ({detail})");
}
format!("photocraft {what} failed ({detail}): {output}")
.trim_end()
.to_string()
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
fn step(command: &str, params: Option<serde_json::Value>) -> Step {
Step {
command: command.to_string(),
params,
}
}
fn outcome(detail: &str, output: &str, stop: Option<Stop>) -> ProgramOutcome {
ProgramOutcome {
success: false,
detail: detail.to_string(),
output: output.to_string(),
has_output: !output.is_empty(),
stop,
}
}
fn counted(count: usize) -> FilesWritten {
FilesWritten { count, whole: true }
}
#[test]
fn a_chain_runs_its_steps_in_order_before_the_output() {
let input = Some(Path::new("/work/plate.psd"));
let output = Path::new("/work/out.png");
assert_eq!(
chain_args(input, None, &[], output),
[
"convert",
"/work/plate.psd",
"/work/out.png",
"--approve-high-memory"
]
);
assert_eq!(
chain_args(input, None, &[step("autocrop", None)], output),
[
"run",
"/work/plate.psd",
"--cmd",
"autocrop",
"--out",
"/work/out.png",
"--approve-high-memory"
]
);
assert_eq!(
chain_args(
input,
None,
&[
step("resize", Some(json!({"width": 800}))),
step("sharpen", None),
],
output
),
[
"run",
"/work/plate.psd",
"--cmd",
"resize",
"--params",
"{\"width\":800}",
"--cmd",
"sharpen",
"--out",
"/work/out.png",
"--approve-high-memory"
]
);
}
#[test]
fn a_canvas_created_from_nothing_is_the_vendors_new_document() {
let canvas = json!({"width": 800, "height": 600});
let output = Path::new("/work/out.png");
assert_eq!(
chain_args(None, Some(&canvas), &[], output),
[
"run",
"--new",
"{\"height\":600,\"width\":800}",
"--out",
"/work/out.png",
"--approve-high-memory"
]
);
let args = chain_args(None, Some(&canvas), &[step("fill", None)], output);
assert_eq!(
args[..3],
["run", "--new", "{\"height\":600,\"width\":800}"]
);
assert_eq!(args[3], "--cmd");
assert!(args.contains(&"--out".to_string()));
}
#[test]
fn a_tiff_destination_keeps_its_layers_and_every_other_format_is_left_alone() {
let input = Some(Path::new("/work/plate.psd"));
let chain = [step("filter.sharpen.smartSharpen", None)];
for output in ["/work/out.tiff", "/work/out.TIF"] {
let args = chain_args(input, None, &chain, Path::new(output));
assert!(
args.contains(&"--tiff-layers".to_string()),
"{output}: {args:?}"
);
let converted = chain_args(input, None, &[], Path::new(output));
assert!(
converted.contains(&"--tiff-layers".to_string()),
"{output}: {converted:?}"
);
}
for output in ["/work/out.png", "/work/out.psd", "/work/out"] {
assert!(
!chain_args(input, None, &chain, Path::new(output))
.contains(&"--tiff-layers".to_string()),
"{output}"
);
}
}
#[test]
fn inspection_and_the_registry_ask_for_what_the_caller_needs() {
assert_eq!(
inspect_args(Path::new("/work/plate.pcraft")),
[
"info",
"/work/plate.pcraft",
"--compact",
"--approve-high-memory"
]
);
assert_eq!(listing_args(None), ["commands"]);
assert_eq!(
listing_args(Some("blur")),
["commands", "--filter", "blur", "--json"]
);
}
#[test]
fn batch_carries_every_flag_it_was_given_and_none_it_was_not() {
let recipe = Path::new("/tmp/recipe.json");
let input = Path::new("/work/in");
let output = Path::new("/work/out");
assert_eq!(
batch_args(recipe, input, output, None, None, false),
[
"batch",
"--actions",
"/tmp/recipe.json",
"--in",
"/work/in",
"--out",
"/work/out",
"--approve-high-memory"
]
);
assert_eq!(
batch_args(recipe, input, output, Some("png"), Some(90), true),
[
"batch",
"--actions",
"/tmp/recipe.json",
"--in",
"/work/in",
"--out",
"/work/out",
"--format",
"png",
"--quality",
"90",
"--tiff-layers",
"--approve-high-memory"
]
);
for format in ["tiff", "TIF"] {
let args = batch_args(recipe, input, output, Some(format), None, false);
assert!(
args.contains(&"--tiff-layers".to_string()),
"{format}: {args:?}"
);
}
}
#[test]
fn a_long_batch_answer_keeps_its_first_and_last_lines_and_says_how_many_it_left_out() {
let mut spelled: Vec<String> = (0..400)
.map(|index| format!("ok /work/in/photo{index}.heic -> /work/out/photo{index}.png"))
.collect();
spelled.push("400 succeeded, 0 failed".to_string());
let results: Vec<&str> = spelled[..400].iter().map(String::as_str).collect();
let output = spelled.join("\n");
assert!(output.len() > MAX_ANSWER_BYTES, "the fixture must not fit");
let capped = batch_answer(&output, &counted(400), Path::new("/work/out"));
let kept: Vec<&str> = capped.lines().collect();
assert_eq!(kept[0], "400 file(s) written to /work/out");
let note = kept[1..]
.iter()
.position(|line| line.starts_with('…'))
.map(|at| at + 1)
.expect("the cap says what it left out");
assert_eq!(kept[1..note], results[..note - 1]);
let tail = &kept[note + 1..kept.len() - 1];
assert_eq!(tail, &results[results.len() - tail.len()..]);
assert!(
kept[note].contains(&format!(
"{} further result lines not shown",
results.len() - (note - 1) - tail.len()
)),
"{}",
kept[note]
);
assert_eq!(capped.lines().last(), Some("400 succeeded, 0 failed"));
assert!(capped.len() <= MAX_ANSWER_BYTES, "{}", capped.len());
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
let short = "ok /work/in/a.heic -> /work/out/a.png\n1 succeeded, 0 failed";
assert_eq!(
batch_answer(short, &counted(1), Path::new("/work/out")),
format!("1 file(s) written to /work/out\n{short}")
);
}
#[test]
fn a_batch_answer_keeps_every_failure_and_the_summary_whatever_it_drops() {
let mut spelled: Vec<String> = (0..300)
.map(|index| format!("ok /work/in/photo{index}.jpg -> /work/out/photo{index}.jpg"))
.collect();
spelled.push("300 succeeded, 1 failed".to_string());
spelled.push("FAIL /work/in/photo150.jpg: unsupported 12-bit depth".to_string());
spelled
.extend((0..300).map(|index| {
format!("warning: written as an 8-bit palette BMP ({index} colours)")
}));
let output = spelled.join("\n");
assert!(output.len() > MAX_ANSWER_BYTES, "the fixture must not fit");
let capped = batch_answer(&output, &counted(300), Path::new("/work/out"));
let kept: Vec<&str> = capped.lines().collect();
assert_eq!(kept[0], "300 file(s) written to /work/out");
assert!(
capped.contains("FAIL /work/in/photo150.jpg: unsupported 12-bit depth"),
"{capped}"
);
assert_eq!(capped.lines().last(), Some("300 succeeded, 1 failed"));
assert!(
capped.contains("… 1 further warning kinds not shown"),
"{capped}"
);
assert!(
kept[1..]
.iter()
.all(|line| spelled.contains(&line.to_string()) || line.starts_with('…')),
"{capped}"
);
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
}
#[test]
fn a_capped_batch_still_shows_a_kind_whose_per_file_values_all_differ() {
let mut spelled: Vec<String> = (0..100)
.map(|index| format!("ok /work/in/photo{index}.png -> /work/out/photo{index}.bmp"))
.collect();
spelled.push("100 succeeded, 0 failed".to_string());
spelled
.extend((0..100).map(|index| {
format!("warning: written as an 8-bit palette BMP ({index} colours)")
}));
let output = spelled.join("\n");
assert!(output.len() > MAX_ANSWER_BYTES, "the fixture must not fit");
let capped = batch_answer(&output, &counted(100), Path::new("/work/out"));
assert!(
capped.contains("warning (100 lines): written as an 8-bit palette BMP (N colours)"),
"{capped}"
);
assert_eq!(capped.lines().last(), Some("100 succeeded, 0 failed"));
assert!(capped.len() <= MAX_ANSWER_BYTES, "{}", capped.len());
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
}
#[test]
fn a_batch_that_needs_every_note_still_fits_and_keeps_its_head_and_summary() {
let mut spelled: Vec<String> = (0..200)
.map(|index| format!("ok /work/in/photo{index}.jpg -> /work/out/photo{index}.jpg"))
.collect();
spelled.push("200 succeeded, 200 failed".to_string());
spelled.extend(
(0..200).map(|index| format!("FAIL /work/in/broken{index}.jpg: unreadable header")),
);
spelled.extend(
(0..200)
.map(|index| format!("warning: an encoder complaint number {index} about a file")),
);
let output = spelled.join("\n");
let capped = batch_answer(&output, &counted(200), Path::new("/work/out"));
assert_eq!(
capped.lines().next(),
Some("200 file(s) written to /work/out")
);
assert_eq!(capped.lines().last(), Some("200 succeeded, 200 failed"));
assert!(
capped.contains("further result lines not shown"),
"{capped}"
);
assert!(capped.contains("further failures not shown"), "{capped}");
assert!(
capped.contains("further warning kinds not shown"),
"{capped}"
);
assert!(capped.len() <= MAX_ANSWER_BYTES, "{}", capped.len());
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
}
#[test]
fn a_batch_answer_collapses_the_engines_warnings_to_one_line_per_kind() {
let mut spelled: Vec<String> = (0..25)
.map(|index| format!("ok /work/in/photo{index}.png -> /work/out/photo{index}.jpg"))
.collect();
spelled.push("25 succeeded, 0 failed".to_string());
for _ in 0..25 {
spelled.push("warning: transparency composited over white for Jpeg".to_string());
spelled.push("warning: 16-bit will be reduced to 8-bit".to_string());
spelled.push("warning: lossy compression".to_string());
spelled.push("warning: text metadata dropped".to_string());
}
let output = spelled.join("\n");
let answer = batch_answer(&output, &counted(25), Path::new("/work/out"));
let kept: Vec<&str> = answer.lines().collect();
assert_eq!(kept[0], "25 file(s) written to /work/out");
assert_eq!(kept.last(), Some(&"25 succeeded, 0 failed"));
assert_eq!(
kept.iter().filter(|line| line.starts_with("ok")).count(),
25,
"{answer}"
);
let warnings: Vec<&&str> = kept
.iter()
.filter(|line| line.starts_with("warning"))
.collect();
assert_eq!(warnings.len(), 4, "{answer}");
for line in warnings {
assert!(line.contains("(25 lines)"), "{line}");
}
assert!(
answer.contains("warning (25 lines): lossy compression"),
"{answer}"
);
assert!(
answer.contains("warning (25 lines): 16-bit will be reduced to 8-bit"),
"{answer}"
);
assert!(answer.len() < 3_000, "{}", answer.len());
assert_eq!(crate::util::truncate_tool_output(&answer), answer);
}
#[test]
fn a_warning_naming_a_per_file_value_is_one_kind_however_the_value_differs() {
let output = [
"ok /work/in/a.png -> /work/out/a.bmp",
"warning: written as an 8-bit palette BMP (16 colours)",
"ok /work/in/b.png -> /work/out/b.bmp",
"warning: written as an 8-bit palette BMP (2 colours)",
"ok /work/in/c.png -> /work/out/c.bmp",
"warning: written as an 8-bit palette BMP (200 colours)",
"3 succeeded, 0 failed",
]
.join("\n");
let answer = batch_answer(&output, &counted(3), Path::new("/work/out"));
let warnings: Vec<&str> = answer
.lines()
.filter(|line| line.starts_with("warning"))
.collect();
assert_eq!(
warnings,
["warning (3 lines): written as an 8-bit palette BMP (N colours)"]
);
assert_eq!(answer.lines().last(), Some("3 succeeded, 0 failed"));
}
#[test]
fn the_engines_own_error_line_is_a_result_and_not_swallowed_as_a_warning() {
let output = [
"ok /work/in/a.png -> /work/out/a.jpg",
"warning: lossy compression",
"error: 1 file(s) failed",
"FAIL /work/in/b.png: unknown file format: png8",
"1 succeeded, 1 failed",
]
.join("\n");
let answer = batch_answer(&output, &counted(1), Path::new("/work/out"));
assert!(answer.contains("error: 1 file(s) failed"), "{answer}");
assert!(
answer.contains("FAIL /work/in/b.png: unknown file format: png8"),
"{answer}"
);
assert!(
answer.contains("warning (1 line): lossy compression"),
"{answer}"
);
assert_eq!(answer.lines().last(), Some("1 succeeded, 1 failed"));
}
#[test]
fn a_batch_too_large_for_its_results_gives_them_the_room_before_any_warning() {
let mut spelled: Vec<String> = (0..400)
.map(|index| format!("ok /work/in/photo{index}.jpg -> /work/out/photo{index}.jpg"))
.collect();
spelled.push("400 succeeded, 0 failed".to_string());
let warning = format!("warning: {}", "x".repeat(300));
spelled.extend((0..400).map(|_| warning.clone()));
let output = spelled.join("\n");
let answer = batch_answer(&output, &counted(400), Path::new("/work/out"));
assert!(
answer.contains("further result lines not shown"),
"{answer}"
);
assert!(
answer.contains("… 1 further warning kinds not shown"),
"{answer}"
);
assert!(!answer.contains("warning (400 lines)"), "{answer}");
assert_eq!(answer.lines().last(), Some("400 succeeded, 0 failed"));
assert!(answer.len() <= MAX_ANSWER_BYTES, "{}", answer.len());
assert_eq!(crate::util::truncate_tool_output(&answer), answer);
}
#[test]
fn a_batch_with_more_failures_than_fit_keeps_the_summary_and_counts_the_rest() {
let mut spelled: Vec<String> = (0..400)
.map(|index| format!("FAIL /work/in/photo{index}.heic: unreadable header"))
.collect();
spelled.push("0 succeeded, 400 failed".to_string());
let output = spelled.join("\n");
let capped = batch_answer(&output, &counted(0), Path::new("/work/out"));
assert_eq!(
capped.lines().next(),
Some("no file was written into /work/out"),
"the count is the head"
);
let note = capped
.lines()
.find(|line| line.starts_with("… ") && line.ends_with("further failures not shown"))
.expect("the cap counts the failures it dropped");
assert!(capped.contains("FAIL /work/in/photo0.heic: unreadable header"));
assert_eq!(capped.lines().last(), Some("0 succeeded, 400 failed"));
assert!(note.contains("further failures not shown"), "{note}");
assert!(capped.len() <= MAX_ANSWER_BYTES, "{}", capped.len());
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
assert!(
capped.len() + 200 >= MAX_ANSWER_BYTES,
"{} of {MAX_ANSWER_BYTES}",
capped.len()
);
}
#[test]
fn a_batch_answer_never_opens_with_the_blank_line_the_engine_printed_first() {
let output = "\n\nok /work/in/a.heic -> /work/out/a.png\n1 succeeded, 0 failed\n";
let answer = batch_answer(output, &counted(1), Path::new("/work/out"));
assert_eq!(
answer.lines().next(),
Some("1 file(s) written to /work/out")
);
assert!(!answer.starts_with('\n'), "{answer:?}");
}
#[test]
fn the_recipe_is_the_vendors_step_list_with_params_only_where_there_are_some() {
let plain = recipe_json(&[step("autocrop", None), step("sharpen", None)]);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&plain).expect("the recipe parses"),
json!([{"command": "autocrop"}, {"command": "sharpen"}])
);
assert!(!plain.contains("params"), "{plain}");
let with_params = recipe_json(&[step("resize", Some(json!({"width": 800})))]);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&with_params).expect("the recipe parses"),
json!([{"command": "resize", "params": {"width": 800}}])
);
}
#[test]
fn a_listing_within_the_cap_comes_back_as_the_vendor_wrote_it() {
let registry = "blur: gaussian blur\ncrop: cut the canvas\n";
assert_eq!(registry_answer(None, registry), registry);
let narrowed = "[\n {\n \"id\": \"image.crop\"\n }\n]";
assert_eq!(registry_answer(Some("crop"), narrowed), narrowed);
}
#[test]
fn a_filter_that_matches_nothing_says_so_instead_of_answering_blank() {
for empty in ["[]", " [ ]\n", "", " \n"] {
assert!(is_empty_listing(empty), "{empty:?}");
}
assert!(!is_empty_listing(r#"[{"id":"image.crop"}]"#));
let answer = no_commands(Some("nosuchthing"));
assert!(answer.contains("no command matches"), "{answer}");
assert!(answer.contains("nosuchthing"), "{answer}");
assert!(no_commands(None).contains("registry is empty"));
}
#[test]
fn a_listing_past_the_cap_is_cut_on_a_line_boundary_and_says_how_much_it_withheld() {
let line = "blur: gaussian blur; params: radius (number)\n";
let fits = (MAX_ANSWER_BYTES - NOTE_ROOM) / line.len();
let withheld = 25;
let registry = line.repeat(fits + withheld);
let capped = capped_listing(®istry);
let mut lines = capped.lines().collect::<Vec<_>>();
let note = lines.pop().expect("the cap says what it withheld");
assert!(lines.iter().all(|kept| *kept == line.trim_end()));
assert_eq!(lines.len(), fits);
assert!(
note.contains(&format!("{withheld} further commands")),
"{note}"
);
assert!(note.contains("a narrower filter shows the rest"), "{note}");
assert!(capped.len() <= MAX_ANSWER_BYTES, "{}", capped.len());
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
}
#[test]
fn a_registry_answer_the_capture_cut_in_the_middle_says_so_instead_of_half_a_document() {
let text = format!(
"[{{\"id\":\"image.crop\"}},\n{}\n[{{\"id\":\"image.trim\"}}]",
crate::util::TRUNCATED_MIDDLE
);
let answer = registry_answer(Some("image"), &text);
assert_eq!(
answer,
format!("… the registry answer was too large to capture whole; {NARROWER}")
);
assert!(
!answer.contains('{'),
"no fragment of the document: {answer}"
);
}
#[test]
fn an_inspection_the_capture_cut_in_the_middle_says_so_and_keeps_the_format() {
let text = format!(
"{{\"width\":4096,\"mode\":\"Rgb\",\"layers\":[{{\"name\":\"Layer 0\"}},\n{}\n{{\"name\":\"Layer 900\"}}]}}",
crate::util::TRUNCATED_MIDDLE
);
let answer = inspection_answer(&text, Path::new("/work/plate.psd"));
assert_eq!(
answer,
"… the inspection was too large to capture whole; format: psd (from the file name)"
);
assert!(!answer.contains('{'), "no fragment: {answer}");
assert!(!answer.starts_with('\n'), "no blank first line");
assert_eq!(crate::util::truncate_tool_output(&answer), answer);
}
#[test]
fn a_line_too_long_to_fit_is_dropped_whole_rather_than_cut_inside() {
let line = format!(
"[{}]",
"{\"id\":\"image.crop\",\"params\":\"кадр\"},".repeat(2000)
);
let capped = capped_listing(&line);
assert_eq!(capped, format!("… 1 further command not shown; {NARROWER}"));
assert!(!capped.starts_with('\n'), "no blank first line");
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
let capped = capped_listing("\n\nblur: gaussian blur\n");
assert_eq!(capped, "blur: gaussian blur");
}
#[test]
fn the_inspection_answer_names_the_format_its_file_name_gives_as_one_more_field() {
let answer = inspection_answer(
r#"{"file":"/work/plate.PSD","mode":"Rgb","depth":8}"#,
Path::new("/work/plate.PSD"),
);
let document: serde_json::Value =
serde_json::from_str(&answer).expect("the answer is still one JSON document");
assert_eq!(document["format"], "psd (from the file name)");
assert_eq!(document["mode"], "Rgb", "the engine's own fields stand");
for name in ["/work/scan", "/work/scan."] {
let answer = inspection_answer(r#"{"file":"x"}"#, Path::new(name));
let document: serde_json::Value =
serde_json::from_str(&answer).expect("still one JSON document");
assert_eq!(
document["format"],
"unknown (the file name has no extension)"
);
}
let answer = inspection_answer("mode: Rgb\ndepth: 8\n", Path::new("/work/plate.pcraft"));
assert_eq!(
answer,
"mode: Rgb\ndepth: 8\nformat: pcraft (from the file name)"
);
let answer = inspection_answer(
"{\"mode\":\"Rgb\"}\nwarning: a profile could not be embedded",
Path::new("/work/plate.psd"),
);
let (document, beside) = answer
.split_once('\n')
.expect("the warning stays after the document");
assert_eq!(beside, "warning: a profile could not be embedded");
let document: serde_json::Value =
serde_json::from_str(document).expect("still one JSON document");
assert_eq!(document["format"], "psd (from the file name)");
assert_eq!(document["mode"], "Rgb");
}
#[test]
fn a_layered_inspection_keeps_its_facts_and_counts_the_layers_that_do_not_fit() {
for count in 1..=40 {
for padding in [0, 7, 13, 29, 41] {
let layers: Vec<serde_json::Value> = (0..count)
.map(|index| {
json!({
"name": format!("Layer {index}{}", "x".repeat(padding)),
"kind": "pixel",
"visible": true,
"opacity": 100,
"blend": "normal",
"bounds": {"x": 0, "y": 0, "width": 3000, "height": 2000},
"source": format!("/work/plate.psd#layer{index}"),
"mask": {"path": format!("/work/mask-{index}.png"), "enabled": true, "density": 100},
"effects": {"dropShadow": false, "stroke": false, "bevel": false},
})
})
.collect();
let document = json!({
"file": "/work/plate.psd",
"width": 3000,
"height": 2000,
"mode": "Rgb",
"depth": 8,
"layers": layers,
"notes": [],
"selectedLayers": [],
"snapshots": [],
"warnings": [],
})
.to_string();
if document.len() <= MAX_ANSWER_BYTES {
continue;
}
let where_ = format!("{count} layers padded by {padding}");
let answer = inspection_answer(&document, Path::new("/work/plate.psd"));
assert!(
answer.len() <= MAX_ANSWER_BYTES,
"{where_}: {}",
answer.len()
);
assert_eq!(
crate::util::truncate_tool_output(&answer),
answer,
"{where_}"
);
let document: serde_json::Value = serde_json::from_str(&answer)
.unwrap_or_else(|_| panic!("{where_}: not one JSON document: {answer}"));
for fact in ["format", "width", "height", "mode", "depth"] {
assert!(
!document[fact].is_null(),
"{where_}: {fact} was lost: {answer}"
);
}
assert_eq!(document["notes"], json!([]), "{where_}: {answer}");
let kept = document["layers"]
.as_array()
.unwrap_or_else(|| panic!("{where_}: {}", document["layers"]));
let (note, entries) = kept.split_last().expect("{where_}: the tree is not empty");
assert_eq!(
note.as_str(),
Some(
format!(
"… {} of {count} further entries not shown",
count - entries.len()
)
.as_str()
),
"{where_}"
);
assert_eq!(
entries[0]["name"],
format!("Layer 0{}", "x".repeat(padding)),
"{where_}"
);
}
}
}
#[test]
fn a_layered_inspection_leaves_a_later_array_its_own_count() {
let warnings: Vec<serde_json::Value> = (0..300)
.map(|index| json!(format!("layer {index} has no colour profile")))
.collect();
let layers: Vec<serde_json::Value> = (0..400)
.map(|index| {
json!({
"name": format!("Layer {index}"),
"kind": "pixel",
"visible": true,
"bounds": {"x": 0, "y": 0, "width": 3000, "height": 2000},
})
})
.collect();
let document = json!({
"file": "/work/plate.psd",
"width": 3000,
"height": 2000,
"mode": "Rgb",
"depth": 8,
"layers": layers,
"warnings": warnings,
})
.to_string();
let answer = inspection_answer(&document, Path::new("/work/plate.psd"));
assert!(answer.len() <= MAX_ANSWER_BYTES, "{}", answer.len());
let document: serde_json::Value =
serde_json::from_str(&answer).expect("still one whole JSON document");
assert_eq!(document["mode"], "Rgb", "{answer}");
for name in ["layers", "warnings"] {
let kept = document[name]
.as_array()
.unwrap_or_else(|| panic!("{name}: {}", document[name]));
assert!(
kept.last().is_some_and(serde_json::Value::is_string),
"{name} keeps its count of the rest: {answer}"
);
}
}
#[test]
fn a_narrowed_answer_drops_whole_commands_and_says_how_many_it_left_out() {
let rows: Vec<serde_json::Value> = (0..500)
.map(|index| json!({"id": format!("image.command{index}"), "params": "x".repeat(40)}))
.collect();
let text = serde_json::to_string_pretty(&rows).expect("the answer serializes");
assert!(text.len() > MAX_ANSWER_BYTES, "the fixture must not fit");
let capped = capped_rows(&text);
let body = capped
.lines()
.take_while(|line| !line.starts_with('…'))
.collect::<Vec<_>>()
.join("\n");
let parsed: Vec<serde_json::Value> =
serde_json::from_str(&body).expect("the kept commands are a JSON array");
assert!(!parsed.is_empty(), "the answer carries what fits");
assert!(parsed.len() < rows.len());
assert_eq!(
parsed,
rows[..parsed.len()].to_vec(),
"leading commands only"
);
let note = capped
.lines()
.last()
.expect("the cap says what it left out");
assert!(
note.contains(&format!(
"{} of 500 matching commands not shown",
rows.len() - parsed.len()
)),
"{note}"
);
assert!(note.contains("a narrower filter shows the rest"), "{note}");
assert!(capped.len() <= MAX_ANSWER_BYTES, "{}", capped.len());
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
}
#[test]
fn a_narrowed_answer_that_fits_comes_back_as_the_vendor_wrote_it() {
let rows: Vec<serde_json::Value> = (0..180)
.map(|index| json!({"id": format!("image.command{index}")}))
.collect();
let pretty = serde_json::to_string_pretty(&rows).expect("the answer serializes");
let compact = serde_json::to_string(&rows).expect("the answer serializes");
assert!(
pretty.len() > MAX_ANSWER_BYTES,
"the fixture must not fit as printed"
);
assert!(
compact.len() <= MAX_ANSWER_BYTES,
"the fixture fits compactly"
);
let capped = registry_answer(Some("command"), &pretty);
assert!(!capped.contains('…'), "nothing was left out: {capped}");
assert_eq!(
serde_json::from_str::<Vec<serde_json::Value>>(&capped).expect("still a JSON array"),
rows
);
}
#[test]
fn a_narrowed_answer_that_is_not_a_json_array_is_still_cut_on_whole_lines() {
let text = "image.crop: Crop\n".repeat(2000);
let capped = capped_rows(&text);
assert!(
capped
.lines()
.all(|line| line == "image.crop: Crop" || line.starts_with('…')),
"whole lines only"
);
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
}
#[test]
fn a_narrowed_answer_finds_its_commands_beside_a_warning_the_engine_wrote() {
let rows: Vec<serde_json::Value> = (0..300)
.map(|index| json!({"id": format!("image.command{index}"), "params": "x".repeat(40)}))
.collect();
let text = format!(
"{}\nwarning: some profile could not be embedded",
serde_json::to_string_pretty(&rows).expect("the answer serializes")
);
let capped = capped_rows(&text);
let body = capped
.lines()
.take_while(|line| !line.starts_with('…'))
.collect::<Vec<_>>()
.join("\n");
let parsed: Vec<serde_json::Value> =
serde_json::from_str(&body).expect("the kept commands are a JSON array");
assert!(!parsed.is_empty());
assert!(parsed.len() < rows.len());
assert_eq!(parsed, rows[..parsed.len()].to_vec());
}
#[test]
fn a_command_too_long_to_fit_whole_is_dropped_with_a_count_rather_than_cut_mid_entry() {
let rows = vec![json!({"id": "image.crop", "params": "x".repeat(MAX_ANSWER_BYTES)})];
let text = serde_json::to_string_pretty(&rows).expect("the answer serializes");
let capped = capped_rows(&text);
let mut lines = capped.lines();
assert_eq!(lines.next(), Some("[]"), "{capped}");
let note = lines.next().expect("the cap says what it left out");
assert!(
note.contains("all 1 matching command(s) not shown"),
"{note}"
);
assert!(note.contains("longer than a whole answer"), "{note}");
assert_eq!(lines.next(), None, "nothing else is left: {capped}");
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
}
#[test]
fn a_failed_run_carries_the_exit_detail_and_the_vendors_own_words() {
let message = failure(
"run",
&outcome("exit status 2", "unknown flag --cmdd\n", None),
);
assert_eq!(
message,
"photocraft run failed (exit status 2): unknown flag --cmdd"
);
}
#[test]
fn a_failure_with_no_reason_says_so_instead_of_leaving_an_empty_parenthesis() {
assert_eq!(
failure("run", &outcome("", "", None)),
"photocraft run failed (no reason was reported)"
);
}
#[test]
fn a_run_the_product_never_started_says_so_instead_of_quoting_an_io_error() {
let message = failure(
"run",
&outcome("io error: No such file or directory", "", Some(Stop::Spawn)),
);
assert!(message.contains("could not be started"), "{message}");
assert!(!message.contains("No such file"), "{message}");
}
#[test]
fn the_memory_watchdog_is_named_as_the_product_stopping_the_run() {
let message = failure(
"batch",
&outcome(
"terminated: exceeded memory limit (used ~15.4 GiB of 18.0 GiB)",
"",
Some(Stop::Memory),
),
);
assert!(message.contains("memory watchdog"), "{message}");
assert!(message.contains("exceeded memory limit"), "{message}");
}
#[test]
fn the_summary_and_the_failures_are_the_vendors_own_lines_and_nothing_else_is() {
for summary in [
"0 succeeded, 0 failed",
"300 succeeded, 1 failed",
"4 succeeded, 2 failed, 7 skipped",
] {
assert!(is_summary(summary), "{summary}");
}
for other in [
"ok /in/a.png -> /out/a.png",
"FAIL /in/a.png: unreadable header",
"error: 1 file(s) failed",
"300 files succeeded, 1 failed",
"warning: photo1.jpg: no ICC profile",
] {
assert!(!is_summary(other), "{other}");
}
assert!(is_failure("FAIL /in/a.png: unreadable header"));
assert!(!is_failure("error: 1 file(s) failed"));
assert!(!is_failure("ok /in/a.png -> /out/a.png"));
}
#[test]
fn a_batch_that_ran_to_its_summary_is_an_answer_and_one_that_stopped_is_a_failure() {
let ran = ProgramOutcome {
success: false,
detail: "exit status 1".to_string(),
output: "ok /in/a.png -> /out/a.png\n1 succeeded, 1 failed\nFAIL /in/b.png: unreadable header".to_string(),
has_output: true,
stop: None,
};
let report = batch_outcome(&ran, &counted(1), Path::new("/out"))
.expect("the run reached its summary");
let answer = &report.answer;
assert_eq!(answer.lines().next(), Some("1 file(s) written to /out"));
assert!(
answer.contains("FAIL /in/b.png: unreadable header"),
"{answer}"
);
assert!(
answer.lines().any(|line| line == "1 succeeded, 1 failed"),
"{answer}"
);
assert!(report.partial, "{answer}");
let stopped = ProgramOutcome {
success: false,
detail: "exit status 1".to_string(),
output: "ok /in/a.png -> /out/a.png\nerror: the disk is full".to_string(),
has_output: true,
stop: None,
};
let error = batch_outcome(&stopped, &counted(1), Path::new("/out"))
.expect_err("no summary, no report");
assert!(
error.starts_with("photocraft batch failed (exit status 1)"),
"{error}"
);
assert!(error.contains("the disk is full"), "{error}");
let clean = ProgramOutcome {
success: true,
detail: "exit status 0".to_string(),
output: "ok /in/a.png -> /out/a.png".to_string(),
has_output: true,
stop: None,
};
let report = batch_outcome(&clean, &counted(1), Path::new("/out"))
.expect("a clean run is an answer");
assert_eq!(
report.answer.lines().next(),
Some("1 file(s) written to /out")
);
assert!(!report.partial, "a clean run is no shortfall");
}
#[test]
fn a_batch_that_produced_nothing_is_a_partial_answer_not_a_success() {
let report = batch_outcome(
&outcome("exit status 1", "0 succeeded, 2 failed\nFAIL /in/a.heic: unreadable header\nFAIL /in/b.heic: unreadable header", None),
&counted(0),
Path::new("/out"),
)
.expect("the run reached its summary");
assert_eq!(
report.answer.lines().next(),
Some("no file was written into /out")
);
assert!(report.partial, "{}", report.answer);
let summary_only = outcome("exit status 1", "3 succeeded, 4 failed", None);
assert!(failed_some(&summary_only.output));
assert!(!failed_some(
"ok /in/a.png -> /out/a.png\n1 succeeded, 0 failed"
));
}
#[test]
fn an_inspection_whose_own_fields_alone_do_not_fit_keeps_the_format_and_counts_the_rest() {
let mut document = serde_json::Map::new();
document.insert("mode".to_string(), json!("Rgb"));
document.insert("depth".to_string(), json!(8));
for index in 0..8 {
document.insert(format!("field{index}"), json!("y".repeat(800)));
}
let answer = inspection_answer(
&serde_json::Value::Object(document).to_string(),
Path::new("/work/plate.psd"),
);
assert!(answer.len() <= MAX_ANSWER_BYTES, "{}", answer.len());
let document: serde_json::Value =
serde_json::from_str(&answer).expect("still one whole JSON document");
assert_eq!(document["format"], "psd (from the file name)");
assert_eq!(document["omitted"], "… 10 further member(s) not shown");
assert_eq!(crate::util::truncate_tool_output(&answer), answer);
}
#[test]
fn a_count_the_folder_could_not_be_read_for_is_stated_as_the_floor_it_is() {
let short = FilesWritten {
count: 12,
whole: false,
};
let report = "ok /work/in/a.png -> /work/out/a.png\n1 succeeded, 0 failed";
let answer = batch_answer(report, &short, Path::new("/work/out"));
assert_eq!(
answer.lines().next(),
Some("at least 12 file(s) written to /work/out (the folder could not be read in full)")
);
let unread = batch_answer(
report,
&FilesWritten {
count: 0,
whole: false,
},
Path::new("/work/out"),
);
assert_eq!(
unread.lines().next(),
Some("the files in /work/out could not be counted")
);
assert_eq!(
counted(12).written_into(Path::new("/work/out")),
"12 file(s) written to /work/out"
);
assert_eq!(
counted(0).written_into(Path::new("/work/out")),
"no file was written into /work/out"
);
}
#[test]
fn a_failure_longer_than_the_whole_per_file_report_is_still_named() {
let mut spelled: Vec<String> = (0..400)
.map(|index| format!("ok /work/in/photo{index}.jpg -> /work/out/photo{index}.jpg"))
.collect();
let reason = "x".repeat(2_600);
spelled.push(format!("FAIL /work/in/deep/photo.jpg: {reason}"));
spelled.push("400 succeeded, 1 failed".to_string());
let output = spelled.join("\n");
let capped = batch_answer(&output, &counted(400), Path::new("/work/out"));
assert!(
capped.contains(&format!("FAIL /work/in/deep/photo.jpg: {reason}")),
"the failing file is named"
);
assert_eq!(capped.lines().last(), Some("400 succeeded, 1 failed"));
assert!(capped.len() <= MAX_ANSWER_BYTES, "{}", capped.len());
assert_eq!(crate::util::truncate_tool_output(&capped), capped);
}
#[test]
fn a_wall_of_output_is_bounded_before_it_reaches_a_model() {
let message = failure(
"batch",
&outcome(
"exit status 1",
&format!("{}broken.png: unreadable\n", "noise line\n".repeat(1000)),
None,
),
);
assert!(
message.chars().count() <= MAX_FAILURE_BYTES + 256,
"{}",
message.chars().count()
);
assert!(message.ends_with("broken.png: unreadable"), "{message}");
assert!(
message.contains("bytes omitted"),
"the cut says so: {message}"
);
}
}