shine-cli 2.0.0-rc.1

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
//! Explicit refresh of manifest-owned generated app files.

use anyhow::{Result, bail};
use std::path::Path;

use crate::colors;
use crate::config::Config;
use crate::presentation::TerminalInteraction;
use shine_core::runtime::{
    AppFileAction, AppRefreshPlanRequest, PlanningInputVersions, RuntimeEvent, RuntimeObserver,
};

use super::report::{print_install_error, print_install_success};

pub async fn handle_refresh(
    config: &Config,
    category: &str,
    file_selector: Option<&str>,
    force: bool,
) -> Result<()> {
    handle_refresh_approved(config, category, file_selector, force, true).await
}

pub async fn handle_refresh_approved(
    config: &Config,
    category: &str,
    file_selector: Option<&str>,
    force: bool,
    yes: bool,
) -> Result<()> {
    crate::config::print_presets_note(config);
    let plan_request = AppRefreshPlanRequest {
        category: category.to_string(),
        file: file_selector.map(Path::new).map(Path::to_path_buf),
        force,
        input_versions: PlanningInputVersions::default(),
    };
    let reviewed = crate::lifecycle_plan::review_plans(
        config,
        [crate::lifecycle_plan::LifecyclePlanRequest::app_refresh(
            plan_request.clone(),
            config,
        )],
        yes,
    )
    .await?
    .into_iter()
    .next()
    .expect("one reviewed App refresh Plan");
    let runtime = crate::lifecycle_plan::prepare_runtime(config, &reviewed).await?;

    println!(
        "{}",
        colors::bold(&format!("Refreshing app generators: {category}"))
    );
    let mut observer = RefreshObserver;
    let mut interaction = TerminalInteraction;
    let report = runtime
        .refresh_app_generators_approved(
            plan_request,
            &reviewed.approval,
            &mut observer,
            &mut interaction,
        )
        .await?;
    let mut updated = 0;
    let mut unchanged = 0;
    let mut failed = 0;
    for file in report.files {
        let label = format!("{category}/{}", file.source.display());
        match file.action {
            AppFileAction::Installed | AppFileAction::BackedUp => {
                print_install_success(&label, "", &file.destination, config);
                updated += 1;
            }
            AppFileAction::Unchanged => {
                println!(
                    "  {} {label}  {}",
                    colors::dim("-"),
                    colors::dim("already up to date")
                );
                unchanged += 1;
            }
            AppFileAction::UserModified => {
                eprintln!(
                    "  {} {label}: user-modified, kept (use --force to overwrite)",
                    colors::symbol("!")
                );
                failed += 1;
            }
            AppFileAction::Failed => {
                print_install_error(&label, &anyhow::anyhow!(file.error.unwrap_or_default()));
                failed += 1;
            }
            _ => unchanged += 1,
        }
    }

    println!(
        "{}",
        colors::dim(&format!(
            "Refresh complete: {updated} updated, {unchanged} unchanged, {failed} failed"
        ))
    );
    if failed > 0 {
        bail!("{failed} generated app file(s) failed to refresh");
    }
    Ok(())
}

struct RefreshObserver;

impl RuntimeObserver for RefreshObserver {
    fn emit(&mut self, event: RuntimeEvent) {
        match event {
            RuntimeEvent::Warning { detail, .. } => eprintln!("  {} {detail}", colors::symbol("!")),
            RuntimeEvent::ProcessOutput { text, .. } => {
                for line in text.lines() {
                    println!("     {}", colors::dim(line));
                }
            }
            RuntimeEvent::Progress {
                code: "app_hook_completed",
                target,
            } => {
                println!(
                    "  {} {}: post-upgrade hook completed",
                    colors::symbol("✓"),
                    target.trim_start_matches("app/")
                );
            }
            _ => {}
        }
    }
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use crate::apps::metadata;
    use crate::apps::{handle_install, handle_upgrade_installed};
    use crate::install_core::manifest::AppManifest;
    use crate::status::{FileStatus, app_entry_status};
    use std::os::unix::fs::PermissionsExt;
    use tokio::fs;

    async fn write_fixture(root: &Path, two_files: bool) -> Config {
        let mut config = Config::new_for_test(root);
        config.is_external_presets = true;
        config
            .env
            .insert("SOURCE_URL".to_string(), "https://example.test".to_string());
        let app_dir = config.presets_dir().join("app/sample");
        fs::create_dir_all(&app_dir).await.unwrap();
        let second = if two_files {
            r#"

[[files]]
source = "second.txt"
generator = { script = "second.sh", env = ["SOURCE_URL"], when_env = "SOURCE_URL", auto = false }
"#
        } else {
            ""
        };
        fs::write(
            app_dir.join("shine.toml"),
            format!(
                r#"description = "sample"
dest = "{}"

[permissions]
schema_version = 1
filesystem = [
  {{ access = ["execute"], base = "preset", path = "first.sh" }},
  {{ access = ["execute"], base = "preset", path = "second.sh" }},
]
environment = [{{ name = "SOURCE_URL", sensitivity = "plain" }}]

[[files]]
source = "first.txt"
generator = {{ script = "first.sh", env = ["SOURCE_URL"], when_env = "SOURCE_URL", auto = false }}
{second}"#,
                root.join("dest").display()
            ),
        )
        .await
        .unwrap();
        fs::write(app_dir.join("first.txt"), b"fallback-first\n")
            .await
            .unwrap();
        fs::write(app_dir.join("first.payload"), b"first-v1\n")
            .await
            .unwrap();
        write_generator(&app_dir.join("first.sh"), "first").await;
        if two_files {
            fs::write(app_dir.join("second.txt"), b"fallback-second\n")
                .await
                .unwrap();
            fs::write(app_dir.join("second.payload"), b"second-v1\n")
                .await
                .unwrap();
            write_generator(&app_dir.join("second.sh"), "second").await;
        }
        crate::trust::grant_current_for_test(&config, "app/sample").await;
        config
    }

    async fn write_generator(path: &Path, stem: &str) {
        fs::write(
            path,
            format!(
                "#!/bin/sh\nprintf x >> '{counter}'\ncat '{payload}'\n",
                counter = path
                    .parent()
                    .unwrap()
                    .join(format!("{stem}.runs"))
                    .display(),
                payload = path
                    .parent()
                    .unwrap()
                    .join(format!("{stem}.payload"))
                    .display()
            ),
        )
        .await
        .unwrap();
        fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn manual_generator_skips_status_and_upgrade_but_refreshes_explicitly() {
        let root = crate::test_support::make_temp_dir("shine-refresh").await;
        let config = write_fixture(&root, false).await;
        handle_install(&config, Some("sample"), false, false)
            .await
            .unwrap();

        let app_dir = config.presets_dir().join("app/sample");
        let dest = root.join("dest/first.txt");
        assert_eq!(
            fs::read_to_string(app_dir.join("first.runs"))
                .await
                .unwrap(),
            "x"
        );
        fs::write(app_dir.join("first.payload"), b"first-v2\n")
            .await
            .unwrap();

        let categories = metadata::load_active_categories(&config, Some("sample"))
            .await
            .unwrap();
        let cat = &categories[0];
        let file = &cat.files[0];
        let manifest = AppManifest::load(&shine_core::runtime::RealHost, config.shine_dir())
            .await
            .unwrap();
        let entry = manifest.find_by_dest(&dest).unwrap();
        assert_eq!(
            app_entry_status(&config, cat, file, entry, &config.env).await,
            FileStatus::UpToDate
        );
        let mut separator = crate::output::SectionSeparator::new();
        let report = handle_upgrade_installed(&config, false, &mut separator)
            .await
            .unwrap();
        assert_eq!(report.updated, 0);
        assert_eq!(
            fs::read_to_string(app_dir.join("first.runs"))
                .await
                .unwrap(),
            "x"
        );
        assert_eq!(fs::read(&dest).await.unwrap(), b"first-v1\n");

        crate::trust::grant_current_for_test(&config, "app/sample").await;
        handle_refresh(&config, "sample", Some("first.txt"), false)
            .await
            .unwrap();
        assert_eq!(fs::read(&dest).await.unwrap(), b"first-v2\n");
        assert_eq!(
            fs::read_to_string(app_dir.join("first.runs"))
                .await
                .unwrap(),
            "xx"
        );
        fs::remove_dir_all(root).await.unwrap();
    }

    #[tokio::test]
    async fn automatic_generator_status_reports_refresh_without_execution() {
        let root = crate::test_support::make_temp_dir("shine-refresh-status").await;
        let config = write_fixture(&root, false).await;
        let metadata_path = config.presets_dir().join("app/sample/shine.toml");
        let metadata = fs::read_to_string(&metadata_path)
            .await
            .unwrap()
            .replace("auto = false", "auto = true");
        fs::write(&metadata_path, metadata).await.unwrap();
        crate::trust::grant_current_for_test(&config, "app/sample").await;
        handle_install(&config, Some("sample"), false, false)
            .await
            .unwrap();

        let categories = metadata::load_active_categories(&config, Some("sample"))
            .await
            .unwrap();
        let rows = crate::status::build_app_rows(&config, &categories)
            .await
            .unwrap();
        assert_eq!(rows[0].file_status, FileStatus::GeneratorNotEvaluated);
        assert_eq!(
            fs::read_to_string(config.presets_dir().join("app/sample/first.runs"))
                .await
                .unwrap(),
            "x",
            "read-only status must not execute an automatic generator"
        );
        fs::remove_dir_all(root).await.unwrap();
    }

    #[tokio::test]
    async fn explicit_generator_evaluation_materializes_desired_content_before_install() {
        let root = crate::test_support::make_temp_dir("shine-generator-preview").await;
        let config = write_fixture(&root, false).await;
        let mut runtime = crate::core_runtime::from_config(&config).await.unwrap();
        runtime.context_mut_for_cli().env = config.env.clone();
        let inspections = runtime
            .inspect_apps_with_options(
                shine_core::runtime::AppInspectionOptions {
                    run_generators: true,
                    categories: vec!["sample".to_string()],
                },
                &mut shine_core::runtime::NullObserver,
            )
            .await
            .unwrap();
        assert_eq!(
            inspections[0].desired_content.as_deref(),
            Some(b"first-v1\n".as_slice())
        );
        assert!(!root.join("dest/first.txt").exists());
        assert_eq!(
            fs::read_to_string(config.presets_dir().join("app/sample/first.runs"))
                .await
                .unwrap(),
            "x"
        );
        fs::remove_dir_all(root).await.unwrap();
    }

    #[tokio::test]
    async fn explicit_generator_evaluation_updates_status_without_writing_destination() {
        let root = crate::test_support::make_temp_dir("shine-generator-evaluation").await;
        let config = write_fixture(&root, false).await;
        crate::trust::grant_current_for_test(&config, "app/sample").await;
        handle_install(&config, Some("sample"), false, false)
            .await
            .unwrap();
        let app_dir = config.presets_dir().join("app/sample");
        let destination = root.join("dest/first.txt");
        fs::write(app_dir.join("first.payload"), b"first-v2\n")
            .await
            .unwrap();
        crate::trust::grant_current_for_test(&config, "app/sample").await;

        let categories = metadata::load_active_categories(&config, Some("sample"))
            .await
            .unwrap();
        let (rows, _, _) =
            crate::status::build_app_rows_with_lifecycle_options(&config, &categories, true)
                .await
                .unwrap();
        assert_eq!(rows[0].file_status, FileStatus::UpdateAvail);
        assert_eq!(fs::read(&destination).await.unwrap(), b"first-v1\n");
        assert_eq!(
            fs::read_to_string(app_dir.join("first.runs"))
                .await
                .unwrap(),
            "xx",
            "explicit evaluation must execute the selected generator exactly once"
        );
        fs::remove_dir_all(root).await.unwrap();
    }

    #[tokio::test]
    async fn refresh_selector_and_force_preserve_other_generated_files() {
        let root = crate::test_support::make_temp_dir("shine-refresh").await;
        let config = write_fixture(&root, true).await;
        handle_install(&config, Some("sample"), false, false)
            .await
            .unwrap();
        let app_dir = config.presets_dir().join("app/sample");
        let first_dest = root.join("dest/first.txt");
        let second_dest = root.join("dest/second.txt");
        fs::write(app_dir.join("first.payload"), b"first-v2\n")
            .await
            .unwrap();
        fs::write(app_dir.join("second.payload"), b"second-v2\n")
            .await
            .unwrap();
        fs::write(&first_dest, b"user edit\n").await.unwrap();
        crate::trust::grant_current_for_test(&config, "app/sample").await;

        assert!(
            handle_refresh(&config, "sample", Some("first.txt"), false)
                .await
                .is_err()
        );
        assert_eq!(fs::read(&first_dest).await.unwrap(), b"user edit\n");
        handle_refresh(&config, "sample", Some("first.txt"), true)
            .await
            .unwrap();
        assert_eq!(fs::read(&first_dest).await.unwrap(), b"first-v2\n");
        assert_eq!(fs::read(&second_dest).await.unwrap(), b"second-v1\n");
        assert_eq!(
            fs::read_to_string(app_dir.join("second.runs"))
                .await
                .unwrap(),
            "x",
            "single-file refresh must not run other generators"
        );
        fs::remove_dir_all(root).await.unwrap();
    }

    #[tokio::test]
    async fn refresh_keeps_last_good_file_and_continues_after_generator_failure() {
        let root = crate::test_support::make_temp_dir("shine-refresh").await;
        let config = write_fixture(&root, true).await;
        handle_install(&config, Some("sample"), false, false)
            .await
            .unwrap();
        let app_dir = config.presets_dir().join("app/sample");
        let first_dest = root.join("dest/first.txt");
        let second_dest = root.join("dest/second.txt");
        fs::write(app_dir.join("first.sh"), b"#!/bin/sh\nexit 1\n")
            .await
            .unwrap();
        fs::write(app_dir.join("second.payload"), b"second-v2\n")
            .await
            .unwrap();
        crate::trust::grant_current_for_test(&config, "app/sample").await;

        assert!(
            handle_refresh(&config, "sample", None, false)
                .await
                .is_err()
        );
        assert_eq!(
            fs::read(&first_dest).await.unwrap(),
            b"first-v1\n",
            "failed generator must retain the last-known-good file"
        );
        assert_eq!(
            fs::read(&second_dest).await.unwrap(),
            b"second-v2\n",
            "a failed generator must not prevent later selected files refreshing"
        );
        fs::remove_dir_all(root).await.unwrap();
    }

    #[tokio::test]
    async fn refresh_requires_the_generator_condition_env() {
        let root = crate::test_support::make_temp_dir("shine-refresh").await;
        let mut config = write_fixture(&root, false).await;
        handle_install(&config, Some("sample"), false, false)
            .await
            .unwrap();
        config.env.remove("SOURCE_URL");
        let dest = root.join("dest/first.txt");

        assert!(
            handle_refresh(&config, "sample", Some("first.txt"), false)
                .await
                .is_err()
        );
        assert_eq!(fs::read(&dest).await.unwrap(), b"first-v1\n");
        fs::remove_dir_all(root).await.unwrap();
    }
}