diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index f442059bb..77f6c85c0 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -24,6 +24,24 @@ jobs: with: extra-checks-script: packaging/check-app-specific.sh + freebsd-layout: + # The FreeBSD package layout, with stub binaries standing in for the build: RFC-0018 rule 1.9 + # puts figcraft-cli's man pages and its bash, zsh and fish completions in it. + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: FreeBSD package layout (dry run) + run: | + CARGO_TARGET_DIR="$RUNNER_TEMP/figcraft-target" bash packaging/freebsd/package.sh --dry-run + listing="$(tar -tzf "$RUNNER_TEMP"/figcraft-target/freebsd-package/figcraft-*-freebsd-x86_64.tar.gz)" + for f in man/man1/figcraft-cli.1 share/bash-completion/completions/figcraft-cli \ + share/zsh/site-functions/_figcraft-cli share/fish/vendor_completions.d/figcraft-cli.fish; do + grep -q "/$f$" <<<"$listing" || { echo "::error::$f is missing from the FreeBSD package"; exit 1; } + done + windows-install-policy: timeout-minutes: 10 name: Windows installation policy (no app build) diff --git a/Cargo.toml b/Cargo.toml index e62a7d019..985e079d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,7 +82,7 @@ craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9 kurbo = { version = "0.13", features = ["serde"] } thiserror = "2" # Command-line parsing for figcraft-cli (craft-contrib RFC-0012: clap derive, as photocraft does). -clap = { version = "4", features = ["derive"] } +clap = { version = "4", features = ["derive", "env"] } serde = { version = "1", features = ["derive", "rc"] } serde_json = { version = "1", features = ["float_roundtrip"] } regex = "1.13" diff --git a/ROADMAP.md b/ROADMAP.md index d32e3f09e..f5feb650f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged | | 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged | | 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | diff --git a/apps/figcraft-cli/Cargo.toml b/apps/figcraft-cli/Cargo.toml index 16c228681..f0c28add4 100644 --- a/apps/figcraft-cli/Cargo.toml +++ b/apps/figcraft-cli/Cargo.toml @@ -6,6 +6,10 @@ license.workspace = true publish = false description = "FigCraft command line: info, export, convert, render, scripted commands, MCP server, perf" +[lib] +name = "figcraft_cli" +path = "src/lib.rs" + [[bin]] name = "figcraft-cli" path = "src/main.rs" diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index b8372ece4..b1a878574 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -16,12 +16,19 @@ use figcraft_doc::{PrintSettings, VdCompat}; /// (best effort; `info` lists what wasn't imported), .sketch (Sketch 48 or newer, best effort), /// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer). #[derive(Parser)] -#[command(name = "figcraft-cli", bin_name = "figcraft-cli", version, arg_required_else_help = true, after_help = "See docs/cli.md and docs/mcp.md.")] +#[command( + name = "figcraft-cli", + bin_name = "figcraft-cli", + version, + propagate_version = true, + arg_required_else_help = true, + after_help = "Exit status:\n 0 success\n 1 a command failed\n 2 usage error\n\nA process ended by a signal exits 128 + the signal number (130 for Ctrl-C), as in the shell.\n\nSee docs/cli.md and docs/mcp.md." +)] pub struct Cli { /// Lay text out with the fonts built into FigCraft only, for renders that match on every - /// machine (or set FIGCRAFT_NO_SYSTEM_FONTS=1). Otherwise installed fonts are indexed the - /// first time text is laid out, as in the app - #[arg(long, global = true)] + /// machine (FIGCRAFT_NO_SYSTEM_FONTS=1 does the same). Otherwise installed fonts are indexed + /// the first time text is laid out, as in the app + #[arg(long, global = true, env = "FIGCRAFT_NO_SYSTEM_FONTS", value_parser = env_flag)] pub no_system_fonts: bool, #[command(subcommand)] pub command: Command, @@ -146,6 +153,9 @@ pub struct ConvertArgs { /// The file to write; its extension picks the format #[arg(value_name = "OUT")] pub output: String, + /// Allow OUT to be the file IN, replacing it + #[arg(long)] + pub in_place: bool, #[command(flatten)] pub roots: RootArgs, } @@ -183,6 +193,9 @@ pub struct RunArgs { /// Save the result here, by extension #[arg(long, value_name = "FILE")] pub out: Option, + /// Allow --out to be the --in file, replacing it + #[arg(long, requires_all = ["input", "out"])] + pub in_place: bool, #[command(flatten)] pub roots: RootArgs, } @@ -234,6 +247,9 @@ pub struct PublishArgs { /// The server, ws://host:port/ (optionally ?key=KEY) #[arg(long, value_name = "URL")] pub server: String, + /// The server's key, when the address has none (FIGCRAFT_SERVER_KEY) + #[arg(long, value_name = "KEY", env = "FIGCRAFT_SERVER_KEY", hide_env_values = true)] + pub key: Option, } #[derive(Subcommand)] @@ -293,6 +309,19 @@ fn scale(s: &str) -> Result { s.trim_end_matches('x').parse::().ok().filter(|v| v.is_finite() && *v > 0.0 && *v <= 64.0).ok_or(ValueError::Scale) } +/// `FIGCRAFT_NO_SYSTEM_FONTS`: the usual boolean spellings; an empty value is unset (RFC-0018 rule 1.7). +fn env_flag(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "" | "0" | "false" | "no" | "off" | "n" | "f" => Ok(false), + "1" | "true" | "yes" | "on" | "y" | "t" => Ok(true), + _ => Err(NotBoolean), + } +} + +#[derive(Debug, thiserror::Error)] +#[error("must be 1, 0, true, false, yes, no, on or off")] +pub struct NotBoolean; + fn bleed(s: &str) -> Result { PrintSettings::parse_length(s).filter(|b| *b <= PrintSettings::MAX_BLEED).ok_or(ValueError::Bleed) } diff --git a/apps/figcraft-cli/src/files.rs b/apps/figcraft-cli/src/files.rs index 5f4a006f4..04f9bc10c 100644 --- a/apps/figcraft-cli/src/files.rs +++ b/apps/figcraft-cli/src/files.rs @@ -2,13 +2,12 @@ use std::ffi::OsStr; use std::path::Path; -use std::process::ExitCode; use figcraft_doc::{Document, ExportFormat, ExportSetting, NodeId, NodeKind, PrintSettings, VdCompat}; use figcraft_engine::{BatchScope, BatchStep, Session}; use serde_json::{Value, json}; -use crate::{CliError, CliResult}; +use crate::{CliError, CliResult, Io}; /// A document's or plugin's text as a terminal should show it: control characters escaped, and /// everything else (quotes, backslashes in paths) left as it is. @@ -16,11 +15,11 @@ pub(crate) fn plain(text: &str) -> String { text.chars().map(|c| if c.is_control() { c.escape_default().to_string() } else { c.to_string() }).collect() } -pub fn load(path: &str) -> CliResult { +pub fn load(path: &str, io: &mut Io) -> CliResult { let (doc, notes) = load_noted(path)?; if ext(path) == "penpot" { for note in notes { - eprintln!("note: {note}"); + errln!(io, "note: {note}"); } } Ok(doc) @@ -115,7 +114,7 @@ fn encode(doc: &Document, pix: &figcraft_render::Pixmap, e: &str) -> CliResult CliResult<()> { +pub fn write_doc(doc: &Document, page: NodeId, out: &str, io: &mut Io) -> CliResult<()> { let e = ext(out); let bytes = match e.as_str() { "figcraft" => { @@ -131,26 +130,26 @@ pub fn write_doc(doc: &Document, page: NodeId, out: &str) -> CliResult<()> { .into_bytes(), "png" | "jpg" | "jpeg" | "webp" => encode(doc, &render_page(doc, page, 1.0)?, &e)?, "pdf" => page_pdf(doc, page, &PrintSettings::default())?, - "fig" => fig_bytes(doc)?, - "penpot" => penpot_bytes(doc)?, + "fig" => fig_bytes(doc, io)?, + "penpot" => penpot_bytes(doc, io)?, other => return Err(CliError::Usage(format!("unknown output format `.{other}` (figcraft, json, svg, png, jpg, webp, pdf, fig, penpot)"))), }; write(out, &bytes) } /// `doc` as a `.fig` file (experimental), printing what was left out. -fn fig_bytes(doc: &Document) -> CliResult> { +fn fig_bytes(doc: &Document, io: &mut Io) -> CliResult> { let (bytes, warnings) = figcraft_engine::cmd::file::fig_bytes(doc).map_err(|e| CliError::Failed(e.to_string()))?; for w in warnings { - eprintln!("note: {w}"); + errln!(io, "note: {w}"); } Ok(bytes) } -fn penpot_bytes(doc: &Document) -> CliResult> { +fn penpot_bytes(doc: &Document, io: &mut Io) -> CliResult> { let (bytes, warnings) = figcraft_engine::cmd::file::penpot_bytes(doc).map_err(|e| CliError::Failed(e.to_string()))?; for w in warnings { - eprintln!("note: {w}"); + errln!(io, "note: {w}"); } Ok(bytes) } @@ -170,7 +169,7 @@ fn page_pdf(doc: &Document, page: NodeId, print: &PrintSettings) -> CliResult CliResult { +pub fn info(path: &str, as_json: bool, io: &mut Io) -> CliResult { let (doc, notes) = load_noted(path)?; let pages: Vec = doc .pages @@ -201,13 +200,14 @@ pub fn info(path: &str, as_json: bool) -> CliResult { "missingFonts": missing.iter().map(|m| json!({"family": m.family, "layers": m.layers})).collect::>(), }); if as_json { - println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default()); - return Ok(ExitCode::SUCCESS); + outln!(io, "{}", serde_json::to_string_pretty(&v).unwrap_or_default()); + return Ok(0); } for n in ¬es { - eprintln!("note: {}", plain(&n.to_string())); + errln!(io, "note: {}", plain(&n.to_string())); } - println!( + outln!( + io, "{} — {} ({} nodes, {} styles, {} variables, {} images)", plain(path), plain(&doc.name), @@ -217,9 +217,10 @@ pub fn info(path: &str, as_json: bool) -> CliResult { doc.images.len() ); for p in &pages { - println!("page {} \"{}\": {} nodes, {} top-level", p["id"], plain(p["name"].as_str().unwrap_or("")), p["nodes"], p["topLevel"]); + outln!(io, "page {} \"{}\": {} nodes, {} top-level", p["id"], plain(p["name"].as_str().unwrap_or("")), p["nodes"], p["topLevel"]); for f in p["frames"].as_array().into_iter().flatten() { - println!( + outln!( + io, " {} {} \"{}\" {}×{}", f["id"], f["type"].as_str().unwrap_or(""), @@ -231,9 +232,9 @@ pub fn info(path: &str, as_json: bool) -> CliResult { } for m in &missing { let layers = if m.layers == 1 { "text layer" } else { "text layers" }; - println!("missing font \"{}\": {} {layers} (drawn in a fallback font)", plain(&m.family), m.layers); + outln!(io, "missing font \"{}\": {} {layers} (drawn in a fallback font)", plain(&m.family), m.layers); } - Ok(ExitCode::SUCCESS) + Ok(0) } /// The file name a layer exports to: the app's rule ([`figcraft_engine::cmd::file::safe_file_name`], @@ -260,18 +261,18 @@ pub struct Target { pub vd_compat: VdCompat, } -pub fn export(file: &str, out: &str, t: &Target) -> CliResult { - let doc = load(file)?; +pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult { + let doc = load(file, io)?; // `.fig`: the whole file. if t.format.as_deref().map_or(ext(out) == "fig", |f| f.eq_ignore_ascii_case("fig")) { - write(out, &fig_bytes(&doc)?)?; - println!("{out}"); - return Ok(ExitCode::SUCCESS); + write(out, &fig_bytes(&doc, io)?)?; + outln!(io, "{out}"); + return Ok(0); } if t.format.as_deref().map_or(ext(out) == "penpot", |f| f.eq_ignore_ascii_case("penpot")) { - write(out, &penpot_bytes(&doc)?)?; - println!("{out}"); - return Ok(ExitCode::SUCCESS); + write(out, &penpot_bytes(&doc, io)?)?; + outln!(io, "{out}"); + return Ok(0); } let page = page_named(&doc, t.page.as_deref())?; let (scale, node, print) = (t.scale, t.node.as_deref(), &t.print); @@ -282,12 +283,12 @@ pub fn export(file: &str, out: &str, t: &Target) -> CliResult { }; let target = node.map(|q| find_node(&doc, page, q)).transpose()?; let single = image_format(&ext(out)).is_some(); - let bytes_of = |ids: &[NodeId]| { + let mut bytes_of = |ids: &[NodeId]| { let setting = ExportSetting { format: fmt, print: *print, vd_compat: t.vd_compat, ..Default::default() }; let (bytes, warnings) = figcraft_engine::cmd::file::export_file(&doc, ids, &setting, scale).map_err(|e| CliError::Failed(e.to_string()))?; // What an Android Vector Drawable changed or left out, like the .fig notes. for w in warnings { - eprintln!("note: {w}"); + errln!(io, "note: {w}"); } Ok::<_, CliError>(bytes) }; @@ -298,8 +299,8 @@ pub fn export(file: &str, out: &str, t: &Target) -> CliResult { None => bytes_of(&children(&doc, page))?, }; write(out, &bytes)?; - println!("{out}"); - return Ok(ExitCode::SUCCESS); + outln!(io, "{out}"); + return Ok(0); } figcraft_engine::file_access::create_dir_all(out).map_err(|e| CliError::Failed(e.to_string()))?; let ids = match target { @@ -329,9 +330,9 @@ pub fn export(file: &str, out: &str, t: &Target) -> CliResult { }; let path = Path::new(out).join(format!("{name}.{}", fmt.ext())).to_string_lossy().into_owned(); write(&path, &bytes_of(&[id])?)?; - println!("{path}"); + outln!(io, "{path}"); } - Ok(ExitCode::SUCCESS) + Ok(0) } fn refuse_dropping_images(input: &str, out: &str, images_left_out: usize) -> CliResult<()> { @@ -353,12 +354,12 @@ fn refuse_dropping_images_from_script(input: Option<(&str, usize)>, active: &fig Ok(()) } -pub fn convert(input: &str, out: &str) -> CliResult { +pub fn convert(input: &str, out: &str, io: &mut Io) -> CliResult { let (loaded, _) = figcraft_engine::cmd::file::load_path(input, None).map_err(|e| CliError::Failed(format!("can't open {input}: {e}")))?; refuse_dropping_images(input, out, loaded.images_past_budget)?; if ext(input) == "penpot" { for note in &loaded.issues { - eprintln!("note: {note}"); + errln!(io, "note: {note}"); } } let doc = loaded.doc; @@ -367,13 +368,13 @@ pub fn convert(input: &str, out: &str) -> CliResult { .filter(|p| doc.pages.contains(p)) .or_else(|| doc.first_page()) .ok_or_else(|| CliError::Failed("the document has no pages".into()))?; - write_doc(&doc, page, out)?; - println!("{out}"); - Ok(ExitCode::SUCCESS) + write_doc(&doc, page, out, io)?; + outln!(io, "{out}"); + Ok(0) } -pub fn render(file: &str, out: &str, scale: f64, page: Option<&str>) -> CliResult { - let doc = load(file)?; +pub fn render(file: &str, out: &str, scale: f64, page: Option<&str>, io: &mut Io) -> CliResult { + let doc = load(file, io)?; let page = page_named(&doc, page)?; let e = ext(out); if !matches!(e.as_str(), "png" | "jpg" | "jpeg" | "webp") { @@ -381,8 +382,8 @@ pub fn render(file: &str, out: &str, scale: f64, page: Option<&str>) -> CliResul } let pix = render_page(&doc, page, scale)?; write(out, &encode(&doc, &pix, &e)?)?; - println!("{out} ({}×{})", pix.width(), pix.height()); - Ok(ExitCode::SUCCESS) + outln!(io, "{out} ({}×{})", pix.width(), pix.height()); + Ok(0) } /// Parse a script: a JSON array of steps, `{"commands": [...]}`, or JSON lines. @@ -422,7 +423,7 @@ pub fn parse_script(text: &str) -> Result, String> { /// file is refused before it is read (#1114). pub const MAX_SCRIPT: u64 = 1 << 30; -pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>) -> CliResult { +pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>, io: &mut Io) -> CliResult { let bytes = figcraft_engine::file_access::read_capped(script, MAX_SCRIPT).map_err(|e| CliError::Failed(e.to_string()))?; let text = String::from_utf8(bytes).map_err(|_| CliError::Failed(format!("{script}: not UTF-8")))?; let steps = parse_script(&text).map_err(|e| CliError::Failed(format!("{script}: {e}")))?; @@ -453,14 +454,14 @@ pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>) -> CliRe if let Err(e) = outcome { let cmd = steps.get(failed_at).map_or("", |step| step.command.as_str()); let i = failed_at; - println!("{}", json!({"step": i, "command": cmd, "ok": false, "error": e.to_string(), "rolledBack": true})); + outln!(io, "{}", json!({"step": i, "command": cmd, "ok": false, "error": e.to_string(), "rolledBack": true})); // Plugin-supplied text: escape terminal controls and line breaks. - eprintln!("error: step {i} ({}) failed: {}", plain(cmd), plain(&e.to_string())); - eprintln!("the script's document changes were rolled back"); - return Ok(ExitCode::from(1)); + errln!(io, "error: step {i} ({}) failed: {}", plain(cmd), plain(&e.to_string())); + errln!(io, "the script's document changes were rolled back"); + return Ok(1); } for (i, (step, v)) in steps.iter().zip(scope.results()).enumerate() { - println!("{}", json!({"step": i, "command": step.command, "ok": true, "result": v})); + outln!(io, "{}", json!({"step": i, "command": step.command, "ok": true, "result": v})); } if let Some(out) = out { let ds = s.ds().map_err(|e| CliError::Failed(e.to_string()))?; @@ -469,17 +470,17 @@ pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>) -> CliRe // Through the engine, so the version history is kept. write(out, &figcraft_engine::cmd::file::file_bytes_at(ds, out).map_err(|e| CliError::Failed(e.to_string()))?)?; } else { - write_doc(&ds.doc, ds.page, out)?; + write_doc(&ds.doc, ds.page, out, io)?; } - eprintln!("wrote {out}"); + errln!(io, "wrote {out}"); } - Ok(ExitCode::SUCCESS) + Ok(0) } /// Link the components of `file` (a `.figcraft`) to their code as `mappings` (a /// `figcraft.connect.json`) says, and save it in place unless `dry_run`. Prints what was linked; /// entries that were skipped are warnings on stderr, and linking nothing fails (exit code 1). -pub fn connect_publish(file: &str, mappings: &str, dry_run: bool) -> CliResult { +pub fn connect_publish(file: &str, mappings: &str, dry_run: bool, io: &mut Io) -> CliResult { if ext(file) != "figcraft" { return Err(CliError::Usage(format!("{file}: connect publish saves code links in a .figcraft file"))); } @@ -487,25 +488,32 @@ pub fn connect_publish(file: &str, mappings: &str, dry_run: bool) -> CliResult { + &mut Io { out: &mut Vec::new(), err: &mut Vec::new() } + }; + } + use super::*; /// `info` and a script's failure print what a file and its steps name, controls escaped. @@ -516,8 +524,8 @@ mod tests { let (svg, script) = (dir.join("a.svg"), dir.join("s.json")); std::fs::write(&svg, r#""#).unwrap(); std::fs::write(&script, r#"[{"command":"no.such\u001b"}]"#).unwrap(); - assert_eq!(info(svg.to_str().unwrap(), false).unwrap(), ExitCode::SUCCESS); - assert_eq!(run_script(script.to_str().unwrap(), None, None).unwrap(), ExitCode::from(1)); + assert_eq!(info(svg.to_str().unwrap(), false, io!()).unwrap(), 0); + assert_eq!(run_script(script.to_str().unwrap(), None, None, io!()).unwrap(), 1); let _ = std::fs::remove_dir_all(&dir); } @@ -602,7 +610,7 @@ mod tests { for ext in ["svg", "pdf"] { let path = dir.join(format!("previous.{ext}")); std::fs::write(&path, b"previous export").unwrap(); - let CliError::Failed(error) = write_doc(&doc, page, path.to_str().unwrap()).unwrap_err() else { + let CliError::Failed(error) = write_doc(&doc, page, path.to_str().unwrap(), io!()).unwrap_err() else { panic!("depth overflow must be an operation failure"); }; assert!(error.contains("maximum export depth of 256"), "{ext}: {error}"); @@ -629,7 +637,7 @@ mod tests { bad.push("/dev/zero".into()); } for path in bad { - let Err(CliError::Failed(e)) = run_script(&path, None, None) else { panic!("{path} ran") }; + let Err(CliError::Failed(e)) = run_script(&path, None, None, io!()) else { panic!("{path} ran") }; assert!(e.contains("is a folder, not a file") || e.contains("isn't a regular file"), "{path}: {e}"); } std::fs::remove_dir_all(dir).unwrap(); @@ -658,16 +666,16 @@ mod tests { doc.nodes().filter(|n| n.name == "Card").map(|n| n.code_links.len()).sum::() }; - assert_eq!(connect_publish(file, mappings, true).unwrap(), ExitCode::SUCCESS); + assert_eq!(connect_publish(file, mappings, true, io!()).unwrap(), 0); assert_eq!(links(), 0, "a dry run saves nothing"); - assert_eq!(connect_publish(file, mappings, false).unwrap(), ExitCode::SUCCESS, "an unknown component is only a warning"); + assert_eq!(connect_publish(file, mappings, false, io!()).unwrap(), 0, "an unknown component is only a warning"); assert_eq!(links(), 1, "Card is linked to its code in the saved file"); let none = dir.join("none.json"); std::fs::write(&none, json!({"version": 1, "links": [link("Nope")]}).to_string()).unwrap(); - assert_eq!(connect_publish(file, none.to_str().unwrap(), false).unwrap(), ExitCode::from(1)); - assert!(matches!(connect_publish(dir.join("ui.svg").to_str().unwrap(), mappings, false), Err(CliError::Usage(_)))); - assert!(matches!(connect_publish(file, dir.join("missing.json").to_str().unwrap(), false), Err(CliError::Failed(_)))); + assert_eq!(connect_publish(file, none.to_str().unwrap(), false, io!()).unwrap(), 1); + assert!(matches!(connect_publish(dir.join("ui.svg").to_str().unwrap(), mappings, false, io!()), Err(CliError::Usage(_)))); + assert!(matches!(connect_publish(file, dir.join("missing.json").to_str().unwrap(), false, io!()), Err(CliError::Failed(_)))); std::fs::remove_dir_all(dir).unwrap(); } @@ -687,7 +695,7 @@ mod tests { ) .unwrap(); let out = dir.join("out.figcraft"); - assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap(), ExitCode::SUCCESS); + assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 0); let mut s = Session::empty(); s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap(); @@ -717,7 +725,7 @@ mod tests { ) .unwrap(); let out = dir.join("out.figcraft"); - assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap(), ExitCode::SUCCESS); + assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 0); let mut s = Session::empty(); s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap(); @@ -734,7 +742,7 @@ mod tests { let dir = temp_dir("run-dup-name"); let script = dir.join("script.json"); std::fs::write(&script, r#"[{"command": "select.none", "as": "a"}, {"command": "select.none", "as": "a"}]"#).unwrap(); - let Err(CliError::Failed(e)) = run_script(script.to_str().unwrap(), None, None) else { panic!("a name twice must fail") }; + let Err(CliError::Failed(e)) = run_script(script.to_str().unwrap(), None, None, io!()) else { panic!("a name twice must fail") }; assert!(e.contains("step 1: `as` \"a\" is already step 0's name"), "{e}"); std::fs::remove_dir_all(dir).unwrap(); } @@ -754,7 +762,7 @@ mod tests { .unwrap(); let out = dir.join("out.figcraft"); // The failure is the script's, not the call's: the CLI reports it and exits non-zero. - assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap(), ExitCode::from(1)); + assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 1); assert!(!out.exists(), "a script that failed writes nothing"); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/apps/figcraft-cli/src/lib.rs b/apps/figcraft-cli/src/lib.rs new file mode 100644 index 000000000..c555c6cac --- /dev/null +++ b/apps/figcraft-cli/src/lib.rs @@ -0,0 +1,257 @@ +//! `figcraft-cli`: FigCraft without a window. Inspect, export, convert and render documents, run +//! command scripts, list commands, serve MCP on stdio, publish plugins to a server's plugin +//! directory, publish code connect mappings to a design file and measure performance. `run` is the +//! whole program, so it can be tested in-process as well as through the binary. The conventions are +//! RFC-0018's: exit 0, 1 (a command failed) or 2 (a usage error), results on stdout, +//! `error: ` on stderr. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// Writes a line to `$io.out`. A closed pipe (`figcraft-cli commands | head`) is not worth an error: +/// the rest of the output is dropped. +macro_rules! outln { + ($io:expr) => { + drop(writeln!($io.out)) + }; + ($io:expr, $($arg:tt)*) => { + drop(writeln!($io.out, $($arg)*)) + }; +} + +/// Writes a line to `$io.err`. +macro_rules! errln { + ($io:expr, $($arg:tt)*) => { + drop(writeln!($io.err, $($arg)*)) + }; +} + +mod args; +mod files; +mod perf; + +use std::ffi::OsString; +use std::io::Write; + +use args::{Cli, Command, ConnectCommand, PluginCommand, RootArgs}; +use serde_json::{Value, json}; + +/// The automation roots a file subcommand was given, if any. Omitting both leaves the run +/// unconfined, as before; giving either confines every file the subcommand touches (#833). +fn roots_of(r: &RootArgs) -> CliResult> { + if r.automation_read_root.is_empty() && r.automation_write_root.is_empty() { + return Ok(None); + } + Ok(Some(figcraft_engine::file_access::Roots::new(&r.automation_read_root, &r.automation_write_root).map_err(CliError::Failed)?)) +} + +/// Runs `f` confined to the roots `r` carries. +fn confined(r: &RootArgs, f: impl FnOnce() -> CliResult) -> CliResult { + let roots = roots_of(r)?.map(std::sync::Arc::new); + figcraft_engine::file_access::confined(roots.as_ref(), f) +} + +/// Why a command did not succeed. The variant is the exit code: a usage error is 2, a failure 1. +#[derive(Debug, thiserror::Error)] +pub enum CliError { + /// Bad arguments found after parsing (an output extension no format writes): exit code 2. + #[error("{0}")] + Usage(String), + /// The operation failed: exit code 1. + #[error("{0}")] + Failed(String), +} + +/// The two output streams a command writes to: results to `out`, diagnostics to `err`. +pub(crate) struct Io<'a> { + pub(crate) out: &'a mut dyn Write, + pub(crate) err: &'a mut dyn Write, +} + +impl From for CliError { + fn from(s: String) -> Self { + CliError::Failed(s) + } +} + +pub type CliResult = Result; + +fn dispatch(cli: Cli, io: &mut Io) -> CliResult { + check(&cli.command)?; + if !cli.no_system_fonts { + // Text lays out with the installed fonts, like the desktop app, so headless renders and + // auto layout sizes match what users see. + figcraft_text::scan_system_fonts_on_demand(); + } else { + // Nothing scans them then, not even a `.sketch` import matching its fonts. + figcraft_text::opt_out_of_system_fonts(); + } + match cli.command { + Command::Info(a) => confined(&a.roots, || files::info(&a.file, a.json, io)), + Command::Export(a) => { + let target = + files::Target { print: a.print(), vd_compat: a.vd_compat, scale: a.scale.scale, format: a.format, page: a.page, node: a.node }; + confined(&a.roots, || files::export(&a.file, &a.out, &target, io)) + } + Command::Convert(a) => confined(&a.roots, || files::convert(&a.input, &a.output, io)), + Command::Render(a) => confined(&a.roots, || files::render(&a.file, &a.out, a.scale.scale, a.page.as_deref(), io)), + Command::Run(a) => confined(&a.roots, || files::run_script(&a.script, a.input.as_deref(), a.out.as_deref(), io)), + Command::Commands(a) => { + commands(a.json, a.filter.as_deref(), io); + Ok(0) + } + // `--attach` conflicts with the roots: the app runs the commands, only its own roots can confine them. + Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, roots_of(&a.roots)?, io), + Command::Plugin { command: PluginCommand::Publish(a) } => publish_plugin(&a.folder, &a.server, a.key.as_deref(), io), + Command::Connect { command: ConnectCommand::Publish(a) } => { + confined(&a.roots, || files::connect_publish(&a.file, &a.mappings, a.dry_run, io)) + } + Command::Perf(a) => { + let sizes: Vec = a.layers.into_iter().map(|n| n.clamp(10, 2_000_000)).collect(); + let instances: Vec = a.instances.into_iter().filter(|n| *n > 0).map(|n| n.min(100_000)).collect(); + perf::run(&sizes, &instances, !cli.no_system_fonts, io) + } + } +} + +fn commands(as_json: bool, filter: Option<&str>, io: &mut Io) { + let f = filter.map(str::to_lowercase).unwrap_or_default(); + let list: Vec<&figcraft_engine::CommandSpec> = figcraft_engine::all_commands() + .iter() + .filter(|c| f.is_empty() || c.id.to_lowercase().contains(&f) || c.label.to_lowercase().contains(&f) || c.params.to_lowercase().contains(&f)) + .collect(); + if as_json { + let v: Vec = list + .iter() + .map(|c| json!({"id": c.id, "label": c.label, "params": c.params, "menu": c.menu(), "shortcut": c.shortcut(), "undoable": c.history})) + .collect(); + outln!(io, "{}", serde_json::to_string_pretty(&v).unwrap_or_default()); + return; + } + for c in list { + let sc = c.shortcut().map(|s| format!(" ({s})")).unwrap_or_default(); + let undo = if c.history { "*" } else { "" }; + outln!(io, "{}{undo} {}{sc}\n {}", c.id, c.label, c.params); + } +} + +/// Publish the plugin folder `folder` to the plugin directory at `server` (the key from the address +/// or `FIGCRAFT_SERVER_KEY`); never prints the key. +fn publish_plugin(folder: &str, server: &str, key: Option<&str>, io: &mut Io) -> CliResult { + let address = server.split('?').next().unwrap_or_default().to_string(); + let server = match key.map(str::trim) { + Some(key) if !server.contains("key=") && !key.is_empty() => format!("{address}?key={key}"), + _ => server.to_string(), + }; + let mut h = figcraft_mcp::Headless::new(); + use figcraft_mcp::Backend as _; + let r = h.call("engine.execute", json!({"command": "plugin.directory.publish", "params": {"path": folder, "server": server}}))?; + let e = &r["published"]; + outln!( + io, + "Published {} {} ({}) to {address}: {} bytes, SHA-256 {}", + e["name"].as_str().unwrap_or_default(), + e["version"].as_str().unwrap_or_default(), + e["id"].as_str().unwrap_or_default(), + e["bytes"], + e["sha256"].as_str().unwrap_or_default() + ); + Ok(0) +} + +fn mcp(attach: Option<&str>, timeout: Option, roots: Option, io: &mut Io) -> CliResult { + let backend: Box = match attach { + Some(addr) => { + let no_app = |e: std::io::Error| format!("can't reach the FigCraft app at {addr}: {e} (start it with `figcraft --control PORT`)"); + let b = figcraft_mcp::Attached::connect(addr).map_err(no_app)?; + match timeout { + Some(secs) => Box::new(b.with_timeout(std::time::Duration::from_secs(secs)).map_err(no_app)?), + None => Box::new(b), + } + } + None => Box::new(figcraft_mcp::Headless::new()), + }; + errln!(io, "figcraft MCP server ({}) on stdio", backend.describe()); + if let Some(r) = &roots { + errln!(io, "file access confined to {}", r.to_json()); + } + let mut server = figcraft_mcp::Server::new(backend).with_roots(roots); + let stdin = std::io::stdin(); + let stdout = std::io::stdout(); + server.serve(stdin.lock(), stdout.lock()).map_err(|e| format!("stdio: {e}"))?; + Ok(0) +} + +/// What the arguments can't say alone: an output that would replace its input needs `--in-place`. +fn check(command: &Command) -> CliResult<()> { + let refuse = |flag: &str, path: &str, input: &str, allowed: bool| -> CliResult<()> { + if !same_file(path, input) { + return Ok(()); + } + if allowed { + return Ok(()); + } + Err(CliError::Usage(format!("{flag} {path} is the input, which it would replace: choose another file, or pass --in-place"))) + }; + match command { + Command::Convert(a) => refuse("OUT", &a.output, &a.input, a.in_place)?, + Command::Run(a) => { + if let (Some(out), Some(input)) = (&a.out, &a.input) { + refuse("--out", out, input, a.in_place)?; + } + } + Command::Export(a) => refuse("--out", &a.out, &a.file, false)?, + Command::Render(a) => refuse("--out", &a.out, &a.file, false)?, + _ => {} + } + if let Command::Convert(a) = command + && a.in_place + && !same_file(&a.output, &a.input) + { + return Err(CliError::Usage("--in-place is for an OUT that is the IN, and this is another file".into())); + } + if let Command::Run(a) = command + && a.in_place + && !matches!((&a.out, &a.input), (Some(out), Some(input)) if same_file(out, input)) + { + return Err(CliError::Usage("--in-place is for an --out that is the --in file, and this is another file".into())); + } + Ok(()) +} + +/// Whether two paths name the same existing file, through links and `.` and `..`. +fn same_file(a: &str, b: &str) -> bool { + matches!((std::fs::canonicalize(a), std::fs::canonicalize(b)), (Ok(a), Ok(b)) if a == b) +} + +/// Run the CLI on its arguments (without the program name), writing results to `out` and +/// diagnostics to `err`. Returns the process exit code: 0 on success, 1 on failure, 2 for a usage +/// error. Help and the version go to `out`, exit 0. `mcp` speaks MCP on the process's own stdin +/// and stdout. +pub fn run(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32 +where + I: IntoIterator, + T: Into, +{ + let argv: Vec = std::iter::once(OsString::from("figcraft-cli")).chain(args.into_iter().map(Into::into)).collect(); + let cli = match args::parse(argv) { + Ok(cli) => cli, + Err(e) => { + // Help and `--version` on stdout with 0, usage errors on stderr with 2. + 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 }; + // Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable. + match dispatch(cli, &mut io) { + Ok(code) => code, + Err(e @ CliError::Usage(_)) => { + errln!(io, "error: {}\n\nFor more information, try '--help'.", files::plain(&e.to_string())); + 2 + } + Err(e @ CliError::Failed(_)) => { + errln!(io, "error: {}", files::plain(&e.to_string())); + 1 + } + } +} diff --git a/apps/figcraft-cli/src/main.rs b/apps/figcraft-cli/src/main.rs index 44bdd4520..7ad70fcdb 100644 --- a/apps/figcraft-cli/src/main.rs +++ b/apps/figcraft-cli/src/main.rs @@ -1,173 +1,7 @@ -//! `figcraft-cli`: FigCraft without a window. Inspect, export, convert and render documents, run -//! command scripts, list commands, serve MCP on stdio, publish plugins to a server's plugin -//! directory, publish code connect mappings to a design file and measure performance. -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! `figcraft-cli`: FigCraft without a window. See the library crate for the commands. -mod args; -mod files; -mod perf; - -use std::io::Write; -use std::process::ExitCode; - -use args::{Cli, Command, ConnectCommand, PluginCommand, RootArgs}; -use serde_json::{Value, json}; - -/// The automation roots a file subcommand was given, if any. Omitting both leaves the run -/// unconfined, as before; giving either confines every file the subcommand touches (#833). -fn roots_of(r: &RootArgs) -> CliResult> { - if r.automation_read_root.is_empty() && r.automation_write_root.is_empty() { - return Ok(None); - } - Ok(Some(figcraft_engine::file_access::Roots::new(&r.automation_read_root, &r.automation_write_root).map_err(CliError::Failed)?)) -} - -/// Runs `f` confined to the roots `r` carries. -fn confined(r: &RootArgs, f: impl FnOnce() -> CliResult) -> CliResult { - let roots = roots_of(r)?.map(std::sync::Arc::new); - figcraft_engine::file_access::confined(roots.as_ref(), f) -} - -fn main() -> ExitCode { +fn main() { // `args_os`: a non-Unicode argument is clap's usage error, not a panic. - let cli = match args::parse(std::env::args_os().collect()) { - Ok(cli) => cli, - Err(e) => { - // Help and `--version` on stdout with 0, usage errors on stderr with 2. - let _ = e.print(); - return ExitCode::from(u8::try_from(e.exit_code()).unwrap_or(2)); - } - }; - // Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable. - match run(cli) { - Ok(code) => code, - Err(CliError::Usage(msg)) => { - eprintln!("error: {}\n\nFor more information, try '--help'.", files::plain(&msg)); - ExitCode::from(2) - } - Err(CliError::Failed(msg)) => { - eprintln!("error: {}", files::plain(&msg)); - ExitCode::from(1) - } - } -} - -#[derive(Debug)] -pub enum CliError { - /// Bad arguments found after parsing (an output extension no format writes): exit code 2. - Usage(String), - /// The operation failed: exit code 1. - Failed(String), -} - -impl From for CliError { - fn from(s: String) -> Self { - CliError::Failed(s) - } -} - -pub type CliResult = Result; - -fn run(cli: Cli) -> CliResult { - if !cli.no_system_fonts { - // Text lays out with the installed fonts, like the desktop app, so headless renders and - // auto layout sizes match what users see. - figcraft_text::scan_system_fonts_on_demand(); - } else { - // Nothing scans them then, not even a `.sketch` import matching its fonts. - figcraft_text::opt_out_of_system_fonts(); - } - match cli.command { - Command::Info(a) => confined(&a.roots, || files::info(&a.file, a.json)), - Command::Export(a) => { - let target = - files::Target { print: a.print(), vd_compat: a.vd_compat, scale: a.scale.scale, format: a.format, page: a.page, node: a.node }; - confined(&a.roots, || files::export(&a.file, &a.out, &target)) - } - Command::Convert(a) => confined(&a.roots, || files::convert(&a.input, &a.output)), - Command::Render(a) => confined(&a.roots, || files::render(&a.file, &a.out, a.scale.scale, a.page.as_deref())), - Command::Run(a) => confined(&a.roots, || files::run_script(&a.script, a.input.as_deref(), a.out.as_deref())), - Command::Commands(a) => { - commands(a.json, a.filter.as_deref()); - Ok(ExitCode::SUCCESS) - } - // `--attach` conflicts with the roots: the app runs the commands, only its own roots can confine them. - Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, roots_of(&a.roots)?), - Command::Plugin { command: PluginCommand::Publish(a) } => publish_plugin(&a.folder, &a.server), - Command::Connect { command: ConnectCommand::Publish(a) } => confined(&a.roots, || files::connect_publish(&a.file, &a.mappings, a.dry_run)), - Command::Perf(a) => { - let sizes: Vec = a.layers.into_iter().map(|n| n.clamp(10, 2_000_000)).collect(); - let instances: Vec = a.instances.into_iter().filter(|n| *n > 0).map(|n| n.min(100_000)).collect(); - perf::run(&sizes, &instances, !cli.no_system_fonts) - } - } -} - -fn commands(as_json: bool, filter: Option<&str>) { - let f = filter.map(str::to_lowercase).unwrap_or_default(); - let list: Vec<&figcraft_engine::CommandSpec> = figcraft_engine::all_commands() - .iter() - .filter(|c| f.is_empty() || c.id.to_lowercase().contains(&f) || c.label.to_lowercase().contains(&f) || c.params.to_lowercase().contains(&f)) - .collect(); - let stdout = std::io::stdout(); - let mut out = stdout.lock(); - if as_json { - let v: Vec = list - .iter() - .map(|c| json!({"id": c.id, "label": c.label, "params": c.params, "menu": c.menu(), "shortcut": c.shortcut(), "undoable": c.history})) - .collect(); - let _ = writeln!(out, "{}", serde_json::to_string_pretty(&v).unwrap_or_default()); - return; - } - for c in list { - let sc = c.shortcut().map(|s| format!(" ({s})")).unwrap_or_default(); - let undo = if c.history { "*" } else { "" }; - let _ = writeln!(out, "{}{undo} {}{sc}\n {}", c.id, c.label, c.params); - } -} - -/// Publish the plugin folder `folder` to the plugin directory at `server` (the key from the address -/// or `FIGCRAFT_SERVER_KEY`); never prints the key. -fn publish_plugin(folder: &str, server: &str) -> CliResult { - let address = server.split('?').next().unwrap_or_default().to_string(); - let server = match std::env::var("FIGCRAFT_SERVER_KEY") { - Ok(key) if !server.contains("key=") && !key.trim().is_empty() => format!("{address}?key={}", key.trim()), - _ => server.to_string(), - }; - let mut h = figcraft_mcp::Headless::new(); - use figcraft_mcp::Backend as _; - let r = h.call("engine.execute", json!({"command": "plugin.directory.publish", "params": {"path": folder, "server": server}}))?; - let e = &r["published"]; - println!( - "Published {} {} ({}) to {address}: {} bytes, SHA-256 {}", - e["name"].as_str().unwrap_or_default(), - e["version"].as_str().unwrap_or_default(), - e["id"].as_str().unwrap_or_default(), - e["bytes"], - e["sha256"].as_str().unwrap_or_default() - ); - Ok(ExitCode::SUCCESS) -} - -fn mcp(attach: Option<&str>, timeout: Option, roots: Option) -> CliResult { - let backend: Box = match attach { - Some(addr) => { - let no_app = |e: std::io::Error| format!("can't reach the FigCraft app at {addr}: {e} (start it with `figcraft --control PORT`)"); - let b = figcraft_mcp::Attached::connect(addr).map_err(no_app)?; - match timeout { - Some(secs) => Box::new(b.with_timeout(std::time::Duration::from_secs(secs)).map_err(no_app)?), - None => Box::new(b), - } - } - None => Box::new(figcraft_mcp::Headless::new()), - }; - eprintln!("figcraft MCP server ({}) on stdio", backend.describe()); - if let Some(r) = &roots { - eprintln!("file access confined to {}", r.to_json()); - } - let mut server = figcraft_mcp::Server::new(backend).with_roots(roots); - let stdin = std::io::stdin(); - let stdout = std::io::stdout(); - server.serve(stdin.lock(), stdout.lock()).map_err(|e| format!("stdio: {e}"))?; - Ok(ExitCode::SUCCESS) + let code = figcraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); + std::process::exit(code); } diff --git a/apps/figcraft-cli/src/perf.rs b/apps/figcraft-cli/src/perf.rs index 4c34a5027..240fac7d8 100644 --- a/apps/figcraft-cli/src/perf.rs +++ b/apps/figcraft-cli/src/perf.rs @@ -4,7 +4,6 @@ //! card group, button instances and a grid of shapes and text). Every row is the mean of several //! runs; use a release build for meaningful numbers (`cargo xtask bench`). -use std::process::ExitCode; use std::time::Instant; use figcraft_doc::geom::Point; @@ -12,7 +11,7 @@ use figcraft_doc::{Document, NodeId, NodeKind}; use figcraft_engine::{PointerEvent, PointerKind, Session, ViewState}; use serde_json::json; -use crate::{CliError, CliResult}; +use crate::{CliError, CliResult, Io}; /// Canvas size of the measured viewport (a typical laptop window). const VIEW_W: u32 = 1440; @@ -31,12 +30,17 @@ fn mean(n: usize, mut f: impl FnMut(usize)) -> f64 { ms(t) / n.max(1) as f64 } +/// The messages of the failed measured commands, written to stderr at the end. +static FAILURES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + /// Set when a measured command fails (the numbers would be meaningless). static FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); fn exec(s: &mut Session, id: &str, p: serde_json::Value) { if let Err(e) = s.execute(id, &p) { - eprintln!("{id}: {e}"); + if let Ok(mut messages) = FAILURES.lock() { + messages.push(format!("{id}: {e}")); + } FAILED.store(true, std::sync::atomic::Ordering::Relaxed); } } @@ -292,39 +296,43 @@ fn measure_boolean_drag(table: &mut Table, col: usize) { /// Time the hot paths for each document size in `sizes` (layers) and, with the synthetic design /// system, for each instance count in `instances`; print the tables. -pub fn run(sizes: &[usize], instances: &[usize], system_fonts: bool) -> CliResult { +pub fn run(sizes: &[usize], instances: &[usize], system_fonts: bool, io: &mut Io) -> CliResult { // Text renders with system fonts too, like the desktop app; scanned up front, outside the timings. if system_fonts { figcraft_text::scan_system_fonts(); } let mut table = Table { rows: Vec::new() }; for (col, n) in sizes.iter().enumerate() { - eprintln!("measuring {n} layers…"); + errln!(io, "measuring {n} layers…"); measure(&mut table, col, *n)?; } let mut comps = Table { rows: Vec::new() }; for (col, n) in instances.iter().enumerate() { - eprintln!("measuring components with {n} instances…"); + errln!(io, "measuring components with {n} instances…"); measure_components(&mut comps, col, *n)?; } if FAILED.load(std::sync::atomic::Ordering::Relaxed) { + for message in FAILURES.lock().map(|m| m.clone()).unwrap_or_default() { + errln!(io, "{message}"); + } return Err(failed("a measured command failed")); } - println!( + outln!( + io, "figcraft perf ({} {}; ms unless noted; mean of several runs)", std::env::consts::OS, if cfg!(debug_assertions) { "debug build" } else { "release build" } ); - print_table(&table, &sizes.iter().map(|n| format!("{n} layers")).collect::>()); + print_table(io, &table, &sizes.iter().map(|n| format!("{n} layers")).collect::>()); if !instances.is_empty() { - println!(); - print_table(&comps, &instances.iter().map(|n| format!("{n} inst.")).collect::>()); + outln!(io); + print_table(io, &comps, &instances.iter().map(|n| format!("{n} inst.")).collect::>()); } - Ok(ExitCode::SUCCESS) + Ok(0) } /// Print `table` as Markdown with one column per `heads`. -fn print_table(table: &Table, heads: &[String]) { +fn print_table(io: &mut Io, table: &Table, heads: &[String]) { let w = table.rows.iter().map(|r| r.0.chars().count()).max().unwrap_or(10); let mut head = format!("| {:10} |")); rule.push_str(&format!("{}:|", "-".repeat(11))); } - println!("{head}"); - println!("{rule}"); + outln!(io, "{head}"); + outln!(io, "{rule}"); for (name, vals) in &table.rows { let mut line = format!("| {name:10} |", if v.is_finite() { format!("{v:.2}") } else { "-".into() })); } - println!("{line}"); + outln!(io, "{line}"); } } diff --git a/apps/figcraft-cli/tests/it/main.rs b/apps/figcraft-cli/tests/it/main.rs index ab0773b7d..75681e165 100644 --- a/apps/figcraft-cli/tests/it/main.rs +++ b/apps/figcraft-cli/tests/it/main.rs @@ -12,4 +12,6 @@ mod pdf; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod pdf_print; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod rfc18; +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod vector_drawable; diff --git a/apps/figcraft-cli/tests/it/rfc18.rs b/apps/figcraft-cli/tests/it/rfc18.rs new file mode 100644 index 000000000..b435b2488 --- /dev/null +++ b/apps/figcraft-cli/tests/it/rfc18.rs @@ -0,0 +1,195 @@ +//! RFC-0018 rule 2.7, in-process through `run`: help, versions, usage errors with exit 2 on stderr, +//! the files a command would replace, and the environment variables its flags declare. + +use std::ffi::OsString; +use std::process::{Command, Stdio}; + +struct Outcome { + code: i32, + out: String, + err: String, +} + +fn invoke(args: I) -> Outcome +where + I: IntoIterator, + T: Into, +{ + let (mut out, mut err) = (Vec::new(), Vec::new()); + let code = figcraft_cli::run(args, &mut out, &mut err); + Outcome { code, out: String::from_utf8_lossy(&out).into_owned(), err: String::from_utf8_lossy(&err).into_owned() } +} + +fn workdir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("figcraft-cli-rfc18-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn usage_error(args: &[&str]) -> String { + let got = invoke(args.iter().copied()); + assert_eq!(got.code, 2, "{args:?}: {}", got.err); + assert_eq!(got.out, "", "{args:?} wrote to stdout"); + assert!(got.err.starts_with("error: "), "{args:?}: {}", got.err); + got.err +} + +const SUBCOMMANDS: [&[&str]; 10] = [ + &["info"], + &["export"], + &["convert"], + &["render"], + &["run"], + &["commands"], + &["mcp"], + &["plugin", "publish"], + &["connect", "publish"], + &["perf"], +]; + +#[test] +fn every_subcommand_takes_help_and_the_version() { + let top = invoke(["--version"]); + assert_eq!((top.code, top.err.as_str()), (0, "")); + let version = top.out.strip_prefix("figcraft-cli ").unwrap().trim_end().to_string(); + for sub in SUBCOMMANDS { + for flag in ["--help", "-h"] { + let got = invoke(sub.iter().copied().chain([flag])); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{sub:?} {flag}"); + assert!(got.out.contains(&format!("Usage: figcraft-cli {}", sub.join(" "))), "{sub:?}: {}", got.out); + } + for flag in ["--version", "-V"] { + let got = invoke(sub.iter().copied().chain([flag])); + assert_eq!((got.code, got.err.as_str()), (0, ""), "{sub:?} {flag}"); + assert_eq!( + got.out, + format!("{} {version}\n", ["figcraft-cli"].iter().chain(sub.iter()).copied().collect::>().join("-")), + "{sub:?}" + ); + } + } + usage_error(&["version"]); +} + +#[test] +fn no_arguments_and_unknown_flags_are_usage_errors() { + let got = invoke(Vec::::new()); + assert_eq!((got.code, got.out.as_str()), (2, "")); + assert!(got.err.contains("Usage: figcraft-cli"), "{}", got.err); + for sub in SUBCOMMANDS { + let args: Vec<&str> = sub.iter().copied().chain(["--fromat"]).collect(); + assert!(usage_error(&args).contains("--fromat"), "{sub:?}"); + } + usage_error(&["--fromat"]); +} + +#[test] +fn a_flag_given_twice_and_bad_values_are_refused() { + usage_error(&["info", "x.figcraft", "--json", "--json"]); + usage_error(&["render", "x.figcraft", "-o", "a.png", "--scale", "0"]); + usage_error(&["export", "x.figcraft", "-o", "out", "--format", "bmp"]); + usage_error(&["mcp", "--attach", "nope"]); + usage_error(&["run", "s.json", "--in-place"]); +} + +#[test] +fn commands_lists_in_json_and_as_text() { + let json = invoke(["commands", "--json", "--filter", "layer"]); + assert_eq!((json.code, json.err.as_str()), (0, "")); + assert!(serde_json::from_str::(&json.out).unwrap().as_array().is_some_and(|l| !l.is_empty())); + let text = invoke(["commands", "--filter", "layer"]); + assert_eq!(text.code, 0); + assert!(text.out.contains(" "), "{}", text.out); +} + +#[test] +fn a_failed_command_exits_1_and_a_closed_stdout_is_not_an_error() { + let got = invoke(["info", "missing.figcraft"]); + assert_eq!((got.code, got.out.as_str()), (1, "")); + assert!(got.err.starts_with("error: "), "{}", got.err); + struct Closed; + impl std::io::Write for Closed { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut err = Vec::new(); + assert_eq!(figcraft_cli::run(["commands"], &mut Closed, &mut err), 0); + assert!(err.is_empty()); +} + +#[test] +fn an_output_that_would_replace_an_input_is_refused_without_in_place() { + let dir = workdir("replace"); + let a = dir.join("a.figcraft"); + let a = a.to_str().unwrap(); + let first = invoke(["convert", "-", "-"]); + assert_eq!(first.code, 1, "{}", first.err); // a missing input is a failure, not a usage error + // Make a real document: a script into a new file. + let script = dir.join("s.json"); + std::fs::write(&script, r#"[{"command": "frame.create", "params": {"x": 0, "y": 0, "width": 10, "height": 10, "name": "F"}}]"#).unwrap(); + let made = invoke(["run", script.to_str().unwrap(), "--out", a]); + assert_eq!(made.code, 0, "{}", made.err); + let before = std::fs::read(a).unwrap(); + let dotted = dir.join(".").join("a.figcraft"); + for args in [ + vec!["convert", a, a], + vec!["convert", a, dotted.to_str().unwrap()], + vec!["run", script.to_str().unwrap(), "--in", a, "--out", a], + vec!["export", a, "-o", a], + vec!["render", a, "-o", a], + ] { + let message = usage_error(&args); + assert!(message.contains("would replace"), "{args:?}: {message}"); + } + assert_eq!(std::fs::read(a).unwrap(), before, "a refused command changes nothing"); + let other = dir.join("b.figcraft"); + let other = other.to_str().unwrap(); + assert!(usage_error(&["convert", a, other, "--in-place"]).contains("--in-place")); + assert!(usage_error(&["run", script.to_str().unwrap(), "--in", a, "--out", other, "--in-place"]).contains("--in-place")); + let got = invoke(["run", script.to_str().unwrap(), "--in", a, "--out", a, "--in-place"]); + assert_eq!(got.code, 0, "{}", got.err); + let got = invoke(["convert", a, a, "--in-place"]); + assert_eq!(got.code, 0, "{}", got.err); + std::fs::remove_dir_all(dir).unwrap(); +} + +fn binary() -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_figcraft-cli")); + command.env_remove("FIGCRAFT_NO_SYSTEM_FONTS").env_remove("FIGCRAFT_SERVER_KEY"); + command +} + +#[test] +fn the_variables_are_declared_on_their_flags() { + // The font variable takes the usual boolean spellings, and an empty one is unset. + for (value, code) in [("1", 0), ("true", 0), ("0", 0), ("", 0), ("maybe", 2)] { + let output = + binary().args(["commands", "--filter", "layer.add"]).env("FIGCRAFT_NO_SYSTEM_FONTS", value).stdin(Stdio::null()).output().unwrap(); + assert_eq!(output.status.code(), Some(code), "{value:?}: {}", String::from_utf8_lossy(&output.stderr)); + } + // The server key's value is never printed in help; an unreachable server reports itself, not the key. + let secret = "do-not-print-this-key-0123456789"; + let help = binary().args(["plugin", "publish", "--help"]).env("FIGCRAFT_SERVER_KEY", secret).output().unwrap(); + let help = String::from_utf8_lossy(&help.stdout).into_owned(); + assert!(help.contains("FIGCRAFT_SERVER_KEY") && !help.contains(secret), "{help}"); + let dir = workdir("key"); + let failed = + binary().args(["plugin", "publish"]).arg(&dir).args(["--server", "ws://127.0.0.1:9/"]).env("FIGCRAFT_SERVER_KEY", secret).output().unwrap(); + assert_eq!(failed.status.code(), Some(1)); + assert!(!String::from_utf8_lossy(&failed.stderr).contains(secret), "{}", String::from_utf8_lossy(&failed.stderr)); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[cfg(unix)] +#[test] +fn a_file_name_that_is_not_valid_unicode_is_a_usage_error() { + use std::os::unix::ffi::OsStringExt; + let got = invoke([OsString::from("info"), OsString::from_vec(b"caf\xe9.figcraft".to_vec())]); + assert_eq!((got.code, got.out.as_str()), (2, "")); + assert!(got.err.starts_with("error: "), "{}", got.err); +} diff --git a/docs/cli.md b/docs/cli.md index 07b19e58b..65c9423e0 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -4,14 +4,13 @@ FigCraft without a window: inspect, export, convert and render documents, run co commands, serve MCP, publish plugins and code connect mappings, and measure performance. Build it with `cargo build --release -p figcraft-cli` (binary `target/release/figcraft-cli`). -The CLI follows [RFC-0012](https://github.com/storytold/craft-contrib/blob/main/rfcs/0012-cli-conventions.md), -the command-line conventions the Craft apps share, in how it parses its arguments (with clap). The -rules it doesn't follow yet are listed below. `figcraft-cli --help` is the source of truth for +Follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md), +the command-line conventions the Craft apps share. `figcraft-cli --help` is the source of truth for the flags; this page explains what they do. `figcraft-cli --help` (or `-h`, `help`, `help `) prints help on stdout and exits with 0. So does `--help` or `-h` after a subcommand (`figcraft-cli mcp --help`), even after a mistake on -the same line. `--version` (or `-V`) prints the version. Bad arguments are usage errors, caught +the same line. `--version` (or `-V`, also after a subcommand) prints the version. Bad arguments are usage errors, caught before any work starts: an option the subcommand doesn't take, an option given twice (only the automation roots repeat), a missing or bad value (`--scale 0`, `--format bmp`, `--attach nope`) and `mcp --attach` with automation roots. They print `error: …` on stderr and exit with code 2. @@ -22,14 +21,24 @@ takes the next option as its value. Put options before `--` to pass a filename b dash, for example `figcraft-cli info --json -- --drawing.figcraft`. Every argument after `--` is literal, including a filename named `--no-system-fonts`. -Not yet as RFC-0012 asks: +Exit codes: 0 for success, 1 for a failure, 2 for a usage error, and 128 plus the signal number +when a signal ends the process. Output goes to stdout and diagnostics to stderr; a closed stdout +(`figcraft-cli commands | head -1`) ends the run quietly instead of with a panic. + +Writing over the input is refused: `convert` and `run` with an output that is the input file +(`--out` the same file as `--in`), and `export -o` or `render -o` naming the file they read, exit +with 2 and say so, rather than replacing the document. Pass `--in-place` to `convert` or `run` to +mean it. `--in-place` with a different output file is a usage error too. `connect publish` +saves into the design file by design, as described below. + +Environment variables are declared on their flags, so `--help` shows them: `--no-system-fonts` +reads `FIGCRAFT_NO_SYSTEM_FONTS` and `plugin publish --key` reads `FIGCRAFT_SERVER_KEY` (its value +is never shown in help or in errors). A blank variable counts as unset. The flag wins over the +variable. No destructive flag has an environment fallback. + +Still as before, and a known gap against the RFC: - Arguments that name files are read as text, so a file name that isn't valid Unicode is a usage error (exit 2) rather than reaching the command. -- Failures are messages rather than error enums, and `main` isn't yet a `run(args, out, err)` - function the tests call in-process. -- `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are read where they're used, not declared - on a flag, so `--help` names them only in the flag descriptions. -- Packages don't install the generated shell completions or man pages yet. - There are no ast-grep checks in CI yet. ## Generating shell completions and man pages @@ -57,8 +66,11 @@ The directory contains completions for five shells: It also contains `figcraft-cli.1` and one man page per subcommand, including nested commands such as `figcraft-cli-plugin-publish.1`. For example, `man target/cli-docs/figcraft-cli-export.1` shows -the export subcommand's options. Generating these files doesn't install them; package installation -is still outstanding in [#1396](https://github.com/storytold/figcraft/issues/1396). +the export subcommand's options. Generating these files doesn't install them: the Linux packages (tar, deb, rpm) put the man pages +in `/usr/share/man/man1` and the Bash, Zsh and Fish completions in the shells' system directories +(the deb also links the Zsh one into Debian's `vendor-completions`), and the FreeBSD package +puts them under `/usr/local` (`man/man1`, `share/bash-completion`, `share/zsh/site-functions`, +`share/fish/vendor_completions.d`). Nightly builds rename the CLI and ship neither. ## Fonts @@ -288,11 +300,11 @@ live sessions (`collab.*`: without a key on a server open to the public, with `c `collab.manageFile` for the owner token and `collab.report`) and use plugin directories (`plugin.directory.*`); the one-shot `run` can't (no network link). -### `plugin publish --server ws://host:port/[?key=KEY]` +### `plugin publish --server ws://host:port/[?key=KEY] [--key KEY]` Publishes a plugin folder (`figcraft-plugin.json`, the module its `main` names, an optional `assets/` folder) to a `figcraft-server`'s plugin directory as a new version, and prints its name, version, -size and SHA-256. The server's key comes from the address or, better, from the +size and SHA-256. The server's key comes from the address, from `--key` or, better, from the `FIGCRAFT_SERVER_KEY` environment variable (it then stays out of the shell history and process lists); it is never printed. The bundle is checked before it is sent and again by the server. See [plugins.md](plugins.md#plugin-directories). diff --git a/docs/roadmap.md b/docs/roadmap.md index 20788fb5d..896fa9bd1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -76,6 +76,7 @@ blockers. | Date | Change | Summary | |---|---|---| +| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged | | 2026-11-19 | minor | M12, #2237 (step 1 of 4): code blocks in the document and engine. `board.codeBlock` places a dark panel of monospace text as tall as its lines, `board.setLanguage` picks one of 16 languages, and `board.nextSticky` makes the next block beside it; the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. Numbers unchanged. | | 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index 3b693d0bb..3a49b4db4 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -67,8 +67,15 @@ echo "==> FigCraft $VERSION for FreeBSD $ARCH" # The release VM has 12 GB; full parallelism on the biggest crates runs it out of memory. export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" +# The man-and-completions example writes figcraft-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 here, so a cross build builds it for the host. +HOST_TRIPLE="$(rustc -vV | sed -n 's/^host: //p')" if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"} "${CARGO_PKGS[@]}") + if [[ "$HAS_CLI" = 1 ]]; then + (cd "$ROOT" && cargo build --release --locked --target "$HOST_TRIPLE" -p figcraft-cli --example man-and-completions) + fi fi WORK="$CARGO_TARGET_DIR/freebsd-package" STAGE="$WORK/$BASENAME" @@ -87,6 +94,16 @@ if [[ "$DRY_RUN" = 1 ]]; then printf '#!/bin/sh\necho "%s %s (dry-run stub)"\n' "$b" "$VERSION" >"$BIN/$b" chmod 755 "$BIN/$b" done + # A stub of the example: it writes the files the real one does. + mkdir -p "$BIN/examples" + cat >"$BIN/examples/man-and-completions" <<'STUB' +#!/bin/sh +mkdir -p "$1" +for f in figcraft-cli.bash _figcraft-cli figcraft-cli.fish figcraft-cli.elv _figcraft-cli.ps1 figcraft-cli.1 figcraft-cli-info.1; do + echo "dry-run stub" >"$1/$f" +done +STUB + chmod 755 "$BIN/examples/man-and-completions" fi # ---- stage a /usr/local-style tree -------------------------------------------------------------- @@ -108,10 +125,31 @@ sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$FIGCRAFT_BUILD_DATE/g" \ cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" copy_docs "$STAGE/share/doc/figcraft" if [[ -f "$ROOT/ATTRIBUTION.md" ]]; then install -m 644 "$ROOT/ATTRIBUTION.md" "$STAGE/share/doc/figcraft/"; fi +# figcraft-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_FILES=() +if [[ "$HAS_CLI" = 1 ]]; then + CLI_DOCS="$CARGO_TARGET_DIR/$HOST_TRIPLE/release/examples/man-and-completions" + [[ "$DRY_RUN" = 0 ]] || CLI_DOCS="$BIN/examples/man-and-completions" + if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is not built (cargo build --release --target $HOST_TRIPLE -p figcraft-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/figcraft-cli.bash" "$STAGE/share/bash-completion/completions/figcraft-cli" + install -m 644 "$WORK/cli-docs/_figcraft-cli" "$STAGE/share/zsh/site-functions/_figcraft-cli" + install -m 644 "$WORK/cli-docs/figcraft-cli.fish" "$STAGE/share/fish/vendor_completions.d/figcraft-cli.fish" + CLI_FILES=(man/man1/figcraft-cli.1 share/bash-completion/completions/figcraft-cli share/zsh/site-functions/_figcraft-cli + share/fish/vendor_completions.d/figcraft-cli.fish) +fi for f in "${BINS[@]/#/bin/}" "share/applications/$APP_ID.desktop" \ "share/icons/hicolor/256x256/apps/$APP_ID.png" \ - share/doc/figcraft/LICENSE-MIT share/doc/figcraft/LICENSE-APACHE; do + share/doc/figcraft/LICENSE-MIT share/doc/figcraft/LICENSE-APACHE "${CLI_FILES[@]}"; do if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi done diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 320a8d49b..6a8ed7910 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -1,6 +1,7 @@ # .deb and .rpm packages (nfpm: https://nfpm.goreleaser.com). Run by package.sh, which stages # the file tree, substitutes its path for ${STAGE} (nfpm doesn't expand env vars in `src`), -# drops the lines marked `#cli` when the workspace has no apps/figcraft-cli, and exports VERSION, +# drops the lines marked `#cli` when the workspace has no apps/figcraft-cli (and those marked +# `#stable-cli` in a Nightly build, which ships no CLI man pages or completions), and exports VERSION, # NFPM_ARCH and FIGCRAFT_MAINTAINER. # # nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ @@ -82,6 +83,12 @@ contents: - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree + # Debian's zsh reads vendor-completions, not /usr/share/zsh/site-functions as Fedora's and + # openSUSE's do (its debian/rules sets --enable-additional-fpath). A Nightly has no completions. + - src: /usr/share/zsh/site-functions/_figcraft-cli #stable-cli + dst: /usr/share/zsh/vendor-completions/_figcraft-cli #stable-cli + type: symlink #stable-cli + packager: deb #stable-cli scripts: postinstall: packaging/linux/postinst.sh diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index d95a0f386..449621893 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -69,10 +69,19 @@ if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then exit 2 fi +# The man-and-completions example writes figcraft-cli's man pages and shell completions below +# (Stable only: a Nightly renames the CLI, so pages for `figcraft-cli` would document a command it +# lacks). It is built in its own cargo run: built with the binaries, its dev-dependencies' features +# would be unified into them. It runs here, so a cross build builds it for the host. +HOST_TRIPLE="$(rustc -vV | sed -n 's/^host: //p')" + echo "==> FigCraft $VERSION for Linux $ARCH ($FORMATS; ${BINS[*]}; channel=${FIGCRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked "${CARGO_PKGS[@]}" ${CROSS_TARGET:+--target "$CROSS_TARGET"}) + if [[ "$HAS_CLI" = 1 && "$IS_NIGHTLY" = 0 ]]; then + (cd "$ROOT" && cargo build --release --locked --target "$HOST_TRIPLE" -p figcraft-cli --example man-and-completions) + fi fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" WORK="$CARGO_TARGET_DIR/linux-package" @@ -84,6 +93,22 @@ for bin in "${BINS[@]}"; do install -Dm755 "$BIN/$bin" "$STAGE/usr/bin/$bin" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/$bin" 2>/dev/null || true done +# figcraft-cli's man pages and shell completions (RFC-0018 rule 1.9), from its clap definition, +# written by the example built above (a --skip-build run needs it built too). zsh reads +# site-functions on Fedora and openSUSE; the deb also links the completion into Debian's +# vendor-completions (nfpm.yaml). +if [[ "$HAS_CLI" = 1 && "$IS_NIGHTLY" = 0 ]]; then + CLI_DOCS="$CARGO_TARGET_DIR/$HOST_TRIPLE/release/examples/man-and-completions" + if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is not built (cargo build --release --target $HOST_TRIPLE -p figcraft-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/figcraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/figcraft-cli" + install -Dm644 "$WORK/cli-docs/_figcraft-cli" "$STAGE/usr/share/zsh/site-functions/_figcraft-cli" + install -Dm644 "$WORK/cli-docs/figcraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/figcraft-cli.fish" +fi install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" if [[ "$IS_NIGHTLY" = 1 ]]; then # The nightly entry point is the distro launcher (packaging/linux/nightly-package-launch.sh): @@ -211,8 +236,11 @@ if has deb || has rpm; then [[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;' cli_filter='/#cli$/d' [[ "$HAS_CLI" = 1 ]] && cli_filter='s/ #cli$//' + # The zsh link into Debian's vendor-completions is for the stable CLI's completion: a Nightly has none. + stable_filter='s/ #stable-cli$//' + [[ "$HAS_CLI" = 1 && "$IS_NIGHTLY" = 0 ]] || stable_filter='/#stable-cli$/d' # shellcheck disable=SC2016 - sed -e "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" -e "$cli_filter" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + sed -e "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" -e "$cli_filter" -e "$stable_filter" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done