portaki-cli 8.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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! `portaki lint` — validate manifest and i18n bundles.

use std::path::PathBuf;

use anyhow::{Context, Result};
use clap::Parser;
use serde_json::from_reader;

use crate::manifest::collect_emissions;
use crate::manifest::{find_emissions_dir, generate_manifest, validate_manifest};
use crate::ui;
use portaki_sdk::manifest::{ManifestCommand, ModuleManifest};

#[derive(Debug, Parser)]
/// Arguments for `portaki lint`.
pub struct LintArgs {
    /// Path to `manifest.json` (defaults to `target/portaki/manifest.json`).
    #[arg(long)]
    pub manifest: Option<PathBuf>,

    /// The channel the module is headed for: `stable` refuses an SDK older than 8.0.0.
    #[arg(long, default_value = "stable", value_parser = ["preview", "stable"])]
    pub channel: String,

    /// `check` enchaîne sur `lint` : un second en-tête ferait croire à deux commandes.
    #[arg(skip)]
    pub nested: bool,
}

/// Runs `portaki lint`.
pub fn run(args: LintArgs) -> Result<()> {
    if !args.nested {
        ui::header(
            "portaki lint",
            "Check that everything the manifest names actually resolves.",
        );
    }

    let module_root = std::env::current_dir().context("current_dir")?;
    let manifest_path = args
        .manifest
        .unwrap_or_else(|| module_root.join("target/portaki/manifest.json"));

    let reading = ui::step("reading the manifest");
    let manifest = if manifest_path.exists() {
        let file = std::fs::File::open(&manifest_path)?;
        let manifest = from_reader::<_, ModuleManifest>(file)?;
        reading.done(format!("read {}", manifest_path.display()));
        manifest
    } else if let Some(emissions_dir) = find_emissions_dir(&module_root) {
        let emissions = collect_emissions(&emissions_dir)?;
        let manifest = generate_manifest(
            &emissions,
            "fr-FR",
            &["fr-FR".to_string(), "en-US".to_string()],
        )?;
        reading.done("read the SDK emissions (no build output yet)");
        manifest
    } else {
        reading.abandon();
        anyhow::bail!("no manifest or emissions found — run portaki build first");
    };

    let checking = ui::step("checking capability ids, connector bindings, and i18n keys");
    validate_manifest(&manifest, &module_root.join("i18n")).map_err(|failure| {
        checking.abandon();
        failure
    })?;
    assert_known_permissions(&module_root).map_err(|failure| {
        checking.abandon();
        failure
    })?;
    // Le manifeste que `publish` enverra, écrit du code par `portaki build` : le registre le
    // refuserait hors schéma, autant le dire ici.
    portaki_test_utils::conformance::Module::at(&module_root)
        .check_manifest()
        .map_err(|findings| {
            checking.abandon();
            anyhow::anyhow!("{findings}")
        })?;
    assert_versions_agree(&module_root, &manifest).map_err(|failure| {
        checking.abandon();
        failure
    })?;
    assert_sdk_version(
        &manifest_path.with_file_name(crate::oci::pack::PUBLISH_MANIFEST),
        &args.channel,
    )
    .map_err(|failure| {
        checking.abandon();
        failure
    })?;
    assert_feeds_valid(&module_root).map_err(|failure| {
        checking.abandon();
        failure
    })?;
    checking.done(format!("{} passes", manifest.id));
    for name in host_like_guest_commands(&manifest.commands) {
        ui::warn(format!(
            "command {name} is open to guests but reads like a host operation — \
             drop `guest` unless a guest really calls it"
        ));
    }
    report_changelog(&module_root, &manifest.version)?;
    ui::detail("capability ids, connector bindings and i18n keys all resolve");
    ui::blank();
    Ok(())
}

/// What `portaki publish` would stamp as this version's changelog, by language.
///
/// A warning, not a failure: preview channels never wait. But a stable version without a line in
/// every language of its listing stays pending at the registry — better read here than after the
/// release job.
fn report_changelog(module_root: &std::path::Path, version: &str) -> Result<()> {
    let lines = crate::changelog::lines(&[], "en", module_root, version)?;
    let langs: std::collections::BTreeSet<&str> = lines
        .iter()
        .flat_map(|line| line.keys().map(String::as_str))
        .collect();
    if langs.is_empty() {
        ui::warn(format!(
            "no changelog for {version} — a stable publication stays pending until it has a line \
             in every language of the listing: write CHANGELOG.<lang>.md, or pass \
             portaki publish --notes <lang>:…"
        ));
    } else {
        ui::detail(format!(
            "changelog {version}: {} line(s) in {}",
            lines.len(),
            langs.into_iter().collect::<Vec<_>>().join(", ")
        ));
    }
    Ok(())
}

/// The manifest `publish` sends must say which SDK built it — and, for `stable`, a recent one.
///
/// Read from the publish manifest `portaki build` writes: that is where `sdkVersion` is stamped,
/// from the crate cargo resolved.
pub(crate) fn assert_sdk_version(publish_manifest: &std::path::Path, channel: &str) -> Result<()> {
    let manifest = std::fs::read_to_string(publish_manifest)
        .ok()
        .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
        .unwrap_or_default();
    match sdk_version_problem(&manifest, channel) {
        Some(problem) => anyhow::bail!("{problem}"),
        None => Ok(()),
    }
}

fn sdk_version_problem(manifest: &serde_json::Value, channel: &str) -> Option<String> {
    use portaki_sdk::manifest::MIN_STABLE_SDK;
    let Some(version) = manifest.get("sdkVersion").and_then(|v| v.as_str()) else {
        return Some(
            "the manifest carries no sdkVersion — run portaki build, which stamps it from the \
             portaki-sdk crate cargo resolved"
                .to_string(),
        );
    };
    let parse = crate::commands::sdk::parse_version;
    let Some(parsed) = parse(version) else {
        return Some(format!("sdkVersion {version} is not a version"));
    };
    if channel == "stable" && parse(MIN_STABLE_SDK).is_some_and(|min| parsed < min) {
        return Some(format!(
            "SDK too old for stable: built on portaki-sdk {version}, stable needs {MIN_STABLE_SDK} \
             or later — run portaki sdk upgrade, or publish with --channel preview"
        ));
    }
    None
}

/// A permission the manifest schema does not know.
///
/// The registry refuses it at publication, against the schema of the SDK the module targets.
/// Saying so here is cheaper than a refused publish — and a misspelt `stay:guest_contact:read`
/// would otherwise build, deploy, and quietly leave the guest's contact details empty.
fn assert_known_permissions(module_root: &std::path::Path) -> Result<()> {
    let unknown = unknown_permissions(&declared_permissions(module_root));
    if unknown.is_empty() {
        return Ok(());
    }
    anyhow::bail!(
        "portaki.module.json declares unknown permission(s) {} — known: {}, connectors:<id>",
        unknown.join(", "),
        portaki_sdk::permission::FIXED.join(", ")
    )
}

/// The `permissions` of `portaki.module.json`, empty when the file or the field is absent.
fn declared_permissions(module_root: &std::path::Path) -> Vec<String> {
    std::fs::read_to_string(module_root.join("portaki.module.json"))
        .ok()
        .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
        .and_then(|manifest| manifest.get("permissions").cloned())
        .and_then(|permissions| serde_json::from_value::<Vec<String>>(permissions).ok())
        .unwrap_or_default()
}

fn unknown_permissions(declared: &[String]) -> Vec<String> {
    declared
        .iter()
        .filter(|permission| !portaki_sdk::permission::is_known(permission))
        .cloned()
        .collect()
}

/// `feeds` — the modules this one supplies — must name another module and say what, in fr and en.
///
/// The catalogue turns it into a sentence (« Nuki fournit le code clavier au module Accès ») :
/// a missing locale or a typo'd id would print a hole or a dead link on the public sheet.
fn assert_feeds_valid(module_root: &std::path::Path) -> Result<()> {
    let Some(manifest) = std::fs::read_to_string(module_root.join("portaki.module.json"))
        .ok()
        .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
    else {
        return Ok(());
    };
    let problems = feeds_problems(&manifest);
    if problems.is_empty() {
        return Ok(());
    }
    anyhow::bail!("portaki.module.json feeds: {}", problems.join("; "))
}

fn feeds_problems(manifest: &serde_json::Value) -> Vec<String> {
    let Some(feeds) = manifest.get("feeds") else {
        return vec![];
    };
    let Some(feeds) = feeds.as_array() else {
        return vec!["must be an array".to_string()];
    };
    let own_id = manifest
        .get("id")
        .and_then(|id| id.as_str())
        .unwrap_or_default();
    let mut problems = Vec::new();
    for (index, feed) in feeds.iter().enumerate() {
        let module = feed
            .get("module")
            .and_then(|m| m.as_str())
            .unwrap_or_default();
        let valid_id = module.starts_with(|c: char| c.is_ascii_lowercase())
            && module
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
        if !valid_id {
            problems.push(format!("[{index}].module \"{module}\" is not a module id"));
        } else if module == own_id {
            problems.push(format!("[{index}].module names the module itself"));
        }
        for locale in ["fr", "en"] {
            let text = feed
                .pointer(&format!("/what/{locale}"))
                .and_then(|t| t.as_str())
                .unwrap_or_default();
            if text.trim().is_empty() {
                problems.push(format!("[{index}].what.{locale} is missing"));
            }
        }
    }
    problems
}

/// La crate et le manifeste doivent annoncer la même version.
///
/// `release-please` incrémente les deux ; si l'un des deux passe à travers, un artefact part
/// sous un numéro que rien d'autre ne porte, et la version publiée cesse de désigner le code
/// qu'elle contient. Le contrôle vivait dans le script bash d'un dépôt — il appartient au lint.
fn assert_versions_agree(module_root: &std::path::Path, manifest: &ModuleManifest) -> Result<()> {
    let cargo = module_root.join("Cargo.toml");
    let Ok(text) = std::fs::read_to_string(&cargo) else {
        // Pas de crate ici : un manifeste peut être linté seul.
        return Ok(());
    };
    let Some(declared) = crate_version(&text) else {
        return Ok(());
    };
    if declared == manifest.version {
        return Ok(());
    }
    anyhow::bail!(
        "Cargo.toml says {declared} and the manifest says {} — a release bumps both, so one of \
         them was missed",
        manifest.version
    )
}

/// La version de `[package]`, sans analyseur TOML pour un champ.
///
/// Lue dans sa seule section : une `version` de dépendance ne doit pas passer pour celle de la
/// crate. Une version héritée de l'espace de travail n'est pas lisible ici, et se lit comme
/// absente plutôt que comme un désaccord.
fn crate_version(cargo: &str) -> Option<String> {
    let mut in_package = false;
    for line in cargo.lines() {
        let line = line.trim();
        if line.starts_with('[') {
            in_package = line == "[package]";
            continue;
        }
        if !in_package {
            continue;
        }
        if let Some(rest) = line.strip_prefix("version") {
            let rest = rest.trim_start().strip_prefix('=')?.trim();
            return rest
                .strip_prefix('"')
                .and_then(|rest| rest.strip_suffix('"'))
                .map(str::to_string);
        }
    }
    None
}

/// Guest commands named like the host's own gestures — a finding, not a failure: the name is
/// only a hint, and the module may have a reason.
fn host_like_guest_commands(commands: &[ManifestCommand]) -> Vec<&str> {
    const HOST: [&str; 5] = [
        "updateConfig",
        "resolve",
        "updateStatus",
        "seedDefaults",
        "replaceItems",
    ];
    commands
        .iter()
        .filter(|command| command.guest)
        .map(|command| command.name.as_str())
        .filter(|name| HOST.contains(name) || name.starts_with("task"))
        .collect()
}

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

    #[test]
    fn a_guest_command_named_like_a_host_one_is_flagged() {
        let command = |name: &str, guest| ManifestCommand {
            name: name.to_string(),
            r#fn: String::new(),
            args: None,
            params: None,
            guest,
        };
        let commands = [
            command("taskToggle", true),
            command("submit", true),
            command("updateConfig", false),
        ];
        assert_eq!(host_like_guest_commands(&commands), ["taskToggle"]);
    }

    #[test]
    fn the_crate_version_is_read_from_its_own_section() {
        let cargo = r#"
[package]
name = "weather"
version = "0.3.24"

[dependencies]
serde = { version = "1", features = ["derive"] }
"#;

        assert_eq!(crate_version(cargo).as_deref(), Some("0.3.24"));
    }

    /// Une `version` de dépendance ne doit pas passer pour celle de la crate.
    #[test]
    fn a_dependency_version_is_not_mistaken_for_the_crate() {
        let cargo = "[dependencies]\nserde = { version = \"1\" }\n";

        assert!(crate_version(cargo).is_none());
    }

    #[test]
    fn the_guest_contact_permission_is_accepted() {
        let declared = vec![
            "kv".to_string(),
            "stay:guest_contact:read".to_string(),
            "connectors:nuki".to_string(),
        ];

        assert!(unknown_permissions(&declared).is_empty());
    }

    /// `stay:read` est un scope de jeton, pas une permission de manifeste : le séjour se lit sans.
    #[test]
    fn an_unknown_or_misspelt_permission_is_named() {
        let declared = vec![
            "stay:read".to_string(),
            "stay:guest-contact:read".to_string(),
            "email".to_string(),
        ];

        assert_eq!(
            unknown_permissions(&declared),
            vec![
                "stay:read".to_string(),
                "stay:guest-contact:read".to_string()
            ]
        );
    }

    #[test]
    fn permissions_are_read_from_the_catalogue_manifest() {
        let root = std::env::temp_dir().join(format!("portaki-lint-{}", std::process::id()));
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(
            root.join("portaki.module.json"),
            r#"{"id":"checkin","permissions":["stay:guest_contact:read","stay:read"]}"#,
        )
        .unwrap();

        let failure = assert_known_permissions(&root).unwrap_err().to_string();
        std::fs::remove_dir_all(&root).ok();

        assert!(failure.contains("stay:read"), "{failure}");
        assert!(!failure.contains("unknown permission(s) stay:guest_contact:read"));
    }

    #[test]
    fn a_well_formed_feed_passes() {
        let manifest = serde_json::json!({
            "id": "nuki",
            "feeds": [{ "module": "access-guide", "what": { "fr": "le code clavier", "en": "the keypad code" } }]
        });

        assert!(feeds_problems(&manifest).is_empty());
        assert!(feeds_problems(&serde_json::json!({ "id": "nuki" })).is_empty());
    }

    #[test]
    fn a_bad_feed_is_named() {
        let manifest = serde_json::json!({
            "id": "nuki",
            "feeds": [
                { "module": "Access_Guide", "what": { "fr": "le code", "en": "the code" } },
                { "module": "nuki", "what": { "fr": "x", "en": "x" } },
                { "module": "access-guide", "what": { "fr": "le code clavier" } }
            ]
        });

        assert_eq!(
            feeds_problems(&manifest),
            vec![
                "[0].module \"Access_Guide\" is not a module id".to_string(),
                "[1].module names the module itself".to_string(),
                "[2].what.en is missing".to_string(),
            ]
        );
    }

    #[test]
    fn the_sdk_version_is_required_and_recent_for_stable() {
        let missing = sdk_version_problem(&serde_json::json!({ "id": "x" }), "preview");
        assert!(missing.unwrap().contains("no sdkVersion"));

        let old = serde_json::json!({ "sdkVersion": "7.9.3" });
        assert!(sdk_version_problem(&old, "stable")
            .unwrap()
            .contains("too old for stable"));
        assert!(sdk_version_problem(&old, "preview").is_none());

        for fine in ["8.0.0", "8.4.0", "10.0.0"] {
            let manifest = serde_json::json!({ "sdkVersion": fine });
            assert!(sdk_version_problem(&manifest, "stable").is_none(), "{fine}");
        }
    }

    #[test]
    fn a_workspace_inherited_version_is_left_alone() {
        let cargo = "[package]\nname = \"weather\"\nversion.workspace = true\n";

        assert!(crate_version(cargo).is_none());
    }
}