sylphx-cli 0.29.58

The Sylphx CLI: every Sylphx API method as a command, generated from the Sylphx schema registry.
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
//! `--output table|json|yaml|name` (spec ยง8.5): tables show name, Ready, and
//! age; `name` prints names only, for scripts.

use serde_json::Value;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    Table,
    Json,
    Yaml,
    Name,
}

impl Format {
    pub fn parse(s: &str) -> Result<Self, String> {
        Ok(match s {
            "table" => Self::Table,
            "json" => Self::Json,
            "yaml" => Self::Yaml,
            "name" => Self::Name,
            other => {
                return Err(format!(
                    "unknown output format `{other}` (table, json, yaml, name)"
                ))
            }
        })
    }
}

/// The items of a List response: its one array field.
pub fn list_items(v: &Value) -> Option<&Vec<Value>> {
    let obj = v.as_object()?;
    obj.iter()
        .filter(|(k, _)| k.as_str() != "next_page_token")
        .find_map(|(_, v)| v.as_array())
}

pub fn render(v: &Value, format: Format) -> String {
    match format {
        Format::Json => serde_json::to_string_pretty(v).unwrap_or_default(),
        Format::Yaml => serde_yaml_ng::to_string(v)
            .unwrap_or_default()
            .trim_end()
            .to_string(),
        Format::Name => {
            // Named resources can contain arrays of their own (e.g. Release services).
            if let Some(name) = v.get("name").and_then(Value::as_str) {
                return name.to_owned();
            }
            list_items(v)
                .into_iter()
                .flatten()
                .filter_map(|i| i.get("name").and_then(Value::as_str))
                .collect::<Vec<_>>()
                .join("\n")
        }
        Format::Table => match list_items(v) {
            Some(items) if is_secret_list(items) => secrets_table(items),
            Some(items) if is_project_list(items) || is_org_list(items) => {
                named_resource_table(items)
            }
            Some(items) if is_env_list(items) => envs_table(items),
            Some(items) => table(items),
            None => serde_yaml_ng::to_string(v)
                .unwrap_or_default()
                .trim_end()
                .to_string(),
        },
    }
}

fn ready(item: &Value) -> String {
    item.get("status")
        .and_then(|s| s.get("conditions"))
        .and_then(Value::as_array)
        .and_then(|cs| {
            cs.iter()
                .find(|c| c.get("type").and_then(Value::as_str) == Some("Ready"))
        })
        .and_then(|c| c.get("status").and_then(Value::as_str))
        .map(|s| s.to_ascii_lowercase())
        .unwrap_or_else(|| "-".into())
}

fn age(item: &Value) -> String {
    let Some(t) = item
        .get("meta")
        .and_then(|m| m.get("create_time"))
        .and_then(Value::as_str)
    else {
        return "-".into();
    };
    match seconds_since(t) {
        Some(s) if s < 120 => format!("{s}s"),
        Some(s) if s < 7200 => format!("{}m", s / 60),
        Some(s) if s < 172_800 => format!("{}h", s / 3600),
        Some(s) => format!("{}d", s / 86_400),
        None => "-".into(),
    }
}

/// Seconds from an RFC 3339 UTC timestamp (`2026-09-22T18:00:00Z`) to now.
fn seconds_since(t: &str) -> Option<u64> {
    let (date, time) = t.trim_end_matches('Z').split_once('T')?;
    let mut d = date.split('-').map(|x| x.parse::<i64>());
    let (y, m, day) = (d.next()?.ok()?, d.next()?.ok()?, d.next()?.ok()?);
    let mut tt = time.split(':');
    let (h, mi) = (
        tt.next()?.parse::<i64>().ok()?,
        tt.next()?.parse::<i64>().ok()?,
    );
    let s = tt.next()?.split('.').next()?.parse::<i64>().ok()?;
    // Days from civil (Howard Hinnant).
    let y2 = if m <= 2 { y - 1 } else { y };
    let era = if y2 >= 0 { y2 } else { y2 - 399 } / 400;
    let yoe = y2 - era * 400;
    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    let days = era * 146_097 + doe - 719_468;
    let then = days * 86_400 + h * 3600 + mi * 60 + s;
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_secs() as i64;
    u64::try_from(now - then).ok()
}

fn table(items: &[Value]) -> String {
    let rows: Vec<[String; 3]> = items
        .iter()
        .map(|i| {
            [
                i.get("name")
                    .and_then(Value::as_str)
                    .unwrap_or("-")
                    .to_string(),
                ready(i),
                age(i),
            ]
        })
        .collect();
    let w = rows.iter().map(|r| r[0].len()).max().unwrap_or(0).max(4);
    let mut out = format!("{:<w$}  {:<5}  AGE", "NAME", "READY");
    for r in rows {
        out.push_str(&format!("\n{:<w$}  {:<5}  {}", r[0], r[1], r[2]));
    }
    out
}

/// Secret rows (`โ€ฆ/secrets/{KEY}` with a `latest_version`): a list of them
/// shows scope, version and active, so an env-wide row and a service row never
/// look alike (cloud#11153).
fn is_secret_list(items: &[Value]) -> bool {
    !items.is_empty()
        && items.iter().all(|i| {
            i.get("name")
                .and_then(Value::as_str)
                .is_some_and(|n| n.contains("/secrets/") && !n.contains("/secret_versions/"))
                && i.get("status")
                    .is_some_and(|s| s.get("latest_version").is_some())
        })
}

/// `env-wide`, or the service the Secret is scoped to.
fn secret_scope(item: &Value) -> String {
    item.get("spec")
        .and_then(|s| s.get("scope"))
        .and_then(|s| s.get("service"))
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .unwrap_or("env-wide")
        .to_string()
}

fn secrets_table(items: &[Value]) -> String {
    let rows: Vec<[String; 4]> = items
        .iter()
        .map(|i| {
            let name = i.get("name").and_then(Value::as_str).unwrap_or("-");
            let version = i
                .get("status")
                .and_then(|s| s.get("latest_version"))
                .and_then(Value::as_str)
                .and_then(|v| v.rsplit('/').next())
                .filter(|v| !v.is_empty())
                .unwrap_or("-");
            // The Secret list serves active variables only, so an absent flag
            // reads as active; only an explicit `false` reads as inactive.
            let active = i
                .get("status")
                .and_then(|s| s.get("active"))
                .and_then(Value::as_bool)
                .unwrap_or(true);
            [
                name.to_string(),
                secret_scope(i),
                version.to_string(),
                if active { "yes" } else { "no" }.to_string(),
            ]
        })
        .collect();
    let w0 = rows.iter().map(|r| r[0].len()).max().unwrap_or(0).max(4);
    let w1 = rows.iter().map(|r| r[1].len()).max().unwrap_or(0).max(5);
    let mut out = format!(
        "{:<w0$}  {:<w1$}  {:<7}  ACTIVE",
        "NAME", "SCOPE", "VERSION"
    );
    for r in rows {
        out.push_str(&format!(
            "\n{:<w0$}  {:<w1$}  {:<7}  {}",
            r[0], r[1], r[2], r[3]
        ));
    }
    out
}

fn non_empty_str(v: &Value) -> Option<&str> {
    v.as_str().map(str::trim).filter(|s| !s.is_empty())
}

fn matches_name_pattern(item: &Value, expected: &[Option<&str>]) -> bool {
    let Some(name) = item.get("name").and_then(Value::as_str) else {
        return false;
    };
    let mut segs = name.split('/');
    for want in expected {
        let Some(seg) = segs.next() else {
            return false;
        };
        match want {
            Some(lit) if seg != *lit => return false,
            None if seg.is_empty() => return false,
            _ => {}
        }
    }
    segs.next().is_none()
}

fn is_org_list(items: &[Value]) -> bool {
    !items.is_empty()
        && items.iter().all(|i| {
            matches_name_pattern(i, &[Some("orgs"), None])
                && i.get("spec").is_some_and(Value::is_object)
        })
}

fn is_project_list(items: &[Value]) -> bool {
    !items.is_empty()
        && items.iter().all(|i| {
            matches_name_pattern(i, &[Some("orgs"), None, Some("projects"), None])
                && i.get("spec").is_some_and(Value::is_object)
        })
}

fn is_env_list(items: &[Value]) -> bool {
    !items.is_empty()
        && items.iter().all(|i| {
            matches_name_pattern(
                i,
                &[
                    Some("orgs"),
                    None,
                    Some("projects"),
                    None,
                    Some("envs"),
                    None,
                ],
            ) && i.get("spec").is_some_and(Value::is_object)
        })
}

fn display_name(item: &Value) -> &str {
    non_empty_str(&item["meta"]["display_name"])
        .or_else(|| non_empty_str(&item["spec"]["name"]))
        .or_else(|| non_empty_str(&item["spec"]["display_name"]))
        .unwrap_or("-")
}

fn format_columns<const N: usize>(headers: [&str; N], rows: &[[String; N]]) -> String {
    let mut widths = [0usize; N];
    for col in 0..N {
        widths[col] = rows
            .iter()
            .map(|r| r[col].chars().count())
            .max()
            .unwrap_or(0)
            .max(headers[col].chars().count());
    }
    let write_row = |cells: &[&str; N]| -> String {
        let mut line = String::new();
        for (col, cell) in cells.iter().enumerate() {
            if col > 0 {
                line.push_str("  ");
            }
            if col + 1 == N {
                line.push_str(cell);
            } else {
                let w = widths[col];
                line.push_str(&format!("{cell:<w$}"));
            }
        }
        line
    };
    let mut out = write_row(&headers);
    for r in rows {
        out.push('\n');
        let refs = std::array::from_fn(|i| r[i].as_str());
        out.push_str(&write_row(&refs));
    }
    out
}

fn named_resource_table(items: &[Value]) -> String {
    let rows: Vec<[String; 4]> = items
        .iter()
        .map(|i| {
            [
                non_empty_str(&i["spec"]["slug"]).unwrap_or("-").to_string(),
                display_name(i).to_string(),
                i.get("name")
                    .and_then(Value::as_str)
                    .unwrap_or("-")
                    .to_string(),
                age(i),
            ]
        })
        .collect();
    format_columns(["SLUG", "DISPLAY NAME", "NAME", "AGE"], &rows)
}

fn envs_table(items: &[Value]) -> String {
    let rows: Vec<[String; 4]> = items
        .iter()
        .map(|i| {
            [
                non_empty_str(&i["spec"]["slug"]).unwrap_or("-").to_string(),
                non_empty_str(&i["spec"]["mode"]).unwrap_or("-").to_string(),
                i.get("name")
                    .and_then(Value::as_str)
                    .unwrap_or("-")
                    .to_string(),
                age(i),
            ]
        })
        .collect();
    format_columns(["SLUG", "MODE", "NAME", "AGE"], &rows)
}

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

    #[test]
    fn a_list_renders_as_a_table_and_as_names() {
        let v = json!({"databases": [
            {"name": "orgs/o/projects/p/envs/e/databases/main", "status": {"conditions": [{"type": "Ready", "status": "TRUE"}]}},
            {"name": "orgs/o/projects/p/envs/e/databases/logs"}
        ], "next_page_token": ""});
        let t = render(&v, Format::Table);
        assert!(t.starts_with("NAME"));
        assert!(t.contains("databases/main  true"));
        assert_eq!(
            render(&v, Format::Name),
            "orgs/o/projects/p/envs/e/databases/main\norgs/o/projects/p/envs/e/databases/logs"
        );
    }

    #[test]
    fn a_named_resource_with_an_array_prints_its_own_name() {
        let name = "orgs/o/projects/p/envs/e/releases/rel_1";
        let release = json!({"name": name, "services": [{"service_name": "web"}]});
        assert_eq!(render(&release, Format::Name), name);
    }

    #[test]
    fn a_secret_list_shows_scope_version_and_active() {
        let p = "orgs/o/projects/p/envs/e/secrets";
        let v = json!({"secrets": [
            {"name": format!("{p}/API_KEY"),
             "status": {"latest_version": format!("{p}/API_KEY/secret_versions/3"), "active": true}},
            {"name": format!("{p}/CRON_SECRET"),
             "spec": {"scope": {"service": "api"}},
             "status": {"latest_version": format!("{p}/CRON_SECRET/secret_versions/2"), "active": false}}
        ], "next_page_token": ""});
        let t = render(&v, Format::Table);
        let lines: Vec<&str> = t.lines().collect();
        assert!(
            lines[0].contains("SCOPE")
                && lines[0].contains("VERSION")
                && lines[0].contains("ACTIVE"),
            "{t}"
        );
        assert!(
            lines[1].contains("API_KEY")
                && lines[1].contains("env-wide")
                && lines[1].contains(" 3 ")
                && lines[1].ends_with("yes"),
            "{t}"
        );
        assert!(
            lines[2].contains("CRON_SECRET")
                && lines[2].contains(" api ")
                && lines[2].ends_with("no"),
            "{t}"
        );
        // Other collections keep the generic table.
        let other = json!({"databases": [{"name": "orgs/o/projects/p/envs/e/databases/main"}]});
        assert!(render(&other, Format::Table).contains("READY"));
    }

    #[test]
    fn project_list_renders_slug_display_name_name_and_age() {
        let v = json!({"projects": [
            {
                "name": "orgs/org_1/projects/prj_web",
                "meta": {"display_name": "Web Console", "create_time": "2020-01-01T00:00:00Z"},
                "spec": {"slug": "web", "name": "Ignored Spec Name"}
            },
            {
                "name": "orgs/org_1/projects/prj_api",
                "meta": {"display_name": "  "},
                "spec": {"slug": "api", "name": "Billing API"}
            },
            {
                "name": "orgs/org_1/projects/prj_legacy",
                "spec": {"slug": "legacy", "display_name": "Legacy App"}
            },
            {
                "name": "orgs/org_1/projects/prj_bare",
                "spec": {"slug": "bare"}
            }
        ], "next_page_token": ""});
        let t = render(&v, Format::Table);
        let lines: Vec<&str> = t.lines().collect();
        assert_eq!(lines.len(), 5, "{t}");
        assert!(
            lines[0].starts_with("SLUG")
                && lines[0].contains("DISPLAY NAME")
                && lines[0].contains("NAME")
                && lines[0].ends_with("AGE"),
            "{t}"
        );
        assert!(
            lines[1].starts_with("web")
                && lines[1].contains("Web Console")
                && lines[1].contains("orgs/org_1/projects/prj_web")
                && lines[1].ends_with('d'),
            "{t}"
        );
        assert!(
            lines[2].starts_with("api")
                && lines[2].contains("Billing API")
                && lines[2].contains("orgs/org_1/projects/prj_api")
                && lines[2].ends_with('-'),
            "{t}"
        );
        assert!(
            lines[3].starts_with("legacy")
                && lines[3].contains("Legacy App")
                && lines[3].contains("orgs/org_1/projects/prj_legacy"),
            "{t}"
        );
        assert!(
            lines[4].starts_with("bare")
                && lines[4].contains("  - ")
                && lines[4].contains("orgs/org_1/projects/prj_bare"),
            "{t}"
        );
        assert_eq!(
            render(&v, Format::Name),
            "orgs/org_1/projects/prj_web\norgs/org_1/projects/prj_api\norgs/org_1/projects/prj_legacy\norgs/org_1/projects/prj_bare"
        );
        assert!(serde_json::from_str::<Value>(&render(&v, Format::Json)).is_ok());
    }

    #[test]
    fn env_list_renders_slug_mode_name_and_age() {
        let v = json!({"envs": [
            {
                "name": "orgs/org_1/projects/prj_1/envs/env_prod",
                "meta": {"create_time": "2020-01-01T00:00:00Z"},
                "spec": {"slug": "production", "mode": "live"}
            },
            {
                "name": "orgs/org_1/projects/prj_1/envs/env_dev",
                "spec": {"slug": "development", "mode": "test"}
            },
            {
                "name": "orgs/org_1/projects/prj_1/envs/env_blank",
                "spec": {"slug": "sandbox"}
            }
        ], "next_page_token": ""});
        let t = render(&v, Format::Table);
        let lines: Vec<&str> = t.lines().collect();
        assert_eq!(lines.len(), 4, "{t}");
        assert!(
            lines[0].starts_with("SLUG")
                && lines[0].contains("MODE")
                && lines[0].contains("NAME")
                && lines[0].ends_with("AGE"),
            "{t}"
        );
        assert!(
            lines[1].starts_with("production")
                && lines[1].contains("live")
                && lines[1].contains("orgs/org_1/projects/prj_1/envs/env_prod")
                && lines[1].ends_with('d'),
            "{t}"
        );
        assert!(
            lines[2].starts_with("development")
                && lines[2].contains("test")
                && lines[2].contains("orgs/org_1/projects/prj_1/envs/env_dev")
                && lines[2].ends_with('-'),
            "{t}"
        );
        assert!(
            lines[3].starts_with("sandbox")
                && lines[3].contains("  - ")
                && lines[3].contains("orgs/org_1/projects/prj_1/envs/env_blank"),
            "{t}"
        );
        assert_eq!(
            render(&v, Format::Name),
            "orgs/org_1/projects/prj_1/envs/env_prod\norgs/org_1/projects/prj_1/envs/env_dev\norgs/org_1/projects/prj_1/envs/env_blank"
        );
    }

    #[test]
    fn org_list_renders_slug_display_name_name_and_age() {
        let v = json!({"orgs": [
            {
                "name": "orgs/org_acme",
                "meta": {"display_name": "Acme Corp", "create_time": "2020-01-01T00:00:00Z"},
                "spec": {"slug": "acme"}
            },
            {
                "name": "orgs/org_beta",
                "spec": {"slug": "beta"}
            }
        ], "next_page_token": ""});
        let t = render(&v, Format::Table);
        let lines: Vec<&str> = t.lines().collect();
        assert_eq!(lines.len(), 3, "{t}");
        assert!(
            lines[0].starts_with("SLUG")
                && lines[0].contains("DISPLAY NAME")
                && lines[0].contains("NAME")
                && lines[0].ends_with("AGE"),
            "{t}"
        );
        assert!(
            lines[1].starts_with("acme")
                && lines[1].contains("Acme Corp")
                && lines[1].contains("orgs/org_acme")
                && lines[1].ends_with('d'),
            "{t}"
        );
        assert!(
            lines[2].starts_with("beta")
                && lines[2].contains("  - ")
                && lines[2].contains("orgs/org_beta")
                && lines[2].ends_with('-'),
            "{t}"
        );
        assert_eq!(render(&v, Format::Name), "orgs/org_acme\norgs/org_beta");

        // Deeper org-scoped resources keep the generic table.
        let keys = json!({"api_keys": [
            {"name": "orgs/org_acme/api_keys/key_1", "spec": {"label": "ci"}}
        ]});
        assert!(render(&keys, Format::Table).contains("READY"));
    }

    #[test]
    fn age_counts_from_create_time() {
        assert!(seconds_since("2000-01-01T00:00:00Z").unwrap() > 800_000_000);
        assert_eq!(seconds_since("nonsense"), None);
    }
}