diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index feb8675d..75332dd7 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -25,3 +25,21 @@ jobs: # Runs the Nightly synthetic suites, the launcher tests and `bash -n` here, so the checks # that need no compiler are part of CI rather than a local step. extra-checks-script: packaging/nightly-checks.sh + + freebsd-layout: + # The FreeBSD package layout, with stub binaries standing in for the build: RFC-0018 rule 1.9 + # puts texturecraft-cli's man pages and its bash, zsh and fish completions in it. + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: FreeBSD package layout (dry run) + run: | + CARGO_TARGET_DIR="$RUNNER_TEMP/texturecraft-target" bash packaging/freebsd/package.sh --dry-run + listing="$(tar -tzf "$RUNNER_TEMP"/texturecraft-target/freebsd-package/texturecraft-*-freebsd-x86_64.tar.gz)" + for f in man/man1/texturecraft-cli.1 share/bash-completion/completions/texturecraft-cli \ + share/zsh/site-functions/_texturecraft-cli share/fish/vendor_completions.d/texturecraft-cli.fish; do + grep -q "/$f$" <<<"$listing" || { echo "::error::$f is missing from the FreeBSD package"; exit 1; } + done diff --git a/Cargo.lock b/Cargo.lock index 206a0ea6..2ccaed92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -212,12 +212,56 @@ dependencies = [ "unicode-width", ] +[[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.6.1" @@ -672,7 +716,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.6", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -776,6 +820,65 @@ dependencies = [ "libloading", ] +[[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.1" @@ -820,6 +923,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.8" @@ -1740,7 +1849,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -2141,7 +2250,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2339,7 +2448,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3237,6 +3346,12 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[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.13.0" @@ -3674,7 +3789,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png", "thiserror 2.0.21", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4343,6 +4458,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 = "openssl-probe" version = "0.2.2" @@ -4391,7 +4512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5138,6 +5259,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "roff" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" + [[package]] name = "ron" version = "0.12.2" @@ -5192,7 +5319,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5205,7 +5332,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5272,7 +5399,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5650,7 +5777,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -5800,10 +5927,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5879,10 +6006,14 @@ dependencies = [ name = "texturecraft-cli" version = "0.6.1" dependencies = [ + "clap", + "clap_complete", + "clap_mangen", "image", "serde_json", "texturecraft-automation", "texturecraft-engine", + "thiserror 2.0.21", "tokio", "winresource", ] @@ -6385,7 +6516,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -6520,6 +6651,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" @@ -7075,7 +7212,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -7462,7 +7599,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" dependencies = [ "bitflags 2.13.2", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 3259c129..1f07aa7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,10 @@ texturecraft-ui-egui = { path = "crates/ui-egui" } # external thiserror = "2" +# The command line of texturecraft-cli (RFC-0018); the generators are dev-dependencies, for the man pages and completions. +clap = { version = "4", features = ["derive", "string", "env"] } +clap_complete = "4" +clap_mangen = "0.2" chrono = { version = "0.4", default-features = false, features = ["now", "wasmbind"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/apps/texturecraft-cli/Cargo.toml b/apps/texturecraft-cli/Cargo.toml index d458a8d0..61f4c61a 100644 --- a/apps/texturecraft-cli/Cargo.toml +++ b/apps/texturecraft-cli/Cargo.toml @@ -6,6 +6,14 @@ edition.workspace = true license.workspace = true build = "build.rs" +[lib] +name = "texturecraft_cli" +path = "src/lib.rs" + +[[bin]] +name = "texturecraft-cli" +path = "src/main.rs" + [lints] workspace = true @@ -14,9 +22,13 @@ texturecraft-automation = { workspace = true } texturecraft-engine = { workspace = true } serde_json = { workspace = true } tokio = { workspace = true } +thiserror = { workspace = true } +clap = { workspace = true } [dev-dependencies] image = { workspace = true } +clap_complete = { workspace = true } +clap_mangen = { workspace = true } [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft-cli/examples/man-and-completions.rs b/apps/texturecraft-cli/examples/man-and-completions.rs new file mode 100644 index 00000000..55885101 --- /dev/null +++ b/apps/texturecraft-cli/examples/man-and-completions.rs @@ -0,0 +1,42 @@ +//! Writes texturecraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish, +//! PowerShell) and man pages ([`clap_mangen`]: `texturecraft-cli.1` and one per subcommand, such as +//! `texturecraft-cli-info.1`) into a directory. The Linux and FreeBSD packages ship them +//! (`packaging/linux/package.sh`, `packaging/freebsd/package.sh`): +//! +//! ```sh +//! cargo run -p texturecraft-cli --example man-and-completions -- +//! ``` + +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 "); + 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 `tests/it/man_and_completions.rs`. +pub(crate) fn generate(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let mut cmd = texturecraft_cli::command(); + for &shell in Shell::value_variants() { + clap_complete::generate_to(shell, &mut cmd, "texturecraft-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 (`texturecraft-cli-help-convert.1`). + clap_mangen::generate_to(texturecraft_cli::command(), dir) +} diff --git a/apps/texturecraft-cli/src/args.rs b/apps/texturecraft-cli/src/args.rs new file mode 100644 index 00000000..64373804 --- /dev/null +++ b/apps/texturecraft-cli/src/args.rs @@ -0,0 +1,422 @@ +//! 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 [`UsageError`], printed and exited like clap's own. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use clap::error::ErrorKind; +use clap::{Args, 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."; + +const INPUTS: &str = "An is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .usd .usda .usdc .usdz .abc .obj .ply .stl) or builtin: (material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate, udim_plane). See docs/control-protocol.md."; + +/// Headless TextureCraft +#[derive(Parser, Debug)] +#[command(name = "texturecraft-cli", propagate_version = true, arg_required_else_help = true, after_help = EXIT_STATUS)] +pub(crate) struct Cli { + #[command(subcommand)] + pub(crate) command: Command, +} + +#[derive(Subcommand, Debug)] +pub(crate) enum Command { + /// Texture sets, layers, triangles, materials and the UV report, as JSON + #[command(after_help = INPUTS)] + Info(InfoArgs), + /// List the engine commands (id, label, params) + Commands(CommandsArgs), + /// Run one command and print its JSON result; -o saves the project + #[command(after_help = INPUTS)] + Run(RunArgs), + /// Run a script of commands + /// + /// The script is JSON: [{"id", "params"}, ...] or {"open": , "steps": [...], "save": }. + Batch(BatchArgs), + /// Bake mesh maps for every texture set + /// + /// A project is saved in place without -o, which needs --in-place; a mesh needs -o. + #[command(after_help = INPUTS)] + Bake(BakeArgs), + /// Export textures (default preset: Document channels + Normal + AO (No Alpha)) + #[command(after_help = INPUTS)] + Export(ExportArgs), + /// Render the viewport to PNG (needs a GPU or software adapter) + /// + /// --camera looks through a camera saved in the project (camera.add); --samples path traces it + /// instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on + /// the CPU. + #[command(after_help = INPUTS)] + Render(RenderArgs), + /// A new project from a mesh or a built-in mesh + /// + /// --sample bakes and applies a smart material to every texture set. The sample's mesh maps are + /// baked at the resolution up to 1024 px (most of the file's size), so a 2048 sample project is + /// as large as a 1024 one. + #[command(after_help = INPUTS)] + New(NewArgs), + /// MCP server on stdio: headless, or bridged to `texturecraft --control ` + /// + /// Headless, file access is only below the roots. + Mcp(McpArgs), + /// JSON lines ({"id","method","params"}) on stdio, or on 127.0.0.1: with a token + Serve(ServeArgs), +} + +#[derive(Args, Debug)] +pub(crate) struct InfoArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, +} + +#[derive(Args, Debug)] +pub(crate) struct CommandsArgs { + /// Only the commands whose id or label contains this text + #[arg(long, value_name = "TEXT")] + pub(crate) filter: Option, + /// Print the list as JSON instead of a table + #[arg(long)] + pub(crate) json: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct RunArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "COMMAND-ID")] + pub(crate) id: String, + /// The command's parameters, as JSON + #[arg(value_name = "PARAMS-JSON", value_parser = json_value)] + pub(crate) params: Option, + /// Save the project here + #[arg(short = 'o', long = "output", value_name = "OUT.TCRAFT")] + pub(crate) output: Option, + /// Allow -o to replace the project it opened + #[arg(long, requires = "output")] + pub(crate) in_place: bool, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("params are not JSON: {0}")] +pub(crate) struct NotJson(String); + +fn json_value(s: &str) -> Result { + serde_json::from_str(s).map_err(|e| NotJson(e.to_string())) +} + +#[derive(Args, Debug)] +pub(crate) struct BatchArgs { + #[arg(value_name = "SCRIPT.JSON")] + pub(crate) script: PathBuf, + /// Allow `save` to replace the project `open` named + #[arg(long)] + pub(crate) in_place: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct BakeArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + /// Save the baked project here + #[arg(short = 'o', long = "output", value_name = "OUT.TCRAFT")] + pub(crate) output: Option, + /// Bake at this size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) resolution: Option, + /// Only these maps (ids, comma separated) + #[arg(long, value_name = "ID,ID,...", value_delimiter = ',')] + pub(crate) maps: Vec, + /// Save over the project it opened (without -o), or allow -o to replace it + #[arg(long)] + pub(crate) in_place: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct ExportArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "DIR")] + pub(crate) dir: PathBuf, + /// An export preset by name + #[arg(long, value_name = "NAME")] + pub(crate) preset: Option, + /// File format (an extension) + #[arg(long, value_name = "EXT")] + pub(crate) format: Option, + /// Padding mode + #[arg(long, value_name = "MODE")] + pub(crate) padding: Option, + /// Texture size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) size: Option, +} + +#[derive(Args, Debug)] +pub(crate) struct RenderArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "OUT.PNG")] + pub(crate) output: PathBuf, + /// Image size + #[arg(long, value_name = "WxH")] + pub(crate) size: Option, + /// The viewport: 3D, or the UV view of the active texture set + #[arg(long, value_name = "VIEW", value_parser = ["3d", "2d", "uv"])] + pub(crate) view: Option, + /// Look through a camera saved in the project + #[arg(long, value_name = "NAME")] + pub(crate) camera: Option, + /// Camera yaw in degrees + #[arg(long, value_name = "DEG", allow_negative_numbers = true, value_parser = finite)] + pub(crate) yaw: Option, + /// Camera pitch in degrees + #[arg(long, value_name = "DEG", allow_negative_numbers = true, value_parser = finite)] + pub(crate) pitch: Option, + /// Path trace with this many samples per pixel + #[arg(long, value_name = "N", value_parser = positive)] + pub(crate) samples: Option, + /// Light bounces of the path tracer + #[arg(long, value_name = "N", requires = "samples")] + pub(crate) bounces: Option, + /// Path trace on the CPU + #[arg(long, requires = "samples")] + pub(crate) cpu: bool, +} + +#[derive(Args, Debug)] +pub(crate) struct NewArgs { + #[arg(value_name = "INPUT")] + pub(crate) input: PathBuf, + #[arg(value_name = "OUT.TCRAFT")] + pub(crate) output: PathBuf, + /// Texture size + #[arg(long, value_name = "PX", value_parser = positive)] + pub(crate) resolution: Option, + /// Bake and apply a smart material to every texture set + #[arg(long)] + pub(crate) sample: bool, +} + +/// The folders a server may read from and write to; with neither, it has no file access. +#[derive(Args, Debug, Default)] +pub(crate) struct RootArgs { + /// Serve file access below this folder (alias --automation-read-root) + #[arg(long, alias = "automation-read-root", value_name = "DIR")] + pub(crate) read_root: Option, + /// Allow writes below this folder (alias --automation-write-root) + #[arg(long, alias = "automation-write-root", value_name = "DIR")] + pub(crate) write_root: Option, +} + +#[derive(Args, Debug)] +pub(crate) struct McpArgs { + /// Bridge to a running app's control port instead of a headless session + #[arg(long, value_name = "PORT", value_parser = port)] + pub(crate) bridge: Option, + /// The app's control token (TEXTURECRAFT_CONTROL_TOKEN; else the file the app wrote) + #[arg(long, value_name = "TOKEN", env = "TEXTURECRAFT_CONTROL_TOKEN", hide_env_values = true)] + pub(crate) token: Option, + #[command(flatten)] + pub(crate) roots: RootArgs, +} + +#[derive(Args, Debug)] +pub(crate) struct ServeArgs { + /// Listen on 127.0.0.1: with a token, instead of stdio + #[arg(long, value_name = "PORT", value_parser = port)] + pub(crate) port: Option, + #[command(flatten)] + pub(crate) roots: RootArgs, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a number of pixels above zero")] +pub(crate) struct NotPositive(String); + +fn positive(s: &str) -> Result { + s.parse::().ok().filter(|n| *n > 0).ok_or_else(|| NotPositive(s.to_string())) +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a finite number")] +pub(crate) struct NotFinite(String); + +fn finite(s: &str) -> Result { + s.parse::().ok().filter(|n| n.is_finite()).ok_or_else(|| NotFinite(s.to_string())) +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not a loopback port (1-65535)")] +pub(crate) struct BadPort(String); + +/// A port, as `7878`, `127.0.0.1:7878` or `localhost:7878`. +fn port(s: &str) -> Result { + let digits = s.strip_prefix("127.0.0.1:").or_else(|| s.strip_prefix("localhost:")).unwrap_or(s); + digits.parse::().ok().filter(|p| *p != 0).ok_or_else(|| BadPort(s.to_string())) +} + +/// `--size` of `render`: WIDTHxHEIGHT. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Dimensions { + pub(crate) width: u32, + pub(crate) height: u32, +} + +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{0}` is not x, e.g. 1280x800")] +pub(crate) struct BadDimensions(String); + +impl FromStr for Dimensions { + type Err = BadDimensions; + + fn from_str(s: &str) -> Result { + let (width, height) = s.split_once(['x', 'X']).ok_or_else(|| BadDimensions(s.to_string()))?; + match (positive(width), positive(height)) { + (Ok(width), Ok(height)) => Ok(Dimensions { width, height }), + _ => Err(BadDimensions(s.to_string())), + } + } +} + +/// A mistake in the command line that clap can't see by itself. +#[derive(Debug, PartialEq, thiserror::Error)] +pub(crate) enum UsageError { + #[error("{output} {} is the {input}, which it would replace: choose another file{}", path.display(), if *in_place_helps { ", or pass --in-place" } else { "" })] + WouldReplace { output: &'static str, input: &'static str, path: PathBuf, in_place_helps: bool }, + #[error("--in-place is for an output that is the INPUT, and this is another file")] + InPlaceNotUsed, + #[error("a mesh is not saved in place: give -o to save the baked project")] + BakeNeedsOutput, + #[error("saving over {} needs --in-place (or give -o )", path.display())] + BakeInPlace { path: PathBuf }, + #[error("{flag} is for a headless server, and --bridge connects to an app")] + RootsWithBridge { flag: &'static str }, + #[error("--token is for --bridge, and this is a headless server")] + TokenNeedsBridge, + #[error("mcp needs --read-root and --write-root (or their --automation-*-root aliases)")] + McpNeedsRoots, +} + +impl UsageError { + /// The clap error, printed with the usage and exited with 2 like clap's own. + pub(crate) fn into_clap(self, subcommand: &str) -> clap::Error { + let mut command = crate::command(); + // Built, so a subcommand's usage names the program: `texturecraft-cli run`. + command.build(); + let mut command = command.find_subcommand_mut(subcommand).map_or_else(crate::command, std::mem::take); + command.error(ErrorKind::ArgumentConflict, self.to_string()) + } +} + +/// Whether two paths name the same existing file, through links and `.` and `..`. +fn same_file(a: &Path, b: &Path) -> bool { + matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b) +} + +/// Whether `path` is a .tcraft project. +pub(crate) fn is_project(path: &Path) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case(texturecraft_engine::core::PROJECT_EXT)) +} + +/// The path `Headless::save` writes: it appends `.tcraft` when the extension is missing. +fn project_save_path(path: &Path) -> PathBuf { + if is_project(path) { + path.to_owned() + } else { + let mut raw = path.as_os_str().to_os_string(); + raw.push("."); + raw.push(texturecraft_engine::core::PROJECT_EXT); + PathBuf::from(raw) + } +} + +fn would_replace(output: &'static str, input: &'static str, to: &Path, from: &Path, in_place_helps: bool) -> Result<(), UsageError> { + if same_file(to, from) { Err(UsageError::WouldReplace { output, input, path: to.to_owned(), in_place_helps }) } else { Ok(()) } +} + +fn would_replace_project(output: &'static str, input: &'static str, to: &Path, from: &Path, in_place_helps: bool) -> Result<(), UsageError> { + would_replace(output, input, &project_save_path(to), from, in_place_helps) +} + +fn same_project(output: &Path, input: &Path) -> bool { + same_file(&project_save_path(output), input) +} + +/// If a batch script's `save` would replace `open`, it needs `--in-place`. An unreadable or +/// malformed script is left to the command, which reports that as a failure (exit 1). +fn batch_would_replace(a: &BatchArgs) -> Result<(), UsageError> { + let Ok(text) = std::fs::read_to_string(&a.script) else { + return Ok(()); + }; + let Ok(script) = serde_json::from_str::(&text) else { + return Ok(()); + }; + let field = |name: &str| script.get(name).and_then(Value::as_str); + let Some(output) = field("save") else { + return Ok(()); + }; + let input = field("open").unwrap_or("builtin:material_ball"); + if input.starts_with("builtin:") { + return if a.in_place { Err(UsageError::InPlaceNotUsed) } else { Ok(()) }; + } + let input = Path::new(input); + let output = Path::new(output); + match (same_project(output, input), a.in_place) { + (true, false) => Err(UsageError::WouldReplace { output: "save", input: "open", path: project_save_path(output), in_place_helps: true }), + (false, true) => Err(UsageError::InPlaceNotUsed), + _ => Ok(()), + } +} + +impl Command { + /// What clap can't check: the files a command would replace, and flags for another mode. + fn check(&self) -> Result<(), (&'static str, UsageError)> { + match self { + Command::Run(a) => match (&a.output, a.in_place) { + (Some(out), false) => would_replace_project("-o", "INPUT", out, &a.input, true).map_err(|e| ("run", e)), + (Some(out), true) if !same_project(out, &a.input) => Err(("run", UsageError::InPlaceNotUsed)), + _ => Ok(()), + }, + Command::Bake(a) => match (&a.output, a.in_place) { + (None, false) if is_project(&a.input) => Err(("bake", UsageError::BakeInPlace { path: a.input.clone() })), + (None, _) if !is_project(&a.input) => Err(("bake", UsageError::BakeNeedsOutput)), + (Some(out), false) => would_replace_project("-o", "INPUT", out, &a.input, true).map_err(|e| ("bake", e)), + (Some(out), true) if !same_project(out, &a.input) => Err(("bake", UsageError::InPlaceNotUsed)), + _ => Ok(()), + }, + Command::Render(a) => would_replace("OUT.PNG", "INPUT", &a.output, &a.input, false).map_err(|e| ("render", e)), + Command::New(a) => would_replace_project("OUT.TCRAFT", "INPUT", &a.output, &a.input, false).map_err(|e| ("new", e)), + Command::Batch(a) => batch_would_replace(a).map_err(|e| ("batch", e)), + Command::Mcp(a) if a.bridge.is_some() => match (&a.roots.read_root, &a.roots.write_root) { + (Some(_), _) => Err(("mcp", UsageError::RootsWithBridge { flag: "--read-root" })), + (_, Some(_)) => Err(("mcp", UsageError::RootsWithBridge { flag: "--write-root" })), + _ => Ok(()), + }, + Command::Mcp(a) if a.bridge.is_none() => match (&a.roots.read_root, &a.roots.write_root) { + (Some(_), Some(_)) => Ok(()), + _ => Err(("mcp", UsageError::McpNeedsRoots)), + }, + _ => Ok(()), + } + } +} + +/// 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 { + let matches = crate::command().try_get_matches_from(std::iter::once(OsString::from("texturecraft-cli")).chain(args.iter().cloned()))?; + let cli = Cli::from_arg_matches(&matches)?; + // An inherited TEXTURECRAFT_CONTROL_TOKEN must not force --bridge: the variable is how a + // client authenticates when --bridge is already set. Only an explicit --token flag requires it. + let token_flag_without_bridge = matches + .subcommand_matches("mcp") + .is_some_and(|mcp| mcp.value_source("token") == Some(clap::parser::ValueSource::CommandLine) && mcp.get_one::("bridge").is_none()); + if token_flag_without_bridge { + return Err(UsageError::TokenNeedsBridge.into_clap("mcp")); + } + cli.command.check().map_err(|(sub, e)| e.into_clap(sub))?; + Ok(cli) +} diff --git a/apps/texturecraft-cli/src/error.rs b/apps/texturecraft-cli/src/error.rs new file mode 100644 index 00000000..30687f1c --- /dev/null +++ b/apps/texturecraft-cli/src/error.rs @@ -0,0 +1,36 @@ +use std::path::{Path, PathBuf}; + +use texturecraft_automation::AutomationError; + +/// Why a subcommand failed: printed as `error: {e}`, exit 1. +#[derive(Debug, thiserror::Error)] +pub(crate) enum CliError { + #[error(transparent)] + Automation(#[from] AutomationError), + /// The engine's commands take paths as JSON text, which holds only Unicode. + #[error("{}: the path is not valid Unicode", .0.display())] + NotUnicode(PathBuf), + #[error("unknown built-in mesh `{0}`")] + UnknownBuiltin(String), + #[error("cannot read {}: {message}", path.display())] + Read { path: PathBuf, message: String }, + #[error("cannot write {}: {source}", path.display())] + Write { path: PathBuf, source: std::io::Error }, + #[error("{} is not JSON: {source}", path.display())] + Script { path: PathBuf, source: serde_json::Error }, + #[error("the script must be a list of steps or {{\"steps\": [...]}}")] + ScriptShape, + #[error("the script's `{0}` field must be a string")] + ScriptField(&'static str), + #[error("step {index} (`{id}`) failed: {message}")] + BatchStopped { index: String, id: String, message: String }, + #[error("{} is already a project", .0.display())] + AlreadyProject(PathBuf), + #[error("{0}")] + Serve(std::io::Error), +} + +/// A path as the text the engine's commands take. +pub(crate) fn unicode(path: &Path) -> Result<&str, CliError> { + path.to_str().ok_or_else(|| CliError::NotUnicode(path.to_owned())) +} diff --git a/apps/texturecraft-cli/src/lib.rs b/apps/texturecraft-cli/src/lib.rs new file mode 100644 index 00000000..872765af --- /dev/null +++ b/apps/texturecraft-cli/src/lib.rs @@ -0,0 +1,342 @@ +//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and +//! serve agents over MCP or JSON lines. Never opens a window. `run` is the whole program, so it can +//! be tested in-process as well as through the binary; `texturecraft-cli --help` lists the +//! subcommands. The conventions are RFC-0018's: exit 0, 1 (a command failed) or 2 (a usage error), +//! results on stdout, `error: ` on stderr. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod args; +mod error; + +use std::ffi::OsString; +use std::io::Write; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use clap::CommandFactory; +use serde_json::{Value, json}; +use texturecraft_automation::security::{client_token, server_token}; +use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc}; +use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report}; + +use args::{ + BakeArgs, BatchArgs, Cli, Command, CommandsArgs, ExportArgs, InfoArgs, McpArgs, NewArgs, RenderArgs, RootArgs, RunArgs, ServeArgs, is_project, parse, +}; +use error::{CliError, unicode}; + +/// Writes a line. A closed pipe (`texturecraft-cli info x | head`) is not worth an error: the rest +/// of the output is dropped. +macro_rules! outln { + ($to:expr, $($arg:tt)*) => { + drop(writeln!($to, $($arg)*)) + }; +} + +/// The version `--version` prints after the program's name: ` ( )`. +fn version() -> String { + let sha = env!("TEXTURECRAFT_BUILD_SHA"); + let short = sha.get(..7).unwrap_or(sha); + let date = env!("TEXTURECRAFT_BUILD_DATE"); + match (short.is_empty(), date.is_empty()) { + (true, true) => texturecraft_engine::VERSION.to_string(), + (true, false) => format!("{} ({date})", texturecraft_engine::VERSION), + _ => format!("{} ({short} {date})", texturecraft_engine::VERSION), + } +} + +/// The command line's clap definition. +pub fn command() -> clap::Command { + Cli::command().version(version()) +} + +/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the +/// GUI only, and a script that passes them to the CLI has the wrong program. +fn launch_profile_argument(args: &[OsString]) -> Option { + args.iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .find(|arg| ["--launch-profile", "--profile-root"].iter().any(|flag| arg == flag || arg.starts_with(&format!("{flag}=")))) +} + +/// Run the CLI on its arguments (without the program name), writing results to `out` and +/// diagnostics to `err`. Returns the process exit code: 0 on success, 1 on failure, 2 for a usage +/// error. Help and the version go to `out`, exit 0. `mcp` and `serve` speak on the process's own +/// stdin and stdout. +pub fn run(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32 +where + I: IntoIterator, + T: Into, +{ + let args: Vec = args.into_iter().map(Into::into).collect(); + if let Some(flag) = launch_profile_argument(&args) { + outln!(err, "error: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); + return 2; + } + // Help and the version (`help`, `-h`, ` --help`, `-V`) come back as errors too. + let cli = match parse(&args) { + Ok(cli) => cli, + Err(e) => { + let to: &mut dyn Write = if e.use_stderr() { err } else { out }; + let _ = write!(to, "{}", e.render()); + return e.exit_code(); + } + }; + match dispatch(cli.command, out, err) { + Ok(()) => 0, + Err(e) => { + outln!(err, "error: {e}"); + 1 + } + } +} + +fn dispatch(command: Command, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + match command { + Command::Info(a) => info(&a, out), + Command::Commands(a) => commands(&a, out), + Command::Run(a) => run_command(&a, out, err), + Command::Batch(a) => batch(&a, out, err), + Command::Bake(a) => bake(&a, out, err), + Command::Export(a) => export(&a, out, err), + Command::Render(a) => render(&a, err), + Command::New(a) => new(&a, err), + Command::Mcp(a) => mcp(&a), + Command::Serve(a) => serve(&a, err), + } +} + +fn print(out: &mut dyn Write, v: &Value) { + outln!(out, "{}", serde_json::to_string_pretty(v).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}"))); +} + +/// A trusted local session on `input`: a project, a mesh file or `builtin:`. +fn open(input: &Path, resolution: Option) -> Result { + let mut h = Headless::new(Headless::default_session()?, Filesystem::TrustedLocal); + match input.to_str().and_then(|text| text.strip_prefix("builtin:")) { + Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ())?, + None if is_project(input) => h.open(unicode(input)?).map(|_| ())?, + None => h.import_mesh(unicode(input)?, resolution, None).map(|_| ())?, + } + Ok(h) +} + +fn save(h: &mut Headless, out: &Path, err: &mut dyn Write) -> Result<(), CliError> { + let r = h.save(Some(unicode(out)?))?; + outln!(err, "saved {}", r["path"].as_str().unwrap_or_default()); + Ok(()) +} + +fn report_json(r: &MeshReport) -> Value { + json!({ + "triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated, + "uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings, + }) +} + +fn info(a: &InfoArgs, out: &mut dyn Write) -> Result<(), CliError> { + let file = unicode(&a.input)?; + if let Some(id) = file.strip_prefix("builtin:") { + let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| CliError::UnknownBuiltin(id.to_string()))?; + let report = mesh_report(&m); + print( + out, + &json!({ + "file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(), + "materials": m.materials, "textureSets": m.materials, "uv": report_json(&report), + }), + ); + return Ok(()); + } + if !is_project(&a.input) { + let m = import_mesh(&a.input).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?; + print( + out, + &json!({ + "file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(), + "materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report), + }), + ); + return Ok(()); + } + let h = open(&a.input, None)?; + let mut v = h.inspect(); + v["file"] = json!(file); + v["kind"] = json!("project"); + // The embedded mesh is re-imported for its UV report (built-in meshes have none). + v["uv"] = match &h.session.mesh_source { + Some((ext, bytes)) => { + let m = import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?; + report_json(&m.report) + } + None => Value::Null, + }; + print(out, &v); + Ok(()) +} + +fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result<(), CliError> { + let h = open(Path::new("builtin:cube"), Some(128))?; + let list = h.command_list(a.filter.as_deref()); + if a.json { + print(out, &list); + return Ok(()); + } + for c in list.as_array().into_iter().flatten() { + let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + outln!(out, "{:<28} {:<36} {}", f("id"), f("label"), f("params")); + } + Ok(()) +} + +fn run_command(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let mut h = open(&a.input, None)?; + print(out, &h.command_run(&a.id, a.params.clone().unwrap_or_else(|| json!({})))?); + match &a.output { + Some(path) => save(&mut h, path, err), + None => Ok(()), + } +} + +fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let text = std::fs::read_to_string(&a.script).map_err(|e| CliError::Read { path: a.script.clone(), message: e.to_string() })?; + let script: Value = serde_json::from_str(&text).map_err(|source| CliError::Script { path: a.script.clone(), source })?; + let steps = script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or(CliError::ScriptShape)?; + let path_field = |field: &'static str| -> Result, CliError> { + match script.get(field) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(path)) => Ok(Some(path.as_str())), + Some(_) => Err(CliError::ScriptField(field)), + } + }; + let input = path_field("open")?.unwrap_or("builtin:material_ball"); + let output = path_field("save")?; + + let mut h = open(Path::new(input), None)?; + let reply = h.batch(steps); + print(out, &reply); + if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) { + return Err(CliError::BatchStopped { + index: failure["index"].to_string(), + id: failure["id"].as_str().unwrap_or_default().to_string(), + message: failure["error"].as_str().unwrap_or_default().to_string(), + }); + } + match output { + Some(path) => save(&mut h, Path::new(path), err), + None => Ok(()), + } +} + +fn bake(a: &BakeArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + // `check` has seen to it: a project without -o is saved in place (--in-place), a mesh has -o. + let target = a.output.as_deref().unwrap_or(&a.input); + let mut p = json!({"ts": "all"}); + if let Some(r) = a.resolution { + p["resolution"] = json!(r); + } + if !a.maps.is_empty() { + p["maps"] = json!(a.maps.iter().map(|m| m.trim()).filter(|m| !m.is_empty()).collect::>()); + } + let mut h = open(&a.input, None)?; + h.command_run("bake.run", p)?; + save(&mut h, target, err)?; + print(out, &h.inspect()["textureSets"]); + Ok(()) +} + +fn export(a: &ExportArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> { + let mut p = json!({"dir": unicode(&a.dir)?}); + for (key, value) in [("preset", &a.preset), ("format", &a.format), ("padding", &a.padding)] { + if let Some(v) = value { + p[key] = json!(v); + } + } + if let Some(v) = a.size { + p["size"] = json!(v); + } + let mut h = open(&a.input, None)?; + let r = h.export(&p)?; + for w in r["warnings"].as_array().into_iter().flatten() { + outln!(err, "warning: {}", w.as_str().unwrap_or_default()); + } + for f in r["files"].as_array().into_iter().flatten() { + outln!(out, "{}", f.as_str().unwrap_or_default()); + } + Ok(()) +} + +fn render(a: &RenderArgs, err: &mut dyn Write) -> Result<(), CliError> { + let options = RenderOptions { + view: a.view.clone(), + width: a.size.map(|s| s.width), + height: a.size.map(|s| s.height), + yaw: a.yaw, + pitch: a.pitch, + samples: a.samples, + bounces: a.bounces, + cpu: a.cpu, + }; + let mut h = open(&a.input, None)?; + if let Some(name) = &a.camera { + h.command_run("camera.select", json!({ "name": name }))?; + } + let t0 = std::time::Instant::now(); + let r = h.render_png(&options)?; + let secs = t0.elapsed().as_secs_f64(); + std::fs::write(&a.output, &r.png).map_err(|source| CliError::Write { path: a.output.clone(), source })?; + outln!(err, "wrote {} ({}x{}, {}, {secs:.2} s)", a.output.display(), r.width, r.height, r.by); + Ok(()) +} + +fn new(a: &NewArgs, err: &mut dyn Write) -> Result<(), CliError> { + if is_project(&a.input) { + return Err(CliError::AlreadyProject(a.input.clone())); + } + let mut h = open(&a.input, a.resolution)?; + if a.sample { + let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024)); + h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res}))?; + for ts in 0..h.session.set_count() { + h.command_run("textureSet.select", json!({"ts": ts}))?; + h.command_run("material.apply", json!({"material": "steel_painted_worn"}))?; + } + h.command_run("textureSet.select", json!({"ts": 0}))?; + } + save(&mut h, &a.output, err) +} + +/// File access for servers: none without roots, else only below them +fn workspace(roots: &RootArgs) -> Result { + if roots.read_root.is_none() && roots.write_root.is_none() { + return Ok(Filesystem::Denied); + } + Ok(Filesystem::Workspace(AuthorizedWorkspace::new(roots.read_root.as_deref(), roots.write_root.as_deref())?)) +} + +fn mcp(a: &McpArgs) -> Result<(), CliError> { + let server = match a.bridge { + Some(port) => TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.token.clone())?)), + None => TexturecraftMcp::headless(Headless::new(Headless::default_session()?, workspace(&a.roots)?)), + }; + let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(CliError::Serve)?; + rt.block_on(server.serve_stdio()).map_err(|e| CliError::Automation(texturecraft_automation::AutomationError::Other(e.to_string()))) +} + +fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result<(), CliError> { + let h = Arc::new(Mutex::new(Headless::new(Headless::default_session()?, workspace(&a.roots)?))); + match a.port { + None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(CliError::Serve)?, + Some(port) => { + // Bind first: a port in use must not replace its server's token file. + let listener = rpc::bind_tcp(port)?; + let addr = listener.local_addr().map_err(CliError::Serve)?; + let (token, file) = server_token(addr.port())?; + match file { + Some(f) => outln!(err, "texturecraft-cli: serving on {addr}; token in {}", f.display()), + None => outln!(err, "texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"), + } + rpc::serve_listener(listener, h, token)?; + } + } + Ok(()) +} diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index 80069d9d..357cf17e 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -1,452 +1,8 @@ -//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and -//! serve agents over MCP or JSON lines. Never opens a window. +//! Headless TextureCraft command line. Never opens a window. See the library crate for the commands. #![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -use std::path::Path; -use std::sync::{Arc, Mutex}; - -use serde_json::{Value, json}; -use texturecraft_automation::security::{client_token, server_token}; -use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc}; -use texturecraft_engine::core::PROJECT_EXT; -use texturecraft_engine::formats::{MeshReport, import_mesh, import_mesh_bytes, mesh_report}; - -const USAGE: &str = "\ -texturecraft-cli: headless TextureCraft - -USAGE: - texturecraft-cli --version - texturecraft-cli info > - Texture sets, layers, triangles, materials and the UV report, as JSON. - texturecraft-cli commands [--filter ] - List the engine commands (id, label, params). - texturecraft-cli run [params-json] [-o ] - Run one command and print its JSON result; -o saves the project. - texturecraft-cli batch - Run [{\"id\", \"params\"}, ...] or {\"open\": , \"steps\": [...], \"save\": }. - texturecraft-cli bake [-o ] [--resolution ] [--maps ] - Bake mesh maps for every texture set (a project is saved in place without -o). - texturecraft-cli export [--preset ] [--format ] [--padding ] [--size ] - Export textures (default preset: Document channels + Normal + AO (No Alpha)). - texturecraft-cli render [--size x] [--view 3d|2d] [--camera ] [--yaw ] - [--pitch ] [--samples ] [--bounces ] [--cpu] - Render the viewport to PNG (needs a GPU or software adapter); --camera looks through a - camera saved in the project (camera.add); --samples path traces it instead (Rendering - mode), on the GPU when it has compute shaders, else (or with --cpu) on the CPU. - texturecraft-cli new > [--resolution ] [--sample] - New project; --sample bakes and applies a smart material to every texture set. The - sample's mesh maps are baked at the resolution up to 1024 px (most of the file's size), - so a 2048 sample project is as large as a 1024 one. - texturecraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] - MCP server on stdio: headless (file access only below the roots), or bridged to - `texturecraft --control `. --automation-read-root / --automation-write-root are - the same as --read-root / --write-root (mcp and serve). - texturecraft-cli serve [--port ] [--read-root ] [--write-root ] - JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token. - - is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .usd .usda .usdc .usdz .abc .obj .ply .stl) -or builtin: (material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate, udim_plane). -See docs/control-protocol.md. -"; - -/// (name, flags taking a value, bare flags) -const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ - ("info", &[], &[]), - ("commands", &["--filter"], &[]), - ("run", &["-o"], &[]), - ("batch", &[], &[]), - ("bake", &["-o", "--resolution", "--maps"], &[]), - ("export", &["--preset", "--format", "--padding", "--size"], &[]), - ("render", &["--size", "--view", "--camera", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]), - ("new", &["--resolution"], &["--sample"]), - ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), - ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), -]; - -struct Args { - pos: Vec, - flags: Vec<(String, Option)>, -} - -impl Args { - fn get(&self, k: &str) -> Option<&str> { - self.flags.iter().rev().find(|(f, _)| f == k).and_then(|(_, v)| v.as_deref()) - } - fn has(&self, k: &str) -> bool { - self.flags.iter().any(|(f, _)| f == k) - } - fn num(&self, k: &str) -> Result, String> { - self.get(k).map(|v| v.parse().map_err(|_| format!("{k}: `{v}` is not a valid number"))).transpose() - } - fn pos(&self, n: usize, what: &str) -> Result<&str, String> { - self.pos.get(n).map(String::as_str).ok_or_else(|| format!("missing {what}")) - } -} - -fn parse(values: &[&str], bare: &[&str], args: &[String]) -> Result { - let mut a = Args { pos: Vec::new(), flags: Vec::new() }; - let mut it = args.iter(); - while let Some(s) = it.next() { - let (k, inline) = match s.split_once('=') { - Some((k, v)) if k.starts_with("--") => (k, Some(v.to_string())), - _ => (s.as_str(), None), - }; - if values.contains(&k) { - let v = match inline { - Some(v) => v, - None => it.next().ok_or_else(|| format!("{k} needs a value"))?.clone(), - }; - a.flags.push((k.to_string(), Some(v))); - } else if bare.contains(&k) && inline.is_none() { - a.flags.push((k.to_string(), None)); - } else if k.starts_with('-') && k.len() > 1 && k.parse::().is_err() { - return Err(format!("unknown option `{s}`")); - } else { - a.pos.push(s.clone()); - } - } - Ok(a) -} - -fn version() -> String { - let sha = env!("TEXTURECRAFT_BUILD_SHA"); - let short = sha.get(..7).unwrap_or(sha); - let date = env!("TEXTURECRAFT_BUILD_DATE"); - match (short.is_empty(), date.is_empty()) { - (true, true) => format!("TextureCraft {}", texturecraft_engine::VERSION), - (true, false) => format!("TextureCraft {} ({date})", texturecraft_engine::VERSION), - _ => format!("TextureCraft {} ({short} {date})", texturecraft_engine::VERSION), - } -} - -/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the -/// GUI only, and a script that passes them to the CLI has the wrong program. -fn is_launch_profile_flag(arg: &str) -> bool { - arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") -} fn main() { - let args: Vec = std::env::args().skip(1).collect(); - if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) { - eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); - std::process::exit(2); - } - let code = match args.first().map(String::as_str) { - None => { - eprint!("{USAGE}"); - 2 - } - Some("--version" | "-V" | "version") => { - println!("{}", version()); - 0 - } - Some("--help" | "-h" | "help") => { - print!("{USAGE}"); - 0 - } - Some(cmd) => match SUBCOMMANDS.iter().find(|(n, _, _)| *n == cmd) { - None => { - eprintln!("texturecraft-cli: unknown command `{cmd}`\n\n{USAGE}"); - 2 - } - Some(_) if args.iter().any(|a| a == "--help" || a == "-h") => { - print!("{USAGE}"); - 0 - } - Some((name, values, bare)) => match parse(values, bare, args.get(1..).unwrap_or_default()) { - Err(e) => { - eprintln!("texturecraft-cli {name}: {e}\n\n{USAGE}"); - 2 - } - Ok(a) => match dispatch(name, &a) { - Ok(()) => 0, - Err(e) => { - eprintln!("texturecraft-cli {name}: error: {e}"); - 1 - } - }, - }, - }, - }; + // `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed. + let code = texturecraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); std::process::exit(code); } - -type R = Result<(), String>; - -fn dispatch(name: &str, a: &Args) -> R { - match name { - "info" => info(a), - "commands" => commands(a), - "run" => run(a), - "batch" => batch(a), - "bake" => bake(a), - "export" => export(a), - "render" => render(a), - "new" => new(a), - "mcp" => mcp(a), - "serve" => serve(a), - other => Err(format!("unknown command `{other}`")), - } -} - -fn s(e: impl std::fmt::Display) -> String { - e.to_string() -} - -fn print_json(v: &Value) -> R { - println!("{}", serde_json::to_string_pretty(v).map_err(s)?); - Ok(()) -} - -fn is_project(path: &str) -> bool { - Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case(PROJECT_EXT)) -} - -/// A trusted local session on `input`: a project, a mesh file or `builtin:`. -fn open(input: &str, resolution: Option) -> Result { - let mut h = Headless::new(Headless::default_session().map_err(s)?, Filesystem::TrustedLocal); - match input.strip_prefix("builtin:") { - Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ()), - None if is_project(input) => h.open(input).map(|_| ()), - None => h.import_mesh(input, resolution, None).map(|_| ()), - } - .map_err(s)?; - Ok(h) -} - -fn save(h: &mut Headless, out: &str) -> R { - let r = h.save(Some(out)).map_err(s)?; - eprintln!("saved {}", r["path"].as_str().unwrap_or_default()); - Ok(()) -} - -fn report_json(r: &MeshReport) -> Value { - json!({ - "triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated, - "uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings, - }) -} - -fn info(a: &Args) -> R { - let file = a.pos(0, "")?; - if let Some(id) = file.strip_prefix("builtin:") { - let m = texturecraft_engine::geom::primitives::builtin(id).ok_or_else(|| format!("unknown built-in mesh `{id}`"))?; - let report = mesh_report(&m); - return print_json(&json!({ - "file": file, "kind": "mesh", "triangles": m.triangle_count(), "vertices": m.vertex_count(), - "materials": m.materials, "textureSets": m.materials, "uv": report_json(&report), - })); - } - if !is_project(file) { - let m = import_mesh(Path::new(file)).map_err(|e| format!("cannot read {file}: {e}"))?; - return print_json(&json!({ - "file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(), - "materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report), - })); - } - let h = open(file, None)?; - let mut v = h.inspect(); - v["file"] = json!(file); - v["kind"] = json!("project"); - // The embedded mesh is re-imported for its UV report (built-in meshes have none). - v["uv"] = match &h.session.mesh_source { - Some((ext, bytes)) => import_mesh_bytes(&format!("mesh.{ext}"), bytes).map(|m| report_json(&m.report)).map_err(s)?, - None => Value::Null, - }; - print_json(&v) -} - -fn commands(a: &Args) -> R { - let h = open("builtin:cube", Some(128))?; - for c in h.command_list(a.get("--filter")).as_array().into_iter().flatten() { - let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); - println!("{:<28} {:<36} {}", f("id"), f("label"), f("params")); - } - Ok(()) -} - -fn run(a: &Args) -> R { - let (input, id) = (a.pos(0, "")?, a.pos(1, "")?); - let params: Value = match a.pos.get(2) { - Some(j) => serde_json::from_str(j).map_err(|e| format!("params are not JSON: {e}"))?, - None => json!({}), - }; - let mut h = open(input, None)?; - print_json(&h.command_run(id, params).map_err(s)?)?; - match a.get("-o") { - Some(out) => save(&mut h, out), - None => Ok(()), - } -} - -fn batch(args: &Args) -> R { - let path = args.pos(0, "")?; - let script: Value = { - let script_text = std::fs::read_to_string(path).map_err(|err| format!("cannot read {path}: {err}"))?; - serde_json::from_str(&script_text).map_err(|err| format!("{path} is not JSON: {err}"))? - }; - - let steps = - script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or("the script must be a list of steps or {\"steps\": [...]}")?; - let path_field = |field: &str| -> Result, String> { - match script.get(field) { - None | Some(Value::Null) => Ok(None), - Some(Value::String(path)) => Ok(Some(path.as_str())), - Some(_) => Err(format!("the script's `{field}` field must be a string")), - } - }; - let input = path_field("open")?.unwrap_or("builtin:material_ball"); - let output = path_field("save")?; - - let mut headless = open(input, None)?; - let reply = headless.batch(steps); - print_json(&reply)?; - if let Some(failure) = reply.get("failed").filter(|failure| !failure.is_null()) { - return Err(format!( - "step {} (`{}`) failed: {}", - failure["index"], - failure["id"].as_str().unwrap_or_default(), - failure["error"].as_str().unwrap_or_default() - )); - } - - match output { - Some(output_path) => save(&mut headless, output_path), - None => Ok(()), - } -} - -fn bake(a: &Args) -> R { - let input = a.pos(0, "")?; - let out = a.get("-o").or(is_project(input).then_some(input)).ok_or("give -o to save the baked project")?; - let mut p = json!({"ts": "all"}); - if let Some(r) = a.num::("--resolution")? { - p["resolution"] = json!(r); - } - if let Some(m) = a.get("--maps") { - p["maps"] = json!(m.split(',').map(str::trim).filter(|m| !m.is_empty()).collect::>()); - } - let mut h = open(input, None)?; - h.command_run("bake.run", p).map_err(s)?; - save(&mut h, out)?; - print_json(&h.inspect()["textureSets"]) -} - -fn export(a: &Args) -> R { - let (input, dir) = (a.pos(0, "")?, a.pos(1, "")?); - let mut p = json!({"dir": dir}); - for k in ["preset", "format", "padding"] { - if let Some(v) = a.get(&format!("--{k}")) { - p[k] = json!(v); - } - } - if let Some(v) = a.num::("--size")? { - p["size"] = json!(v); - } - let mut h = open(input, None)?; - let r = h.export(&p).map_err(s)?; - for w in r["warnings"].as_array().into_iter().flatten() { - eprintln!("warning: {}", w.as_str().unwrap_or_default()); - } - for f in r["files"].as_array().into_iter().flatten() { - println!("{}", f.as_str().unwrap_or_default()); - } - Ok(()) -} - -fn render(a: &Args) -> R { - let (input, out) = (a.pos(0, "")?, a.pos(1, "")?); - let (width, height) = match a.get("--size") { - Some(sz) => { - let (w, h) = sz.split_once(['x', 'X']).ok_or("--size must be x, e.g. 1280x800")?; - (Some(w.parse().map_err(|_| "bad --size width")?), Some(h.parse().map_err(|_| "bad --size height")?)) - } - None => (None, None), - }; - let o = RenderOptions { - view: a.get("--view").map(str::to_string), - width, - height, - yaw: a.num("--yaw")?, - pitch: a.num("--pitch")?, - samples: a.num("--samples")?, - bounces: a.num("--bounces")?, - cpu: a.has("--cpu"), - }; - let mut h = open(input, None)?; - if let Some(name) = a.get("--camera") { - h.command_run("camera.select", json!({ "name": name })).map_err(s)?; - } - let t0 = std::time::Instant::now(); - let r = h.render_png(&o).map_err(s)?; - let secs = t0.elapsed().as_secs_f64(); - std::fs::write(out, &r.png).map_err(|e| format!("cannot write {out}: {e}"))?; - eprintln!("wrote {out} ({}x{}, {}, {secs:.2} s)", r.width, r.height, r.by); - Ok(()) -} - -fn new(a: &Args) -> R { - let (input, out) = (a.pos(0, "")?, a.pos(1, "")?); - if is_project(input) { - return Err(format!("{input} is already a project")); - } - let res = a.num::("--resolution")?; - let mut h = open(input, res)?; - if a.has("--sample") { - let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024)); - h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res})).map_err(s)?; - for ts in 0..h.session.set_count() { - h.command_run("textureSet.select", json!({"ts": ts})).map_err(s)?; - h.command_run("material.apply", json!({"material": "steel_painted_worn"})).map_err(s)?; - } - h.command_run("textureSet.select", json!({"ts": 0})).map_err(s)?; - } - save(&mut h, out) -} - -fn workspace(a: &Args) -> Result { - // `--automation-*-root` is the spelling the other crafting apps use. - let root = |k: &str| a.get(&format!("--automation-{k}")).or_else(|| a.get(&format!("--{k}"))).map(Path::new); - let (r, w) = (root("read-root"), root("write-root")); - if r.is_none() && w.is_none() { - return Ok(Filesystem::Denied); - } - Ok(Filesystem::Workspace(AuthorizedWorkspace::new(r, w).map_err(s)?)) -} - -fn port_of(v: &str) -> Result { - let p = v.strip_prefix("127.0.0.1:").or_else(|| v.strip_prefix("localhost:")).unwrap_or(v); - p.parse::().ok().filter(|p| *p != 0).ok_or_else(|| format!("`{v}` is not a loopback port (1-65535)")) -} - -fn mcp(a: &Args) -> R { - let server = match a.get("--bridge") { - Some(b) => { - let port = port_of(b)?; - TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.get("--token").map(str::to_string)).map_err(s)?)) - } - None => TexturecraftMcp::headless(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?)), - }; - let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(s)?; - rt.block_on(server.serve_stdio()).map_err(s) -} - -fn serve(a: &Args) -> R { - let h = Arc::new(Mutex::new(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?))); - match a.get("--port") { - None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(s), - Some(p) => { - // Bind first: a port in use must not replace its server's token file, and port 0's - // token file is named after the port actually picked. - let listener = rpc::bind_tcp(port_of(p)?).map_err(s)?; - let addr = listener.local_addr().map_err(s)?; - let (token, file) = server_token(addr.port()).map_err(s)?; - match file { - Some(f) => eprintln!("texturecraft-cli: serving on {addr}; token in {}", f.display()), - None => eprintln!("texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"), - } - rpc::serve_listener(listener, h, token).map_err(s) - } - } -} diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 6bef0017..a5089e96 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -44,9 +44,9 @@ fn p(path: &Path) -> &str { #[test] fn version_and_usage_errors() { let v = ok(&["--version"]); - assert!(v.starts_with("TextureCraft "), "{v}"); + assert!(v.starts_with("texturecraft-cli "), "{v}"); assert_eq!(v.lines().count(), 1); - assert!(ok(&["--help"]).contains("texturecraft-cli mcp")); + assert!(ok(&["--help"]).contains("Usage: texturecraft-cli ")); assert_eq!(cli(&[]).status.code(), Some(2)); assert_eq!(cli(&["frobnicate"]).status.code(), Some(2)); assert_eq!(cli(&["info", "--bogus"]).status.code(), Some(2)); @@ -54,8 +54,8 @@ fn version_and_usage_errors() { assert_eq!(o.status.code(), Some(1)); assert!(String::from_utf8_lossy(&o.stderr).contains("error")); assert_eq!(cli(&["run", "builtin:nope", "layer.add.fill"]).status.code(), Some(1)); - assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(1)); - assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(1)); + assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(2)); + assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(2)); } #[test] @@ -73,7 +73,7 @@ fn new_info_run_bake_export_batch() { assert!(r["layer"].is_u64(), "{r}"); assert_eq!(json(&["info", p(&b)])["layers"][0]["kind"], "fill"); - ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature"]); + ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature", "--in-place"]); let maps = json(&["info", p(&b)])["textureSets"][0]["baked"]["maps"].clone(); assert_eq!(maps.as_array().unwrap().len(), 2, "{maps}"); @@ -202,10 +202,10 @@ fn path_traced_render_needs_no_gpu() { // --camera looks through a camera saved in the project; an unknown name is an error. let proj = d.join("cams.tcraft"); ok(&["run", "builtin:cube", "camera.set", r#"{"yaw": 80, "distance": 9}"#, "-o", p(&proj)]); - ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj)]); + ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj), "--in-place"]); ok(&["render", p(&proj), p(&out), "--size", "48x32", "--camera", "Side", "--samples", "2", "--cpu"]); assert_eq!(cli(&["render", p(&proj), p(&out), "--camera", "Nope", "--samples", "2", "--cpu"]).status.code(), Some(1)); - assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(1)); + assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(2)); assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "4", "--view", "2d"]).status.code(), Some(1)); let _ = std::fs::remove_dir_all(&d); } diff --git a/apps/texturecraft-cli/tests/it/cli.rs b/apps/texturecraft-cli/tests/it/cli.rs new file mode 100644 index 00000000..332da939 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/cli.rs @@ -0,0 +1,331 @@ +//! RFC-0018 rule 2.7: help, versions, usage errors with exit 2 on stderr, and nothing written +//! before the arguments are checked. + +use std::ffi::OsString; + +use crate::{argv, invoke, project, workdir}; + +const SUBCOMMANDS: [&str; 10] = ["info", "commands", "run", "batch", "bake", "export", "render", "new", "mcp", "serve"]; + +/// The shortest valid command line of each subcommand. +fn minimal(sub: &str) -> Vec<&str> { + match sub { + "info" => vec!["info", "builtin:cube"], + "run" => vec!["run", "builtin:cube", "layer.add.fill"], + "batch" => vec!["batch", "s.json"], + "bake" => vec!["bake", "builtin:cube", "-o", "o.tcraft"], + "export" => vec!["export", "builtin:cube", "dir"], + "render" => vec!["render", "builtin:cube", "o.png"], + "new" => vec!["new", "builtin:cube", "o.tcraft"], + other => vec![other], + } +} + +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: "), "{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("texturecraft-cli"), "{args:?}: {}", got.out); + } + let help = invoke(["--help"]).out; + assert!(help.contains("Exit status:") && help.contains("128 + the signal number"), "{help}"); + for sub in SUBCOMMANDS { + 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: texturecraft-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 top = invoke(["--version"]).out; + let want = top.strip_prefix("texturecraft-cli ").unwrap().trim_end().to_string(); + assert!(want.starts_with(texturecraft_engine::VERSION), "{want}"); + for sub in SUBCOMMANDS { + for flag in ["--version", "-V"] { + let got = invoke([sub, flag]); + assert_eq!((got.code, got.out.as_str(), got.err.as_str()), (0, format!("texturecraft-cli-{sub} {want}\n").as_str(), ""), "{sub} {flag}"); + } + } + usage_error(&["version"]); +} + +#[test] +fn no_arguments_is_a_usage_error_that_prints_the_help_on_stderr() { + let got = invoke(Vec::::new()); + assert_eq!((got.code, got.out.as_str()), (2, "")); + assert!(got.err.contains("Usage: texturecraft-cli "), "{}", got.err); +} + +#[test] +fn an_unknown_flag_or_subcommand_is_refused_by_every_subcommand() { + for sub in SUBCOMMANDS { + let mut args = minimal(sub); + args.push("--fromat"); + let message = usage_error(&args); + assert!(message.contains("--fromat"), "{sub}: {message}"); + } + usage_error(&["rendre"]); + usage_error(&["--fromat"]); +} + +#[test] +fn a_flag_given_twice_is_refused() { + usage_error(&["new", "builtin:cube", "o.tcraft", "--resolution", "8", "--resolution", "9"]); + usage_error(&["bake", "builtin:cube", "-o", "a.tcraft", "-o", "b.tcraft"]); + usage_error(&["render", "builtin:cube", "o.png", "--samples", "2", "--cpu", "--cpu"]); + usage_error(&["mcp", "--read-root", "a", "--automation-read-root", "b"]); +} + +#[test] +fn bad_values_conflicts_and_missing_arguments_are_refused_before_any_file_is_written() { + let dir = workdir("refused"); + let out = dir.join("never"); + let o = out.to_str().unwrap(); + let project_file = dir.join("p.tcraft"); + let p = project_file.to_str().unwrap(); + for (args, expect) in [ + (vec!["new", "builtin:cube", o, "--resolution", "0"], "--resolution"), + (vec!["new", "builtin:cube", o, "--resolution", "big"], "--resolution"), + (vec!["bake", "builtin:cube", "-o", o, "--resolution", "-1"], "-1"), + (vec!["bake", "builtin:cube"], "give -o"), + (vec!["bake", p], "--in-place"), + (vec!["bake", "builtin:cube", "--in-place"], "-o"), + (vec!["export", "builtin:cube", o, "--size", "0"], "--size"), + (vec!["export", "builtin:cube"], "required"), + (vec!["run", "builtin:cube", "layer.add.fill", "{not json"], "not JSON"), + (vec!["run", "builtin:cube", "layer.add.fill", "{}", "--in-place"], "--output"), + (vec!["render", "builtin:cube", o, "--size", "big"], "x"), + (vec!["render", "builtin:cube", o, "--size", "0x5"], "x"), + (vec!["render", "builtin:cube", o, "--view", "4d"], "--view"), + (vec!["render", "builtin:cube", o, "--yaw", "NaN"], "--yaw"), + (vec!["render", "builtin:cube", o, "--samples", "0"], "--samples"), + (vec!["render", "builtin:cube", o, "--cpu"], "--samples"), + (vec!["render", "builtin:cube", o, "--bounces", "3"], "--samples"), + (vec!["mcp", "--token", "abcdefghijklmnop"], "--bridge"), + (vec!["mcp", "--bridge", "9878", "--read-root", o], "headless server"), + (vec!["mcp", "--bridge", "99999"], "--bridge"), + (vec!["mcp", "--bridge", "0"], "--bridge"), + (vec!["serve", "--port", "http"], "--port"), + ] { + let message = usage_error(&args); + assert!(message.contains(expect), "{args:?}: {message}"); + } + assert!(!out.exists()); + assert!(std::fs::read_dir(&dir).unwrap().next().is_none()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn loopback_ports_take_the_host_prefix_and_a_dashed_name_follows_a_double_dash() { + // `--bridge 127.0.0.1:PORT` and `localhost:PORT` are still ports: the failure is the missing token. + for bridge in ["127.0.0.1:9", "localhost:9"] { + let got = invoke(["mcp", "--bridge", bridge, "--token", "short"]); + assert_eq!(got.code, 1, "{bridge}: {}", got.err); + } + let got = invoke(["info", "--", "-odd.tcraft"]); + assert_eq!(got.code, 1); + assert!(got.err.contains("-odd.tcraft"), "{}", got.err); + usage_error(&["render", "builtin:cube", "o.png", "--camera", "--cpu"]); +} + +#[test] +fn info_and_commands_print_what_a_program_reads() { + let got = invoke(["info", "builtin:cube"]); + assert_eq!((got.code, got.err.as_str()), (0, "")); + assert_eq!(serde_json::from_str::(&got.out).unwrap()["kind"], "mesh"); + let table = invoke(["commands", "--filter", "layer.add"]); + assert_eq!((table.code, table.err.as_str()), (0, "")); + assert!(table.out.lines().all(|l| l.starts_with("layer.add") || l.trim().is_empty()) && !table.out.is_empty(), "{}", table.out); + let json = invoke(["commands", "--filter", "layer.add", "--json"]); + assert_eq!(json.code, 0); + let list: serde_json::Value = serde_json::from_str(&json.out).unwrap(); + assert!(list.as_array().is_some_and(|l| !l.is_empty()), "{}", json.out); + let got = invoke(["info", "builtin:bogus"]); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.starts_with("error: unknown built-in mesh `bogus`"), "{}", got.err); +} + +#[test] +fn new_run_bake_and_export_through_files() { + let dir = workdir("files"); + let a = project(&dir, "a.tcraft"); + let b = dir.join("b.tcraft"); + let got = invoke(argv(&[&"run", &a, &"layer.add.fill", &r#"{"color":[1,0,0]}"#, &"-o", &b])); + assert_eq!(got.code, 0, "{}", got.err); + assert!(got.err.starts_with("saved "), "{}", got.err); + assert!(b.is_file()); + let got = invoke(argv(&[&"bake", &b, &"--resolution", &"128", &"--maps", &"ambientOcclusion", &"--in-place"])); + assert_eq!(got.code, 0, "{}", got.err); + let textures = dir.join("tex"); + let got = invoke(argv(&[&"export", &b, &textures, &"--preset", &"glTF PBR Metal Roughness", &"--size", &"128"])); + assert_eq!(got.code, 0, "{}", got.err); + assert!(got.out.lines().count() >= 3, "{}", got.out); + let got = invoke(argv(&[&"new", &"builtin:cube", &a])); + assert_eq!(got.code, 0, "{}", got.err); + let got = invoke(argv(&[&"new", &a, &dir.join("again.tcraft")])); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.contains("is already a project"), "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn an_output_that_would_replace_an_input_is_refused_without_in_place() { + let dir = workdir("replace"); + let source = project(&dir, "a.tcraft"); + let a = source.to_str().unwrap(); + let before = std::fs::read(&source).unwrap(); + let again = dir.join(".").join("a.tcraft"); + let again = again.to_str().unwrap(); + for args in [ + vec!["run", a, "layer.add.fill", "{}", "-o", a], + vec!["run", a, "layer.add.fill", "{}", "-o", again], + vec!["bake", a, "-o", a], + vec!["bake", a], + vec!["render", a, again], + vec!["new", a, a], + ] { + let message = usage_error(&args); + assert!(message.contains("--in-place") || message.contains("would replace"), "{args:?}: {message}"); + } + assert_eq!(std::fs::read(&source).unwrap(), before, "a refused command changes nothing"); + // `--in-place` lets only a project be replaced, and only by itself. + let got = invoke(["run", a, "layer.add.fill", "{}", "-o", a, "--in-place"]); + assert_eq!(got.code, 0, "{}", got.err); + let got = invoke(["bake", a, "--in-place", "--resolution", "128", "--maps", "ambientOcclusion"]); + assert_eq!(got.code, 0, "{}", got.err); + let elsewhere = dir.join("b.tcraft"); + assert!(usage_error(&["run", a, "layer.add.fill", "{}", "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place")); + assert!(usage_error(&["bake", a, "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place")); + assert!(!elsewhere.exists()); + // Headless::save appends .tcraft, so `-o scene` would replace scene.tcraft. + let unsuffixed = dir.join("a"); + let unsuffixed = unsuffixed.to_str().unwrap(); + let after_in_place = std::fs::read(&source).unwrap(); + let message = usage_error(&["run", a, "layer.add.fill", "{}", "-o", unsuffixed]); + assert!(message.contains("would replace") || message.contains("--in-place"), "{message}"); + assert_eq!(std::fs::read(&source).unwrap(), after_in_place, "an unsuffixed -o changes nothing"); + let got = invoke(["run", a, "layer.add.fill", "{}", "-o", unsuffixed, "--in-place"]); + assert_eq!(got.code, 0, "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn batch_runs_a_script_and_a_failing_step_fails_the_command() { + let dir = workdir("batch"); + let good = dir.join("good.json"); + std::fs::write(&good, r#"[{"id": "layer.add.paint", "params": {"name": "Scripted"}}]"#).unwrap(); + let got = invoke(argv(&[&"batch", &good])); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{}", got.out); + let bad = dir.join("bad.json"); + std::fs::write(&bad, r#"[{"id": "layer.add.paint"}, {"id": "no.such.command"}]"#).unwrap(); + let got = invoke(argv(&[&"batch", &bad])); + assert_eq!(got.code, 1); + assert!(got.err.starts_with("error: step 1 (`no.such.command`) failed: "), "{}", got.err); + for (body, expect) in [("[", "is not JSON"), ("{}", "list of steps"), (r#"{"steps": [], "open": false}"#, "`open` field must be a string")] { + let script = dir.join("odd.json"); + std::fs::write(&script, body).unwrap(); + let got = invoke(argv(&[&"batch", &script])); + assert_eq!(got.code, 1, "{body}"); + assert!(got.err.contains(expect), "{body}: {}", got.err); + } + let got = invoke(argv(&[&"batch", &dir.join("missing.json")])); + assert_eq!(got.code, 1); + assert!(got.err.contains("missing.json"), "{}", got.err); + // A script that saves over the project it opened needs --in-place, and must not have run. + let opened = project(&dir, "opened.tcraft"); + let before = std::fs::read(&opened).unwrap(); + let overwrite = dir.join("overwrite.json"); + std::fs::write( + &overwrite, + serde_json::json!({ + "open": opened, + "save": opened, + "steps": [{"id": "layer.add.paint", "params": {"name": "Batch"}}] + }) + .to_string(), + ) + .unwrap(); + let message = usage_error(&["batch", overwrite.to_str().unwrap()]); + assert!(message.contains("--in-place") || message.contains("would replace"), "{message}"); + assert_eq!(std::fs::read(&opened).unwrap(), before); + let got = invoke(argv(&[&"batch", &overwrite, &"--in-place"])); + assert_eq!(got.code, 0, "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_failed_command_exits_1_with_the_message_on_stderr() { + let got = invoke(["run", "builtin:cube", "no.such.command"]); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.starts_with("error: "), "{}", got.err); + let got = invoke(["info", "missing.tcraft"]); + assert_eq!(got.code, 1); + assert!(got.err.starts_with("error: ") && got.err.contains("missing.tcraft"), "{}", got.err); +} + +#[test] +fn the_desktop_launch_options_are_refused_before_any_subcommand() { + for args in + [vec!["--launch-profile", "nightly-v1", "--version"], vec!["--profile-root=/tmp/p", "--version"], vec!["info", "builtin:cube", "--launch-profile=x"]] + { + let message = usage_error(&args); + assert!(message.contains("desktop launch option"), "{args:?}: {message}"); + } +} + +#[cfg(unix)] +#[test] +fn a_path_that_is_not_valid_unicode_is_named_in_the_error() { + use std::os::unix::ffi::OsStringExt; + let dir = workdir("non-unicode"); + // The engine's commands take their paths as JSON text: the command says so and names the file. + let input = dir.join(OsString::from_vec(b"in-\xff.tcraft".to_vec())); + let got = invoke(argv(&[&"info", &input])); + assert_eq!(got.code, 1); + assert!(got.err.contains("the path is not valid Unicode") && got.err.contains("in-"), "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_closed_stdout_is_not_an_error() { + struct Closed; + impl std::io::Write for Closed { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut err = Vec::new(); + assert_eq!(texturecraft_cli::run(["commands"], &mut Closed, &mut err), 0); + assert_eq!(texturecraft_cli::run(["--help"], &mut Closed, &mut err), 0); + assert!(err.is_empty()); +} + +#[test] +fn headless_mcp_requires_both_roots() { + for args in [ + vec!["mcp"], + vec!["mcp", "--read-root", "."], + vec!["mcp", "--write-root", "."], + vec!["mcp", "--automation-read-root", "."], + vec!["mcp", "--automation-write-root", "."], + ] { + let message = usage_error(&args); + assert!(message.contains("--read-root") && message.contains("--write-root"), "{args:?}: {message}"); + } +} diff --git a/apps/texturecraft-cli/tests/it/main.rs b/apps/texturecraft-cli/tests/it/main.rs new file mode 100644 index 00000000..ea1db565 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/main.rs @@ -0,0 +1,48 @@ +//! 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, the environment). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod cli; +mod man_and_completions; +mod protocol; + +use std::ffi::{OsStr, OsString}; +use std::path::{Path, PathBuf}; + +/// What `run` returned and wrote. +pub struct Outcome { + pub code: i32, + pub out: String, + pub err: String, +} + +pub fn invoke(args: I) -> Outcome +where + I: IntoIterator, + T: Into, +{ + let (mut out, mut err) = (Vec::new(), Vec::new()); + let code = texturecraft_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!("texturecraft-cli-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A small project made by `new`. +pub fn project(dir: &Path, name: &str) -> PathBuf { + let path = dir.join(name); + let made = invoke(argv(&[&"new", &"builtin:cube", &path, &"--resolution", &"128"])); + assert_eq!(made.code, 0, "{}", made.err); + path +} + +/// An argument vector from parts of different types (strings, paths). +pub fn argv(parts: &[&dyn AsRef]) -> Vec { + parts.iter().map(|p| p.as_ref().to_os_string()).collect() +} diff --git a/apps/texturecraft-cli/tests/it/man_and_completions.rs b/apps/texturecraft-cli/tests/it/man_and_completions.rs new file mode 100644 index 00000000..47607b5a --- /dev/null +++ b/apps/texturecraft-cli/tests/it/man_and_completions.rs @@ -0,0 +1,55 @@ +//! 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() { + texturecraft_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 texturecraft_cli::command(), "texturecraft-cli", &mut out); + assert!(!out.is_empty(), "{shell}"); + } +} + +#[test] +fn man_pages_render_for_the_command_and_every_subcommand() { + let cmd = texturecraft_cli::command(); + for page in std::iter::once(&cmd).chain(cmd.get_subcommands()) { + let mut out = Vec::new(); + clap_mangen::Man::new(page.clone()).render(&mut out).unwrap(); + assert!(!out.is_empty(), "{}", page.get_name()); + } +} + +/// The example writes the five completion files under the names `packaging/linux/package.sh` and +/// `packaging/freebsd/package.sh` install, `texturecraft-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!("mc-cli-{}-man-and-completions", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + example::generate(&dir).unwrap(); + + let mut written: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect(); + written.sort(); + let completions = ["texturecraft-cli.bash", "_texturecraft-cli", "texturecraft-cli.fish", "texturecraft-cli.elv", "_texturecraft-cli.ps1"]; + let subcommands = ["info", "commands", "run", "batch", "bake", "export", "render", "new", "mcp", "serve"]; + let mut expected: Vec = completions.map(String::from).into(); + expected.push("texturecraft-cli.1".into()); + expected.extend(subcommands.iter().map(|s| format!("texturecraft-cli-{s}.1"))); + expected.sort(); + assert_eq!(written, expected); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/apps/texturecraft-cli/tests/it/protocol.rs b/apps/texturecraft-cli/tests/it/protocol.rs new file mode 100644 index 00000000..db504b54 --- /dev/null +++ b/apps/texturecraft-cli/tests/it/protocol.rs @@ -0,0 +1,118 @@ +//! The subcommands that talk over a stream (`mcp` and `serve` on stdio, through the real binary, +//! which owns stdin and stdout) and the environment variable of the control token. + +use std::io::Write; +use std::net::TcpListener; +use std::process::{Command, Output, Stdio}; + +fn binary() -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")); + command.env("TEXTURECRAFT_NO_PREFS", "1").env_remove("TEXTURECRAFT_CONTROL_TOKEN"); + command +} + +/// A port nothing listens on, with no token file. +fn free_port() -> String { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port().to_string() +} + +#[test] +fn serve_writes_nothing_but_json_lines_to_stdout() { + let mut child = binary().arg("serve").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + let mut stdin = child.stdin.take().unwrap(); + writeln!(stdin, r#"{{"id":1,"method":"ping","params":{{}}}}"#).unwrap(); + writeln!(stdin, "not json").unwrap(); + drop(stdin); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr)); + let lines: Vec<_> = String::from_utf8(output.stdout).unwrap().lines().map(str::to_string).collect(); + assert_eq!(lines.len(), 2, "{lines:?}"); + for line in &lines { + assert!(serde_json::from_str::(line).unwrap().get("ok").is_some(), "{line}"); + } +} + +#[test] +fn serve_ends_quietly_and_mcp_reports_it_when_stdin_is_closed() { + let output = binary().arg("serve").stdin(Stdio::null()).output().unwrap(); + assert_eq!((output.status.code(), output.stdout.is_empty(), output.stderr.is_empty()), (Some(0), true, true)); + // An MCP client must open with `initialize`; end of input before it is a failed start. + let dir = std::env::temp_dir().join(format!("tc-mcp-stdio-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let output = binary().args(["mcp", "--read-root", dir.to_str().unwrap(), "--write-root", dir.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!((output.status.code(), output.stdout.is_empty()), (Some(1), true)); + assert!(String::from_utf8_lossy(&output.stderr).starts_with("error: MCP start: "), "{}", String::from_utf8_lossy(&output.stderr)); +} + +fn bridge(token_flag: Option<&str>, env: Option<&str>) -> Output { + let port = free_port(); + let mut command = binary(); + command.args(["mcp", "--bridge", &port]); + if let Some(token) = token_flag { + command.args(["--token", token]); + } + if let Some(token) = env { + command.env("TEXTURECRAFT_CONTROL_TOKEN", token); + } + command.stdin(Stdio::null()).output().unwrap() +} + +#[test] +fn the_control_token_variable_is_a_fallback_the_flag_wins_and_an_empty_one_is_unset() { + let secret = "env-token-0123456789-secret"; + // Empty or blank counts as unset: the error says to set one, as when there is none. + for blank in ["", " "] { + let output = bridge(None, Some(blank)); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{err}"); + assert!(err.contains("no control token: set TEXTURECRAFT_CONTROL_TOKEN"), "{err}"); + } + // The variable is used when there is no flag: a good token gets as far as connecting. + let err = String::from_utf8_lossy(&bridge(None, Some(secret)).stderr).into_owned(); + assert!(!err.contains("16 to 1024") && !err.contains(secret), "{err}"); + // The flag wins over a good variable: its bad value is what is reported, without echoing either. + let err = String::from_utf8_lossy(&bridge(Some("short"), Some(secret)).stderr).into_owned(); + assert!(err.contains("control token must be 16 to 1024"), "{err}"); + assert!(!err.contains(secret) && !err.contains("short\n"), "{err}"); + // A bad value in the variable is refused too, and its value stays out of the message. + let err = String::from_utf8_lossy(&bridge(None, Some("bad token")).stderr).into_owned(); + assert!(err.contains("control token must be 16 to 1024") && !err.contains("bad token"), "{err}"); +} + +#[test] +fn help_lists_the_variable_but_never_its_value() { + let output = binary().args(["mcp", "--help"]).env("TEXTURECRAFT_CONTROL_TOKEN", "do-not-print-this-0123456789").output().unwrap(); + let help = String::from_utf8_lossy(&output.stdout); + assert!(help.contains("TEXTURECRAFT_CONTROL_TOKEN") && !help.contains("do-not-print-this"), "{help}"); +} + +#[test] +fn a_variable_alone_grants_no_file_access() { + // The token variable is for authentication only: a headless server with no roots still refuses files. + let mut child = + binary().arg("serve").env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + let mut stdin = child.stdin.take().unwrap(); + writeln!(stdin, r#"{{"id":1,"method":"project.save","params":{{"path":"never.tcraft"}}}}"#).unwrap(); + drop(stdin); + let output = child.wait_with_output().unwrap(); + let reply: serde_json::Value = serde_json::from_str(String::from_utf8(output.stdout).unwrap().lines().next().unwrap()).unwrap(); + assert_eq!(reply["ok"], false, "{reply}"); +} + +#[test] +fn a_token_in_the_environment_does_not_require_bridge() { + // Headless MCP must parse even when TEXTURECRAFT_CONTROL_TOKEN is set; only --token on the + // command line requires --bridge. + let output = binary().args(["mcp", "--fromat"]).env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").output().unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{err}"); + assert!(err.contains("--fromat"), "{err}"); + assert!(!err.contains("--bridge") && !err.contains("--token is for"), "{err}"); + + let output = binary().args(["mcp", "--token", "flag-token-0123456789"]).output().unwrap(); + let err = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{err}"); + assert!(err.contains("--token") && err.contains("--bridge"), "{err}"); +} diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 63c12b0e..6d4bca71 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -45,9 +45,16 @@ pub fn generate_token() -> Result { Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) } +/// `TEXTURECRAFT_CONTROL_TOKEN`; an empty (or blank) variable counts as unset, as for every other +/// variable of the command line (RFC-0018 rule 1.7). +fn env_token() -> Option { + std::env::var(TOKEN_ENV).ok().filter(|t| !t.trim().is_empty()) +} + /// Token for a client of `port`: explicit, else `TEXTURECRAFT_CONTROL_TOKEN`, else the token file. +/// A blank value counts as not given. pub fn client_token(port: u16, supplied: Option) -> Result { - let token = match supplied.or_else(|| std::env::var(TOKEN_ENV).ok()) { + let token = match supplied.filter(|t| !t.trim().is_empty()).or_else(env_token) { Some(t) => t, None => { let path = token_file(port); @@ -64,7 +71,7 @@ pub fn client_token(port: u16, supplied: Option) -> Result Result<(String, Option), AutomationError> { - if let Ok(t) = std::env::var(TOKEN_ENV) { + if let Some(t) = env_token() { validate_token(t.trim())?; return Ok((t.trim().to_string(), None)); } @@ -228,6 +235,25 @@ mod tests { assert!(client_token(1, Some(format!(" {a}\n"))).is_ok()); } + #[test] + fn a_blank_token_counts_as_not_given() { + // No token anywhere (the port has no token file): the error says what to set, not that a + // blank token is invalid. A non-blank inherited TOKEN_ENV can still satisfy the client + // after a blank supplied value, so do not unwrap_err() first. + match client_token(1, Some(" ".into())) { + Err(error) => { + if std::env::var_os(TOKEN_ENV).is_none() { + let message = error.to_string(); + assert!(message.contains("no control token"), "{message}"); + } + } + Ok(_) => { + let inherited = std::env::var(TOKEN_ENV).unwrap_or_default(); + assert!(!inherited.trim().is_empty(), "a blank token was accepted with no inherited value"); + } + } + } + fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("tc-token-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 27a60c1d..49070f1b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -426,7 +426,8 @@ A `prefs` object without `language` sets the system language (`""`), the default them: `--read-root ` for `project_open` / `mesh_import` / `mesh_reimport` / `bake_mesh_add`, `--write-root ` for `project_save` / `material_save` / `textures_export` / `mesh_export` (`--automation-read-root` / `--automation-write-root`, as in the other crafting apps, are the - same flags). Without roots there is no file access. `..`, absolute + same flags). Headless mcp refuses to start unless both roots are set; file access is only + below them. `..`, absolute paths, drive letters, device names and symlink or junction escapes are refused. - **Bridge**: `--bridge ` forwards to a running `texturecraft --control ` (token from `--token`, `TEXTURECRAFT_CONTROL_TOKEN` or the app's token file). The app reads and writes its @@ -818,15 +819,15 @@ set. ## CLI ```sh -texturecraft-cli --version # TextureCraft 0.1.0 (abc1234 2026-10-14) +texturecraft-cli --version # texturecraft-cli 0.1.0 (abc1234 2026-10-14) texturecraft-cli info model.glb # triangles, materials, UV report texturecraft-cli info project.tcraft # texture sets, layers, baked maps -texturecraft-cli commands --filter mask +texturecraft-cli commands --filter mask --json texturecraft-cli new builtin:material_ball ball.tcraft --resolution 1024 --sample # mesh maps baked at ≤ 1024 px texturecraft-cli new model.glb model.tcraft --resolution 2048 -texturecraft-cli run ball.tcraft layer.add.fill '{"color":"#c08040","metallic":1}' -o ball.tcraft +texturecraft-cli run ball.tcraft layer.add.fill '{"color":"#c08040","metallic":1}' -o ball.tcraft --in-place texturecraft-cli batch script.json -texturecraft-cli bake model.tcraft --resolution 2048 --maps ambientOcclusion,curvature,thickness +texturecraft-cli bake model.tcraft --resolution 2048 --maps ambientOcclusion,curvature,thickness --in-place texturecraft-cli export model.tcraft out/ --preset "Unreal Engine (Packed)" --format png --size 2048 texturecraft-cli render ball.tcraft ball.png --size 1280x800 --view 3d --yaw 30 --pitch 15 texturecraft-cli render scene.tcraft hero.png --size 1200x900 --camera Hero --samples 2048 # a saved camera (camera.add), path traced @@ -847,5 +848,24 @@ steps or an object with an optional input and output (paths relative to the curr } ``` -Errors print `texturecraft-cli : error: …` and exit 1; usage errors exit 2. The CLI is a -console program and never opens a window; `render` needs a GPU or software adapter. +The CLI is a console program and never opens a window; `render` needs a GPU or software adapter. + +`texturecraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md) +(command-line conventions); `texturecraft-cli --help` and ` --help` are the reference for every flag. +Exit status: 0 success, 1 a command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that +conflict or that the subcommand doesn't use, all checked before any file is touched), and 128 plus the signal number +when a signal ends the process. Errors are `error: ` on stderr. `--version`/`-V` work on every subcommand +(`texturecraft-cli 0.6.1 ( )`, with no `version` subcommand), and no arguments print the help on +stderr and exit 2. `info`, `run`, `batch` and `bake` print JSON because agents read it; `commands --json` prints the +list as JSON where it prints a table without it. + +- **Environment.** `TEXTURECRAFT_CONTROL_TOKEN` is the one variable the CLI reads for a flag (`mcp --bridge`'s + `--token`; `serve --port` reads it for its own token). The flag wins, an empty or blank variable counts as unset, + and `--help` never shows its value. No variable grants file access (roots come from `--read-root`/`--write-root`) + or replaces a file. The app's own `TEXTURECRAFT_NO_PREFS` is a setting of the app, not a flag fallback. +- **Replacing files.** `run -o` and `bake -o` onto the project they opened, and `bake` of a project without `-o`, + need `--in-place`; `render` and `new` never replace their input, and `bake` of a mesh needs `-o`. +- **Packages.** The Linux packages (deb, rpm, tar.gz) and the FreeBSD package install `texturecraft-cli`'s man pages + and its bash, zsh and fish completions. Nightly packages ship no CLI, so none; macOS and Windows are outside + RFC-0018's scope. +- **Not yet.** The ast-grep scan of RFC-0018 section 3 is not switched on. diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index 6927f0a4..39ff32fa 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -54,8 +54,14 @@ echo "==> TextureCraft $VERSION for FreeBSD $ARCH" # The release VM has 12 GB; full parallelism on the biggest crates runs it out of memory. export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" +# The man-and-completions example writes texturecraft-cli's man pages and shell completions below. +# It is built in its own cargo run: built with the binaries, its dev-dependencies' features would +# be unified into them. if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli) + # The example is run on this host to write man pages and completions, so it must be a host + # binary even when CARGO_BUILD_TARGET is set for a cross package. + (cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p texturecraft-cli --example man-and-completions) fi WORK="$CARGO_TARGET_DIR/freebsd-package" STAGE="$WORK/$BASENAME" @@ -73,6 +79,16 @@ if [[ "$DRY_RUN" = 1 ]]; then printf '#!/bin/sh\necho "%s %s (dry-run stub)"\n' "$b" "$VERSION" >"$BIN/$b" chmod 755 "$BIN/$b" done + # A stub of the example: it writes the files the real one does. + mkdir -p "$BIN/examples" + cat >"$BIN/examples/man-and-completions" <<'STUB' +#!/bin/sh +mkdir -p "$1" +for f in texturecraft-cli.bash _texturecraft-cli texturecraft-cli.fish texturecraft-cli.elv _texturecraft-cli.ps1 texturecraft-cli.1 texturecraft-cli-info.1; do + echo "dry-run stub" >"$1/$f" +done +STUB + chmod 755 "$BIN/examples/man-and-completions" fi # ---- stage a /usr/local-style tree -------------------------------------------------------------- @@ -88,10 +104,32 @@ sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$TEXTURECRAFT_BUILD_DATE/g" \ "$LINUX/$APP_ID.metainfo.xml.in" >"$STAGE/share/metainfo/$APP_ID.metainfo.xml" cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" copy_docs "$STAGE/share/doc/texturecraft" +# texturecraft-cli's man pages and shell completions, from its clap definition, written by the +# example built above (a --skip-build run needs it built too). Under /usr/local, man pages go in +# man/ and the completions in the directories bash, zsh and fish read there. +if [[ "$DRY_RUN" = 1 ]]; then + CLI_DOCS="$BIN/examples/man-and-completions" +else + # Host path: the example is built with CARGO_BUILD_TARGET unset, above. + CLI_DOCS="$CARGO_TARGET_DIR/release/examples/man-and-completions" +fi +if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is not built (env -u CARGO_BUILD_TARGET cargo build --release -p texturecraft-cli --example man-and-completions)" >&2 + exit 1 +fi +"$CLI_DOCS" "$WORK/cli-docs" +mkdir -p "$STAGE/man/man1" "$STAGE/share/bash-completion/completions" \ + "$STAGE/share/zsh/site-functions" "$STAGE/share/fish/vendor_completions.d" +install -m 644 "$WORK"/cli-docs/*.1 "$STAGE/man/man1/" +install -m 644 "$WORK/cli-docs/texturecraft-cli.bash" "$STAGE/share/bash-completion/completions/texturecraft-cli" +install -m 644 "$WORK/cli-docs/_texturecraft-cli" "$STAGE/share/zsh/site-functions/_texturecraft-cli" +install -m 644 "$WORK/cli-docs/texturecraft-cli.fish" "$STAGE/share/fish/vendor_completions.d/texturecraft-cli.fish" for f in bin/texturecraft bin/texturecraft-cli "share/applications/$APP_ID.desktop" \ "share/icons/hicolor/256x256/apps/$APP_ID.png" "share/icons/hicolor/scalable/apps/$APP_ID.svg" \ - share/doc/texturecraft/LICENSE-MIT share/doc/texturecraft/LICENSE-APACHE; do + share/doc/texturecraft/LICENSE-MIT share/doc/texturecraft/LICENSE-APACHE \ + man/man1/texturecraft-cli.1 share/bash-completion/completions/texturecraft-cli share/zsh/site-functions/_texturecraft-cli \ + share/fish/vendor_completions.d/texturecraft-cli.fish; do if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi done diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 1cea1c4b..bbabbf7e 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -81,6 +81,13 @@ contents: - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree + # Debian's zsh reads vendor-completions, not /usr/share/zsh/site-functions as Fedora's and + # openSUSE's do (its debian/rules sets --enable-additional-fpath). package.sh drops this entry + # from a Nightly build, which has no CLI. + - src: /usr/share/zsh/site-functions/_texturecraft-cli + dst: /usr/share/zsh/vendor-completions/_texturecraft-cli + type: symlink + packager: deb scripts: postinstall: packaging/linux/postinst.sh diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 8c2ca936..52358cf4 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -65,6 +65,14 @@ echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS, channel=${TEXTURECRAF if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"}) + # The man-and-completions example writes texturecraft-cli's man pages and shell completions + # below (Stable only: a Nightly ships no CLI). It is built in its own cargo run: built with the + # binaries, its dev-dependencies' features would be unified into them. It is run here, so a + # cross build builds it for the host. + if [[ "$IS_NIGHTLY" = 0 ]]; then + # Unset CARGO_BUILD_TARGET so a cross package still builds a host example (run below). + (cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p texturecraft-cli --example man-and-completions) + fi fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" WORK="$CARGO_TARGET_DIR/linux-package" @@ -80,6 +88,20 @@ install -Dm755 "$BIN/texturecraft" "$STAGE/usr/bin/texturecraft" if [[ "$IS_NIGHTLY" = 0 ]]; then install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true + # texturecraft-cli's man pages and shell completions (RFC-0018 rule 1.9), from its clap + # definition, written by the example built above (a --skip-build run needs it built too). zsh + # reads site-functions on Fedora and openSUSE; the deb also links the completion into Debian's + # vendor-completions (nfpm.yaml). + CLI_DOCS="$CARGO_TARGET_DIR/release/examples/man-and-completions" + if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is not built (env -u CARGO_BUILD_TARGET cargo build --release -p texturecraft-cli --example man-and-completions)" >&2 + exit 1 + fi + "$CLI_DOCS" "$WORK/cli-docs" + install -Dm644 -t "$STAGE/usr/share/man/man1" "$WORK"/cli-docs/*.1 + install -Dm644 "$WORK/cli-docs/texturecraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/texturecraft-cli" + install -Dm644 "$WORK/cli-docs/_texturecraft-cli" "$STAGE/usr/share/zsh/site-functions/_texturecraft-cli" + install -Dm644 "$WORK/cli-docs/texturecraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/texturecraft-cli.fish" fi install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" if [[ "$IS_NIGHTLY" = 1 ]]; then @@ -192,6 +214,9 @@ WRAPPER # A Nightly package has no CLI, so its file list must not name one either. # shellcheck disable=SC2016 [[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI='\|^ - src: \${STAGE}/usr/bin/\${NFPM_CLI}|,+2d;/Includes texturecraft-cli/d;' + # ... nor the zsh link into Debian's vendor-completions for the CLI's completion. + # shellcheck disable=SC2016 + [[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI="$DROP_CLI"'\|^ - src: /usr/share/zsh/site-functions/_texturecraft-cli|,+3d;' # shellcheck disable=SC2016 sed "${DROP_LIB_TREE}${DROP_CLI}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" # The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39.