shine-cli 1.8.0

Give personal automation a reviewable lifecycle
Documentation
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use anyhow::{Context, Result, bail};
use std::collections::BTreeSet;
use std::path::Path;

use crate::config::Config;
use crate::preset_validation::PresetValidationFailure;

use super::{
    LoadedSysPreset, SysDetection, SysDetectionProbe, SysDriverKind, SysInstall, SysItem,
    SysItemMode, SysItemStatus, SysManifest,
};

pub(super) async fn load_sys_preset(config: &Config, os_id: &str) -> Result<LoadedSysPreset> {
    if os_id.contains('/') || os_id.contains('\\') || os_id.contains("..") {
        bail!("invalid os id: {os_id:?}");
    }
    let prefix = format!("sys/{os_id}");
    if !config.is_external_presets {
        crate::presets::extract_prefix(&prefix, config.presets_dir(), true).await?;
    }

    let root = Path::new("sys").join(os_id);
    let preset_root = config.preset_path(&root);
    let manifest_path = preset_root.join("shine.toml");
    let content = tokio::fs::read_to_string(&manifest_path)
        .await
        .with_context(|| format!("reading {}", manifest_path.display()))?;
    let manifest = parse_and_validate_manifest(&content)
        .with_context(|| format!("parsing {}", manifest_path.display()))?;
    Ok(LoadedSysPreset {
        manifest,
        root: std::fs::canonicalize(&preset_root)
            .with_context(|| format!("resolving sys preset root {}", preset_root.display()))?,
    })
}

pub(super) fn parse_and_validate_manifest(content: &str) -> Result<SysManifest> {
    let manifest: SysManifest = toml::from_str(content)?;
    validate_manifest(&manifest)?;
    Ok(manifest)
}

/// Parse and validate a sys v2 category plus every preset-owned file it
/// references. This is static and intentionally does not construct `Config`.
pub(super) fn validate_preset_category(
    name: &str,
    root: &Path,
) -> std::result::Result<(), PresetValidationFailure> {
    let manifest_path = root.join("shine.toml");
    let content = std::fs::read_to_string(&manifest_path).map_err(|error| {
        PresetValidationFailure::at(
            "missing_metadata",
            format!("sys/{name} requires a readable shine.toml: {error}"),
            &manifest_path,
        )
    })?;
    let manifest = parse_and_validate_manifest(&content).map_err(|error| {
        PresetValidationFailure::at(
            "invalid_metadata",
            format!("failed to validate sys/{name}/shine.toml: {error:#}"),
            &manifest_path,
        )
    })?;

    for item in &manifest.items {
        if let Some(SysInstall::Script { path, .. }) = &item.install {
            validate_reference(root, path, "install script")?;
        }
        for integration in &item.shell {
            if let Some(fragment) = &integration.fragment {
                let path = validate_reference(root, fragment, "profile fragment")?;
                std::fs::read_to_string(&path).map_err(|error| {
                    PresetValidationFailure::at(
                        "invalid_reference",
                        format!("profile fragment must be valid UTF-8: {error}"),
                        path,
                    )
                })?;
            }
        }
        if item.driver == SysDriverKind::ManagedFile {
            let source = item
                .config
                .get("source")
                .and_then(toml::Value::as_str)
                .expect("managed-file source is guaranteed by validate_manifest");
            validate_reference(root, source, "managed-file source")?;
            if let Some(transforms) = item
                .config
                .get("transforms")
                .and_then(toml::Value::as_array)
            {
                let specs = transforms
                    .iter()
                    .map(|value| value.as_str().unwrap_or_default().to_string())
                    .collect::<Vec<_>>();
                crate::install_core::transforms::validate(&specs).map_err(|error| {
                    PresetValidationFailure::at(
                        "invalid_metadata",
                        format!(
                            "sys item `{}` has invalid managed-file transforms: {error}",
                            item.id
                        ),
                        &manifest_path,
                    )
                })?;
            }
            let target = item
                .config
                .get("target")
                .and_then(toml::Value::as_str)
                .expect("managed-file target is guaranteed by validate_manifest");
            let expanded = crate::config::full_expand(target).map_err(|error| {
                PresetValidationFailure::at(
                    "invalid_metadata",
                    format!(
                        "sys item `{}` has invalid managed-file target: {error}",
                        item.id
                    ),
                    &manifest_path,
                )
            })?;
            if !Path::new(&expanded).is_absolute() {
                return Err(PresetValidationFailure::at(
                    "invalid_metadata",
                    format!(
                        "sys item `{}` managed-file target must resolve to an absolute path",
                        item.id
                    ),
                    &manifest_path,
                ));
            }
        }
    }
    Ok(())
}

fn validate_reference(
    root: &Path,
    relative: &str,
    label: &str,
) -> std::result::Result<std::path::PathBuf, PresetValidationFailure> {
    let path = root.join(relative);
    let canonical = std::fs::canonicalize(&path).map_err(|error| {
        PresetValidationFailure::at(
            "missing_reference",
            format!("{label} is missing or unreadable: {error}"),
            &path,
        )
    })?;
    if !canonical.starts_with(root) || !canonical.is_file() {
        return Err(PresetValidationFailure::at(
            "invalid_reference",
            format!("{label} must be a file inside the preset category"),
            path,
        ));
    }
    Ok(canonical)
}

fn validate_manifest(manifest: &SysManifest) -> Result<()> {
    match manifest.version {
        Some(2) => {}
        None | Some(1) => bail!(
            "sys preset v1 is unsupported; migrate it to version = 2 by removing the monolithic dispatcher, adding detect/install to every init item, and moving software-specific profile code to item integrations. See docs/manual/guides/sys-preset-v2-migration.md"
        ),
        Some(version) => {
            bail!("sys preset version {version} is not supported by this Shine release")
        }
    }
    let mut ids = BTreeSet::new();
    for item in &manifest.items {
        validate_item_id(&item.id)?;
        if item.label.trim().is_empty() {
            bail!("sys bootstrap item `{}` must have a label", item.id);
        }
        if !ids.insert(item.id.clone()) {
            bail!("duplicate sys bootstrap item id `{}`", item.id);
        }
        let mut env_keys = BTreeSet::new();
        for key in &item.required_env {
            let mut chars = key.chars();
            let valid = chars
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
                && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
            if !valid {
                bail!(
                    "sys item `{}` has invalid required_env key `{key}`",
                    item.id
                );
            }
            if !env_keys.insert(key) {
                bail!("sys item `{}` repeats required_env key `{key}`", item.id);
            }
        }
        validate_driver_config(item)?;
        validate_bootstrap_config(item)?;
        validate_shell_integrations(item)?;
    }

    if let Some(default_profile) = &manifest.default_profile
        && !manifest.profiles.contains_key(default_profile)
    {
        bail!("default profile `{default_profile}` is not defined");
    }

    for (profile_name, profile) in &manifest.profiles {
        for item_id in &profile.items {
            if !ids.contains(item_id) {
                bail!("profile `{profile_name}` references unknown item `{item_id}`");
            }
            if manifest
                .items
                .iter()
                .find(|item| item.id == *item_id)
                .is_some_and(|item| item.mode == SysItemMode::Managed)
            {
                bail!(
                    "profile `{profile_name}` references managed item `{item_id}`; enable it with `shine sys apply {item_id}`"
                );
            }
        }
    }

    Ok(())
}

fn validate_bootstrap_config(item: &SysItem) -> Result<()> {
    if item.mode == SysItemMode::Managed {
        if item.detect.is_some() || item.install.is_some() || !item.shell.is_empty() {
            bail!(
                "managed sys item `{}` cannot declare bootstrap detect/install/shell fields",
                item.id
            );
        }
        return Ok(());
    }

    let detect = item
        .detect
        .as_ref()
        .with_context(|| format!("sys bootstrap item `{}` must declare `detect`", item.id))?;
    let install = item
        .install
        .as_ref()
        .with_context(|| format!("sys bootstrap item `{}` must declare `install`", item.id))?;
    validate_detection(&item.id, detect)?;
    {
        match install {
            SysInstall::Package {
                package,
                success_status,
                success_hint,
                ..
            } => {
                validate_plain_value(&item.id, "package", package)?;
                if package.starts_with('-')
                    || !package
                        .chars()
                        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-'))
                {
                    bail!(
                        "sys item `{}` has invalid package identifier `{package}`",
                        item.id
                    );
                }
                validate_success_status(&item.id, *success_status)?;
                if !success_hint.is_empty() {
                    validate_plain_value(&item.id, "success hint", success_hint)?;
                }
            }
            SysInstall::Script {
                path,
                success_status,
                success_hint,
            } => {
                validate_relative_preset_path(&item.id, "install script", path)?;
                validate_success_status(&item.id, *success_status)?;
                if !success_hint.is_empty() {
                    validate_plain_value(&item.id, "success hint", success_hint)?;
                }
            }
        }
    }
    Ok(())
}

fn validate_detection(item_id: &str, detect: &SysDetection) -> Result<()> {
    match detect {
        SysDetection::Command {
            command,
            version_args,
        } => {
            validate_command_name(item_id, command)?;
            for arg in version_args {
                validate_plain_value(item_id, "version argument", arg)?;
            }
        }
        SysDetection::Path { path } => validate_plain_value(item_id, "detection path", path)?,
        SysDetection::Any { probes } => {
            if probes.is_empty() {
                bail!("sys item `{item_id}` detection `any` requires at least one probe");
            }
            for probe in probes {
                match probe {
                    SysDetectionProbe::Command { command } => {
                        validate_command_name(item_id, command)?
                    }
                    SysDetectionProbe::Path { path } => {
                        validate_plain_value(item_id, "detection path", path)?
                    }
                }
            }
        }
    }
    Ok(())
}

fn validate_success_status(item_id: &str, status: Option<SysItemStatus>) -> Result<()> {
    if status.is_some_and(|status| {
        !matches!(
            status,
            SysItemStatus::Installed | SysItemStatus::NeedsAction
        )
    }) {
        bail!("sys item `{item_id}` install success_status must be installed or needs-action");
    }
    Ok(())
}

fn validate_shell_integrations(item: &SysItem) -> Result<()> {
    for (index, integration) in item.shell.iter().enumerate() {
        if integration.shells.is_empty() {
            bail!(
                "sys item `{}` shell integration {} requires at least one shell",
                item.id,
                index + 1
            );
        }
        if let Some(command) = &integration.when_command {
            validate_command_name(&item.id, command)?;
        }
        let action_count = usize::from(integration.path.is_some())
            + usize::from(!integration.env.is_empty())
            + usize::from(!integration.eval_argv.is_empty())
            + usize::from(integration.source.is_some())
            + usize::from(!integration.aliases.is_empty())
            + usize::from(integration.fragment.is_some());
        if action_count != 1 {
            bail!(
                "sys item `{}` shell integration {} must declare exactly one of path, env, eval, source, aliases, or fragment",
                item.id,
                index + 1
            );
        }
        if let Some(path) = &integration.path {
            validate_plain_value(&item.id, "profile path", path)?;
        }
        for (key, value) in &integration.env {
            validate_env_key(&item.id, key)?;
            validate_plain_value(&item.id, "profile env value", value)?;
        }
        for arg in &integration.eval_argv {
            validate_plain_value(&item.id, "profile eval argument", arg)?;
        }
        if let Some(source) = &integration.source {
            validate_plain_value(&item.id, "profile source", source)?;
        }
        for (name, value) in &integration.aliases {
            if name.is_empty()
                || !name
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
            {
                bail!("sys item `{}` has invalid alias name `{name}`", item.id);
            }
            validate_plain_value(&item.id, "profile alias", value)?;
        }
        if let Some(fragment) = &integration.fragment {
            validate_relative_preset_path(&item.id, "profile fragment", fragment)?;
        }
    }
    Ok(())
}

fn validate_command_name(item_id: &str, command: &str) -> Result<()> {
    if command.is_empty()
        || !command
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+'))
    {
        bail!("sys item `{item_id}` has invalid command name `{command}`");
    }
    Ok(())
}

fn validate_env_key(item_id: &str, key: &str) -> Result<()> {
    let mut chars = key.chars();
    let valid = chars
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
    if !valid {
        bail!("sys item `{item_id}` has invalid profile env key `{key}`");
    }
    Ok(())
}

fn validate_plain_value(item_id: &str, label: &str, value: &str) -> Result<()> {
    if value.trim().is_empty() || value.chars().any(char::is_control) {
        bail!("sys item `{item_id}` has invalid {label}");
    }
    Ok(())
}

fn validate_relative_preset_path(item_id: &str, label: &str, value: &str) -> Result<()> {
    validate_plain_value(item_id, label, value)?;
    let path = Path::new(value);
    if path.is_absolute()
        || path.components().any(|component| {
            matches!(
                component,
                std::path::Component::ParentDir
                    | std::path::Component::RootDir
                    | std::path::Component::Prefix(_)
            )
        })
    {
        bail!("sys item `{item_id}` {label} must stay inside the preset: `{value}`");
    }
    Ok(())
}

fn validate_driver_config(item: &SysItem) -> Result<()> {
    if item.mode == SysItemMode::Init && item.driver != SysDriverKind::Script {
        bail!(
            "sys bootstrap item `{}` cannot use managed driver `{:?}`",
            item.id,
            item.driver
        );
    }
    let allowed: &[&str] = match item.driver {
        SysDriverKind::Script => &[],
        SysDriverKind::SplitDns => &["domain_env", "servers_env"],
        SysDriverKind::ManagedFile => &["source", "target", "transforms", "restart_hint"],
    };
    for key in item.config.keys() {
        if !allowed.contains(&key.as_str()) {
            bail!(
                "sys item `{}` has unknown {:?} driver config key `{key}`",
                item.id,
                item.driver
            );
        }
    }
    let require_string = |key: &str| -> Result<&str> {
        item.config
            .get(key)
            .and_then(toml::Value::as_str)
            .filter(|value| !value.trim().is_empty())
            .with_context(|| format!("sys item `{}` requires config `{key}`", item.id))
    };
    match item.driver {
        SysDriverKind::Script => {
            if !item.config.is_empty() {
                bail!(
                    "script sys item `{}` does not accept driver config",
                    item.id
                );
            }
        }
        SysDriverKind::SplitDns => {
            for key in ["domain_env", "servers_env"] {
                let env_key = require_string(key)?;
                if !item.required_env.iter().any(|required| required == env_key) {
                    bail!(
                        "sys item `{}` config `{key}` references `{env_key}` but required_env does not include it",
                        item.id
                    );
                }
            }
        }
        SysDriverKind::ManagedFile => {
            require_string("source")?;
            require_string("target")?;
            if let Some(transforms) = item.config.get("transforms") {
                let transforms = transforms.as_array().with_context(|| {
                    format!(
                        "sys item `{}` config `transforms` must be an array",
                        item.id
                    )
                })?;
                if transforms.iter().any(|value| value.as_str().is_none()) {
                    bail!(
                        "sys item `{}` config `transforms` must contain strings",
                        item.id
                    );
                }
            }
        }
    }
    Ok(())
}

fn validate_item_id(item_id: &str) -> Result<()> {
    if item_id.trim().is_empty() {
        bail!("sys bootstrap item ids must not be empty");
    }
    if !item_id
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        bail!(
            "sys bootstrap item id `{item_id}` contains invalid characters (allowed: a-z A-Z 0-9 - _)"
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{SysInstall, parse_and_validate_manifest};
    use crate::sys::SysPackageProvider;

    const ITEM: &str = r#"
[[items]]
id = "tool"
label = "Tool"
detect = { kind = "command", command = "tool" }
install = { kind = "package", provider = "apt", package = "tool" }
"#;

    #[test]
    fn rejects_missing_or_unknown_sys_preset_versions() {
        let missing = parse_and_validate_manifest(ITEM).unwrap_err();
        assert!(missing.to_string().contains("v1 is unsupported"));
        let unknown = parse_and_validate_manifest(&format!("version = 3\n{ITEM}")).unwrap_err();
        assert!(unknown.to_string().contains("version 3 is not supported"));
    }

    #[test]
    fn v2_requires_detection_and_installer_for_init_items() {
        let missing_detect = parse_and_validate_manifest(
            "version = 2\n[[items]]\nid = 'tool'\nlabel = 'Tool'\ninstall = { kind = 'package', provider = 'apt', package = 'tool' }",
        )
        .unwrap_err();
        assert!(missing_detect.to_string().contains("must declare `detect`"));
        let missing_install = parse_and_validate_manifest(
            "version = 2\n[[items]]\nid = 'tool'\nlabel = 'Tool'\ndetect = { kind = 'command', command = 'tool' }",
        )
        .unwrap_err();
        assert!(
            missing_install
                .to_string()
                .contains("must declare `install`")
        );
    }

    #[test]
    fn built_in_sys_presets_are_all_executable_v2_manifests() {
        for manifest in [
            include_str!("../../../presets/sys/macos/shine.toml"),
            include_str!("../../../presets/sys/ubuntu/shine.toml"),
            include_str!("../../../presets/sys/windows/shine.toml"),
        ] {
            parse_and_validate_manifest(manifest).unwrap();
        }
    }

    #[test]
    fn built_in_ubuntu_all_profile_includes_bun() {
        let manifest =
            parse_and_validate_manifest(include_str!("../../../presets/sys/ubuntu/shine.toml"))
                .unwrap();

        assert!(manifest.items.iter().any(|item| item.id == "bun"));
        assert!(
            manifest.profiles["all"]
                .items
                .iter()
                .any(|item| item == "bun")
        );
        assert!(
            !manifest.profiles["recommended"]
                .items
                .iter()
                .any(|item| item == "bun")
        );
        assert!(!include_str!("../../../presets/sys/ubuntu/install/bun.sh").is_empty());
        assert!(!include_str!("../../../presets/sys/ubuntu/profile/bun.sh").is_empty());
    }

    #[test]
    fn built_in_ubuntu_profiles_include_rust_except_minimal() {
        let manifest =
            parse_and_validate_manifest(include_str!("../../../presets/sys/ubuntu/shine.toml"))
                .unwrap();

        assert!(manifest.items.iter().any(|item| item.id == "rust"));
        for profile in ["recommended", "all"] {
            assert!(
                manifest.profiles[profile]
                    .items
                    .iter()
                    .any(|item| item == "rust")
            );
        }
        assert!(
            !manifest.profiles["minimal"]
                .items
                .iter()
                .any(|item| item == "rust")
        );
        assert!(!include_str!("../../../presets/sys/ubuntu/install/rust.sh").is_empty());
    }

    #[test]
    fn built_in_windows_profiles_include_neovim_except_required() {
        let manifest =
            parse_and_validate_manifest(include_str!("../../../presets/sys/windows/shine.toml"))
                .unwrap();
        let neovim = manifest
            .items
            .iter()
            .find(|item| item.id == "neovim")
            .unwrap();

        assert!(matches!(
            neovim.install.as_ref(),
            Some(SysInstall::Package {
                provider: SysPackageProvider::Winget,
                package,
                ..
            }) if package == "Neovim.Neovim"
        ));
        for profile in ["recommended", "all"] {
            assert!(
                manifest.profiles[profile]
                    .items
                    .iter()
                    .any(|item| item == "neovim")
            );
        }
        assert!(
            !manifest.profiles["required"]
                .items
                .iter()
                .any(|item| item == "neovim")
        );
    }
}