dodot-lib 2.0.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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
//! 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;

pub mod validate;
pub use validate::{
    error_sidecar_path, validate_shell_sources, NoopSyntaxChecker, ShellValidationFailure,
    ShellValidationReport, SyntaxCheckResult, SyntaxChecker, SystemSyntaxChecker, ERRORS_SUBDIR,
};

/// 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;
        }
        // The datastore subtree is keyed by the on-disk directory
        // name (e.g. `010-nvim`), but the comment we emit in the
        // generated init script uses the pack's display name
        // (`nvim`) — that's what the user sees in `dodot status` and
        // expects to recognise here.
        let pack_dir = &pack_entry.name;
        let pack_display = crate::packs::display_name_for(pack_dir).to_string();

        // Shell handler: source scripts
        let shell_dir = paths.handler_data_dir(pack_dir, "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_display.clone(), target));
                }
            }
        }

        // Path handler: add to PATH
        let path_dir = paths.handler_data_dir(pack_dir, "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_display.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 {
                // Loud-failure wrapper: if the source command itself
                // exits non-zero, print a dodot-attributed message to
                // stderr alongside the shell's own error so the user
                // can see *which* dodot-managed file failed. The
                // shell's native message already carries the line
                // number; we add the breadcrumb back to dodot.
                writeln!(
                    script,
                    "[ -f \"{p}\" ] && {{ . \"{p}\" || echo \"dodot: shell source exited $?: {p}\" >&2; }}",
                    p = 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();
    // Sibling errors log: one record per source whose stderr was non-empty.
    // Format: `@@\t<target>\t<exit_status>` header line, followed by the
    // captured stderr verbatim, followed by a trailing newline. Loaded
    // alongside the profile by `probe::shell_init::read_recent_profiles`
    // and parsed by `probe::shell_init::parse_errors_log`.
    writeln!(
        script,
        "    _dodot_err_file=\"${{_dodot_prof_file%.tsv}}.errors.log\""
    )
    .unwrap();
    // Per-shell scratch file for capturing each source's stderr. Reused
    // across every source in this shell startup; truncated each time.
    writeln!(script, "    _dodot_err_tmp=\"$_dodot_prof_dir/.errtmp-$$\"").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();
    // Errors log is created lazily — see `emit_timed_source`. Most shell
    // startups have no stderr from any source, and writing an empty
    // header file for each one would defeat the "fast path is free"
    // claim. The first source that actually emits stderr seeds the
    // header before appending its record.
    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 and stderr. Same overhead profile as the PATH variant
/// when the sourced file is silent; one extra `[ -s ]` test plus an
/// append when stderr is non-empty.
///
/// Both branches (profiling-active and unprofiled fallback) emit the
/// loud-failure message on a non-zero source exit, so users see the
/// dodot breadcrumb whether or not their shell supports the timing
/// path.
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();
    // `_dodot_rc` is initialised to 0 *before* the source attempt so a
    // missing file (the `[ -f … ]` test failing) does not get reported
    // as "exited 1". The compound `&& { … }` only sets `_dodot_rc` from
    // the actual `.` invocation; otherwise it stays 0. Stderr from the
    // source is redirected to `_dodot_err_tmp`; if non-empty, we
    // re-emit it to the user's stderr (preserving the shell's own
    // error display) and append it to the per-shell errors log.
    writeln!(
        script,
        "  _dodot_rc=0; : > \"$_dodot_err_tmp\" 2>/dev/null; _dodot_t0=$EPOCHREALTIME; [ -f \"{target_str}\" ] && {{ . \"{target_str}\" 2>\"$_dodot_err_tmp\"; _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();
    // Stderr-handling block. Skipped entirely when the sourced file was
    // silent (the common case). When non-empty, we print to the user's
    // stderr and append a record to the errors log. The errors log is
    // seeded with its `v1` header on first use — keeping creation lazy
    // means a clean shell startup leaves no orphan `*.errors.log` on
    // disk. The trailing `\n` after each record guarantees the next
    // record's `@@` header starts on its own line even if the captured
    // stderr didn't end with a newline.
    writeln!(script, "  if [ -s \"$_dodot_err_tmp\" ]; then").unwrap();
    writeln!(script, "    cat \"$_dodot_err_tmp\" >&2").unwrap();
    writeln!(
        script,
        "    [ -f \"$_dodot_err_file\" ] || printf '# dodot shell-init errors v1\\n' > \"$_dodot_err_file\" 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "    {{").unwrap();
    writeln!(
        script,
        "      printf '@@\\t%s\\t%s\\n' {target_q} \"$_dodot_rc\""
    )
    .unwrap();
    writeln!(script, "      cat \"$_dodot_err_tmp\"").unwrap();
    writeln!(script, "      printf '\\n'").unwrap();
    writeln!(script, "    }} >> \"$_dodot_err_file\" 2>/dev/null").unwrap();
    writeln!(script, "  elif [ \"$_dodot_rc\" -ne 0 ]; then").unwrap();
    // Non-zero exit with empty stderr — still emit the loud breadcrumb
    // so the user knows dodot saw a failure (matches prior behaviour).
    writeln!(
        script,
        "    echo \"dodot: shell source exited $_dodot_rc: {target_str}\" >&2"
    )
    .unwrap();
    writeln!(script, "  fi").unwrap();
    writeln!(script, "else").unwrap();
    writeln!(
        script,
        "  [ -f \"{target_str}\" ] && {{ . \"{target_str}\" || echo \"dodot: shell source exited $?: {target_str}\" >&2; }}"
    )
    .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();
    // Remove the per-shell stderr scratch file. It's reused across
    // sources within one shell startup; here at exit we tidy up.
    writeln!(
        script,
        "  [ -n \"${{_dodot_err_tmp:-}}\" ] && rm -f \"$_dodot_err_tmp\" 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(
        script,
        "unset _dodot_prof _dodot_prof_dir _dodot_prof_file _dodot_err_file _dodot_err_tmp _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}");
        // Loud-failure wrapper: existence-guarded source, with a
        // dodot-attributed echo on non-zero exit.
        assert!(
            script.contains(&format!(
                "[ -f \"{p}\" ] && {{ . \"{p}\" || echo \"dodot: shell source exited $?: {p}\" >&2; }}",
                p = 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_captures_source_stderr_into_errors_log() {
        // The wrapper must redirect each source's stderr to the per-shell
        // scratch file and append a versioned record (`@@\ttarget\texit`)
        // to the errors.log sibling whenever stderr is non-empty.
        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();

        // Errors-log sibling is derived from the profile-file path.
        assert!(
            script.contains("_dodot_err_file=\"${_dodot_prof_file%.tsv}.errors.log\""),
            "errors-log path must be a sibling of the profile TSV:\n{script}"
        );
        // Versioned header is seeded lazily — only on first stderr from
        // a sourced file, guarded by `[ -f "$_dodot_err_file" ]` so an
        // all-silent shell startup leaves no sidecar on disk.
        assert!(
            script.contains("[ -f \"$_dodot_err_file\" ] || printf '# dodot shell-init errors v1"),
            "errors-log header must be seeded lazily on first stderr:\n{script}"
        );
        // Stderr is redirected to the per-shell scratch file during the source.
        assert!(
            script.contains("2>\"$_dodot_err_tmp\""),
            "source must redirect stderr to scratch file:\n{script}"
        );
        // Truncation before each source so a previous source's stderr
        // doesn't leak into the next record.
        assert!(
            script.contains(": > \"$_dodot_err_tmp\""),
            "scratch file must be truncated before each source:\n{script}"
        );
        // The record header uses the @@ sentinel + tab-separated target/exit.
        assert!(
            script.contains("printf '@@\\t%s\\t%s\\n'"),
            "errors-log records must use @@ header format:\n{script}"
        );
    }

    #[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 profiled_source_initialises_rc_so_missing_file_isnt_reported_as_failure() {
        // Regression: previously the profiled branch was
        //
        //   _dodot_rc=$?  # after `[ -f X ] && . X`
        //
        // which captured the file-test exit (1) when the file was
        // absent — falsely classifying "file missing" as "source
        // exited 1". The fix initialises _dodot_rc to 0 before the
        // attempt, and only updates it inside the `&& { . X; rc=$?; }`
        // group when the source actually ran.
        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();
        // Pre-attempt initialisation present.
        assert!(
            script.contains("_dodot_rc=0;"),
            "profiled branch must seed _dodot_rc=0 before the source attempt:\n{script}"
        );
        // Source is wrapped so the rc only updates when `.` ran.
        assert!(
            script.contains("&& { . "),
            "profiled branch must guard the rc update inside `&& {{ … }}`:\n{script}"
        );
    }

    #[test]
    fn loud_failure_wrapper_present_in_both_modes() {
        // A non-zero exit from a sourced file must surface as a
        // dodot-attributed message on stderr, regardless of whether
        // profiling is on. This is the user-facing breadcrumb that
        // says "the dodot-managed source exited non-zero" alongside
        // the shell's own line-numbered error.
        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();

        // Profiling off: inline OR-echo form.
        let plain = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();
        assert!(
            plain.contains("dodot: shell source exited $?:"),
            "plain script missing loud-failure echo:\n{plain}"
        );

        // Profiling on: timed branch echoes from the elif-empty-stderr
        // arm (silent failure case); the with-stderr arm relies on
        // re-emitting the captured stderr to the user's TTY. Unprofiled
        // fallback uses the OR-echo form like the plain path.
        let timed = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true).unwrap();
        assert!(
            timed.contains("echo \"dodot: shell source exited $_dodot_rc:"),
            "timed script missing silent-failure echo:\n{timed}"
        );
        assert!(
            timed.contains("dodot: shell source exited $?:"),
            "timed script missing fallback-branch echo:\n{timed}"
        );
        // Captured stderr is re-emitted to the user's TTY before being
        // appended to the errors log, so they still see it live.
        assert!(
            timed.contains("cat \"$_dodot_err_tmp\" >&2"),
            "timed script must echo captured stderr to user's TTY:\n{timed}"
        );
    }

    #[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(""), "''");
    }
}