lean_ctx/core/
command_cwd.rs1use std::path::{Path, PathBuf};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct SegmentCwd {
19 pub segment: String,
20 pub cwd: Option<PathBuf>,
22}
23
24pub fn segments_with_cwd(command: &str, base: Option<&Path>) -> Vec<SegmentCwd> {
29 let mut cwd: Option<PathBuf> = base.map(Path::to_path_buf);
30 let mut out = Vec::new();
31
32 for segment in super::shell_allowlist::extract_all_commands_pub(command) {
33 if let Some(target) = cd_target(&segment) {
34 cwd = resolve_cd(cwd.as_deref(), target);
35 out.push(SegmentCwd {
38 segment,
39 cwd: cwd.clone(),
40 });
41 continue;
42 }
43 out.push(SegmentCwd {
44 segment,
45 cwd: cwd.clone(),
46 });
47 }
48 out
49}
50
51pub fn final_cwd(command: &str, base: Option<&Path>) -> Option<PathBuf> {
53 segments_with_cwd(command, base)
54 .last()
55 .and_then(|s| s.cwd.clone())
56}
57
58fn cd_target(segment: &str) -> Option<&str> {
60 let mut words = segment.split_whitespace();
61 if words.next()? != "cd" {
62 return None;
63 }
64 let target = words.next()?;
65 if words.next().is_some() {
66 return None;
68 }
69 Some(target)
70}
71
72fn resolve_cd(from: Option<&Path>, target: &str) -> Option<PathBuf> {
78 let unquoted = target.trim_matches(['"', '\'']);
79 if unquoted.is_empty() || unquoted.contains('$') || unquoted.contains('`') || unquoted == "-" {
80 return None;
81 }
82 if let Some(rest) = unquoted.strip_prefix('~') {
84 let home = std::env::var_os("HOME").map(PathBuf::from)?;
85 return Some(join_in(&home, rest.trim_start_matches('/')));
86 }
87 if unquoted.starts_with('/') {
94 return Some(PathBuf::from(normalize_posix(unquoted)));
95 }
96 let path = Path::new(unquoted);
97 if path.is_absolute() {
98 return Some(normalize(path));
99 }
100 Some(join_in(from?, unquoted))
101}
102
103pub fn join_in(base: &Path, rel: &str) -> PathBuf {
108 let base_str = base.to_string_lossy();
109 if base_str.starts_with('/') {
110 return PathBuf::from(normalize_posix(&format!(
111 "{}/{rel}",
112 base_str.trim_end_matches('/')
113 )));
114 }
115 normalize(&base.join(rel))
116}
117
118fn normalize_posix(path: &str) -> String {
120 let mut out: Vec<&str> = Vec::new();
121 for part in path.split('/') {
122 match part {
123 "" | "." => {}
124 ".." => {
125 out.pop();
126 }
127 other => out.push(other),
128 }
129 }
130 format!("/{}", out.join("/"))
131}
132
133fn normalize(path: &Path) -> PathBuf {
136 use std::path::Component;
137 let mut out = PathBuf::new();
138 for component in path.components() {
139 match component {
140 Component::CurDir => {}
141 Component::ParentDir => {
142 out.pop();
143 }
144 other => out.push(other),
145 }
146 }
147 out
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153
154 #[test]
155 fn a_leading_cd_moves_the_following_segments() {
156 let segs = segments_with_cwd(
157 "cd /tmp/work && curl -o x.png http://e/x",
158 Some(Path::new("/proj")),
159 );
160 assert_eq!(
161 segs.last().unwrap().cwd.as_deref(),
162 Some(Path::new("/tmp/work"))
163 );
164 }
165
166 #[test]
167 fn without_a_cd_every_segment_keeps_the_call_directory() {
168 let segs = segments_with_cwd("echo a && echo b", Some(Path::new("/proj")));
169 assert!(
170 segs.iter()
171 .all(|s| s.cwd.as_deref() == Some(Path::new("/proj")))
172 );
173 }
174
175 #[test]
176 fn a_relative_cd_is_joined_onto_the_call_directory() {
177 assert_eq!(
178 final_cwd("cd sub/dir && ls", Some(Path::new("/proj"))),
179 Some(PathBuf::from("/proj/sub/dir"))
180 );
181 assert_eq!(
182 final_cwd("cd ../side && ls", Some(Path::new("/proj/here"))),
183 Some(PathBuf::from("/proj/side"))
184 );
185 }
186
187 #[test]
191 fn an_unresolvable_cd_makes_the_directory_unknown() {
192 assert_eq!(
193 final_cwd("cd \"$TMPDIR\" && ls", Some(Path::new("/proj"))),
194 None
195 );
196 assert_eq!(final_cwd("cd - && ls", Some(Path::new("/proj"))), None);
197 }
198
199 #[test]
203 fn a_unix_path_in_shell_text_is_absolute_on_every_platform() {
204 assert_eq!(
205 final_cwd("cd /tmp && curl -o shot.png https://e/x", None),
206 Some(PathBuf::from("/tmp"))
207 );
208 assert_eq!(
209 final_cwd("cd /private/tmp/session/../session && ls", None),
210 Some(PathBuf::from("/private/tmp/session"))
211 );
212 assert_eq!(
213 join_in(Path::new("/tmp/work"), "sub/shot.png"),
214 PathBuf::from("/tmp/work/sub/shot.png"),
215 "and joins with a forward slash, which the scratch prefixes match on"
216 );
217 }
218
219 #[test]
220 fn no_base_and_no_cd_is_unknown() {
221 assert_eq!(final_cwd("ls -la", None), None);
222 }
223}