portaki-cli 6.6.0

Portaki module CLI (portaki) — init, build, lint, test, and OCI publish
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
//! `portaki init` — scaffold a module from templates.

use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use clap::{Parser, ValueEnum};
use include_dir::{include_dir, Dir};

use crate::ui;

/// The scaffolding, compiled into the binary.
///
/// Read from disk, it resolved against this crate's source directory — a path that exists in a
/// checkout of this repository and nowhere else, so `cargo install portaki-cli` produced a
/// command that could not scaffold anything.
static TEMPLATES: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/templates");

#[derive(Debug, Clone, ValueEnum)]
/// Template kind for `portaki init`.
pub enum InitTemplate {
    /// Default module with entity, surfaces, and i18n bundles.
    Default,
    /// Minimal empty module skeleton.
    Empty,
}

#[derive(Debug, Parser)]
/// Arguments for `portaki init`.
pub struct InitArgs {
    /// Module name (kebab-case recommended).
    pub name: String,
    /// Template to use.
    #[arg(long, value_enum, default_value_t = InitTemplate::Default)]
    pub template: InitTemplate,
    /// Output directory (defaults to `./{name}`).
    #[arg(long)]
    pub path: Option<PathBuf>,
}

/// Runs `portaki init`.
pub fn run(args: InitArgs) -> Result<()> {
    ui::header(
        "portaki init",
        "Scaffold a module crate — buildable, runnable in the sandbox, publishable.",
    );

    let dest = args
        .path
        .clone()
        .unwrap_or_else(|| PathBuf::from(&args.name));

    let template_dir = TEMPLATES
        .get_dir(directory(&args.template))
        .with_context(|| {
            format!(
                "template missing from this build: {}",
                label(&args.template)
            )
        })?;

    if dest.exists() && !dest.is_dir() {
        bail!("destination is not a directory: {}", dest.display());
    }

    // A cloned repository is the usual starting point — the directory is there, and holds a
    // `.git` and maybe a licence. Only a file the scaffold would overwrite is a reason to stop.
    let clashes = clashes(&dest, &planned_paths(template_dir));
    if !clashes.is_empty() {
        bail!(
            "{} already has {} — move them aside, or scaffold elsewhere",
            dest.display(),
            listed(&clashes)
        );
    }

    let scaffolding = ui::step(format!(
        "scaffolding {} from the {} template",
        args.name,
        label(&args.template)
    ));
    copy_template(template_dir, &dest, &args.name)?;
    scaffolding.done(format!("created {}", dest.display()));

    describe(&args.template);
    let mut next: Vec<(&str, &str)> = Vec::new();
    let cd = format!("cd {}", dest.display());
    // Scaffolded in place — `cd .` would be a step that does nothing.
    if dest != Path::new(".") {
        next.push((cd.as_str(), "everything below runs from the module root"));
    }
    next.push((
        "portaki build",
        "compile to wasm32 and assemble the manifest",
    ));
    next.push((
        "portaki dev --watch",
        "run it in the hosted sandbox on every save",
    ));
    ui::next(&next);
    ui::blank();
    Ok(())
}

/// Ce qui vient d'être écrit, et à quoi chaque morceau sert.
///
/// Un squelette qu'on découvre fichier par fichier se lit mal : `ids.rs` et `i18n/` n'ont de
/// sens que l'un par rapport à l'autre, et rien dans leur nom ne le dit.
fn describe(template: &InitTemplate) {
    let mut rows = vec![
        ("src/lib.rs", "the module — entity, capability, manifest"),
        ("src/ids.rs", "typed surface and operation ids"),
    ];
    if matches!(template, InitTemplate::Default) {
        rows.push(("src/host/", "surfaces the host dashboard renders"));
        rows.push(("src/guest/", "surfaces the guest booklet renders"));
        rows.push((
            "src/commands.rs",
            "updateConfig — what the sheet's Save posts",
        ));
        rows.push((
            "src/queries.rs",
            "getConfig — what the dashboard reads back",
        ));
        rows.push(("src/config.rs", "the settings blob, in the module's own KV"));
        rows.push(("tests/", "the mock host, the settings round-tripped"));
        rows.push((
            "tests/conformance.rs",
            "the battery every module passes before it publishes",
        ));
    }
    rows.push((
        "i18n/*.json",
        "one file per locale — the keys ids.rs points at",
    ));
    rows.push(("Cargo.toml", "wired to portaki-sdk, cdylib for wasm32"));
    rows.push((
        "build.rs",
        "no build step — it exists so cargo gives the macros an OUT_DIR",
    ));
    rows.push((
        "portaki.module.json",
        "the catalogue entry — name, author, surfaces, permissions",
    ));

    ui::list("what you got", &rows);
}

fn label(template: &InitTemplate) -> &'static str {
    match template {
        InitTemplate::Default => "default",
        InitTemplate::Empty => "empty",
    }
}

/// Names a few of the clashing paths and counts the rest.
///
/// Scaffolding over an existing module clashes on every file; seventeen paths on one line say
/// less than three and a number.
fn listed(paths: &[PathBuf]) -> String {
    const SHOWN: usize = 3;
    let named = paths
        .iter()
        .take(SHOWN)
        .map(|path| path.display().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    match paths.len().saturating_sub(SHOWN) {
        0 => named,
        rest => format!("{named} and {rest} more"),
    }
}

/// Every path this scaffold would write, relative to the destination.
fn planned_paths(source: &Dir<'_>) -> Vec<PathBuf> {
    let root = source.path();
    let mut planned = Vec::new();
    collect_paths(source, root, &mut planned);
    planned
}

fn collect_paths(source: &Dir<'_>, root: &Path, planned: &mut Vec<PathBuf>) {
    for file in source.files() {
        let relative = file.path().strip_prefix(root).unwrap_or(file.path());
        planned.push(rendered_path(relative));
    }
    for child in source.dirs() {
        collect_paths(child, root, planned);
    }
}

/// The same `.template` strip `copy_template` applies, on a whole path.
fn rendered_path(relative: &Path) -> PathBuf {
    let Some(name) = relative
        .file_name()
        .map(|name| name.to_string_lossy().to_string())
    else {
        return relative.to_path_buf();
    };
    let stripped = name.strip_suffix(".template").unwrap_or(&name);
    relative.with_file_name(stripped)
}

/// Which of those already exist — the only reason to refuse a directory that is already there.
fn clashes(dest: &Path, planned: &[PathBuf]) -> Vec<PathBuf> {
    planned
        .iter()
        .filter(|path| dest.join(path).exists())
        .cloned()
        .collect()
}

/// What `use` statements have to spell: cargo turns a kebab-case package into a snake_case lib.
fn crate_name(module_name: &str) -> String {
    module_name.replace('-', "_")
}

fn directory(template: &InitTemplate) -> &'static str {
    match template {
        InitTemplate::Default => "default-module",
        InitTemplate::Empty => "empty-module",
    }
}

/// Writes an embedded directory out, rendering each file on the way.
fn copy_template(source: &Dir<'_>, dest: &Path, module_name: &str) -> Result<()> {
    fs::create_dir_all(dest).with_context(|| format!("create {}", dest.display()))?;

    for file in source.files() {
        let name = file
            .path()
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or_default();
        // `Cargo.toml.template` would otherwise make the scaffolded crate a cargo package the
        // moment it is written, and cargo would read it while it still holds placeholders.
        let name = name.strip_suffix(".template").unwrap_or(&name).to_string();
        let target = dest.join(&name);

        let text = file
            .contents_utf8()
            .with_context(|| format!("template {} is not UTF-8", file.path().display()))?;
        // The CLI's version is the SDK it was published with: a scaffolded module compiles
        // against the SDK this command knows, not against whatever is newest.
        let rendered = text
            .replace("{{MODULE_NAME}}", module_name)
            .replace("{{CRATE_NAME}}", &crate_name(module_name))
            .replace("{{SDK_VERSION}}", env!("CARGO_PKG_VERSION"));
        fs::write(&target, rendered).with_context(|| format!("write {}", target.display()))?;
    }

    for child in source.dirs() {
        let name = child
            .path()
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or_default();
        copy_template(child, &dest.join(name), module_name)?;
    }

    Ok(())
}

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

    /// Both templates have to be in the binary, or `init` only fails for whoever installed it.
    #[test]
    fn every_template_is_embedded() {
        for template in [InitTemplate::Default, InitTemplate::Empty] {
            let dir = TEMPLATES
                .get_dir(directory(&template))
                .expect("template embedded");
            assert!(dir.files().count() + dir.dirs().count() > 0);
        }
    }

    #[test]
    fn what_a_scaffold_would_write_is_known_before_it_writes() {
        let planned = planned_paths(TEMPLATES.get_dir("default-module").expect("template"));

        // Rendered names, not template ones — that is what a clash has to be checked against.
        assert!(planned.contains(&PathBuf::from("Cargo.toml")));
        assert!(planned.contains(&PathBuf::from("portaki.module.json")));
        assert!(planned.contains(&PathBuf::from("src/host/mod.rs")));
        assert!(planned.contains(&PathBuf::from(".cargo/config.toml")));
        assert!(!planned
            .iter()
            .any(|path| path.to_string_lossy().ends_with(".template")));
    }

    #[test]
    fn a_long_clash_is_three_names_and_a_count() {
        let paths: Vec<PathBuf> = ["Cargo.toml", "build.rs", "src/lib.rs", "i18n/en-US.json"]
            .iter()
            .map(PathBuf::from)
            .collect();

        assert_eq!(listed(&paths[..2]), "Cargo.toml, build.rs");
        assert_eq!(
            listed(&paths),
            "Cargo.toml, build.rs, src/lib.rs and 1 more"
        );
    }

    /// The point of #115: a cloned repository is a directory that already exists.
    #[test]
    fn an_existing_directory_is_fine_until_a_file_would_be_overwritten() {
        let dest = std::env::temp_dir().join(format!("portaki-clash-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dest);
        fs::create_dir_all(dest.join(".git")).expect("a clone");
        let planned = planned_paths(TEMPLATES.get_dir("default-module").expect("template"));

        assert!(clashes(&dest, &planned).is_empty());

        fs::write(dest.join("Cargo.toml"), "[package]").expect("an existing crate");
        assert_eq!(clashes(&dest, &planned), vec![PathBuf::from("Cargo.toml")]);

        fs::remove_dir_all(&dest).ok();
    }

    #[test]
    fn a_kebab_case_module_becomes_a_snake_case_crate() {
        assert_eq!(crate_name("pre-arrival-form"), "pre_arrival_form");
        assert_eq!(crate_name("trmnl"), "trmnl");
    }

    /// What the two commands `init` recommends need in order to run at all.
    #[test]
    fn a_scaffold_has_what_build_and_dev_read() {
        for template in [InitTemplate::Default, InitTemplate::Empty] {
            let dir = TEMPLATES.get_dir(directory(&template)).expect("template");
            let names: Vec<String> = dir
                .files()
                .map(|file| {
                    file.path()
                        .file_name()
                        .unwrap()
                        .to_string_lossy()
                        .to_string()
                })
                .collect();

            // `portaki build` reads emissions from OUT_DIR, which only a build script creates.
            assert!(names.iter().any(|name| name == "build.rs"), "{names:?}");
            // `portaki dev`, `ci info` and `publish` all read the catalogue manifest.
            assert!(
                names
                    .iter()
                    .any(|name| name == "portaki.module.json.template"),
                "{names:?}"
            );
            // Without the custom getrandom backend, the wasm32 build stops inside getrandom.
            let cargo_config = dir
                .get_file(format!(
                    "{}/.cargo/config.toml.template",
                    directory(&template)
                ))
                .expect("wasm rustflags");
            assert!(cargo_config
                .contents_utf8()
                .unwrap_or_default()
                .contains("getrandom_backend"));
        }
    }

    #[test]
    fn a_scaffolded_module_carries_its_name_and_the_sdk_version() {
        let dest = std::env::temp_dir().join(format!("portaki-init-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dest);

        copy_template(
            TEMPLATES.get_dir("default-module").expect("template"),
            &dest,
            "concierge",
        )
        .expect("scaffold");

        let cargo = fs::read_to_string(dest.join("Cargo.toml")).expect("Cargo.toml written");
        assert!(cargo.contains("name = \"concierge\""));
        assert!(cargo.contains(env!("CARGO_PKG_VERSION")));
        assert!(!cargo.contains("{{"));
        // Nested and dot directories come out too — the wasm rustflags live in one of them.
        assert!(dest.join("src/host/mod.rs").exists());
        assert!(dest.join(".cargo/config.toml").exists());
        assert!(!dest.join("Cargo.toml.template").exists());
        // A crate name is not a module id: `use` statements need the snake_case spelling.
        let integration =
            fs::read_to_string(dest.join("tests/integration.rs")).expect("tests written");
        assert!(integration.contains("use concierge::{"));
        assert!(!integration.contains("{{"));
        // Every new module runs the conformance battery `portaki publish` gates on.
        let conformance =
            fs::read_to_string(dest.join("tests/conformance.rs")).expect("battery written");
        assert!(conformance.contains("portaki_test_utils::conformance!();"));
        let catalog =
            fs::read_to_string(dest.join("portaki.module.json")).expect("catalogue written");
        assert!(catalog.contains("\"id\": \"concierge\""));

        fs::remove_dir_all(&dest).ok();
    }
}