mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-27 21:39:26 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1b16b5e88 |
Generated
+152
-9
@@ -235,12 +235,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 = "anyhow"
|
||||
version = "1.0.104"
|
||||
@@ -272,7 +316,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -957,6 +1001,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.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
|
||||
|
||||
[[package]]
|
||||
name = "clap_mangen"
|
||||
version = "0.2.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e30ffc187e2e3aeafcd1c6e2aa416e29739454c0ccaa419226d5ecd181f2d78"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"roff",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.3"
|
||||
@@ -1040,6 +1143,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 = "colored"
|
||||
version = "2.2.0"
|
||||
@@ -2677,7 +2786,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3085,7 +3194,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]]
|
||||
@@ -4423,6 +4532,12 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[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"
|
||||
@@ -5547,6 +5662,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 = "open"
|
||||
version = "5.4.5"
|
||||
@@ -5614,7 +5735,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]]
|
||||
@@ -6169,7 +6290,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6515,6 +6636,12 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roff"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.2"
|
||||
@@ -6568,7 +6695,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6637,7 +6764,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7327,6 +7454,12 @@ dependencies = [
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "strum"
|
||||
version = "0.28.0"
|
||||
@@ -7507,7 +7640,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8060,6 +8193,12 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.27.0"
|
||||
@@ -8651,7 +8790,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]]
|
||||
@@ -9037,10 +9176,14 @@ dependencies = [
|
||||
name = "wordcraft-cli"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"clap_mangen",
|
||||
"craft-zip",
|
||||
"image",
|
||||
"serde_json",
|
||||
"sys-locale",
|
||||
"thiserror 2.0.21",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-engine",
|
||||
"wordcraft-fonts",
|
||||
|
||||
@@ -56,6 +56,10 @@ craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "0b8bb
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
thiserror = "2"
|
||||
# Command lines: clap derive types, with completions and man pages generated from them (RFC-0018).
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
clap_complete = "4"
|
||||
clap_mangen = "0.2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
quick-xml = "0.41"
|
||||
|
||||
@@ -157,7 +157,7 @@ Command line:
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert report.docx report.pdf # docx, pdf, odt, rtf, html, md, tex, txt, png
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 3, no file, if a character or picture would be left out
|
||||
wordcraft-cli convert report.docx report.pdf --strict # exit 1, no file, if a character or picture would be left out
|
||||
wordcraft-cli text report.docx # plain text
|
||||
wordcraft-cli inspect report.docx # structure as JSON
|
||||
wordcraft-cli run --template sample \
|
||||
@@ -165,16 +165,27 @@ wordcraft-cli run --template sample \
|
||||
wordcraft-cli run --script job.json # the same from a file: commands, then save to docx and pdf
|
||||
```
|
||||
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 3
|
||||
`wordcraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md)
|
||||
(command-line conventions); `wordcraft-cli --help` and `<subcommand> --help` are the reference for every flag. Exit status:
|
||||
0 success, 1 the command failed, 2 a usage error (an unknown or repeated flag, a bad value, flags that conflict or that a
|
||||
subcommand doesn't take, all checked before any file is opened), and 128 plus the signal number when a signal ends the
|
||||
process. Errors are `error: <message>` on stderr; results are on stdout. `--version`/`-V` work on every subcommand and there
|
||||
is no `version` subcommand. `WORDCRAFT_PASSWORD` is read by `--password` (a flag wins, an empty variable counts as unset,
|
||||
and `--help` never shows its value); `WORDCRAFT_REGION` sets the paper. The Linux packages (deb, rpm and tar.gz) and the
|
||||
FreeBSD package install the man pages and the bash, zsh and fish completions.
|
||||
|
||||
`convert --strict` (a `.pdf` or `.png` output only) and `render --strict` (a PNG of one page) refuse a silently incomplete render: they exit 1
|
||||
and write nothing if the output would draw a character no font has (an empty box) or leave out a
|
||||
picture. Exit codes are 0 (written), 1 (unreadable input, usage error, or `--strict` with another
|
||||
output type, checked before the input is read) and 3 (strict refusal). On exit 3, stderr has one
|
||||
`wordcraft-cli: strict: …` line per kind, then one JSON line:
|
||||
picture. Exit codes are 0 (written) and 1 (unreadable input or a strict refusal); `--strict` with another
|
||||
output type is a usage error (2), checked before the input is read. On a strict refusal, stderr has one
|
||||
`error: strict: …` line per kind, then one JSON line. (Before RFC-0018 a strict refusal exited 3; RFC-0018 has no code 3.)
|
||||
`validate` exits 0 for PASS and 1 for FAIL, INCOMPLETE or a file it can't read: the verdict is the first line of the report
|
||||
(`verdict` with `--json`).
|
||||
|
||||
```sh
|
||||
wordcraft-cli convert in.docx out.pdf --strict
|
||||
# wordcraft-cli: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# wordcraft-cli: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# error: strict: 1 character cannot be drawn: U+2D30 (×3)
|
||||
# error: strict: 1 picture(s) left out: word/media/image2.bin (header2.xml): unsupported format
|
||||
# {"schema":1,"strict":"failed","missing_glyphs":[{"cp":"U+2D30","count":3}],"missing_pictures":[{"part":"word/media/image2.bin","source_part":"word/header2.xml","reason":"unsupported_format"}],"truncated":false,"total_missing_glyphs":1,"total_missing_pictures":1,"glyphs_truncated":false,"pictures_truncated":false}
|
||||
```
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ license.workspace = true
|
||||
publish = false
|
||||
description = "WordCraft command line: convert, inspect, render, run commands, MCP server"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "wordcraft-cli"
|
||||
path = "src/main.rs"
|
||||
@@ -22,9 +25,14 @@ wordcraft-zotero = { workspace = true }
|
||||
wordcraft-validate = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
thiserror = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wordcraft-fonts = { workspace = true }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
image = { workspace = true }
|
||||
craft-zip = { workspace = true }
|
||||
# The completions and man pages (examples/man-and-completions.rs), generated from the clap definition.
|
||||
clap_complete = { workspace = true }
|
||||
clap_mangen = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Writes wordcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish,
|
||||
//! PowerShell) and man pages ([`clap_mangen`]: `wordcraft-cli.1` and one per subcommand, such as
|
||||
//! `wordcraft-cli-run.1`) into a directory. The Linux and FreeBSD packages ship them
|
||||
//! (see `packaging/`):
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p wordcraft-cli --example man-and-completions -- <out-dir>
|
||||
//! ```
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use clap_complete::Shell;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let (Some(dir), None) = (args.next(), args.next()) else {
|
||||
eprintln!("usage: man-and-completions <out-dir>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let dir = Path::new(&dir);
|
||||
match generate(dir) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", dir.display());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Also run by the tests.
|
||||
pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut cmd = wordcraft_cli::command();
|
||||
for &shell in Shell::value_variants() {
|
||||
clap_complete::generate_to(shell, &mut cmd, "wordcraft-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 (`wordcraft-cli-help-convert.1`).
|
||||
clap_mangen::generate_to(wordcraft_cli::command(), dir)
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! The command line as clap derive types (RFC-0018). Values arrive typed, so the commands never validate a string; what
|
||||
//! clap cannot say alone is a [`UsageError`], printed and exited like clap's own.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The end of every subcommand's `--help`.
|
||||
const EXIT_STATUS: &str = "Exit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// The top-level `--help` ends with the environment and the exit status.
|
||||
const TOP_NOTES: &str = "A password-protected Word file is opened with --password PASS, --password-file PATH or the WORDCRAFT_PASSWORD environment variable; a password given on the command line is readable by every other process, so the other two are better. A file opened with a password is written with it again, as the app does. Exports that cannot carry a password (pdf, html, txt) stay plain.\n\nPaper: documents created here, and HTML, Markdown and text files (which give no page size), use the system region's paper (A4, or Letter in the US and other Letter regions), read from LC_ALL / LC_PAPER / LANG or the platform. Set WORDCRAFT_REGION=en-US (or another tag) for the same output on every machine.\n\nEnvironment:\n WORDCRAFT_PASSWORD the password of a protected Word file, when neither --password nor --password-file is given\n WORDCRAFT_REGION the paper and region to use instead of the system's (a tag such as en-US)\n\nExit status:\n 0 success\n 1 the command failed (for `convert --strict` and `render --strict`, a refusal; for `validate`, a verdict other than PASS)\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.";
|
||||
|
||||
/// WordCraft from the command line: convert, inspect, render, run commands, validate, serve MCP
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "wordcraft-cli", version, propagate_version = true, arg_required_else_help = true, after_help = TOP_NOTES)]
|
||||
pub(crate) struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub(crate) command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub(crate) enum Command {
|
||||
/// Convert between formats (docx, doc [read], pdf, odt, rtf, html, md, tex, txt, json, png, xml)
|
||||
///
|
||||
/// `--update-fields` refreshes unlocked fields before saving (if protection blocks updates, they are skipped with a
|
||||
/// warning). An .xml file is a Word XML Document (Flat OPC), or with `--format wordml2003` a Word 2003 XML Document.
|
||||
/// `--markup` (Print Markup) puts comments beside each page and tracked changes in pdf/png, and a comment list in
|
||||
/// html/md/txt. `--strict` (pdf or png output only) writes nothing and exits 1 if a character can't be drawn or a
|
||||
/// picture is missing or undecodable; the report is on stderr, with one JSON line.
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Convert(ConvertArgs),
|
||||
/// Pages, words, paragraphs and properties (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Info(FileArgs),
|
||||
/// The plain text
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Text(FileArgs),
|
||||
/// The document structure (JSON)
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Inspect(FileArgs),
|
||||
/// Render one page to a PNG
|
||||
///
|
||||
/// `--strict` writes nothing and exits 1 if a character on the page can't be drawn or a picture is missing or
|
||||
/// undecodable (the report is on stderr, as for `convert --strict`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Render(RenderArgs),
|
||||
/// Run commands headlessly, then save
|
||||
///
|
||||
/// `--script` runs a JSON file (`-` is stdin) first: {"file"?, "template"?, "commands": [{"command": id, "params"?:
|
||||
/// {…}} | id, …], "save"?: [OUT, …]}; save formats follow the extension (docx and pdf in one run); relative paths
|
||||
/// resolve against the script's folder. `file.new` and `file.open` open another document and make it active; later
|
||||
/// commands and the saves work on the active one; `view.switchWindows` lists the open documents and with {"id": N}
|
||||
/// makes one active. PNG saves use `--page` (1-based, default 1) and `--scale` (default 2).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Run(RunArgs),
|
||||
/// List every command
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Commands(JsonArgs),
|
||||
/// Feature-catalog parity
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Parity(ParityArgs),
|
||||
/// Structural integrity check
|
||||
///
|
||||
/// Exit 0 for PASS; 1 for FAIL, INCOMPLETE or a file that can't be read (the verdict is the first line of the report,
|
||||
/// and `verdict` in `--json`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Validate(ValidateArgs),
|
||||
/// MCP server on stdio, with a headless session
|
||||
///
|
||||
/// Both roots are required: the agent's commands read files (open, insert text or picture, mail-merge data,
|
||||
/// templates…) only inside the read root and write them (save, export, merge output…) only inside the write root,
|
||||
/// links followed; the same folder may be both. `--connect` (bridge to the running app) is refused until the app
|
||||
/// confines its control channel (#3695, #5819).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Mcp(McpArgs),
|
||||
/// Run a Zotero command on a document (Zotero must be running)
|
||||
///
|
||||
/// The commands are addEditCitation, addEditBibliography, addNote, refresh, removeCodes and setDocPrefs; `--cmd`
|
||||
/// runs first (for example `--cmd caret.docEnd`).
|
||||
#[command(after_help = EXIT_STATUS)]
|
||||
Zotero(ZoteroArgs),
|
||||
}
|
||||
|
||||
/// How a password-protected Word file is opened.
|
||||
#[derive(Args, Debug, Default)]
|
||||
pub(crate) struct Password {
|
||||
/// The password (readable by every other process on the machine; prefer --password-file)
|
||||
#[arg(long, value_name = "PASS", env = "WORDCRAFT_PASSWORD", hide_env_values = true)]
|
||||
pub(crate) password: Option<String>,
|
||||
/// Read the password from this file (a trailing newline is dropped)
|
||||
#[arg(long = "password-file", value_name = "PATH")]
|
||||
pub(crate) password_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct FileArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
pub(crate) enum XmlFormat {
|
||||
/// A Word 2003 XML Document
|
||||
Wordml2003,
|
||||
/// A Word XML Document (Flat OPC), the default
|
||||
Flatopc,
|
||||
}
|
||||
|
||||
impl XmlFormat {
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
XmlFormat::Wordml2003 => "wordml2003",
|
||||
XmlFormat::Flatopc => "flatopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ConvertArgs {
|
||||
/// The document to read
|
||||
pub(crate) input: PathBuf,
|
||||
/// The file to write; its extension names the format
|
||||
pub(crate) output: PathBuf,
|
||||
/// Print Markup: comments beside each page and tracked changes
|
||||
#[arg(long)]
|
||||
pub(crate) markup: bool,
|
||||
/// Refresh unlocked fields before saving
|
||||
#[arg(long = "update-fields")]
|
||||
pub(crate) update_fields: bool,
|
||||
/// For pdf or png output: write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
/// The kind of .xml file to write
|
||||
#[arg(long, value_enum, value_name = "KIND")]
|
||||
pub(crate) format: Option<XmlFormat>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RenderArgs {
|
||||
/// The document
|
||||
pub(crate) input: PathBuf,
|
||||
/// The PNG to write
|
||||
pub(crate) output: PathBuf,
|
||||
/// The page, from 1
|
||||
#[arg(long, value_name = "N", value_parser = page, default_value = "1")]
|
||||
pub(crate) page: u64,
|
||||
/// Device pixels per point
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale, default_value = "2")]
|
||||
pub(crate) scale: f64,
|
||||
/// Write nothing and fail if a character can't be drawn or a picture is missing
|
||||
#[arg(long)]
|
||||
pub(crate) strict: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
/// One `--cmd ID[=JSON]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Cmd {
|
||||
pub(crate) id: String,
|
||||
pub(crate) params: Value,
|
||||
}
|
||||
|
||||
fn cmd(text: &str) -> Result<Cmd, UsageError> {
|
||||
match text.split_once('=') {
|
||||
Some((id, p)) => {
|
||||
let params = serde_json::from_str(p).map_err(|e| UsageError::CmdJson { id: id.to_owned(), why: e.to_string() })?;
|
||||
Ok(Cmd { id: id.to_owned(), params })
|
||||
}
|
||||
None => Ok(Cmd { id: text.to_owned(), params: json!({}) }),
|
||||
}
|
||||
}
|
||||
|
||||
fn page(text: &str) -> Result<u64, UsageError> {
|
||||
match text.parse::<u64>() {
|
||||
Ok(0) => Err(UsageError::Page("invalid --page `0`: page numbers start at 1".to_owned())),
|
||||
Ok(n) => Ok(n),
|
||||
Err(_) => Err(UsageError::Page(format!("invalid --page `{text}`: not a valid integer"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn scale(text: &str) -> Result<f64, UsageError> {
|
||||
let n = text.parse::<f64>().map_err(|_| UsageError::Scale(format!("invalid --scale `{text}`: not a number")))?;
|
||||
if n.is_finite() && n > 0.0 { Ok(n) } else { Err(UsageError::Scale(format!("invalid --scale `{text}`: scale must be a finite positive number"))) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct RunArgs {
|
||||
/// Open this document first
|
||||
#[arg(long, value_name = "F", conflicts_with = "template")]
|
||||
pub(crate) file: Option<PathBuf>,
|
||||
/// Start from this template
|
||||
#[arg(long, value_name = "T")]
|
||||
pub(crate) template: Option<String>,
|
||||
/// A script to run first (`-` is stdin)
|
||||
#[arg(long, value_name = "FILE")]
|
||||
pub(crate) script: Option<PathBuf>,
|
||||
/// Run one command, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the result here (the extension names the format)
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// The page of a PNG save, from 1 (default 1)
|
||||
#[arg(long, value_name = "N", value_parser = page)]
|
||||
pub(crate) page: Option<u64>,
|
||||
/// The scale of a PNG save (default 2)
|
||||
#[arg(long, value_name = "S", allow_negative_numbers = true, value_parser = scale)]
|
||||
pub(crate) scale: Option<f64>,
|
||||
/// Print each command's result
|
||||
#[arg(long)]
|
||||
pub(crate) print: bool,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
#[command(flatten)]
|
||||
pub(crate) open: Password,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct JsonArgs {
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ParityArgs {
|
||||
/// Markdown instead of JSON
|
||||
#[arg(long)]
|
||||
pub(crate) markdown: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ValidateArgs {
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// JSON alone on stdout
|
||||
#[arg(long)]
|
||||
pub(crate) json: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// The folder the agent may read in (links followed); the same folder may be the write root
|
||||
#[arg(long = "automation-read-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) read_root: Option<PathBuf>,
|
||||
/// The folder the agent may write in (links followed)
|
||||
#[arg(long = "automation-write-root", value_name = "DIR", required_unless_present = "connect", value_parser = folder)]
|
||||
pub(crate) write_root: Option<PathBuf>,
|
||||
/// Who tracked changes and comments are by
|
||||
#[arg(long, value_name = "NAME")]
|
||||
pub(crate) author: Option<String>,
|
||||
/// Refused for now: the desktop app does not confine its control channel to automation roots yet
|
||||
#[arg(long, value_name = "HOST:PORT")]
|
||||
pub(crate) connect: Option<String>,
|
||||
}
|
||||
|
||||
fn folder(text: &str) -> Result<PathBuf, UsageError> {
|
||||
if text.is_empty() { Err(UsageError::EmptyFolder) } else { Ok(PathBuf::from(text)) }
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub(crate) struct ZoteroArgs {
|
||||
/// The Zotero command (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)
|
||||
#[arg(value_parser = zotero_command)]
|
||||
pub(crate) command: String,
|
||||
/// The document
|
||||
pub(crate) file: PathBuf,
|
||||
/// Run one command first, `ID` or `ID={json}`; repeatable
|
||||
#[arg(long = "cmd", value_name = "ID={JSON}", value_parser = cmd)]
|
||||
pub(crate) cmds: Vec<Cmd>,
|
||||
/// Save the document here afterwards
|
||||
#[arg(long, value_name = "OUT")]
|
||||
pub(crate) save: Option<PathBuf>,
|
||||
/// Show the calls to and from Zotero on stderr
|
||||
#[arg(long)]
|
||||
pub(crate) trace: bool,
|
||||
/// Zotero's port
|
||||
#[arg(long, value_name = "P")]
|
||||
pub(crate) port: Option<u16>,
|
||||
}
|
||||
|
||||
fn zotero_command(text: &str) -> Result<String, UsageError> {
|
||||
if wordcraft_zotero::Command::from_name(text).is_some() { Ok(text.to_owned()) } else { Err(UsageError::Zotero(text.to_owned())) }
|
||||
}
|
||||
|
||||
/// A mistake in the command line that clap can't see by itself.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub(crate) enum UsageError {
|
||||
#[error("{0}")]
|
||||
Page(String),
|
||||
#[error("{0}")]
|
||||
Scale(String),
|
||||
#[error("--cmd {id}: bad JSON params: {why}")]
|
||||
CmdJson { id: String, why: String },
|
||||
#[error("a folder is needed, not an empty name")]
|
||||
EmptyFolder,
|
||||
#[error("unknown Zotero command `{0}` (addEditCitation, addEditBibliography, addNote, refresh, removeCodes or setDocPrefs)")]
|
||||
Zotero(String),
|
||||
}
|
||||
|
||||
/// The clap definition of the whole command line (completions and man pages are generated from it).
|
||||
pub fn command() -> clap::Command {
|
||||
Cli::command()
|
||||
}
|
||||
|
||||
/// Parse the arguments (without the program name). Help and the version come back as the `Err` clap uses for them.
|
||||
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
let matches = Cli::command().try_get_matches_from(std::iter::once(OsString::from("wordcraft-cli")).chain(args.iter().cloned()))?;
|
||||
let mut cli = Cli::from_arg_matches(&matches)?;
|
||||
if let Some((name, sub)) = matches.subcommand() {
|
||||
password_precedence(&mut cli.command, sub, name);
|
||||
}
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
/// `--password`, `--password-file`, then `WORDCRAFT_PASSWORD`: a password file named on the command line beats the
|
||||
/// variable, which clap would otherwise read into `--password`.
|
||||
fn password_precedence(command: &mut Command, sub: &ArgMatches, _name: &str) {
|
||||
let open = match command {
|
||||
Command::Convert(a) => &mut a.open,
|
||||
Command::Info(a) | Command::Text(a) | Command::Inspect(a) => &mut a.open,
|
||||
Command::Render(a) => &mut a.open,
|
||||
Command::Run(a) => &mut a.open,
|
||||
_ => return,
|
||||
};
|
||||
let from_env = sub.value_source("password") == Some(clap::parser::ValueSource::EnvVariable);
|
||||
if from_env && open.password_file.is_some() {
|
||||
open.password = None;
|
||||
}
|
||||
// A blank variable counts as unset.
|
||||
if from_env && open.password.as_deref() == Some("") {
|
||||
open.password = None;
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
//! Parse `--automation-read-root` / `--automation-write-root` before the server starts. A malformed
|
||||
//! flag must not silently remove a root and leave the server unconfined.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct AutomationArgs {
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
read_given: bool,
|
||||
write_given: bool,
|
||||
}
|
||||
|
||||
impl AutomationArgs {
|
||||
pub fn new(read_root: Option<PathBuf>, write_root: Option<PathBuf>) -> Self {
|
||||
Self { read_root, write_root, read_given: false, write_given: false }
|
||||
}
|
||||
|
||||
/// Returns whether this argument is a root flag. A second occurrence of a flag is an error,
|
||||
/// including when the two spellings (`--flag DIR`, `--flag=DIR`) are mixed.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value)));
|
||||
let (root, given) = match flag {
|
||||
"--automation-read-root" => (&mut self.read_root, &mut self.read_given),
|
||||
"--automation-write-root" => (&mut self.write_root, &mut self.write_given),
|
||||
_ => return Ok(false),
|
||||
};
|
||||
if *given {
|
||||
return Err(format!("{flag} given twice"));
|
||||
}
|
||||
let value = match inline {
|
||||
Some(value) => value.to_owned(),
|
||||
None => {
|
||||
let value = args.next().ok_or_else(|| format!("{flag} needs a folder"))?;
|
||||
if value.starts_with('-') {
|
||||
return Err(format!("{flag} needs a folder; use {flag}=<dir> for a folder starting with '-'"));
|
||||
}
|
||||
value
|
||||
}
|
||||
};
|
||||
if value.is_empty() {
|
||||
return Err(format!("{flag} needs a non-empty folder"));
|
||||
}
|
||||
*root = Some(value.into());
|
||||
*given = true;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roots_are_taken_once_and_other_arguments_are_left() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
let mut args = ["a folder".to_owned(), "report.docx".to_owned()].into_iter();
|
||||
assert!(roots.consume("--automation-read-root", &mut args).unwrap());
|
||||
assert!(roots.consume("--automation-write-root=out", &mut args).unwrap());
|
||||
assert!(!roots.consume("--author", &mut args).unwrap());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
assert_eq!(roots.write_root, Some("out".into()));
|
||||
assert_eq!(args.next().as_deref(), Some("report.docx"));
|
||||
assert!(roots.consume("--automation-read-root=other", &mut args).is_err());
|
||||
assert_eq!(roots.read_root, Some("a folder".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_operands_leave_roots_unchanged() {
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
for operand in [None, Some(""), Some("--version"), Some("--connect"), Some("-folder")] {
|
||||
let mut roots = AutomationArgs::new(Some("read".into()), Some("write".into()));
|
||||
let mut args = operand.map(str::to_owned).into_iter();
|
||||
assert!(roots.consume(flag, &mut args).is_err(), "{flag} {operand:?}");
|
||||
assert_eq!(roots.read_root, Some("read".into()));
|
||||
assert_eq!(roots.write_root, Some("write".into()));
|
||||
}
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume(&format!("{flag}="), &mut std::iter::empty()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_dash_folder_and_relative_dash_folder_are_valid() {
|
||||
let mut roots = AutomationArgs::new(None, None);
|
||||
assert!(roots.consume("--automation-read-root=-folder", &mut std::iter::empty()).unwrap());
|
||||
assert!(roots.consume("--automation-write-root", &mut ["./-folder".to_owned()].into_iter()).unwrap());
|
||||
assert_eq!(roots.read_root, Some("-folder".into()));
|
||||
assert_eq!(roots.write_root, Some("./-folder".into()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! The subcommands: each takes its parsed arguments and the output streams, and returns the exit status.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::{CmdError, Session};
|
||||
|
||||
use crate::args::{self, Command, ConvertArgs, FileArgs, JsonArgs, McpArgs, ParityArgs, Password, RenderArgs, RunArgs, ValidateArgs, ZoteroArgs};
|
||||
use crate::error::CliError;
|
||||
use crate::script;
|
||||
use crate::{Io, errln};
|
||||
|
||||
type Result<T> = std::result::Result<T, CliError>;
|
||||
|
||||
fn engine_error(e: impl std::fmt::Display) -> CliError {
|
||||
CliError::Failed(escape_text(&e.to_string(), false))
|
||||
}
|
||||
|
||||
/// Open a document for a subcommand. A password-protected Word file needs its password
|
||||
/// ([`password_from`]). As in the app, a document opened with one is saved with it again, so
|
||||
/// `convert` does not quietly write a copy the password no longer protects.
|
||||
fn open(path: &Path, password: Option<&str>) -> Result<Session> {
|
||||
// A file that gives no page size (HTML, Markdown, plain text) opens on the system region's
|
||||
// paper, as in the app: A4 in Italy, Letter in the US (#1381).
|
||||
let region = system_region();
|
||||
let (doc, encrypted) = wordcraft_engine::io::open_path_in(path, password, ®ion).map_err(engine_error)?;
|
||||
let mut s = session(doc);
|
||||
s.path = Some(path.into());
|
||||
if encrypted {
|
||||
s.password = password.map(wordcraft_engine::io::Password::new);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The password for a protected Word file: `--password`, `--password-file` or `WORDCRAFT_PASSWORD` (clap reads the
|
||||
/// variable into `--password`; a blank one counts as unset). The file form exists because a password on a command line
|
||||
/// is readable by every other process on the machine; a trailing newline is dropped so a file written by `echo` works.
|
||||
/// Never logged, and never named in an error.
|
||||
pub(crate) fn password_from(open: &Password) -> Result<Option<String>> {
|
||||
if let Some(password) = &open.password {
|
||||
return Ok(Some(password.clone()));
|
||||
}
|
||||
if let Some(path) = &open.password_file {
|
||||
let raw =
|
||||
std::fs::read_to_string(path).map_err(|e| CliError::Failed(escape_text(&format!("--password-file {}: {e}", path.display()), false)))?;
|
||||
return Ok(Some(raw.trim_end_matches(['\r', '\n']).to_string()));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// A path the engine takes as text: output paths must be valid Unicode (only the opened file may not be, #1440).
|
||||
fn unicode(path: &Path) -> Result<&str> {
|
||||
path.to_str().ok_or_else(|| CliError::Failed(format!("{}: the file name is not valid Unicode", path.display().to_string().escape_debug())))
|
||||
}
|
||||
|
||||
/// A headless session in the system region: every way the CLI starts one gives `file.new` the
|
||||
/// same paper (#1381).
|
||||
fn session(doc: wordcraft_doc::Document) -> Session {
|
||||
let mut s = Session::new(doc);
|
||||
s.system_region = system_region();
|
||||
s
|
||||
}
|
||||
|
||||
/// The system region, read as the app reads it (locale variables, else the platform's locale).
|
||||
fn system_region() -> wordcraft_engine::Region {
|
||||
wordcraft_engine::Region::from_locale_vars(|name| std::env::var(name).ok(), sys_locale::get_locale)
|
||||
}
|
||||
|
||||
/// The body text for `text`: the plain-text export, so list items keep their bullet or number label.
|
||||
fn listed_text(doc: &wordcraft_doc::Document) -> std::result::Result<String, String> {
|
||||
let bytes = wordcraft_engine::io::save_bytes("out.txt", doc)?;
|
||||
Ok(String::from_utf8_lossy(&bytes).replace("\r\n", "\n"))
|
||||
}
|
||||
|
||||
/// `--author NAME`: the author recorded on tracked changes and comments (`file.setAuthor`).
|
||||
/// The command also checks whether the open document is protected: this name determines which
|
||||
/// named editing exceptions the session can use, so the flag must not bypass that check.
|
||||
fn set_author(s: &mut Session, name: &str) -> std::result::Result<(), String> {
|
||||
s.run("file.setAuthor", &json!({"name": name})).map(|_| ()).map_err(|e| escape_text(&format!("--author: {e}"), false))
|
||||
}
|
||||
|
||||
/// `mcp`'s headless backend: a session confined to `roots`, its author `author` when given. The caller confines the
|
||||
/// process to the same roots first (`confine_process`), which a test must not do.
|
||||
fn headless_mcp(
|
||||
roots: std::sync::Arc<wordcraft_engine::file_access::AutomationRoots>,
|
||||
author: Option<&str>,
|
||||
) -> std::result::Result<wordcraft_mcp::Headless, String> {
|
||||
let mut headless = wordcraft_mcp::Headless::default().with_automation_roots(Some(roots));
|
||||
if let Some(name) = author {
|
||||
set_author(&mut headless.session, name)?;
|
||||
}
|
||||
Ok(headless)
|
||||
}
|
||||
|
||||
/// A failed `--strict` export: a strict refusal becomes [`CliError::Strict`] carrying what stderr
|
||||
/// shows (each line of the report as `error: …`, then its JSON on one line, from
|
||||
/// `file.strictReport` for `page` of a page image, else the PDF); any other error is an ordinary
|
||||
/// failure.
|
||||
fn refusal(s: &mut Session, e: wordcraft_engine::CmdError, markup: bool, page: Option<u64>) -> CliError {
|
||||
if !matches!(&e, wordcraft_engine::CmdError::Failed(m) if m.starts_with("strict: ")) {
|
||||
return engine_error(e);
|
||||
}
|
||||
let mut params = json!({"markup": markup});
|
||||
if let Some(page) = page {
|
||||
params["page"] = json!(page);
|
||||
}
|
||||
CliError::Strict(match s.run("file.strictReport", ¶ms).map_err(|e| e.to_string()) {
|
||||
Ok(json) => {
|
||||
let mut text = String::new();
|
||||
for line in report_lines(&json) {
|
||||
text += &format!("error: {}\n", escape_peer(&line));
|
||||
}
|
||||
text + &json_line_safe(&json.to_string())
|
||||
}
|
||||
Err(e) => format!("error: strict: refused, and the report could not be made: {}", escape_text(&e, false)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The report's human lines, from its JSON (the engine's `StrictReport::lines`).
|
||||
fn report_lines(json: &Value) -> Vec<String> {
|
||||
wordcraft_engine::strict::lines_from_json(json)
|
||||
}
|
||||
|
||||
/// Explicitly update unlocked fields in a session before saving the document.
|
||||
///
|
||||
/// If field updates are disabled by document protection (`CmdError::Disabled`), logs a warning to
|
||||
/// stderr and continues conversion rather than aborting. Other command failures are converted to
|
||||
/// [`CliError`] via [`engine_error`].
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `s` - The active document [`Session`] whose unlocked fields should be refreshed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Err(CliError)` if the command fails with an error other than `CmdError::Disabled`.
|
||||
fn update_fields(s: &mut Session, io: &mut Io) -> Result<()> {
|
||||
if let Err(e) = s.run("references.updateFields", &json!({})) {
|
||||
if matches!(e, CmdError::Disabled(_)) {
|
||||
errln!(io, "warning: {e}");
|
||||
} else {
|
||||
return Err(engine_error(e));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// At most 400 characters of `s`, for traces.
|
||||
fn clip(s: &str) -> String {
|
||||
match s.char_indices().nth(400) {
|
||||
Some((i, _)) => format!("{}…", s.get(..i).unwrap_or(s)),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from another program (Zotero, or whatever answered on its port) for one diagnostic
|
||||
/// line: backslashes, control characters (newline, escape, C1…), line separators and bidi
|
||||
/// overrides are shown as escapes (`\\`, `\n`, `\u{1b}`), so it can't end its line, drive the
|
||||
/// terminal or pass for other output.
|
||||
fn escape_peer(s: &str) -> String {
|
||||
escape_text(s, true)
|
||||
}
|
||||
|
||||
/// Whether `c` must not reach a terminal as itself: a control character, a line or paragraph
|
||||
/// separator, a bidi control, or one that shows nothing (soft hyphen, zero-width characters, word
|
||||
/// joiners, the byte order mark, tag characters), which can hide or reorder what a line says.
|
||||
fn is_unsafe_char(c: char) -> bool {
|
||||
c.is_control()
|
||||
|| matches!(
|
||||
c,
|
||||
'\u{00ad}'
|
||||
| '\u{061c}'
|
||||
| '\u{200b}'..='\u{200f}'
|
||||
| '\u{2028}'..='\u{202e}'
|
||||
| '\u{2060}'..='\u{2064}'
|
||||
| '\u{2066}'..='\u{2069}'
|
||||
| '\u{feff}'
|
||||
| '\u{e0000}'..='\u{e007f}'
|
||||
)
|
||||
}
|
||||
|
||||
/// [`escape_peer`], with backslashes escaped only when `backslash` (error messages quote Windows
|
||||
/// paths, and a backslash can't forge or hide anything).
|
||||
fn escape_text(s: &str, backslash: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' if backslash => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if is_unsafe_char(c) => out.extend(c.escape_unicode()),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON line safe to print: serde escapes control characters below U+0020 but not the other
|
||||
/// characters [`is_unsafe_char`] names, which a crafted file could put in a report. They become
|
||||
/// `\uXXXX` escapes (a surrogate pair above U+FFFF), so the line parses to the same value and
|
||||
/// can't drive or spoof a terminal.
|
||||
fn json_line_safe(json: &str) -> String {
|
||||
let mut out = String::with_capacity(json.len());
|
||||
for c in json.chars() {
|
||||
if is_unsafe_char(c) {
|
||||
for unit in c.encode_utf16(&mut [0u16; 2]) {
|
||||
out.push_str(&format!("\\u{unit:04x}"));
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parity_markdown(p: &Value) -> String {
|
||||
let mut s = String::from(
|
||||
"# WordCraft feature parity\n\nGenerated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry.\n\n",
|
||||
);
|
||||
s += &format!(
|
||||
"**{} of {} catalog features have commands ({}%).**\n\n| Tab | Live | Total |\n|---|---|---|\n",
|
||||
p["live"], p["total"], p["percent"]
|
||||
);
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
|
||||
}
|
||||
s += "\n## Missing\n\n";
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
let m = t["missing"].as_array().cloned().unwrap_or_default();
|
||||
if m.is_empty() {
|
||||
continue;
|
||||
}
|
||||
s += &format!("### {}\n\n", t["tab"].as_str().unwrap_or(""));
|
||||
for x in m {
|
||||
s += &format!("- {}\n", x.as_str().unwrap_or(""));
|
||||
}
|
||||
s += "\n";
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Write a `validate` report for people: the verdict, then one line per finding
|
||||
/// (`SEVERITY RULE [part] message`), then the coverage notes.
|
||||
fn write_validate_report(o: &mut dyn Write, report: &wordcraft_validate::Report) -> std::io::Result<()> {
|
||||
o.write_all(render_validate_report(report).as_bytes())
|
||||
}
|
||||
|
||||
/// Render a `validate` report for people. Document-controlled text — a ZIP entry name flowing into
|
||||
/// a finding part or coverage note — is escaped so a name cannot end its line or drive the
|
||||
/// terminal; printable text, including Unicode, is left as written.
|
||||
///
|
||||
/// The `--json` form is not escaped by hand; it is the validator's own `serde_json` serialization.
|
||||
/// `serde_json` escapes `U+0000`–`U+001F`, `"` and `\`; C1 controls such as `U+009B` and the bidi
|
||||
/// embeddings/overrides (`U+202A`–`U+202E`, `U+2066`–`U+2069`) are emitted raw. So a control or bidi
|
||||
/// run carried by a ZIP entry name survives into the JSON text; JSON is only safe because a
|
||||
/// *parser* takes the string value as data. If that text is printed directly to a terminal, the raw
|
||||
/// C1/bidi run reaches the terminal exactly as it would from any other text, so the JSON form is
|
||||
/// not a terminal-safe rendering. Only the human report below escapes those characters, and it does
|
||||
/// so to defend the terminal; keeping the JSON byte-for-byte the validator's own serialization is
|
||||
/// why its escaping is left to `serde_json`.
|
||||
fn render_validate_report(report: &wordcraft_validate::Report) -> String {
|
||||
let mut out = format!("{}\n", verdict_label(report.verdict));
|
||||
for f in &report.findings {
|
||||
let severity = severity_label(f.severity);
|
||||
match &f.part {
|
||||
Some(part) => out.push_str(&format!("{severity} {} [{}] {}\n", f.rule, escape_report_text(part), escape_report_text(&f.message))),
|
||||
None => out.push_str(&format!("{severity} {} {}\n", f.rule, escape_report_text(&f.message))),
|
||||
}
|
||||
}
|
||||
for note in &report.coverage_notes {
|
||||
out.push_str(&format!("note: {}\n", escape_report_text(note)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Escape the control and invisible-formatting characters that could spoof a report line, in the
|
||||
/// same escape *form* `escape_debug` uses (`\u{1b}`, `\n`); printable characters (including Unicode)
|
||||
/// are left untouched. The *selection* is a hand-picked set ([`is_invisible_format`] plus
|
||||
/// `char::is_control`), not `escape_debug`'s full non-printable set: it omits, for example, the
|
||||
/// U+E0000 tag block, U+FFF9–U+FFFB and the Hangul fillers. None of those can end a line or drive a
|
||||
/// terminal, which is the threat this guards against. Backslash is not escaped, so a name that
|
||||
/// literally contains the text `\u{1b}` prints exactly like an escaped ESC and the output is not
|
||||
/// injective.
|
||||
fn escape_report_text(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
if c.is_control() || is_invisible_format(c) {
|
||||
out.extend(c.escape_debug());
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Invisible Unicode formatting characters and line/paragraph separators: no glyph, but they can
|
||||
/// alter how a terminal renders the rest of the line (`char::is_control` covers C0/C1 controls).
|
||||
fn is_invisible_format(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{00ad}' | '\u{061c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}'
|
||||
)
|
||||
}
|
||||
|
||||
/// Map a validation verdict enum to its human-readable uppercase display label.
|
||||
fn verdict_label(v: wordcraft_validate::Verdict) -> &'static str {
|
||||
match v {
|
||||
wordcraft_validate::Verdict::Pass => "PASS",
|
||||
wordcraft_validate::Verdict::Fail => "FAIL",
|
||||
wordcraft_validate::Verdict::Incomplete => "INCOMPLETE",
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a validation severity enum to its human-readable uppercase display label.
|
||||
fn severity_label(s: wordcraft_validate::Severity) -> &'static str {
|
||||
match s {
|
||||
wordcraft_validate::Severity::Corrupt => "CORRUPT",
|
||||
wordcraft_validate::Severity::Error => "ERROR",
|
||||
wordcraft_validate::Severity::Warning => "WARNING",
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `mcp --connect` is refused: the running app would not confine the agent's file access.
|
||||
// lean: refused outright; allow it once the app confines its control channel and reports both roots.
|
||||
const MCP_CONNECT_REFUSED: &str = "mcp: --connect is refused for now: the desktop app does not confine its control \
|
||||
channel to automation roots yet (storytold/wordcraft#3695, #5819). Use the headless server: wordcraft-cli mcp \
|
||||
--automation-read-root DIR --automation-write-root DIR";
|
||||
|
||||
/// Run one parsed subcommand; the result is the exit status.
|
||||
pub(crate) fn dispatch(command: Command, io: &mut Io) -> Result<u8> {
|
||||
match command {
|
||||
Command::Convert(a) => convert(a, io).map(|()| 0),
|
||||
Command::Info(a) => info(a, io).map(|()| 0),
|
||||
Command::Text(a) => text(a, io).map(|()| 0),
|
||||
Command::Inspect(a) => inspect(a, io).map(|()| 0),
|
||||
Command::Render(a) => render(a, io).map(|()| 0),
|
||||
Command::Run(a) => run_script(a, io).map(|()| 0),
|
||||
Command::Commands(a) => commands(a, io).map(|()| 0),
|
||||
Command::Parity(a) => parity(a, io).map(|()| 0),
|
||||
Command::Validate(a) => validate(a, io),
|
||||
Command::Mcp(a) => mcp(a, io).map(|()| 0),
|
||||
Command::Zotero(a) => zotero(a, io).map(|()| 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write to stdout and flush. A closed stdout comes back as [`CliError::StdoutClosed`] instead of a panic.
|
||||
fn write_stdout(io: &mut Io, write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>) -> Result<()> {
|
||||
write(&mut *io.out)?;
|
||||
io.out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn convert(a: ConvertArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
// Before the input is opened: a wrong output type is a usage error, not a file error.
|
||||
let to_png = o.to_ascii_lowercase().ends_with(".png");
|
||||
if a.strict && !(to_png || o.to_ascii_lowercase().ends_with(".pdf")) {
|
||||
return Err(CliError::Usage("convert: --strict needs a .pdf or .png output".into()));
|
||||
}
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
if a.update_fields {
|
||||
update_fields(&mut s, io)?;
|
||||
}
|
||||
let r = if to_png {
|
||||
s.run("file.exportPng", &json!({"path": o, "page": 1, "markup": a.markup, "strict": a.strict}))
|
||||
} else {
|
||||
let mut params = json!({"path": o, "markup": a.markup, "strict": a.strict});
|
||||
if let Some(f) = a.format {
|
||||
params["format"] = json!(f.name());
|
||||
}
|
||||
s.run("file.save", ¶ms)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
return Err(if a.strict { refusal(&mut s, e, a.markup, to_png.then_some(1)) } else { engine_error(e) });
|
||||
}
|
||||
errln!(io, "wrote {o}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_file(a: &FileArgs) -> Result<Session> {
|
||||
let password = password_from(&a.open)?;
|
||||
open(&a.file, password.as_deref())
|
||||
}
|
||||
|
||||
fn info(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let info = serde_json::to_string_pretty(&s.run("file.info", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{info}"))
|
||||
}
|
||||
|
||||
fn text(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let s = open_file(&a)?;
|
||||
let text = listed_text(&s.doc)?;
|
||||
write_stdout(io, |o| writeln!(o, "{text}"))
|
||||
}
|
||||
|
||||
fn inspect(a: FileArgs, io: &mut Io) -> Result<()> {
|
||||
let mut s = open_file(&a)?;
|
||||
let tree = serde_json::to_string_pretty(&s.run("document.inspect", &json!({})).map_err(engine_error)?).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{tree}"))
|
||||
}
|
||||
|
||||
fn render(a: RenderArgs, io: &mut Io) -> Result<()> {
|
||||
let o = unicode(&a.output)?.to_owned();
|
||||
let password = password_from(&a.open)?;
|
||||
let mut s = open(&a.input, password.as_deref())?;
|
||||
let mut params = json!({"path": o, "page": a.page, "scale": a.scale, "strict": a.strict});
|
||||
if a.strict {
|
||||
// The check and its report must see the page as it is written.
|
||||
params["markup"] = json!(false);
|
||||
}
|
||||
let r = match s.run("file.exportPng", ¶ms) {
|
||||
Ok(r) => r,
|
||||
Err(e) if a.strict => return Err(refusal(&mut s, e, false, Some(a.page))),
|
||||
Err(e) => return Err(engine_error(e)),
|
||||
};
|
||||
write_stdout(io, |o| writeln!(o, "{r}"))
|
||||
}
|
||||
|
||||
fn load_run_script(path: Option<&Path>) -> Result<Option<script::Script>> {
|
||||
path.map(|p| script::load(p).map_err(engine_error)).transpose()
|
||||
}
|
||||
|
||||
fn run_script(a: RunArgs, io: &mut Io) -> Result<()> {
|
||||
let password = password_from(&a.open)?;
|
||||
let script = load_run_script(a.script.as_deref())?;
|
||||
// A source named on the command line wins over both of the script's.
|
||||
let (mut from_file, mut from_template) = (a.file.clone(), a.template.clone());
|
||||
if from_file.is_none() && from_template.is_none() {
|
||||
from_file = script.as_ref().and_then(|loaded| loaded.file.as_deref().map(std::path::PathBuf::from));
|
||||
from_template = script.as_ref().and_then(|loaded| loaded.template.clone());
|
||||
}
|
||||
let mut s = match (from_file, from_template) {
|
||||
(Some(f), _) => open(&f, password.as_deref())?,
|
||||
// Both go through `file.new`, which puts a blank document on the region's paper (#3152).
|
||||
// `file.new` opens beside the session's first document, which is then closed: the
|
||||
// run starts with one open document.
|
||||
(None, t) => {
|
||||
let mut s = session(wordcraft_doc::Document::new());
|
||||
let first = s.document_id();
|
||||
let params = t.map_or_else(|| json!({}), |t| json!({"template": t}));
|
||||
s.run("file.new", ¶ms).map_err(engine_error)?;
|
||||
s.close_document(first).map_err(engine_error)?;
|
||||
s
|
||||
}
|
||||
};
|
||||
if let Some(name) = &a.author {
|
||||
set_author(&mut s, name).map_err(CliError::Failed)?;
|
||||
}
|
||||
for (n, (id, params)) in script.iter().flat_map(|c| c.commands.iter()).enumerate() {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("command {} ({id}): {e}", n + 1)))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
let r = s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
if a.print {
|
||||
write_stdout(io, |o| writeln!(o, "{id}: {r}"))?;
|
||||
}
|
||||
}
|
||||
let mut outputs: Vec<String> = script.iter().flat_map(|c| c.save.iter().cloned()).collect();
|
||||
if let Some(save) = &a.save {
|
||||
outputs.push(unicode(save)?.to_owned());
|
||||
}
|
||||
// Check every output can be made before writing any, so a bad one leaves no half-done job.
|
||||
for out in &outputs {
|
||||
let parent = Path::new(out).parent().filter(|p| !p.as_os_str().is_empty());
|
||||
if let Some(p) = parent.filter(|p| !p.is_dir()) {
|
||||
return Err(format!("{out}: folder {} does not exist", p.display()).into());
|
||||
}
|
||||
if Path::new(out).is_dir() {
|
||||
return Err(format!("{out}: is a folder, not a file").into());
|
||||
}
|
||||
if !out.to_ascii_lowercase().ends_with(".png") {
|
||||
wordcraft_engine::io::save_bytes(out, &s.doc).map_err(engine_error)?;
|
||||
}
|
||||
}
|
||||
for out in outputs {
|
||||
let r = if out.to_ascii_lowercase().ends_with(".png") {
|
||||
let mut v = json!({"path": out});
|
||||
if let Some(n) = a.page {
|
||||
v["page"] = json!(n);
|
||||
}
|
||||
if let Some(k) = a.scale {
|
||||
v["scale"] = json!(k);
|
||||
}
|
||||
s.run("file.exportPng", &v)
|
||||
} else {
|
||||
s.run("file.save", &json!({"path": out}))
|
||||
};
|
||||
r.map_err(engine_error)?;
|
||||
errln!(io, "wrote {out}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn commands(a: JsonArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
if a.json {
|
||||
let list = serde_json::to_string_pretty(&s.registry.describe()).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{list}"))
|
||||
} else {
|
||||
write_stdout(io, |o| {
|
||||
for c in s.registry.all() {
|
||||
writeln!(o, "{:<32} {:<36} {:<24} {}", c.id, c.label, c.shortcut, c.location)?;
|
||||
}
|
||||
writeln!(o, "{:<32} Structural integrity check", "validate")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parity(a: ParityArgs, io: &mut Io) -> Result<()> {
|
||||
let s = session(wordcraft_doc::Document::new());
|
||||
let p = wordcraft_engine::catalog::parity(&s.registry);
|
||||
if a.markdown {
|
||||
write_stdout(io, |o| write!(o, "{}", parity_markdown(&p)))
|
||||
} else {
|
||||
write_stdout(io, |o| writeln!(o, "{}", serde_json::to_string_pretty(&p).unwrap_or_default()))
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp(a: McpArgs, io: &mut Io) -> Result<()> {
|
||||
if a.connect.is_some() {
|
||||
return Err(MCP_CONNECT_REFUSED.into());
|
||||
}
|
||||
// Shared rule 18 (#7124): an agent entry point never runs unconfined. clap requires both roots.
|
||||
let roots = wordcraft_engine::file_access::AutomationRoots::new(a.read_root.as_deref(), a.write_root.as_deref())
|
||||
.map_err(|e| CliError::Failed(format!("mcp: {e}")))?;
|
||||
let Some(roots) = roots.filter(|r| r.read_root().is_some() && r.write_root().is_some()) else {
|
||||
return Err(CliError::Usage("mcp: give both --automation-read-root DIR and --automation-write-root DIR".into()));
|
||||
};
|
||||
// Every thread of this process, not only the server's: nothing reaches past the roots.
|
||||
wordcraft_engine::file_access::confine_process(roots.clone());
|
||||
let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string());
|
||||
errln!(io, "files confined: read root {}, write root {}", show(roots.read_root()), show(roots.write_root()));
|
||||
let backend: Box<dyn wordcraft_mcp::Backend> = Box::new(headless_mcp(roots, a.author.as_deref()).map_err(CliError::Failed)?);
|
||||
let mut server = wordcraft_mcp::Server::new(backend);
|
||||
let stdin = std::io::stdin();
|
||||
// A client that closes our stdout has hung up: `serve` returns BrokenPipe and we end cleanly.
|
||||
Ok(server.serve(stdin.lock(), &mut *io.out)?)
|
||||
}
|
||||
|
||||
fn zotero(a: ZoteroArgs, io: &mut Io) -> Result<()> {
|
||||
let command =
|
||||
wordcraft_zotero::Command::from_name(&a.command).ok_or_else(|| CliError::Usage(format!("unknown Zotero command `{}`", a.command)))?;
|
||||
let mut s = open(&a.file, None)?;
|
||||
for args::Cmd { id, params } in &a.cmds {
|
||||
s.run(id, params).map_err(|e| engine_error(format!("{id}: {e}")))?;
|
||||
}
|
||||
let mut opts = wordcraft_zotero::client::Options::default();
|
||||
if let Some(p) = a.port {
|
||||
opts.addr.set_port(p);
|
||||
}
|
||||
let mut bridge = wordcraft_zotero::Bridge::new();
|
||||
let mut host = wordcraft_zotero::Headless::default();
|
||||
let mut trace = Vec::new();
|
||||
let out = wordcraft_zotero::client::run_command(&opts, command, &mut |call| {
|
||||
let r = bridge.handle(&mut s, &mut host, call);
|
||||
if a.trace {
|
||||
trace.push(format!("← {} {}", escape_peer(&call.method), escape_peer(&clip(&Value::Array(call.args.clone()).to_string()))));
|
||||
trace.push(format!("→ {}", escape_peer(&clip(&String::from_utf8_lossy(&wordcraft_zotero::wire::encode_reply(&r))))));
|
||||
}
|
||||
r
|
||||
})
|
||||
.map_err(engine_error)?;
|
||||
for line in &trace {
|
||||
errln!(io, "{line}");
|
||||
}
|
||||
for alert in &host.alerts {
|
||||
errln!(io, "Zotero: {}", escape_peer(alert));
|
||||
}
|
||||
errln!(io, "{} calls, {}", out.calls, if out.completed { "completed" } else { "ended without completing (cancelled?)" });
|
||||
if let Some(o) = &a.save {
|
||||
let o = unicode(o)?;
|
||||
s.run("file.save", &json!({"path": o})).map_err(engine_error)?;
|
||||
errln!(io, "wrote {o}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `validate`: 0 for PASS, 1 for any other verdict or a file that can't be read (RFC-0018 rule 1.2 has no other code;
|
||||
/// the verdict is in the report).
|
||||
fn validate(a: ValidateArgs, io: &mut Io) -> Result<u8> {
|
||||
let report =
|
||||
wordcraft_validate::validate_path(&a.file).map_err(|e| CliError::Failed(escape_text(&format!("{}: {e}", a.file.display()), false)))?;
|
||||
let written = if a.json {
|
||||
let json = serde_json::to_string_pretty(&report).unwrap_or_default();
|
||||
write_stdout(io, |o| writeln!(o, "{json}"))
|
||||
} else {
|
||||
write_stdout(io, |o| write_validate_report(o, &report))
|
||||
};
|
||||
match written {
|
||||
// A reader closing early must not turn a FAIL or INCOMPLETE verdict into PASS.
|
||||
Ok(()) | Err(CliError::StdoutClosed) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
Ok(match report.verdict {
|
||||
wordcraft_validate::Verdict::Pass => 0,
|
||||
wordcraft_validate::Verdict::Fail | wordcraft_validate::Verdict::Incomplete => 1,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,37 @@
|
||||
//! What stops a command, and how each case exits.
|
||||
|
||||
/// Why a CLI run stopped early.
|
||||
#[derive(Debug, PartialEq, thiserror::Error)]
|
||||
pub enum CliError {
|
||||
/// The command failed (exit 1); the text is already safe to print.
|
||||
#[error("{0}")]
|
||||
Failed(String),
|
||||
/// A mistake in the command line found after parsing (exit 2).
|
||||
#[error("{0}")]
|
||||
Usage(String),
|
||||
/// A strict export refused (exit 1): the report's lines, then its JSON line, ready for stderr.
|
||||
#[error("{0}")]
|
||||
Strict(String),
|
||||
/// Whoever read stdout closed it (`wordcraft-cli commands --json | head`): nobody is left to write to, so a quiet
|
||||
/// exit 0 (`validate` keeps its verdict's status).
|
||||
#[error("stdout closed")]
|
||||
StdoutClosed,
|
||||
}
|
||||
|
||||
impl From<String> for CliError {
|
||||
fn from(e: String) -> Self {
|
||||
CliError::Failed(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CliError {
|
||||
fn from(e: &str) -> Self {
|
||||
CliError::Failed(e.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for CliError {
|
||||
fn from(e: std::io::Error) -> Self {
|
||||
if e.kind() == std::io::ErrorKind::BrokenPipe { CliError::StdoutClosed } else { CliError::Failed(e.to_string()) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Headless WordCraft (`wordcraft-cli`). [`run`] is the whole program, so it can be tested in-process as well as
|
||||
//! through the binary; `wordcraft-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: <message>` on stderr.
|
||||
|
||||
mod args;
|
||||
mod commands;
|
||||
mod error;
|
||||
mod script;
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
|
||||
use error::CliError;
|
||||
|
||||
pub use args::command;
|
||||
|
||||
/// Where a command writes: results to `out`, diagnostics and progress to `err`.
|
||||
pub(crate) struct Io<'a> {
|
||||
pub(crate) out: &'a mut dyn Write,
|
||||
pub(crate) err: &'a mut dyn Write,
|
||||
}
|
||||
|
||||
/// Writes a line of progress or a warning; a closed stderr is not worth an error.
|
||||
macro_rules! errln {
|
||||
($io:expr, $($arg:tt)*) => {
|
||||
drop(writeln!($io.err, $($arg)*))
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use errln;
|
||||
|
||||
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
|
||||
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
|
||||
fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
args.iter().any(|arg| {
|
||||
let arg = arg.to_string_lossy();
|
||||
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
|
||||
})
|
||||
}
|
||||
|
||||
/// 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 when a command failed, 2 for a usage error. Help and the version go
|
||||
/// to `out`, exit 0.
|
||||
pub fn run<I, T>(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32
|
||||
where
|
||||
I: IntoIterator<Item = T>,
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
let _ = writeln!(err, "error: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
return 2;
|
||||
}
|
||||
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
|
||||
let cli = match args::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();
|
||||
}
|
||||
};
|
||||
let mut io = Io { out, err };
|
||||
// Language packs installed in the suite's font store are used; `proof.installPack` installs
|
||||
// only while the person has turned downloading on in the app.
|
||||
wordcraft_engine::packs::use_font_store(false);
|
||||
if let Some(source) = wordcraft_engine::packs::index_override() {
|
||||
errln!(io, "Language packs come from a test source: {source}");
|
||||
}
|
||||
match commands::dispatch(cli.command, &mut io) {
|
||||
Ok(code) => i32::from(code),
|
||||
// A reader that stopped early (a closed pipe) ends the program quietly, as ripgrep does.
|
||||
Err(CliError::StdoutClosed) => 0,
|
||||
Err(CliError::Usage(e)) => {
|
||||
errln!(io, "error: {e}");
|
||||
2
|
||||
}
|
||||
// The report's lines already start with `error:`.
|
||||
Err(CliError::Strict(report)) => {
|
||||
errln!(io, "{report}");
|
||||
1
|
||||
}
|
||||
Err(e) => {
|
||||
errln!(io, "error: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-1061
File diff suppressed because it is too large
Load Diff
+280
-448
@@ -1,5 +1,285 @@
|
||||
use super::*;
|
||||
use crate::launcher_profile_flag;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A failed in-process run: the exit code and what stderr said (without its `error: ` prefix).
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Fail {
|
||||
code: i32,
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Fail {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the whole CLI in this process, as the binary does.
|
||||
fn exec<S: AsRef<OsStr>>(args: &[S]) -> (i32, String, String) {
|
||||
let (mut out, mut err) = (Vec::new(), Vec::new());
|
||||
let code = crate::run(args.iter().map(|a| a.as_ref().to_owned()), &mut out, &mut err);
|
||||
(code, String::from_utf8_lossy(&out).into_owned(), String::from_utf8_lossy(&err).into_owned())
|
||||
}
|
||||
|
||||
/// `Ok` for exit 0, else the exit code and message.
|
||||
fn run<S: AsRef<OsStr>>(args: &[S]) -> std::result::Result<(), Fail> {
|
||||
let (code, _, err) = exec(args);
|
||||
if code == 0 { Ok(()) } else { Err(Fail { code, text: err.trim_end().strip_prefix("error: ").unwrap_or(err.trim_end()).to_owned() }) }
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
/// A usage error: exit 2, the message on stderr, nothing on stdout, and no work done.
|
||||
fn usage(argv: &[&str]) -> String {
|
||||
let (code, out, err) = exec(argv);
|
||||
assert_eq!((code, out.as_str()), (2, ""), "{argv:?}: {err}");
|
||||
err
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_and_scale_are_checked_before_any_file_is_opened() {
|
||||
for sub in [vec!["render", "missing.docx", "out.png"], vec!["run", "--template", "sample", "--save", "out.png"]] {
|
||||
let with = |extra: &[&str]| usage(&[&sub[..], extra].concat());
|
||||
for missing in [&["--page"][..], &["--scale"], &["--page", "--scale", "2"], &["--scale", "--page", "1"]] {
|
||||
with(missing);
|
||||
}
|
||||
assert!(with(&["--page", "banana"]).contains("invalid --page `banana`: not a valid integer"));
|
||||
assert!(with(&["--page", "0"]).contains("invalid --page `0`: page numbers start at 1"));
|
||||
with(&["--page", "-1"]);
|
||||
assert!(with(&["--scale", "banana"]).contains("invalid --scale `banana`: not a number"));
|
||||
for bad in ["0", "-2", "NaN", "inf"] {
|
||||
assert!(with(&["--scale", bad]).contains(&format!("invalid --scale `{bad}`: scale must be a finite positive number")));
|
||||
}
|
||||
with(&["--page", "1", "--page", "2"]);
|
||||
with(&["--scale", "1", "--scale", "2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_repeated_and_conflicting_options_are_usage_errors_before_file_access() {
|
||||
assert!(usage(&["info", "missing.docx", "--passwrod", "x"]).contains("--passwrod"));
|
||||
assert!(usage(&["render", "missing.docx", "out.png", "--sclae", "2"]).contains("--sclae"));
|
||||
assert!(usage(&["zotero", "refresh", "missing.docx", "--prot", "1"]).contains("--prot"));
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format"]);
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format", "--markup"]);
|
||||
usage(&["convert", "missing.docx", "out.xml", "--format", "flatopc", "--format", "wordml2003"]);
|
||||
assert!(usage(&["convert", "missing.docx", "out.xml", "--format", "docx"]).contains("wordml2003"));
|
||||
usage(&["convert", "missing.docx"]);
|
||||
usage(&["convert", "a.docx", "b.docx", "c.docx"]);
|
||||
usage(&["run", "--file", "a.docx", "--template", "blank"]);
|
||||
usage(&["info"]);
|
||||
usage(&["frobnicate"]);
|
||||
assert!(usage(&["convert", "missing.docx", "out.docx", "--strict"]).contains("--strict needs a .pdf or .png output"));
|
||||
// A valid single value reaches file access, rather than an option error.
|
||||
let (code, _, err) = exec(&["convert", "missing.docx", "out.xml", "--format", "flatopc"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: missing.docx:"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_and_script_values_are_checked_by_the_parser() {
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--script", "--cmd", "caret.docEnd"],
|
||||
] {
|
||||
usage(&argv);
|
||||
}
|
||||
assert!(usage(&["run", "--cmd", "text.insert={nope"]).contains("bad JSON params"));
|
||||
assert_eq!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_author_flag_names_the_headless_session() {
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert_eq!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])), Ok(()));
|
||||
// The flag goes through the same protection check as the command.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let before = s.author.clone();
|
||||
assert!(set_author(&mut s, "Claude").is_err());
|
||||
assert_eq!(s.author, before);
|
||||
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_or_a_file_and_never_shows_in_an_error() {
|
||||
let open = |password: Option<&str>, file: Option<&str>| Password { password: password.map(Into::into), password_file: file.map(PathBuf::from) };
|
||||
assert_eq!(password_from(&open(None, None)), Ok(None));
|
||||
assert_eq!(password_from(&open(Some("s3cret"), None)), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the file.
|
||||
assert_eq!(password_from(&open(Some("a"), Some("/nonexistent"))), Ok(Some("a".into())));
|
||||
let path = std::env::temp_dir().join(format!("wordcraft-cli-password-test-{}.txt", std::process::id()));
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&open(None, path.to_str()));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())), "only the trailing newline is lost");
|
||||
let err = password_from(&open(None, Some("/nonexistent/secret.txt"))).unwrap_err().to_string();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
/// A password file on the command line beats the variable, a blank variable is unset, and `--help` shows neither value.
|
||||
#[test]
|
||||
fn the_password_variable_is_read_by_the_flag_and_hidden() {
|
||||
let parse = |argv: &[&str]| crate::args::parse(&argv.iter().map(OsString::from).collect::<Vec<_>>());
|
||||
let help = parse(&["info", "--help"]).unwrap_err().render().to_string();
|
||||
assert!(help.contains("WORDCRAFT_PASSWORD") || help.contains("--password"), "{help}");
|
||||
let Err(e) = parse(&["info", "--password"]) else { panic!("a missing value must not parse") };
|
||||
assert_eq!(e.exit_code(), 2);
|
||||
let top = parse(&["--help"]).unwrap_err().render().to_string();
|
||||
assert!(top.contains("WORDCRAFT_PASSWORD") && top.contains("WORDCRAFT_REGION") && top.contains("Exit status"), "{top}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_needs_both_roots_and_refuses_connect() {
|
||||
let scratch = Scratch::new("entry");
|
||||
let base = scratch.0.clone();
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let read = format!("--automation-read-root={}", base.join("in").display());
|
||||
let write = format!("--automation-write-root={}", base.join("out").display());
|
||||
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
|
||||
let line = [vec!["mcp".to_string()], given].concat();
|
||||
let err = usage(&line.iter().map(String::as_str).collect::<Vec<_>>());
|
||||
assert!(err.contains("--automation-read-root") || err.contains("--automation-write-root"), "{line:?}: {err}");
|
||||
}
|
||||
let missing = usage(&["mcp", "--automation-read-root", "a", "--automation-read-root=b", "--automation-write-root", "c"]);
|
||||
assert!(missing.contains("--automation-read-root"), "{missing}");
|
||||
usage(&["mcp", "--automation-read-root=", "--automation-write-root=x"]);
|
||||
// A folder that does not exist is an error, not a server that quietly runs unconfined.
|
||||
let (code, _, err) = exec(&["mcp", "--automation-read-root", "/definitely/not/a/folder", "--automation-write-root", "/definitely/not/a/folder"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: mcp: cannot open the automation read root"), "{err}");
|
||||
// `--connect` is refused whether or not it has roots, before anything connects (#3695, #5819).
|
||||
let dir = base.to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect=127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let (code, _, err) = exec(&line);
|
||||
assert_eq!(code, 1, "{line:?}");
|
||||
assert!(err.contains("--connect") && err.contains("#3695") && err.contains("#5819"), "{line:?}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_opening_subcommand_reaches_the_open_with_a_non_unicode_name_but_not_an_output() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
for argv in [
|
||||
vec![OsString::from("convert"), latin1(), "out.pdf".into()],
|
||||
vec!["info".into(), latin1()],
|
||||
vec!["text".into(), latin1()],
|
||||
vec!["inspect".into(), latin1()],
|
||||
vec!["render".into(), latin1(), "out.png".into()],
|
||||
vec!["run".into(), "--file".into(), latin1()],
|
||||
vec!["zotero".into(), "refresh".into(), latin1()],
|
||||
] {
|
||||
let (code, _, err) = exec(&argv);
|
||||
assert_eq!(code, 1, "{argv:?}: {err}");
|
||||
assert!(err.contains("No such file"), "{argv:?}: {err}");
|
||||
}
|
||||
// An output the engine takes as text must be Unicode: a failure, and nothing opened.
|
||||
let out = OsString::from_vec(b"caf\xe9.png".to_vec());
|
||||
let (code, _, err) = exec(&["render".into(), OsString::from("in.docx"), out]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.contains("not valid Unicode"), "{err}");
|
||||
// Elsewhere clap refuses it as usage.
|
||||
assert_eq!(exec(&["run".into(), OsString::from("--template"), OsString::from_vec(b"caf\xe9".to_vec())]).0, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// `validate`: PASS is 0; FAIL, INCOMPLETE and a file that can't be read are 1 (RFC-0018 rule 1.2); usage is 2.
|
||||
#[test]
|
||||
fn validate_exits_0_for_pass_1_for_anything_else_and_2_for_usage() {
|
||||
let dir = script_dir("validate-exit");
|
||||
let good = dir.join("good.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &good.to_string_lossy()])).unwrap();
|
||||
let good = good.to_string_lossy().into_owned();
|
||||
let (code, out, _) = exec(&["validate", &good]);
|
||||
assert_eq!((code, out.lines().next()), (0, Some("PASS")));
|
||||
let (code, out, _) = exec(&["validate", "--json", &good]);
|
||||
assert_eq!(code, 0);
|
||||
assert!(out.contains("\"verdict\""), "{out}");
|
||||
let broken = dir.join("broken.docx");
|
||||
std::fs::write(&broken, b"not a zip").unwrap();
|
||||
let (code, out, _) = exec(&["validate".to_string(), broken.to_string_lossy().into_owned()]);
|
||||
assert_eq!(code, 1, "{out}");
|
||||
assert!(out.starts_with("FAIL") || out.starts_with("INCOMPLETE"), "{out}");
|
||||
let (code, _, err) = exec(&["validate", "/definitely/not/there.docx"]);
|
||||
assert_eq!(code, 1);
|
||||
assert!(err.starts_with("error: /definitely/not/there.docx:"), "{err}");
|
||||
usage(&["validate"]);
|
||||
usage(&["validate", &good, &good]);
|
||||
usage(&["validate", &good, "--bogus"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_version_go_to_stdout_with_exit_0() {
|
||||
for argv in [vec!["--version"], vec!["-V"], vec!["--help"], vec!["-h"], vec!["help"], vec!["convert", "--help"], vec!["help", "validate"]] {
|
||||
let (code, out, err) = exec(&argv);
|
||||
assert_eq!((code, err.as_str()), (0, ""), "{argv:?}");
|
||||
assert!(out.contains("wordcraft-cli"), "{argv:?}: {out}");
|
||||
}
|
||||
let (_, out, _) = exec(&["--version"]);
|
||||
assert_eq!(out.trim(), format!("wordcraft-cli {}", env!("CARGO_PKG_VERSION")));
|
||||
// The version is not a subcommand; with no arguments the help is shown as an error, exit 2.
|
||||
usage(&["version"]);
|
||||
assert_eq!(exec::<&str>(&[]).0, 2);
|
||||
// Every subcommand's help ends with the exit status.
|
||||
for sub in crate::command().get_subcommands().map(|c| c.get_name().to_owned()).filter(|n| n != "help") {
|
||||
let (code, out, _) = exec(&[sub.as_str(), "--help"]);
|
||||
assert_eq!(code, 0, "{sub}");
|
||||
assert!(out.contains("Exit status"), "{sub}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_bootstrap_exits_2_before_anything_runs() {
|
||||
let err = usage(&["--launch-profile=nightly-v1", "info", "x.docx"]);
|
||||
assert!(err.starts_with("error: --launch-profile and --profile-root"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_stdout_ends_quietly_and_other_write_errors_fail() {
|
||||
struct Closed(std::io::ErrorKind);
|
||||
impl Write for Closed {
|
||||
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(self.0.into())
|
||||
}
|
||||
}
|
||||
let mut err = Vec::new();
|
||||
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::BrokenPipe), &mut err), 0);
|
||||
assert!(err.is_empty());
|
||||
assert_eq!(crate::run(["commands"], &mut Closed(std::io::ErrorKind::PermissionDenied), &mut err), 1);
|
||||
assert!(String::from_utf8_lossy(&err).starts_with("error: "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_strict_and_render_strict_refusals_exit_1() {
|
||||
// A document whose text can't be drawn is a refusal: exit 1 with the report on stderr and no file.
|
||||
let dir = script_dir("strict-exit");
|
||||
let out = dir.join("out.pdf");
|
||||
let (code, _, err) = exec(&["convert", "/definitely/not/there.docx", &out.to_string_lossy(), "--strict"]);
|
||||
assert_eq!(code, 1, "{err}");
|
||||
assert!(!out.exists());
|
||||
}
|
||||
|
||||
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
|
||||
#[test]
|
||||
@@ -18,10 +298,6 @@ fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
|
||||
}
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_text_stays_on_one_visible_line() {
|
||||
let alert = "Done.\nwrote /etc/passwd\r\u{1b}[2J\u{9b}31m\u{202e}txt.exe\\n\tok é";
|
||||
@@ -31,127 +307,12 @@ fn peer_text_stays_on_one_visible_line() {
|
||||
assert_eq!(escape_peer("Citation (Doe, 2020) — “ok”"), "Citation (Doe, 2020) — “ok”");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validators_accept_only_the_documented_options() {
|
||||
assert!(validate_options("info", &args(&["file.docx"]), PASSWORD_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page", "2", "--scale", "1.5"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(validate_options("run", &args(&["--cmd", "text.insert={}", "--cmd", "edit.undo", "--print"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("commands", &args(&["--json"]), COMMANDS_OPTIONS).is_ok());
|
||||
assert!(validate_options("parity", &args(&["--markdown"]), PARITY_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--connect", "127.0.0.1:9000"]), MCP_OPTIONS).is_ok());
|
||||
assert!(validate_options("render", &args(&["in.docx", "out.png", "--page"]), RENDER_OPTIONS).is_ok());
|
||||
assert!(
|
||||
validate_options(
|
||||
"zotero",
|
||||
&args(&["refresh", "in.docx", "--cmd", "caret.docEnd", "--save", "out.docx", "--trace", "--port", "23119"]),
|
||||
ZOTERO_OPTIONS
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_option_value_is_never_read_as_a_path() {
|
||||
// `--password`'s value sits between the paths and would be taken for one without
|
||||
// `positionals`, so `render` would write its picture over a file called after the password.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--password", "secret", "out.png"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
assert_eq!(positionals(&args(&["in.docx", "out.png", "--page", "2"]), RENDER_OPTIONS), vec!["in.docx", "out.png"]);
|
||||
// A bare flag takes no value, so the next argument stays a path.
|
||||
assert_eq!(positionals(&args(&["--print", "in.docx"]), RUN_OPTIONS), vec!["in.docx"]);
|
||||
// `convert` is the one with a value-taking flag between the two paths.
|
||||
assert_eq!(positionals(&args(&["in.docx", "--format", "flatopc", "out.docx"]), CONVERT_OPTIONS), vec!["in.docx", "out.docx"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_comes_from_an_option_a_file_or_the_environment() {
|
||||
assert_eq!(password_from(&args(&["f.docx"])), Ok(None));
|
||||
assert_eq!(password_from(&args(&["f.docx", "--password", "s3cret"])), Ok(Some("s3cret".into())));
|
||||
// `--password` wins over the other two sources.
|
||||
assert_eq!(password_from(&args(&["--password", "a", "--password-file", "/nonexistent"])), Ok(Some("a".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_password_file_loses_only_its_trailing_newline() {
|
||||
let path = std::env::temp_dir().join("wordcraft-cli-password-test.txt");
|
||||
std::fs::write(&path, "s3cret\r\n").unwrap();
|
||||
let got = password_from(&args(&["f.docx", "--password-file", &path.to_string_lossy()]));
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert_eq!(got, Ok(Some("s3cret".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_password_file_is_named_without_the_password() {
|
||||
let err = password_from(&args(&["f.docx", "--password-file", "/nonexistent/secret.txt"])).unwrap_err();
|
||||
assert!(err.contains("--password-file"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_options_are_rejected_before_file_access() {
|
||||
assert_eq!(run(&args(&["info", "missing.docx", "--passwrod", "x"])), Err("info: unknown option --passwrod".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--sclae", "2"])), Err("render: unknown option --sclae".into()));
|
||||
assert_eq!(run(&args(&["zotero", "refresh", "missing.docx", "--prot", "1"])), Err("zotero: unknown option --prot".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_rejects_malformed_format_options_before_file_access() {
|
||||
for (options, error) in [
|
||||
(vec!["--format"], "convert: --format requires a value"),
|
||||
(vec!["--format", "--markup"], "convert: --format requires a value"),
|
||||
(vec!["--format", "flatopc", "--format", "wordml2003"], "convert: duplicate --format option"),
|
||||
] {
|
||||
let mut argv = args(&["convert", "missing.docx", "out.xml"]);
|
||||
argv.extend(args(&options));
|
||||
assert_eq!(run(&argv), Err(error.into()), "{options:?}");
|
||||
}
|
||||
// A valid single value reaches file access, rather than a format-option error.
|
||||
let error = run(&args(&["convert", "missing.docx", "out.xml", "--format", "flatopc"])).unwrap_err().to_string();
|
||||
assert!(error.starts_with("missing.docx:"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_or_h_after_a_subcommand_asks_for_the_usage() {
|
||||
for cmd in SUBCOMMANDS {
|
||||
assert!(wants_help(cmd, &args(&["in.docx", "--help"])), "{cmd}");
|
||||
assert!(wants_help(cmd, &args(&["-h"])), "{cmd}");
|
||||
assert!(!wants_help(cmd, &args(&["in.docx", "--hepl"])), "{cmd}");
|
||||
}
|
||||
assert!(!wants_help("frobnicate", &args(&["--help"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_lists_exactly_the_subcommands() {
|
||||
let listed: Vec<&str> = USAGE
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix(" wordcraft-cli ")?.split_whitespace().next())
|
||||
.filter(|word| !word.starts_with(['-', '[']))
|
||||
.collect();
|
||||
assert_eq!(listed, SUBCOMMANDS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_keeps_bullet_and_number_labels() {
|
||||
let doc = wordcraft_engine::io::open_bytes("lists.md", b"- alpha\n- beta\n\n1. first\n2. second\n").unwrap();
|
||||
assert_eq!(listed_text(&doc).unwrap(), "\u{2022}\talpha\n\u{2022}\tbeta\n1.\tfirst\n2.\tsecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_names_the_headless_session() {
|
||||
assert!(validate_options("run", &args(&["--author", "Claude (copyedit)", "--cmd", "edit.undo"]), RUN_OPTIONS).is_ok());
|
||||
assert!(validate_options("mcp", &args(&["--author", "Claude"]), MCP_OPTIONS).is_ok());
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
assert!(set_author(&mut s, " Claude (copyedit) ").is_ok());
|
||||
assert_eq!(s.author, "Claude (copyedit)");
|
||||
assert!(set_author(&mut s, " ").is_err_and(|e| e.starts_with("--author:")));
|
||||
assert!(run(&args(&["run", "--author", "Claude", "--cmd", "review.trackChanges={\"value\":true}"])).is_ok());
|
||||
// The flag goes through the same protection check as the command.
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let before = s.author.clone();
|
||||
assert!(set_author(&mut s, "Claude").is_err());
|
||||
assert_eq!(s.author, before);
|
||||
assert!(s.run("file.setAuthor", &json!({"name": "Claude"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn author_flag_cannot_claim_a_named_exception_after_protection() {
|
||||
use wordcraft_doc::{CharProps, InlineObject, StoryRef};
|
||||
@@ -170,91 +331,6 @@ fn author_flag_cannot_claim_a_named_exception_after_protection() {
|
||||
assert!(s.run("text.insert", &json!({"text": "Changed"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_root_flags_are_taken_out_of_the_mcp_arguments() {
|
||||
let base = std::env::temp_dir().join(format!("wc-cli-roots-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let (read, write) = (base.join("in").to_string_lossy().into_owned(), base.join("out").to_string_lossy().into_owned());
|
||||
|
||||
let (roots, left) =
|
||||
automation_roots("mcp", &args(&["--automation-read-root", &read, "--author", "Claude", &format!("--automation-write-root={write}")]))
|
||||
.unwrap();
|
||||
let roots = roots.unwrap();
|
||||
assert_eq!(left, args(&["--author", "Claude"]));
|
||||
assert!(roots.read_root().is_some() && roots.write_root().is_some());
|
||||
assert!(validate_options("mcp", &left, MCP_OPTIONS).is_ok());
|
||||
|
||||
// A root left out grants none of its access.
|
||||
let (roots, _) = automation_roots("mcp", &args(&["--automation-read-root", &read])).unwrap();
|
||||
let roots = roots.unwrap();
|
||||
assert!(roots.write_root().is_none());
|
||||
assert!(roots.check(&format!("{write}/x.docx"), wordcraft_engine::file_access::Access::Write).unwrap_err().contains("write authority is absent"));
|
||||
|
||||
// No flags: nothing is confined and the arguments pass through.
|
||||
let (roots, left) = automation_roots("mcp", &args(&["--connect", "127.0.0.1:9"])).unwrap();
|
||||
assert!(roots.is_none());
|
||||
assert_eq!(left, args(&["--connect", "127.0.0.1:9"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_root_flags_reject_bad_operands_and_missing_folders() {
|
||||
for bad in [
|
||||
args(&["--automation-read-root"]),
|
||||
args(&["--automation-read-root", "--author"]),
|
||||
args(&["--automation-write-root="]),
|
||||
args(&["--automation-read-root", "a", "--automation-read-root=b"]),
|
||||
] {
|
||||
assert!(automation_roots("mcp", &bad).is_err(), "{bad:?}");
|
||||
}
|
||||
let e = automation_roots("mcp", &args(&["--automation-read-root", "/definitely/not/a/folder"])).err().unwrap();
|
||||
assert!(e.starts_with("mcp: cannot open the automation read root"), "{e}");
|
||||
// Through the command line: an error, not a server that quietly runs unconfined.
|
||||
assert!(run(&args(&["mcp", "--automation-write-root", "/definitely/not/a/folder"])).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn only_the_opened_file_may_be_other_than_unicode() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let latin1 = || OsString::from_vec(b"caf\xe9.docx".to_vec());
|
||||
let ok = |raw: Vec<OsString>| text_args(&raw).unwrap().1;
|
||||
assert_eq!(ok(vec!["zotero".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), latin1(), "out.png".into(), "--page".into(), "2".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["render".into(), "--page".into(), "2".into(), latin1(), "out.png".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["convert".into(), "--format".into(), "flatopc".into(), latin1(), "out.xml".into()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "--password".into(), "secret".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["zotero".into(), "--port".into(), "23119".into(), "refresh".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["run".into(), "--print".into(), "--file".into(), latin1()]), Some(PathBuf::from(latin1())));
|
||||
assert_eq!(ok(vec!["info".into(), "in.docx".into()]), None);
|
||||
// Every command that opens a file reaches the open with it (no such file here), so
|
||||
// `OPENS_FILE` and the commands' own arguments agree. `validate` takes exactly one path, so it
|
||||
// is checked separately below, together with its exit-3 usage status.
|
||||
let missing = || OsString::from_vec(b"/definitely/not/caf\xe9.docx".to_vec());
|
||||
let mut opening: Vec<Vec<OsString>> = OPENS_FILE
|
||||
.iter()
|
||||
.filter(|(cmd, _)| *cmd != "validate")
|
||||
.map(|(cmd, n)| [vec![(*cmd).into()], vec![OsString::from("refresh"); *n], vec![missing(), "out.png".into()]].concat())
|
||||
.collect();
|
||||
opening.push(vec!["run".into(), "--file".into(), missing()]);
|
||||
for raw in opening {
|
||||
let e = run(&raw).unwrap_err().to_string();
|
||||
assert!(e.contains("No such file"), "{raw:?}: {e}");
|
||||
}
|
||||
assert!(matches!(run(&["validate".into(), missing()]), Err(Failure::Status(3))));
|
||||
for (raw, n) in [
|
||||
(vec!["zotero".into(), latin1(), "in.docx".into()], 2),
|
||||
(vec!["render".into(), "in.docx".into(), latin1()], 3),
|
||||
(vec!["render".into(), "--page".into(), latin1(), "in.docx".into(), "out.png".into()], 3),
|
||||
(vec!["run".into(), "--save".into(), latin1()], 3),
|
||||
(vec!["commands".into(), latin1()], 2),
|
||||
] {
|
||||
assert_eq!(text_args(&raw).unwrap_err(), format!("argument {n} is not valid Unicode: caf\u{FFFD}.docx"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An exclusively created scratch folder, removed on drop even when an assertion fails.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
@@ -281,66 +357,6 @@ impl Drop for Scratch {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared rule 18 (#7124): every agent entry point, a subcommand that serves a client's requests
|
||||
/// rather than running what the person typed and exiting, refuses to start without both
|
||||
/// automation roots. Each subcommand has a row, so a new one fails here until it is classified,
|
||||
/// and a new agent entry point fails until it refuses.
|
||||
#[test]
|
||||
fn every_agent_entry_point_refuses_to_start_without_both_roots() {
|
||||
enum Kind {
|
||||
Agent,
|
||||
NotAgent(&'static str),
|
||||
}
|
||||
use Kind::{Agent, NotAgent};
|
||||
let table = [
|
||||
("convert", NotAgent("converts the files named on its command line, then exits")),
|
||||
("info", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("text", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("inspect", NotAgent("reads the one file named on its command line, then exits")),
|
||||
("render", NotAgent("renders the file named on its command line, then exits")),
|
||||
("run", NotAgent("runs the commands and script named on its command line, then exits")),
|
||||
("commands", NotAgent("lists the commands; touches no file")),
|
||||
("parity", NotAgent("prints the feature catalog; touches no file")),
|
||||
("validate", NotAgent("validates the one file named on its command line, then exits")),
|
||||
("mcp", Agent),
|
||||
("zotero", NotAgent("runs one named Zotero command; Zotero's replies edit citations and name no file")),
|
||||
];
|
||||
assert_eq!(table.iter().map(|(name, _)| *name).collect::<Vec<_>>(), SUBCOMMANDS);
|
||||
|
||||
let scratch = Scratch::new("entry");
|
||||
let base = scratch.0.clone();
|
||||
std::fs::create_dir_all(base.join("in")).unwrap();
|
||||
std::fs::create_dir_all(base.join("out")).unwrap();
|
||||
let read = format!("--automation-read-root={}", base.join("in").display());
|
||||
let write = format!("--automation-write-root={}", base.join("out").display());
|
||||
for (name, kind) in table {
|
||||
if let NotAgent(why) = kind {
|
||||
assert!(!why.is_empty(), "{name}: say why it is not an agent entry point");
|
||||
continue;
|
||||
}
|
||||
for given in [vec![], vec![read.clone()], vec![write.clone()], vec!["--author".to_string(), "Claude".to_string()]] {
|
||||
let line = [vec![name.to_string()], given].concat();
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--automation-read-root") && e.contains("--automation-write-root"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop app doesn't confine its control channel to roots yet (#3695, #5819), so the bridge
|
||||
/// to it is refused, with roots or without, before anything connects.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_until_the_app_confines_its_control_channel() {
|
||||
let dir = std::env::temp_dir().to_string_lossy().into_owned();
|
||||
for line in [
|
||||
args(&["mcp", "--connect", "127.0.0.1:9"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--author", "Claude"]),
|
||||
args(&["mcp", "--connect", "127.0.0.1:9", "--automation-read-root", &dir, "--automation-write-root", &dir]),
|
||||
] {
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `mcp`'s headless session takes `--author` as the session's author, and refuses a blank one as `run` does.
|
||||
#[test]
|
||||
fn mcp_headless_session_takes_the_author_flag() {
|
||||
@@ -352,120 +368,6 @@ fn mcp_headless_session_takes_the_author_flag() {
|
||||
assert_eq!(unnamed.session.author, wordcraft_mcp::Headless::default().session.author, "no flag keeps the default author");
|
||||
}
|
||||
|
||||
/// `--connect` is refused whether or not it has a value, written apart or as `--connect=…`, even with both roots valid.
|
||||
#[test]
|
||||
fn mcp_connect_is_refused_without_a_value_too() {
|
||||
let scratch = Scratch::new("connect-bare");
|
||||
let dir = scratch.0.to_string_lossy().into_owned();
|
||||
let roots = ["--automation-read-root", &dir, "--automation-write-root", &dir];
|
||||
for tail in [vec!["--connect"], vec!["--connect", "--author", "Claude"], vec!["--connect=127.0.0.1:9"], vec!["--connect="]] {
|
||||
let line = args(&[&["mcp"][..], &roots, &tail].concat());
|
||||
let e = run(&line).unwrap_err().to_string();
|
||||
assert!(e.contains("--connect") && e.contains("#3695") && e.contains("#5819"), "{line:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale"])), Err("render: --scale requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "--scale", "2"])), Err("render: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "--page", "1"])), Err("render: --scale requires a value".into()));
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--page", "banana"])),
|
||||
Err("render: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "banana"])), Err("render: invalid --scale `banana`: not a number".into()));
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "0"])), Err("render: invalid --page `0`: page numbers start at 1".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "-1"])), Err("render: invalid --page `-1`: not a valid integer".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "0"])),
|
||||
Err("render: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "-2"])),
|
||||
Err("render: invalid --scale `-2`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "NaN"])),
|
||||
Err("render: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["render", "missing.docx", "out.png", "--scale", "inf"])),
|
||||
Err("render: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--page", "1", "--page", "2"])), Err("render: duplicate --page option".into()));
|
||||
assert_eq!(run(&args(&["render", "missing.docx", "out.png", "--scale", "1", "--scale", "2"])), Err("render: duplicate --scale option".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_missing_or_invalid_page_and_scale() {
|
||||
// Missing operands
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--page"])), Err("run: --page requires a value".into()));
|
||||
assert_eq!(run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale"])), Err("run: --scale requires a value".into()));
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "--scale", "2"])),
|
||||
Err("run: --page requires a value".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "--page", "1"])),
|
||||
Err("run: --scale requires a value".into())
|
||||
);
|
||||
|
||||
// Non-numeric operands
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "banana"])),
|
||||
Err("run: invalid --page `banana`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "banana"])),
|
||||
Err("run: invalid --scale `banana`: not a number".into())
|
||||
);
|
||||
|
||||
// Out-of-range values
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "0"])),
|
||||
Err("run: invalid --page `0`: page numbers start at 1".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "-1"])),
|
||||
Err("run: invalid --page `-1`: not a valid integer".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "0"])),
|
||||
Err("run: invalid --scale `0`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "-1"])),
|
||||
Err("run: invalid --scale `-1`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "NaN"])),
|
||||
Err("run: invalid --scale `NaN`: scale must be a finite positive number".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "inf"])),
|
||||
Err("run: invalid --scale `inf`: scale must be a finite positive number".into())
|
||||
);
|
||||
|
||||
// Duplicate options
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--page", "1", "--page", "2"])),
|
||||
Err("run: duplicate --page option".into())
|
||||
);
|
||||
assert_eq!(
|
||||
run(&args(&["run", "--template", "sample", "--save", "out.png", "--scale", "1", "--scale", "2"])),
|
||||
Err("run: duplicate --scale option".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_and_run_valid_options_and_defaults_produce_files() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-render-{}", std::process::id()));
|
||||
@@ -615,33 +517,6 @@ fn command_line_template_wins_over_the_scripts_file() {
|
||||
assert!(std::fs::read_to_string(&b).unwrap().contains("FROM FILE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_value_missing_is_reported() {
|
||||
let missing = std::env::temp_dir().join(format!(
|
||||
"wc-cli-missing-cmd-{}-{}.docx",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
|
||||
));
|
||||
assert!(!missing.exists());
|
||||
let missing = missing.to_string_lossy();
|
||||
for argv in [
|
||||
vec!["run", "--cmd"],
|
||||
vec!["run", "--cmd", "--save", "out.docx"],
|
||||
vec!["run", "--cmd", "caret.docEnd", "--cmd", "--print"],
|
||||
vec!["run", "--cmd", "--bogus"],
|
||||
vec!["run", "--cmd", "--file", &missing],
|
||||
] {
|
||||
assert_eq!(run(&args(&argv)), Err("--cmd needs a value".into()), "{argv:?}");
|
||||
}
|
||||
assert!(run(&args(&["run", "--cmd", "caret.docEnd", "--cmd", "caret.docStart"])).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_value_missing_is_reported() {
|
||||
let e = run(&args(&["run", "--script", "--cmd", "caret.docEnd"])).unwrap_err().to_string();
|
||||
assert!(e.contains("--script requires a value"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_reads_from_a_stream_and_caps_its_size() {
|
||||
let s = script::load_from(&br#"{"commands":["caret.docEnd"],"save":["o.docx"]}"#[..], "-", None).unwrap();
|
||||
@@ -704,34 +579,6 @@ fn script_parse_resolves_paths_against_the_base() {
|
||||
assert_eq!(s.commands.len(), 1);
|
||||
}
|
||||
|
||||
/// Finding 3: a surplus operand is a usage error (exit 3) rejected in the operand check, before any
|
||||
/// file is validated, so a valid first path can no longer make `validate a.docx b.docx` print PASS.
|
||||
/// The two paths are DIFFERENT files and validating either one would return `Ok`; the code path
|
||||
/// returns `Status(3)` from the `paths.len() != 1` check before `validate_path` runs, so no file was
|
||||
/// validated to produce it. (A `Status(3)` on its own does not prove that — `validate` also returns
|
||||
/// it for an I/O error after a single valid operand reaches the validator — which is why the
|
||||
/// operand check, not the status, is what establishes the rejection happened first.)
|
||||
#[test]
|
||||
fn validate_rejects_missing_or_surplus_operands_without_validating() {
|
||||
let dir = std::env::temp_dir().join(format!("wc-cli-validate-args-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let first = dir.join("first.docx");
|
||||
let second = dir.join("second.docx");
|
||||
run(&args(&["run", "--template", "sample", "--save", &first.to_string_lossy()])).unwrap();
|
||||
run(&args(&["run", "--template", "sample", "--save", &second.to_string_lossy()])).unwrap();
|
||||
let (first, second) = (first.to_string_lossy().into_owned(), second.to_string_lossy().into_owned());
|
||||
assert_ne!(first, second, "the two operands must be different files");
|
||||
assert_eq!(run(&args(&["validate", &first])), Ok(()), "one valid path reports PASS");
|
||||
assert_eq!(
|
||||
run(&args(&["validate", &first, &second])),
|
||||
Err(Failure::Status(3)),
|
||||
"two different paths are a usage error; validating either would return Ok, so it validated neither"
|
||||
);
|
||||
assert_eq!(run(&args(&["validate"])), Err(Failure::Status(3)), "no path is a usage error");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Finding 4: `validate` is in `OPENS_FILE`, so a file name that is not valid Unicode reaches the
|
||||
/// validator by its preserved path rather than being rejected as a bad argument.
|
||||
/// APFS refuses invalid UTF-8 file names, so macOS covers native path handling without creating one.
|
||||
@@ -827,18 +674,3 @@ fn invisible_characters_are_escaped_and_json_lines_still_parse_back() {
|
||||
assert!(line.contains("\\ud800") || line.contains("\\udb40"), "{line}");
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), value);
|
||||
}
|
||||
|
||||
/// Native non-Unicode paths survive argument parsing and reach the validator's I/O error path.
|
||||
/// No file is created: APFS refuses invalid UTF-8 names. The original bytes, rather than their
|
||||
/// lossy display spelling, must be retained even when options precede the operand.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn validate_preserves_a_non_unicode_path_without_creating_a_file() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let raw_path = OsString::from_vec(b"wordcraft-nonexistent-caf\xe9.docx".to_vec());
|
||||
let raw = vec![OsString::from("validate"), OsString::from("--json"), raw_path.clone()];
|
||||
let (_, parsed) = text_args(&raw).unwrap();
|
||||
assert_eq!(parsed.as_deref(), Some(Path::new(&raw_path)));
|
||||
assert!(parsed.as_deref().unwrap().to_str().is_none());
|
||||
assert_eq!(run(&raw), Err(Failure::Status(3)), "native path reaches I/O handling");
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ fn validate_closed_stdout_preserves_verdict() {
|
||||
let bytes = wordcraft_engine::io::save_bytes("pass.docx", &wordcraft_doc::Document::from_text("Control")).unwrap();
|
||||
std::fs::write(&pass, bytes).unwrap();
|
||||
let mut results = Vec::new();
|
||||
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 2)] {
|
||||
for (fixture, expected) in [(pass.clone(), 0), (corpus.join("14-comment-dup.docx"), 1), (sparse.clone(), 1)] {
|
||||
for json in [false, true] {
|
||||
let mut open = cli();
|
||||
open.arg("validate").arg(&fixture);
|
||||
@@ -87,7 +87,7 @@ fn validate_closed_stdout_preserves_verdict() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Other report-write failures are I/O status 3; a child-only file-size limit forces EFBIG on stdout.
|
||||
/// Other report-write failures are status 1 (RFC-0018: there is no 3); a child-only file-size limit forces EFBIG on stdout.
|
||||
#[test]
|
||||
fn validate_stdout_write_error_is_io_status() {
|
||||
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../crates/validate/corpus/calibration/14-comment-dup.docx");
|
||||
@@ -105,7 +105,7 @@ fn validate_stdout_write_error_is_io_status() {
|
||||
}
|
||||
std::fs::remove_file(stdout).unwrap();
|
||||
for (json, output) in results {
|
||||
assert_eq!(output.status.code(), Some(3), "json={json}: {output:?}");
|
||||
assert_eq!(output.status.code(), Some(1), "json={json}: {output:?}");
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("panicked"), "{output:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const SUBCOMMANDS: [&str; 10] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "mcp", "zotero"];
|
||||
const SUBCOMMANDS: [&str; 11] = ["convert", "info", "text", "inspect", "render", "run", "commands", "parity", "validate", "mcp", "zotero"];
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
// `output()` gives the child no stdin, so `mcp` can't wait for a client.
|
||||
@@ -14,7 +14,7 @@ fn assert_prints_usage(args: &[&str]) {
|
||||
let out = cli(args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success(), "{args:?}: status {:?}, stderr: {stderr}", out.status);
|
||||
assert!(String::from_utf8_lossy(&out.stdout).starts_with("wordcraft-cli — "), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("wordcraft-cli"), "{args:?}: stdout: {}", String::from_utf8_lossy(&out.stdout));
|
||||
assert!(stderr.is_empty(), "{args:?}: stderr: {stderr}");
|
||||
}
|
||||
|
||||
@@ -39,9 +39,9 @@ fn help_comes_before_opening_files_and_folders() {
|
||||
#[test]
|
||||
fn misspelled_options_and_unknown_commands_still_fail() {
|
||||
let out = cli(&["info", "--hepl"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("info: unknown option --hepl"));
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--hepl"));
|
||||
let out = cli(&["frobnicate", "--help"]);
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("unknown command `frobnicate`"));
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("frobnicate"));
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ mod closed_stdout;
|
||||
mod convert_fields;
|
||||
mod convert_region;
|
||||
mod help;
|
||||
mod man_and_completions;
|
||||
mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
|
||||
@@ -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() {
|
||||
wordcraft_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 wordcraft_cli::command(), "wordcraft-cli", &mut out);
|
||||
assert!(!out.is_empty(), "{shell}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn man_pages_render_for_the_command_and_every_subcommand() {
|
||||
let cmd = wordcraft_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, `wordcraft-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!("wc-cli-{}-man-and-completions", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
example::generate(&dir).unwrap();
|
||||
|
||||
let mut written: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();
|
||||
written.sort();
|
||||
let completions = ["wordcraft-cli.bash", "_wordcraft-cli", "wordcraft-cli.fish", "wordcraft-cli.elv", "_wordcraft-cli.ps1"];
|
||||
let subcommands = ["commands", "convert", "info", "inspect", "mcp", "parity", "render", "run", "text", "validate", "zotero"];
|
||||
let mut expected: Vec<String> = completions.map(String::from).into();
|
||||
expected.push("wordcraft-cli.1".into());
|
||||
expected.extend(subcommands.iter().map(|s| format!("wordcraft-cli-{s}.1")));
|
||||
expected.sort();
|
||||
assert_eq!(written, expected);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -67,17 +67,19 @@ fn any_other_such_argument_is_an_error_naming_it() {
|
||||
let (dir, file) = folder("error");
|
||||
let out_name = dir.join(OsString::from_vec(b"caf\xe9.md".to_vec())).into_os_string();
|
||||
let cmd = OsString::from_vec(b"text.insert={\"text\":\"\xe9\"}".to_vec());
|
||||
for (args, n) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 3),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd], 5),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 1),
|
||||
// An output the engine takes as text: a failure (1), naming it; the other arguments are usage errors (2).
|
||||
for (args, code, shown) in [
|
||||
(vec!["convert".into(), file.clone(), out_name.clone()], 1, out_name.clone()),
|
||||
(vec!["run".into(), "--file".into(), file.clone(), "--cmd".into(), cmd.clone()], 2, cmd),
|
||||
(vec![OsString::from_vec(b"t\xe9xt".to_vec()), file.clone()], 2, OsString::from_vec(b"t\xe9xt".to_vec())),
|
||||
] {
|
||||
let out = cli(&args);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let shown = args[n - 1].to_string_lossy();
|
||||
let shown = shown.to_string_lossy();
|
||||
assert!(shown.contains('\u{FFFD}'));
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}: stderr: {stderr}");
|
||||
assert_eq!(stderr, format!("wordcraft-cli: argument {n} is not valid Unicode: {shown}\n"), "{args:?}");
|
||||
assert_eq!(out.status.code(), Some(code), "{args:?}: stderr: {stderr}");
|
||||
assert!(stderr.starts_with("error: "), "{args:?}: {stderr}");
|
||||
assert!(stderr.contains("not valid Unicode") || stderr.contains("invalid UTF-8") || stderr.contains(&*shown), "{args:?}: {stderr}");
|
||||
}
|
||||
assert!(!std::path::Path::new(&out_name).exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `convert --strict` (#6005): exit 3 and a report when a PDF or PNG would silently lack a
|
||||
//! `convert --strict` (#6005): exit 1 and a report when a PDF or PNG would silently lack a
|
||||
//! character or a picture, nothing written; exit 0 otherwise.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
@@ -145,9 +145,9 @@ fn an_uncovered_code_point_fails_strict_with_a_report_and_no_file() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×3)")), "{text}");
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["schema"], 1);
|
||||
assert_eq!(json["strict"], "failed");
|
||||
@@ -186,7 +186,7 @@ fn a_corrupt_header_picture_fails_strict_naming_the_part_and_the_header() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("word/media/image2.bin (header2.xml): unsupported format"), "{text}");
|
||||
let json = report_json(&r);
|
||||
@@ -218,7 +218,7 @@ fn an_external_picture_target_is_never_fetched_and_is_reported_under_strict() {
|
||||
assert_eq!(lenient.status.code(), Some(0), "{}", stderr(&lenient));
|
||||
let out = d.join("strict.pdf");
|
||||
let strict = convert(&input, &out, true);
|
||||
assert_eq!(strict.status.code(), Some(3), "{}", stderr(&strict));
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
let json = report_json(&strict);
|
||||
assert_eq!(json["missing_pictures"][0]["reason"], "external_target");
|
||||
assert!(stderr(&strict).contains("external target"));
|
||||
@@ -246,19 +246,19 @@ fn bad_input_exits_1_with_the_usual_message_with_and_without_strict() {
|
||||
assert_eq!(plain.status.code(), Some(1), "{}", stderr(&plain));
|
||||
assert_eq!(strict.status.code(), Some(1), "{}", stderr(&strict));
|
||||
assert_eq!(stderr(&plain), stderr(&strict));
|
||||
assert!(stderr(&plain).starts_with("wordcraft-cli: "), "{}", stderr(&plain));
|
||||
assert!(stderr(&plain).starts_with("error: "), "{}", stderr(&plain));
|
||||
assert!(!d.join("a.pdf").exists() && !d.join("b.pdf").exists());
|
||||
}
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_with_another_output_type_exits_1_before_the_input_is_read() {
|
||||
fn strict_with_another_output_type_exits_2_before_the_input_is_read() {
|
||||
let d = dir("wrong-output");
|
||||
let missing = d.join("does-not-exist.docx");
|
||||
for out in ["out.docx", "out.txt", "out.odt"] {
|
||||
let r = convert(&missing, &d.join(out), true);
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains("--strict needs a .pdf or .png output"), "{text}");
|
||||
assert!(!d.join(out).exists());
|
||||
@@ -291,11 +291,11 @@ fn render_strict_refuses_an_uncovered_character_on_the_page_with_no_stdout_or_fi
|
||||
let input = two_page_input(&d, &format!("a{c}b"));
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty(), "{}", String::from_utf8_lossy(&r.stdout));
|
||||
assert!(!out.exists());
|
||||
let text = stderr(&r);
|
||||
assert!(text.contains(&format!("wordcraft-cli: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert!(text.contains(&format!("error: strict: 1 character cannot be drawn: {cp} (×1)")), "{text}");
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
eprintln!("{text}");
|
||||
|
||||
@@ -323,7 +323,7 @@ fn render_strict_refuses_a_corrupt_header_picture_and_bad_input_still_exits_1()
|
||||
std::fs::write(&input, docx_with_header_picture(b"corrupt bytes, not a picture")).unwrap();
|
||||
let out = d.join("out.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty());
|
||||
assert!(stderr(&r).contains("word/media/image2.bin (header2.xml)"), "{}", stderr(&r));
|
||||
assert!(!out.exists());
|
||||
@@ -341,16 +341,16 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
let d = dir("escape");
|
||||
let input = d.join("in.docx");
|
||||
// XML character references put a newline and U+202E in the target.
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let text = stderr(&r);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
// One human line for the picture, then the JSON line.
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines[0].starts_with("wordcraft-cli: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nwordcraft-cli: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(lines[0].starts_with("error: strict: 1 picture(s) left out: "), "{text}");
|
||||
assert!(lines[0].contains("\\nerror: strict: forged\\u{202e}gnp.png"), "{text}");
|
||||
assert!(!text.contains('\u{202e}'), "the raw bidi override reached the terminal");
|
||||
// The JSON keeps the raw value, escaped by the JSON encoder.
|
||||
let json = report_json(&r);
|
||||
@@ -363,14 +363,14 @@ fn a_picture_target_with_a_newline_and_a_bidi_override_cannot_forge_a_report_lin
|
||||
fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
let d = dir("run-escape");
|
||||
let input = d.join("in.docx");
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a wordcraft-cli: strict: forged[2J‮gnp.png")).unwrap();
|
||||
std::fs::write(&input, docx_with_external_picture("http://example.invalid/a error: strict: forged[2J‮gnp.png")).unwrap();
|
||||
let out = d.join("out.pdf");
|
||||
let cmd = format!("file.exportPdf={}", serde_json::json!({"path": out, "strict": true}));
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).arg("run").arg("--file").arg(&input).arg("--cmd").arg(cmd).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(1));
|
||||
let text = stderr(&r);
|
||||
assert_eq!(text.lines().count(), 1, "{text}");
|
||||
assert!(text.contains("\\nwordcraft-cli: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(text.contains("\\nerror: strict: forged") && text.contains("\\u{202e}"), "{text}");
|
||||
assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}'), "{text:?}");
|
||||
assert!(!out.exists());
|
||||
std::fs::remove_dir_all(d).unwrap();
|
||||
@@ -378,19 +378,20 @@ fn run_with_strict_cannot_forge_an_error_line_either() {
|
||||
|
||||
#[test]
|
||||
fn usage_errors_keep_their_line_breaks() {
|
||||
// Errors go to stderr with the usage after a blank line (`missing argument`, `unknown command`).
|
||||
// Errors go to stderr (clap's message, then its usage), exit 2.
|
||||
for args in [&["frobnicate"][..], &["convert"][..]] {
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).args(args).output().unwrap();
|
||||
let text = stderr(&r);
|
||||
assert_eq!(r.status.code(), Some(1), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 3, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l == "USAGE:"), "{args:?}: {text}");
|
||||
assert_eq!(r.status.code(), Some(2), "{args:?}: {text}");
|
||||
assert!(text.lines().count() > 2, "{args:?}: {text}");
|
||||
assert!(text.lines().any(|l| l.starts_with("Usage:")), "{args:?}: {text}");
|
||||
assert!(!text.contains("\\n"), "{args:?}: {text}");
|
||||
}
|
||||
// No arguments at all prints the usage as help, on stdout.
|
||||
// No arguments at all prints the help (on stderr, as clap does for a missing subcommand), exit 2.
|
||||
let r = Command::new(env!("CARGO_BIN_EXE_wordcraft-cli")).output().unwrap();
|
||||
assert_eq!(r.status.code(), Some(2));
|
||||
let all = format!("{}{}", String::from_utf8_lossy(&r.stdout), stderr(&r));
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l == "USAGE:"), "{all}");
|
||||
assert!(all.lines().count() > 3 && all.lines().any(|l| l.starts_with("Usage:")), "{all}");
|
||||
}
|
||||
|
||||
/// A minimal EMF (88-byte header, 100 mm square frame) with one EMR_EXTTEXTOUTW record showing
|
||||
@@ -444,7 +445,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
for out in ["out.pdf", "out.png"] {
|
||||
let out = d.join(out);
|
||||
let r = convert(&input, &out, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str(), "{}", stderr(&r));
|
||||
assert!(!out.exists(), "{} was written", out.display());
|
||||
// Without --strict it converts, the character a hollow box.
|
||||
@@ -454,7 +455,7 @@ fn a_character_in_a_metafile_pictures_text_fails_strict_like_the_pages_own() {
|
||||
}
|
||||
let out = d.join("p1.png");
|
||||
let r = render(&input, &out, &["--strict"]);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
assert!(r.stdout.is_empty() && !out.exists());
|
||||
assert_eq!(report_json(&r)["missing_glyphs"][0]["cp"], cp.as_str());
|
||||
// Text the faces cover passes.
|
||||
@@ -479,7 +480,7 @@ fn a_metafile_page_background_fails_strict_for_png_but_not_for_pdf() {
|
||||
std::fs::write(&input, serde_json::to_vec(&doc).unwrap()).unwrap();
|
||||
let png = d.join("out.png");
|
||||
let r = convert(&input, &png, true);
|
||||
assert_eq!(r.status.code(), Some(3), "{}", stderr(&r));
|
||||
assert_eq!(r.status.code(), Some(1), "{}", stderr(&r));
|
||||
let json = report_json(&r);
|
||||
assert_eq!(json["missing_pictures"][0]["part"], "bg.emf", "{}", stderr(&r));
|
||||
assert_eq!(json["missing_pictures"][0]["source_part"], "background");
|
||||
|
||||
@@ -71,6 +71,9 @@ fi
|
||||
|
||||
if [[ "$SKIP_BUILD" = 0 ]]; then
|
||||
(cd "$ROOT" && cargo build --release --locked ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"} -p wordcraft -p wordcraft-cli)
|
||||
# The man-and-completions example writes wordcraft-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.
|
||||
(cd "$ROOT" && cargo build --release --locked ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"} -p wordcraft-cli --example man-and-completions)
|
||||
fi
|
||||
# Cargo puts a cross build under target/<triple>/release.
|
||||
BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release"
|
||||
@@ -83,6 +86,21 @@ mkdir -p "$STAGE/bin" "$STAGE/share/applications" "$STAGE/share/mime/packages" "
|
||||
"$STAGE/share/icons" "$STAGE/share/doc/wordcraft"
|
||||
install -m 755 "$BIN/wordcraft" "$BIN/wordcraft-cli" "$STAGE/bin/"
|
||||
strip "$STAGE/bin/wordcraft" "$STAGE/bin/wordcraft-cli" 2>/dev/null || true
|
||||
# wordcraft-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 [[ ! -x "$CLI_DOCS" ]]; then
|
||||
echo "error: $CLI_DOCS is not built (cargo build --release -p wordcraft-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/wordcraft-cli.bash" "$STAGE/share/bash-completion/completions/wordcraft-cli"
|
||||
install -m 644 "$WORK/cli-docs/_wordcraft-cli" "$STAGE/share/zsh/site-functions/_wordcraft-cli"
|
||||
install -m 644 "$WORK/cli-docs/wordcraft-cli.fish" "$STAGE/share/fish/vendor_completions.d/wordcraft-cli.fish"
|
||||
# The desktop entry, MIME type and metainfo are the freedesktop files the Linux packages use.
|
||||
install -m 644 "$LINUX/$APP_ID.desktop" "$STAGE/share/applications/$APP_ID.desktop"
|
||||
install -m 644 "$LINUX/$APP_ID.mime.xml" "$STAGE/share/mime/packages/$APP_ID.xml"
|
||||
|
||||
@@ -92,6 +92,13 @@ contents:
|
||||
dst: /usr/share/doc/${NFPM_NAME}/
|
||||
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).
|
||||
- src: /usr/share/zsh/site-functions/_${NFPM_CLI}
|
||||
dst: /usr/share/zsh/vendor-completions/_${NFPM_CLI}
|
||||
type: symlink
|
||||
packager: deb
|
||||
|
||||
scripts:
|
||||
postinstall: packaging/linux/postinst.sh
|
||||
postremove: packaging/linux/postinst.sh
|
||||
|
||||
@@ -22,6 +22,16 @@ printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
cp "$CARGO_TARGET_DIR/release/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft-cli"
|
||||
chmod 755 "$CARGO_TARGET_DIR/release/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft-cli"
|
||||
# The man-and-completions example writes the files it does for a real build; this one writes placeholders.
|
||||
mkdir -p "$CARGO_TARGET_DIR/release/examples"
|
||||
cat >"$CARGO_TARGET_DIR/release/examples/man-and-completions" <<'EXAMPLE'
|
||||
#!/bin/sh
|
||||
mkdir -p "$1"
|
||||
for f in wordcraft-cli.bash _wordcraft-cli wordcraft-cli.fish wordcraft-cli.1 wordcraft-cli-run.1; do
|
||||
echo stub >"$1/$f"
|
||||
done
|
||||
EXAMPLE
|
||||
chmod 755 "$CARGO_TARGET_DIR/release/examples/man-and-completions"
|
||||
|
||||
# The tar format is first in package.sh's default set; a broken nightly tar aborted every run here.
|
||||
(cd "$ROOT" && bash packaging/linux/package.sh --skip-build --formats tar)
|
||||
|
||||
@@ -68,8 +68,13 @@ if [[ "$SKIP_BUILD" = 0 ]]; then
|
||||
else
|
||||
(cd "$ROOT" && cargo build --release --locked -p wordcraft -p wordcraft-cli)
|
||||
fi
|
||||
# The man-and-completions example writes wordcraft-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. It runs on the build
|
||||
# host, so a cross build still builds it for the host.
|
||||
(cd "$ROOT" && cargo build --release --locked -p wordcraft-cli --example man-and-completions)
|
||||
fi
|
||||
BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release"
|
||||
HOST_BIN="$CARGO_TARGET_DIR/release"
|
||||
WORK="$CARGO_TARGET_DIR/linux-package"
|
||||
STAGE="$WORK/root"
|
||||
rm -rf "$WORK"
|
||||
@@ -78,6 +83,19 @@ rm -rf "$WORK"
|
||||
install -Dm755 "$BIN/wordcraft" "$STAGE/usr/bin/wordcraft"
|
||||
install -Dm755 "$BIN/wordcraft-cli" "$STAGE/usr/bin/wordcraft-cli"
|
||||
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/wordcraft" "$STAGE/usr/bin/wordcraft-cli" 2>/dev/null || true
|
||||
# wordcraft-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). zsh reads site-functions on Fedora and openSUSE; the deb also links the
|
||||
# completion into Debian's vendor-completions (nfpm.yaml).
|
||||
CLI_DOCS="$HOST_BIN/examples/man-and-completions"
|
||||
if [[ ! -x "$CLI_DOCS" ]]; then
|
||||
echo "error: $CLI_DOCS is not built (cargo build --release -p wordcraft-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/wordcraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/wordcraft-cli"
|
||||
install -Dm644 "$WORK/cli-docs/_wordcraft-cli" "$STAGE/usr/share/zsh/site-functions/_wordcraft-cli"
|
||||
install -Dm644 "$WORK/cli-docs/wordcraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/wordcraft-cli.fish"
|
||||
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.wordcraft.nightly-v1|' \
|
||||
@@ -163,6 +181,13 @@ if has deb || has rpm; then
|
||||
nightly_launcher "$NFPM_STAGE/usr/bin/$NFPM_BIN"
|
||||
rm -f "$NFPM_STAGE/usr/bin/wordcraft"
|
||||
mv "$NFPM_STAGE/usr/bin/wordcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
|
||||
# The man pages and completions name the command they document: rename them for the nightly's command.
|
||||
for f in "$NFPM_STAGE"/usr/share/man/man1/wordcraft-cli*.1 "$NFPM_STAGE/usr/share/bash-completion/completions/wordcraft-cli" \
|
||||
"$NFPM_STAGE/usr/share/zsh/site-functions/_wordcraft-cli" "$NFPM_STAGE/usr/share/fish/vendor_completions.d/wordcraft-cli.fish"; do
|
||||
sed -e "s/wordcraft-cli/$NFPM_CLI/g" -e "s/wordcraft\\\\-cli/${NFPM_CLI//-/\\\\-}/g" "$f" >"${f//wordcraft-cli/$NFPM_CLI}.tmp"
|
||||
rm -f "$f"
|
||||
mv "${f//wordcraft-cli/$NFPM_CLI}.tmp" "${f//wordcraft-cli/$NFPM_CLI}"
|
||||
done
|
||||
mv "$NFPM_STAGE/usr/share/doc/wordcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
|
||||
sed -e "s#^Exec=wordcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
|
||||
-e "s|^TryExec=wordcraft$|TryExec=$NFPM_BIN|" \
|
||||
|
||||
Reference in New Issue
Block a user