shine-cli 1.5.0

Keep development environments portable across machines and remote sessions
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
use super::manifest::{AppEntry, hash_content};
use anyhow::{Context, Result};
use std::io::IsTerminal;
#[cfg(unix)]
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use tokio::fs;

/// Cross-process advisory lock serialising privileged (sudo) filesystem
/// mutations. `nextest` runs each test in its own OS process, so an
/// in-process `Mutex` cannot prevent concurrent test processes from racing
/// on a real, shared system path (e.g. `/etc/docker/daemon.json`); this
/// lock closes that window for both tests and real concurrent invocations.
pub struct AdminLockGuard {
    path: PathBuf,
}

impl Drop for AdminLockGuard {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir(&self.path);
    }
}

/// Acquires the cross-process advisory lock serializing privileged (sudo)
/// filesystem mutations. Shared beyond this module by other privileged
/// writes (e.g. the self-install binary copy in `self_install.rs`) that
/// need to serialize against concurrent `sudo`-driven writes.
pub async fn admin_lock() -> Result<AdminLockGuard> {
    let path = std::env::temp_dir().join("shine-admin.lock");
    let deadline = Instant::now() + Duration::from_secs(30);
    loop {
        match fs::create_dir(&path).await {
            Ok(()) => return Ok(AdminLockGuard { path }),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                if Instant::now() >= deadline {
                    // Stale lock from a crashed process: reclaim it.
                    let _ = fs::remove_dir(&path).await;
                    continue;
                }
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
            Err(e) => return Err(e).context("failed to acquire admin operation lock"),
        }
    }
}

#[derive(Debug)]
pub enum InstallOutcome {
    Installed { hash: u64 },
    AlreadyManaged,
    BackedUpAndInstalled { backup: PathBuf, hash: u64 },
    DryRun,
}

#[derive(Debug)]
pub enum UninstallOutcome {
    Removed,
    RestoredBackup { backup: PathBuf },
    ForceRemoved,
    ForceRestoredBackup { backup: PathBuf },
    NotFound,
    UserModified,
    DryRun,
}

pub async fn install_bytes(
    content: &[u8],
    destination: &Path,
    is_managed: bool,
    dry_run: bool,
    force: bool,
) -> Result<InstallOutcome> {
    if dry_run {
        return Ok(InstallOutcome::DryRun);
    }
    install_bytes_impl(content, destination, is_managed, force).await
}

pub async fn install_bytes_admin(
    content: &[u8],
    destination: &Path,
    is_managed: bool,
    dry_run: bool,
    force: bool,
) -> Result<InstallOutcome> {
    if dry_run {
        return Ok(InstallOutcome::DryRun);
    }
    if !cfg!(unix) || std::env::var("USER").is_ok_and(|user| user == "root") {
        return install_bytes_impl(content, destination, is_managed, force).await;
    }
    let _lock = admin_lock().await?;
    if !crate::privilege::ensure_admin(1).await? {
        anyhow::bail!("administrator permission was not granted");
    }

    let hash = hash_content(content);
    if destination.exists() && is_managed && !force {
        let existing = fs::read(destination).await.unwrap_or_default();
        if hash_content(&existing) == hash {
            return Ok(InstallOutcome::AlreadyManaged);
        }
    }

    let temp = std::env::temp_dir().join(format!("shine-admin-{}", uuid::Uuid::new_v4()));
    #[cfg(unix)]
    {
        let mut file = std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .mode(0o600)
            .open(&temp)
            .with_context(|| format!("creating temporary file: {}", temp.display()))?;
        file.write_all(content)
            .with_context(|| format!("writing temporary file: {}", temp.display()))?;
    }
    let parent = destination
        .parent()
        .ok_or_else(|| anyhow::anyhow!("destination has no parent: {}", destination.display()))?;

    let mut backup = None;
    if destination.exists() && !is_managed {
        let path = backup_path(destination);
        let status = sudo_command()
            .args(["mv", "--"])
            .arg(destination)
            .arg(&path)
            .status()
            .await
            .context("failed to run sudo for app backup")?;
        if !status.success() {
            let _ = fs::remove_file(&temp).await;
            anyhow::bail!("administrator permission was not granted");
        }
        backup = Some(path);
    }

    let status = sudo_command()
        .arg("mkdir")
        .arg("-p")
        .arg(parent)
        .status()
        .await
        .context("failed to create privileged destination directory")?;
    if !status.success() {
        let _ = fs::remove_file(&temp).await;
        if let Some(backup) = &backup {
            let _ = sudo_command()
                .args(["mv", "--"])
                .arg(backup)
                .arg(destination)
                .status()
                .await;
        }
        anyhow::bail!("administrator permission was not granted");
    }
    let status = sudo_command()
        .args(["install", "-m", "0644", "--"])
        .arg(&temp)
        .arg(destination)
        .status()
        .await
        .context("failed to install privileged app configuration")?;
    let _ = fs::remove_file(&temp).await;
    if !status.success() {
        if let Some(backup) = &backup {
            let _ = sudo_command()
                .args(["mv", "--"])
                .arg(backup)
                .arg(destination)
                .status()
                .await;
        }
        anyhow::bail!("failed to install privileged app configuration");
    }

    Ok(match backup {
        Some(backup) => InstallOutcome::BackedUpAndInstalled { backup, hash },
        None => InstallOutcome::Installed { hash },
    })
}

/// Builds a `sudo` command, passing `-n` (non-interactive) when stdin isn't
/// a TTY so a scripted invocation fails fast instead of hanging on a prompt.
pub fn sudo_command() -> tokio::process::Command {
    let mut command = tokio::process::Command::new("sudo");
    if !std::io::stdin().is_terminal() {
        command.arg("-n");
    }
    command
}

async fn install_bytes_impl(
    content: &[u8],
    destination: &Path,
    is_managed: bool,
    force: bool,
) -> Result<InstallOutcome> {
    if let Some(parent) = destination.parent() {
        fs::create_dir_all(parent)
            .await
            .with_context(|| format!("failed to create directory: {}", parent.display()))?;
    }

    let hash = hash_content(content);

    if destination.exists() {
        if is_managed {
            let existing = fs::read(destination).await.unwrap_or_default();
            if !force && hash_content(&existing) == hash {
                return Ok(InstallOutcome::AlreadyManaged);
            }
            fs::write(destination, content)
                .await
                .with_context(|| format!("failed to overwrite: {}", destination.display()))?;
            return Ok(InstallOutcome::Installed { hash });
        }

        let backup = backup_path(destination);
        fs::rename(destination, &backup).await.with_context(|| {
            format!(
                "failed to back up {} to {}",
                destination.display(),
                backup.display()
            )
        })?;
        fs::write(destination, content)
            .await
            .with_context(|| format!("failed to install to: {}", destination.display()))?;
        return Ok(InstallOutcome::BackedUpAndInstalled { backup, hash });
    }

    fs::write(destination, content)
        .await
        .with_context(|| format!("failed to install to: {}", destination.display()))?;
    Ok(InstallOutcome::Installed { hash })
}

pub async fn uninstall_entry(
    entry: &AppEntry,
    dry_run: bool,
    force: bool,
) -> Result<UninstallOutcome> {
    if dry_run {
        return Ok(UninstallOutcome::DryRun);
    }

    if !entry.destination.exists() {
        return Ok(UninstallOutcome::NotFound);
    }

    let current = fs::read(&entry.destination)
        .await
        .with_context(|| format!("reading: {}", entry.destination.display()))?;
    let user_modified = hash_content(&current) != entry.content_hash;
    if user_modified && !force {
        return Ok(UninstallOutcome::UserModified);
    }

    fs::remove_file(&entry.destination)
        .await
        .with_context(|| format!("removing: {}", entry.destination.display()))?;

    if let Some(backup) = &entry.backup
        && backup.exists()
    {
        fs::rename(backup, &entry.destination)
            .await
            .with_context(|| format!("restoring backup: {}", backup.display()))?;
        return Ok(if user_modified {
            UninstallOutcome::ForceRestoredBackup {
                backup: backup.clone(),
            }
        } else {
            UninstallOutcome::RestoredBackup {
                backup: backup.clone(),
            }
        });
    }

    Ok(if user_modified {
        UninstallOutcome::ForceRemoved
    } else {
        UninstallOutcome::Removed
    })
}

pub async fn uninstall_entry_admin(
    entry: &AppEntry,
    dry_run: bool,
    force: bool,
) -> Result<UninstallOutcome> {
    if dry_run {
        return Ok(UninstallOutcome::DryRun);
    }
    if !cfg!(unix) || std::env::var("USER").is_ok_and(|user| user == "root") {
        return uninstall_entry(entry, false, force).await;
    }
    let _lock = admin_lock().await?;
    if !crate::privilege::ensure_admin(1).await? {
        anyhow::bail!("administrator permission was not granted");
    }
    if !entry.destination.exists() {
        return Ok(UninstallOutcome::NotFound);
    }
    let current = fs::read(&entry.destination)
        .await
        .with_context(|| format!("reading: {}", entry.destination.display()))?;
    let user_modified = hash_content(&current) != entry.content_hash;
    if user_modified && !force {
        return Ok(UninstallOutcome::UserModified);
    }
    let status = sudo_command()
        .args(["rm", "-f", "--"])
        .arg(&entry.destination)
        .status()
        .await
        .context("failed to remove privileged app configuration")?;
    if !status.success() {
        anyhow::bail!("administrator permission was not granted");
    }
    if let Some(backup) = &entry.backup
        && backup.exists()
    {
        let status = sudo_command()
            .args(["mv", "--"])
            .arg(backup)
            .arg(&entry.destination)
            .status()
            .await
            .context("failed to restore privileged app backup")?;
        if !status.success() {
            anyhow::bail!("failed to restore privileged app backup");
        }
        return Ok(if user_modified {
            UninstallOutcome::ForceRestoredBackup {
                backup: backup.clone(),
            }
        } else {
            UninstallOutcome::RestoredBackup {
                backup: backup.clone(),
            }
        });
    }
    Ok(if user_modified {
        UninstallOutcome::ForceRemoved
    } else {
        UninstallOutcome::Removed
    })
}

fn backup_path(dest: &Path) -> PathBuf {
    let name = dest.file_name().and_then(|n| n.to_str()).unwrap_or("file");
    dest.with_file_name(format!("{name}.shine.bak"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::install_core::AppInstallStrategy;
    use crate::install_core::manifest::AppEntry;

    async fn make_temp_dir() -> PathBuf {
        crate::test_support::make_temp_dir("shine-fileops").await
    }

    fn entry_for(dest: &Path, hash: u64) -> AppEntry {
        AppEntry {
            source: "app/test/f".to_string(),
            destination: dest.to_path_buf(),
            backup: None,
            content_hash: hash,
            install_strategy: AppInstallStrategy::Copy,
            uses_env: false,
            requires_admin: false,
        }
    }

    #[tokio::test]
    async fn install_to_empty_destination() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");

        let outcome = install_bytes(b"content", &dest, false, false, false)
            .await
            .unwrap();
        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
        assert!(dest.exists());
        assert_eq!(fs::read(&dest).await.unwrap(), b"content");
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn install_creates_parent_directories() {
        let dir = make_temp_dir().await;
        let dest = dir.join("deep/nested/dest.toml");

        install_bytes(b"content", &dest, false, false, false)
            .await
            .unwrap();
        assert!(dest.exists());
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn install_backs_up_unmanaged_existing_file() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        fs::write(&dest, b"user content").await.unwrap();

        let outcome = install_bytes(b"new content", &dest, false, false, false)
            .await
            .unwrap();
        let backup = match outcome {
            InstallOutcome::BackedUpAndInstalled { backup, .. } => backup,
            other => panic!("expected BackedUpAndInstalled, got {other:?}"),
        };
        assert!(backup.exists());
        assert_eq!(fs::read(&backup).await.unwrap(), b"user content");
        assert_eq!(fs::read(&dest).await.unwrap(), b"new content");
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn install_already_managed_same_content_returns_already_managed() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        fs::write(&dest, b"content").await.unwrap();

        let outcome = install_bytes(b"content", &dest, true, false, false)
            .await
            .unwrap();
        assert!(matches!(outcome, InstallOutcome::AlreadyManaged));
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn install_already_managed_different_content_overwrites() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        fs::write(&dest, b"old").await.unwrap();

        let outcome = install_bytes(b"updated", &dest, true, false, false)
            .await
            .unwrap();
        assert!(matches!(outcome, InstallOutcome::Installed { .. }));
        assert_eq!(fs::read(&dest).await.unwrap(), b"updated");
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn install_dry_run_does_not_write() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");

        let outcome = install_bytes(b"content", &dest, false, true, false)
            .await
            .unwrap();
        assert!(matches!(outcome, InstallOutcome::DryRun));
        assert!(!dest.exists());
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn uninstall_removes_matching_file() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        let content = b"managed content";
        fs::write(&dest, content).await.unwrap();
        let entry = entry_for(&dest, hash_content(content));

        let outcome = uninstall_entry(&entry, false, false).await.unwrap();
        assert!(matches!(outcome, UninstallOutcome::Removed));
        assert!(!dest.exists());
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn uninstall_restores_backup() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        let backup = dir.join("dest.toml.shine.bak");
        let content = b"managed";
        fs::write(&dest, content).await.unwrap();
        fs::write(&backup, b"original").await.unwrap();

        let entry = AppEntry {
            source: "app/test/dest.toml".to_string(),
            destination: dest.clone(),
            backup: Some(backup.clone()),
            content_hash: hash_content(content),
            install_strategy: AppInstallStrategy::Copy,
            uses_env: false,
            requires_admin: false,
        };
        let outcome = uninstall_entry(&entry, false, false).await.unwrap();
        assert!(matches!(outcome, UninstallOutcome::RestoredBackup { .. }));
        assert!(!backup.exists());
        assert_eq!(fs::read(&dest).await.unwrap(), b"original");
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn uninstall_skips_when_not_found() {
        let dir = make_temp_dir().await;
        let dest = dir.join("missing.toml");
        let entry = entry_for(&dest, 0);

        let outcome = uninstall_entry(&entry, false, false).await.unwrap();
        assert!(matches!(outcome, UninstallOutcome::NotFound));
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn uninstall_skips_user_modified_file() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        fs::write(&dest, b"user modified").await.unwrap();
        let entry = entry_for(&dest, hash_content(b"original content"));

        let outcome = uninstall_entry(&entry, false, false).await.unwrap();
        assert!(matches!(outcome, UninstallOutcome::UserModified));
        assert!(dest.exists(), "user-modified file must not be removed");
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn uninstall_force_removes_user_modified_file() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        fs::write(&dest, b"user modified").await.unwrap();
        let entry = entry_for(&dest, hash_content(b"original content"));

        let outcome = uninstall_entry(&entry, false, true).await.unwrap();
        assert!(matches!(outcome, UninstallOutcome::ForceRemoved));
        assert!(!dest.exists(), "force should remove user-modified file");
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn uninstall_force_restores_backup_after_user_modified_file() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        let backup = dir.join("dest.toml.shine.bak");
        fs::write(&dest, b"user modified").await.unwrap();
        fs::write(&backup, b"original").await.unwrap();

        let entry = AppEntry {
            source: "app/test/dest.toml".to_string(),
            destination: dest.clone(),
            backup: Some(backup.clone()),
            content_hash: hash_content(b"managed"),
            install_strategy: AppInstallStrategy::Copy,
            uses_env: false,
            requires_admin: false,
        };

        let outcome = uninstall_entry(&entry, false, true).await.unwrap();
        assert!(matches!(
            outcome,
            UninstallOutcome::ForceRestoredBackup { .. }
        ));
        assert!(!backup.exists());
        assert_eq!(fs::read(&dest).await.unwrap(), b"original");
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn uninstall_dry_run_leaves_file_intact() {
        let dir = make_temp_dir().await;
        let dest = dir.join("dest.toml");
        let content = b"managed";
        fs::write(&dest, content).await.unwrap();
        let entry = entry_for(&dest, hash_content(content));

        let outcome = uninstall_entry(&entry, true, false).await.unwrap();
        assert!(matches!(outcome, UninstallOutcome::DryRun));
        assert!(dest.exists());
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[test]
    fn backup_path_appends_shine_bak() {
        let p = PathBuf::from("/home/user/.gitconfig");
        let b = backup_path(&p);
        assert_eq!(b, PathBuf::from("/home/user/.gitconfig.shine.bak"));
    }
}