1use std::path::{Path, PathBuf};
2
3use crate::{dropin, marked_block};
4
5const MARKER_START: &str = "# >>> lean-ctx shell hook >>>";
6const MARKER_END: &str = "# <<< lean-ctx shell hook <<<";
7const ALIAS_START: &str = "# >>> lean-ctx agent aliases >>>";
8const ALIAS_END: &str = "# <<< lean-ctx agent aliases <<<";
9
10const DROPIN_ZSH: &str = "00-lean-ctx.zsh";
14const DROPIN_SH: &str = "00-lean-ctx.sh";
15
16const KNOWN_AGENT_ENV_VARS: &[&str] = &[
17 "LEAN_CTX_AGENT",
18 "CLAUDECODE",
19 "CODEX_CLI_SESSION",
20 "GEMINI_SESSION",
21];
22
23const AGENT_ALIASES: &[(&str, &str)] = &[
24 ("claude", "claude"),
25 ("codex", "codex"),
26 ("gemini", "gemini"),
27];
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Style {
37 Inline,
39 DropIn,
42 #[default]
44 Auto,
45}
46
47#[derive(Debug, Clone, Copy)]
51struct Slot {
52 rc_file: &'static str,
53 dropin_dir: &'static str,
54 dropin_file: &'static str,
55 marker_start: &'static str,
56 marker_end: &'static str,
57}
58
59const SLOT_ZSHENV: Slot = Slot {
60 rc_file: ".zshenv",
61 dropin_dir: ".zshenv.d",
62 dropin_file: DROPIN_ZSH,
63 marker_start: MARKER_START,
64 marker_end: MARKER_END,
65};
66
67const SLOT_BASHENV: Slot = Slot {
68 rc_file: ".bashenv",
69 dropin_dir: ".bashenv.d",
70 dropin_file: DROPIN_SH,
71 marker_start: MARKER_START,
72 marker_end: MARKER_END,
73};
74
75const SLOT_ZSHRC: Slot = Slot {
76 rc_file: ".zshrc",
77 dropin_dir: ".zshrc.d",
78 dropin_file: DROPIN_ZSH,
79 marker_start: ALIAS_START,
80 marker_end: ALIAS_END,
81};
82
83const SLOT_BASHRC: Slot = Slot {
84 rc_file: ".bashrc",
85 dropin_dir: ".bashrc.d",
86 dropin_file: DROPIN_SH,
87 marker_start: ALIAS_START,
88 marker_end: ALIAS_END,
89};
90
91enum InstallTarget {
93 Marked {
94 path: PathBuf,
95 start: &'static str,
96 end: &'static str,
97 },
98 DropIn {
99 dir: PathBuf,
100 filename: &'static str,
101 },
102}
103
104impl InstallTarget {
105 fn upsert(&self, content: &str, quiet: bool, label: &str) {
106 match self {
107 Self::Marked { path, start, end } => {
108 marked_block::upsert(path, start, end, content, quiet, label);
109 }
110 Self::DropIn { dir, filename } => dropin::write(dir, filename, content, quiet, label),
111 }
112 }
113}
114
115fn pick_target(home: &Path, slot: &Slot, style: Style) -> InstallTarget {
117 let inline = InstallTarget::Marked {
118 path: home.join(slot.rc_file),
119 start: slot.marker_start,
120 end: slot.marker_end,
121 };
122 match style {
123 Style::Inline => inline,
124 Style::DropIn | Style::Auto => match dropin::detect(home, slot.rc_file, slot.dropin_dir) {
129 Some(dir) => InstallTarget::DropIn {
130 dir,
131 filename: slot.dropin_file,
132 },
133 None => inline,
134 },
135 }
136}
137
138struct BackupStamp(String);
151
152impl BackupStamp {
153 fn now() -> Self {
156 Self::at(chrono::Utc::now())
157 }
158
159 fn at(stamp: chrono::DateTime<chrono::Utc>) -> Self {
163 Self(stamp.format("%Y%m%dT%H%M%SZ").to_string())
164 }
165
166 fn backup_path_for(&self, path: &Path) -> Option<PathBuf> {
168 let file_name = path.file_name().and_then(|n| n.to_str())?;
169 Some(path.with_file_name(format!("{file_name}.lean-ctx-{}.bak", self.0)))
170 }
171}
172
173fn save_migration_backup(path: &Path, quiet: bool, stamp: &BackupStamp) {
195 if !path.exists() {
196 return;
197 }
198 let Some(bak) = stamp.backup_path_for(path) else {
199 return;
200 };
201 match std::fs::copy(path, &bak) {
202 Ok(_) => {
203 if !quiet {
204 eprintln!(" Backup: {} -> {}", path.display(), bak.display());
205 }
206 }
207 Err(e) => {
208 tracing::warn!("Failed to back up {}: {e}", path.display());
209 }
210 }
211}
212
213fn strip_other_style(
226 home: &Path,
227 slot: &Slot,
228 target: &InstallTarget,
229 quiet: bool,
230 label: &str,
231 stamp: &BackupStamp,
232) {
233 match target {
234 InstallTarget::Marked { .. } => {
235 let dropin_dir = home.join(slot.dropin_dir);
237 let dropin_path = dropin_dir.join(slot.dropin_file);
238 if dropin_path.exists() {
239 save_migration_backup(&dropin_path, quiet, stamp);
243 dropin::remove(&dropin_dir, slot.dropin_file, quiet, label);
244 }
245 }
246 InstallTarget::DropIn { .. } => {
247 let rc_path = home.join(slot.rc_file);
252 if let Ok(existing) = std::fs::read_to_string(&rc_path) {
253 if existing.contains(slot.marker_start) {
254 save_migration_backup(&rc_path, quiet, stamp);
255 }
256 }
257 marked_block::remove_from_file(
258 &rc_path,
259 slot.marker_start,
260 slot.marker_end,
261 quiet,
262 label,
263 );
264 }
265 }
266}
267
268pub fn install_all(quiet: bool) {
272 install_all_with_style(quiet, Style::Auto);
273}
274
275pub fn install_all_with_style(quiet: bool, style: Style) {
282 let Some(home) = dirs::home_dir() else {
283 tracing::error!("Cannot resolve home directory");
284 return;
285 };
286
287 let stamp = BackupStamp::now();
288 install_zshenv(&home, quiet, style, &stamp);
289 install_bashenv(&home, quiet, style, &stamp);
290 install_aliases(&home, quiet, style, &stamp);
291}
292
293pub fn uninstall_all(quiet: bool) {
294 let Some(home) = dirs::home_dir() else { return };
295
296 let slots: &[(Slot, &str)] = &[
299 (SLOT_ZSHENV, "shell hook for ~/.zshenv"),
300 (SLOT_BASHENV, "shell hook for ~/.bashenv"),
301 (SLOT_ZSHRC, "agent aliases for ~/.zshrc"),
302 (SLOT_BASHRC, "agent aliases for ~/.bashrc"),
303 ];
304
305 for (slot, label) in slots {
306 marked_block::remove_from_file(
307 &home.join(slot.rc_file),
308 slot.marker_start,
309 slot.marker_end,
310 quiet,
311 label,
312 );
313 let dir_path = home.join(slot.dropin_dir);
314 if dir_path.exists() {
315 dropin::remove(&dir_path, slot.dropin_file, quiet, label);
316 }
317 }
318}
319
320fn install_zshenv(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
321 let env_check = build_env_check();
322 let hook = format!(
323 r#"{MARKER_START}
324if [[ -z "$LEAN_CTX_ACTIVE" && -n "$ZSH_EXECUTION_STRING" ]] && command -v lean-ctx &>/dev/null; then
325 if {env_check}; then
326 export LEAN_CTX_ACTIVE=1
327 exec lean-ctx -c "$ZSH_EXECUTION_STRING"
328 fi
329fi
330{MARKER_END}"#
331 );
332
333 let label = "shell hook in ~/.zshenv";
334 let target = pick_target(home, &SLOT_ZSHENV, style);
335 strip_other_style(home, &SLOT_ZSHENV, &target, quiet, label, stamp);
336 target.upsert(&hook, quiet, label);
337}
338
339fn install_bashenv(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
340 let env_check = build_env_check();
341 let hook = format!(
342 r#"{MARKER_START}
343if [[ -z "$LEAN_CTX_ACTIVE" && -n "$BASH_EXECUTION_STRING" ]] && command -v lean-ctx &>/dev/null; then
344 if {env_check}; then
345 export LEAN_CTX_ACTIVE=1
346 exec lean-ctx -c "$BASH_EXECUTION_STRING"
347 fi
348fi
349{MARKER_END}"#
350 );
351
352 let label = "shell hook in ~/.bashenv";
353 let target = pick_target(home, &SLOT_BASHENV, style);
354 strip_other_style(home, &SLOT_BASHENV, &target, quiet, label, stamp);
355 target.upsert(&hook, quiet, label);
356}
357
358fn install_aliases(home: &Path, quiet: bool, style: Style, stamp: &BackupStamp) {
359 let mut lines = Vec::new();
360 lines.push(ALIAS_START.to_string());
361 for (alias_name, bin_name) in AGENT_ALIASES {
362 lines.push(format!(
363 "alias {alias_name}='LEAN_CTX_AGENT=1 BASH_ENV=\"$HOME/.bashenv\" {bin_name}'"
364 ));
365 }
366 lines.push(ALIAS_END.to_string());
367 let block = lines.join("\n");
368
369 for slot in &[SLOT_ZSHRC, SLOT_BASHRC] {
370 if !home.join(slot.rc_file).exists() {
373 continue;
374 }
375 let label = format!("agent aliases in ~/{}", slot.rc_file);
376 let target = pick_target(home, slot, style);
377 strip_other_style(home, slot, &target, quiet, &label, stamp);
378 target.upsert(&block, quiet, &label);
379 }
380}
381
382fn build_env_check() -> String {
383 let checks: Vec<String> = KNOWN_AGENT_ENV_VARS
384 .iter()
385 .map(|v| format!("-n \"${v}\""))
386 .collect();
387 format!("[[ {} ]]", checks.join(" || "))
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 fn test_stamp() -> BackupStamp {
398 BackupStamp::at(
399 chrono::DateTime::parse_from_rfc3339("2026-05-11T20:38:45Z")
400 .unwrap()
401 .with_timezone(&chrono::Utc),
402 )
403 }
404
405 #[test]
406 fn env_check_format() {
407 let check = build_env_check();
408 assert!(check.contains("LEAN_CTX_AGENT"));
409 assert!(check.contains("CLAUDECODE"));
410 assert!(check.contains("||"));
411 }
412
413 #[test]
414 fn pick_target_inline_when_forced() {
415 let tmp = tempfile::tempdir().unwrap();
416 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
418 std::fs::write(
419 tmp.path().join(".zshenv"),
420 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
421 )
422 .unwrap();
423 let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Inline);
424 assert!(matches!(t, InstallTarget::Marked { .. }));
425 }
426
427 #[test]
428 fn pick_target_dropin_when_detected_under_auto() {
429 let tmp = tempfile::tempdir().unwrap();
430 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
431 std::fs::write(
432 tmp.path().join(".zshenv"),
433 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
434 )
435 .unwrap();
436 let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Auto);
437 assert!(matches!(t, InstallTarget::DropIn { .. }));
438 }
439
440 #[test]
441 fn pick_target_inline_under_auto_when_no_dropin() {
442 let tmp = tempfile::tempdir().unwrap();
443 std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
444 let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::Auto);
445 assert!(matches!(t, InstallTarget::Marked { .. }));
446 }
447
448 #[test]
449 fn pick_target_dropin_falls_back_to_inline_when_no_directory() {
450 let tmp = tempfile::tempdir().unwrap();
453 std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
454 let t = pick_target(tmp.path(), &SLOT_ZSHENV, Style::DropIn);
455 assert!(matches!(t, InstallTarget::Marked { .. }));
456 }
457
458 #[test]
459 fn install_zshenv_writes_inline_block() {
460 let tmp = tempfile::tempdir().unwrap();
461 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
462 let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
463 assert!(body.contains(MARKER_START));
464 assert!(body.contains(MARKER_END));
465 assert!(body.contains("ZSH_EXECUTION_STRING"));
466 }
467
468 #[test]
469 fn install_zshenv_writes_dropin_when_loop_present() {
470 let tmp = tempfile::tempdir().unwrap();
471 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
472 std::fs::write(
473 tmp.path().join(".zshenv"),
474 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
475 )
476 .unwrap();
477 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
478
479 let dropin_file = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
480 assert!(dropin_file.exists(), "expected drop-in file");
481 let dropin_body = std::fs::read_to_string(&dropin_file).unwrap();
482 assert!(dropin_body.contains("ZSH_EXECUTION_STRING"));
483
484 let zshenv_body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
485 assert!(
486 !zshenv_body.contains(MARKER_START),
487 "drop-in install must not also leave the inline block"
488 );
489 }
490
491 fn find_migration_backups(path: &Path) -> Vec<PathBuf> {
494 let Some(parent) = path.parent() else {
495 return Vec::new();
496 };
497 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
498 return Vec::new();
499 };
500 let prefix = format!("{name}.lean-ctx-");
501 let mut out: Vec<PathBuf> = std::fs::read_dir(parent)
502 .into_iter()
503 .flatten()
504 .flatten()
505 .map(|e| e.path())
506 .filter(|p| {
507 p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
508 n.starts_with(&prefix)
509 && std::path::Path::new(n)
510 .extension()
511 .is_some_and(|ext| ext.eq_ignore_ascii_case("bak"))
512 })
513 })
514 .collect();
515 out.sort();
516 out
517 }
518
519 #[test]
520 fn migration_inline_to_dropin_preserves_hand_edits_via_backup() {
521 let tmp = tempfile::tempdir().unwrap();
522 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
523 let edited_zshenv = format!(
526 "export PATH=/usr/bin\n\
527 \n\
528 {MARKER_START}\n\
529 # USER CUSTOM: bump zsh history size for this workstation\n\
530 export HISTSIZE=99999\n\
531 # original lean-ctx hook content lived here\n\
532 {MARKER_END}\n\
533 \n\
534 for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
535 );
536 std::fs::write(tmp.path().join(".zshenv"), &edited_zshenv).unwrap();
537
538 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
539
540 let baks = find_migration_backups(&tmp.path().join(".zshenv"));
542 assert_eq!(baks.len(), 1, "expected one timestamped backup");
543 let bak_body = std::fs::read_to_string(&baks[0]).unwrap();
544 assert_eq!(bak_body, edited_zshenv);
545 assert!(bak_body.contains("USER CUSTOM"));
546 assert!(bak_body.contains("HISTSIZE=99999"));
547 }
548
549 #[test]
550 fn migration_dropin_to_inline_preserves_hand_edits_via_backup() {
551 let tmp = tempfile::tempdir().unwrap();
552 let dropin_dir = tmp.path().join(".zshenv.d");
553 std::fs::create_dir_all(&dropin_dir).unwrap();
554 let edited_dropin = "# USER CUSTOM addition to lean-ctx drop-in\nexport FAVOURITE_EDITOR=helix\n# canonical lean-ctx content would follow\n";
556 std::fs::write(dropin_dir.join(DROPIN_ZSH), edited_dropin).unwrap();
557 std::fs::write(tmp.path().join(".zshenv"), "# plain zshenv\n").unwrap();
560
561 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
562
563 let baks = find_migration_backups(&dropin_dir.join(DROPIN_ZSH));
564 assert_eq!(baks.len(), 1, "expected one timestamped backup");
565 let bak_body = std::fs::read_to_string(&baks[0]).unwrap();
566 assert_eq!(bak_body, edited_dropin);
567 assert!(bak_body.contains("USER CUSTOM"));
568 assert!(!dropin_dir.join(DROPIN_ZSH).exists());
570 let zshenv = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
571 assert!(zshenv.contains(MARKER_START));
572 }
573
574 #[test]
575 fn migration_skips_backup_when_no_prior_block_exists() {
576 let tmp = tempfile::tempdir().unwrap();
579 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
580 std::fs::write(
581 tmp.path().join(".zshenv"),
582 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
583 )
584 .unwrap();
585
586 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
587
588 assert!(
589 find_migration_backups(&tmp.path().join(".zshenv")).is_empty(),
590 "clean install should not create a .bak file"
591 );
592 }
593
594 #[test]
595 fn idempotent_dropin_reinstall_does_not_create_backup() {
596 let tmp = tempfile::tempdir().unwrap();
601 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
602 std::fs::write(
603 tmp.path().join(".zshenv"),
604 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
605 )
606 .unwrap();
607
608 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
609 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
610
611 assert!(find_migration_backups(&tmp.path().join(".zshenv")).is_empty());
612 }
613
614 #[test]
615 fn backup_filename_handles_dotfile_correctly() {
616 let tmp = tempfile::tempdir().unwrap();
620 std::fs::write(tmp.path().join(".zshenv"), "content\n").unwrap();
621 save_migration_backup(&tmp.path().join(".zshenv"), true, &test_stamp());
622 let baks = find_migration_backups(&tmp.path().join(".zshenv"));
623 assert_eq!(baks.len(), 1);
624 let name = baks[0].file_name().unwrap().to_str().unwrap();
627 assert!(name.starts_with(".zshenv.lean-ctx-"), "got: {name}");
628 assert!(std::path::Path::new(name)
629 .extension()
630 .is_some_and(|ext| ext.eq_ignore_ascii_case("bak")));
631 let stamp = name
633 .trim_start_matches(".zshenv.lean-ctx-")
634 .trim_end_matches(".bak");
635 assert_eq!(stamp.len(), 16, "stamp should be YYYYMMDDTHHMMSSZ: {stamp}");
636 assert!(stamp.contains('T'));
637 assert!(stamp.ends_with('Z'));
638 }
639
640 #[test]
641 fn repeated_migrations_never_clobber_prior_backups() {
642 let stamp_first = BackupStamp::at(
647 chrono::DateTime::parse_from_rfc3339("2026-05-11T20:38:45Z")
648 .unwrap()
649 .with_timezone(&chrono::Utc),
650 );
651 let stamp_later = BackupStamp::at(
652 chrono::DateTime::parse_from_rfc3339("2026-05-12T09:00:00Z")
653 .unwrap()
654 .with_timezone(&chrono::Utc),
655 );
656 let tmp = tempfile::tempdir().unwrap();
657 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
658
659 let with_block_v1 = format!(
660 "{MARKER_START}\n# first-era custom content\n{MARKER_END}\n\nfor f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
661 );
662 std::fs::write(tmp.path().join(".zshenv"), &with_block_v1).unwrap();
663 install_zshenv(tmp.path(), true, Style::Auto, &stamp_first);
664 let baks_after_first = find_migration_backups(&tmp.path().join(".zshenv"));
665 assert_eq!(baks_after_first.len(), 1);
666
667 let with_block_v2 = format!(
670 "{}{MARKER_START}\n# second-era custom content\n{MARKER_END}\n",
671 std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap(),
672 );
673 std::fs::write(tmp.path().join(".zshenv"), &with_block_v2).unwrap();
674 install_zshenv(tmp.path(), true, Style::Auto, &stamp_later);
675 let baks_after_second = find_migration_backups(&tmp.path().join(".zshenv"));
676
677 assert_eq!(
678 baks_after_second.len(),
679 2,
680 "second migration should leave a second backup, not overwrite"
681 );
682 assert_eq!(baks_after_second[0], baks_after_first[0]);
684 let first_body = std::fs::read_to_string(&baks_after_second[0]).unwrap();
685 let second_body = std::fs::read_to_string(&baks_after_second[1]).unwrap();
686 assert!(first_body.contains("first-era custom"));
687 assert!(second_body.contains("second-era custom"));
688 }
689
690 #[test]
691 fn install_migrates_inline_to_dropin() {
692 let tmp = tempfile::tempdir().unwrap();
693 std::fs::write(
695 tmp.path().join(".zshenv"),
696 format!(
697 "export PATH=/usr/bin\n\n{MARKER_START}\n# old hook\n{MARKER_END}\n\nfor f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
698 ),
699 )
700 .unwrap();
701 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
702
703 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
704
705 let zshenv_body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
706 assert!(
707 !zshenv_body.contains(MARKER_START),
708 "old inline block should be stripped after migration"
709 );
710 assert!(
711 zshenv_body.contains(".zshenv.d"),
712 "source loop must be preserved"
713 );
714 let dropin_file = tmp.path().join(".zshenv.d").join(DROPIN_ZSH);
715 assert!(dropin_file.exists(), "new drop-in file should be present");
716 }
717
718 #[test]
719 fn install_migrates_dropin_to_inline() {
720 let tmp = tempfile::tempdir().unwrap();
721 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
724 std::fs::write(
725 tmp.path().join(".zshenv.d").join(DROPIN_ZSH),
726 "# stale lean-ctx drop-in\n",
727 )
728 .unwrap();
729 std::fs::write(tmp.path().join(".zshenv"), "export PATH=/usr/bin\n").unwrap();
730
731 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
732
733 assert!(
734 !tmp.path().join(".zshenv.d").join(DROPIN_ZSH).exists(),
735 "drop-in file should be removed when installing inline"
736 );
737 let body = std::fs::read_to_string(tmp.path().join(".zshenv")).unwrap();
738 assert!(body.contains(MARKER_START));
739 }
740
741 #[test]
742 fn install_is_idempotent_in_dropin_mode() {
743 let tmp = tempfile::tempdir().unwrap();
744 std::fs::create_dir_all(tmp.path().join(".zshenv.d")).unwrap();
745 std::fs::write(
746 tmp.path().join(".zshenv"),
747 "for f in $HOME/.zshenv.d/*.zsh; do source $f; done\n",
748 )
749 .unwrap();
750
751 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
752 let after_first = std::fs::read(tmp.path().join(".zshenv.d").join(DROPIN_ZSH)).unwrap();
753
754 install_zshenv(tmp.path(), true, Style::Auto, &test_stamp());
755 let after_second = std::fs::read(tmp.path().join(".zshenv.d").join(DROPIN_ZSH)).unwrap();
756
757 assert_eq!(after_first, after_second);
758 }
759
760 #[test]
761 fn install_is_idempotent_in_inline_mode() {
762 let tmp = tempfile::tempdir().unwrap();
763 std::fs::write(tmp.path().join(".zshenv"), "# top\n").unwrap();
764
765 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
766 let after_first = std::fs::read(tmp.path().join(".zshenv")).unwrap();
767
768 install_zshenv(tmp.path(), true, Style::Inline, &test_stamp());
769 let after_second = std::fs::read(tmp.path().join(".zshenv")).unwrap();
770
771 assert_eq!(after_first, after_second);
772 }
773
774 #[test]
775 fn install_aliases_skips_when_rc_missing() {
776 let tmp = tempfile::tempdir().unwrap();
777 install_aliases(tmp.path(), true, Style::Auto, &test_stamp());
779 assert!(!tmp.path().join(".zshrc").exists());
780 assert!(!tmp.path().join(".bashrc").exists());
781 }
782
783 #[test]
784 fn install_aliases_writes_dropin_when_zshrc_d_configured() {
785 let tmp = tempfile::tempdir().unwrap();
786 std::fs::create_dir_all(tmp.path().join(".zshrc.d")).unwrap();
787 std::fs::write(
788 tmp.path().join(".zshrc"),
789 "for f in $HOME/.zshrc.d/*.zsh; do source $f; done\n",
790 )
791 .unwrap();
792
793 install_aliases(tmp.path(), true, Style::Auto, &test_stamp());
794
795 let dropin_file = tmp.path().join(".zshrc.d").join(DROPIN_ZSH);
796 assert!(dropin_file.exists());
797 let body = std::fs::read_to_string(&dropin_file).unwrap();
798 assert!(body.contains("LEAN_CTX_AGENT=1"));
799 }
800}