dodot-lib 0.20.0

Core library for dodot dotfiles manager
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! Shell integration — generates `dodot-init.sh`.
//!
//! Unlike the Go implementation which ships a ~400-line shell script
//! that re-discovers the datastore layout at runtime, we generate a
//! flat, declarative script from the actual datastore state. This
//! means:
//!
//! - Zero logic duplication between Rust and shell
//! - The script is just `source` and `PATH=` lines — trivially fast
//! - Changes to the datastore layout only need to happen in Rust
//!
//! The generated script is written to `data_dir/shell/dodot-init.sh`.
//! Users source it from their shell profile:
//!
//! ```sh
//! [ -f ~/.local/share/dodot/shell/dodot-init.sh ] && . ~/.local/share/dodot/shell/dodot-init.sh
//! ```
//!
//! In the future, this can also be exposed as `dodot init-sh` or
//! a minimal standalone binary for even faster shell startup.
//!
//! # Profiling wrapper (Phase 2 of profiling.lex)
//!
//! When the caller passes `profiling_enabled = true`, the generator
//! wraps every `source` and PATH line with an inline `EPOCHREALTIME`
//! capture and writes one `profile-*.tsv` per shell start under
//! `<data_dir>/probes/shell-init/`. The wrapper is gated on a runtime
//! check (`bash 5+` / `zsh` with `EPOCHREALTIME` available); shells
//! without the variable fall through to the unchanged source/PATH
//! path with a single `[ "$_dodot_prof" = "1" ]` test of overhead.
//! When `profiling_enabled = false`, the generated script is
//! byte-identical to the pre-Phase-2 form.
//!
//! Sources are *not* wrapped in a shell function: in zsh, `source`
//! inside a function changes scoping for plain variable assignments
//! in the sourced file, which is a behavioural surprise nobody asked
//! for. We pay the price of a slightly longer script in exchange for
//! semantic equivalence with the un-instrumented form.

use std::fmt::Write;
use std::path::{Path, PathBuf};

use crate::fs::Fs;
use crate::paths::Pather;
use crate::Result;

/// Append the "nothing to do" notice for an empty init script.
fn append_empty_notice(script: &mut String) {
    writeln!(script, "# No shell scripts or PATH additions to load.").unwrap();
    writeln!(
        script,
        "# Run `dodot up` to deploy packs, or `dodot status` to see available packs."
    )
    .unwrap();
}

/// Generate the shell init script content from the current datastore state.
///
/// Scans the datastore for:
/// - `packs/*/shell/*` — symlinks to shell scripts → `source` lines
/// - `packs/*/path/*` — symlinks to directories → `PATH=` lines
///
/// When `profiling_enabled` is true and there is at least one entry to
/// emit, the script also carries the per-line timing wrapper described
/// in the module docs.
pub fn generate_init_script(
    fs: &dyn Fs,
    paths: &dyn Pather,
    profiling_enabled: bool,
) -> Result<String> {
    let mut script = String::new();

    writeln!(script, "#!/bin/sh").unwrap();
    writeln!(script, "# Generated by dodot — do not edit manually.").unwrap();
    writeln!(script, "# Regenerated on every `dodot up` / `dodot down`.").unwrap();
    writeln!(script).unwrap();

    // Discover all packs with state
    let packs_dir = paths.data_dir().join("packs");
    if !fs.exists(&packs_dir) {
        append_empty_notice(&mut script);
        return Ok(script);
    }

    let pack_entries = fs.read_dir(&packs_dir)?;

    // Collect shell sources and path additions separately so we can
    // group them in the output for readability.
    let mut shell_sources: Vec<(String, PathBuf)> = Vec::new(); // (pack, target)
    let mut path_additions: Vec<(String, PathBuf)> = Vec::new(); // (pack, target)

    for pack_entry in &pack_entries {
        if !pack_entry.is_dir {
            continue;
        }
        let pack_name = &pack_entry.name;

        // Shell handler: source scripts
        let shell_dir = paths.handler_data_dir(pack_name, "shell");
        if fs.is_dir(&shell_dir) {
            if let Ok(entries) = fs.read_dir(&shell_dir) {
                for entry in entries {
                    if !entry.is_symlink {
                        continue;
                    }
                    // Follow the symlink to get the actual file path
                    let target = fs.readlink(&entry.path)?;
                    shell_sources.push((pack_name.clone(), target));
                }
            }
        }

        // Path handler: add to PATH
        let path_dir = paths.handler_data_dir(pack_name, "path");
        if fs.is_dir(&path_dir) {
            if let Ok(entries) = fs.read_dir(&path_dir) {
                for entry in entries {
                    if !entry.is_symlink {
                        continue;
                    }
                    let target = fs.readlink(&entry.path)?;
                    path_additions.push((pack_name.clone(), target));
                }
            }
        }
    }

    // If nothing is deployed, add an explanatory comment
    if path_additions.is_empty() && shell_sources.is_empty() {
        append_empty_notice(&mut script);
        return Ok(script);
    }

    // Profiling preamble (only when enabled and there's at least one entry).
    let profiling_active = profiling_enabled;
    if profiling_active {
        emit_profiling_preamble(
            &mut script,
            &paths.probes_shell_init_dir(),
            &paths.init_script_path(),
        );
    }

    // Emit PATH additions
    if !path_additions.is_empty() {
        writeln!(script, "# PATH additions").unwrap();
        for (pack, target) in &path_additions {
            writeln!(script, "# [{pack}]").unwrap();
            if profiling_active {
                emit_timed_path(&mut script, pack, target);
            } else {
                writeln!(script, "export PATH=\"{}:$PATH\"", target.display()).unwrap();
            }
        }
        writeln!(script).unwrap();
    }

    // Emit shell sources
    if !shell_sources.is_empty() {
        writeln!(script, "# Shell scripts").unwrap();
        for (pack, target) in &shell_sources {
            writeln!(script, "# [{pack}]").unwrap();
            if profiling_active {
                emit_timed_source(&mut script, pack, target);
            } else {
                writeln!(
                    script,
                    "[ -f \"{}\" ] && . \"{}\"",
                    target.display(),
                    target.display()
                )
                .unwrap();
            }
        }
        writeln!(script).unwrap();
    }

    // Profiling epilogue (close the report, scrub our state).
    if profiling_active {
        emit_profiling_epilogue(&mut script);
    }

    Ok(script)
}

/// Generate and write the init script to `data_dir/shell/dodot-init.sh`.
///
/// Returns the path where the script was written.
pub fn write_init_script(
    fs: &dyn Fs,
    paths: &dyn Pather,
    profiling_enabled: bool,
) -> Result<PathBuf> {
    let script_content = generate_init_script(fs, paths, profiling_enabled)?;
    let script_path = paths.init_script_path();

    fs.mkdir_all(paths.shell_dir())?;
    fs.write_file(&script_path, script_content.as_bytes())?;
    fs.set_permissions(&script_path, 0o755)?;

    Ok(script_path)
}

// ── Profiling wrapper emitters ───────────────────────────────────────

/// The runtime-detection preamble. Sets `_dodot_prof` to `1` when the
/// current shell is bash 5+ or zsh with `EPOCHREALTIME` available;
/// otherwise leaves it `0` (the wrapper falls through to the no-op
/// path). All shell variables are namespaced `_dodot_*` so we don't
/// stomp on the user's environment.
fn emit_profiling_preamble(script: &mut String, profiles_dir: &Path, init_script_path: &Path) {
    let dir = sh_quote(&profiles_dir.display().to_string());
    let init_script = sh_quote(&init_script_path.display().to_string());
    writeln!(script, "# ── dodot shell-init profiling (Phase 2) ──").unwrap();
    writeln!(script, "_dodot_prof=0").unwrap();
    writeln!(
        script,
        "if [ -n \"${{BASH_VERSION:-}}\" ] || [ -n \"${{ZSH_VERSION:-}}\" ]; then"
    )
    .unwrap();
    // zsh exposes EPOCHREALTIME only after `zmodload zsh/datetime`. Load
    // it eagerly here; bash 5+ has the variable built in and ignores
    // unknown commands like `zmodload` (we suppress its `command not
    // found` error). Doing this *inside* the bash/zsh guard keeps it off
    // hot paths in plain sh.
    writeln!(
        script,
        "  [ -n \"${{ZSH_VERSION:-}}\" ] && zmodload zsh/datetime 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "  if [ -n \"${{EPOCHREALTIME:-}}\" ]; then").unwrap();
    writeln!(script, "    _dodot_prof_dir={dir}").unwrap();
    writeln!(
        script,
        "    _dodot_prof_file=\"$_dodot_prof_dir/profile-${{EPOCHSECONDS:-0}}-$$-${{RANDOM}}.tsv\""
    )
    .unwrap();
    writeln!(
        script,
        "    if mkdir -p \"$_dodot_prof_dir\" 2>/dev/null; then"
    )
    .unwrap();
    writeln!(script, "      _dodot_prof_t0=$EPOCHREALTIME").unwrap();
    writeln!(script, "      {{").unwrap();
    writeln!(script, "        printf '# dodot shell-init profile v1\\n'").unwrap();
    writeln!(
        script,
        "        printf '# shell\\t%s\\n' \"${{BASH_VERSION:+bash $BASH_VERSION}}${{ZSH_VERSION:+zsh $ZSH_VERSION}}\""
    )
    .unwrap();
    writeln!(
        script,
        "        printf '# start_t\\t%s\\n' \"$_dodot_prof_t0\""
    )
    .unwrap();
    writeln!(
        script,
        "        printf '# init_script\\t%s\\n' {init_script}"
    )
    .unwrap();
    writeln!(
        script,
        "        printf '# columns\\tphase\\tpack\\thandler\\ttarget\\tstart_t\\tend_t\\texit_status\\n'"
    )
    .unwrap();
    writeln!(
        script,
        "      }} > \"$_dodot_prof_file\" 2>/dev/null && _dodot_prof=1"
    )
    .unwrap();
    writeln!(script, "    fi").unwrap();
    writeln!(script, "  fi").unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(script).unwrap();
}

/// One inline-timed `export PATH=…` row. The branch is one comparison
/// at runtime — negligible on shells where the wrapper is inert.
fn emit_timed_path(script: &mut String, pack: &str, target: &Path) {
    let target_str = target.display().to_string();
    let target_q = sh_quote(&target_str);
    writeln!(script, "if [ \"$_dodot_prof\" = \"1\" ]; then").unwrap();
    writeln!(
        script,
        "  _dodot_t0=$EPOCHREALTIME; export PATH=\"{target_str}:$PATH\"; _dodot_t1=$EPOCHREALTIME"
    )
    .unwrap();
    writeln!(
        script,
        "  printf 'path\\t{pack}\\tpath\\t%s\\t%s\\t%s\\t0\\n' {target_q} \"$_dodot_t0\" \"$_dodot_t1\" >> \"$_dodot_prof_file\" 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "else").unwrap();
    writeln!(script, "  export PATH=\"{target_str}:$PATH\"").unwrap();
    writeln!(script, "fi").unwrap();
}

/// One inline-timed `[ -f X ] && . X` row, capturing the source's
/// exit status. Same overhead profile as the PATH variant.
fn emit_timed_source(script: &mut String, pack: &str, target: &Path) {
    let target_str = target.display().to_string();
    let target_q = sh_quote(&target_str);
    writeln!(script, "if [ \"$_dodot_prof\" = \"1\" ]; then").unwrap();
    writeln!(
        script,
        "  _dodot_t0=$EPOCHREALTIME; [ -f \"{target_str}\" ] && . \"{target_str}\"; _dodot_rc=$?; _dodot_t1=$EPOCHREALTIME"
    )
    .unwrap();
    writeln!(
        script,
        "  printf 'source\\t{pack}\\tshell\\t%s\\t%s\\t%s\\t%s\\n' {target_q} \"$_dodot_t0\" \"$_dodot_t1\" \"$_dodot_rc\" >> \"$_dodot_prof_file\" 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "else").unwrap();
    writeln!(script, "  [ -f \"{target_str}\" ] && . \"{target_str}\"").unwrap();
    writeln!(script, "fi").unwrap();
}

/// Closes out the report (writes the `# end_t` marker) and clears
/// every `_dodot_*` shell variable so we don't leak state into the
/// user's interactive shell.
fn emit_profiling_epilogue(script: &mut String) {
    writeln!(script, "# ── dodot shell-init profiling epilogue ──").unwrap();
    writeln!(script, "if [ \"$_dodot_prof\" = \"1\" ]; then").unwrap();
    writeln!(
        script,
        "  printf '# end_t\\t%s\\n' \"$EPOCHREALTIME\" >> \"$_dodot_prof_file\" 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(
        script,
        "unset _dodot_prof _dodot_prof_dir _dodot_prof_file _dodot_prof_t0 _dodot_t0 _dodot_t1 _dodot_rc 2>/dev/null"
    )
    .unwrap();
}

/// Single-quote a string for safe use in POSIX shell. Embedded single
/// quotes are escaped via the `'\''` idiom.
fn sh_quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('\'');
    for c in s.chars() {
        if c == '\'' {
            out.push_str("'\\''");
        } else {
            out.push(c);
        }
    }
    out.push('\'');
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::datastore::{CommandOutput, CommandRunner, DataStore, FilesystemDataStore};
    use crate::testing::TempEnvironment;
    use std::sync::Arc;

    struct NoopRunner;
    impl CommandRunner for NoopRunner {
        fn run(&self, _: &str, _: &[String]) -> Result<CommandOutput> {
            Ok(CommandOutput {
                exit_code: 0,
                stdout: String::new(),
                stderr: String::new(),
            })
        }
    }

    fn make_datastore(env: &TempEnvironment) -> FilesystemDataStore {
        FilesystemDataStore::new(env.fs.clone(), env.paths.clone(), Arc::new(NoopRunner))
    }

    #[test]
    fn empty_datastore_produces_helpful_script() {
        let env = TempEnvironment::builder().build();
        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();

        assert!(script.starts_with("#!/bin/sh"));
        assert!(script.contains("Generated by dodot"));
        assert!(script.contains("No shell scripts or PATH additions"));
        assert!(script.contains("dodot up"));
        assert!(script.contains("dodot status"));
        // No source or PATH lines
        assert!(!script.contains("export PATH"));
        assert!(!script.contains(". \""));
    }

    #[test]
    fn shell_handler_state_produces_source_lines() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        let source = env.dotfiles_root.join("vim/aliases.sh");
        ds.create_data_link("vim", "shell", &source).unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();

        assert!(script.contains("# Shell scripts"), "script:\n{script}");
        assert!(script.contains("# [vim]"), "script:\n{script}");
        assert!(
            script.contains(&format!(
                "[ -f \"{}\" ] && . \"{}\"",
                source.display(),
                source.display()
            )),
            "script:\n{script}"
        );
    }

    #[test]
    fn path_handler_state_produces_path_lines() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("bin/myscript", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);
        let source = env.dotfiles_root.join("vim/bin");
        ds.create_data_link("vim", "path", &source).unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();

        assert!(script.contains("# PATH additions"), "script:\n{script}");
        assert!(script.contains("# [vim]"), "script:\n{script}");
        assert!(
            script.contains(&format!("export PATH=\"{}:$PATH\"", source.display())),
            "script:\n{script}"
        );
    }

    #[test]
    fn multiple_packs_combined() {
        let env = TempEnvironment::builder()
            .pack("git")
            .file("aliases.sh", "alias gs='git status'")
            .done()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .file("bin/vimrun", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);

        // Shell scripts
        ds.create_data_link("git", "shell", &env.dotfiles_root.join("git/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        // Path
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();

        // Should have both shell sources
        assert!(script.contains("# [git]"), "script:\n{script}");
        assert!(script.contains("# [vim]"), "script:\n{script}");
        // Should have PATH addition
        assert!(script.contains("export PATH="), "script:\n{script}");
        // Should have source lines
        let source_count = script.matches(". \"").count();
        assert_eq!(
            source_count, 2,
            "expected 2 source lines, script:\n{script}"
        );
    }

    #[test]
    fn write_init_script_creates_executable_file() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script_path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();

        assert_eq!(script_path, env.paths.init_script_path());
        env.assert_exists(&script_path);

        let content = env.fs.read_to_string(&script_path).unwrap();
        assert!(content.starts_with("#!/bin/sh"));
        assert!(content.contains("aliases.sh"));

        // Check executable permission
        let meta = std::fs::metadata(&script_path).unwrap();
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(meta.permissions().mode() & 0o111, 0o111);
    }

    #[test]
    fn script_regenerated_reflects_current_state() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);

        // Initially empty
        let script1 = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();
        assert!(!script1.contains("aliases.sh"));

        // Deploy shell script
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script2 = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();
        assert!(script2.contains("aliases.sh"));

        // Remove state
        ds.remove_state("vim", "shell").unwrap();

        let script3 = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();
        assert!(!script3.contains("aliases.sh"));
    }

    #[test]
    fn ignores_non_symlink_files_in_handler_dirs() {
        let env = TempEnvironment::builder().build();

        // Create a non-symlink file in the shell handler dir
        let shell_dir = env.paths.handler_data_dir("vim", "shell");
        env.fs.mkdir_all(&shell_dir).unwrap();
        env.fs
            .write_file(&shell_dir.join("not-a-symlink"), b"noise")
            .unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();
        assert!(!script.contains("not-a-symlink"));
    }

    #[test]
    fn path_additions_come_before_shell_sources() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .file("bin/myscript", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();

        let path_pos = script.find("# PATH additions").unwrap();
        let shell_pos = script.find("# Shell scripts").unwrap();
        assert!(
            path_pos < shell_pos,
            "PATH additions should come before shell sources"
        );
    }

    // ── Phase 2: profiling wrapper ──────────────────────────────────

    #[test]
    fn profiling_disabled_matches_phase1_byte_for_byte() {
        // The contract: when profiling is off, the script must be the
        // exact same bytes a Phase-1 generator would have produced. This
        // protects users who don't want any change to their init script.
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();
        assert!(!script.contains("_dodot_prof"));
        assert!(!script.contains("EPOCHREALTIME"));
        assert!(!script.contains("dodot shell-init profile"));
    }

    #[test]
    fn profiling_enabled_emits_runtime_gated_preamble() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true).unwrap();

        // Preamble feature-detects bash 5+ / zsh + EPOCHREALTIME
        assert!(script.contains("BASH_VERSION"));
        assert!(script.contains("ZSH_VERSION"));
        assert!(script.contains("EPOCHREALTIME"));
        // The profile dir comes from Pather, so the script should embed it.
        assert!(script.contains(env.paths.probes_shell_init_dir().to_str().unwrap()));
        // File naming includes pid + RANDOM for collision-resistance.
        assert!(script.contains("$$"));
        assert!(script.contains("RANDOM"));
        // Header lines we always emit.
        assert!(script.contains("# dodot shell-init profile v1"));
        assert!(script.contains("columns\\tphase\\tpack\\thandler\\ttarget"));
    }

    #[test]
    fn profiling_enabled_wraps_each_source_with_else_path() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "")
            .file("bin/tool", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true).unwrap();

        // Each entry has an if/else so unprofiled shells still source / set PATH.
        // (One else per entry; the epilogue uses an if-only form, so counting
        // `else` keeps us focused on the entry wrappers.)
        let else_count = script.matches("else").count();
        assert_eq!(
            else_count, 2,
            "expected one else-branch per entry; script:\n{script}"
        );

        // Source row carries the captured exit status; PATH row hard-codes 0.
        assert!(script.contains("printf 'source\\tvim\\tshell\\t"));
        assert!(script.contains("printf 'path\\tvim\\tpath\\t"));
        assert!(script.contains("\"$_dodot_rc\""));
    }

    #[test]
    fn profiling_epilogue_writes_end_marker_and_unsets_state() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true).unwrap();
        // End-of-run timestamp.
        assert!(script.contains("# end_t"));
        // We scrub our state to avoid leaking into the user's shell.
        assert!(script.contains("unset _dodot_prof"));
        assert!(script.contains("_dodot_prof_file"));
    }

    #[test]
    fn profiling_enabled_with_empty_datastore_skips_preamble() {
        // No deployed entries → empty notice only, no profiling boilerplate.
        let env = TempEnvironment::builder().build();
        let script = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true).unwrap();
        assert!(script.contains("No shell scripts or PATH additions"));
        assert!(!script.contains("_dodot_prof"));
    }

    #[test]
    fn shell_quoting_handles_paths_with_single_quotes() {
        // A path with a single quote in it must round-trip safely
        // through the printf args. Embedded `'` becomes `'\''`.
        assert_eq!(sh_quote("plain"), "'plain'");
        assert_eq!(sh_quote("it's"), "'it'\\''s'");
        assert_eq!(sh_quote(""), "''");
    }
}