Skip to content

Commit 89f57d1

Browse files
natelustmmlbMichaReiser
committed
[ty]: Search PYTHONPATH to find modules
This brings ty in line with other type checkers and python interpreters, including on by default and no options to disable. Can be disabled by clearing the PYTHONPATH environment variable or specifying paths in the --exta-paths. Co-authored-by: Manuel Mendez <[email protected]> Co-authored-by: Micha Reiser <[email protected]>
1 parent 859475f commit 89f57d1

File tree

1 file changed

+45
-7
lines changed

1 file changed

+45
-7
lines changed

crates/ty_project/src/metadata/options.rs

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -277,14 +277,52 @@ impl Options {
277277
roots
278278
};
279279

280+
// collect the existing site packages
281+
let mut extra_paths: Vec<SystemPathBuf> = Vec::new();
282+
283+
match (&environment.extra_paths, system.env_var("PYTHONPATH")) {
284+
(Some(extra_paths_env), Ok(_)) => {
285+
tracing::debug!(
286+
"Both --extra-paths and `PYTHONPATH` are set, ignoring `PYTHONPATH`"
287+
);
288+
extra_paths.extend(
289+
extra_paths_env
290+
.iter()
291+
.map(|path| path.absolute(project_root, system)),
292+
);
293+
}
294+
(Some(extra_paths_env), Err(_)) => {
295+
extra_paths.extend(
296+
extra_paths_env
297+
.iter()
298+
.map(|path| path.absolute(project_root, system)),
299+
);
300+
}
301+
(None, Ok(python_path)) => {
302+
// read all the paths off the PYTHONPATH environment variable,
303+
// check they exist as a directory, and add them to the vec of
304+
// extra_paths as they should be checked before site-packages
305+
// just like python interpreter does
306+
for path in python_path.split(':') {
307+
let possible_path = SystemPathBuf::from(path);
308+
309+
if system.is_directory(&possible_path) {
310+
tracing::debug!(
311+
"Adding `{possible_path}` from the `PYTHONPATH` environment variable to `extra_paths`"
312+
);
313+
extra_paths.push(possible_path);
314+
} else {
315+
tracing::debug!(
316+
"Skipping `{possible_path}` listed in `PYTHONPATH` because the path doesn't exist or isn't a directory"
317+
);
318+
}
319+
}
320+
}
321+
(None, Err(_)) => {}
322+
}
323+
280324
let settings = SearchPathSettings {
281-
extra_paths: environment
282-
.extra_paths
283-
.as_deref()
284-
.unwrap_or_default()
285-
.iter()
286-
.map(|path| path.absolute(project_root, system))
287-
.collect(),
325+
extra_paths,
288326
src_roots,
289327
custom_typeshed: environment
290328
.typeshed

0 commit comments

Comments
 (0)