1use std::path::{Component, Path, PathBuf};
4
5pub const ENV_DIRS: &[&str] = &[
6 ".venv",
7 "venv",
8 "node_modules",
9 "site-packages",
10 "archive-v0",
11];
12
13pub fn summary_worktree(summary: &serde_json::Value) -> Result<PathBuf, String> {
16 let wt = summary
17 .get("worktree")
18 .and_then(|v| v.as_str())
19 .map(str::trim)
20 .filter(|s| !s.is_empty())
21 .ok_or_else(|| "missing `worktree` field in summary".to_string())?;
22 Ok(PathBuf::from(wt))
23}
24
25pub fn borrowed_env_commands(log: &str, worktree: &Path) -> Vec<String> {
28 let norm_wt = normalize_path(worktree);
29 let mut out = Vec::new();
30 for cmd in crate::dispatch::bash_commands(log) {
31 if borrows_env(&cmd, &norm_wt) {
32 let trimmed: String = cmd.chars().take(200).collect();
33 if !out.contains(&trimmed) {
34 out.push(trimmed);
35 }
36 }
37 }
38 out
39}
40
41pub fn flag(commands: &[String]) -> Option<String> {
43 let first = commands.first()?;
44 Some(format!(
45 "the gate may have run in an environment from outside the worktree: {} command(s), first: {}",
46 commands.len(),
47 first
48 ))
49}
50
51fn borrows_env(cmd: &str, norm_wt: &Path) -> bool {
52 cmd.split("&&")
53 .flat_map(|s| s.split(';'))
54 .flat_map(|s| s.split('|'))
55 .any(|part| part_borrows_env(part, norm_wt))
56}
57
58fn part_borrows_env(part: &str, norm_wt: &Path) -> bool {
59 let tokens = shell_words(part);
60 let mut i = 0;
61 while i < tokens.len() {
62 let t = tokens[i].as_str();
63 if t == "sudo" || is_env_assignment(t) {
64 i += 1;
65 } else {
66 break;
67 }
68 }
69 let Some(prog) = tokens.get(i).map(String::as_str) else {
70 return false;
71 };
72 let prog_name = Path::new(prog)
73 .file_name()
74 .and_then(|s| s.to_str())
75 .filter(|s| !s.is_empty());
76 if !matches!(prog_name, Some("cp" | "ln" | "rsync" | "mv")) {
77 return false;
78 }
79
80 for raw_arg in &tokens[i + 1..] {
81 if raw_arg.is_empty() {
82 continue;
83 }
84 let arg = if raw_arg.starts_with('-') {
85 match raw_arg.split_once('=') {
86 Some((_, val)) => val,
87 None => continue,
88 }
89 } else {
90 raw_arg.as_str()
91 };
92 if has_env_dir_component(arg) && is_outside_worktree(arg, norm_wt) {
93 return true;
94 }
95 }
96 false
97}
98
99pub fn shell_words(part: &str) -> Vec<String> {
101 enum Quote {
102 None,
103 Single,
104 Double,
105 }
106
107 let mut words = Vec::new();
108 let mut current = String::new();
109 let mut in_word = false;
110 let mut quote = Quote::None;
111 let mut chars = part.chars().peekable();
112
113 while let Some(c) = chars.next() {
114 match quote {
115 Quote::None => match c {
116 c if c.is_whitespace() => {
117 if in_word {
118 words.push(std::mem::take(&mut current));
119 in_word = false;
120 }
121 }
122 '\'' => {
123 quote = Quote::Single;
124 in_word = true;
125 }
126 '"' => {
127 quote = Quote::Double;
128 in_word = true;
129 }
130 '\\' => {
131 in_word = true;
132 match chars.next() {
133 Some(next) => current.push(next),
134 None => current.push('\\'),
135 }
136 }
137 _ => {
138 in_word = true;
139 current.push(c);
140 }
141 },
142 Quote::Single => {
143 if c == '\'' {
144 quote = Quote::None;
145 } else {
146 current.push(c);
147 }
148 }
149 Quote::Double => match c {
150 '"' => quote = Quote::None,
151 '\\' => {
152 if matches!(chars.peek(), Some('"' | '\\')) {
153 if let Some(next) = chars.next() {
154 current.push(next);
155 }
156 } else {
157 current.push('\\');
158 }
159 }
160 _ => current.push(c),
161 },
162 }
163 }
164
165 if in_word {
166 words.push(current);
167 }
168 words
169}
170
171fn is_env_assignment(token: &str) -> bool {
172 let Some((name, _)) = token.split_once('=') else {
173 return false;
174 };
175 !name.is_empty()
176 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
177 && !name.chars().next().is_some_and(|c| c.is_ascii_digit())
178}
179
180fn has_env_dir_component(arg: &str) -> bool {
181 Path::new(arg).components().any(|c| match c {
182 Component::Normal(os) => os.to_str().is_some_and(|s| ENV_DIRS.contains(&s)),
183 _ => false,
184 })
185}
186
187fn is_outside_worktree(arg: &str, norm_wt: &Path) -> bool {
188 if arg == "~"
189 || arg.starts_with("~/")
190 || arg == "$HOME"
191 || arg.starts_with("$HOME/")
192 || arg.starts_with("${HOME}/")
193 {
194 return true;
195 }
196 let p = Path::new(arg);
197 let joined = if p.is_absolute() {
198 p.to_path_buf()
199 } else {
200 norm_wt.join(p)
201 };
202 let resolved = normalize_path(&joined);
203 !resolved.starts_with(norm_wt)
204}
205
206pub fn normalize_path(path: &Path) -> PathBuf {
208 let mut stack: Vec<Component<'_>> = Vec::new();
209 for comp in path.components() {
210 match comp {
211 Component::Prefix(_) | Component::RootDir | Component::Normal(_) => stack.push(comp),
212 Component::CurDir => {}
213 Component::ParentDir => match stack.last() {
214 Some(Component::Normal(_)) => {
215 stack.pop();
216 }
217 Some(Component::RootDir) => {}
218 _ => stack.push(comp),
219 },
220 }
221 }
222 stack.into_iter().collect()
223}