1use super::{
9 config_artifact_dir, generate_hook_fish, generate_hook_posix, generate_hook_powershell,
10 hook_binary_for_shell, write_env_sh_for_containers,
11};
12
13fn lc_shim_dirs(
21 current_exe: Option<&std::path::Path>,
22 path_dirs: &[std::path::PathBuf],
23 home: Option<&std::path::Path>,
24) -> Vec<std::path::PathBuf> {
25 use crate::core::portable_binary::{dir_on_path, launchers_on_path};
26
27 let exe_dir = current_exe
28 .and_then(std::path::Path::parent)
29 .filter(|d| dir_on_path(d, path_dirs))
30 .map(std::path::Path::to_path_buf);
31 let launcher_dirs = launchers_on_path(path_dirs)
32 .into_iter()
33 .filter_map(|p| p.parent().map(std::path::Path::to_path_buf));
34 let user_bin = home
35 .map(|h| h.join(".local").join("bin"))
36 .filter(|d| dir_on_path(d, path_dirs));
37
38 let mut dirs: Vec<std::path::PathBuf> = Vec::new();
39 for dir in exe_dir.into_iter().chain(launcher_dirs).chain(user_bin) {
40 if !dirs.contains(&dir) {
41 dirs.push(dir);
42 }
43 }
44 dirs
45}
46
47fn shim_script(name: &str, binary: &str, flag: &str) -> String {
52 format!(
53 "#!/bin/sh\n\
54 # lean-ctx PATH fallback for the `{name}` shell function -- DO NOT EDIT.\n\
55 # Shell resolves alias -> function -> PATH, so the hook's shell function\n\
56 # shadows this whenever it is loaded (identical behavior there). This runs\n\
57 # only where the function is absent: non-interactive subshells, scripts,\n\
58 # xargs/find -exec, a pipeline's outer shell, and agent harnesses that\n\
59 # snapshot+replay the shell and drop the function but keep the aliases\n\
60 # that call it. Without it those contexts fail `{name}: command not found`.\n\
61 if [ -n \"${{LEAN_CTX_DISABLED:-}}\" ] || [ -n \"${{LEAN_CTX_NO_HOOK:-}}\" ]; then\n\
62 \texec \"$@\"\n\
63 fi\n\
64 if [ ! -t 1 ] && [ -z \"${{LEAN_CTX_AGENT:-}}\" ] && [ -z \"${{CURSOR_AGENT:-}}\" ] && [ -z \"${{CODEX_CLI_SESSION:-}}\" ] \\\n\
65 \t&& [ -z \"${{CLAUDECODE:-}}\" ] && [ -z \"${{CODEBUDDY:-}}\" ] && [ -z \"${{GEMINI_SESSION:-}}\" ]; then\n\
66 \texec \"$@\"\n\
67 fi\n\
68 '{binary}' {flag} \"$@\"\n\
69 _lc_rc=$?\n\
70 if [ \"$_lc_rc\" -eq 127 ] || [ \"$_lc_rc\" -eq 126 ]; then\n\
71 \texec \"$@\"\n\
72 fi\n\
73 exit \"$_lc_rc\"\n"
74 )
75}
76
77fn write_lc_path_shims_in(dir: &std::path::Path, binary: &str) -> bool {
80 let mut ok = true;
81 for (name, flag) in [("_lc", "-t"), ("_lc_compress", "-c")] {
82 let path = dir.join(name);
83 let written = std::fs::write(&path, shim_script(name, binary, flag));
84 if let Err(e) = &written {
85 tracing::debug!("could not write shim {}: {e}", path.display());
86 ok = false;
87 }
88 #[cfg(unix)]
89 if written.is_ok() {
90 use std::os::unix::fs::PermissionsExt;
91 let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755));
92 }
93 }
94 ok
95}
96
97pub(super) fn write_lc_path_shims(binary: &str) {
103 let current_exe = std::env::current_exe().ok();
104 let candidates = lc_shim_dirs(
105 current_exe.as_deref(),
106 &crate::core::portable_binary::path_dirs(),
107 dirs::home_dir().as_deref(),
108 );
109 if candidates
110 .iter()
111 .any(|dir| write_lc_path_shims_in(dir, binary))
112 {
113 return;
114 }
115 tracing::warn!(
116 "could not write the _lc/_lc_compress shims to a PATH directory; \
117 aliases fail where the shell function is unavailable"
118 );
119}
120
121pub fn refresh_installed_shell_hooks() {
131 if crate::core::config::Config::load().shell_hook_disabled_effective() {
132 return;
133 }
134 let Some(dir) = config_artifact_dir() else {
135 return;
136 };
137 let binary = crate::core::portable_binary::stable_shell_binary(
138 &crate::core::portable_binary::resolve_portable_binary(),
139 );
140 if refresh_shell_hooks_in(&dir, &binary) {
141 let bash_binary = hook_binary_for_shell("bash", &binary);
142 if dir.join("env.sh").exists() {
143 write_env_sh_for_containers(&generate_hook_posix(&bash_binary));
144 }
145 write_lc_path_shims(&bash_binary);
146 }
147}
148
149fn refresh_shell_hooks_in(dir: &std::path::Path, binary: &str) -> bool {
152 let mut posix_refreshed = false;
153 for (ext, shell) in [
154 ("bash", "bash"),
155 ("zsh", "zsh"),
156 ("fish", "fish"),
157 ("ps1", "powershell"),
158 ] {
159 let path = dir.join(format!("shell-hook.{ext}"));
160 let Ok(current) = std::fs::read_to_string(&path) else {
161 continue;
162 };
163 let shell_binary = hook_binary_for_shell(shell, binary);
164 let fresh = match shell {
165 "fish" => generate_hook_fish(&shell_binary),
166 "powershell" => generate_hook_powershell(&shell_binary),
167 _ => generate_hook_posix(&shell_binary),
168 };
169 if current == fresh {
170 continue;
171 }
172 match std::fs::write(&path, fresh) {
173 Ok(()) => {
174 tracing::info!("refreshed stale shell hook {}", path.display());
175 posix_refreshed |= matches!(shell, "bash" | "zsh");
176 }
177 Err(e) => tracing::debug!("could not refresh {}: {e}", path.display()),
178 }
179 }
180 posix_refreshed
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn lc_shim_script_is_self_contained_fallback() {
189 let s = shim_script("_lc", "/usr/bin/lean-ctx", "-t");
190 assert!(s.starts_with("#!/bin/sh\n"), "needs a shebang: {s}");
191 assert!(s.contains("'/usr/bin/lean-ctx' -t \"$@\""), "{s}");
192 assert!(s.contains("exec \"$@\""), "{s}");
193 assert!(s.contains("CLAUDECODE"), "{s}");
194 assert!(s.contains("LEAN_CTX_DISABLED"), "{s}");
195 }
196
197 #[test]
198 fn lc_compress_shim_uses_compress_flag() {
199 let s = shim_script("_lc_compress", "/usr/bin/lean-ctx", "-c");
200 assert!(s.contains("'/usr/bin/lean-ctx' -c \"$@\""), "{s}");
201 }
202
203 #[test]
206 fn stale_installed_hooks_are_refreshed_and_absent_ones_left_alone() {
207 let _iso = crate::core::data_dir::isolated_data_dir();
209 let tmp = tempfile::tempdir().expect("tempdir");
210 let bin = "/usr/local/bin/lean-ctx";
211 let hook = tmp.path().join("shell-hook.bash");
212 std::fs::write(&hook, "alias grep='_lc grep'\n").expect("write stale hook");
213
214 assert!(refresh_shell_hooks_in(tmp.path(), bin), "stale bash hook");
215 assert_eq!(
216 std::fs::read_to_string(&hook).expect("read hook"),
217 generate_hook_posix(bin)
218 );
219 assert!(!tmp.path().join("shell-hook.zsh").exists());
220 assert!(!tmp.path().join("shell-hook.fish").exists());
221 assert!(
222 !refresh_shell_hooks_in(tmp.path(), bin),
223 "a current hook is not rewritten"
224 );
225 }
226
227 #[test]
228 fn write_lc_path_shims_writes_both_executables() {
229 let tmp = tempfile::tempdir().expect("tempdir");
230 assert!(write_lc_path_shims_in(tmp.path(), "/usr/bin/lean-ctx"));
231 for name in ["_lc", "_lc_compress"] {
232 assert!(tmp.path().join(name).exists(), "missing shim {name}");
233 }
234 }
235
236 #[test]
237 fn write_lc_path_shims_reports_an_unwritable_dir() {
238 let tmp = tempfile::tempdir().expect("tempdir");
239 assert!(!write_lc_path_shims_in(
240 &tmp.path().join("missing"),
241 "/usr/bin/lean-ctx"
242 ));
243 }
244
245 #[cfg(unix)]
248 mod lc_shim_dirs_1851 {
249 use super::super::lc_shim_dirs;
250 use std::path::{Path, PathBuf};
251
252 fn launcher_dir(root: &Path, rel: &str) -> PathBuf {
253 let dir = root.join(rel);
254 std::fs::create_dir_all(&dir).unwrap();
255 std::fs::write(dir.join("lean-ctx"), "#!/bin/sh\n").unwrap();
256 dir
257 }
258
259 #[test]
260 fn versioned_install_dir_off_path_is_skipped() {
261 let tmp = tempfile::tempdir().unwrap();
262 let apps = launcher_dir(tmp.path(), "scoop/apps/lean-ctx/3.10.2");
263 let shims = launcher_dir(tmp.path(), "scoop/shims");
264 let dirs = lc_shim_dirs(
265 Some(&apps.join("lean-ctx")),
266 &[tmp.path().join("usr/bin"), shims.clone()],
267 None,
268 );
269 assert_eq!(dirs, vec![shims]);
270 }
271
272 #[test]
273 fn exe_dir_on_path_comes_first_then_launchers_then_user_bin() {
274 let tmp = tempfile::tempdir().unwrap();
275 let home = tmp.path().join("home");
276 let user_bin = home.join(".local/bin");
277 std::fs::create_dir_all(&user_bin).unwrap();
278 let brew = launcher_dir(tmp.path(), "opt/homebrew/bin");
279 let exe_dir = launcher_dir(tmp.path(), "exe");
280 let dirs = lc_shim_dirs(
281 Some(&exe_dir.join("lean-ctx")),
282 &[brew.clone(), user_bin.clone(), exe_dir.clone()],
283 Some(&home),
284 );
285 assert_eq!(dirs, vec![exe_dir, brew, user_bin]);
286 }
287
288 #[test]
289 fn user_bin_off_path_is_not_a_candidate() {
290 let tmp = tempfile::tempdir().unwrap();
291 let home = tmp.path().join("home");
292 std::fs::create_dir_all(home.join(".local/bin")).unwrap();
293 let dirs = lc_shim_dirs(None, &[tmp.path().join("usr/bin")], Some(&home));
294 assert!(dirs.is_empty(), "{dirs:?}");
295 }
296 }
297}