Skip to main content

vtcode_commons/
editor.rs

1#![expect(
2    clippy::indexing_slicing,
3    clippy::string_slice,
4    unused_results,
5    reason = "Editor URI parsing uses validated delimiters and intentionally ignores String mutation results."
6)]
7
8use std::borrow::Cow;
9use std::env;
10use std::path::{Path, PathBuf};
11
12use percent_encoding::percent_decode_str;
13use url::Url;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct EditorPoint {
17    pub line: usize,
18    pub column: Option<usize>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct EditorTarget {
23    path: PathBuf,
24    location_suffix: Option<String>,
25}
26
27impl EditorTarget {
28    #[must_use]
29    pub fn new(path: PathBuf, location_suffix: Option<String>) -> Self {
30        Self { path, location_suffix }
31    }
32
33    #[must_use]
34    pub fn path(&self) -> &Path {
35        &self.path
36    }
37
38    #[must_use]
39    pub fn location_suffix(&self) -> Option<&str> {
40        self.location_suffix.as_deref()
41    }
42
43    #[must_use]
44    pub fn with_resolved_path(mut self, base: &Path) -> Self {
45        self.path = resolve_editor_path(&self.path, base);
46        self
47    }
48
49    #[must_use]
50    pub fn canonical_string(&self) -> String {
51        let mut target = self.path.display().to_string();
52        if let Some(location) = self.location_suffix() {
53            target.push_str(location);
54        }
55        target
56    }
57
58    #[must_use]
59    pub fn point(&self) -> Option<EditorPoint> {
60        let suffix = self.location_suffix()?.strip_prefix(':')?;
61        if suffix.contains('-') {
62            return None;
63        }
64
65        let mut parts = suffix.split(':');
66        let line = parts.next()?.parse().ok()?;
67        let column = parts.next().map(str::parse).transpose().ok().flatten();
68        if parts.next().is_some() {
69            return None;
70        }
71
72        Some(EditorPoint { line, column })
73    }
74}
75
76#[must_use]
77pub fn parse_editor_target(raw: &str) -> Option<EditorTarget> {
78    let raw = raw.trim();
79    if raw.is_empty() {
80        return None;
81    }
82
83    if raw.starts_with("http://") || raw.starts_with("https://") {
84        return None;
85    }
86    if raw.contains("://") && !raw.starts_with("file://") {
87        return None;
88    }
89
90    if raw.starts_with("file://") {
91        let mut url = Url::parse(raw).ok()?;
92        let location_suffix = if let Some(fragment) = url.fragment().and_then(normalize_editor_hash_fragment) {
93            Some(fragment)
94        } else if let Some(suffix) = extract_trailing_location(url.path()) {
95            let path = url.path().strip_suffix(&suffix)?.to_owned();
96            url.set_path(&path);
97            Some(suffix)
98        } else {
99            None
100        };
101        let path = url.to_file_path().ok()?;
102        return Some(EditorTarget::new(path, location_suffix));
103    }
104
105    if let Some((path_str, fragment)) = raw.split_once('#')
106        && let Some(location_suffix) = normalize_editor_hash_fragment(fragment)
107    {
108        if path_str.is_empty() {
109            return None;
110        }
111        let decoded_path = decode_bare_local_path(path_str);
112        return Some(EditorTarget::new(
113            expand_home_relative_path(decoded_path.as_ref()).unwrap_or_else(|| PathBuf::from(decoded_path.as_ref())),
114            Some(location_suffix),
115        ));
116    }
117
118    if let Some(paren_start) = location_paren_suffix_start(raw) {
119        let location_suffix = parse_paren_location_suffix(&raw[paren_start..])?;
120        let path_str = &raw[..paren_start];
121        if path_str.is_empty() {
122            return None;
123        }
124        let decoded_path = decode_bare_local_path(path_str);
125
126        return Some(EditorTarget::new(
127            expand_home_relative_path(decoded_path.as_ref()).unwrap_or_else(|| PathBuf::from(decoded_path.as_ref())),
128            Some(location_suffix),
129        ));
130    }
131
132    let location_suffix = extract_trailing_location(raw);
133    let path_str = match location_suffix.as_deref() {
134        Some(suffix) => &raw[..raw.len().saturating_sub(suffix.len())],
135        None => raw,
136    };
137    if path_str.is_empty() {
138        return None;
139    }
140    let decoded_path = decode_bare_local_path(path_str);
141
142    Some(EditorTarget::new(
143        expand_home_relative_path(decoded_path.as_ref()).unwrap_or_else(|| PathBuf::from(decoded_path.as_ref())),
144        location_suffix,
145    ))
146}
147
148#[must_use]
149pub fn resolve_editor_target(raw: &str, base: &Path) -> Option<EditorTarget> {
150    parse_editor_target(raw).map(|target| target.with_resolved_path(base))
151}
152
153#[must_use]
154pub fn resolve_editor_path(path: &Path, base: &Path) -> PathBuf {
155    if path.is_absolute() {
156        return path.to_path_buf();
157    }
158
159    let mut joined = PathBuf::from(base);
160    for component in path.components() {
161        match component {
162            std::path::Component::CurDir => {}
163            std::path::Component::ParentDir => {
164                joined.pop();
165            }
166            other => joined.push(other.as_os_str()),
167        }
168    }
169    joined
170}
171
172fn expand_home_relative_path(path: &str) -> Option<PathBuf> {
173    let remainder = path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\"))?;
174    let home = env::var_os("HOME").or_else(|| env::var_os("USERPROFILE"))?;
175    Some(PathBuf::from(home).join(remainder))
176}
177
178fn decode_bare_local_path(path: &str) -> Cow<'_, str> {
179    percent_decode_str(path).decode_utf8().unwrap_or(Cow::Borrowed(path))
180}
181
182fn extract_trailing_location(raw: &str) -> Option<String> {
183    let bytes = raw.as_bytes();
184    let mut idx = bytes.len();
185    while idx > 0 && (bytes[idx - 1].is_ascii_digit() || matches!(bytes[idx - 1], b':' | b'-')) {
186        idx -= 1;
187    }
188    if idx >= bytes.len() || bytes.get(idx).copied() != Some(b':') {
189        return None;
190    }
191
192    let suffix = &raw[idx..];
193    let digits = suffix.chars().filter(|ch| ch.is_ascii_digit()).count();
194    (digits > 0).then(|| suffix.to_string())
195}
196
197fn location_paren_suffix_start(token: &str) -> Option<usize> {
198    let paren_start = token.rfind('(')?;
199    let inner = token[paren_start + 1..].strip_suffix(')')?;
200    let valid = !inner.is_empty()
201        && !inner.starts_with(',')
202        && !inner.ends_with(',')
203        && !inner.contains(",,")
204        && inner.chars().all(|c| c.is_ascii_digit() || c == ',');
205    valid.then_some(paren_start)
206}
207
208fn parse_paren_location_suffix(suffix: &str) -> Option<String> {
209    let inner = suffix.strip_prefix('(')?.strip_suffix(')')?;
210    if inner.is_empty() {
211        return None;
212    }
213
214    let mut parts = inner.split(',');
215    let line = parts.next()?;
216    let column = parts.next();
217    if parts.next().is_some() {
218        return None;
219    }
220
221    if line.is_empty() || !line.chars().all(|ch| ch.is_ascii_digit()) {
222        return None;
223    }
224
225    let mut normalized = format!(":{line}");
226    if let Some(column) = column {
227        if column.is_empty() || !column.chars().all(|ch| ch.is_ascii_digit()) {
228            return None;
229        }
230        normalized.push(':');
231        normalized.push_str(column);
232    }
233
234    Some(normalized)
235}
236
237#[must_use]
238pub fn normalize_editor_hash_fragment(fragment: &str) -> Option<String> {
239    let (start, end) = match fragment.split_once('-') {
240        Some((start, end)) => (start, Some(end)),
241        None => (fragment, None),
242    };
243
244    let (start_line, start_col) = parse_hash_point(start)?;
245    let mut normalized = format!(":{start_line}");
246    if let Some(col) = start_col {
247        normalized.push(':');
248        normalized.push_str(col);
249    }
250
251    if let Some(end) = end {
252        let (end_line, end_col) = parse_hash_point(end)?;
253        normalized.push('-');
254        normalized.push_str(end_line);
255        if let Some(col) = end_col {
256            normalized.push(':');
257            normalized.push_str(col);
258        }
259    }
260
261    Some(normalized)
262}
263
264fn parse_hash_point(point: &str) -> Option<(&str, Option<&str>)> {
265    let point = point.strip_prefix('L')?;
266    let (line, column) = match point.split_once('C') {
267        Some((line, column)) => (line, Some(column)),
268        None => (point, None),
269    };
270    if line.is_empty() || !line.chars().all(|ch| ch.is_ascii_digit()) {
271        return None;
272    }
273    if let Some(column) = column
274        && (column.is_empty() || !column.chars().all(|ch| ch.is_ascii_digit()))
275    {
276        return None;
277    }
278    Some((line, column))
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    #[test]
286    fn parses_colon_location_suffix() {
287        let target = parse_editor_target("/tmp/demo.rs:12:4").expect("target");
288        assert_eq!(target.path(), Path::new("/tmp/demo.rs"));
289        assert_eq!(target.location_suffix(), Some(":12:4"));
290        assert_eq!(target.point(), Some(EditorPoint { line: 12, column: Some(4) }));
291    }
292
293    #[test]
294    fn parses_paren_location_suffix() {
295        let target = parse_editor_target("/tmp/demo.rs(12,4)").expect("target");
296        assert_eq!(target.path(), Path::new("/tmp/demo.rs"));
297        assert_eq!(target.location_suffix(), Some(":12:4"));
298    }
299
300    #[test]
301    fn parses_hash_location_suffix() {
302        let target = parse_editor_target("/tmp/demo.rs#L12C4").expect("target");
303        assert_eq!(target.path(), Path::new("/tmp/demo.rs"));
304        assert_eq!(target.location_suffix(), Some(":12:4"));
305    }
306
307    #[test]
308    fn normalizes_hash_location_ranges() {
309        assert_eq!(normalize_editor_hash_fragment("L74C3-L76C9"), Some(":74:3-76:9".to_string()));
310        assert_eq!(normalize_editor_hash_fragment("L74-L76"), Some(":74-76".to_string()));
311        assert_eq!(normalize_editor_hash_fragment("L"), None);
312        assert_eq!(normalize_editor_hash_fragment("L74-"), None);
313        assert_eq!(normalize_editor_hash_fragment("L74C"), None);
314    }
315
316    #[test]
317    fn hash_ranges_preserve_suffix_but_not_point() {
318        let target = parse_editor_target("/tmp/demo.rs#L12-L18").expect("target");
319        assert_eq!(target.location_suffix(), Some(":12-18"));
320        assert_eq!(target.point(), None);
321    }
322
323    #[test]
324    fn file_urls_are_supported() {
325        let target = parse_editor_target("file:///tmp/demo.rs#L12").expect("target");
326        assert_eq!(target.path(), Path::new("/tmp/demo.rs"));
327        assert_eq!(target.location_suffix(), Some(":12"));
328    }
329
330    #[test]
331    fn file_url_colon_location_is_removed_from_encoded_path() {
332        let target = parse_editor_target("file:///tmp/Example%20Folder/R%C3%A9sum%C3%A9.md:12:4").expect("target");
333        assert_eq!(target.path(), Path::new("/tmp/Example Folder/Résumé.md"));
334        assert_eq!(target.point(), Some(EditorPoint { line: 12, column: Some(4) }));
335
336        let fragment = parse_editor_target("file:///tmp/name:42#L7").expect("target");
337        assert_eq!(fragment.path(), Path::new("/tmp/name:42"));
338        assert_eq!(fragment.location_suffix(), Some(":7"));
339    }
340
341    #[test]
342    fn bare_percent_encoded_paths_are_decoded() {
343        let target = parse_editor_target("/tmp/Example%20Folder/R%C3%A9sum%C3%A9.md:12").expect("target");
344        assert_eq!(target.path(), Path::new("/tmp/Example Folder/Résumé.md"));
345        assert_eq!(target.location_suffix(), Some(":12"));
346    }
347
348    #[test]
349    fn non_file_urls_are_rejected() {
350        assert!(parse_editor_target("https://example.com/file.rs").is_none());
351    }
352
353    #[test]
354    fn resolves_relative_paths_against_base() {
355        let target = resolve_editor_target("src/lib.rs:12", Path::new("/workspace")).expect("target");
356        assert_eq!(target.path(), Path::new("/workspace/src/lib.rs"));
357        assert_eq!(target.location_suffix(), Some(":12"));
358        assert_eq!(target.canonical_string(), "/workspace/src/lib.rs:12");
359    }
360}