portaki-cli 10.1.0

Portaki module CLI (portaki) — init, build, test, hosted sandbox, OCI publish and registry announcement
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! `portaki release status <v>` and `portaki release notes <v>` — a published version, as the
//! developer space's Versions page shows it, and as its « Compléter la version » drawer does.
//!
//! Routes: `GET /dev/v1/modules/{id}/versions` to find the version's digest, then
//! `GET|PUT /dev/v1/publications/{digest}/release`. The registry revalidates everything on the
//! `PUT`: whatever is still missing comes back as a 409, and nothing is written.

use std::collections::BTreeMap;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use reqwest::Method;
use serde_json::{json, Value};

use crate::api::Platform;
use crate::workspace::ModuleArgs;
use crate::{changelog, ui};

#[derive(Debug, Subcommand)]
pub enum ReleaseAction {
    /// Where a published version stands: draft or available, signature, review, what is missing.
    Status(StatusArgs),
    /// Read a version's release notes — and complete them, from flags or CHANGELOG files.
    Notes(NotesArgs),
}

#[derive(Debug, Parser)]
/// Arguments for `portaki release status`.
pub struct StatusArgs {
    /// The version, e.g. `1.2.0`.
    pub version: String,
    /// The channel, when the version exists on both.
    #[arg(long, value_parser = ["preview", "stable"])]
    pub channel: Option<String>,
    #[command(flatten)]
    pub modules: ModuleArgs,
}

#[derive(Debug, Parser)]
/// Arguments for `portaki release notes`.
pub struct NotesArgs {
    /// The version, e.g. `1.2.0`.
    pub version: String,
    /// The channel, when the version exists on both.
    #[arg(long, value_parser = ["preview", "stable"])]
    pub channel: Option<String>,
    /// Send the notes to the registry: the changelog from `--notes`, then from `CHANGELOG*.md`.
    /// Implied by any of the flags below.
    #[arg(long)]
    pub complete: bool,
    /// A changelog line, `[lang:]text` — replaces the language's lines.
    #[arg(long = "notes", value_name = "[LANG:]LINE")]
    pub notes: Vec<String>,
    /// Why a permission is added, `<permission>=[lang:]text`.
    #[arg(long = "permission-reason", value_name = "PERMISSION=[LANG:]TEXT")]
    pub permission_reasons: Vec<String>,
    /// The host has to act after updating.
    #[arg(long)]
    pub host_action_required: bool,
    /// What the host has to do, `[lang:]text`.
    #[arg(long = "host-action", value_name = "[LANG:]TEXT")]
    pub host_action: Vec<String>,
    #[command(flatten)]
    pub modules: ModuleArgs,
}

impl NotesArgs {
    fn completes(&self) -> bool {
        self.complete
            || !self.notes.is_empty()
            || !self.permission_reasons.is_empty()
            || self.host_action_required
            || !self.host_action.is_empty()
    }
}

/// Runs `portaki release status|notes`.
pub async fn run(action: ReleaseAction) -> Result<()> {
    match action {
        ReleaseAction::Status(args) => status(args).await,
        ReleaseAction::Notes(args) => notes(args).await,
    }
}

async fn status(args: StatusArgs) -> Result<()> {
    ui::header(
        "portaki release status",
        &crate::tr!(
            "Where a published version stands — and what it still needs.",
            "Où en est une version publiée — et ce qui lui manque encore."
        ),
    );
    let member = args.modules.one("release status")?;
    let mut platform = open()?;
    let (entry, release) = find(
        &mut platform,
        &member.id,
        &args.version,
        args.channel.as_deref(),
    )
    .await?;
    let next = next_for(&release, &args.version, &args.modules);

    if ui::json() {
        ui::emit(&json!({
            "schemaVersion": 1,
            "module": member.id,
            "version": args.version,
            "channel": release["channel"],
            "digest": release["digest"],
            "state": release["releaseState"],
            "review": entry["status"],
            "yanked": entry["yanked"],
            "signature": release["supplyChain"]["signature"].as_str().unwrap_or("unsigned"),
            "signatureSource": release["supplyChain"]["signatureSource"],
            "missing": release["missing"],
            "next": { "command": next.0, "reason": next.1 },
        }));
        return Ok(());
    }

    let text = |value: &Value| value.as_str().unwrap_or_default().to_string();
    ui::field(
        "version",
        format!("{} · {}", args.version, text(&release["channel"])),
    );
    ui::field("digest", text(&release["digest"]));
    ui::field("state", text(&release["releaseState"]));
    ui::field("review", text(&entry["status"]));
    ui::field("signature", signature_line(&release["supplyChain"]));
    if entry["yanked"].as_bool().unwrap_or(false) {
        ui::warn(crate::tr!(
            "yanked — hosts can no longer install it",
            "retirée — les hôtes ne peuvent plus l'installer"
        ));
    }
    print_missing(&release["missing"]);
    let said = if crate::lang::french() {
        next.2
    } else {
        next.1
    };
    ui::next(&[(next.0.as_deref().unwrap_or("—"), said)]);
    ui::blank();
    Ok(())
}

async fn notes(args: NotesArgs) -> Result<()> {
    ui::header(
        "portaki release notes",
        &crate::tr!("A version's release notes, as hosts read them — completed here, checked by the registry.", "Les notes d'une version, telles que les hôtes les lisent — complétées ici, vérifiées par le registre."),
    );
    let member = args.modules.one("release notes")?;
    let mut platform = open()?;
    let (_, mut release) = find(
        &mut platform,
        &member.id,
        &args.version,
        args.channel.as_deref(),
    )
    .await?;

    if args.completes() {
        let body = merged_notes(&release["notes"], &args, &member.root)?;
        let sending = ui::step(crate::tr!(
            "sending the notes to the registry",
            "envoi des notes au registre"
        ));
        let path = format!("/dev/v1/publications/{}/release", text(&release["digest"]));
        let (status, answer) = platform.send(Method::PUT, &path, Some(&body)).await?;
        match status {
            200..=299 => {
                sending.done(crate::tr!(
                    "{} is {}",
                    "{} est {}",
                    args.version,
                    text(&answer["releaseState"])
                ));
                release = answer;
            }
            409 => {
                sending.abandon();
                // Refused without writing anything: what is missing is in the refusal, to be
                // passed on as it stands.
                print_missing(&answer["missing"]);
                anyhow::bail!(crate::tr!(
                    "the registry kept {} as a draft — {}",
                    "le registre garde {} en brouillon — {}",
                    args.version,
                    answer["message"]
                        .as_str()
                        .unwrap_or("notes still incomplete")
                ));
            }
            _ => {
                sending.abandon();
                anyhow::bail!(
                    "{}",
                    crate::http::refused(
                        &format!("{}{path}", platform.base),
                        status,
                        &answer.to_string()
                    )
                );
            }
        }
    }

    if ui::json() {
        ui::emit(&json!({
            "schemaVersion": 1,
            "module": member.id,
            "version": args.version,
            "digest": release["digest"],
            "state": release["releaseState"],
            "langs": release["langs"],
            "added": release["added"],
            "notes": release["notes"],
            "missing": release["missing"],
        }));
        return Ok(());
    }

    let notes = &release["notes"];
    let langs: Vec<String> = release["langs"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|lang| lang.as_str().map(str::to_string))
        .collect();
    ui::field("state", text(&release["releaseState"]));
    ui::field("languages", langs.join(", "));
    for lang in &langs {
        ui::section(&format!("changelog · {lang}"));
        let lines: Vec<&str> = notes["changelog"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|line| line[lang.as_str()].as_str())
            .collect();
        if lines.is_empty() {
            ui::skipped(crate::tr!("no line", "aucune ligne"));
        }
        for line in lines {
            ui::detail(format!("- {line}"));
        }
    }
    if let Some(reasons) = notes["permissionReasons"]
        .as_object()
        .filter(|r| !r.is_empty())
    {
        ui::section(&crate::tr!(
            "permission reasons",
            "justifications de permission"
        ));
        for (permission, by_lang) in reasons {
            for (lang, reason) in by_lang.as_object().into_iter().flatten() {
                ui::field(
                    permission,
                    format!("{lang}: {}", reason.as_str().unwrap_or_default()),
                );
            }
        }
    }
    if notes["hostActionRequired"].as_bool().unwrap_or(false) {
        ui::section(&crate::tr!("host action", "action de l'hôte"));
        for (lang, action) in notes["hostAction"].as_object().into_iter().flatten() {
            ui::field(lang, action.as_str().unwrap_or_default());
        }
    }
    print_missing(&release["missing"]);
    let next = next_for(&release, &args.version, &args.modules);
    let said = if crate::lang::french() {
        next.2
    } else {
        next.1
    };
    ui::next(&[(next.0.as_deref().unwrap_or("—"), said)]);
    ui::blank();
    Ok(())
}

fn open() -> Result<Platform> {
    Platform::open(&crate::profile::api_url(None))
}

fn text(value: &Value) -> String {
    value.as_str().unwrap_or_default().to_string()
}

/// The entry in the list of versions, and its release page.
async fn find(
    platform: &mut Platform,
    id: &str,
    version: &str,
    channel: Option<&str>,
) -> Result<(Value, Value)> {
    let versions = platform
        .get(&format!("/dev/v1/modules/{id}/versions"))
        .await?
        .unwrap_or(Value::Array(Vec::new()));
    let entry = pick(&versions, version, channel).with_context(|| {
        crate::tr!(
            "{id} {version} is not published — portaki status lists the latest version",
            "{id} {version} n'est pas publiée — portaki status donne la dernière version"
        )
    })?;
    let digest = text(&entry["digest"]);
    let release = platform
        .get(&format!("/dev/v1/publications/{digest}/release"))
        .await?
        .with_context(|| format!("no release page for {digest}"))?;
    Ok((entry, release))
}

/// The requested version; the stable one first when it exists on both channels.
fn pick(versions: &Value, version: &str, channel: Option<&str>) -> Option<Value> {
    let matching: Vec<&Value> = versions
        .as_array()?
        .iter()
        .filter(|entry| entry["version"] == version)
        .filter(|entry| channel.map_or(true, |channel| entry["channel"] == channel))
        .collect();
    matching
        .iter()
        .find(|entry| entry["channel"] == "stable")
        .or(matching.first())
        .map(|entry| (*entry).clone())
}

/// The notes to send: the registry's, completed with what the flags and the version's
/// `CHANGELOG*.md` files say.
fn merged_notes(current: &Value, args: &NotesArgs, module_root: &std::path::Path) -> Result<Value> {
    let lang = changelog::default_lang(module_root);
    let extra = changelog::release_notes(
        &args.permission_reasons,
        args.host_action_required,
        &args.host_action,
        &lang,
    )?;
    let mut changelog: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for line in current["changelog"].as_array().into_iter().flatten() {
        for (lang, text) in line.as_object().into_iter().flatten() {
            changelog
                .entry(lang.clone())
                .or_default()
                .push(text.as_str().unwrap_or_default().to_string());
        }
    }
    // A language given by `--notes` or by a file is replaced whole; the others stay put.
    let mut fresh: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for line in changelog::lines(&args.notes, &lang, module_root, &args.version)? {
        for (lang, text) in line {
            fresh.entry(lang).or_default().push(text);
        }
    }
    changelog.extend(fresh);
    let count = changelog.values().map(Vec::len).max().unwrap_or(0);
    let lines: Vec<BTreeMap<&str, &str>> = (0..count)
        .map(|index| {
            changelog
                .iter()
                .filter_map(|(lang, lines)| Some((lang.as_str(), lines.get(index)?.as_str())))
                .collect()
        })
        .collect();

    let mut reasons = current["permissionReasons"]
        .as_object()
        .cloned()
        .unwrap_or_default();
    for (permission, by_lang) in extra["permissionReasons"].as_object().into_iter().flatten() {
        let entry = reasons
            .entry(permission.clone())
            .or_insert_with(|| json!({}));
        for (lang, text) in by_lang.as_object().into_iter().flatten() {
            entry[lang] = text.clone();
        }
    }
    let mut action = current["hostAction"]
        .as_object()
        .cloned()
        .unwrap_or_default();
    for (lang, text) in extra["hostAction"].as_object().into_iter().flatten() {
        action.insert(lang.clone(), text.clone());
    }
    let required = current["hostActionRequired"].as_bool().unwrap_or(false)
        || extra["hostActionRequired"].as_bool().unwrap_or(false);
    Ok(json!({
        "changelog": lines,
        "permissionReasons": reasons,
        "hostActionRequired": required,
        "hostAction": action,
    }))
}

/// What is missing, in the developer space's own words.
fn print_missing(missing: &Value) {
    let items = missing.as_array().cloned().unwrap_or_default();
    if items.is_empty() {
        return;
    }
    ui::section(&crate::tr!("missing", "ce qui manque"));
    for item in &items {
        ui::failure(missing_line(item));
    }
}

pub(crate) fn missing_line(item: &Value) -> String {
    let lang = item["lang"].as_str().unwrap_or("?");
    match item["kind"].as_str().unwrap_or_default() {
        "changelog" => format!("changelog ({lang})"),
        "changelogRewrite" => crate::tr!(
            "changelog to rewrite ({lang}) — a line reads like a commit",
            "changelog à reformuler ({lang}) — une ligne ressemble à un commit"
        ),
        "hostAction" => crate::tr!("host action ({lang})", "action de l'hôte ({lang})"),
        "permissionReason" => crate::tr!(
            "reason for {} ({lang})",
            "justification de {} ({lang})",
            item["permission"].as_str().unwrap_or("?")
        ),
        "conformance" => crate::tr!(
            "check {} fails — fix the module and publish a new version",
            "contrôle {} en échec — corrigez le module et publiez une nouvelle version",
            item["check"].as_str().unwrap_or("?")
        ),
        "conformance_pending" => {
            crate::tr!(
                "checks still running — the version goes live by itself if they pass",
                "contrôles techniques en cours — la version paraîtra d'elle-même s'ils passent"
            )
        }
        other => other.to_string(),
    }
}

fn signature_line(chain: &Value) -> String {
    match (
        chain["signature"].as_str(),
        chain["signatureSource"].as_str(),
    ) {
        (Some("signed"), Some(source)) => crate::tr!("signed ({source})", "signée ({source})"),
        (Some("signed"), None) => crate::tr!("signed", "signée"),
        (Some("unverified"), _) => crate::tr!(
            "not verified — production will not run it",
            "non vérifiée — la production ne l'exécutera pas"
        ),
        _ => crate::tr!(
            "unsigned — production will never run it",
            "non signée — la production ne l'exécutera jamais"
        ),
    }
}

/// The next command for this version.
/// The next command, the reason in English (the one `--json` carries) and in French.
fn next_for(
    release: &Value,
    version: &str,
    modules: &ModuleArgs,
) -> (Option<String>, &'static str, &'static str) {
    let flag = modules
        .module
        .as_deref()
        .map(|id| format!(" --module {id}"))
        .unwrap_or_default();
    let kinds: Vec<&str> = release["missing"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|item| item["kind"].as_str())
        .collect();
    if kinds.contains(&"conformance") {
        return (
            Some(format!("portaki check{flag}")),
            "a blocking check fails on this digest — fix, then release a new version",
            "un contrôle bloquant échoue sur ce digest — corrigez, puis publiez une nouvelle version",
        );
    }
    if kinds.contains(&"conformance_pending") {
        return (
            Some(format!("portaki release status {version}{flag}")),
            "checks are still running — look again in a moment",
            "les contrôles tournent encore — revenez dans un instant",
        );
    }
    if !kinds.is_empty() {
        return (
            Some(format!("portaki release notes {version} --complete{flag}")),
            "write what is missing (--notes, CHANGELOG.<lang>.md), then complete the version",
            "écrivez ce qui manque (--notes, CHANGELOG.<lang>.md), puis complétez la version",
        );
    }
    if release["supplyChain"]["signature"] != "signed" {
        return (
            Some(format!("portaki release{flag}")),
            "sign the next version — production runs signed versions only",
            "signer la prochaine version — la production n'exécute que des versions signées",
        );
    }
    (
        Some(format!("portaki reports --open{flag}")),
        "live — follow what hosts and the runtime report",
        "disponible — suivez ce que remontent les hôtes et le runtime",
    )
}

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

    #[test]
    fn the_stable_wins_when_a_version_is_on_both_channels() {
        let versions = json!([
            { "version": "1.0.0", "channel": "preview", "digest": "sha256:p" },
            { "version": "1.0.0", "channel": "stable", "digest": "sha256:s" },
            { "version": "0.9.0", "channel": "stable", "digest": "sha256:o" },
        ]);

        assert_eq!(
            pick(&versions, "1.0.0", None).unwrap()["digest"],
            "sha256:s"
        );
        assert_eq!(
            pick(&versions, "1.0.0", Some("preview")).unwrap()["digest"],
            "sha256:p"
        );
        assert!(pick(&versions, "2.0.0", None).is_none());
    }

    /// A language given by `--notes` is replaced; one it does not give stays as the registry has
    /// it.
    #[test]
    fn completing_replaces_only_the_languages_given() {
        let dir = tempfile::tempdir().unwrap();
        let current = json!({
            "changelog": [{ "fr": "Ancienne", "en": "Old" }],
            "permissionReasons": { "email": { "fr": "Pour prévenir" } },
            "hostActionRequired": false,
            "hostAction": {},
        });
        let args = NotesArgs {
            version: "1.0.0".into(),
            channel: None,
            complete: true,
            notes: vec!["en:Faster sync".into()],
            permission_reasons: vec!["email=en:To warn".into()],
            host_action_required: false,
            host_action: vec![],
            modules: ModuleArgs::default(),
        };

        let body = merged_notes(&current, &args, dir.path()).unwrap();

        assert_eq!(
            body["changelog"],
            json!([{ "fr": "Ancienne", "en": "Faster sync" }])
        );
        assert_eq!(
            body["permissionReasons"]["email"],
            json!({ "fr": "Pour prévenir", "en": "To warn" })
        );
    }

    #[test]
    fn the_next_command_follows_what_is_missing() {
        let modules = ModuleArgs::default();
        let draft = json!({ "missing": [{ "kind": "changelog", "lang": "fr" }] });
        assert_eq!(
            next_for(&draft, "1.0.0", &modules).0.unwrap(),
            "portaki release notes 1.0.0 --complete"
        );
        let blocked = json!({ "missing": [{ "kind": "conformance", "check": "surfaces" }] });
        assert_eq!(
            next_for(&blocked, "1.0.0", &modules).0.unwrap(),
            "portaki check"
        );
        let live = json!({ "missing": [], "supplyChain": { "signature": "signed" } });
        assert_eq!(
            next_for(&live, "1.0.0", &modules).0.unwrap(),
            "portaki reports --open"
        );
    }
}