use std::path::{Path, PathBuf};
use grep_regex::RegexMatcher;
use grep_searcher::{BinaryDetection, MmapChoice, Searcher, SearcherBuilder, Sink, SinkMatch};
use ignore::WalkBuilder;
const RUST_EXT: &str = "rs";
struct FirstLine(Option<u64>);
impl Sink for FirstLine {
type Error = std::io::Error;
fn matched(&mut self, _s: &Searcher, mat: &SinkMatch<'_>) -> Result<bool, std::io::Error> {
self.0 = mat.line_number();
Ok(false) }
}
pub fn find_test_source(root: &Path, full_name: &str) -> Option<(PathBuf, u32)> {
if full_name.contains(".py::") {
return pytest_source(root, full_name);
}
if let Some((file, _)) = full_name.split_once("::")
&& crate::testing::parse::is_js_test_file(file)
{
return js_source(root, full_name);
}
let mut segments: Vec<&str> = full_name.split("::").collect();
let leaf = segments.pop()?;
let module: Vec<&str> = segments.into_iter().filter(|s| *s != "tests").collect();
let matcher =
RegexMatcher::new(&format!(r"\bfn\s+{}\s*[(<\s]", super::regex_escape(leaf))).ok()?;
let mut searcher = SearcherBuilder::new()
.line_number(true)
.binary_detection(BinaryDetection::quit(b'\x00'))
.memory_map(MmapChoice::never())
.build();
let mut best: Option<(PathBuf, u32, usize)> = None; for entry in WalkBuilder::new(root)
.require_git(false)
.filter_entry(|e| {
!(e.file_type().is_some_and(|t| t.is_dir())
&& matches!(e.file_name().to_str(), Some("target" | "node_modules")))
})
.build()
.flatten()
{
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some(RUST_EXT) {
continue;
}
let mut sink = FirstLine(None);
if searcher.search_path(&matcher, path, &mut sink).is_err() {
continue;
}
let Some(line1) = sink.0 else { continue };
let score = path_score(path, &module);
let line0 = line1.saturating_sub(1) as u32;
if best.as_ref().is_none_or(|(_, _, s)| score > *s) {
best = Some((path.to_path_buf(), line0, score));
}
}
best.map(|(p, l, _)| (p, l))
}
fn pytest_source(root: &Path, full_name: &str) -> Option<(PathBuf, u32)> {
let (file, rest) = full_name.split_once(".py::")?;
let path = root.join(format!("{file}.py"));
let leaf = rest.rsplit("::").next()?.split('[').next()?;
let matcher =
RegexMatcher::new(&format!(r"\bdef\s+{}\s*\(", super::regex_escape(leaf))).ok()?;
let mut searcher = SearcherBuilder::new()
.line_number(true)
.binary_detection(BinaryDetection::quit(b'\x00'))
.memory_map(MmapChoice::never())
.build();
let mut sink = FirstLine(None);
searcher.search_path(&matcher, &path, &mut sink).ok()?;
let line1 = sink.0?;
Some((path, line1.saturating_sub(1) as u32))
}
fn js_source(root: &Path, full_name: &str) -> Option<(PathBuf, u32)> {
let (file, rest) = full_name.split_once("::")?;
let path = root.join(file);
let leaf = rest.rsplit("::").next()?;
let escaped = super::regex_escape(leaf);
let mut searcher = SearcherBuilder::new()
.line_number(true)
.binary_detection(BinaryDetection::quit(b'\x00'))
.memory_map(MmapChoice::never())
.build();
let decl = RegexMatcher::new(&format!(r#"\b(?:test|it)\b[^'"`]*['"`]{escaped}"#)).ok()?;
let mut sink = FirstLine(None);
searcher.search_path(&decl, &path, &mut sink).ok()?;
let line1 = match sink.0 {
Some(l) => l,
None => {
let bare = RegexMatcher::new(&escaped).ok()?;
let mut sink = FirstLine(None);
searcher.search_path(&bare, &path, &mut sink).ok()?;
sink.0?
}
};
Some((path, line1.saturating_sub(1) as u32))
}
pub fn enclosing_fn_name(lines: &[String], cursor_row: usize) -> Option<String> {
let start = cursor_row.min(lines.len().checked_sub(1)?);
for line in lines[..=start].iter().rev() {
if let Some(name) = fn_name_in(line) {
return Some(name);
}
}
None
}
pub fn test_fn_on_line(path: Option<&Path>, lines: &[String], idx: usize) -> Option<String> {
let file = path?.file_name()?.to_str()?;
let line = lines.get(idx)?;
if file.ends_with(".py") {
let name = name_after(line, "def ")?;
let collectable = file.starts_with("test_") || file.ends_with("_test.py");
return (collectable && name.starts_with("test")).then_some(name);
}
if !file.ends_with(".rs") {
return None;
}
let name = name_after(line, "fn ")?;
for above in lines[..idx].iter().rev() {
let t = above.trim_start();
if !t.starts_with("#[") {
break;
}
if attr_marks_test(t) {
return Some(name);
}
}
None
}
fn attr_marks_test(attr_line: &str) -> bool {
let inner = attr_line.trim_start_matches("#[");
let name_end = inner
.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == ':'))
.unwrap_or(inner.len());
inner[..name_end]
.rsplit("::")
.next()
.is_some_and(|seg| seg == "test" || seg == "rstest")
}
fn fn_name_in(line: &str) -> Option<String> {
["fn ", "def "].iter().find_map(|kw| name_after(line, kw))
}
fn name_after(line: &str, keyword: &str) -> Option<String> {
let idx = line.find(keyword)?;
let name: String = line[idx + keyword.len()..]
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
let before = &line[..idx];
let boundary = before.is_empty() || before.ends_with(|c: char| c.is_whitespace());
(boundary && !name.is_empty()).then_some(name)
}
fn path_score(path: &Path, module: &[&str]) -> usize {
let components: Vec<&str> = path
.components()
.filter_map(|c| c.as_os_str().to_str())
.collect();
module
.iter()
.filter(|seg| {
components
.iter()
.any(|c| c == *seg || c.strip_suffix(".rs") == Some(seg))
})
.count()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_the_fn_and_prefers_the_module_matching_path() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("src/other")).unwrap();
std::fs::create_dir_all(root.join("src/widgets")).unwrap();
std::fs::write(
root.join("src/other/misc.rs"),
"fn helper() {}\nfn target_test() { /* decoy */ }\n",
)
.unwrap();
std::fs::write(
root.join("src/widgets/testing.rs"),
"mod tests {\n fn setup() {}\n fn target_test() { assert!(true); }\n}\n",
)
.unwrap();
let (path, line) = find_test_source(root, "widgets::testing::tests::target_test").unwrap();
assert!(
path.ends_with("src/widgets/testing.rs"),
"the module-matching file wins over the decoy, got {path:?}"
);
assert_eq!(line, 2, "0-based line of `fn target_test` in testing.rs");
}
#[test]
fn enclosing_fn_scans_upward_to_the_nearest_fn() {
let lines: Vec<String> = [
"mod tests {",
" fn first() {",
" assert!(true);", " }",
" fn second() {",
" assert!(false);", " }",
"}",
]
.iter()
.map(|s| s.to_string())
.collect();
assert_eq!(enclosing_fn_name(&lines, 2).as_deref(), Some("first"));
assert_eq!(enclosing_fn_name(&lines, 5).as_deref(), Some("second"));
assert_eq!(enclosing_fn_name(&lines, 0), None);
let noise = vec![String::from("let define_fn_thing = 3;")];
assert_eq!(enclosing_fn_name(&noise, 0), None);
}
#[test]
fn pytest_node_ids_resolve_to_the_def_in_their_file() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("tests")).unwrap();
std::fs::write(
root.join("tests/test_sample.py"),
"import pytest\n\ndef test_passes():\n assert True\n\nclass TestGroup:\n def test_method(self):\n assert True\n",
)
.unwrap();
let (path, line) = find_test_source(root, "tests/test_sample.py::test_passes").unwrap();
assert!(path.ends_with("tests/test_sample.py"), "got {path:?}");
assert_eq!(line, 2, "0-based line of `def test_passes`");
let (_, line) =
find_test_source(root, "tests/test_sample.py::TestGroup::test_method").unwrap();
assert_eq!(line, 6, "class methods resolve through the last segment");
let (_, line) = find_test_source(root, "tests/test_sample.py::test_passes[1]").unwrap();
assert_eq!(line, 2);
assert!(find_test_source(root, "tests/gone.py::test_x").is_none());
}
#[test]
fn enclosing_fn_understands_python_defs() {
let lines: Vec<String> = [
"import pytest",
"def test_first():",
" assert True", "class TestGroup:",
" def test_method(self):",
" assert True", ]
.iter()
.map(|s| s.to_string())
.collect();
assert_eq!(enclosing_fn_name(&lines, 2).as_deref(), Some("test_first"));
assert_eq!(enclosing_fn_name(&lines, 5).as_deref(), Some("test_method"));
assert_eq!(enclosing_fn_name(&lines, 0), None);
}
#[test]
fn an_empty_buffer_has_no_enclosing_fn() {
assert_eq!(enclosing_fn_name(&[], 0), None);
assert_eq!(enclosing_fn_name(&[], 5), None);
}
#[test]
fn gitignore_is_honoured_even_outside_a_git_repo() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join(".gitignore"), "gen/\n").unwrap();
std::fs::create_dir_all(root.join("gen/widgets")).unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("gen/widgets/parse.rs"), "fn target_case() {}\n").unwrap();
std::fs::write(root.join("src/lib.rs"), "fn target_case() {}\n").unwrap();
let (path, _) = find_test_source(root, "widgets::parse::tests::target_case").unwrap();
assert!(
path.ends_with("src/lib.rs"),
"an ignored dir must never win the jump target, got {path:?}"
);
}
#[test]
fn build_output_dirs_are_skipped_even_without_a_gitignore() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("target/debug")).unwrap();
std::fs::create_dir_all(root.join("node_modules/pkg")).unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("target/debug/parse.rs"), "fn target_case() {}\n").unwrap();
std::fs::write(
root.join("node_modules/pkg/parse.rs"),
"fn target_case() {}\n",
)
.unwrap();
std::fs::write(root.join("src/lib.rs"), "fn target_case() {}\n").unwrap();
let (path, _) = find_test_source(root, "widgets::parse::tests::target_case").unwrap();
assert!(
path.ends_with("src/lib.rs"),
"build output must never win the jump target, got {path:?}"
);
}
#[test]
fn js_test_titles_resolve_to_their_file_and_line() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(
root.join("src/math.test.ts"),
"import { test } from 'vitest'\n\ntest('adds (1 + 1)', () => {})\n\ntest('parses [ tokens', () => {})\n",
)
.unwrap();
let (path, line) = find_test_source(root, "src/math.test.ts::adds (1 + 1)").unwrap();
assert!(path.ends_with("src/math.test.ts"), "got {path:?}");
assert_eq!(line, 2, "0-based line of the first test title");
let (_, line) = find_test_source(root, "src/math.test.ts::suite::parses [ tokens").unwrap();
assert_eq!(line, 4);
}
#[test]
fn a_title_in_a_comment_above_the_test_does_not_hijack_the_jump() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(
root.join("math.test.js"),
"// adds (1 + 1) covers the carry path\nconst fixture = 'adds (1 + 1)'\n\ntest('adds (1 + 1)', () => {})\n",
)
.unwrap();
let (_, line) = find_test_source(root, "math.test.js::adds (1 + 1)").unwrap();
assert_eq!(line, 3, "the declaration, not the comment or the fixture");
}
#[test]
fn a_title_only_in_an_exotic_declaration_still_resolves() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(
root.join("a.test.js"),
"xit('odd little title', () => {})\n",
)
.unwrap();
let (_, line) = find_test_source(root, "a.test.js::odd little title").unwrap();
assert_eq!(line, 0);
}
#[test]
fn returns_none_when_the_fn_is_absent() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("a.rs"), "fn something_else() {}\n").unwrap();
assert!(find_test_source(tmp.path(), "m::nope").is_none());
}
#[test]
fn test_fn_on_line_detects_rust_test_attributes() {
let lines: Vec<String> = [
"fn helper() {}",
"#[test]",
"fn plain_case() {}",
"#[rstest]",
"#[tokio::test(flavor = \"multi_thread\")]",
"async fn async_case() {}",
"#[derive(Debug)]",
"fn derived_not_a_test() {}",
]
.iter()
.map(|s| s.to_string())
.collect();
let rs = Some(Path::new("a.rs"));
assert_eq!(
test_fn_on_line(rs, &lines, 0),
None,
"no attribute, no test"
);
assert_eq!(
test_fn_on_line(rs, &lines, 2).as_deref(),
Some("plain_case")
);
assert_eq!(
test_fn_on_line(rs, &lines, 5).as_deref(),
Some("async_case"),
"tokio::test in a stacked attribute block must count"
);
assert_eq!(
test_fn_on_line(rs, &lines, 7),
None,
"a non-test attribute above a fn must not count"
);
assert_eq!(
test_fn_on_line(rs, &lines, 1),
None,
"attribute lines define no fn"
);
}
#[test]
fn cfg_test_is_configuration_not_a_test_attribute() {
let lines: Vec<String> = [
"#[cfg(test)]",
"pub fn clear_native() {}",
"#[cfg(not(test))]",
"fn scan() {}",
"#[cfg_attr(test, derive(Clone))]",
"fn configured() {}",
]
.iter()
.map(|s| s.to_string())
.collect();
let rs = Some(Path::new("a.rs"));
assert_eq!(
test_fn_on_line(rs, &lines, 1),
None,
"#[cfg(test)] gates compilation; it does not mark a test"
);
assert_eq!(test_fn_on_line(rs, &lines, 3), None);
assert_eq!(
test_fn_on_line(rs, &lines, 5),
None,
"cfg_attr is configuration"
);
}
#[test]
fn suffix_named_attributes_are_not_test_markers() {
let lines: Vec<String> = [
"#[contest]",
"fn fake_case() {}",
"#[mytest]",
"fn other_fake_case() {}",
"#[googletest::test]",
"fn qualified_case() {}",
]
.iter()
.map(|s| s.to_string())
.collect();
let rs = Some(Path::new("a.rs"));
assert_eq!(
test_fn_on_line(rs, &lines, 1),
None,
"#[contest] merely ends in `test`"
);
assert_eq!(
test_fn_on_line(rs, &lines, 3),
None,
"#[mytest] merely ends in `test`"
);
assert_eq!(
test_fn_on_line(rs, &lines, 5).as_deref(),
Some("qualified_case"),
"a path-qualified exact `test` segment still counts"
);
}
#[test]
fn test_fn_on_line_detects_pytest_defs_by_name() {
let lines: Vec<String> = [
"def test_first():",
"def helper():",
" async def test_inner(self):",
]
.iter()
.map(|s| s.to_string())
.collect();
let tf = Some(Path::new("test_app.py"));
assert_eq!(
test_fn_on_line(tf, &lines, 0).as_deref(),
Some("test_first")
);
assert_eq!(
test_fn_on_line(tf, &lines, 1),
None,
"pytest only collects test_*"
);
assert_eq!(
test_fn_on_line(tf, &lines, 2).as_deref(),
Some("test_inner")
);
assert_eq!(
test_fn_on_line(Some(Path::new("app_test.py")), &lines, 0).as_deref(),
Some("test_first"),
"the *_test.py collection form counts too"
);
assert_eq!(
test_fn_on_line(Some(Path::new("app.py")), &lines, 0),
None,
"a def test_* in production code (non-collectable file) gets no bead"
);
assert_eq!(
test_fn_on_line(None, &lines, 0),
None,
"an unsaved buffer has nothing a runner could target"
);
}
}