mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 02:38:30 -06:00
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.
This commit is contained in:
@@ -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 });
|
||||
|
||||
@@ -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<dyn cadcraft_mcp::Backend> = match a.target() {
|
||||
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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<Value> {
|
||||
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<String> {
|
||||
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<PathBuf> {
|
||||
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",
|
||||
|
||||
@@ -134,6 +134,7 @@ fn run_recover(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
Err(bad(cmd, "paths are not available on the web; pass `data`"))
|
||||
|
||||
@@ -200,6 +200,7 @@ fn csv(columns: &[String], rows: &[Vec<Cell>], 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"))]
|
||||
{
|
||||
|
||||
@@ -82,6 +82,7 @@ fn read_drawing(path: &str) -> Result<Drawing> {
|
||||
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<Vec<u8>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
|
||||
@@ -353,6 +353,7 @@ fn run_xbind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
let d = s.doc()?;
|
||||
let name = match str_param(p, "name") {
|
||||
|
||||
@@ -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 => {
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
|
||||
@@ -330,6 +330,7 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
|
||||
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<String>) -> Result<ReadFile> {
|
||||
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))?;
|
||||
|
||||
@@ -107,6 +107,7 @@ fn other_drawing(s: &Session, p: &Value) -> Result<(Arc<Drawing>, 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<Vec<u8>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
|
||||
@@ -78,6 +78,7 @@ fn read_bytes(path: &str) -> Result<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
Err(bad("new", format!("template {path}: paths are not available on the web")))
|
||||
|
||||
@@ -127,6 +127,7 @@ fn read_support_file(cmd: &str, path: &str) -> crate::Result<String> {
|
||||
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<String> {
|
||||
Err(super::bad(cmd, "paths are not available on the web; pass the file's contents"))
|
||||
|
||||
@@ -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<Value> {
|
||||
let cmd = "stylesmanager";
|
||||
let action = str_param(p, "action").unwrap_or("list").to_ascii_lowercase();
|
||||
|
||||
@@ -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<Value> {
|
||||
let cmd = "plottermanager";
|
||||
let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase();
|
||||
|
||||
@@ -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 "] {
|
||||
|
||||
@@ -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<String> {
|
||||
doc.to_ascii_lowercase().split(|c: char| !c.is_ascii_alphanumeric()).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
@@ -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<Value>) -> Result<Flow, LispError> {
|
||||
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()
|
||||
|
||||
@@ -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<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
if let Some(why) = crate::file_access::commands::refusal(spec.id) {
|
||||
|
||||
@@ -286,6 +286,7 @@ pub fn format_angle_list(angles: &[f64]) -> String {
|
||||
angles.iter().map(|a| format!("{}", (a.to_degrees() * 1e6).round() / 1e6)).collect::<Vec<_>>().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) {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Value, String> {
|
||||
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<Value, String> {
|
||||
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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user