refactor(cli): anicraft-cli follows RFC-0018 (clap, typed errors, run(args, out, err), exit codes 0/1/2)

This commit is contained in:
FredApps committed 2026-11-26 23:25:02 +01:00
1 parent 259566a033
commit 7a1a75b894
15 files changed
+2371 -1106

No files matched your search

Generated
+155
View File
@@ -284,8 +284,12 @@ dependencies = [
"anicraft-geom",
"anicraft-guide",
"anicraft-render",
"clap",
"clap_complete",
"clap_mangen",
"getrandom 0.3.4",
"serde_json",
"thiserror 2.0.21",
"wat",
]
@@ -467,6 +471,56 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]]
name = "arboard"
version = "3.7.0"
@@ -1029,6 +1083,65 @@ dependencies = [
"num-traits",
]
[[package]]
name = "clap"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_complete"
version = "4.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "clap_mangen"
version = "0.2.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78"
dependencies = [
"clap",
"roff",
]
[[package]]
name = "clipboard-win"
version = "5.4.3"
@@ -1064,6 +1177,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "combine"
version = "4.6.9"
@@ -2500,6 +2619,12 @@ dependencies = [
"fearless_simd",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.3"
@@ -2728,6 +2853,12 @@ dependencies = [
"memoffset",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.14.0"
@@ -3621,6 +3752,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "oorandom"
version = "11.1.5"
@@ -4282,6 +4419,12 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "roff"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
[[package]]
name = "roxmltree"
version = "0.21.2"
@@ -4728,6 +4871,12 @@ dependencies = [
"serde",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
@@ -5408,6 +5557,12 @@ dependencies = [
"utf_types",
]
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "utf_types"
version = "1.0.0"
+3
View File
@@ -64,6 +64,9 @@ anicraft-actions = { path = "crates/actions" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4"
clap_mangen = "0.2"
rayon = "1"
# Unions of flattened polygons on an integer grid, for a stroke's outline (ADR 0110): pure
# Rust, no unsafe in our use, MIT OR Apache-2.0 (its i_float, i_shape, i_tree and i_key_sort: MIT).
+5
View File
@@ -23,6 +23,8 @@ anicraft-guide.workspace = true
# The legacy Flash container, for `fla-dump` (ADR 0120).
anicraft-fla.workspace = true
serde_json.workspace = true
thiserror.workspace = true
clap.workspace = true
# The live control port's per-run token (ADR 0104): the operating system's random numbers.
# MIT OR Apache-2.0, already in the tree. Not for the web: a page has no sockets, so the control
@@ -31,6 +33,9 @@ serde_json.workspace = true
getrandom = "0.3"
[dev-dependencies]
# Man pages and shell completions, written by `examples/man-and-completions.rs` (RFC-0018 rule 1.9).
clap_complete.workspace = true
clap_mangen.workspace = true
# Exporter plug-in fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception).
wat = "1.228"
@@ -0,0 +1,42 @@
//! Writes anicraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
//! PowerShell) and man pages ([`clap_mangen`]: `anicraft-cli.1` and one per subcommand, such as
//! `anicraft-cli-render.1`) into a directory. The Linux packages ship them
//! (`packaging/linux/package.sh`):
//!
//! ```sh
//! cargo run -p anicraft-cli --example man-and-completions -- <out-dir>
//! ```
use std::path::Path;
use std::process::ExitCode;
use clap::ValueEnum;
use clap_complete::Shell;
fn main() -> ExitCode {
let mut args = std::env::args_os().skip(1);
let (Some(dir), None) = (args.next(), args.next()) else {
eprintln!("usage: man-and-completions <out-dir>");
return ExitCode::from(2);
};
let dir = Path::new(&dir);
match generate(dir) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("error: {}: {e}", dir.display());
ExitCode::FAILURE
}
}
}
/// Also run by the tests.
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let mut cmd = anicraft_cli::command();
for &shell in Shell::value_variants() {
clap_complete::generate_to(shell, &mut cmd, "anicraft-cli", dir)?;
}
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
// which `clap_mangen` would otherwise give pages of its own (`anicraft-cli-help-render.1`).
clap_mangen::generate_to(anicraft_cli::command(), dir)
}
+544
View File
@@ -0,0 +1,544 @@
//! The command line as clap derive types. Values arrive typed, so the commands never validate a
//! string; what clap can't say alone is a usage error built here, printed and exited (2) like
//! clap's own. The help text is the doc comments (RFC-0018 rule 1.8).
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use clap::builder::BoolishValueParser;
use clap::error::ErrorKind;
use clap::{Arg, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use serde_json::Value;
/// The end of `--help` of every command.
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 a command failed\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
/// What a document argument is.
const DOCUMENT_NOTE: &str = "The document is an .anicraft file, an Animate document (.fla, .xfl) or `--sample`, a built-in sample.";
const FRAMES_NOTE: &str = "Frame flags on the command line (--frame, --from, --to) are 1-based, as in the timeline. Frame numbers inside JSON params, scripts and command results are 0-based, as everywhere in the engine.";
const ROOTS_NOTE: &str = "Commands read files only inside the read roots and write only inside the write root: links and `..` are followed first, and a refusal names the root. --automation-read-root may be given several times (docs/mcp.md).";
/// AniCraft without a window: headless animation engine, MCP server and the app's control channel
#[derive(Parser, Debug)]
#[command(name = "anicraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = EXIT_STATUS, after_long_help = format!("{FRAMES_NOTE}\n\n{EXIT_STATUS}"))]
pub(crate) struct Cli {
#[command(subcommand)]
pub(crate) command: Command,
}
#[derive(Subcommand, Debug)]
pub(crate) enum Command {
/// Print a document's state as JSON
#[command(after_help = DOCUMENT_NOTE)]
Info(InfoArgs),
/// List the streams and CPic* record tags of a legacy Flash 8-CS4 .fla file as JSON
FlaDump(FlaDumpArgs),
/// Render one frame to a PNG file
#[command(after_help = format!("{DOCUMENT_NOTE}\n{FRAMES_NOTE}"))]
Render(RenderArgs),
/// Render a frame range to numbered PNG files in a folder
#[command(after_help = format!("{DOCUMENT_NOTE}\n{FRAMES_NOTE}"))]
RenderSeq(RenderSeqArgs),
/// Write an animated GIF
#[command(after_help = format!("{DOCUMENT_NOTE}\n{FRAMES_NOTE}"))]
Gif(GifArgs),
/// Write an animated PNG, in full colour with real transparency
#[command(after_help = format!("{DOCUMENT_NOTE}\n{FRAMES_NOTE}"))]
Apng(MotionArgs),
/// Write an animated WebP (lossless), in full colour with real transparency
#[command(after_help = format!("{DOCUMENT_NOTE}\n{FRAMES_NOTE}"))]
Webp(MotionArgs),
/// Export in any format: a built-in one or an exporter plug-in
///
/// The built-in formats are gif, apng, webp, lottie, html, video, svg, png, png-sequence,
/// svg-sequence and sprite-sheet; exporter plug-ins are named by id and need --plugins.
/// `formats` lists them all. --options are the plug-in's options, or a built-in's extra
/// params, as a JSON object.
#[command(after_help = format!("{DOCUMENT_NOTE}\n{FRAMES_NOTE}"))]
Export(ExportArgs),
/// List every export format, plug-ins included, as JSON
Formats(FormatsArgs),
/// List every command with its parameters, as JSON
Commands,
/// Run a script on a document: a JSON array of {cmd, params}, or a saved command
///
/// The steps are one undo step, and nothing changes if one fails. With FILE, the document is
/// FILE; with --sample, the first argument is the script.
#[command(after_help = DOCUMENT_NOTE, override_usage = "anicraft-cli run [OPTIONS] <FILE> <SCRIPT>\n anicraft-cli run [OPTIONS] --sample <SCRIPT>")]
Run(RunArgs),
/// Run one command on a document and print its result
///
/// With FILE, the arguments are FILE, the command id and its JSON params; with --sample, the
/// command id and its JSON params.
#[command(after_help = DOCUMENT_NOTE, override_usage = "anicraft-cli exec [OPTIONS] <FILE> <COMMAND> [PARAMS]\n anicraft-cli exec [OPTIONS] --sample <COMMAND> [PARAMS]")]
Exec(ExecArgs),
/// Create an empty document
New(NewArgs),
/// Write the user guide as HTML pages, or search it
#[command(args_conflicts_with_subcommands = true, subcommand_negates_reqs = true)]
Guide(GuideArgs),
/// Performance probe on a generated stress document (use --release)
Bench(BenchArgs),
/// Serve JSON-lines requests on stdin and stdout
///
/// One request per line, for example
/// {"id":1,"cmd":"draw.rect","params":{"x":10,"y":10,"w":50,"h":50}}.
#[command(after_help = format!("{DOCUMENT_NOTE}\n{ROOTS_NOTE}"))]
Serve(ServeArgs),
/// Serve the Model Context Protocol on stdin and stdout, for AI assistants (docs/mcp.md)
///
/// Both roots are required: an assistant's commands read files only inside the read roots and
/// write only inside the write root. With --bridge, the same tools act live on the AniCraft
/// window started with `anicraft --control <port>` (docs/control-protocol.md); the window
/// applies the roots to this assistant's commands.
#[command(after_help = format!("{DOCUMENT_NOTE}\n{ROOTS_NOTE}"))]
Mcp(McpArgs),
}
/// A document to open: a path, or the built-in sample.
#[derive(Args, Debug)]
pub(crate) struct Document {
/// The document
#[arg(value_name = "FILE", required_unless_present = "sample")]
pub(crate) file: Option<PathBuf>,
/// Use the built-in sample instead of a file
#[arg(long, conflicts_with = "file")]
pub(crate) sample: bool,
}
/// A document that may be left out: a new, empty one then.
#[derive(Args, Debug)]
pub(crate) struct OptionalDocument {
/// The document
#[arg(value_name = "FILE")]
pub(crate) file: Option<PathBuf>,
/// Use the built-in sample instead of a file
#[arg(long, conflicts_with = "file")]
pub(crate) sample: bool,
}
/// `--plugins`, for what opens a session.
#[derive(Args, Debug)]
pub(crate) struct Plugins {
/// Load the WebAssembly plug-ins in a folder first
#[arg(long, value_name = "FOLDER", env = "ANICRAFT_PLUGINS", value_parser = non_empty_path)]
pub(crate) plugins: Option<PathBuf>,
}
/// `--from` and `--to` (1-based, inclusive) and `--scale`.
#[derive(Args, Debug)]
pub(crate) struct Range {
/// First frame, counting from 1
#[arg(long, value_name = "N", value_parser = frame_number)]
pub(crate) from: Option<u32>,
/// Last frame, counting from 1
#[arg(long, value_name = "N", value_parser = frame_number)]
pub(crate) to: Option<u32>,
/// Scale of the stage, 1 for its own size
#[arg(long, value_name = "S", value_parser = finite_number)]
pub(crate) scale: Option<f32>,
}
#[derive(Args, Debug)]
pub(crate) struct InfoArgs {
#[command(flatten)]
pub(crate) document: Document,
#[command(flatten)]
pub(crate) plugins: Plugins,
}
#[derive(Args, Debug)]
pub(crate) struct FlaDumpArgs {
/// A legacy .fla file
#[arg(value_name = "FILE")]
pub(crate) file: PathBuf,
/// Only this stream's tags
#[arg(long, value_name = "NAME")]
pub(crate) stream: Option<String>,
}
#[derive(Args, Debug)]
pub(crate) struct RenderArgs {
#[command(flatten)]
pub(crate) document: Document,
/// The PNG file to write
#[arg(long = "out", value_name = "FRAME.PNG")]
pub(crate) output: PathBuf,
/// The frame, counting from 1 (the first one without it)
#[arg(long, value_name = "N", value_parser = frame_number)]
pub(crate) frame: Option<u32>,
/// Scale of the stage, 1 for its own size
#[arg(long, value_name = "S", value_parser = finite_number)]
pub(crate) scale: Option<f32>,
#[command(flatten)]
pub(crate) plugins: Plugins,
}
#[derive(Args, Debug)]
pub(crate) struct RenderSeqArgs {
#[command(flatten)]
pub(crate) document: Document,
/// The folder to write frame_00001.png, ... into
#[arg(long = "out-dir", value_name = "DIR")]
pub(crate) output: PathBuf,
#[command(flatten)]
pub(crate) range: Range,
#[command(flatten)]
pub(crate) plugins: Plugins,
}
#[derive(Args, Debug)]
pub(crate) struct GifArgs {
#[command(flatten)]
pub(crate) document: Document,
/// The GIF file to write
#[arg(long = "out", value_name = "ANIM.GIF")]
pub(crate) output: PathBuf,
#[command(flatten)]
pub(crate) range: Range,
/// Replace the file if it exists (`--overwrite yes` still works)
#[arg(long, num_args = 0..=1, default_missing_value = "yes", default_value = "no", value_parser = BoolishValueParser::new(), value_name = "yes|no", hide_possible_values = true)]
pub(crate) overwrite: bool,
#[command(flatten)]
pub(crate) plugins: Plugins,
}
/// How many times an animation plays.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Loop {
Forever,
Times(u32),
}
fn loop_count(text: &str) -> Result<Loop, String> {
if text == "forever" {
return Ok(Loop::Forever);
}
text.parse().map(Loop::Times).map_err(|_| format!("forever, or how many times it plays, not '{text}'"))
}
#[derive(Args, Debug)]
pub(crate) struct MotionArgs {
#[command(flatten)]
pub(crate) document: Document,
/// The file to write (.png for apng, .webp for webp)
#[arg(long = "out", value_name = "ANIM")]
pub(crate) output: PathBuf,
#[command(flatten)]
pub(crate) range: Range,
/// How many times it plays: forever, or a number
#[arg(long = "loop", value_name = "forever|N", value_parser = loop_count)]
pub(crate) loops: Option<Loop>,
/// Paint the stage background instead of leaving it transparent
#[arg(long, num_args = 0..=1, default_missing_value = "yes", default_value = "no", value_parser = BoolishValueParser::new(), value_name = "yes|no", hide_possible_values = true)]
pub(crate) background: bool,
/// Replace the file if it exists (`--overwrite yes` still works)
#[arg(long, num_args = 0..=1, default_missing_value = "yes", default_value = "no", value_parser = BoolishValueParser::new(), value_name = "yes|no", hide_possible_values = true)]
pub(crate) overwrite: bool,
#[command(flatten)]
pub(crate) plugins: Plugins,
}
#[derive(Args, Debug)]
pub(crate) struct ExportArgs {
#[command(flatten)]
pub(crate) document: Document,
/// The format id (`formats` lists them)
#[arg(long, value_name = "ID")]
pub(crate) format: String,
/// The file to write, or the folder for a sequence
#[arg(long = "out", value_name = "PATH")]
pub(crate) output: PathBuf,
/// First frame, counting from 1
#[arg(long, value_name = "N", value_parser = frame_number, conflicts_with = "frame")]
pub(crate) from: Option<u32>,
/// Last frame, counting from 1
#[arg(long, value_name = "N", value_parser = frame_number, conflicts_with = "frame")]
pub(crate) to: Option<u32>,
/// The frame of png and svg, counting from 1
#[arg(long, value_name = "N", value_parser = frame_number)]
pub(crate) frame: Option<u32>,
/// Extra parameters of the format, as a JSON object
#[arg(long, value_name = "JSON", value_parser = json_text)]
pub(crate) options: Option<Value>,
/// Replace the file if it exists (`--overwrite yes` still works)
#[arg(long, num_args = 0..=1, default_missing_value = "yes", default_value = "no", value_parser = BoolishValueParser::new(), value_name = "yes|no", hide_possible_values = true)]
pub(crate) overwrite: bool,
#[command(flatten)]
pub(crate) plugins: Plugins,
}
#[derive(Args, Debug)]
pub(crate) struct FormatsArgs {
#[command(flatten)]
pub(crate) plugins: Plugins,
}
#[derive(Args, Debug)]
pub(crate) struct RunArgs {
/// FILE and the script, or only the script with --sample
#[arg(value_names = ["FILE", "SCRIPT"], num_args = 1..=2, required = true)]
inputs: Vec<OsString>,
/// Use the built-in sample instead of a file
#[arg(long)]
pub(crate) sample: bool,
/// Save the document afterwards, to this file
#[arg(long, value_name = "OUT.ANICRAFT")]
pub(crate) save: Option<PathBuf>,
/// Let --save replace the document that was opened
#[arg(long, requires = "save")]
pub(crate) in_place: bool,
#[command(flatten)]
pub(crate) plugins: Plugins,
/// The document, from the arguments. Filled in by [`parse`].
#[arg(skip)]
pub(crate) file: Option<PathBuf>,
/// The script, from the arguments. Filled in by [`parse`].
#[arg(skip)]
pub(crate) script: PathBuf,
}
#[derive(Args, Debug)]
pub(crate) struct ExecArgs {
/// FILE, the command id and its JSON params; with --sample, the id and the params
#[arg(value_names = ["FILE", "COMMAND", "PARAMS"], num_args = 1..=3, required = true)]
inputs: Vec<OsString>,
/// Use the built-in sample instead of a file
#[arg(long)]
pub(crate) sample: bool,
/// Save the document afterwards, to this file
#[arg(long, value_name = "OUT.ANICRAFT")]
pub(crate) save: Option<PathBuf>,
/// Let --save replace the document that was opened
#[arg(long, requires = "save")]
pub(crate) in_place: bool,
#[command(flatten)]
pub(crate) plugins: Plugins,
/// The document, from the arguments. Filled in by [`parse`].
#[arg(skip)]
pub(crate) file: Option<PathBuf>,
/// The command id, from the arguments. Filled in by [`parse`].
#[arg(skip)]
pub(crate) command: String,
/// The params, from the arguments. Filled in by [`parse`].
#[arg(skip)]
pub(crate) params: Value,
}
#[derive(Args, Debug)]
pub(crate) struct NewArgs {
/// The document to write
#[arg(long = "out", value_name = "FILE.ANICRAFT")]
pub(crate) output: PathBuf,
/// Stage width in pixels
#[arg(long, value_name = "W")]
pub(crate) width: Option<u32>,
/// Stage height in pixels
#[arg(long, value_name = "H")]
pub(crate) height: Option<u32>,
/// Frames per second
#[arg(long, value_name = "F", value_parser = finite_number)]
pub(crate) fps: Option<f32>,
}
#[derive(Args, Debug)]
pub(crate) struct GuideArgs {
/// The folder to write the pages to (open index.html)
#[arg(long = "out", value_name = "FOLDER", required = true)]
pub(crate) output: Option<PathBuf>,
#[command(subcommand)]
pub(crate) search: Option<GuideCommand>,
}
#[derive(Subcommand, Debug)]
pub(crate) enum GuideCommand {
/// Search the user guide: chapter, heading, page and a passage for each result, best first
Search(SearchArgs),
}
#[derive(Args, Debug)]
pub(crate) struct SearchArgs {
/// What to look for
#[arg(value_name = "WORDS", required = true, num_args = 1..)]
pub(crate) words: Vec<String>,
/// The most results
#[arg(long, value_name = "N", default_value_t = 10, value_parser = clap::value_parser!(u32).range(1..=100))]
pub(crate) limit: u32,
/// Print the results as JSON
#[arg(long, num_args = 0..=1, default_missing_value = "yes", default_value = "no", value_parser = BoolishValueParser::new(), value_name = "yes|no", hide_possible_values = true)]
pub(crate) json: bool,
}
/// A number of samples for `bench --stroke`, or `yes` for the default.
fn samples(text: &str) -> Result<u32, String> {
if matches!(text, "yes" | "true") {
return Ok(crate::bench_stroke::DEFAULT_SAMPLES);
}
text.parse().map_err(|_| "a number of samples (or yes)".to_string())
}
#[derive(Args, Debug)]
pub(crate) struct BenchArgs {
/// Layers of the stress document
#[arg(long, value_name = "N", conflicts_with_all = ["stroke", "stroke_file"])]
pub(crate) layers: Option<u32>,
/// Shapes in each layer
#[arg(long, value_name = "N", conflicts_with_all = ["stroke", "stroke_file"])]
pub(crate) shapes: Option<u32>,
/// Frames of the stress document
#[arg(long, value_name = "N", conflicts_with_all = ["stroke", "stroke_file"])]
pub(crate) frames: Option<u32>,
/// Compare the default scenario with the budgets in docs/performance.md; fails when one is missed
#[arg(long, num_args = 0..=1, default_missing_value = "yes", default_value = "no", value_parser = BoolishValueParser::new(), value_name = "yes|no", hide_possible_values = true, conflicts_with_all = ["layers", "shapes", "frames", "stroke", "stroke_file"])]
pub(crate) check: bool,
/// One long Brush stroke of this many samples: painting it, picking it, moving it and the merge when it is deselected (ADR 0129)
#[arg(long, value_name = "SAMPLES", num_args = 0..=1, default_missing_value = "yes", value_parser = samples, conflicts_with = "stroke_file")]
pub(crate) stroke: Option<u32>,
/// The same steps on a document's own artwork
#[arg(long, value_name = "FILE.ANICRAFT")]
pub(crate) stroke_file: Option<PathBuf>,
}
#[derive(Args, Debug)]
pub(crate) struct ServeArgs {
#[command(flatten)]
pub(crate) document: OptionalDocument,
#[command(flatten)]
pub(crate) plugins: Plugins,
/// A folder commands may read from (repeatable); needs --automation-write-root
#[arg(long = "automation-read-root", value_name = "FOLDER", value_parser = non_empty_path, requires = "write_root")]
read_root: Vec<PathBuf>,
/// The one folder commands may write to; needs --automation-read-root
#[arg(long = "automation-write-root", value_name = "FOLDER", value_parser = non_empty_path, requires = "read_root")]
write_root: Option<PathBuf>,
}
impl ServeArgs {
/// The roots, when both were given.
pub(crate) fn roots(&self) -> Option<(&[PathBuf], &Path)> {
Some((self.read_root.as_slice(), self.write_root.as_deref()?)).filter(|(read, _)| !read.is_empty())
}
}
#[derive(Args, Debug)]
pub(crate) struct McpArgs {
#[command(flatten)]
pub(crate) document: OptionalDocument,
#[command(flatten)]
pub(crate) plugins: Plugins,
/// Act live on the AniCraft window listening on this port (or host:port), not on a file
#[arg(long, value_name = "PORT", conflicts_with_all = ["file", "sample"])]
pub(crate) bridge: Option<String>,
/// A folder the assistant's commands may read from (repeatable)
#[arg(long = "automation-read-root", value_name = "FOLDER", value_parser = non_empty_path, required = true)]
pub(crate) read_root: Vec<PathBuf>,
/// The one folder the assistant's commands may write to (it may be a read root too)
#[arg(long = "automation-write-root", value_name = "FOLDER", value_parser = non_empty_path, required = true)]
pub(crate) write_root: PathBuf,
}
/// A path that is not empty.
fn non_empty_path(text: &str) -> Result<PathBuf, String> {
if text.trim().is_empty() { Err("needs a folder".into()) } else { Ok(PathBuf::from(text)) }
}
fn frame_number(text: &str) -> Result<u32, String> {
match text.parse::<u32>() {
Ok(0) => Err("frames count from 1; the first frame is 1".into()),
Ok(n) => Ok(n),
Err(_) => Err(format!("a whole number from 1, not '{text}'")),
}
}
/// A finite number: `NaN` and `inf` parse as floats but mean nothing here.
fn finite_number(text: &str) -> Result<f32, String> {
let value: f32 = text.parse().map_err(|_| format!("a number, not '{text}'"))?;
if value.is_finite() { Ok(value) } else { Err("a finite number".into()) }
}
fn json_text(text: &str) -> Result<Value, String> {
serde_json::from_str(text).map_err(|e| format!("not JSON: {e}"))
}
/// For `Command::mut_args`: an empty or blank variable counts as unset (RFC-0018 rule 1.7),
/// where clap would pass the empty value to the parser.
fn blank_env_is_unset(arg: Arg) -> Arg {
let blank = arg.get_env().and_then(std::env::var_os).is_some_and(|v| v.to_str().is_some_and(|v| v.trim().is_empty()));
if blank { arg.env(None::<&str>) } else { arg }
}
fn blank_envs(command: clap::Command) -> clap::Command {
command.mut_args(blank_env_is_unset).mut_subcommands(blank_envs)
}
/// The clap command: what `--help`, the completions and the man pages are made of.
pub(crate) fn command() -> clap::Command {
blank_envs(Cli::command())
}
/// A usage error in the way clap prints one, under the usage of `subcommand`.
fn usage_error(subcommand: &str, message: impl std::fmt::Display) -> clap::Error {
let mut command = command();
command.build();
let mut command = command.find_subcommand_mut(subcommand).map_or_else(command_fallback, std::mem::take);
command.error(ErrorKind::ArgumentConflict, message)
}
fn command_fallback() -> clap::Command {
command()
}
/// Splits the positional arguments of `run` and `exec` into the document and the rest: with
/// `--sample`, none of them is the document.
fn split(subcommand: &str, sample: bool, inputs: &[OsString], names: &[&str]) -> Result<(Option<PathBuf>, Vec<OsString>), clap::Error> {
let (file, rest) = if sample { (None, inputs) } else { (inputs.first().map(PathBuf::from), inputs.get(1..).unwrap_or_default()) };
// The names in `[]` are optional, the others are required.
let required = names.iter().filter(|n| !n.starts_with('[')).count();
if rest.len() < required || rest.len() > names.len() {
let shape = if sample { format!("--sample {}", names.join(" ")) } else { format!("<FILE> {}", names.join(" ")) };
return Err(usage_error(subcommand, format!("expected {shape}")));
}
Ok((file, rest.to_vec()))
}
/// Parses the arguments (without the program name). Help and the version come back as errors too,
/// which print to stdout and exit 0.
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let matches = command().try_get_matches_from(std::iter::once(OsString::from("anicraft-cli")).chain(args.iter().cloned()))?;
let mut cli = Cli::from_arg_matches(&matches)?;
match &mut cli.command {
Command::Run(run) => {
let (file, rest) = split("run", run.sample, &run.inputs, &["SCRIPT"])?;
run.file = file;
run.script = rest.first().map(PathBuf::from).unwrap_or_default();
}
Command::Exec(exec) => {
let (file, rest) = split("exec", exec.sample, &exec.inputs, &["COMMAND", "[PARAMS]"])?;
exec.file = file;
let text =
|s: &OsString| s.to_str().map(str::to_owned).ok_or_else(|| usage_error("exec", "the command id and params must be valid Unicode"));
exec.command = rest.first().map(text).transpose()?.unwrap_or_default();
exec.params = match rest.get(1) {
Some(t) => serde_json::from_str(&text(t)?).map_err(|e| usage_error("exec", format!("the params are not JSON: {e}")))?,
None => serde_json::json!({}),
};
}
Command::Mcp(mcp) => {
if let Some(target) = &mcp.bridge {
// The variable alone doesn't conflict: only the flag says this run wants plug-ins.
let sub = matches.subcommand_matches("mcp");
if sub.and_then(|m| m.value_source("plugins")) == Some(clap::parser::ValueSource::CommandLine) {
return Err(usage_error("mcp", "--bridge acts on the open AniCraft window: it takes no --plugins"));
}
#[cfg(not(target_arch = "wasm32"))]
crate::control::parse_bridge_target(target).map_err(|reason| usage_error("mcp", format!("--bridge {target}: {reason}")))?;
#[cfg(target_arch = "wasm32")]
let _ = target;
}
}
_ => {}
}
Ok(cli)
}
+13 -13
View File
@@ -3,7 +3,8 @@
//! 0122), and each step is timed. `--stroke-file` times the same steps on the artwork of a
//! document instead, so a reported file can be measured as it is.
use crate::{Args, avg_ms, open_session, round};
use crate::args::BenchArgs;
use crate::{CliError, Source, avg_ms, open_session, round};
use anicraft_engine::Session;
use serde_json::{Value, json};
use std::time::Instant;
@@ -38,23 +39,22 @@ fn segments(s: &Session) -> usize {
s.display_list().items.iter().map(|i| i.path.cmds.len()).sum()
}
pub fn bench_stroke(a: &Args) -> Result<String, String> {
let file = a.flag("stroke-file");
let samples = match a.flag("stroke") {
Some("yes" | "true") | None => DEFAULT_SAMPLES,
Some(v) => v.parse::<u32>().map_err(|_| "--stroke takes a number of samples (or yes)".to_string())?.clamp(2, MAX_SAMPLES),
};
pub fn bench_stroke(a: &BenchArgs) -> Result<String, CliError> {
let file = a.stroke_file.as_deref();
let samples = a.stroke.unwrap_or(DEFAULT_SAMPLES).clamp(2, MAX_SAMPLES);
let mut out = json!({"build": if cfg!(debug_assertions) { "debug (use --release for real numbers)" } else { "release" }});
let mut s = match file {
Some(p) => {
out["file"] = json!(p);
open_session(Some(p))?
out["file"] = json!(p.display().to_string());
open_session(Source::File(p))?
}
None => {
let mut s = Session::default();
let _ = s.execute("draw.object_drawing", &json!({"on": false}));
let t = Instant::now();
let v = s.execute("draw.brush", &json!({"points": scribble(samples), "size": 10, "color": "#000000", "object": false})).map_err(|e| e.to_string())?;
let v = s
.execute("draw.brush", &json!({"points": scribble(samples), "size": 10, "color": "#000000", "object": false}))
.map_err(|source| CliError::Command { id: "draw.brush".into(), source })?;
out["samples"] = json!(samples);
out["draw_brush_ms"] = json!(ms(t));
out["pieces"] = json!(v["elements"].as_array().map_or(0, Vec::len));
@@ -83,9 +83,9 @@ pub fn bench_stroke(a: &Args) -> Result<String, String> {
// The reporter's steps: select it, move it, let go of the mouse (it floats), deselect (it
// merges into the drawing).
let mut step = |s: &mut Session, key: &str, id: &str, p: Value| -> Result<Value, String> {
let mut step = |s: &mut Session, key: &str, id: &str, p: Value| -> Result<Value, CliError> {
let t = Instant::now();
let v = s.execute(id, &p).map_err(|e| format!("{id}: {e}"))?;
let v = s.execute(id, &p).map_err(|source| CliError::Command { id: id.to_owned(), source })?;
out[key] = json!(ms(t));
Ok(v)
};
@@ -97,5 +97,5 @@ pub fn bench_stroke(a: &Args) -> Result<String, String> {
let _ = s.undo();
out["undo_ms"] = json!(ms(t));
out["segments_after"] = json!(segments(&s));
serde_json::to_string_pretty(&out).map_err(|e| e.to_string())
Ok(serde_json::to_string_pretty(&out)?)
}
+98
View File
@@ -0,0 +1,98 @@
//! Why a subcommand failed. The exit code comes from the variant, never from the message text
//! (RFC-0018 rules 1.2 and 2.4): a mistake in how the program was started is exit 2, a command
//! that ran and failed is exit 1. clap's own errors are exit 2 and are printed by clap.
use std::path::PathBuf;
use anicraft_engine::EngineError;
/// The message of a refused Nightly launch: what the Nightly window's launcher passes, which this
/// headless tool has no use for.
pub(crate) const NIGHTLY_PROTOCOL: &str = "--launch-profile and --profile-root belong to the AniCraft Nightly window";
#[derive(Debug, thiserror::Error)]
pub enum CliError {
// ----- exit 2: the command line is wrong in a way only the run can tell -----
#[error(
"{NIGHTLY_PROTOCOL} (`{argument}`); anicraft-cli is the stable headless front end. Run `anicraft --launch-profile nightly-v1 --profile-root <folder> --` instead."
)]
NightlyProtocol { argument: String },
/// An automation root that is not a folder that exists, or that cannot be resolved.
#[error("{0}")]
Roots(String),
#[error("--automation-{flag}-root {}: {source}", path.display())]
RootPath { flag: &'static str, path: PathBuf, source: std::io::Error },
#[error("--options must be a JSON object")]
OptionsNotObject,
#[error("guide search needs words to look for, e.g. anicraft-cli guide search onion skin")]
NoSearchTerms,
#[error("bench --check needs a release build: cargo run --release -p anicraft-cli -- bench --check yes")]
CheckNeedsRelease,
#[error("mcp --bridge needs sockets, which this build doesn't have")]
NoSockets,
#[error("--bridge {target}: {reason}")]
BridgeTarget { target: String, reason: String },
#[error("{output} {} is the document it works on, which it would replace: choose another file{}", path.display(), if *in_place_helps { ", or pass --in-place" } else { "" })]
WouldReplace { output: &'static str, path: PathBuf, in_place_helps: bool },
#[error("{flag} is not used by the {format} format")]
FlagNotUsed { flag: &'static str, format: String },
#[error("--in-place is for a --save onto the opened file, and this --save is to another file or there is no file")]
InPlaceNotUsed,
// ----- exit 1: it ran and failed -----
/// The engine's commands take paths as JSON, which holds only text.
#[error("{}: the path is not valid Unicode", .0.display())]
NotUnicode(PathBuf),
#[error("{id}: {source}")]
Command { id: String, source: EngineError },
#[error("step {step}: {source}")]
Step { step: usize, source: Box<CliError> },
#[error("step {step}: missing \"cmd\"")]
MissingCmd { step: usize },
#[error("{}: {source}", path.display())]
Open { path: PathBuf, source: EngineError },
#[error("{}: {source}", path.display())]
Io { path: PathBuf, source: std::io::Error },
#[error("{}: expected a JSON array of {{cmd, params}} or a saved command: {source}", path.display())]
ScriptSyntax { path: PathBuf, source: serde_json::Error },
#[error("{}: expected a JSON array of {{cmd, params}}: {source}", path.display())]
ScriptShape { path: PathBuf, source: serde_json::Error },
#[error("{}: {source}", path.display())]
Fla { path: PathBuf, source: anicraft_fla::cfb::Error },
#[error("{}: not a legacy Flash document (its first bytes are not the compound binary signature)", path.display())]
NotLegacyFla { path: PathBuf },
#[error("no export format '{id}' (formats: {known}; exporter plug-ins load with --plugins <folder>)")]
UnknownFormat { id: String, known: String },
#[error("{0}")]
Bridge(String),
#[error("{0}")]
Stdio(std::io::Error),
#[error("{0}")]
Json(#[from] serde_json::Error),
#[error("over budget: {0}")]
OverBudget(String),
#[error("--screenshot needs the AniCraft desktop app (`anicraft`) next to anicraft-cli; build it with `cargo build`")]
NoDesktopApp,
#[error("could not start {}: {source}", path.display())]
StartDesktop { path: PathBuf, source: std::io::Error },
}
impl CliError {
/// RFC-0018 rule 1.2: 2 when the program was started wrongly, else 1.
pub fn exit_code(&self) -> i32 {
match self {
CliError::NightlyProtocol { .. }
| CliError::Roots(_)
| CliError::RootPath { .. }
| CliError::OptionsNotObject
| CliError::NoSearchTerms
| CliError::CheckNeedsRelease
| CliError::NoSockets
| CliError::BridgeTarget { .. }
| CliError::FlagNotUsed { .. }
| CliError::WouldReplace { .. }
| CliError::InPlaceNotUsed => 2,
_ => 1,
}
}
}
+446 -1062
View File
File diff suppressed because it is too large. Load diff
+5 -31
View File
@@ -1,33 +1,7 @@
fn main() {
let argv: Vec<String> = std::env::args().skip(1).collect();
// `--screenshot` is a desktop-app feature: hand over to the `anicraft` binary next to us.
if argv.iter().any(|a| a == "--screenshot") {
std::process::exit(delegate_to_desktop(&argv));
}
match anicraft_cli::run(&argv) {
Ok(out) => {
if !out.is_empty() {
println!("{out}");
}
}
Err(e) => {
eprintln!("error: {e}");
std::process::exit(anicraft_cli::exit_code(&e));
}
}
}
//! `anicraft-cli`: AniCraft without a window. See the library crate for the commands.
fn delegate_to_desktop(argv: &[String]) -> i32 {
let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.join(format!("anicraft{}", std::env::consts::EXE_SUFFIX))));
let Some(exe) = exe.filter(|p| p.exists()) else {
eprintln!("error: --screenshot needs the AniCraft desktop app (`anicraft`) next to anicraft-cli; build it with `cargo build`");
return 1;
};
match std::process::Command::new(&exe).args(argv).status() {
Ok(s) => s.code().unwrap_or(1),
Err(e) => {
eprintln!("error: could not start {}: {e}", exe.display());
1
}
}
fn main() {
// `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed.
let code = anicraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr());
std::process::exit(code);
}
+203
View File
@@ -0,0 +1,203 @@
//! Unit tests of what the integration tests (`tests/it`) can't reach: the in-process helpers,
//! the serve loop, the budgets and the plug-in and export paths.
use super::*;
use anicraft_engine::EngineError;
/// Runs the CLI in-process: its exit code, stdout and stderr.
fn cli<S: AsRef<str>>(args: &[S]) -> (i32, String, String) {
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = run(args.iter().map(|a| OsString::from(a.as_ref())), &mut out, &mut err);
(code, String::from_utf8(out).unwrap(), String::from_utf8(err).unwrap())
}
/// Stdout of a run that must succeed.
fn ok<S: AsRef<str>>(args: &[S]) -> String {
let (code, out, err) = cli(args);
assert_eq!(code, 0, "{}: {err}", args.iter().map(AsRef::as_ref).collect::<Vec<_>>().join(" "));
out.trim_end().to_string()
}
/// `<temp>/…/{work,out,secret}`: `work` is the read root and `out` the write root.
pub(crate) struct Roots3 {
pub dir: std::path::PathBuf,
pub roots: std::sync::Arc<anicraft_engine::access::Roots>,
}
impl Drop for Roots3 {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
impl Roots3 {
pub fn new(tag: &str) -> Roots3 {
let dir = std::env::temp_dir().join(format!("anicraft-cli-roots-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for d in ["work", "out", "secret"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
std::fs::write(dir.join("secret").join("s.json"), b"{\"steps\": []}").unwrap();
let roots = std::sync::Arc::new(anicraft_engine::access::Roots::new(&[dir.join("work")], Some(&dir.join("out"))).unwrap());
Roots3 { dir, roots }
}
pub fn path(&self, parts: &[&str]) -> String {
parts.iter().fold(self.dir.clone(), |p, x| p.join(x)).display().to_string()
}
}
#[test]
fn serve_keeps_inside_its_roots_when_given_them() {
let r = Roots3::new("serve");
let mut s = Session::default();
let req = |cmd: &str, path: String| json!({"cmd": cmd, "params": {"path": path}}).to_string();
let refused = handle_request_in(&mut s, Some(&r.roots), &req("file.save_as", r.path(&["secret", "x.anicraft"])));
assert_eq!(refused["ok"], false);
assert!(refused["error"].as_str().unwrap().contains("automation write root"), "{refused}");
assert_eq!(handle_request_in(&mut s, Some(&r.roots), &req("file.save_as", r.path(&["out", "x.anicraft"])))["ok"], true);
// Without roots, serve is the plain CLI it was.
assert_eq!(handle_request(&mut s, &req("file.save_as", r.path(&["secret", "y.anicraft"])))["ok"], true);
}
#[test]
fn serve_refuses_ffmpeg_path_but_exec_keeps_it() {
let mut s = Session::default();
let r = handle_request(&mut s, r#"{"cmd":"file.export_video","params":{"path":"a.mp4","ffmpeg":"/bin/sh"}}"#);
assert_eq!(r["ok"], false);
assert!(r["error"].as_str().unwrap().contains("ANICRAFT_FFMPEG"));
// Every command that runs ffmpeg takes the same parameter, and none may be given it here.
let takes_it: Vec<&str> = commands().iter().filter(|c| c.params.contains("ffmpeg?")).map(|c| c.id).collect();
assert!(takes_it.contains(&"file.export_video") && takes_it.contains(&"file.import_video"), "{takes_it:?}");
for id in takes_it {
let r = handle_request(&mut s, &json!({"cmd": id, "params": {"path": "a.mp4", "ffmpeg": "/bin/sh"}}).to_string());
assert!(r["error"].as_str().is_some_and(|e| e.contains("ANICRAFT_FFMPEG")), "{id}: {r}");
}
// Direct CLI use is not filtered: the command runs and fails on the missing program, not on the parameter.
let e = exec(&mut s, "file.export_video", &json!({"path": "a.mp4", "ffmpeg": "/nonexistent/anicraft-ffmpeg"})).unwrap_err().to_string();
assert!(!e.contains("ANICRAFT_FFMPEG environment variable"), "{e}");
}
#[test]
fn long_lines_are_bounded() {
let mut input = &b"abcdefghij\nok\r\nxy"[..];
assert!(matches!(read_line(&mut input, 4).unwrap(), Line::TooLong));
assert!(matches!(read_line(&mut input, 4).unwrap(), Line::Text(t) if t == "ok"));
assert!(matches!(read_line(&mut input, 4).unwrap(), Line::Text(t) if t == "xy"));
assert!(matches!(read_line(&mut input, 4).unwrap(), Line::Eof));
}
#[test]
fn serve_round_trip() {
let mut s = Session::default();
let input = b"\xef\xbb\xbf{\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":1,\"y\":1,\"w\":5,\"h\":5}}\nnot json\n{\"id\":3,\"cmd\":\"nope\"}\n\xef\xbb\xbf{\"cmd\":\"quit\"}\n{\"id\":4,\"cmd\":\"edit.undo\"}\n";
let mut out = Vec::new();
serve(&mut s, &input[..], &mut out).unwrap();
let lines: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines[0]["ready"], true);
assert_eq!(lines[1]["ok"], true);
assert_eq!(lines[2]["ok"], false);
assert_eq!(lines[3]["ok"], false);
assert_eq!(lines[4]["bye"], true);
assert_eq!(lines.len(), 5, "nothing runs after quit");
assert_eq!(s.visible_elements().len(), 1);
}
/// The budgets in docs/performance.md that don't depend on the machine, checked on every
/// build. (Timing budgets are `bench --check yes`, on a known machine.)
#[test]
fn machine_independent_budgets() {
use anicraft_doc::{evaluate, sample};
use anicraft_engine::history::document_bytes;
// 20 layers × 500 shapes × 120 frames: 100k element instances.
let doc = sample::stress(20, 500, 120);
let instances: usize = doc.timeline(0).layers.iter().flat_map(|l| l.keyframes.iter()).map(|k| k.elements.len()).sum();
assert_eq!(instances, 100_000);
// A snapshot (for undo, the render worker, autosave) shares everything: O(1).
let snap = doc.clone();
assert!(snap.scenes.iter().zip(&doc.scenes).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)));
// Undo memory per small edit < 16 KB, however large the document.
let mut s = Session::new(doc);
s.execute("layer.select", &json!({"index": 3})).unwrap();
s.set_frame(30);
let id = s.visible_elements()[0].id.0;
s.execute("element.select", &json!({"ids": [id]})).unwrap();
s.execute("element.translate", &json!({"dx": 5, "dy": 0})).unwrap();
let step = s.history().bytes();
assert!(step < 16 * 1024, "one edit kept {step} bytes of undo history (budget 16 KB)");
assert!(step * 1000 < document_bytes(&s.doc), "an edit keeps what changed, not the document");
// File size: < 400 bytes per element instance (shared paths are written once).
let small = sample::stress(10, 100, 48);
let n: usize = small.timeline(0).layers.iter().flat_map(|l| l.keyframes.iter()).map(|k| k.elements.len()).sum();
let bytes = format::to_json(&small).unwrap().len();
assert!(bytes < n * 400, "{} bytes per instance (budget 400)", bytes / n.max(1));
// At 400% zoom on the stage centre, off-screen shapes are culled: at most 1/8 drawn.
let dl = evaluate(&small, 5);
let view = anicraft_render::View::stage(&small, 1.0);
let zoomed =
anicraft_render::View { transform: anicraft_geom::Affine::translate(-2880.0, -1620.0).mul(&anicraft_geom::Affine::scale(4.0, 4.0)), ..view };
let (_, st) = anicraft_render::render(&dl, &zoomed).unwrap();
assert!(st.items >= 1000 && st.drawn * 8 <= st.items, "{} of {} shapes drawn at 400%", st.drawn, st.items);
}
#[test]
fn export_prefers_out_over_a_destination_in_options() {
use anicraft_engine::vfs;
vfs::use_memory();
let export = |format: &str, out: &str, options: &str| {
let argv = ["export", "--sample", "--format", format, "--out", out, "--options", options].map(str::to_string);
serde_json::from_str::<Value>(&ok(&argv)).unwrap()
};
let written_paths = || vfs::take_written().into_iter().map(|(path, _)| path).collect::<Vec<_>>();
let svg = export("svg", "chosen.svg", r#"{"path":"preset.svg","frame":2}"#);
assert_eq!(svg["frame"], 2);
assert_eq!(written_paths(), [PathBuf::from("chosen.svg")]);
let sequence = export("png-sequence", "chosen-frames", r#"{"dir":"preset-frames","from":0,"to":0,"scale":0.05}"#);
assert_eq!(sequence["frames"], 1);
assert_eq!(written_paths(), [PathBuf::from("chosen-frames").join("frame_00001.png")]);
}
#[test]
fn budget_check_reads_bench_output() {
let mut out = json!({"edit_command_ms": 0.01, "undo_ms": 0.01, "snapshot_clone_us": 0.4, "evaluate_ms_per_frame": 1.5,
"render_1080p_ms_per_frame": 20.0, "render_zoom400_ms_per_frame": 10.0, "hit_test_us": 50.0, "file": {"save_ms": 100.0}, "autosave": {"ui_us": 5.0, "background_ms": 300.0}});
let (rows, missed) = check_budgets(&out);
assert_eq!(rows.len(), TIME_BUDGETS.len());
assert_eq!(missed, ["render 1080p (ms): 20 (budget 16.7)", "load the 65 MB file (ms): not measured"]);
out["render_1080p_ms_per_frame"] = json!(16.0);
out["file"]["load_ms"] = json!(120.0);
assert!(check_budgets(&out).1.is_empty());
}
/// RFC-0018 rule 1.2: the exit code comes from the error's variant, not from its message.
#[test]
fn exit_codes_come_from_the_variant() {
let usage = [
CliError::NightlyProtocol { argument: "--launch-profile".into() },
CliError::Roots("not a folder".into()),
CliError::RootPath { flag: "read", path: PathBuf::from("x"), source: std::io::Error::other("e") },
CliError::OptionsNotObject,
CliError::NoSearchTerms,
CliError::CheckNeedsRelease,
CliError::NoSockets,
CliError::BridgeTarget { target: "x".into(), reason: "r".into() },
CliError::FlagNotUsed { flag: "--frame", format: "gif".into() },
CliError::WouldReplace { output: "--out", path: PathBuf::from("x"), in_place_helps: false },
CliError::InPlaceNotUsed,
];
for e in &usage {
assert_eq!(e.exit_code(), 2, "{e}");
}
// A message that looks like a usage error is still a failure when it comes from a command.
let from_a_command = CliError::Command { id: "file.save".into(), source: EngineError::Param("--automation-read-root needs a folder".into()) };
assert_eq!(from_a_command.exit_code(), 1, "{from_a_command}");
let failures =
[CliError::NoDesktopApp, CliError::Bridge("no app".into()), CliError::OverBudget("render".into()), CliError::NotUnicode(PathBuf::from("x"))];
for e in &failures {
assert_eq!(e.exit_code(), 1, "{e}");
}
}
+319
View File
@@ -0,0 +1,319 @@
//! RFC-0018 rule 2.7: help, versions, usage errors with exit 2 on stderr, and nothing written
//! before the arguments are checked.
use crate::{invoke, workdir};
const SUBCOMMANDS: [&str; 16] = [
"info",
"fla-dump",
"render",
"render-seq",
"gif",
"apng",
"webp",
"export",
"formats",
"commands",
"run",
"exec",
"new",
"guide",
"bench",
"serve",
];
fn usage_error(args: &[&str]) -> String {
let got = invoke(args.iter().copied());
assert_eq!(got.code, 2, "{args:?}: {}", got.err);
assert_eq!(got.out, "", "{args:?} wrote to stdout");
assert!(got.err.starts_with("error: ") || got.err.contains("Usage:"), "{args:?}: {}", got.err);
got.err
}
#[test]
fn help_and_the_version_go_to_stdout_with_exit_0() {
for args in [&["--help"][..], &["-h"], &["help"], &["--version"], &["-V"]] {
let got = invoke(args.iter().copied());
assert_eq!((got.code, got.err.as_str()), (0, ""), "{args:?}");
assert!(got.out.contains("anicraft-cli"), "{args:?}: {}", got.out);
}
let help = invoke(["--help"]).out;
assert!(help.contains("Exit status:") && help.contains("128 + the signal number"), "{help}");
assert!(help.contains("1-based") && help.contains("0-based"), "the frame numbering is explained: {help}");
for sub in SUBCOMMANDS.iter().chain(&["mcp"]) {
for flag in ["--help", "-h"] {
let got = invoke([sub, &flag]);
assert_eq!((got.code, got.err.as_str()), (0, ""), "{sub} {flag}");
assert!(got.out.contains(&format!("Usage: anicraft-cli {sub}")), "{sub}: {}", got.out);
}
assert_eq!(invoke(["help", sub]).out, invoke([sub, "--help"]).out, "{sub}");
}
}
#[test]
fn every_subcommand_takes_the_version_and_there_is_no_version_subcommand() {
let want = env!("CARGO_PKG_VERSION");
for sub in SUBCOMMANDS.iter().chain(&["mcp"]) {
for flag in ["--version", "-V"] {
let got = invoke([sub, &flag]);
assert_eq!((got.code, got.out.as_str(), got.err.as_str()), (0, format!("anicraft-cli-{sub} {want}\n").as_str(), ""), "{sub} {flag}");
}
}
assert_eq!(invoke(["--version"]).out, format!("anicraft-cli {want}\n"));
usage_error(&["version"]);
}
/// With no arguments the help goes to stderr and the exit code is 2.
#[test]
fn no_arguments_is_a_usage_error() {
let got = invoke(Vec::<&str>::new());
assert_eq!((got.code, got.out.as_str()), (2, ""));
assert!(got.err.contains("Usage: anicraft-cli"), "{}", got.err);
}
#[test]
fn an_unknown_subcommand_or_flag_is_exit_2_on_every_subcommand() {
usage_error(&["nope"]);
usage_error(&["--no-such-flag"]);
usage_error(&["nope", "--help-me"]);
for sub in &SUBCOMMANDS {
let err = usage_error(&[sub, "--no-such-option", "1"]);
assert!(err.contains("--no-such-option"), "{sub}: {err}");
}
// The typo that used to render frame 1 as if it had been asked for.
let dir = workdir("typo");
let png = dir.join("f.png");
let err = usage_error(&["render", "--sample", "--out", png.to_str().unwrap(), "--frmae", "12"]);
assert!(err.contains("--frmae") && err.contains("--frame"), "clap suggests the flag: {err}");
assert!(!png.exists(), "nothing was written");
}
#[test]
fn repeated_flags_bad_values_and_conflicts_are_usage_errors() {
let dir = workdir("values");
let png = dir.join("f.png");
let out = png.to_str().unwrap();
for args in [
vec!["render", "--sample", "--out", out, "--frame", "1", "--frame", "2"],
vec!["render", "--sample", "--out", out, "--frame", "0"],
vec!["render", "--sample", "--out", out, "--frame", "-1"],
vec!["render", "--sample", "--out", out, "--frame", "x"],
vec!["render", "--sample", "--out", out, "--scale", "NaN"],
vec!["render", "--sample", "--out", out, "--scale", "inf"],
vec!["render", "--sample", "--out", out, "--scale", "1e40"],
vec!["render", "--sample", "--out", out, "--scale"],
vec!["render", "--sample", "--out"],
vec!["render", "--sample", "--out", "--frame", "2"],
vec!["render", "--sample", "nowhere.anicraft", "--out", out],
vec!["render", "--out", out],
vec!["render", "--sample"],
vec!["render-seq", "--sample", "--out-dir", out, "--from", "0"],
vec!["gif", "--sample", "--out", out, "--overwrite", "maybe"],
vec!["apng", "--sample", "--out", out, "--loop", "twice"],
vec!["apng", "--sample", "--out", out, "--loop", "-1"],
vec!["new", "--out", out, "--width", "wide"],
vec!["new", "--out", out, "--fps", "NaN"],
vec!["new"],
vec!["export", "--sample", "--format", "svg", "--out", out, "--options", "{not json"],
vec!["export", "--sample", "--format", "png", "--out", out, "--frame", "1", "--from", "1"],
vec!["exec", "--sample", "edit.select_all", "{not json"],
vec!["exec", "--sample"],
vec!["exec"],
vec!["run", "--sample"],
vec!["run", "--sample", "a.json", "b.json"],
vec!["run", "--sample", "a.json", "--in-place"],
vec!["guide"],
vec!["guide", "search"],
vec!["guide", "search", "pen", "--limit", "x"],
vec!["guide", "search", "pen", "--limit", "0"],
vec!["guide", "search", "pen", "--limit", "101"],
vec!["guide", "--out", out, "--json", "yes"],
vec!["bench", "--layers", "many"],
vec!["bench", "--stroke", "many"],
vec!["bench", "--check", "--layers", "3"],
vec!["bench", "--stroke", "5", "--stroke-file", "f.anicraft"],
vec!["info"],
vec!["info", "--sample", "--plugins"],
vec!["info", "--sample", "--plugins", ""],
vec!["formats", "--sample"],
vec!["commands", "--json"],
] {
usage_error(&args);
}
assert!(!png.exists(), "nothing was written");
assert!(std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing was created");
}
/// A value that starts with `-` is written `--out=-image.png`, and a negative number is a value.
#[test]
fn a_dash_value_needs_the_equals_form() {
let dir = workdir("dash");
let render = |out: &str| {
let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_anicraft-cli"));
command.current_dir(&dir).args(["render", "--sample", out, "--frame=1", "--scale=0.1"]).output().unwrap()
};
let got = render("--out=-image.png");
assert_eq!(got.status.code(), Some(0), "{}", String::from_utf8_lossy(&got.stderr));
assert!(dir.join("-image.png").exists());
usage_error(&["render", "--sample", "--out", "-image.png"]);
}
#[test]
fn a_blank_plugins_variable_counts_as_unset() {
// The environment is shared by the tests of this binary: the variable is set only around one call.
let dir = workdir("env");
let out = dir.join("a.png");
let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_anicraft-cli"));
let got = command
.args(["render", "--sample", "--frame", "1", "--scale", "0.1", "--out", out.to_str().unwrap()])
.env("ANICRAFT_PLUGINS", " ")
.output()
.unwrap();
assert_eq!((got.status.code(), String::from_utf8_lossy(&got.stderr).as_ref()), (Some(0), ""));
assert!(out.exists());
}
/// No environment variable sets a destructive flag, and none of the flags that overwrite declares one.
#[test]
fn no_destructive_flag_reads_an_environment_variable() {
fn walk(command: &clap::Command, path: &str, found: &mut Vec<String>) {
for arg in command.get_arguments() {
let destructive = matches!(arg.get_id().as_str(), "overwrite" | "in_place" | "force" | "delete");
if destructive && arg.get_env().is_some() {
found.push(format!("{path} --{}", arg.get_id()));
}
}
for sub in command.get_subcommands() {
walk(sub, &format!("{path} {}", sub.get_name()), found);
}
}
let mut found = Vec::new();
walk(&anicraft_cli::command(), "anicraft-cli", &mut found);
assert!(found.is_empty(), "{found:?}");
// `--plugins` is the one flag with a variable, and `--help` lists it.
assert!(invoke(["info", "--help"]).out.contains("ANICRAFT_PLUGINS"));
}
/// RFC-0018 rule 1.6: an output never replaces its input unless `--in-place` asks.
#[test]
fn an_output_never_replaces_its_input_unless_in_place_is_given() {
let dir = workdir("replace");
let doc = dir.join("a.anicraft");
let d = doc.to_str().unwrap();
assert_eq!(invoke(["new", "--out", d]).code, 0);
let before = std::fs::read(&doc).unwrap();
for args in [
vec!["render", d, "--out", d],
vec!["render-seq", d, "--out-dir", d],
vec!["gif", d, "--out", d, "--overwrite"],
vec!["apng", d, "--out", d, "--overwrite"],
vec!["webp", d, "--out", d, "--overwrite"],
vec!["export", d, "--format", "svg", "--out", d, "--overwrite"],
] {
let got = invoke(args.iter().copied());
assert_ne!(got.code, 0, "{args:?}");
}
let script = dir.join("s.json");
std::fs::write(&script, r#"[{"cmd": "edit.select_all"}]"#).unwrap();
let s = script.to_str().unwrap();
// `run` and `exec` save onto the opened document only with --in-place.
let got = invoke(["run", d, s, "--save", d]);
assert_eq!(got.code, 2, "{}", got.err);
assert!(got.err.contains("--in-place") && got.err.contains("replace"), "{}", got.err);
let got = invoke(["exec", d, "edit.select_all", "--save", d]);
assert_eq!(got.code, 2, "{}", got.err);
// --in-place with nothing to replace has nothing to allow.
let elsewhere = dir.join("b.anicraft");
let got = invoke(["run", d, s, "--save", elsewhere.to_str().unwrap(), "--in-place"]);
assert_eq!(got.code, 2, "{}", got.err);
assert!(!elsewhere.exists());
assert_eq!(std::fs::read(&doc).unwrap(), before, "nothing replaced the document");
// With --in-place it is saved.
let got = invoke(["run", d, s, "--save", d, "--in-place"]);
assert_eq!(got.code, 0, "{}", got.err);
let got = invoke(["exec", d, "edit.select_all", "--save", d, "--in-place"]);
assert_eq!(got.code, 0, "{}", got.err);
// A different file is the ordinary case.
let got = invoke(["run", d, s, "--save", elsewhere.to_str().unwrap()]);
assert_eq!(got.code, 0, "{}", got.err);
assert!(elsewhere.exists());
}
/// A path that is not valid Unicode reaches the command: a document is read from it, and the
/// engine's JSON-valued commands say so by name.
#[cfg(unix)]
#[test]
fn a_path_that_is_not_unicode_is_a_path_not_a_panic() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let dir = workdir("nonunicode");
let bad = dir.join(OsString::from_vec(b"caf\xe9.anicraft".to_vec()));
let made = invoke([OsString::from("new"), "--out".into(), dir.join("ok.anicraft").into()]);
assert_eq!(made.code, 0, "{}", made.err);
std::fs::copy(dir.join("ok.anicraft"), &bad).unwrap();
// Reading a document by that name works: it is a PathBuf all the way to the loader.
let got = invoke([OsString::from("info"), bad.clone().into()]);
assert_eq!(got.code, 0, "{}", got.err);
// Writing goes through a JSON command, which holds only text: refused by name, exit 1.
let got = invoke([OsString::from("render"), "--sample".into(), "--out".into(), bad.into()]);
assert_eq!((got.code, got.out.as_str()), (1, ""), "{}", got.err);
assert!(got.err.contains("is not valid Unicode"), "{}", got.err);
}
/// `--screenshot` is the desktop app's: this binary hands the whole command line to the `anicraft`
/// next to it, and ends with the code it ended with, 128 + the signal when a signal ended it.
#[cfg(unix)]
mod desktop {
use std::os::unix::fs::PermissionsExt;
use std::process::Command;
use crate::workdir;
/// Runs the command, again when the system says the file is busy: another test's child process
/// may still hold the copy this one just wrote open between its fork and its exec.
fn output(command: &mut Command) -> std::process::Output {
for _ in 0..50 {
match command.output() {
Err(e) if e.raw_os_error() == Some(26) => std::thread::sleep(std::time::Duration::from_millis(100)),
other => return other.unwrap(),
}
}
command.output().unwrap()
}
/// A copy of the binary in a folder of its own, with `anicraft` beside it when `app` is given.
fn installed(name: &str, app: Option<&str>) -> (std::path::PathBuf, std::path::PathBuf) {
let dir = workdir(name);
let cli = dir.join("anicraft-cli");
std::fs::copy(env!("CARGO_BIN_EXE_anicraft-cli"), &cli).unwrap();
if let Some(script) = app {
let app = dir.join("anicraft");
std::fs::write(&app, format!("#!/bin/sh\n{script}\n")).unwrap();
std::fs::set_permissions(&app, std::fs::Permissions::from_mode(0o755)).unwrap();
}
(dir, cli)
}
#[test]
fn without_the_desktop_app_it_says_so_with_exit_1() {
let (_dir, cli) = installed("no-desktop", None);
let got = output(Command::new(cli).args(["--screenshot", "x.png"]));
assert_eq!(got.status.code(), Some(1));
assert!(String::from_utf8_lossy(&got.stderr).contains("needs the AniCraft desktop app"), "{}", String::from_utf8_lossy(&got.stderr));
}
#[test]
fn the_desktop_apps_exit_code_is_passed_on() {
let (dir, cli) = installed("desktop-code", Some("echo \"$@\" > args.txt; exit 3"));
let got = output(Command::new(cli).current_dir(&dir).args(["--screenshot", "x.png", "--look", "dark"]));
assert_eq!(got.status.code(), Some(3));
assert_eq!(std::fs::read_to_string(dir.join("args.txt")).unwrap().trim(), "--screenshot x.png --look dark");
}
#[test]
fn a_signal_that_ended_the_desktop_app_is_128_plus_the_signal() {
let (_dir, cli) = installed("desktop-signal", Some("kill -TERM $$"));
let got = output(Command::new(cli).args(["--screenshot", "x.png"]));
assert_eq!(got.status.code(), Some(128 + 15));
}
}
+304
View File
@@ -0,0 +1,304 @@
//! What each subcommand does, through `run`: the behaviour the command line had before RFC-0018,
//! kept.
use serde_json::{Value, json};
use crate::{invoke, workdir};
fn ok(args: &[&str]) -> String {
let got = invoke(args.iter().copied());
assert_eq!((got.code, got.err.as_str()), (0, ""), "{args:?}");
got.out.trim_end().to_owned()
}
fn failed(args: &[&str]) -> String {
let got = invoke(args.iter().copied());
assert_eq!((got.code, got.out.as_str()), (1, ""), "{args:?}: {}", got.err);
assert!(got.err.starts_with("error: "), "{}", got.err);
got.err
}
#[test]
fn commands_lists_every_command_as_json() {
let list: Value = serde_json::from_str(&ok(&["commands"])).unwrap();
assert!(list.as_array().unwrap().iter().any(|c| c["id"] == "timeline.insert_keyframe"));
}
#[test]
fn info_reads_the_sample_and_a_file_and_an_animate_document() {
let info: Value = serde_json::from_str(&ok(&["info", "--sample"])).unwrap();
assert!(info["layers"].is_array() || info.get("layers").is_some() || info.is_object(), "{info}");
// #226: an Animate document is imported as File › Open does, untitled.
let xfl = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../xfl/tests/corpus/shapes/shapes.xfl");
assert!(ok(&["info", xfl.to_str().unwrap()]).contains("\"layers\""));
let dir = workdir("info");
let missing = dir.join("missing.anicraft");
let err = failed(&["info", missing.to_str().unwrap()]);
assert!(err.contains("missing.anicraft"), "{err}");
}
/// Frame flags on the command line count from 1, the engine's frames from 0.
#[test]
fn frame_flags_count_from_one_and_json_frames_from_zero() {
let dir = workdir("frames");
let (cli, exec) = (dir.join("cli.png"), dir.join("exec.png"));
let by_cli: Value = serde_json::from_str(&ok(&["render", "--sample", "--frame", "1", "--out", cli.to_str().unwrap()])).unwrap();
let params = json!({"path": exec.to_str().unwrap(), "frame": 0}).to_string();
let by_exec: Value = serde_json::from_str(&ok(&["exec", "--sample", "file.export_png", &params])).unwrap();
assert_eq!((&by_cli["frame"], &by_exec["frame"]), (&json!(0), &json!(0)));
assert_eq!(std::fs::read(&cli).unwrap(), std::fs::read(&exec).unwrap());
}
#[test]
fn render_and_render_seq_write_pngs() {
let dir = workdir("png");
let png = dir.join("f.png");
ok(&["render", "--sample", "--frame", "12", "--scale", "0.25", "--out", png.to_str().unwrap()]);
assert_eq!(&std::fs::read(&png).unwrap()[1..4], b"PNG");
let seq = dir.join("seq");
let done: Value =
serde_json::from_str(&ok(&["render-seq", "--sample", "--from", "2", "--to", "3", "--scale", "0.1", "--out-dir", seq.to_str().unwrap()]))
.unwrap();
assert_eq!(done["frames"], 2, "{done}");
assert!(seq.join("frame_00002.png").exists() && !seq.join("frame_00001.png").exists());
}
#[test]
fn animations_are_written_and_replacing_one_needs_overwrite() {
let dir = workdir("anim");
for (cmd, file, magic) in [("gif", "a.gif", &b"GIF8"[..]), ("apng", "a.png", &b"\x89PNG"[..]), ("webp", "a.webp", &b"RIFF"[..])] {
let path = dir.join(file);
let p = path.to_str().unwrap();
ok(&[cmd, "--sample", "--from", "1", "--to", "2", "--scale", "0.1", "--out", p]);
assert!(std::fs::read(&path).unwrap().starts_with(magic), "{cmd}");
// Replacing it needs --overwrite, bare or as `--overwrite yes`; `no` is the default.
failed(&[cmd, "--sample", "--from", "1", "--to", "2", "--scale", "0.1", "--out", p]);
failed(&[cmd, "--sample", "--from", "1", "--to", "2", "--scale", "0.1", "--out", p, "--overwrite", "no"]);
ok(&[cmd, "--sample", "--from", "1", "--to", "2", "--scale", "0.1", "--out", p, "--overwrite"]);
ok(&[cmd, "--sample", "--from", "1", "--to", "2", "--scale", "0.1", "--out", p, "--overwrite", "yes"]);
}
let p = dir.join("loop.png");
ok(&["apng", "--sample", "--from", "1", "--to", "2", "--scale", "0.1", "--loop", "3", "--background", "--out", p.to_str().unwrap()]);
ok(&[
"apng",
"--sample",
"--from",
"1",
"--to",
"2",
"--scale",
"0.1",
"--loop",
"forever",
"--background",
"yes",
"--overwrite",
"--out",
p.to_str().unwrap(),
]);
}
#[test]
fn new_makes_a_document_that_info_reads() {
let dir = workdir("new");
let path = dir.join("n.anicraft");
ok(&["new", "--out", path.to_str().unwrap(), "--width", "320", "--height", "200", "--fps", "12.5"]);
let info: Value = serde_json::from_str(&ok(&["info", path.to_str().unwrap()])).unwrap();
assert!(info.to_string().contains("320") && info.to_string().contains("200"), "{info}");
}
#[test]
fn export_any_format_built_in_or_plugin() {
let dir = workdir("export");
std::fs::create_dir_all(dir.join("plugins")).unwrap();
// A built-in format by id.
let svg = dir.join("f.svg");
ok(&["export", "--sample", "--format", "svg", "--frame", "3", "--out", svg.to_str().unwrap()]);
assert!(std::fs::read_to_string(&svg).unwrap().contains("<svg"));
// A sequence goes to a folder, one file per frame (#504).
let seq = dir.join("vectors");
ok(&["export", "--sample", "--format", "svg-sequence", "--from", "2", "--to", "3", "--out", seq.to_str().unwrap()]);
assert!(seq.join("frame_00002.svg").exists() && seq.join("frame_00003.svg").exists() && !seq.join("frame_00001.svg").exists());
// A format's flags are the ones it uses: a frame for a range format and a range for a frame format are refused.
for args in [vec!["--format", "svg", "--from", "1"], vec!["--format", "svg-sequence", "--frame", "1"], vec!["--format", "png", "--to", "2"]] {
let mut full = vec!["export", "--sample", "--out", "unused"];
full.extend(args);
let got = invoke(full.iter().copied());
assert_eq!(got.code, 2, "{full:?}: {}", got.err);
assert!(got.err.contains("is not used by the"), "{}", got.err);
}
// An unknown format names the known ones; options must be an object for a built-in.
let err = failed(&["export", "--sample", "--format", "nope", "--out", "x"]);
assert!(err.contains("lottie") && err.contains("--plugins"), "{err}");
let got = invoke(["export", "--sample", "--format", "svg", "--out", svg.to_str().unwrap(), "--options", "[1]"]);
assert_eq!((got.code, got.err.as_str()), (2, "error: --options must be a JSON object\n"));
}
#[test]
fn plugins_add_formats() {
let dir = workdir("plugin");
std::fs::create_dir_all(dir.join("plugins")).unwrap();
// An exporter plug-in that writes the request it was handed.
let m = r#"{"id":"org.test.count","name":"Count","kind":"exporter","format":{"name":"Count","extension":"txt"}}"#;
let req = r#"{"op":"movie"}"#;
let wat = format!(
r#"(module (import "anicraft" "call" (func $call (param i32 i32) (result i32))) (import "anicraft" "response" (func $response (param i32 i32) (result i32)))
(memory (export "memory") 4) (data (i32.const 1024) "{}") (data (i32.const 4096) "{}")
(func (export "ac_abi_version") (result i32) i32.const 1)
(func (export "ac_manifest") (result i64) (i64.or (i64.shl (i64.const {}) (i64.const 32)) (i64.const 1024)))
(func (export "ac_alloc") (param i32) (result i32) i32.const 60000)
(func (export "ac_export") (param i32 i32) (result i64) (local $n i32)
(local.set $n (call $response (i32.const 100000) (call $call (i32.const 4096) (i32.const {}))))
(i64.or (i64.shl (i64.extend_i32_u (local.get $n)) (i64.const 32)) (i64.const 100000))))"#,
m.replace('"', "\\22"),
req.replace('"', "\\22"),
m.len(),
req.len()
);
std::fs::write(dir.join("plugins").join("count.wasm"), wat::parse_str(&wat).unwrap()).unwrap();
let plugins = dir.join("plugins");
let plugins = plugins.to_str().unwrap();
let listed = ok(&["formats", "--plugins", plugins]);
assert!(listed.contains("org.test.count") && listed.contains("\"gif\""));
assert!(!ok(&["formats"]).contains("org.test.count"), "plug-ins load only on request");
let out = dir.join("movie.txt");
let o = out.to_str().unwrap();
let v = ok(&["export", "--sample", "--format", "org.test.count", "--from", "2", "--to", "5", "--out", o, "--plugins", plugins]);
assert!(v.contains("\"frames\":4"), "{v}");
let movie: Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap();
assert_eq!((movie["result"]["from"].as_u64(), movie["result"]["frames"].as_u64()), (Some(1), Some(4)));
// Replacing it needs --overwrite.
failed(&["export", "--sample", "--format", "org.test.count", "--out", o, "--plugins", plugins]);
ok(&["export", "--sample", "--format", "org.test.count", "--out", o, "--plugins", plugins, "--overwrite", "yes"]);
// A folder with nothing loadable is still the plug-ins folder.
ok(&["info", "--sample", "--plugins", dir.join("not-yet").to_str().unwrap()]);
}
#[test]
fn run_takes_a_script_or_a_saved_command() {
let dir = workdir("run");
let script = dir.join("s.json");
std::fs::write(&script, "\u{feff}[{\"cmd\": \"edit.select_all\"}, {\"cmd\": \"modify.rotate_cw\"}]").unwrap();
let results: Value = serde_json::from_str(&ok(&["run", "--sample", script.to_str().unwrap()])).unwrap();
assert_eq!(results.as_array().map(Vec::len), Some(2), "{results}");
// A step names itself.
std::fs::write(&script, r#"[{"cmd": "edit.select_all"}, {"params": {}}]"#).unwrap();
assert!(failed(&["run", "--sample", script.to_str().unwrap()]).contains("step 2: missing \"cmd\""));
std::fs::write(&script, r#"[{"cmd": "edit.select_all"}, {"cmd": "no.such"}]"#).unwrap();
assert!(failed(&["run", "--sample", script.to_str().unwrap()]).starts_with("error: step 2: no.such: "));
std::fs::write(&script, "not json").unwrap();
assert!(failed(&["run", "--sample", script.to_str().unwrap()]).contains("expected a JSON array of {cmd, params} or a saved command"));
std::fs::write(&script, "[1]").unwrap();
assert!(failed(&["run", "--sample", script.to_str().unwrap()]).contains("step 1: missing \"cmd\""));
std::fs::write(&script, "5").unwrap();
assert!(failed(&["run", "--sample", script.to_str().unwrap()]).contains("expected a JSON array of {cmd, params}:"));
assert!(failed(&["run", "--sample", dir.join("none.json").to_str().unwrap()]).contains("none.json"));
// A saved command (ADR 0097) runs as one transactional step.
let file = dir.join("Spin.json");
std::fs::write(&file, r#"{"format": "anicraft-command", "version": 1, "steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}]}"#)
.unwrap();
let v: Value = serde_json::from_str(&ok(&["run", "--sample", file.to_str().unwrap()])).unwrap();
assert_eq!((v["name"].as_str(), v["steps"].as_u64()), (Some("Spin"), Some(2)), "{v}");
// A failing step names itself and leaves nothing behind.
std::fs::write(
&file,
r#"{"steps": [{"cmd": "edit.select_all"}, {"cmd": "modify.rotate_cw"}, {"cmd": "layer.set_height", "params": {"height": 7}}]}"#,
)
.unwrap();
assert!(failed(&["run", "--sample", file.to_str().unwrap()]).contains("stopped at step 3 of 3"));
// --save writes the document, for a saved command too.
std::fs::write(&file, r#"{"steps": [{"cmd": "edit.select_all"}]}"#).unwrap();
let saved = dir.join("saved.anicraft");
ok(&["run", "--sample", file.to_str().unwrap(), "--save", saved.to_str().unwrap()]);
assert!(saved.exists());
}
#[test]
fn exec_runs_one_command_and_saves() {
let dir = workdir("exec");
let saved = dir.join("e.anicraft");
let v: Value =
serde_json::from_str(&ok(&["exec", "--sample", "draw.rect", r#"{"x":1,"y":1,"w":5,"h":5}"#, "--save", saved.to_str().unwrap()])).unwrap();
assert!(v.is_object(), "{v}");
assert!(saved.exists());
// The command id is the first argument after the document, and one that doesn't exist is a failure.
assert!(failed(&["exec", saved.to_str().unwrap(), "no.such"]).starts_with("error: no.such: "));
}
#[test]
fn guide_writes_the_book_and_searches_it() {
let dir = workdir("guide");
let site = dir.join("site");
let wrote = ok(&["guide", "--out", site.to_str().unwrap()]);
assert!(wrote.starts_with("wrote ") && site.join("index.html").exists(), "{wrote}");
let out = ok(&["guide", "search", "onion", "skin"]);
assert_eq!(out.lines().next(), Some("1. Onion skin · The timeline"), "{out}");
assert!(out.contains("timeline.html#onion-skin"), "{out}");
let json: Value = serde_json::from_str(&ok(&["guide", "search", "export", "gif", "--json", "yes", "--limit", "3"])).unwrap();
let list = json.as_array().unwrap();
assert!(list.len() <= 3 && list[0]["url"] == "getting-started.html#export-a-gif-or-a-video", "{json}");
let bare: Value = serde_json::from_str(&ok(&["guide", "search", "export", "gif", "--json"])).unwrap();
assert!(bare.is_array());
assert!(ok(&["guide", "search", "zzzzqqq"]).starts_with("nothing in the user guide matches"));
// Words with nothing to search for are a usage error, found by the run.
let got = invoke(["guide", "search", "?!"]);
assert_eq!((got.code, got.out.as_str()), (2, ""), "{}", got.err);
}
/// `fla-dump` reads a file only up to the legacy container's cap, and refuses one over it before
/// parsing; a file that isn't a compound binary is refused by its first bytes.
#[test]
fn fla_dump_refuses_files_over_the_cap_and_other_formats() {
let dir = workdir("fla");
let zip = dir.join("new.fla");
std::fs::write(&zip, b"PK\x03\x04").unwrap();
assert!(failed(&["fla-dump", zip.to_str().unwrap()]).contains("not a legacy Flash document"));
assert!(failed(&["fla-dump", dir.join("none.fla").to_str().unwrap()]).contains("none.fla"));
// One byte over the cap, sparse where the file system allows: refused, not parsed.
#[cfg(unix)]
{
let big = dir.join("big.fla");
let f = std::fs::File::create(&big).unwrap();
std::io::Write::write_all(&mut &f, &anicraft_fla::MAGIC).unwrap();
f.set_len(anicraft_fla::cfb::MAX_FILE + 1).unwrap();
assert!(failed(&["fla-dump", big.to_str().unwrap()]).contains("larger than AniCraft reads"));
}
}
/// `bench --stroke` walks the reporter's steps of #519 and `--stroke-file` the same on a document.
#[test]
fn stroke_bench_paints_moves_and_merges_a_long_stroke() {
let out: Value = serde_json::from_str(&ok(&["bench", "--stroke", "400"])).unwrap();
assert_eq!(out["samples"], 400);
assert_eq!(out["merged"], true);
let segments = out["segments"].as_u64().unwrap();
assert!(segments > 50, "a scribble has an outline of many curves: {segments}");
assert_eq!(out["segments_after"].as_u64(), Some(segments), "undo takes the move and its merge back");
for step in ["draw_brush_ms", "hit_test_us", "move_ms", "float_ms", "deselect_merge_ms", "undo_ms", "render_ms"] {
assert!(out[step].as_f64().is_some_and(|v| v >= 0.0), "{step} was timed: {out}");
}
// The same steps on a saved document's artwork.
let dir = workdir("stroke");
let file = dir.join("stroke.anicraft");
ok(&["new", "--out", file.to_str().unwrap()]);
ok(&["exec", file.to_str().unwrap(), "draw.rect", r#"{"x":1,"y":1,"w":50,"h":50}"#, "--save", file.to_str().unwrap(), "--in-place"]);
let out: Value = serde_json::from_str(&ok(&["bench", "--stroke-file", file.to_str().unwrap()])).unwrap();
assert!(out["samples"].is_null() && out["deselect_merge_ms"].is_number(), "{out}");
}
/// The timing budgets need a release build; a debug build says so and exits 2.
#[cfg(debug_assertions)]
#[test]
fn bench_check_needs_a_release_build() {
let got = invoke(["bench", "--check", "yes"]);
assert_eq!((got.code, got.out.as_str()), (2, ""));
assert!(got.err.contains("release"), "{}", got.err);
}
/// A small stress document, measured: the report is JSON alone on stdout.
#[test]
fn bench_reports_json_on_stdout() {
let report: Value = serde_json::from_str(&ok(&["bench", "--layers", "2", "--shapes", "3", "--frames", "4"])).unwrap();
assert_eq!(report["document"]["layers"], 2);
assert!(report["render_1080p_ms_per_frame"].is_number());
}
+36
View File
@@ -0,0 +1,36 @@
//! Integration tests, built as one test binary: each file is a module. They call `run` in-process,
//! except where a test needs the real binary (a protocol on stdio).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod cli;
mod commands;
mod man_and_completions;
mod protocol;
use std::ffi::OsString;
use std::path::PathBuf;
/// What `run` returned and wrote.
pub struct Outcome {
pub code: i32,
pub out: String,
pub err: String,
}
pub fn invoke<I, T>(args: I) -> Outcome
where
I: IntoIterator<Item = T>,
T: Into<OsString>,
{
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = anicraft_cli::run(args, &mut out, &mut err);
Outcome { code, out: String::from_utf8_lossy(&out).into_owned(), err: String::from_utf8_lossy(&err).into_owned() }
}
/// A new, empty folder for one test.
pub fn workdir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("anicraft-cli-it-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
@@ -0,0 +1,50 @@
//! The clap definition is consistent, and every shell's completions and every man page
//! (`examples/man-and-completions.rs`) can be generated from it.
use clap::ValueEnum;
use clap_complete::Shell;
// The example itself, so the test writes the files exactly as the packages get them.
#[allow(dead_code)]
#[path = "../../examples/man-and-completions.rs"]
mod example;
#[test]
fn command_is_consistent() {
anicraft_cli::command().debug_assert();
}
#[test]
fn completions_generate_for_every_shell() {
for &shell in Shell::value_variants() {
let mut out = Vec::new();
clap_complete::generate(shell, &mut anicraft_cli::command(), "anicraft-cli", &mut out);
assert!(!out.is_empty(), "{shell}");
}
}
/// The example writes the five completion files under the names `packaging/linux/package.sh`
/// installs, `anicraft-cli.1` and a page per subcommand, and no pages for the `help` subcommand.
#[test]
fn the_example_writes_the_files_the_packages_install() {
let dir = std::env::temp_dir().join(format!("anicraft-cli-{}-man-and-completions", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
example::generate(&dir).unwrap();
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
written.sort();
let completions = ["anicraft-cli.bash", "_anicraft-cli", "anicraft-cli.fish", "anicraft-cli.elv", "_anicraft-cli.ps1"];
let mut expected: Vec<String> = completions.map(String::from).into();
expected.push("anicraft-cli.1".into());
let cmd = anicraft_cli::command();
expected.extend(cmd.get_subcommands().filter(|s| s.get_name() != "help").flat_map(|s| {
// `guide search` is a page of its own.
let mut pages = vec![format!("anicraft-cli-{}.1", s.get_name())];
pages.extend(s.get_subcommands().filter(|n| n.get_name() != "help").map(|n| format!("anicraft-cli-{}-{}.1", s.get_name(), n.get_name())));
pages
}));
expected.sort();
assert_eq!(written, expected);
assert!(written.iter().any(|w| w == "anicraft-cli-render-seq.1") && written.iter().any(|w| w == "anicraft-cli-guide-search.1"), "{written:?}");
std::fs::remove_dir_all(&dir).unwrap();
}
+148
View File
@@ -0,0 +1,148 @@
//! `serve` and `mcp` speak a protocol on stdio: nothing else is written to stdout, and `mcp`
//! refuses to start without its roots (AGENTS.md rule 18).
use std::io::Write;
use std::process::{Command, Stdio};
use serde_json::Value;
use crate::{invoke, workdir};
fn binary() -> Command {
Command::new(env!("CARGO_BIN_EXE_anicraft-cli"))
}
/// Feeds `input` to the binary and returns its exit code, stdout and stderr.
fn talk(args: &[&str], input: &str) -> (i32, String, String) {
let mut child = binary().args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap();
let got = child.wait_with_output().unwrap();
(got.status.code().unwrap(), String::from_utf8(got.stdout).unwrap(), String::from_utf8(got.stderr).unwrap())
}
#[test]
fn serve_writes_only_json_lines_to_stdout() {
let (code, out, err) = talk(&["serve", "--sample"], "{\"id\":1,\"cmd\":\"edit.select_all\"}\n{\"cmd\":\"quit\"}\n");
assert_eq!((code, err.as_str()), (0, ""));
let lines: Vec<Value> = out.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines[0]["ready"], true);
assert_eq!(lines[1]["ok"], true);
assert_eq!(lines.last().unwrap()["bye"], true);
}
#[test]
fn serve_ends_quietly_when_stdin_closes() {
let (code, out, err) = talk(&["serve"], "");
assert_eq!((code, err.as_str()), (0, ""));
assert_eq!(out.lines().count(), 1, "only the ready line: {out}");
}
#[test]
fn mcp_answers_on_stdout_inside_its_roots() {
let dir = workdir("mcp");
let root = dir.to_str().unwrap();
let init = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"t\",\"version\":\"1\"}}}\n";
let (code, out, err) = talk(&["mcp", "--sample", "--automation-read-root", root, &format!("--automation-write-root={root}")], init);
assert_eq!((code, err.as_str()), (0, ""));
let reply: Value = serde_json::from_str(out.lines().next().unwrap()).unwrap();
assert_eq!(reply["id"], 1, "{out}");
assert!(out.lines().all(|l| serde_json::from_str::<Value>(l).is_ok()), "stdout holds JSON-RPC only: {out}");
}
/// AGENTS.md rule 18: `mcp` refuses to start without both roots, bridge or not, with the usage
/// exit code, before it opens anything; a root that is not a folder stops the start too.
#[test]
fn mcp_refuses_to_start_without_both_automation_roots() {
let dir = workdir("mcp-roots");
let (work, file) = (dir.to_str().unwrap().to_owned(), dir.join("f.json"));
std::fs::write(&file, "{}").unwrap();
let file = file.to_str().unwrap();
for argv in [
vec!["mcp"],
vec!["mcp", "--sample"],
vec!["mcp", "no-such-file.anicraft"],
vec!["mcp", "--bridge", "9878"],
vec!["mcp", "--automation-read-root", &work],
vec!["mcp", "--automation-write-root", &work],
vec!["mcp", "--bridge", "9878", "--automation-write-root", &work],
vec!["mcp", "--automation-read-root", &work, "--automation-write-root", &work, "--automation-write-root", &work],
vec!["mcp", "--automation-read-root", "", "--automation-write-root", &work],
vec!["mcp", "--automation-read-root", &work, "--automation-write-root"],
vec!["mcp", "--automation-read-root=", &format!("--automation-write-root={work}")],
vec!["serve", "--automation-read-root", &work],
vec!["serve", "--automation-write-root", &work],
] {
let got = invoke(argv.iter().copied());
assert_eq!((got.code, got.out.as_str()), (2, ""), "{argv:?}: {}", got.err);
assert!(got.err.contains("--automation-"), "{argv:?}: {}", got.err);
}
let missing = dir.join("nowhere");
let got = invoke(["mcp", "--automation-read-root", missing.to_str().unwrap(), "--automation-write-root", &work]);
assert!(got.code == 2 && got.err.starts_with("error: ") && got.err.contains("nowhere"), "{}", got.err);
let got = invoke(["serve", "--automation-read-root", &work, "--automation-write-root", file]);
assert_eq!(got.code, 2, "{}", got.err);
// The help says so.
let help = invoke(["mcp", "--help"]).out;
assert!(help.contains("--automation-read-root") && help.contains("--automation-write-root") && help.contains("required"), "{help}");
}
/// `--bridge` takes a port; a bad one is a usage error before anything connects.
#[test]
fn a_bad_bridge_port_is_a_usage_error() {
let dir = workdir("bridge");
let root = dir.to_str().unwrap();
for target in ["nope", "0", "70000", ""] {
let got = invoke(["mcp", "--bridge", target, "--automation-read-root", root, "--automation-write-root", root]);
assert_eq!((got.code, got.out.as_str()), (2, ""), "{target:?}: {}", got.err);
}
// A bridge acts on a window: no file, no plug-ins.
let got = invoke(["mcp", "--bridge", "9878", "--sample", "--automation-read-root", root, "--automation-write-root", root]);
assert_eq!(got.code, 2, "{}", got.err);
let got = invoke(["mcp", "--bridge", "9878", "--plugins", root, "--automation-read-root", root, "--automation-write-root", root]);
assert_eq!(got.code, 2, "{}", got.err);
}
/// The Nightly window's launch arguments belong to the desktop app.
#[test]
fn the_nightly_launch_protocol_is_refused() {
for argv in [vec!["--launch-profile", "nightly-v1", "info", "--sample"], vec!["info", "--sample", "--profile-root=/x"]] {
let got = invoke(argv.iter().copied());
assert_eq!((got.code, got.out.as_str()), (2, ""), "{argv:?}");
assert!(got.err.contains("belong to the AniCraft Nightly window"), "{}", got.err);
}
}
/// `serve` with roots keeps the commands inside them, and says so in the reply.
#[test]
fn serve_with_roots_refuses_a_write_outside_them() {
let dir = workdir("serve-roots");
let (work, out) = (dir.join("work"), dir.join("out"));
std::fs::create_dir_all(&work).unwrap();
std::fs::create_dir_all(&out).unwrap();
let request = |path: &std::path::Path| {
format!("{{\"id\":1,\"cmd\":\"file.save_as\",\"params\":{{\"path\":{}}}}}\n", serde_json::json!(path.to_str().unwrap()))
};
let input = format!("{}{}{{\"cmd\":\"quit\"}}\n", request(&work.join("no.anicraft")), request(&out.join("yes.anicraft")));
let (code, stdout, err) =
talk(&["serve", "--sample", "--automation-read-root", work.to_str().unwrap(), "--automation-write-root", out.to_str().unwrap()], &input);
assert_eq!((code, err.as_str()), (0, ""));
let lines: Vec<Value> = stdout.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines[1]["ok"], false, "{stdout}");
assert!(lines[1]["error"].as_str().unwrap().contains("automation write root"), "{stdout}");
assert_eq!(lines[2]["ok"], true, "{stdout}");
assert!(out.join("yes.anicraft").exists() && !work.join("no.anicraft").exists());
}
/// `mcp --bridge` starts without the app and answers on stdout; a call says how to start it.
#[test]
fn the_bridge_answers_without_the_app() {
let dir = workdir("bridge-down");
let root = dir.to_str().unwrap();
// A port nothing listens on: bound, then released.
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port().to_string();
let init = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"t\",\"version\":\"1\"}}}\n";
let (code, out, err) = talk(&["mcp", "--bridge", &port, "--automation-read-root", root, "--automation-write-root", root], init);
assert_eq!((code, err.as_str()), (0, ""), "{out}");
let reply: Value = serde_json::from_str(out.lines().next().unwrap()).unwrap();
assert_eq!(reply["id"], 1, "{out}");
}