fix(cli): enable clap env, and close replacement and token gaps

- Enable clap's `env` feature so TEXTURECRAFT_CONTROL_TOKEN compiles in a
  standalone `-p texturecraft-cli` release build (the FreeBSD package job).
- An inherited token no longer implies --bridge; only a command-line
  --token does.
- Compare run/bake/new outputs to the path Headless::save actually writes
  (it appends .tcraft when the extension is missing).
- Apply the same replacement rule to batch (save vs open), with --in-place.
- Build man-and-completions for the host when CARGO_BUILD_TARGET is set.
- Don't panic in the blank-token test when the environment already has a
  token.
This commit is contained in:
FredApps committed 2026-11-28 04:19:20 +07:00
1 parent 97834531e9
commit b993669b37
7 files changed
+135 -14

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ 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"] }
clap = { version = "4", features = ["derive", "string", "env"] }
clap_complete = "4"
clap_mangen = "0.2"
chrono = { version = "0.4", default-features = false, features = ["now", "wasmbind"] }
+66 -6
View File
@@ -111,6 +111,9 @@ fn json_value(s: &str) -> Result<Value, NotJson> {
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)]
@@ -214,7 +217,7 @@ pub(crate) struct McpArgs {
#[arg(long, value_name = "PORT", value_parser = port)]
pub(crate) bridge: Option<u16>,
/// 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, requires = "bridge")]
#[arg(long, value_name = "TOKEN", env = "TEXTURECRAFT_CONTROL_TOKEN", hide_env_values = true)]
pub(crate) token: Option<String>,
#[command(flatten)]
pub(crate) roots: RootArgs,
@@ -291,6 +294,8 @@ pub(crate) enum UsageError {
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,
}
impl UsageError {
@@ -314,28 +319,75 @@ 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::<Value>(&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("-o", "INPUT", out, &a.input, true).map_err(|e| ("run", e)),
(Some(out), true) if !same_file(out, &a.input) => Err(("run", UsageError::InPlaceNotUsed)),
(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("-o", "INPUT", out, &a.input, true).map_err(|e| ("bake", e)),
(Some(out), true) if !same_file(out, &a.input) => Err(("bake", UsageError::InPlaceNotUsed)),
(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("OUT.TCRAFT", "INPUT", &a.output, &a.input, false).map_err(|e| ("new", 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" })),
@@ -351,6 +403,14 @@ impl Command {
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
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::<u16>("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)
}
+28
View File
@@ -210,6 +210,15 @@ fn an_output_that_would_replace_an_input_is_refused_without_in_place() {
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();
}
@@ -235,6 +244,25 @@ fn batch_runs_a_script_and_a_failing_step_fails_the_command() {
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();
}
@@ -97,3 +97,19 @@ fn a_variable_alone_grants_no_file_access() {
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}");
}
+13 -4
View File
@@ -238,10 +238,19 @@ mod tests {
#[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.
let message = client_token(1, Some(" ".into())).map(drop).unwrap_err().to_string();
if std::env::var_os(TOKEN_ENV).is_none() {
assert!(message.contains("no control token"), "{message}");
// 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");
}
}
}
+9 -2
View File
@@ -59,7 +59,9 @@ export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}"
# be unified into them.
if [[ "$SKIP_BUILD" = 0 ]]; then
(cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli)
(cd "$ROOT" && cargo build --release --locked -p texturecraft-cli --example man-and-completions)
# 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"
@@ -105,7 +107,12 @@ 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.
CLI_DOCS="$BIN/examples/man-and-completions"
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 (cargo build --release -p texturecraft-cli --example man-and-completions)" >&2
exit 1
+2 -1
View File
@@ -70,7 +70,8 @@ if [[ "$SKIP_BUILD" = 0 ]]; then
# 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
(cd "$ROOT" && cargo build --release --locked -p texturecraft-cli --example man-and-completions)
# 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"