dodot-lib 5.5.0

Core library for dodot dotfiles manager
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! Shell integration — generates `dodot-init.sh`.
//!
//! The script is generated flat and declarative from the actual
//! datastore state, rather than re-discovering the datastore layout at
//! runtime in shell. 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`.
//! `dodot install --write` wires the line below into the user's rc
//! file ([`rc`]), and [`probe`] measures whether a new shell actually
//! runs it. Users can also add it by hand:
//!
//! ```sh
//! [ -f "$HOME/.local/share/dodot/shell/dodot-init.sh" ] && . "$HOME/.local/share/dodot/shell/dodot-init.sh"
//! ```
//!
//! # Activation evidence (shell-hookup.lex §2.1)
//!
//! Every generated script — profiled or not, empty datastore or not —
//! opens with two lines that prove it ran: an `export DODOT_INIT_GEN=`
//! carrying the *generation* the script was written at, and a single
//! truncating redirect of that same generation into the heartbeat
//! marker. `dodot up` and `dodot status` read them back through
//! [`activation`] to tell "no shell has ever loaded dodot" from "this
//! terminal predates your last `up`" from "healthy".
//!
//! The generation is an argument, not something the generator invents:
//! callers that write the script stamp [`activation::current_generation`],
//! and tests pin a value so the emitted script is deterministic.
//!
//! Both lines are on a strict budget — one export, one redirect, no
//! command execution — because they run on every shell start forever.
//! That is also why the heartbeat is a whole-file rewrite of static
//! content: concurrent shell startups race, and last-writer-wins on a
//! truncating redirect is a correct answer to that race, where an
//! append or a read-modify-write would not be.
//!
//! # 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 unwrapped 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 activation;
pub mod probe;
pub mod rc;
pub mod validate;
pub use activation::{ActivationNotice, ActivationState, INIT_GEN_ENV};
pub use probe::ProbePolicy;
pub use rc::ShellEnv;
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
///
/// `generation` is stamped into the activation-evidence block (see the
/// module docs), which is emitted unconditionally — before the
/// early-return for an empty datastore, because "a shell sourced this"
/// is worth knowing even when the script has nothing else to do.
///
/// 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,
    generation: u64,
) -> 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();

    emit_activation_evidence(&mut script, generation, &paths.hookup_heartbeat_path());

    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;
                    }
                    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 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(),
        );
    }

    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();
    }

    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();
    }

    if profiling_active {
        emit_profiling_epilogue(&mut script);
    }

    Ok(script)
}

/// Generate and write the init script to `data_dir/shell/dodot-init.sh`,
/// stamping it with a fresh generation.
///
/// Also creates the heartbeat's parent directory. The emitted redirect
/// can't `mkdir -p` its own way out of a missing directory without
/// spending a process on every shell start, so the write side owns
/// that once per regeneration instead.
///
/// 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 generation = activation::current_generation();
    let script_content = generate_init_script(fs, paths, profiling_enabled, generation)?;
    let script_path = paths.init_script_path();

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

    Ok(script_path)
}

// ── Activation evidence emitter ──────────────────────────────────────

/// Emit the two evidence lines (shell-hookup.lex §2.1).
///
/// - `export DODOT_INIT_GEN=<generation>` — free to read back from any
///   dodot process that the shell later spawns.
/// - `echo <generation> > <heartbeat> 2>/dev/null || :` — one builtin
///   and one truncating redirect. `2>/dev/null` keeps an unwritable
///   data dir from spraying errors across every shell start, and the
///   `|| :` keeps the failed redirect's non-zero status from aborting
///   an rc file that runs under `set -e`.
fn emit_activation_evidence(script: &mut String, generation: u64, heartbeat_path: &Path) {
    let heartbeat = sh_quote(&heartbeat_path.display().to_string());
    writeln!(script, "# ── dodot activation evidence ──").unwrap();
    writeln!(script, "export {}={generation}", activation::INIT_GEN_ENV).unwrap();
    writeln!(script, "echo {generation} > {heartbeat} 2>/dev/null || :").unwrap();
    writeln!(script).unwrap();
}

// ── 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;

    /// Pinned generation so emitted scripts are deterministic in
    /// tests; production stamps `activation::current_generation()`.
    const TEST_GEN: u64 = 1_755_200_000;

    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, TEST_GEN).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"));
        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, TEST_GEN).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, TEST_GEN).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);

        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();

        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, TEST_GEN).unwrap();

        assert!(script.contains("# [git]"), "script:\n{script}");
        assert!(script.contains("# [vim]"), "script:\n{script}");
        assert!(script.contains("export PATH="), "script:\n{script}");
        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"));

        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);

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

        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, TEST_GEN).unwrap();
        assert!(script2.contains("aliases.sh"));

        ds.remove_state("vim", "shell").unwrap();

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

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

        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, TEST_GEN).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, TEST_GEN).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, TEST_GEN).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, TEST_GEN).unwrap();

        assert!(script.contains("BASH_VERSION"));
        assert!(script.contains("ZSH_VERSION"));
        assert!(script.contains("EPOCHREALTIME"));
        assert!(script.contains(env.paths.probes_shell_init_dir().to_str().unwrap()));
        assert!(script.contains("$$"));
        assert!(script.contains("RANDOM"));
        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, TEST_GEN).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, TEST_GEN).unwrap();

        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}"
        );
        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}"
        );
        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, TEST_GEN).unwrap();
        assert!(script.contains("# end_t"));
        assert!(script.contains("unset _dodot_prof"));
        assert!(script.contains("_dodot_prof_file"));
    }

    #[test]
    fn profiling_enabled_with_empty_datastore_skips_preamble() {
        let env = TempEnvironment::builder().build();
        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN).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() {
        // A missing file is not a source failure: initialize rc to zero
        // and only update it when the source command actually runs.
        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, TEST_GEN).unwrap();
        assert!(
            script.contains("_dodot_rc=0;"),
            "profiled branch must seed _dodot_rc=0 before the source attempt:\n{script}"
        );
        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, TEST_GEN).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, TEST_GEN).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}"
        );
    }

    // ── Activation evidence (shell-hookup.lex §2.1) ─────────────────

    /// Every shape of generated script must carry both evidence lines:
    /// the evidence is unconditional, which is exactly what separates
    /// it from the opt-in profiling instrumentation.
    #[test]
    fn evidence_is_emitted_unconditionally_in_every_script_shape() {
        let empty = TempEnvironment::builder().build();
        let populated = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();
        let ds = make_datastore(&populated);
        ds.create_data_link(
            "vim",
            "shell",
            &populated.dotfiles_root.join("vim/aliases.sh"),
        )
        .unwrap();

        let shapes = [
            ("empty datastore", &empty, false),
            ("empty datastore, profiled", &empty, true),
            ("populated", &populated, false),
            ("populated, profiled", &populated, true),
        ];
        for (label, env, profiling) in shapes {
            let script =
                generate_init_script(env.fs.as_ref(), env.paths.as_ref(), profiling, TEST_GEN)
                    .unwrap();
            assert!(
                script.contains(&format!("export DODOT_INIT_GEN={TEST_GEN}")),
                "{label}: missing generation stamp:\n{script}"
            );
            assert!(
                script.contains(&format!(
                    "echo {TEST_GEN} > '{}' 2>/dev/null || :",
                    env.paths.hookup_heartbeat_path().display()
                )),
                "{label}: missing heartbeat write:\n{script}"
            );
            assert_eq!(
                activation::parse_script_generation(&script),
                Some(TEST_GEN),
                "{label}: generation must round-trip out of the script"
            );
        }
    }

    /// The hot-path budget: one export plus one redirect, and nothing
    /// that costs a process. A `mkdir -p` or a `dodot` call here would
    /// be paid on every shell start, forever.
    #[test]
    fn evidence_costs_one_export_and_one_redirect() {
        let env = TempEnvironment::builder().build();
        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN).unwrap();

        let evidence: Vec<&str> = script
            .lines()
            .filter(|l| l.contains("DODOT_INIT_GEN") || l.contains("heartbeat"))
            .collect();
        assert_eq!(evidence.len(), 2, "evidence block: {evidence:?}");
        assert!(evidence[0].starts_with("export DODOT_INIT_GEN="));
        assert!(evidence[1].starts_with("echo "));
        for forbidden in ["mkdir", "dodot ", "date", "$(", "`"] {
            assert!(
                !evidence.iter().any(|l| l.contains(forbidden)),
                "evidence must not run `{forbidden}`: {evidence:?}"
            );
        }
    }

    /// `write_init_script` owns the heartbeat directory so the emitted
    /// redirect never has to create it, and stamps a real generation
    /// that reads back through the same parser `status` uses.
    #[test]
    fn write_init_script_stamps_generation_and_creates_heartbeat_dir() {
        let env = TempEnvironment::builder().build();

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

        assert!(
            env.fs.is_dir(&env.paths.probes_hookup_dir()),
            "heartbeat dir must exist before any shell writes the marker"
        );
        let gen = activation::read_script_generation(env.fs.as_ref(), env.paths.as_ref())
            .expect("written script must carry a generation");
        assert!(gen > 1_700_000_000, "generation should be a unix ts: {gen}");
        let content = env.fs.read_to_string(&path).unwrap();
        assert!(content.contains(&format!("export DODOT_INIT_GEN={gen}")));
        // No shell has run yet, so there is no heartbeat — that
        // absence is the "never activated" signal.
        assert!(!env.fs.exists(&env.paths.hookup_heartbeat_path()));
    }

    /// Portability leg: the emitted script must parse under POSIX sh,
    /// bash, and zsh — the shells dodot generates init for.
    #[test]
    fn generated_script_parses_in_sh_bash_and_zsh() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .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();

        for profiling in [false, true] {
            let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), profiling).unwrap();
            for shell in ["sh", "bash", "zsh"] {
                let out = std::process::Command::new(shell)
                    .arg("-n")
                    .arg(&path)
                    .output();
                let Ok(out) = out else {
                    continue; // interpreter not installed on this host
                };
                assert!(
                    out.status.success(),
                    "{shell} -n rejected the generated script (profiling={profiling}): {}",
                    String::from_utf8_lossy(&out.stderr)
                );
            }
        }
    }

    /// The evidence is only worth anything if sourcing the script
    /// actually leaves it: run the real thing under `sh` and read both
    /// signals back.
    #[test]
    fn sourcing_the_script_exports_the_stamp_and_writes_the_heartbeat() {
        let env = TempEnvironment::builder().build();
        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();
        let gen = activation::read_script_generation(env.fs.as_ref(), env.paths.as_ref()).unwrap();

        let out = std::process::Command::new("sh")
            .arg("-c")
            .arg(format!(
                ". '{}'; printf '%s' \"$DODOT_INIT_GEN\"",
                path.display()
            ))
            .env_remove(activation::INIT_GEN_ENV)
            .output()
            .expect("sh is required to run dodot's own init script");
        assert!(out.status.success(), "sourcing failed: {out:?}");
        assert_eq!(String::from_utf8_lossy(&out.stdout), gen.to_string());
        assert_eq!(
            activation::read_heartbeat(env.fs.as_ref(), env.paths.as_ref()),
            Some(gen),
            "sourcing must leave a heartbeat at the script's generation"
        );
    }

    /// Concurrency: many shells starting at once each truncate the
    /// same marker with the same static content, so the marker is
    /// always exactly one generation — never interleaved bytes.
    #[test]
    fn concurrent_sources_leave_an_intact_heartbeat() {
        let env = TempEnvironment::builder().build();
        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false).unwrap();
        let gen = activation::read_script_generation(env.fs.as_ref(), env.paths.as_ref()).unwrap();

        let children: Vec<_> = (0..8)
            .filter_map(|_| {
                std::process::Command::new("sh")
                    .arg("-c")
                    .arg(format!(". '{}'", path.display()))
                    .spawn()
                    .ok()
            })
            .collect();
        for mut child in children {
            let _ = child.wait();
        }

        assert_eq!(
            activation::read_heartbeat(env.fs.as_ref(), env.paths.as_ref()),
            Some(gen)
        );
    }

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