Python: Only track modules that are imported

This greatly restricts the set of modules that have a new name under
this scheme.

One change to the tests was needed, which reflects the fact that the
two `main.py` files no longer have the name `main` (which makes sense,
since they're never imported under this name).
This commit is contained in:
Taus
2021-04-06 19:55:43 +00:00
committed by Taus Brock-Nannestad
parent 8e11abca40
commit 43ae7462b4
2 changed files with 18 additions and 5 deletions

View File

@@ -201,6 +201,20 @@ private string moduleNameFromBase(Container file) {
file instanceof File and result = file.getStem()
}
/**
* Holds if `file` may be transitively imported from a file that may serve as the entry point of
* the execution.
*/
private predicate transitively_imported_from_entry_point(File file) {
file.getExtension().matches("%py%") and
exists(File importer |
importer.getParent() = file.getParent() and
exists(ImportExpr i | i.getLocation().getFile() = importer and i.getName() = file.getStem())
|
importer.maybeExecutedDirectly() or transitively_imported_from_entry_point(importer)
)
}
string moduleNameFromFile(Container file) {
exists(string basename |
basename = moduleNameFromBase(file) and
@@ -208,9 +222,10 @@ string moduleNameFromFile(Container file) {
|
result = moduleNameFromFile(file.getParent()) + "." + basename
or
// If execution can start in the folder containing this module, then we will assume `file` can
// be imported as an absolute import, and hence return `basename` as a possible name.
file.getParent().(Folder).mayContainEntryPoint() and result = basename
// If `file` is a transitive import of a file that's executed directly, we allow references
// to it by its `basename`.
transitively_imported_from_entry_point(file) and
result = basename
)
or
isPotentialSourcePackage(file) and

View File

@@ -1,5 +1,3 @@
| main | hash_bang/main.py:0:0:0:0 | Script main |
| main | name_main/main.py:0:0:0:0 | Module main |
| module | hash_bang/module.py:0:0:0:0 | Module module |
| module | name_main/module.py:0:0:0:0 | Module module |
| package | hash_bang/package:0:0:0:0 | Package package |