Debian Codegraph @

saltpylint/thirdparty.py

raw symbols SCIP
1 """
2 saltpylint.thirdparty
3 ~~~~~~~~~~~~~~~~~~~~~
4
5 Checks all imports against a list of known and allowed 3rd-party modules
6 and raises a lint error if an import not in that known 3rd-party modules list
7 is not gated.
8 """
9
10 import os
11 import pkgutil
12 from typing import ClassVar
13
14 import astroid
15 import astroid.exceptions
16 from astroid.modutils import is_relative
17 from astroid.modutils import is_standard_module
18 from pylint.checkers import BaseChecker
19
20 MSGS = {
21 "W8410": (
22 "3rd-party module import is not gated in a try/except: %r",
23 "3rd-party-module-not-gated",
24 "3rd-party module imported without being gated in a try/except.",
25 ),
26 "C8410": (
27 "3rd-party local module import is not gated in a try/except: %r. "
28 "Consider importing at the module global scope level and gate it "
29 "in a try/except.",
30 "3rd-party-local-module-not-gated",
31 "3rd-party module locally imported without being gated. Consider importing "
32 "at the module global scope level and gate it in a try/except",
33 ),
34 }
35
36
37 def get_import_package(modname):
38 """Return the import package.
39
40 Given modname is 'salt.utils', returns 'salt'
41 """
42 return modname.split(".")[0]
43
44
45 class ThirdPartyImportsChecker(BaseChecker):
46 name = "3rd-party-imports"
47 msgs = MSGS
48 priority = -2
49
50 options = (
51 (
52 "allowed-3rd-party-modules",
53 {
54 "default": (),
55 "type": "csv",
56 "metavar": "<3rd-party-modules>",
57 "help": "Known 3rd-party modules which don' require being gated, separated by a comma",
58 },
59 ),
60 )
61
62 known_py3_modules: ClassVar = ["builtins"]
63
64 unix_modules = (
65 "posix",
66 "pwd",
67 "spwd",
68 "grp",
69 "crypt",
70 "termios",
71 "tty",
72 "pty",
73 "fcntl",
74 "pipes",
75 "resource",
76 "nis",
77 "syslog",
78 "posixpath",
79 )
80 win_modules = ("msilib", "msvcrt", "winreg", "winsound", "ntpath")
81
82 all_modules: ClassVar = {m[1]: m[0] for m in pkgutil.iter_modules()}
83 std_modules_path: ClassVar = all_modules["os"]
84 std_modules: ClassVar = []
85 for mod, path in all_modules.items():
86 if path == std_modules_path and mod not in unix_modules + win_modules:
87 std_modules.append(mod)
88
89 known_std_modules = known_py3_modules + std_modules
90
91 def __init__(self, linter=None) -> None:
92 BaseChecker.__init__(self, linter)
93 self._inside_try_except = False
94 self._inside_funcdef = False
95 self._inside_if = False
96 self.cwd = None
97 self.allowed_3rd_party_modules = []
98
99 def open(self):
100 super().open()
101 self.cwd = os.getcwd()
102 self.allowed_3rd_party_modules = set(
103 self.linter.config.allowed_3rd_party_modules,
104 ) # pylint: disable=no-member
105
106 # pylint: disable=unused-argument
107 def visit_if(self, node):
108 self._inside_if = True
109
110 def leave_if(self, node):
111 self._inside_if = True
112
113 def visit_try(self, node):
114 self._inside_try_except = True
115
116 def leave_try(self, node):
117 self._inside_try_except = False
118
119 def visit_functiondef(self, node):
120 self._inside_funcdef = True
121
122 def leave_functiondef(self, node):
123 self._inside_funcdef = False
124
125 # pylint: enable=unused-argument
126
127 def visit_import(self, node):
128 names = [name for name, _ in node.names]
129 for name in names:
130 self._check_third_party_import(node, name)
131
132 def visit_importfrom(self, node):
133 self._check_third_party_import(node, node.modname)
134
135 def _check_third_party_import(self, node, modname):
136 if modname in self.known_std_modules:
137 # Don't even care about these
138 return
139 module_file = node.root().file
140
141 if is_relative(modname, module_file):
142 # Is the import relative to the curent module being checked
143 return
144
145 base_modname = modname.split(".", 1)[0]
146 import_modname = modname
147 while True:
148 try:
149 imported_module = node.do_import_module(import_modname)
150 if not imported_module:
151 break
152 if imported_module.file.startswith(self.cwd):
153 # This is an import to package under the project being tested
154 return
155 # If we reached this far, we were able to import the module but it's
156 # not considered a module from within the project being checked
157 break
158 except Exception: # pylint: disable=broad-except
159 # This is, for example, from salt.ext.six.moves import Y
160 # Because `moves` is a dynamic/runtime module
161 import_modname = import_modname.rsplit(".", 1)[0]
162
163 if import_modname == base_modname or not import_modname:
164 break
165
166 try:
167 if not is_standard_module(modname) and self._inside_try_except is False:
168 if get_import_package(modname) in self.allowed_3rd_party_modules:
169 return
170 if self._inside_if or self._inside_funcdef:
171 message_id = "3rd-party-local-module-not-gated"
172 else:
173 message_id = "3rd-party-module-not-gated"
174 self.add_message(message_id, node=node, args=modname)
175 except astroid.exceptions.AstroidBuildingException:
176 # Failed to import
177 if self._inside_try_except is False:
178 if get_import_package(modname) in self.allowed_3rd_party_modules:
179 return
180 if self._inside_if or self._inside_funcdef:
181 message_id = "3rd-party-local-module-not-gated"
182 else:
183 message_id = "3rd-party-module-not-gated"
184 self.add_message(message_id, node=node, args=modname)
185 except astroid.exceptions.InferenceError:
186 # Failed to import
187 if self._inside_try_except is False:
188 if get_import_package(modname) in self.allowed_3rd_party_modules:
189 return
190 if self._inside_if or self._inside_funcdef:
191 message_id = "3rd-party-local-module-not-gated"
192 else:
193 message_id = "3rd-party-module-not-gated"
194 self.add_message(message_id, node=node, args=modname)
195 except ImportError:
196 # Definitly not a standard library import
197 if self._inside_try_except is False:
198 if get_import_package(modname) in self.allowed_3rd_party_modules:
199 return
200 if self._inside_if or self._inside_funcdef:
201 message_id = "3rd-party-local-module-not-gated"
202 else:
203 message_id = "3rd-party-module-not-gated"
204 self.add_message(message_id, node=node, args=modname)
205
206
207 def register(linter):
208 """Required method to auto register this checker."""
209 linter.register_checker(ThirdPartyImportsChecker(linter))