[ty] Add PYTHONPATH to EnvVars and fix on Windows (#20490)

Co-authored-by: Micha Reiser <micha@reiser.io>
This commit is contained in:
Manuel Mendez 2025-09-23 04:27:05 -04:00 committed by GitHub
parent 68ae9c8a15
commit 036f3616a1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 116 additions and 22 deletions

View file

@ -22,6 +22,7 @@ ruff_python_formatter = { workspace = true, optional = true }
ruff_text_size = { workspace = true }
ty_combine = { workspace = true }
ty_python_semantic = { workspace = true, features = ["serde"] }
ty_static = { workspace = true }
ty_vendored = { workspace = true }
anyhow = { workspace = true }

View file

@ -34,6 +34,7 @@ use ty_python_semantic::{
PythonVersionSource, PythonVersionWithSource, SearchPathSettings, SearchPathValidationError,
SearchPaths, SitePackagesPaths, SysPrefixPathOrigin,
};
use ty_static::EnvVars;
#[derive(
Debug,
@ -296,38 +297,48 @@ impl Options {
};
// collect the existing site packages
let mut extra_paths: Vec<SystemPathBuf> = Vec::new();
let mut extra_paths: Vec<SystemPathBuf> = environment
.extra_paths
.as_deref()
.unwrap_or_default()
.iter()
.map(|path| path.absolute(project_root, system))
.collect();
// read all the paths off the PYTHONPATH environment variable, check
// they exist as a directory, and add them to the vec of extra_paths
// as they should be checked before site-packages just like python
// interpreter does
if let Ok(python_path) = system.env_var("PYTHONPATH") {
for path in python_path.split(':') {
let possible_path = SystemPath::absolute(path, system.current_directory());
if let Ok(python_path) = system.env_var(EnvVars::PYTHONPATH) {
for path in std::env::split_paths(python_path.as_str()) {
let path = match SystemPathBuf::from_path_buf(path) {
Ok(path) => path,
Err(path) => {
tracing::debug!(
"Skipping `{path}` listed in `PYTHONPATH` because the path is not valid UTF-8",
path = path.display()
);
continue;
}
};
if system.is_directory(&possible_path) {
let abspath = SystemPath::absolute(path, system.current_directory());
if !system.is_directory(&abspath) {
tracing::debug!(
"Adding `{possible_path}` from the `PYTHONPATH` environment variable to `extra_paths`"
);
extra_paths.push(possible_path);
} else {
tracing::debug!(
"Skipping `{possible_path}` listed in `PYTHONPATH` because the path doesn't exist or isn't a directory"
"Skipping `{abspath}` listed in `PYTHONPATH` because the path doesn't exist or isn't a directory"
);
continue;
}
tracing::debug!(
"Adding `{abspath}` from the `PYTHONPATH` environment variable to `extra_paths`"
);
extra_paths.push(abspath);
}
}
extra_paths.extend(
environment
.extra_paths
.as_deref()
.unwrap_or_default()
.iter()
.map(|path| path.absolute(project_root, system)),
);
let settings = SearchPathSettings {
extra_paths,
src_roots,