Skip to content
This repository was archived by the owner on Sep 9, 2025. It is now read-only.

Commit d0b940e

Browse files
committed
fix: add auxiliary function to remove file ext
1 parent 3d28315 commit d0b940e

File tree

2 files changed

+41
-5
lines changed

2 files changed

+41
-5
lines changed

languages/tree-sitter-stack-graphs-typescript/src/stack-graphs.tsg

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ attribute node_symbol = node => symbol = (source-text node), source_n
260260

261261
; expose globals
262262
edge proj_scope -> @prog.globals
263-
263+
264264
var mod_scope = proj_scope
265265
if (not (is-empty @imexs)) {
266266
; module definition
@@ -540,10 +540,9 @@ attribute node_symbol = node => symbol = (source-text node), source_n
540540

541541
; module reference
542542
var mod_scope = mod_ref__ns
543-
scan (path-normalize mod_path) {
544-
; ignore .js and .ts extensions on imports, as ts allows this
545-
; this might lead to false positives
546-
"([^/|(\.j|ts)]+)/?" {
543+
; normalize path and remove the extension as we want to match 'foo', 'foo.js', 'foo.ts', etc.
544+
scan (path-remove-ext (path-normalize mod_path)) {
545+
"([^/]+)/?" {
547546
node mod_ref
548547
attr (mod_ref) push_symbol = $1
549548
edge mod_ref -> mod_scope

tree-sitter-stack-graphs/src/functions.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@ pub mod path {
4343
path_fn(|p| normalize(p).map(|p| p.as_os_str().to_os_string())),
4444
);
4545
functions.add("path-split".into(), PathSplit);
46+
functions.add(
47+
"path-remove-ext".into(),
48+
path_fn(|p| remove_extension(p).map(|p| p.as_os_str().to_os_string())),
49+
);
4650
}
4751

4852
pub fn path_fn<F>(f: F) -> impl Function
@@ -159,4 +163,37 @@ pub mod path {
159163
}
160164
Some(ret)
161165
}
166+
167+
/// Removes the extension from a path.
168+
/// eg. `foo/bar.rs` -> `foo/bar`
169+
/// eg. `foo/bar` -> `foo/bar`
170+
/// eg. `foo/bar.rs.bak` -> `foo/bar.rs`
171+
pub fn remove_extension(path: &Path) -> Option<PathBuf> {
172+
path.extension()
173+
.map_or(Some(path.into()), |_| path.with_extension("").into())
174+
}
175+
176+
#[test]
177+
fn test_remove_extension() {
178+
assert_eq!(
179+
remove_extension(Path::new("foo/bar.rs")),
180+
Some(PathBuf::from("foo/bar"))
181+
);
182+
assert_eq!(
183+
remove_extension(Path::new("foo/bar")),
184+
Some(PathBuf::from("foo/bar"))
185+
);
186+
assert_eq!(
187+
remove_extension(Path::new("foo/bar.rs.bak")),
188+
Some(PathBuf::from("foo/bar.rs"))
189+
);
190+
assert_eq!(
191+
remove_extension(Path::new("foo")),
192+
Some(PathBuf::from("foo"))
193+
);
194+
assert_eq!(
195+
remove_extension(Path::new("foo.rs")),
196+
Some(PathBuf::from("foo"))
197+
);
198+
}
162199
}

0 commit comments

Comments
 (0)