Skip to main content

chainsaw/lang/python/
mod.rs

1//! Python support: tree-sitter parser with source-root and virtualenv resolution.
2
3mod parser;
4mod resolver;
5
6#[cfg(test)]
7mod conformance;
8
9use std::path::{Path, PathBuf};
10
11use crate::lang::{LanguageSupport, ParseError, ParseResult};
12
13use self::resolver::{PythonResolver, package_name_from_path};
14
15#[derive(Debug)]
16pub struct PythonSupport {
17    resolver: PythonResolver,
18}
19
20impl PythonSupport {
21    pub fn new(root: &Path) -> Self {
22        Self {
23            resolver: PythonResolver::new(root),
24        }
25    }
26
27    pub fn source_roots(&self) -> &[PathBuf] {
28        self.resolver.source_roots()
29    }
30}
31
32impl LanguageSupport for PythonSupport {
33    fn extensions(&self) -> &'static [&'static str] {
34        &["py"]
35    }
36
37    fn parse(&self, path: &Path, source: &str) -> Result<ParseResult, ParseError> {
38        parser::parse_file(path, source)
39    }
40
41    fn resolve(&self, from_dir: &Path, specifier: &str) -> Option<PathBuf> {
42        self.resolver.resolve(from_dir, specifier)
43    }
44
45    fn package_name(&self, resolved_path: &Path) -> Option<String> {
46        package_name_from_path(resolved_path, self.resolver.site_packages())
47    }
48
49    fn workspace_package_name(&self, _file_path: &Path, _project_root: &Path) -> Option<String> {
50        None
51    }
52}