cli-engine 0.9.3

Rust CLI framework for consistent command modules
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
//! Filesystem and path utilities shared across the engine.
//!
//! These primitives back both the engine [config file](crate::config) and
//! [credential storage](crate::auth::storage): resolving the per-user base
//! directory, validating untrusted path components, and writing files
//! atomically with restrictive permissions. They are domain-agnostic so callers
//! that persist their own files can reuse them rather than re-implementing the
//! same path safety and atomic-write logic.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use crate::error::CliCoreError;

/// Reads `key` from the environment as a non-empty path, or `None`.
fn env_path(key: &str) -> Option<PathBuf> {
    std::env::var(key)
        .ok()
        .filter(|v| !v.is_empty())
        .map(PathBuf::from)
}

/// XDG-conventional `$HOME/.config`, if `HOME` is set.
fn home_config_dir() -> Option<PathBuf> {
    env_path("HOME").map(|home| home.join(".config"))
}

/// macOS-idiomatic `$HOME/Library/Application Support`, if `HOME` is set.
fn home_application_support_dir() -> Option<PathBuf> {
    env_path("HOME").map(|home| home.join("Library").join("Application Support"))
}

/// Resolves the per-user base directory for an app's config and data files.
///
/// Returns `$XDG_CONFIG_HOME` when set, else the platform-idiomatic default:
/// `$HOME/Library/Application Support` on macOS, `%APPDATA%` on Windows, or
/// `$HOME/.config` elsewhere. Only absolute paths are accepted; a relative
/// value is rejected so files never land relative to the current working
/// directory.
#[must_use]
pub fn config_base_dir() -> Option<PathBuf> {
    env_path("XDG_CONFIG_HOME")
        .or_else(|| {
            // On Windows prefer APPDATA over HOME/.config: HOME is often set by
            // Git Bash/MSYS shells and would place files in a non-standard
            // location. On macOS prefer the idiomatic Application Support
            // directory over XDG-conventional HOME/.config. `cfg!(...)` keeps
            // every branch compiled (and type-checked) on all platforms.
            if cfg!(windows) {
                env_path("APPDATA").or_else(home_config_dir)
            } else if cfg!(target_os = "macos") {
                home_application_support_dir().or_else(home_config_dir)
            } else {
                home_config_dir().or_else(|| env_path("APPDATA"))
            }
        })
        // Reject relative paths: a relative XDG_CONFIG_HOME/APPDATA/HOME would
        // silently place files relative to the current working directory.
        .filter(|p| p.is_absolute())
}

/// Name of the marker file that records a completed macOS config-dir
/// migration, so [`migrate_macos_config_dir`] only ever moves files once.
const MACOS_MIGRATION_FLAG: &str = ".cli_engine_macos_migrated";

/// One-time startup migration for the `$HOME/.config` → `$HOME/Library/Application
/// Support` default change on macOS.
///
/// No-op on any other platform, when `XDG_CONFIG_HOME` is set (the user
/// already controls the location explicitly), or once the migration marker
/// exists under the new `<app_id>` directory. Otherwise moves every entry
/// files and subdirectories alike, whatever they're named, out of
/// `$HOME/.config/<app_id>` and into `$HOME/Library/Application
/// Support/<app_id>`, since callers other than this crate (credential
/// storage, and any consumer-owned files) may have written there and this
/// function has no way to know their names.
pub(crate) fn migrate_macos_config_dir(app_id: &str) {
    if !cfg!(target_os = "macos") || env_path("XDG_CONFIG_HOME").is_some() {
        return;
    }
    let (Some(new_base), Some(old_base)) = (home_application_support_dir(), home_config_dir())
    else {
        return;
    };
    let new_app_dir = new_base.join(app_id);
    let flag_path = new_app_dir.join(MACOS_MIGRATION_FLAG);
    if flag_path.is_file() {
        return;
    }

    let old_app_dir = old_base.join(app_id);
    let outcome = move_directory_contents(&old_app_dir, &new_app_dir);
    if write_string_atomic(&flag_path, "").is_err() {
        // Couldn't record the marker (e.g. read-only filesystem), leave
        // things as they are and just re-check on the next invocation.
        return;
    }
    if outcome.moved > 0 {
        warn_macos_config_migrated(&old_app_dir, &new_app_dir, outcome.moved);
    }
    if outcome.skipped > 0 {
        warn_macos_config_migration_conflicts(&old_app_dir, &new_app_dir, outcome.skipped);
    }
}

/// Result of [`move_directory_contents`]: counts, not names, are all callers
/// currently need.
struct MoveOutcome {
    moved: usize,
    skipped: usize,
}

/// Moves every entry from `old_dir` into `new_dir`, creating `new_dir` only
/// if there's at least one entry to move. An entry whose name already exists
/// under `new_dir` is left untouched in `old_dir` (never overwritten) and
/// counted as skipped. Returns `(0, 0)` when `old_dir` doesn't exist.
///
/// Platform-agnostic: callers decide *when* to invoke this (e.g. only on
/// macOS); this function only knows how to move a directory's contents.
fn move_directory_contents(old_dir: &Path, new_dir: &Path) -> MoveOutcome {
    let Ok(entries) = std::fs::read_dir(old_dir) else {
        return MoveOutcome {
            moved: 0,
            skipped: 0,
        };
    };
    if ensure_private_dir(new_dir).is_err() {
        return MoveOutcome {
            moved: 0,
            skipped: 0,
        };
    }

    let mut moved = 0;
    let mut skipped = 0;
    for entry in entries.flatten() {
        let old_path = entry.path();
        let new_path = new_dir.join(entry.file_name());
        if new_path.exists() {
            skipped += 1;
            continue;
        }
        if std::fs::rename(&old_path, &new_path).is_ok() {
            moved += 1;
            continue;
        }
        // Cross-device fallback for regular files; a directory (in practice,
        // only the `credentials/` subdirectory) that fails to rename across
        // devices is left in place rather than recursively copied — same-
        // volume rename covers every normal `$HOME`-relative setup.
        if old_path.is_file()
            && std::fs::copy(&old_path, &new_path).is_ok()
            && std::fs::remove_file(&old_path).is_ok()
        {
            moved += 1;
        } else {
            skipped += 1;
        }
    }
    if skipped == 0 {
        std::fs::remove_dir(old_dir).ok();
    }
    MoveOutcome { moved, skipped }
}

/// Best-effort, single-line stderr notice for a completed migration.
fn warn_macos_config_migrated(old_dir: &Path, new_dir: &Path, moved: usize) {
    use std::io::Write as _;
    std::io::stderr()
        .lock()
        .write_all(
            format!(
                "cli-engine: moved {moved} file(s) from {} to {} (macOS config location changed)\n",
                old_dir.display(),
                new_dir.display()
            )
            .as_bytes(),
        )
        .ok();
}

/// Best-effort, single-line stderr notice for entries left behind because the
/// destination already had a same-named entry.
fn warn_macos_config_migration_conflicts(old_dir: &Path, new_dir: &Path, skipped: usize) {
    use std::io::Write as _;
    std::io::stderr()
        .lock()
        .write_all(
            format!(
                "cli-engine: left {skipped} file(s) in {} because {} already has file(s) with the same name. Please reconcile manually\n",
                old_dir.display(),
                new_dir.display()
            )
            .as_bytes(),
        )
        .ok();
}

/// Returns the user's home directory.
///
/// On non-Windows platforms this reads `$HOME`. On Windows, `%USERPROFILE%` is
/// tried first, then `$HOME` as a fallback (matching shell environments such as
/// Git Bash that set `HOME`).
///
/// Only absolute paths are accepted; a relative value is rejected so files
/// never land relative to the current working directory. Returns `None` when
/// no suitable variable is set or the resolved path is relative.
#[must_use]
pub fn home_dir() -> Option<PathBuf> {
    if cfg!(windows) {
        env_path("USERPROFILE").or_else(|| env_path("HOME"))
    } else {
        env_path("HOME")
    }
    .filter(|p| p.is_absolute())
}

/// Returns true only when `s` is a single, non-traversal path component that is
/// valid on all supported platforms.
///
/// Use this to validate untrusted segments (app ids, environment names, etc.)
/// before joining them into a path.
///
/// Rejects:
/// - empty strings, `.`, and `..`
/// - strings containing `/` or `\` (path separators on any platform)
/// - Windows-forbidden filename characters: `:  * ? " < > |`
/// - ASCII control characters (bytes 0x00–0x1F) and the DEL character (0x7F)
/// - leading or trailing space (leading space is invisible in directory listings)
/// - trailing `.` (valid on Unix but rejected by Windows)
/// - Windows reserved device names (`CON`, `NUL`, `COM1`, etc.) with or without extension
#[must_use]
pub fn is_safe_path_component(s: &str) -> bool {
    // '/' is listed explicitly because Path::components() silently strips trailing
    // slashes — "prod/" parses as a single Normal("prod") component and would
    // otherwise pass the components check below.
    const FORBIDDEN: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
    if s.contains(FORBIDDEN) || s.bytes().any(|b| b < 0x20 || b == 0x7F) {
        return false;
    }
    if s.starts_with(' ') || s.ends_with('.') || s.ends_with(' ') {
        return false;
    }
    // Windows treats these device names as special regardless of extension,
    // e.g. opening "NUL.json" writes to the null device, not a file.
    const RESERVED: &[&str] = &[
        "CON", "PRN", "AUX", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",
        "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8",
        "LPT9",
    ];
    let stem = Path::new(s)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(s);
    if RESERVED.iter().any(|r| stem.eq_ignore_ascii_case(r)) {
        return false;
    }
    let mut components = Path::new(s).components();
    matches!(components.next(), Some(std::path::Component::Normal(_)))
        && components.next().is_none()
}

/// Writes `contents` to `path` via a uniquely-named temp file then renames it
/// into place. On Unix the rename is atomic, the file is created `0600`, and
/// **newly-created** parent directories are best-effort restricted to `0700`.
/// Pre-existing parent directories are left unchanged so callers that write
/// into established locations (e.g. `$HOME`) do not alter their permissions.
/// On Windows the rename replaces an existing destination but is not
/// crash-atomic.
///
/// **Blocking**: this function uses synchronous filesystem I/O. Call it from
/// within [`tokio::task::spawn_blocking`] when used in an async context to
/// avoid stalling the executor.
///
/// # Errors
/// Returns an error when the directory cannot be created or the write/rename
/// fails.
pub fn write_string_atomic(path: &Path, contents: &str) -> crate::Result<()> {
    if let Some(parent) = path.parent() {
        ensure_private_dir(parent)
            .map_err(|e| CliCoreError::message(format!("failed to create directory: {e}")))?;
    }
    // Unique temp name without pulling in `rand`: pid plus a monotonic counter is
    // unique within a process, and the pid differs across processes.
    static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
    let unique = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let pid = std::process::id();
    let tmp_path = path.with_file_name(format!(
        "{}.{pid:x}.{unique:x}.tmp",
        path.file_name().and_then(|s| s.to_str()).unwrap_or("tmp"),
    ));
    write_tmp_file(&tmp_path, contents)?;
    if let Err(e) = std::fs::rename(&tmp_path, path) {
        std::fs::remove_file(&tmp_path).ok();
        return Err(CliCoreError::message(format!(
            "failed to finalize {}: {e}",
            path.display()
        )));
    }
    Ok(())
}

/// Creates `dir` (and any missing ancestors) if absent. On Unix, a directory
/// that did **not** already exist is best-effort restricted to `0700`;
/// pre-existing directories (e.g. `$HOME`) are left unchanged so their
/// permissions aren't altered by a caller that merely writes into them.
fn ensure_private_dir(dir: &Path) -> std::io::Result<()> {
    let existed = dir.is_dir();
    std::fs::create_dir_all(dir)?;
    #[cfg(unix)]
    if !existed {
        use std::os::unix::fs::PermissionsExt as _;
        if let Err(e) = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)) {
            tracing::debug!(
                path = %dir.display(),
                error = %e,
                "could not restrict directory permissions"
            );
        }
    }
    Ok(())
}

/// Opens `tmp_path` with `O_CREAT|O_EXCL` and writes `contents`, mode `0600` on
/// Unix so files are never world-readable.
fn write_tmp_file(tmp_path: &Path, contents: &str) -> crate::Result<()> {
    use std::io::Write as _;
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        opts.mode(0o600);
    }
    let mut file = opts.open(tmp_path).map_err(|e| {
        CliCoreError::message(format!("failed to write {}: {e}", tmp_path.display()))
    })?;
    file.write_all(contents.as_bytes())
        .map_err(|e| CliCoreError::message(format!("failed to write {}: {e}", tmp_path.display())))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::test_env::{EnvVarGuard, lock, with_xdg_config_home};

    fn with_home<F: FnOnce() -> R, R>(value: &Path, f: F) -> R {
        let _lock = lock();
        let _restore = EnvVarGuard::set("HOME", Some(value));
        f()
    }

    #[test]
    fn safe_path_component_basic() {
        assert!(is_safe_path_component("godaddy"));
        assert!(!is_safe_path_component(".."));
        assert!(!is_safe_path_component(""));
        assert!(!is_safe_path_component("a/b"));
        assert!(!is_safe_path_component("NUL"));
    }

    #[test]
    fn safe_path_component_rejects_windows_reserved_names() {
        for name in &[
            "CON", "con", "NUL", "nul", "COM1", "LPT9", "CON.txt", "NUL.json",
        ] {
            assert!(
                !is_safe_path_component(name),
                "{name:?} should be rejected as a Windows reserved name"
            );
        }
    }

    #[test]
    fn safe_path_component_rejects_control_and_space_edges() {
        assert!(!is_safe_path_component(" prod"), "leading space");
        assert!(!is_safe_path_component("prod\x7f"), "DEL byte");
        assert!(!is_safe_path_component("prod."), "trailing dot");
        assert!(!is_safe_path_component("prod "), "trailing space");
    }

    #[test]
    fn safe_path_component_accepts_normal_values() {
        for name in &["dev", "prod", "staging", "my-app", "my_app", "app.v2"] {
            assert!(is_safe_path_component(name), "{name:?} should be accepted");
        }
    }

    #[test]
    fn config_base_dir_rejects_relative_xdg() {
        with_xdg_config_home(Path::new("."), || {
            assert!(
                config_base_dir().is_none(),
                "relative XDG_CONFIG_HOME should be rejected"
            );
        });
    }

    #[test]
    fn config_base_dir_honors_xdg() {
        let dir = std::env::temp_dir().join("cli-engine-fs-base-test");
        with_xdg_config_home(&dir, || {
            assert_eq!(config_base_dir(), Some(dir.clone()));
        });
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn config_base_dir_defaults_to_application_support_on_macos() {
        let home = std::env::temp_dir().join("cli-engine-fs-macos-test");
        let _lock = lock();
        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", None);
        let _home = EnvVarGuard::set("HOME", Some(&home));
        assert_eq!(
            config_base_dir(),
            Some(home.join("Library").join("Application Support"))
        );
    }

    #[test]
    fn home_dir_honors_home_env() {
        let dir = std::env::temp_dir().join("cli-engine-fs-home-test");
        with_home(&dir, || {
            assert_eq!(home_dir(), Some(dir.clone()));
        });
    }

    #[test]
    fn home_dir_rejects_relative() {
        with_home(Path::new("."), || {
            assert!(home_dir().is_none(), "relative HOME should be rejected");
        });
    }

    #[tokio::test]
    async fn write_string_atomic_round_trip_creates_dirs() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("nested").join("file.txt");
        write_string_atomic(&path, "hello").expect("write");
        assert_eq!(std::fs::read_to_string(&path).expect("read"), "hello");
        // Overwrite replaces the contents.
        write_string_atomic(&path, "world").expect("rewrite");
        assert_eq!(std::fs::read_to_string(&path).expect("read"), "world");
        // No stray temp files remain alongside the target.
        let strays: Vec<_> = std::fs::read_dir(path.parent().expect("parent"))
            .expect("read_dir")
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
            .collect();
        assert!(strays.is_empty(), "temp files should be renamed away");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn write_string_atomic_sets_owner_only_mode() {
        use std::os::unix::fs::PermissionsExt as _;
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("secret.txt");
        write_string_atomic(&path, "s3cr3t").expect("write");
        let mode = std::fs::metadata(&path).expect("meta").permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "file should be owner read/write only");
    }

    #[test]
    fn move_directory_contents_returns_zero_when_old_dir_is_absent() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let outcome = move_directory_contents(&tmp.path().join("missing"), &tmp.path().join("new"));
        assert_eq!((outcome.moved, outcome.skipped), (0, 0));
        assert!(
            !tmp.path().join("new").exists(),
            "destination should not be created for a no-op move"
        );
    }

    #[test]
    fn move_directory_contents_moves_files_and_subdirectories() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let old_dir = tmp.path().join("old");
        let new_dir = tmp.path().join("new");
        std::fs::create_dir_all(old_dir.join("credentials")).expect("mkdir");
        std::fs::write(old_dir.join("config.toml"), "a = 1").expect("write");
        std::fs::write(old_dir.join("contacts.toml"), "b = 2").expect("write");
        std::fs::write(old_dir.join("credentials").join("token.json"), "{}").expect("write");

        let outcome = move_directory_contents(&old_dir, &new_dir);

        assert_eq!(outcome.moved, 3, "config.toml, contacts.toml, credentials/");
        assert_eq!(outcome.skipped, 0);
        assert_eq!(
            std::fs::read_to_string(new_dir.join("config.toml")).expect("read"),
            "a = 1"
        );
        assert_eq!(
            std::fs::read_to_string(new_dir.join("contacts.toml")).expect("read"),
            "b = 2"
        );
        assert_eq!(
            std::fs::read_to_string(new_dir.join("credentials").join("token.json")).expect("read"),
            "{}"
        );
        assert!(!old_dir.exists(), "emptied old directory should be removed");
    }

    #[test]
    fn move_directory_contents_leaves_conflicting_entries_in_place() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let old_dir = tmp.path().join("old");
        let new_dir = tmp.path().join("new");
        std::fs::create_dir_all(&old_dir).expect("mkdir");
        std::fs::create_dir_all(&new_dir).expect("mkdir");
        std::fs::write(old_dir.join("config.toml"), "old").expect("write");
        std::fs::write(new_dir.join("config.toml"), "new").expect("write");
        std::fs::write(old_dir.join("contacts.toml"), "moves fine").expect("write");

        let outcome = move_directory_contents(&old_dir, &new_dir);

        assert_eq!(outcome.moved, 1, "contacts.toml has no conflict");
        assert_eq!(
            outcome.skipped, 1,
            "config.toml conflicts and is left alone"
        );
        assert_eq!(
            std::fs::read_to_string(new_dir.join("config.toml")).expect("read"),
            "new",
            "destination copy must never be overwritten"
        );
        assert_eq!(
            std::fs::read_to_string(old_dir.join("config.toml")).expect("read"),
            "old",
            "conflicting source file is left in place"
        );
        assert!(
            old_dir.exists(),
            "old directory is not removed while a conflict remains"
        );
        assert!(!old_dir.join("contacts.toml").exists());
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn migrate_macos_config_dir_moves_files_once() {
        let home = std::env::temp_dir().join("cli-engine-fs-migrate-test");
        let old_app_dir = home.join(".config").join("my-app");
        let new_app_dir = home
            .join("Library")
            .join("Application Support")
            .join("my-app");
        // Fixed temp-dir name (matching this file's other macOS test): clean
        // up any residue from a previous run before writing real fixtures.
        std::fs::remove_dir_all(&home).ok();
        std::fs::create_dir_all(&old_app_dir).expect("mkdir");
        std::fs::write(old_app_dir.join("environments.toml"), "env = true").expect("write");
        let _lock = lock();
        let _xdg = EnvVarGuard::set("XDG_CONFIG_HOME", None);
        let _home = EnvVarGuard::set("HOME", Some(&home));

        migrate_macos_config_dir("my-app");
        assert_eq!(
            std::fs::read_to_string(new_app_dir.join("environments.toml")).expect("read"),
            "env = true"
        );
        assert!(new_app_dir.join(MACOS_MIGRATION_FLAG).is_file());
        assert!(!old_app_dir.exists());

        // Second run is a no-op: dropping a new file into the old location
        // (simulating a stray write) must not be picked up once migrated.
        std::fs::create_dir_all(&old_app_dir).expect("mkdir");
        std::fs::write(old_app_dir.join("late.toml"), "ignored").expect("write");
        migrate_macos_config_dir("my-app");
        assert!(
            !new_app_dir.join("late.toml").exists(),
            "migration must not repeat once the marker exists"
        );
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn migrate_macos_config_dir_is_a_noop_when_xdg_config_home_is_set() {
        let home = std::env::temp_dir().join("cli-engine-fs-migrate-xdg-test");
        let xdg = std::env::temp_dir().join("cli-engine-fs-migrate-xdg-override");
        let old_app_dir = home.join(".config").join("my-app");
        std::fs::remove_dir_all(&home).ok();
        std::fs::create_dir_all(&old_app_dir).expect("mkdir");
        std::fs::write(old_app_dir.join("config.toml"), "x = 1").expect("write");
        // `with_xdg_config_home` takes the shared env-var lock itself; taking
        // it again here would deadlock on the same thread.
        with_xdg_config_home(&xdg, || {
            let _home = EnvVarGuard::set("HOME", Some(&home));
            migrate_macos_config_dir("my-app");
        });

        assert!(
            old_app_dir.join("config.toml").is_file(),
            "an explicit XDG_CONFIG_HOME must leave the old default location untouched"
        );
    }
}