Skip to content

Commit dcc7785

Browse files
yofftausbn
andcommitted
Python: refactor code
Also add explanatory comment. Co-authored-by: Taus <[email protected]>
1 parent 50041f0 commit dcc7785

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

python/ql/lib/semmle/python/Module.qll

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -231,17 +231,25 @@ private predicate isRegularPackage(Folder f, string name) {
231231
exists(f.getFile("__init__.py"))
232232
}
233233

234+
/** Gets the name of a module imported in package `c`. */
235+
private string moduleImportedInPackage(Container c) {
236+
legalShortName(result) and
237+
// it has to be imported in this folder
238+
result =
239+
any(ImportExpr i | i.getLocation().getFile().getParent() = c)
240+
.getName()
241+
// strip everything after the first `.`
242+
.regexpReplaceAll("\\..*", "") and
243+
result != ""
244+
}
245+
234246
/** Holds if the file `f` could be resolved to a module named `name`. */
235247
private predicate isPotentialModuleFile(File file, string name) {
236248
legalShortName(name) and
237249
name = file.getStem() and
238250
file.getExtension() = ["py", "pyc", "so", "pyd"] and
239251
// it has to be imported in this folder
240-
name =
241-
any(ImportExpr i | i.getLocation().getFile().getParent() = file.getParent())
242-
.getName()
243-
.regexpReplaceAll("\\..*", "") and
244-
name != ""
252+
name = moduleImportedInPackage(file.getParent())
245253
}
246254

247255
/**
@@ -256,11 +264,7 @@ private predicate isNameSpacePackage(Folder f, string name) {
256264
not isRegularPackage(f, name) and
257265
// it has to be imported in a file
258266
// either in this folder or next to this folder
259-
name =
260-
any(ImportExpr i | i.getLocation().getFile().getParent() in [f, f.getParent()])
261-
.getName()
262-
.regexpReplaceAll("\\..*", "") and
263-
name != "" and
267+
name = moduleImportedInPackage([f, f.getParent()]) and
264268
// no sibling regular package
265269
// and no sibling module
266270
not exists(Folder sibling | sibling.getParent() = f.getParent() |

0 commit comments

Comments
 (0)