pipecircuit-cli 0.0.2

Command-line architectural tools for Pipecircuit programs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::{error::Error, ffi::OsString, fs, io::Write as _, path::PathBuf};

use super::{CliError, Command, utf8};

pub(super) struct NewCommand {
    destination: PathBuf,
    name: String,
    framework: Option<PathBuf>,
}

pub(super) fn parse(mut arguments: impl Iterator<Item = OsString>) -> Result<Command, CliError> {
    let mut destination = None;
    let mut name = None;
    let mut framework = None;
    while let Some(argument) = arguments.next() {
        match argument.to_str() {
            Some("--name") => {
                let value = arguments
                    .next()
                    .ok_or_else(|| CliError::new("missing value after `--name`"))?;
                if name.replace(utf8(value, "project name")?).is_some() {
                    return Err(CliError::new("`--name` was provided more than once"));
                }
            }
            Some("--framework-path") => {
                let value = arguments
                    .next()
                    .ok_or_else(|| CliError::new("missing path after `--framework-path`"))?;
                if framework.replace(PathBuf::from(value)).is_some() {
                    return Err(CliError::new(
                        "`--framework-path` was provided more than once",
                    ));
                }
            }
            Some("-h" | "--help") => return Ok(Command::Help),
            Some(flag) if flag.starts_with('-') => {
                return Err(CliError::new(format!("unknown option `{flag}`")));
            }
            _ => {
                if destination.replace(PathBuf::from(argument)).is_some() {
                    return Err(CliError::new("more than one destination was provided"));
                }
            }
        }
    }
    let destination =
        destination.ok_or_else(|| CliError::new("missing destination for `pipec new`"))?;
    let name = match name {
        Some(name) => name,
        None => destination
            .file_name()
            .and_then(|name| name.to_str())
            .ok_or_else(|| {
                CliError::new("destination needs a UTF-8 project name, or use `--name`")
            })?
            .to_owned(),
    };
    validate_name(&name)?;
    Ok(Command::New(NewCommand {
        destination,
        name,
        framework,
    }))
}

fn validate_name(name: &str) -> Result<(), CliError> {
    let starts_with_letter = name
        .bytes()
        .next()
        .is_some_and(|first| first.is_ascii_lowercase());
    let portable = name.bytes().all(|byte| {
        byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-' || byte == b'_'
    });
    let reserved = matches!(name, "con" | "prn" | "aux" | "nul")
        || (name.len() == 4
            && (name.starts_with("com") || name.starts_with("lpt"))
            && name.ends_with(|ch: char| ch.is_ascii_digit()));
    if !starts_with_letter || !portable || reserved || name.len() > 64 {
        return Err(CliError::new(
            "project name must start with a lowercase ASCII letter and contain only lowercase letters, digits, hyphens or underscores (at most 64 characters, excluding reserved device names)",
        ));
    }
    Ok(())
}

fn toml_string(value: &str) -> Result<String, CliError> {
    let mut escaped = String::from("\"");
    for character in value.chars() {
        match character {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            character if character.is_control() => {
                return Err(CliError::new(
                    "framework path contains an unsupported control character",
                ));
            }
            character => escaped.push(character),
        }
    }
    escaped.push('"');
    Ok(escaped)
}

const FRAMEWORK_VERSION: &str = "0.0.17";

const FILES: &[(&str, &str)] = &[
    ("README.md", include_str!("../template/README.md")),
    (
        "programs/src/tests.rs",
        include_str!("../template/programs/src/tests.rs"),
    ),
    (
        "core/src/state_machines/architecture.rs",
        include_str!("../template/core/src/state_machines/architecture.rs"),
    ),
    ("Cargo.toml", include_str!("../template/Cargo.toml.in")),
    (".gitignore", include_str!("../template/.gitignore")),
    (
        ".cargo/config.toml",
        include_str!("../template/.cargo/config.toml"),
    ),
    (
        "core/Cargo.toml",
        include_str!("../template/core/Cargo.toml.in"),
    ),
    (
        "core/src/lib.rs",
        include_str!("../template/core/src/lib.rs"),
    ),
    (
        "core/src/domain_primitives/mod.rs",
        include_str!("../template/core/src/domain_primitives/mod.rs"),
    ),
    (
        "core/src/state_machines/mod.rs",
        include_str!("../template/core/src/state_machines/mod.rs"),
    ),
    (
        "programs/Cargo.toml",
        include_str!("../template/programs/Cargo.toml.in"),
    ),
    (
        "programs/src/lib.rs",
        include_str!("../template/programs/src/lib.rs"),
    ),
    (
        "programs/src/pipes/mod.rs",
        include_str!("../template/programs/src/pipes/mod.rs"),
    ),
    (
        "programs/src/switchboard/mod.rs",
        include_str!("../template/programs/src/switchboard/mod.rs"),
    ),
    ("src/main.rs", include_str!("../template/src/main.rs")),
    ("src/client.rs", include_str!("../template/src/client.rs")),
    (
        "src/wiring/mod.rs",
        include_str!("../template/src/wiring/mod.rs"),
    ),
    (
        "benches/.gitkeep",
        include_str!("../template/benches/.gitkeep"),
    ),
    (
        "core/src/domain_primitives/proofs.rs",
        include_str!("../template/core/src/domain_primitives/proofs.rs"),
    ),
    (
        "core/src/domain_primitives/tests.rs",
        include_str!("../template/core/src/domain_primitives/tests.rs"),
    ),
    (
        "core/src/state_machines/proofs.rs",
        include_str!("../template/core/src/state_machines/proofs.rs"),
    ),
    (
        "core/src/state_machines/tests.rs",
        include_str!("../template/core/src/state_machines/tests.rs"),
    ),
    (
        "fuzz/.gitignore",
        include_str!("../template/fuzz/.gitignore"),
    ),
    (
        "fuzz/Cargo.toml",
        include_str!("../template/fuzz/Cargo.toml.in"),
    ),
    (
        "fuzz/fuzz_targets/.gitkeep",
        include_str!("../template/fuzz/fuzz_targets/.gitkeep"),
    ),
    (
        "fuzz/src/lib.rs",
        include_str!("../template/fuzz/src/lib.rs"),
    ),
    ("tests/cli.rs", include_str!("../template/tests/cli.rs")),
    (
        "tests/ui/.gitkeep",
        include_str!("../template/tests/ui/.gitkeep"),
    ),
];

fn local_dependency(path: &std::path::Path, version: &str) -> Result<String, CliError> {
    if !path.join("Cargo.toml").is_file() {
        return Err(CliError::new(format!(
            "missing framework crate manifest: {}",
            path.display()
        )));
    }
    let path = path
        .to_str()
        .ok_or_else(|| CliError::new("framework path must be UTF-8"))?;
    Ok(format!(
        r#"{{ path = {}, version = "={version}", default-features = false }}"#,
        toml_string(path)?
    ))
}

pub(super) fn create(command: NewCommand) -> Result<String, Box<dyn Error>> {
    validate_name(&command.name)?;
    let (dependency, mio_dependency, visualization_dependency) = match command.framework {
        Some(framework) => {
            let framework = framework.canonicalize()?;
            let parent = framework
                .parent()
                .ok_or_else(|| CliError::new("framework crate needs its checkout parent"))?;
            (
                local_dependency(&framework, FRAMEWORK_VERSION)?,
                local_dependency(&parent.join("libraries/mio"), "0.0.7")?,
                local_dependency(&parent.join("libraries/visualization"), "0.0.4")?,
            )
        }
        None => (
            format!(r#"{{ version = "={FRAMEWORK_VERSION}", default-features = false }}"#),
            r#"{ version = "=0.0.7", default-features = false }"#.into(),
            r#"{ version = "=0.0.4", default-features = false }"#.into(),
        ),
    };
    fs::create_dir(&command.destination)?;
    for (relative, template) in FILES {
        let path = command.destination.join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let contents = template
            .replace("__PROJECT__", &command.name)
            .replace("__PROJECT_CRATE__", &command.name.replace('-', "_"))
            .replace("__FRAMEWORK_DEPENDENCY__", &dependency)
            .replace("__MIO_DEPENDENCY__", &mio_dependency)
            .replace("__VISUALIZATION_DEPENDENCY__", &visualization_dependency);
        let mut file = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(path)?;
        file.write_all(contents.as_bytes())?;
    }
    Ok(format!(
        "Created {} with core, programs, and src/main.rs.\n",
        command.destination.display()
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn framework_fixture(root: &std::path::Path) -> Result<PathBuf, Box<dyn Error>> {
        let checkout = root.join("checkout with spaces");
        for relative in ["pipecircuit", "libraries/mio", "libraries/visualization"] {
            let directory = checkout.join(relative);
            fs::create_dir_all(&directory)?;
            fs::write(
                directory.join("Cargo.toml"),
                "# manifest-presence fixture\n",
            )?;
        }
        Ok(checkout.join("pipecircuit"))
    }

    #[test]
    fn generation_preserves_existing_destinations_and_rejects_invalid_names()
    -> Result<(), Box<dyn Error>> {
        let scratch = tempfile::tempdir()?;
        let destination = scratch.path().join("existing");
        fs::create_dir(&destination)?;
        fs::write(destination.join("keep"), "user work")?;
        assert!(
            create(NewCommand {
                destination: destination.clone(),
                name: "safe".to_owned(),
                framework: Some(
                    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../pipecircuit")
                ),
            })
            .is_err()
        );
        assert_eq!(fs::read_to_string(destination.join("keep"))?, "user work");
        assert!(!destination.join("Cargo.toml").exists());
        for name in ["", "../escape", "name\"injection", "Caps", "con", "com1"] {
            assert!(validate_name(name).is_err());
        }
        Ok(())
    }

    #[test]
    fn generated_libraries_share_strictness_and_only_depend_inward() -> Result<(), Box<dyn Error>> {
        let scratch = tempfile::tempdir()?;
        let destination = scratch.path().join("conversation");
        create(NewCommand {
            destination: destination.clone(),
            name: "conversation".to_owned(),
            framework: Some(framework_fixture(scratch.path())?),
        })?;
        let core = fs::read_to_string(destination.join("core/Cargo.toml"))?;
        let program = fs::read_to_string(destination.join("programs/Cargo.toml"))?;
        assert!(core.contains("workspace = true"));
        assert!(!core.contains("conversation-program"));
        assert!(program.contains("app_core.workspace = true"));
        for path in ["core/src/lib.rs", "programs/src/lib.rs"] {
            assert!(fs::read_to_string(destination.join(path))?.starts_with("#![no_std]"));
        }
        assert!(!destination.join("core/src/circuits").exists());
        assert!(destination.join("src/wiring/mod.rs").is_file());
        Ok(())
    }

    #[test]
    fn registry_default_and_incomplete_local_checkout() -> Result<(), Box<dyn Error>> {
        let scratch = tempfile::tempdir()?;
        let destination = scratch.path().join("registry-starter");
        create(NewCommand {
            destination: destination.clone(),
            name: "safe".into(),
            framework: None,
        })?;
        let manifest = fs::read_to_string(destination.join("Cargo.toml"))?;
        assert!(
            manifest.contains(r#"pipecircuit = { version = "=0.0.17", default-features = false }"#)
        );
        assert!(
            manifest
                .contains(r#"pipecircuit-mio = { version = "=0.0.7", default-features = false }"#)
        );
        assert!(manifest.contains(
            r#"pipecircuit-visualization = { version = "=0.0.4", default-features = false }"#
        ));
        let destination = scratch.path().join("not-created");
        let framework = scratch.path().join("pipecircuit");
        fs::create_dir(&framework)?;
        fs::write(framework.join("Cargo.toml"), "")?;
        assert!(
            create(NewCommand {
                destination: destination.clone(),
                name: "safe".into(),
                framework: Some(framework)
            })
            .is_err()
        );
        assert!(!destination.exists());
        Ok(())
    }

    #[test]
    fn hyphenated_names_render_rust_imports_and_all_dependencies() -> Result<(), Box<dyn Error>> {
        let scratch = tempfile::tempdir()?;
        let destination = scratch.path().join("a project with spaces");
        create(NewCommand {
            destination: destination.clone(),
            name: "counter-demo".into(),
            framework: Some(framework_fixture(scratch.path())?),
        })?;
        assert!(
            fs::read_to_string(destination.join("programs/src/lib.rs"))?
                .contains("use counter_demo_program::")
        );
        for (relative, _) in FILES {
            let contents = fs::read_to_string(destination.join(relative))?;
            for token in [
                "__PROJECT__",
                "__PROJECT_CRATE__",
                "__FRAMEWORK_DEPENDENCY__",
                "__MIO_DEPENDENCY__",
                "__VISUALIZATION_DEPENDENCY__",
            ] {
                assert!(
                    !contents.contains(token),
                    "unexpanded {token} in {relative}"
                );
            }
        }
        let manifest = fs::read_to_string(destination.join("Cargo.toml"))?;
        assert!(manifest.contains("libraries/mio"));
        assert!(manifest.contains("libraries/visualization"));
        Ok(())
    }

    #[test]
    fn new_arguments_are_unambiguous_and_paths_are_encoded_as_toml_strings()
    -> Result<(), Box<dyn Error>> {
        for values in [
            vec!["new"],
            vec!["new", "a", "b"],
            vec!["new", "a", "--name"],
            vec!["new", "a", "--framework-path"],
            vec!["new", "a", "--name", "b", "--name", "c"],
        ] {
            assert!(super::super::parse_arguments(values.into_iter().map(OsString::from)).is_err());
        }
        let Command::New(command) = parse(
            [
                "somewhere",
                "--name",
                "conversation",
                "--framework-path",
                "../pipecircuit",
            ]
            .into_iter()
            .map(OsString::from),
        )?
        else {
            return Err("new command absent".into());
        };
        assert_eq!(command.name, "conversation");
        assert_eq!(command.framework, Some(PathBuf::from("../pipecircuit")));
        assert_eq!(toml_string("a\\b\"c\nd")?, "\"a\\\\b\\\"c\\nd\"");
        Ok(())
    }
}