Skip to main content

astrs_cli/command/
new.rs

1//! `astrs new` (blueprint §17): scaffold a buildable node/operator crate,
2//! or a starter graph manifest, wired into a starter manifest.
3//!
4//! Every template file lives under `src/templates/` and is embedded at
5//! compile time via `include_str!` (no runtime template lookup, no path
6//! that could accidentally read a file outside this crate's own source
7//! tree) with placeholder tokens substituted by plain [`str::replace`] —
8//! no templating engine dependency for a handful of tokens:
9//! `__ASTRS_PROJECT_NAME__` (the project name, verbatim), and, where a
10//! template needs it, `__ASTRS_PROJECT_TYPE__` (the operator template's
11//! Rust struct name, `PascalCase`) or `__ASTRS_PROJECT_LIB_FILE_STEM__`
12//! (the `operator-dylib` template's built artifact file stem, `snake_case`
13//! — see `lib_file_stem`'s own docs for why a hyphenated project name
14//! needs a third, distinct rendering).
15
16use std::io::Write;
17use std::path::{Path, PathBuf};
18
19use serde::Serialize;
20
21use crate::error::CliError;
22
23const NODE_CARGO_TOML: &str = include_str!("../templates/node/Cargo.toml.template");
24const NODE_MAIN_RS: &str = include_str!("../templates/node/main.rs.template");
25const NODE_DATAFLOW_YML: &str = include_str!("../templates/node/dataflow.yml.template");
26
27const OPERATOR_CARGO_TOML: &str = include_str!("../templates/operator/Cargo.toml.template");
28const OPERATOR_LIB_RS: &str = include_str!("../templates/operator/lib.rs.template");
29const OPERATOR_DATAFLOW_YML: &str = include_str!("../templates/operator/dataflow.yml.template");
30
31const OPERATOR_DYLIB_CARGO_TOML: &str =
32    include_str!("../templates/operator-dylib/Cargo.toml.template");
33const OPERATOR_DYLIB_LIB_RS: &str = include_str!("../templates/operator-dylib/lib.rs.template");
34const OPERATOR_DYLIB_DATAFLOW_YML: &str =
35    include_str!("../templates/operator-dylib/dataflow.yml.template");
36
37const GRAPH_DATAFLOW_YML: &str = include_str!("../templates/graph/dataflow.yml.template");
38
39const NAME_TOKEN: &str = "__ASTRS_PROJECT_NAME__";
40const TYPE_TOKEN: &str = "__ASTRS_PROJECT_TYPE__";
41const LIB_FILE_STEM_TOKEN: &str = "__ASTRS_PROJECT_LIB_FILE_STEM__";
42
43/// Which template `astrs new` scaffolds.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
45#[value(rename_all = "lower")]
46pub enum NewKind {
47    /// A standalone node crate (a binary that runs as its own process).
48    Node,
49    /// A runtime-hosted operator crate (a library, compiled into a
50    /// runtime binary via `register_operator!`).
51    Operator,
52    /// A dylib-hosted operator crate (a `cdylib`, `dlopen`ed at spawn time
53    /// by `astrs-runtime`'s `dylib-operators` feature — blueprint §9.3,
54    /// §22).
55    ///
56    /// An explicit `#[value(name = ...)]` rather than the enum's own
57    /// `rename_all = "lower"`: that default would lowercase every letter
58    /// with no word separator (`operatordylib`), while every multi-word
59    /// value elsewhere in this CLI's surface (`astrs migrate from-dora`,
60    /// this same command's own subcommand name below) is kebab-case.
61    #[value(name = "operator-dylib")]
62    OperatorDylib,
63    /// A starter multi-node graph manifest, no Rust project.
64    Graph,
65}
66
67/// Which language a scaffolded node/operator is written in.
68///
69/// Only [`NewLang::Rust`] exists in 0.1.0 (blueprint §5.3's `astrs-python`
70/// is a P1 stretch crate) — a real, closed enum rather than a bare string
71/// so `--lang python` fails clap's own argument parsing with a clear
72/// "possible values: rust" message instead of this module inventing its
73/// own "unsupported language" error for a value clap could have already
74/// rejected.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
76#[value(rename_all = "lower")]
77pub enum NewLang {
78    /// Rust — the only language 0.1.0 scaffolds.
79    #[default]
80    Rust,
81}
82
83/// Arguments for `astrs new`.
84#[derive(Debug, Clone)]
85pub struct NewArgs {
86    /// Which template to scaffold.
87    pub kind: NewKind,
88    /// The new project's name — also its directory name (for
89    /// [`NewKind::Node`]/[`NewKind::Operator`]) or manifest file stem
90    /// (for [`NewKind::Graph`]). Must be a single path component with no
91    /// separators or `..` — see `validate_name` (crate-private).
92    pub name: String,
93    /// The language to scaffold in. Ignored for [`NewKind::Graph`]
94    /// (a manifest has no language).
95    pub lang: NewLang,
96    /// The directory to scaffold into (the project itself becomes
97    /// `dir/name/` or, for a graph, `dir/name.astrs.yml`).
98    pub dir: PathBuf,
99    /// Overwrite files that already exist at the target location.
100    pub force: bool,
101    /// Emit the report as JSON instead of the human-readable file listing.
102    pub json: bool,
103}
104
105/// The result of scaffolding one new project.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
107pub struct NewReport {
108    /// Every file written, in the order they were created.
109    pub files: Vec<PathBuf>,
110}
111
112/// Validate that `name` is safe to join onto a target directory: exactly
113/// one plain path component, no separators, no `.`/`..`, non-empty.
114///
115/// # Errors
116///
117/// Returns [`CliError::UnsafePath`] otherwise.
118fn validate_name(name: &str) -> Result<(), CliError> {
119    let unsafe_path = || CliError::UnsafePath {
120        path: name.to_string(),
121    };
122    if name.is_empty() {
123        return Err(unsafe_path());
124    }
125    let path = Path::new(name);
126    let mut components = path.components();
127    match (components.next(), components.next()) {
128        (Some(std::path::Component::Normal(component)), None) if component == path.as_os_str() => {
129            Ok(())
130        }
131        _ => Err(unsafe_path()),
132    }
133}
134
135/// Convert an arbitrary project name into a valid, exported Rust type
136/// identifier in `PascalCase` — splitting on any run of characters that
137/// are not `[A-Za-z0-9]`, capitalizing each segment's first letter, and
138/// prefixing with `Op` if the result would not otherwise start with a
139/// letter (a name like `"3d-tracker"` becomes `Op3DTracker`, never the
140/// invalid identifier `3DTracker`).
141fn pascal_case_type_name(name: &str) -> String {
142    let mut out = String::new();
143    for segment in name.split(|c: char| !c.is_ascii_alphanumeric()) {
144        let mut chars = segment.chars();
145        if let Some(first) = chars.next() {
146            out.extend(first.to_uppercase());
147            out.extend(chars);
148        }
149    }
150    if out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
151        format!("Op{out}")
152    } else if out.is_empty() {
153        "Op".to_string()
154    } else {
155        out
156    }
157}
158
159/// The file stem cargo gives a `cdylib` built from a crate named `name` —
160/// every `-` replaced with `_`, matching cargo's own crate-name-to-file-name
161/// rule for library artifacts (the same rule a `Cargo.toml` `name = "a-b"`
162/// crate's `liba_b.so`/`.dylib`/`a_b.dll` follows). The
163/// `operator-dylib` template's `dataflow.yml` uses this, not
164/// [`NAME_TOKEN`] verbatim, so a hyphenated project name still produces a
165/// `dylib:` path that names the file cargo actually built.
166fn lib_file_stem(name: &str) -> String {
167    name.replace('-', "_")
168}
169
170/// Substitute every placeholder token in `template`.
171fn render(template: &str, name: &str) -> String {
172    template
173        .replace(NAME_TOKEN, name)
174        .replace(TYPE_TOKEN, &pascal_case_type_name(name))
175        .replace(LIB_FILE_STEM_TOKEN, &lib_file_stem(name))
176}
177
178/// Write `contents` to `path`, refusing to overwrite an existing file
179/// unless `force`.
180fn write_file(path: &Path, contents: &str, force: bool) -> Result<(), CliError> {
181    if !force && path.exists() {
182        return Err(CliError::TargetExists {
183            path: path.display().to_string(),
184        });
185    }
186    if let Some(parent) = path.parent() {
187        std::fs::create_dir_all(parent).map_err(|err| CliError::io(parent, err))?;
188    }
189    std::fs::write(path, contents).map_err(|err| CliError::io(path, err))
190}
191
192/// Run `astrs new`: validate `args.name`, then write every file the
193/// requested [`NewKind`] template needs.
194///
195/// # Errors
196///
197/// Returns [`CliError::UnsafePath`] if `args.name` is not a single plain
198/// path component, [`CliError::TargetExists`] if a target file already
199/// exists and `args.force` is not set, or [`CliError::Io`] if a file
200/// cannot be written.
201pub fn run(out: &mut dyn Write, args: &NewArgs) -> Result<NewReport, CliError> {
202    validate_name(&args.name)?;
203    let _ = args.lang; // recorded for forward compatibility; only `Rust` exists today.
204
205    let files = match args.kind {
206        NewKind::Node => {
207            let root = args.dir.join(&args.name);
208            let entries = [
209                (root.join("Cargo.toml"), NODE_CARGO_TOML),
210                (root.join("src/main.rs"), NODE_MAIN_RS),
211                (root.join("dataflow.yml"), NODE_DATAFLOW_YML),
212            ];
213            write_all(&entries, &args.name, args.force)?
214        }
215        NewKind::Operator => {
216            let root = args.dir.join(&args.name);
217            let entries = [
218                (root.join("Cargo.toml"), OPERATOR_CARGO_TOML),
219                (root.join("src/lib.rs"), OPERATOR_LIB_RS),
220                (root.join("dataflow.yml"), OPERATOR_DATAFLOW_YML),
221            ];
222            write_all(&entries, &args.name, args.force)?
223        }
224        NewKind::OperatorDylib => {
225            let root = args.dir.join(&args.name);
226            let entries = [
227                (root.join("Cargo.toml"), OPERATOR_DYLIB_CARGO_TOML),
228                (root.join("src/lib.rs"), OPERATOR_DYLIB_LIB_RS),
229                (root.join("dataflow.yml"), OPERATOR_DYLIB_DATAFLOW_YML),
230            ];
231            write_all(&entries, &args.name, args.force)?
232        }
233        NewKind::Graph => {
234            let path = args.dir.join(format!("{}.astrs.yml", args.name));
235            write_all(&[(path, GRAPH_DATAFLOW_YML)], &args.name, args.force)?
236        }
237    };
238
239    let report = NewReport { files };
240
241    if args.json {
242        let json = serde_json::to_string_pretty(&report).unwrap_or_else(|err| {
243            format!("{{\"error\": \"failed to serialize new report: {err}\"}}")
244        });
245        writeln!(out, "{json}").map_err(|e| CliError::io("<output>", e))?;
246    } else {
247        writeln!(
248            out,
249            "created {} file(s) for {} `{}`:",
250            report.files.len(),
251            kind_label(args.kind),
252            args.name
253        )
254        .map_err(|e| CliError::io("<output>", e))?;
255        for file in &report.files {
256            writeln!(out, "  {}", file.display()).map_err(|e| CliError::io("<output>", e))?;
257        }
258    }
259
260    Ok(report)
261}
262
263fn kind_label(kind: NewKind) -> &'static str {
264    match kind {
265        NewKind::Node => "node",
266        NewKind::Operator => "operator",
267        NewKind::OperatorDylib => "dylib operator",
268        NewKind::Graph => "graph",
269    }
270}
271
272fn write_all(
273    entries: &[(PathBuf, &str)],
274    name: &str,
275    force: bool,
276) -> Result<Vec<PathBuf>, CliError> {
277    let mut written = Vec::with_capacity(entries.len());
278    for (path, template) in entries {
279        write_file(path, &render(template, name), force)?;
280        written.push(path.clone());
281    }
282    Ok(written)
283}
284
285#[cfg(test)]
286mod tests {
287    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
288    use super::*;
289
290    fn scratch_dir(name: &str) -> PathBuf {
291        // A monotonic counter, not just `(pid, name)`, disambiguates the
292        // directory -- see `command::graph`'s own test helper for the
293        // observed race this guards against if a future test ever reuses
294        // an existing `name` under cargo's multi-threaded test runner.
295        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
296        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
297        let dir = std::env::temp_dir().join(format!(
298            "astrs-cli-new-test-{}-{name}-{n}",
299            std::process::id()
300        ));
301        let _ = std::fs::remove_dir_all(&dir);
302        std::fs::create_dir_all(&dir).unwrap();
303        dir
304    }
305
306    fn args(kind: NewKind, name: &str, dir: PathBuf) -> NewArgs {
307        NewArgs {
308            kind,
309            name: name.to_string(),
310            lang: NewLang::Rust,
311            dir,
312            force: false,
313            json: false,
314        }
315    }
316
317    #[test]
318    fn node_template_creates_cargo_toml_main_rs_and_dataflow_yml() {
319        let dir = scratch_dir("node");
320        let mut out = Vec::new();
321        let report = run(&mut out, &args(NewKind::Node, "my-node", dir.clone())).unwrap();
322        assert_eq!(report.files.len(), 3);
323        for file in &report.files {
324            assert!(file.exists(), "{} was not written", file.display());
325        }
326        let cargo_toml = std::fs::read_to_string(dir.join("my-node/Cargo.toml")).unwrap();
327        assert!(cargo_toml.contains("name = \"my-node\""));
328        assert!(!cargo_toml.contains(NAME_TOKEN));
329        let main_rs = std::fs::read_to_string(dir.join("my-node/src/main.rs")).unwrap();
330        assert!(main_rs.contains("my-node"));
331        let dataflow = std::fs::read_to_string(dir.join("my-node/dataflow.yml")).unwrap();
332        assert!(dataflow.contains("path: ./target/release/my-node"));
333    }
334
335    #[test]
336    fn json_flag_emits_a_structured_file_list_instead_of_the_human_summary() {
337        let dir = scratch_dir("json");
338        let mut out = Vec::new();
339        let mut a = args(NewKind::Node, "json-node", dir.clone());
340        a.json = true;
341        let report = run(&mut out, &a).unwrap();
342
343        let printed = String::from_utf8(out).unwrap();
344        let value: serde_json::Value = serde_json::from_str(printed.trim_end()).unwrap();
345        let files = value["files"].as_array().unwrap();
346        assert_eq!(files.len(), 3);
347        assert_eq!(files.len(), report.files.len());
348        // Every file this run actually wrote is named in the JSON, and
349        // nothing else -- the "created N file(s) for node `...`:" human
350        // summary line does not also appear.
351        for file in &report.files {
352            assert!(
353                files
354                    .iter()
355                    .any(|v| v.as_str() == Some(&file.display().to_string()))
356            );
357        }
358        assert!(!printed.contains("created"));
359    }
360
361    #[test]
362    fn node_dataflow_yml_validates_cleanly() {
363        let dir = scratch_dir("node-validates");
364        let mut out = Vec::new();
365        run(&mut out, &args(NewKind::Node, "camera-node", dir.clone())).unwrap();
366        let yaml = std::fs::read_to_string(dir.join("camera-node/dataflow.yml")).unwrap();
367        let manifest = astrs_manifest::Manifest::from_yaml_str(&yaml).unwrap();
368        manifest.validate().unwrap();
369    }
370
371    #[test]
372    fn operator_template_creates_lib_rs_with_a_pascal_case_type_and_validates() {
373        let dir = scratch_dir("operator");
374        let mut out = Vec::new();
375        let report = run(
376            &mut out,
377            &args(NewKind::Operator, "my-cool-op", dir.clone()),
378        )
379        .unwrap();
380        assert_eq!(report.files.len(), 3);
381        let lib_rs = std::fs::read_to_string(dir.join("my-cool-op/src/lib.rs")).unwrap();
382        assert!(lib_rs.contains("struct MyCoolOp"));
383        assert!(lib_rs.contains("register_operator!(MyCoolOp)"));
384        assert!(!lib_rs.contains(TYPE_TOKEN));
385
386        // Plain textual assertions -- no compiler invocation -- guarding the
387        // exact shape a real `cargo check` on this scaffold needs (verified
388        // by hand against the live templates; this crate's tests deliberately
389        // never shell out to cargo, see `generated_cargo_toml_is_textually_well_formed`
390        // above). Each line below pins one way the template used to fail to
391        // compile:
392        //   - `OpEvent::Stop` was matched without its `{ cause, grace }`
393        //     fields (`E0533`).
394        //   - `Status::Stop` does not exist; `Status::Finished` is the
395        //     terminal variant.
396        //   - `OpEvent` is `#[non_exhaustive]`, so a downstream match (this
397        //     one) needs a wildcard arm.
398        //   - `register_operator!(...)` expands to a `(name, ctor)` tuple
399        //     expression, which is not legal at module/item scope -- it must
400        //     live inside a function body, here `operator_entry`.
401        assert!(lib_rs.contains("OpEvent::Stop {"));
402        assert!(lib_rs.contains("Status::Finished"));
403        assert!(!lib_rs.contains("Status::Stop"));
404        assert!(lib_rs.contains("_ =>"));
405        assert!(lib_rs.contains("fn operator_entry()"));
406
407        let cargo_toml = std::fs::read_to_string(dir.join("my-cool-op/Cargo.toml")).unwrap();
408        // The facade's `Operator`/`OpEvent`/`Status`/`register_operator!`
409        // surface is gated behind the `operator` feature (off by default,
410        // see `astrs`'s own `[features]` table) -- without this, the
411        // template's `use astrs::prelude::*;` would not even bring those
412        // names into scope.
413        assert!(cargo_toml.contains(r#"features = ["operator"]"#));
414
415        let yaml = std::fs::read_to_string(dir.join("my-cool-op/dataflow.yml")).unwrap();
416        let manifest = astrs_manifest::Manifest::from_yaml_str(&yaml).unwrap();
417        manifest.validate().unwrap();
418        assert_eq!(
419            manifest.nodes[0].operators.as_ref().unwrap()[0].operator,
420            "MyCoolOp"
421        );
422        // `register_operator!`'s default name is `stringify!(Type)`
423        // (PascalCase) -- the same spelling the manifest's `operator:`
424        // field above names (`astrs-runtime`'s `RuntimeConfig` docs: "the
425        // `register_operator!` name"), asserted together so a future edit
426        // to `operator_entry` cannot drift the two apart.
427    }
428
429    #[test]
430    fn operator_dylib_template_creates_a_cdylib_crate_with_a_dylib_locator_and_validates() {
431        let dir = scratch_dir("operator-dylib");
432        let mut out = Vec::new();
433        let report = run(
434            &mut out,
435            &args(NewKind::OperatorDylib, "my-cool-dylib-op", dir.clone()),
436        )
437        .unwrap();
438        assert_eq!(report.files.len(), 3);
439
440        let cargo_toml = std::fs::read_to_string(dir.join("my-cool-dylib-op/Cargo.toml")).unwrap();
441        assert!(!cargo_toml.contains(NAME_TOKEN));
442        assert!(cargo_toml.contains(r#"crate-type = ["cdylib", "lib"]"#));
443        // `export_dylib_operator!` lives behind `astrs-operator-api`'s own
444        // `dylib` feature (off by default, matching that crate's
445        // `[features]` table) -- without this, `use ...
446        // export_dylib_operator;` in the template would not resolve.
447        assert!(cargo_toml.contains(r#"features = ["dylib"]"#));
448
449        let lib_rs = std::fs::read_to_string(dir.join("my-cool-dylib-op/src/lib.rs")).unwrap();
450        assert!(!lib_rs.contains(TYPE_TOKEN));
451        assert!(lib_rs.contains("struct MyCoolDylibOp"));
452        // The exported-symbol macro, not `register_operator!` -- a dylib
453        // operator is loaded, never linked into a compiled-in registry.
454        assert!(lib_rs.contains("export_dylib_operator!(MyCoolDylibOp)"));
455        assert!(!lib_rs.contains("register_operator!"));
456        // Same non-exhaustive-match and terminal-variant pitfalls as the
457        // compiled-in operator template -- see that test's own comment for
458        // why each of these lines is pinned rather than assumed.
459        assert!(lib_rs.contains("OpEvent::Stop {"));
460        assert!(lib_rs.contains("Status::Finished"));
461        assert!(!lib_rs.contains("Status::Stop"));
462        assert!(lib_rs.contains("_ =>"));
463
464        let yaml = std::fs::read_to_string(dir.join("my-cool-dylib-op/dataflow.yml")).unwrap();
465        let manifest = astrs_manifest::Manifest::from_yaml_str(&yaml).unwrap();
466        manifest.validate().unwrap();
467        let operator = &manifest.nodes[0].operators.as_ref().unwrap()[0];
468        assert_eq!(operator.operator, "MyCoolDylibOp");
469        assert_eq!(
470            operator.dylib.as_deref(),
471            // Hyphens in the project name become underscores here (cargo's
472            // own `cdylib` file-naming rule — see `lib_file_stem`'s own
473            // docs), not carried over verbatim the way `NAME_TOKEN` is
474            // elsewhere in this same file.
475            Some("./target/release/libmy_cool_dylib_op.so")
476        );
477        assert_eq!(operator.locator_kinds(), vec!["dylib"]);
478    }
479
480    #[test]
481    fn graph_template_creates_a_single_yaml_file_and_validates() {
482        let dir = scratch_dir("graph");
483        let mut out = Vec::new();
484        let report = run(&mut out, &args(NewKind::Graph, "perception", dir.clone())).unwrap();
485        assert_eq!(report.files, vec![dir.join("perception.astrs.yml")]);
486        let yaml = std::fs::read_to_string(&report.files[0]).unwrap();
487        let manifest = astrs_manifest::Manifest::from_yaml_str(&yaml).unwrap();
488        manifest.validate().unwrap();
489        assert_eq!(manifest.name.as_deref(), Some("perception"));
490    }
491
492    #[test]
493    fn path_traversal_in_name_is_rejected() {
494        let dir = scratch_dir("traversal");
495        for bad in ["../escape", "/etc/passwd", "a/b", "..", "."] {
496            let err = run(&mut Vec::new(), &args(NewKind::Node, bad, dir.clone())).unwrap_err();
497            assert!(
498                matches!(err, CliError::UnsafePath { .. }),
499                "name `{bad}` should be rejected, got {err:?}"
500            );
501        }
502    }
503
504    #[test]
505    fn empty_name_is_rejected() {
506        let dir = scratch_dir("empty");
507        let err = run(&mut Vec::new(), &args(NewKind::Node, "", dir)).unwrap_err();
508        assert!(matches!(err, CliError::UnsafePath { .. }));
509    }
510
511    #[test]
512    fn existing_target_without_force_is_rejected() {
513        let dir = scratch_dir("exists");
514        run(&mut Vec::new(), &args(NewKind::Node, "dup", dir.clone())).unwrap();
515        let err = run(&mut Vec::new(), &args(NewKind::Node, "dup", dir)).unwrap_err();
516        assert!(matches!(err, CliError::TargetExists { .. }));
517    }
518
519    #[test]
520    fn force_overwrites_an_existing_target() {
521        let dir = scratch_dir("force");
522        run(&mut Vec::new(), &args(NewKind::Node, "dup", dir.clone())).unwrap();
523        let mut a = args(NewKind::Node, "dup", dir);
524        a.force = true;
525        run(&mut Vec::new(), &a).unwrap();
526    }
527
528    #[test]
529    fn pascal_case_handles_hyphens_underscores_and_leading_digits() {
530        assert_eq!(pascal_case_type_name("my-cool-op"), "MyCoolOp");
531        assert_eq!(pascal_case_type_name("my_cool_op"), "MyCoolOp");
532        // "3d" is one segment (digits and letters are both alphanumeric,
533        // so no split occurs between them) -- only its first character
534        // (itself a digit, case-less) is touched by the capitalization
535        // step, and the whole identifier is `Op`-prefixed because it
536        // would otherwise start with a digit.
537        assert_eq!(pascal_case_type_name("3d-tracker"), "Op3dTracker");
538        assert_eq!(pascal_case_type_name("simple"), "Simple");
539    }
540
541    #[test]
542    fn lib_file_stem_turns_hyphens_into_underscores_and_leaves_everything_else_alone() {
543        assert_eq!(lib_file_stem("my-cool-op"), "my_cool_op");
544        assert_eq!(lib_file_stem("my_cool_op"), "my_cool_op");
545        assert_eq!(lib_file_stem("simple"), "simple");
546        assert_eq!(lib_file_stem("3d-tracker"), "3d_tracker");
547    }
548
549    #[test]
550    fn generated_cargo_toml_is_textually_well_formed() {
551        let dir = scratch_dir("cargo-toml-shape");
552        run(
553            &mut Vec::new(),
554            &args(NewKind::Node, "shape-check", dir.clone()),
555        )
556        .unwrap();
557        let cargo_toml = std::fs::read_to_string(dir.join("shape-check/Cargo.toml")).unwrap();
558        // Plain textual assertions -- no `toml` crate dependency, and
559        // deliberately not a real `cargo metadata` invocation (slow,
560        // network-touching in the worst case); see this crate's own test
561        // suite conventions.
562        assert!(cargo_toml.contains("[package]"));
563        assert!(cargo_toml.contains("[dependencies]"));
564        assert!(
565            cargo_toml
566                .lines()
567                .any(|l| l.trim() == "name = \"shape-check\"")
568        );
569        assert!(!cargo_toml.contains("workspace = true"));
570    }
571}