From 1a64ca23f586fc169fced0f8cf46754e6f7ab77d Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:08:28 +0530 Subject: [PATCH] Document the functions the automation roots touch CodeRabbit measures docstring coverage over the functions a PR touches, and this one was at 62%, under the repository's 80% threshold. --- apps/cadcraft-cli/src/args.rs | 3 +++ apps/cadcraft-cli/src/mcp.rs | 1 + apps/cadcraft-cli/tests/mcp_roots.rs | 8 ++++++++ apps/cadcraft-cli/tests/mcp_roots_walk.rs | 7 +++++++ crates/engine/src/cmd/audit.rs | 2 ++ crates/engine/src/cmd/blocks/extract.rs | 1 + crates/engine/src/cmd/blocks/insert_file.rs | 1 + crates/engine/src/cmd/blocks/xref.rs | 1 + crates/engine/src/cmd/blocks/xref/load.rs | 1 + crates/engine/src/cmd/exchange.rs | 1 + crates/engine/src/cmd/file.rs | 1 + crates/engine/src/cmd/file/compare.rs | 1 + crates/engine/src/cmd/file/template.rs | 1 + crates/engine/src/cmd/helpers.rs | 1 + crates/engine/src/cmd/layout/plotstyle.rs | 1 + crates/engine/src/cmd/plotters.rs | 1 + crates/engine/src/file_access.rs | 10 ++++++++++ crates/engine/src/file_access/commands.rs | 1 + crates/engine/src/lisp/builtins/files.rs | 3 +++ crates/engine/src/session/execute.rs | 1 + crates/engine/src/sysvars.rs | 1 + crates/engine/tests/dash_wblock.rs | 1 + crates/mcp/src/backend.rs | 3 +++ 23 files changed, 52 insertions(+) diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index 5d3864e0e..c8daf8d14 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -423,6 +423,7 @@ enum UsageError { } impl UsageError { + /// This error in clap's form, so it prints with the usual usage text. fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { let kind = match self { Self::FramingNeedsImage { .. } | Self::OutIsInput(_) | Self::AutomationRootsNeedHeadless => ErrorKind::ArgumentConflict, @@ -530,6 +531,7 @@ pub(crate) enum McpTarget { } impl McpArgs { + /// What these arguments ask the server to talk to. pub(crate) fn target(&self) -> McpTarget { match &self.connect { // `--launch` connects at the first call too (the app opens then). @@ -663,6 +665,7 @@ mod tests { } } + /// Without `--connect` the server runs headless, confining nothing unless asked. #[test] fn mcp_without_connect_is_headless() { assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless { read_root: None, write_root: None }); diff --git a/apps/cadcraft-cli/src/mcp.rs b/apps/cadcraft-cli/src/mcp.rs index 4727d29c1..ea6849f71 100644 --- a/apps/cadcraft-cli/src/mcp.rs +++ b/apps/cadcraft-cli/src/mcp.rs @@ -1,6 +1,7 @@ use super::args::{McpArgs, McpTarget}; use super::error::{CliError, Result}; +/// Serve MCP on stdin and stdout against the running app or a headless session held to any roots given. pub(crate) fn mcp(a: &McpArgs) -> Result { let backend: Box = match a.target() { McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)), diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index 99ecb0ec1..6011842b9 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -56,6 +56,7 @@ fn folders(tag: &str) -> TestDir { base } +/// `p` as the text a tool call passes. fn s(p: &Path) -> String { p.to_string_lossy().into_owned() } @@ -106,15 +107,18 @@ fn run_env(args: &[&str], calls: &[(&str, Value)], env: &[(&str, &str)]) -> (Out (out, tools) } +/// The call succeeded. fn ok(t: &Tool) { assert!(!t.error, "should be allowed: {}", t.text); } +/// The call was refused, saying `why`. fn refused(t: &Tool, why: &str) { assert!(t.error, "should be refused ({why}): {}", t.text); assert!(t.text.contains(why), "should say `{why}`: {}", t.text); } +/// `open` and every other read stay inside the read root or the write root. #[test] fn files_open_only_from_inside_the_read_root() { let base = folders("open"); @@ -265,6 +269,7 @@ fn plotter_settings_outside_the_roots_are_refused() { assert!(!settings.join("Office.plotter.json.cadcraft-tmp").exists()); } +/// With no roots nothing changes: files anywhere can be reached. #[test] fn without_roots_files_are_reachable_as_before() { let base = folders("none"); @@ -276,6 +281,7 @@ fn without_roots_files_are_reachable_as_before() { assert!(base.join("outside/new.dxf").is_file()); } +/// A link inside a root leading out is refused for reads and writes. #[cfg(unix)] #[test] fn links_out_of_a_root_are_refused() { @@ -292,6 +298,7 @@ fn links_out_of_a_root_are_refused() { assert!(!base.join("outside/new.dxf").exists()); } +/// Each kind of command that touches a file is refused outside the roots. #[test] fn every_file_a_command_touches_is_held_to_the_roots() { let base = folders("commands"); @@ -335,6 +342,7 @@ fn every_file_a_command_touches_is_held_to_the_roots() { assert!(!base.join("outside/plot.pdf").exists()); } +/// A root that can't be opened, or roots with `--connect`, stop the server at startup. #[test] fn missing_roots_and_roots_with_connect_fail_at_startup() { let base = folders("bad-roots"); diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs index 11492660d..d74c71631 100644 --- a/apps/cadcraft-cli/tests/mcp_roots_walk.rs +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -30,6 +30,7 @@ const PNG: &[u8] = &[ 0xAE, 0x42, 0x60, 0x82, ]; +/// `p` as the text a tool call passes. fn s(p: &Path) -> String { p.to_string_lossy().into_owned() } @@ -43,6 +44,7 @@ struct Server { } impl Server { + /// Start the real binary as an MCP server and initialize it. fn start(args: &[String], cwd: &Path, config: &Path) -> Self { let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) .arg("mcp") @@ -71,6 +73,7 @@ impl Server { server } + /// Send one JSON-RPC request; `None` if the server stopped answering. fn request(&mut self, method: &str, params: Value) -> Option { let id = self.next; self.next += 1; @@ -90,6 +93,7 @@ impl Server { Some(reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string()) } + /// Run an engine command through the `execute` tool. fn execute(&mut self, command: &str, params: Value) -> Option { self.tool("execute", json!({"command": command, "params": params})) } @@ -138,6 +142,7 @@ struct Fixture { } impl Fixture { + /// A new fixture, finding out whether this file system records reads. fn new(tag: &str) -> Self { let base = fresh_dir(tag); for d in ["in", "out"] { @@ -224,6 +229,7 @@ impl Drop for Fixture { } } +/// Every file and folder under `dir`. fn tree(dir: &Path) -> Vec { let mut out = vec![dir.to_path_buf()]; for e in std::fs::read_dir(dir).unwrap().flatten() { @@ -458,6 +464,7 @@ fn walk(tag: &str, roots: bool) -> Walk { result } +/// One line saying what a walk saw. fn summary(w: &Walk) -> String { format!( "{} commands, {} calls, reads seen: {}, {} commands touched files outside, {} calls lost the server", diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index 816769598..7ede5a67c 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -134,6 +134,7 @@ fn run_recover(s: &mut Session, p: &Value) -> Result { Ok(r) } +/// Write the report to the `.adt` file beside the saved drawing, held to the automation roots. #[cfg(not(target_arch = "wasm32"))] fn write_audit_log(s: &Session, report: &crate::audit::Report) { let (path_str, title) = match s.state() { @@ -165,6 +166,7 @@ fn read_path(cmd: &str, path: &str) -> Result> { std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}"))) } +/// The bytes of the drawing at `path`, held to the automation roots. #[cfg(target_arch = "wasm32")] fn read_path(cmd: &str, _path: &str) -> Result> { Err(bad(cmd, "paths are not available on the web; pass `data`")) diff --git a/crates/engine/src/cmd/blocks/extract.rs b/crates/engine/src/cmd/blocks/extract.rs index ecb2ca540..7720a588e 100644 --- a/crates/engine/src/cmd/blocks/extract.rs +++ b/crates/engine/src/cmd/blocks/extract.rs @@ -200,6 +200,7 @@ fn csv(columns: &[String], rows: &[Vec], sep: char) -> String { out } +/// Write the extracted table to `path`, held to the automation roots. fn write_file(path: &str, text: &str) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 650bf9468..4d79a7367 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -82,6 +82,7 @@ fn read_drawing(path: &str) -> Result { Err(last.unwrap_or_else(|| bad("insert", format!("{path}: file not found")))) } +/// The bytes of the drawing to insert, held to the automation roots. fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index c5be66c70..832c1bc85 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -353,6 +353,7 @@ fn run_xbind(s: &mut Session, p: &Value) -> Result { Ok(json!({ "bound": bound })) } +/// Open the file a selected reference points at, as its own drawing. fn run_xopen(s: &mut Session, p: &Value) -> Result { let d = s.doc()?; let name = match str_param(p, "name") { diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index fe03b5d5d..bdd71e7f0 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -150,6 +150,7 @@ pub(crate) enum Missing { } impl Missing { + /// The status and message a reference gets when its file can't be loaded. fn outcome(self, path: &str) -> (XrefStatus, String) { match self { Self::NotFound => { diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index a395390db..d5562621e 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -202,6 +202,7 @@ fn import_drawing(s: &mut Session, src: &Drawing, at: Vec2, scale: f64, file: &s })) } +/// The bytes of the file to import, held to the automation roots. fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0d17665cc..331fedf79 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -330,6 +330,7 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result { Ok(opened(s, i, true)) } +/// Parse a drawing's bytes, and search its folder for fonts where the automation roots allow. fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result { let hooks = io().ok_or_else(|| bad("open", "file formats are not available in this build"))?; let drawing = (hooks.read)(bytes, name).map_err(|e| bad("open", e))?; diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 2b0b2678a..518e79829 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -107,6 +107,7 @@ fn other_drawing(s: &Session, p: &Value) -> Result<(Arc, String)> { Ok((Arc::new(d), name)) } +/// The bytes of the drawing to compare with, held to the automation roots. fn read_path(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 0134f2e9f..be09af71c 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -78,6 +78,7 @@ fn read_bytes(path: &str) -> Result> { std::fs::read(path).map_err(|e| bad("new", format!("template {path}: {e}"))) } +/// The bytes of the template at `path`, held to the automation roots. #[cfg(target_arch = "wasm32")] fn read_bytes(path: &str) -> Result> { Err(bad("new", format!("template {path}: paths are not available on the web"))) diff --git a/crates/engine/src/cmd/helpers.rs b/crates/engine/src/cmd/helpers.rs index b68990048..ad9d5aaf7 100644 --- a/crates/engine/src/cmd/helpers.rs +++ b/crates/engine/src/cmd/helpers.rs @@ -127,6 +127,7 @@ fn read_support_file(cmd: &str, path: &str) -> crate::Result { Ok(String::from_utf8_lossy(&bytes).into_owned()) } +/// The text of a support file (a linetype or hatch pattern file, say), size-limited and held to the automation roots. #[cfg(target_arch = "wasm32")] fn read_support_file(cmd: &str, _path: &str) -> crate::Result { Err(super::bad(cmd, "paths are not available on the web; pass the file's contents")) diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index ef6c2edab..7097a4739 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -187,6 +187,7 @@ fn edit_style(cmd: &str, st: &mut PlotStyle, v: &Value) -> Result<()> { Ok(()) } +/// List, read, change, load and export plot style tables; any file is held to the automation roots. fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { let cmd = "stylesmanager"; let action = str_param(p, "action").unwrap_or("list").to_ascii_lowercase(); diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 71691d4b1..9208c2a0f 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -556,6 +556,7 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> { Ok(()) } +/// List, read, change, load, export and delete plotter configurations; any file is held to the automation roots. fn run_plottermanager(_s: &mut Session, p: &Value) -> Result { let cmd = "plottermanager"; let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase(); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index ccaa24105..340bdc59a 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -316,6 +316,7 @@ mod tests { assert_eq!(roots.check(s(base.join("out/new/x.png")), Access::Write), Ok(()), "a normal save inside still works"); } + /// `in2` starts like `in` and isn't inside it. #[test] fn a_sibling_with_the_same_prefix_is_outside() { let (base, roots) = folders("prefix"); @@ -324,6 +325,7 @@ mod tests { assert!(roots.check(format!("{}2/c.dxf", s(base.join("in"))), Access::Read).is_err()); } + /// `..` is followed where it can be, and refused below a missing folder. #[test] fn parent_traversal_is_resolved_or_refused() { let (base, roots) = folders("dotdot"); @@ -338,6 +340,7 @@ mod tests { assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}"); } + /// A relative path means the working directory, and an empty one is refused. #[test] fn relative_paths_resolve_against_the_working_directory() { let (_base, roots) = folders("relative"); @@ -346,6 +349,7 @@ mod tests { assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty")); } + /// A root must be a folder that exists; no roots at all confines nothing. #[test] fn a_missing_root_is_an_error_and_none_is_no_confinement() { let (base, _) = folders("missing"); @@ -365,6 +369,7 @@ mod tests { assert!(e.contains("write authority is absent"), "{e}"); } + /// Links are judged by where they lead, so a link out is refused and one inside is fine. #[test] fn links_are_followed_before_comparing() { let (base, roots) = folders("links"); @@ -408,6 +413,7 @@ mod tests { assert!(same(Path::new("/w/root"), Path::new("/w/root"))); } + /// The superscript ports, `COM0`, `LPT0` and the `:` form are device names. #[test] fn device_names_include_the_superscript_ports() { for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.dxf", "NUL ", "COM¹", "lpt³.txt", "com²", "NUL:", "con:stream", "COM0", "lpt0.txt"] { @@ -452,6 +458,7 @@ mod tests { assert_eq!(roots.check(base.join("out/new/deep/x.dxf"), Access::Write), Ok(())); } + /// On a real case-sensitive folder, `Root` beside the root `root` is outside it. #[cfg(windows)] #[test] fn a_case_sensitive_windows_folder_can_hold_a_sibling_of_the_root() { @@ -472,6 +479,7 @@ mod tests { assert_eq!(roots.check(&s(base.join("root/new.dxf")), Access::Write), Ok(())); } + /// On an ordinary Windows folder any case finds the root, and device names are refused. #[cfg(windows)] #[test] fn windows_gives_a_root_its_real_spelling_and_refuses_devices() { @@ -486,6 +494,7 @@ mod tests { assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(())); } + /// Roots end with their scope, also when a nested scope or a panic ends it. #[test] fn scopes_nest_and_restore_after_a_panic() { let (base, roots) = folders("scopes"); @@ -504,6 +513,7 @@ mod tests { assert_eq!(confine(None, || check_read(&outside)), Ok(())); } + /// The plain device names, and names that only look like them. #[test] fn device_names() { for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL "] { diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index 322317e09..4ff6b992c 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -496,6 +496,7 @@ mod tests { /// direction. const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"]; + /// The words of a command's documentation, lower case. fn words(doc: &str) -> BTreeSet { doc.to_ascii_lowercase().split(|c: char| !c.is_ascii_alphanumeric()).map(str::to_string).collect() } diff --git a/crates/engine/src/lisp/builtins/files.rs b/crates/engine/src/lisp/builtins/files.rs index 58cb1fb3a..232c338d7 100644 --- a/crates/engine/src/lisp/builtins/files.rs +++ b/crates/engine/src/lisp/builtins/files.rs @@ -13,6 +13,7 @@ pub struct LispFile { pub text: String, } +/// LISP `open`: a file handle, or nil when the file can't be opened or the automation roots refuse it. pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 2, 3)?; let path = string(&a[0])?.to_string(); @@ -98,6 +99,7 @@ fn can_write(_path: &str) -> bool { false } +/// Write or append `text`, doing nothing when the automation roots refuse the path. #[cfg(not(target_arch = "wasm32"))] fn write_text_file(path: &str, text: &str, append: bool) { use std::io::Write; @@ -113,6 +115,7 @@ fn write_text_file(path: &str, text: &str, append: bool) { #[cfg(target_arch = "wasm32")] fn write_text_file(_path: &str, _text: &str, _append: bool) {} +/// Whether a file is at `path`; outside the automation roots the answer is no. #[cfg(not(target_arch = "wasm32"))] fn file_exists(path: &str) -> bool { crate::file_access::check_read(path).is_ok() && std::path::Path::new(path).is_file() diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 6f71b2537..74e2a9f6e 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -24,6 +24,7 @@ impl Session { } } + /// Run a command by id, unless the automation roots, its own state or the block editor refuse it. fn execute_guarded(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; if let Some(why) = crate::file_access::commands::refusal(spec.id) { diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 0cd902021..eb2182d0b 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -286,6 +286,7 @@ pub fn format_angle_list(angles: &[f64]) -> String { angles.iter().map(|a| format!("{}", (a.to_degrees() * 1e6).round() / 1e6)).collect::>().join(";") } +/// Set a system variable, refusing values out of its range and folders the automation roots can't hold. pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { let n = name.trim().to_ascii_uppercase(); if is_read_only(&n) { diff --git a/crates/engine/tests/dash_wblock.rs b/crates/engine/tests/dash_wblock.rs index b4c2f7f67..d19fcc60f 100644 --- a/crates/engine/tests/dash_wblock.rs +++ b/crates/engine/tests/dash_wblock.rs @@ -285,6 +285,7 @@ fn oops_brings_back_what_it_erased_where_it_was() { assert_eq!(order, [a, b, c]); } +/// A refused -WBLOCK leaves OOPS as it was. #[test] fn a_dash_wblock_refused_during_refedit_leaves_oops_as_it_was() { let (mut s, a, b, c) = drawing(); diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index c74599b77..de7a4b957 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -342,6 +342,7 @@ fn state(s: &Session) -> Value { } impl Headless { + /// The reply to one control method; the caller holds it to the roots. fn answer(&mut self, method: &str, p: &Value) -> Result { let s = &mut self.session; let str_p = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); @@ -462,6 +463,7 @@ impl Headless { } impl Backend for Headless { + /// Run one control method inside the roots, if any. fn call(&mut self, method: &str, p: Value) -> Result { let roots = self.roots.clone(); file_access::confine(roots.as_ref(), || self.answer(method, &p)) @@ -469,6 +471,7 @@ impl Backend for Headless { fn has_ui(&self) -> bool { false } + /// What this backend talks to, for messages. fn describe(&self) -> String { "headless CADCraft session".into() }