| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import ast |
| 6 |
import collections |
| 7 |
import os |
| 8 |
import sys |
| 9 |
|
| 10 |
import typing |
| 11 |
|
| 12 |
|
| 13 |
# Import a minimal set of stdlib modules needed for list_stdlib_modules() |
| 14 |
# to work when run from a virtualenv. The modules were chosen empirically |
| 15 |
# so that the return value matches the return value without virtualenv. |
| 16 |
if True: # disable lexical sorting checks |
| 17 |
import argparse |
| 18 |
import zlib |
| 19 |
|
| 20 |
import testparseutil |
| 21 |
|
| 22 |
if typing.TYPE_CHECKING: |
| 23 |
from typing import Iterator |
| 24 |
|
| 25 |
ImportDictT = dict[str, list[str]] |
| 26 |
# source code, modename, filename, line (embedded-only) |
| 27 |
SourceT = tuple[bytes, str, str, int] |
| 28 |
|
| 29 |
# Allow list of modules that symbols can be directly imported from. |
| 30 |
allowsymbolimports = ( |
| 31 |
'__future__', |
| 32 |
'breezy', |
| 33 |
'concurrent', |
| 34 |
'hgclient', |
| 35 |
'packaging.version', |
| 36 |
'mercurial', |
| 37 |
'mercurial.hgweb.common', |
| 38 |
'mercurial.hgweb.request', |
| 39 |
# allows import to the hgweb*_mod_inner module to accomodate the external |
| 40 |
# entry points. |
| 41 |
'mercurial.hgweb.hgweb_mod_inner', |
| 42 |
'mercurial.hgweb.hgwebdir_mod_inner', |
| 43 |
'mercurial.hgweb.wsgicgi_inner', |
| 44 |
'mercurial.i18n', |
| 45 |
'mercurial.interfaces', |
| 46 |
'mercurial.interfaces._basetypes', |
| 47 |
'mercurial.interfaces.types', |
| 48 |
'mercurial.node', |
| 49 |
'mercurial.pycompat', |
| 50 |
# for revlog to re-export constant to extensions |
| 51 |
'mercurial.revlogutils.constants', |
| 52 |
'mercurial.revlogutils.flagutil', |
| 53 |
# for cffi modules to re-export pure functions |
| 54 |
'mercurial.pure.base85', |
| 55 |
'mercurial.pure.bdiff', |
| 56 |
'mercurial.pure.mpatch', |
| 57 |
'mercurial.pure.osutil', |
| 58 |
'mercurial.pure.parsers', |
| 59 |
# third-party imports should be directly imported |
| 60 |
'mercurial.thirdparty', |
| 61 |
'mercurial.thirdparty.attr', |
| 62 |
'mercurial.thirdparty.jaraco.collections', |
| 63 |
'mercurial.thirdparty.tomli', |
| 64 |
'typing', |
| 65 |
'xml.etree.ElementTree', |
| 66 |
) |
| 67 |
|
| 68 |
# Allow list of symbols that can be directly imported. |
| 69 |
directsymbols = ('demandimport',) |
| 70 |
|
| 71 |
# Modules that must be aliased because they are commonly confused with |
| 72 |
# common variables and can create aliasing and readability issues. |
| 73 |
requirealias = { |
| 74 |
'ui': 'uimod', |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
def walklocal(root): |
| 79 |
"""Recursively yield all descendant nodes but not in a different scope""" |
| 80 |
todo = collections.deque(ast.iter_child_nodes(root)) |
| 81 |
yield root, False |
| 82 |
while todo: |
| 83 |
node = todo.popleft() |
| 84 |
newscope = isinstance(node, ast.FunctionDef) |
| 85 |
if not newscope: |
| 86 |
todo.extend(ast.iter_child_nodes(node)) |
| 87 |
yield node, newscope |
| 88 |
|
| 89 |
|
| 90 |
def dotted_name_of_path(path: str) -> str: |
| 91 |
"""Given a relative path to a source file, return its dotted module name. |
| 92 |
|
| 93 |
>>> dotted_name_of_path('mercurial/error.py') |
| 94 |
'mercurial.error' |
| 95 |
>>> dotted_name_of_path('zlibmodule.so') |
| 96 |
'zlib' |
| 97 |
""" |
| 98 |
parts = path.replace(os.sep, '/').split('/') |
| 99 |
parts[-1] = parts[-1].split('.', 1)[0] # remove .py and .so and .ARCH.so |
| 100 |
if parts[-1].endswith('module'): |
| 101 |
parts[-1] = parts[-1][:-6] |
| 102 |
return '.'.join(parts) |
| 103 |
|
| 104 |
|
| 105 |
def fromlocalfunc(modulename, localmods): |
| 106 |
"""Get a function to examine which locally defined module the |
| 107 |
target source imports via a specified name. |
| 108 |
|
| 109 |
`modulename` is an `dotted_name_of_path()`-ed source file path, |
| 110 |
which may have `.__init__` at the end of it, of the target source. |
| 111 |
|
| 112 |
`localmods` is a set of absolute `dotted_name_of_path()`-ed source file |
| 113 |
paths of locally defined (= Mercurial specific) modules. |
| 114 |
|
| 115 |
This function assumes that module names not existing in |
| 116 |
`localmods` are from the Python standard library. |
| 117 |
|
| 118 |
This function returns the function, which takes `name` argument, |
| 119 |
and returns `(absname, dottedpath, hassubmod)` tuple if `name` |
| 120 |
matches against locally defined module. Otherwise, it returns |
| 121 |
False. |
| 122 |
|
| 123 |
It is assumed that `name` doesn't have `.__init__`. |
| 124 |
|
| 125 |
`absname` is an absolute module name of specified `name` |
| 126 |
(e.g. "hgext.convert"). This can be used to compose prefix for sub |
| 127 |
modules or so. |
| 128 |
|
| 129 |
`dottedpath` is a `dotted_name_of_path()`-ed source file path |
| 130 |
(e.g. "hgext.convert.__init__") of `name`. This is used to look |
| 131 |
module up in `localmods` again. |
| 132 |
|
| 133 |
`hassubmod` is whether it may have sub modules under it (for |
| 134 |
convenient, even though this is also equivalent to "absname != |
| 135 |
dottednpath") |
| 136 |
|
| 137 |
>>> localmods = {'foo.__init__', 'foo.foo1', |
| 138 |
... 'foo.bar.__init__', 'foo.bar.bar1', |
| 139 |
... 'baz.__init__', 'baz.baz1'} |
| 140 |
>>> fromlocal = fromlocalfunc('foo.xxx', localmods) |
| 141 |
>>> # relative |
| 142 |
>>> fromlocal('foo1') |
| 143 |
('foo.foo1', 'foo.foo1', False) |
| 144 |
>>> fromlocal('bar') |
| 145 |
('foo.bar', 'foo.bar.__init__', True) |
| 146 |
>>> fromlocal('bar.bar1') |
| 147 |
('foo.bar.bar1', 'foo.bar.bar1', False) |
| 148 |
>>> # absolute |
| 149 |
>>> fromlocal('baz') |
| 150 |
('baz', 'baz.__init__', True) |
| 151 |
>>> fromlocal('baz.baz1') |
| 152 |
('baz.baz1', 'baz.baz1', False) |
| 153 |
>>> # unknown = maybe standard library |
| 154 |
>>> fromlocal('os') |
| 155 |
False |
| 156 |
>>> fromlocal(None, 1) |
| 157 |
('foo', 'foo.__init__', True) |
| 158 |
>>> fromlocal('foo1', 1) |
| 159 |
('foo.foo1', 'foo.foo1', False) |
| 160 |
>>> fromlocal2 = fromlocalfunc('foo.xxx.yyy', localmods) |
| 161 |
>>> fromlocal2(None, 2) |
| 162 |
('foo', 'foo.__init__', True) |
| 163 |
>>> fromlocal2('bar2', 1) |
| 164 |
False |
| 165 |
>>> fromlocal2('bar', 2) |
| 166 |
('foo.bar', 'foo.bar.__init__', True) |
| 167 |
""" |
| 168 |
if not isinstance(modulename, str): |
| 169 |
modulename = modulename.decode('ascii') |
| 170 |
prefix = '.'.join(modulename.split('.')[:-1]) |
| 171 |
if prefix: |
| 172 |
prefix += '.' |
| 173 |
|
| 174 |
def fromlocal(name, level=0): |
| 175 |
# name is false value when relative imports are used. |
| 176 |
if not name: |
| 177 |
# If relative imports are used, level must not be absolute. |
| 178 |
assert level > 0 |
| 179 |
candidates = ['.'.join(modulename.split('.')[:-level])] |
| 180 |
else: |
| 181 |
if not level: |
| 182 |
# Check relative name first. |
| 183 |
candidates = [prefix + name, name] |
| 184 |
else: |
| 185 |
candidates = [ |
| 186 |
'.'.join(modulename.split('.')[:-level]) + '.' + name |
| 187 |
] |
| 188 |
|
| 189 |
for n in candidates: |
| 190 |
if n in localmods: |
| 191 |
return (n, n, False) |
| 192 |
dottedpath = n + '.__init__' |
| 193 |
if dottedpath in localmods: |
| 194 |
return (n, dottedpath, True) |
| 195 |
return False |
| 196 |
|
| 197 |
return fromlocal |
| 198 |
|
| 199 |
|
| 200 |
def populateextmods(localmods): |
| 201 |
"""Populate C extension modules based on pure modules""" |
| 202 |
newlocalmods = set(localmods) |
| 203 |
for n in localmods: |
| 204 |
if n.startswith('mercurial.pure.'): |
| 205 |
m = n[len('mercurial.pure.') :] |
| 206 |
newlocalmods.add('mercurial.cext.' + m) |
| 207 |
newlocalmods.add('mercurial.cffi._' + m) |
| 208 |
return newlocalmods |
| 209 |
|
| 210 |
|
| 211 |
def list_stdlib_modules(): |
| 212 |
"""List the modules present in the stdlib. |
| 213 |
|
| 214 |
>>> mods = set(list_stdlib_modules()) |
| 215 |
>>> 'http' in mods |
| 216 |
True |
| 217 |
|
| 218 |
os.path isn't really a module, so it's missing: |
| 219 |
|
| 220 |
>>> 'os.path' in mods |
| 221 |
False |
| 222 |
|
| 223 |
sys requires special treatment, because it's baked into the |
| 224 |
interpreter, but it should still appear: |
| 225 |
|
| 226 |
>>> 'sys' in mods |
| 227 |
True |
| 228 |
|
| 229 |
>>> 'collections' in mods |
| 230 |
True |
| 231 |
|
| 232 |
>>> 'array' in mods |
| 233 |
True |
| 234 |
|
| 235 |
>>> 'cffi' in mods |
| 236 |
True |
| 237 |
""" |
| 238 |
yield from sys.builtin_module_names |
| 239 |
# These modules only exist on windows, but we should always |
| 240 |
# consider them stdlib. |
| 241 |
yield from ['msvcrt', '_winreg'] |
| 242 |
yield '__builtin__' |
| 243 |
yield 'builtins' # python3 only |
| 244 |
yield 'importlib.abc' # python3 only |
| 245 |
yield 'importlib.machinery' # python3 only |
| 246 |
yield 'importlib.util' # python3 only |
| 247 |
yield 'packaging.version' |
| 248 |
yield from ['fcntl', 'grp', 'pwd', 'select', 'termios'] |
| 249 |
yield from ['cPickle', 'datetime'] |
| 250 |
yield from ['cffi'] |
| 251 |
stdlib_prefixes = {sys.prefix, sys.exec_prefix} |
| 252 |
# We need to supplement the list of prefixes for the search to work |
| 253 |
# when run from within a virtualenv. |
| 254 |
for mod in (argparse, zlib): |
| 255 |
if mod is None: |
| 256 |
continue |
| 257 |
try: |
| 258 |
# Not all module objects have a __file__ attribute. |
| 259 |
filename = mod.__file__ |
| 260 |
except AttributeError: |
| 261 |
continue |
| 262 |
dirname = os.path.dirname(filename) |
| 263 |
for prefix in stdlib_prefixes: |
| 264 |
if dirname.startswith(prefix): |
| 265 |
# Then this directory is redundant. |
| 266 |
break |
| 267 |
else: |
| 268 |
stdlib_prefixes.add(dirname) |
| 269 |
sourceroot = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) |
| 270 |
for libpath in sys.path: |
| 271 |
# We want to walk everything in sys.path that starts with something in |
| 272 |
# stdlib_prefixes, but not directories from the hg sources. |
| 273 |
if os.path.abspath(libpath).startswith(sourceroot) or not any( |
| 274 |
libpath.startswith(p) for p in stdlib_prefixes |
| 275 |
): |
| 276 |
continue |
| 277 |
for top, dirs, files in os.walk(libpath): |
| 278 |
if 'dist-packages' in top.split(os.path.sep): |
| 279 |
continue |
| 280 |
for i, d in reversed(list(enumerate(dirs))): |
| 281 |
if ( |
| 282 |
not os.path.exists(os.path.join(top, d, '__init__.py')) |
| 283 |
or top == libpath |
| 284 |
and d in ('hgdemandimport', 'hgext', 'mercurial') |
| 285 |
): |
| 286 |
del dirs[i] |
| 287 |
for name in files: |
| 288 |
if not name.endswith(('.py', '.so', '.pyc', '.pyo', '.pyd')): |
| 289 |
continue |
| 290 |
if name.startswith('__init__.py'): |
| 291 |
full_path = top |
| 292 |
else: |
| 293 |
full_path = os.path.join(top, name) |
| 294 |
rel_path = full_path[len(libpath) + 1 :] |
| 295 |
mod = dotted_name_of_path(rel_path) |
| 296 |
yield mod |
| 297 |
|
| 298 |
|
| 299 |
stdlib_modules = set(list_stdlib_modules()) |
| 300 |
|
| 301 |
|
| 302 |
def imported_modules(source, modulename, f, localmods, ignore_nested=False): |
| 303 |
"""Given the source of a file as a string, yield the names |
| 304 |
imported by that file. |
| 305 |
|
| 306 |
Args: |
| 307 |
source: The python source to examine as a string. |
| 308 |
modulename: of specified python source (may have `__init__`) |
| 309 |
localmods: set of locally defined module names (may have `__init__`) |
| 310 |
ignore_nested: If true, import statements that do not start in |
| 311 |
column zero will be ignored. |
| 312 |
|
| 313 |
Returns: |
| 314 |
A list of absolute module names imported by the given source. |
| 315 |
|
| 316 |
>>> f = 'foo/xxx.py' |
| 317 |
>>> modulename = 'foo.xxx' |
| 318 |
>>> localmods = {'foo.__init__': True, |
| 319 |
... 'foo.foo1': True, 'foo.foo2': True, |
| 320 |
... 'foo.bar.__init__': True, 'foo.bar.bar1': True, |
| 321 |
... 'baz.__init__': True, 'baz.baz1': True } |
| 322 |
>>> # standard library (= not locally defined ones) |
| 323 |
>>> sorted(imported_modules( |
| 324 |
... 'from stdlib1 import foo, bar; import stdlib2', |
| 325 |
... modulename, f, localmods)) |
| 326 |
[] |
| 327 |
>>> # relative importing |
| 328 |
>>> sorted(imported_modules( |
| 329 |
... 'import foo1; from bar import bar1', |
| 330 |
... modulename, f, localmods)) |
| 331 |
['foo.bar.bar1', 'foo.foo1'] |
| 332 |
>>> sorted(imported_modules( |
| 333 |
... 'from bar.bar1 import name1, name2, name3', |
| 334 |
... modulename, f, localmods)) |
| 335 |
['foo.bar.bar1'] |
| 336 |
>>> # absolute importing |
| 337 |
>>> sorted(imported_modules( |
| 338 |
... 'from baz import baz1, name1', |
| 339 |
... modulename, f, localmods)) |
| 340 |
['baz.__init__', 'baz.baz1'] |
| 341 |
>>> # mixed importing, even though it shouldn't be recommended |
| 342 |
>>> sorted(imported_modules( |
| 343 |
... 'import stdlib, foo1, baz', |
| 344 |
... modulename, f, localmods)) |
| 345 |
['baz.__init__', 'foo.foo1'] |
| 346 |
>>> # ignore_nested |
| 347 |
>>> sorted(imported_modules( |
| 348 |
... '''import foo |
| 349 |
... def wat(): |
| 350 |
... import bar |
| 351 |
... ''', modulename, f, localmods)) |
| 352 |
['foo.__init__', 'foo.bar.__init__'] |
| 353 |
>>> sorted(imported_modules( |
| 354 |
... '''import foo |
| 355 |
... def wat(): |
| 356 |
... import bar |
| 357 |
... ''', modulename, f, localmods, ignore_nested=True)) |
| 358 |
['foo.__init__'] |
| 359 |
""" |
| 360 |
fromlocal = fromlocalfunc(modulename, localmods) |
| 361 |
for node in ast.walk(ast.parse(source, f)): |
| 362 |
if ignore_nested and getattr(node, 'col_offset', 0) > 0: |
| 363 |
continue |
| 364 |
if isinstance(node, ast.Import): |
| 365 |
for n in node.names: |
| 366 |
found = fromlocal(n.name) |
| 367 |
if not found: |
| 368 |
# this should import standard library |
| 369 |
continue |
| 370 |
yield found[1] |
| 371 |
elif isinstance(node, ast.ImportFrom): |
| 372 |
found = fromlocal(node.module, node.level) |
| 373 |
if not found: |
| 374 |
# this should import standard library |
| 375 |
continue |
| 376 |
|
| 377 |
absname, dottedpath, hassubmod = found |
| 378 |
if not hassubmod: |
| 379 |
# "dottedpath" is not a package; must be imported |
| 380 |
yield dottedpath |
| 381 |
# examination of "node.names" should be redundant |
| 382 |
# e.g.: from mercurial.node import nullid, nullrev |
| 383 |
continue |
| 384 |
|
| 385 |
modnotfound = False |
| 386 |
prefix = absname + '.' |
| 387 |
for n in node.names: |
| 388 |
found = fromlocal(prefix + n.name) |
| 389 |
if not found: |
| 390 |
# this should be a function or a property of "node.module" |
| 391 |
modnotfound = True |
| 392 |
continue |
| 393 |
yield found[1] |
| 394 |
if modnotfound and dottedpath != modulename: |
| 395 |
# "dottedpath" is a package, but imported because of non-module |
| 396 |
# lookup |
| 397 |
# specifically allow "from . import foo" from __init__.py |
| 398 |
yield dottedpath |
| 399 |
|
| 400 |
|
| 401 |
def verify_import_convention(module, source, localmods): |
| 402 |
"""Verify imports match our established coding convention.""" |
| 403 |
root = ast.parse(source) |
| 404 |
|
| 405 |
return verify_modern_convention(module, root, localmods) |
| 406 |
|
| 407 |
|
| 408 |
def verify_modern_convention( |
| 409 |
module, |
| 410 |
root, |
| 411 |
localmods, |
| 412 |
root_col_offset=0, |
| 413 |
warn_local=False, |
| 414 |
local_main_prefix='mercurial', |
| 415 |
): |
| 416 |
"""Verify a file conforms to the modern import convention rules. |
| 417 |
|
| 418 |
The rules of the modern convention are: |
| 419 |
|
| 420 |
* Ordering is stdlib followed by local imports. Each group is lexically |
| 421 |
sorted. |
| 422 |
* Importing multiple modules via "import X, Y" is not allowed: use |
| 423 |
separate import statements. |
| 424 |
* Importing multiple modules via "from X import ..." is allowed if using |
| 425 |
parenthesis and one entry per line. |
| 426 |
* Only 1 relative import statement per import level ("from .", "from ..") |
| 427 |
is allowed. |
| 428 |
* Relative imports from higher levels must occur before lower levels. e.g. |
| 429 |
"from .." must be before "from .". |
| 430 |
* Imports from peer packages should use relative import (e.g. do not |
| 431 |
"import mercurial.foo" from a "mercurial.*" module). |
| 432 |
* Symbols can only be imported from specific modules (see |
| 433 |
`allowsymbolimports`). For other modules, first import the module then |
| 434 |
assign the symbol to a module-level variable. In addition, these imports |
| 435 |
must be performed before other local imports. This rule only |
| 436 |
applies to import statements outside of any blocks. |
| 437 |
* Relative imports from the standard library are not allowed, unless that |
| 438 |
library is also a local module. |
| 439 |
* Certain modules must be aliased to alternate names to avoid aliasing |
| 440 |
and readability problems. See `requirealias`. |
| 441 |
""" |
| 442 |
if not isinstance(module, str): |
| 443 |
module = module.decode('ascii') |
| 444 |
topmodule = module.split('.')[0] |
| 445 |
fromlocal = fromlocalfunc(module, localmods) |
| 446 |
|
| 447 |
# Whether a local/non-stdlib import has been performed. |
| 448 |
seenlocal = None |
| 449 |
# Whether a local/non-stdlib, non-symbol import has been seen. |
| 450 |
seennonsymbollocal = False |
| 451 |
# The last name to be imported (for sorting). |
| 452 |
lastname = None |
| 453 |
laststdlib = None |
| 454 |
# Relative import levels encountered so far. |
| 455 |
seenlevels = set() |
| 456 |
|
| 457 |
for node, newscope in walklocal(root): |
| 458 |
|
| 459 |
def msg(fmt, *args): |
| 460 |
return (fmt % args, node.lineno) |
| 461 |
|
| 462 |
if newscope: |
| 463 |
# Check for local imports in function |
| 464 |
yield from verify_modern_convention( |
| 465 |
module, |
| 466 |
node, |
| 467 |
localmods, |
| 468 |
node.col_offset + 4, |
| 469 |
warn_local=topmodule == local_main_prefix, |
| 470 |
) |
| 471 |
elif isinstance(node, ast.Import): |
| 472 |
# Disallow "import foo, bar" and require separate imports |
| 473 |
# for each module. |
| 474 |
if len(node.names) > 1: |
| 475 |
yield msg( |
| 476 |
'multiple imported names: %s', |
| 477 |
', '.join(n.name for n in node.names), |
| 478 |
) |
| 479 |
|
| 480 |
name = node.names[0].name |
| 481 |
asname = node.names[0].asname |
| 482 |
|
| 483 |
stdlib = name in stdlib_modules |
| 484 |
|
| 485 |
# Ignore sorting rules on imports inside blocks. |
| 486 |
if node.col_offset == root_col_offset: |
| 487 |
if lastname and name < lastname and laststdlib == stdlib: |
| 488 |
yield msg( |
| 489 |
'imports not lexically sorted: %s < %s', name, lastname |
| 490 |
) |
| 491 |
|
| 492 |
lastname = name |
| 493 |
laststdlib = stdlib |
| 494 |
|
| 495 |
# stdlib imports should be before local imports. |
| 496 |
if stdlib and seenlocal and node.col_offset == root_col_offset: |
| 497 |
yield msg( |
| 498 |
'stdlib import "%s" follows local import: %s', |
| 499 |
name, |
| 500 |
seenlocal, |
| 501 |
) |
| 502 |
|
| 503 |
if not stdlib: |
| 504 |
seenlocal = name |
| 505 |
|
| 506 |
# Import of sibling modules should use relative imports. |
| 507 |
topname = name.split('.')[0] |
| 508 |
if topname == topmodule: |
| 509 |
yield msg('import should be relative: %s', name) |
| 510 |
|
| 511 |
if name in requirealias and asname != requirealias[name]: |
| 512 |
yield msg( |
| 513 |
'%s module must be "as" aliased to %s', |
| 514 |
name, |
| 515 |
requirealias[name], |
| 516 |
) |
| 517 |
# note all function level import are bad, but as this check is |
| 518 |
# added most of them are. See rational explained in e703ef157565. |
| 519 |
# |
| 520 |
# When all import cycle induced by this pattern are gone, we might |
| 521 |
# consider relaxing this check for the case where function level |
| 522 |
# import really help. |
| 523 |
if warn_local and name.startswith(local_main_prefix): |
| 524 |
yield msg('function level import: %s', name) |
| 525 |
|
| 526 |
elif isinstance(node, ast.ImportFrom): |
| 527 |
# Resolve the full imported module name. |
| 528 |
if node.level > 0: |
| 529 |
fullname = '.'.join(module.split('.')[: -node.level]) |
| 530 |
if node.module: |
| 531 |
fullname += '.%s' % node.module |
| 532 |
else: |
| 533 |
assert node.module |
| 534 |
fullname = node.module |
| 535 |
|
| 536 |
topname = fullname.split('.')[0] |
| 537 |
if topname == topmodule: |
| 538 |
yield msg('import should be relative: %s', fullname) |
| 539 |
|
| 540 |
# __future__ is special since it needs to come first and use |
| 541 |
# symbol import. |
| 542 |
if fullname != '__future__': |
| 543 |
if not fullname or ( |
| 544 |
fullname in stdlib_modules |
| 545 |
# allow standard 'from typing import ...' style |
| 546 |
and fullname.startswith('.') |
| 547 |
and fullname not in localmods |
| 548 |
and fullname + '.__init__' not in localmods |
| 549 |
): |
| 550 |
yield msg('relative import of stdlib module') |
| 551 |
else: |
| 552 |
seenlocal = fullname |
| 553 |
|
| 554 |
# Direct symbol import is only allowed from certain modules and |
| 555 |
# must occur before non-symbol imports. |
| 556 |
found = fromlocal(node.module, node.level) |
| 557 |
if found and found[2]: # node.module is a package |
| 558 |
prefix = found[0] + '.' |
| 559 |
symbols = ( |
| 560 |
n.name for n in node.names if not fromlocal(prefix + n.name) |
| 561 |
) |
| 562 |
else: |
| 563 |
symbols = (n.name for n in node.names) |
| 564 |
symbols = [sym for sym in symbols if sym not in directsymbols] |
| 565 |
if node.module and node.col_offset == root_col_offset: |
| 566 |
if symbols and fullname not in allowsymbolimports: |
| 567 |
yield msg( |
| 568 |
'direct symbol import %s from %s', |
| 569 |
', '.join(symbols), |
| 570 |
fullname, |
| 571 |
) |
| 572 |
|
| 573 |
if symbols and seennonsymbollocal: |
| 574 |
yield msg( |
| 575 |
'symbol import follows non-symbol import: %s', fullname |
| 576 |
) |
| 577 |
if not symbols and fullname not in stdlib_modules: |
| 578 |
seennonsymbollocal = True |
| 579 |
|
| 580 |
if not node.module: |
| 581 |
assert node.level |
| 582 |
|
| 583 |
# Only allow 1 group per level. |
| 584 |
if ( |
| 585 |
node.level in seenlevels |
| 586 |
and node.col_offset == root_col_offset |
| 587 |
): |
| 588 |
yield msg( |
| 589 |
'multiple "from %s import" statements', '.' * node.level |
| 590 |
) |
| 591 |
|
| 592 |
# Higher-level groups come before lower-level groups. |
| 593 |
if any(node.level > l for l in seenlevels): |
| 594 |
yield msg( |
| 595 |
'higher-level import should come first: %s', fullname |
| 596 |
) |
| 597 |
|
| 598 |
seenlevels.add(node.level) |
| 599 |
|
| 600 |
# Entries in "from .X import ( ... )" lists must be lexically |
| 601 |
# sorted. |
| 602 |
lastentryname = None |
| 603 |
|
| 604 |
for n in node.names: |
| 605 |
if lastentryname and n.name < lastentryname: |
| 606 |
yield msg( |
| 607 |
'imports from %s not lexically sorted: %s < %s', |
| 608 |
fullname, |
| 609 |
n.name, |
| 610 |
lastentryname, |
| 611 |
) |
| 612 |
|
| 613 |
lastentryname = n.name |
| 614 |
|
| 615 |
if n.name in requirealias and n.asname != requirealias[n.name]: |
| 616 |
yield msg( |
| 617 |
'%s from %s must be "as" aliased to %s', |
| 618 |
n.name, |
| 619 |
fullname, |
| 620 |
requirealias[n.name], |
| 621 |
) |
| 622 |
# note all function level import are bad, but as this check is |
| 623 |
# added most of them are. See rational explained in e703ef157565. |
| 624 |
# |
| 625 |
# When all import cycle induced by this pattern are gone, we might |
| 626 |
# consider relaxing this check for the case where function level |
| 627 |
# import really help. |
| 628 |
if warn_local and found: |
| 629 |
yield msg('function level import: %s.%s', fullname, n.name) |
| 630 |
|
| 631 |
|
| 632 |
class CircularImport(Exception): |
| 633 |
pass |
| 634 |
|
| 635 |
|
| 636 |
def checkmod(mod: str, imports: ImportDictT) -> None: |
| 637 |
shortest: dict[str, int] = {} |
| 638 |
visit: list[list[str]] = [[mod]] |
| 639 |
while visit: |
| 640 |
path = visit.pop(0) |
| 641 |
for i in sorted(imports.get(path[-1], [])): |
| 642 |
if len(path) < shortest.get(i, 1000): |
| 643 |
shortest[i] = len(path) |
| 644 |
if i in path: |
| 645 |
if i == path[0]: |
| 646 |
raise CircularImport(path) |
| 647 |
continue |
| 648 |
visit.append(path + [i]) |
| 649 |
|
| 650 |
|
| 651 |
def rotatecycle(cycle: list[str]) -> list[str]: |
| 652 |
"""arrange a cycle so that the lexicographically first module listed first |
| 653 |
|
| 654 |
>>> rotatecycle(['foo', 'bar']) |
| 655 |
['bar', 'foo', 'bar'] |
| 656 |
""" |
| 657 |
lowest = min(cycle) |
| 658 |
idx = cycle.index(lowest) |
| 659 |
return cycle[idx:] + cycle[:idx] + [lowest] |
| 660 |
|
| 661 |
|
| 662 |
def find_cycles(imports: ImportDictT) -> set[str]: |
| 663 |
"""Find cycles in an already-loaded import graph. |
| 664 |
|
| 665 |
All module names recorded in `imports` should be absolute one. |
| 666 |
|
| 667 |
>>> imports = {'top.foo': ['top.bar', 'os.path', 'top.qux'], |
| 668 |
... 'top.bar': ['top.baz', 'sys'], |
| 669 |
... 'top.baz': ['top.foo'], |
| 670 |
... 'top.qux': ['top.foo']} |
| 671 |
>>> print('\\n'.join(sorted(find_cycles(imports)))) |
| 672 |
top.bar -> top.baz -> top.foo -> top.bar |
| 673 |
top.foo -> top.qux -> top.foo |
| 674 |
""" |
| 675 |
cycles = set() |
| 676 |
for mod in sorted(imports.keys()): |
| 677 |
try: |
| 678 |
checkmod(mod, imports) |
| 679 |
except CircularImport as e: |
| 680 |
cycle: list[str] = e.args[0] |
| 681 |
cycles.add(" -> ".join(rotatecycle(cycle))) |
| 682 |
return cycles |
| 683 |
|
| 684 |
|
| 685 |
def _cycle_sortkey(c): |
| 686 |
return len(c), c |
| 687 |
|
| 688 |
|
| 689 |
def embedded(f, modname, src) -> Iterator[SourceT]: |
| 690 |
"""Extract embedded python code |
| 691 |
|
| 692 |
>>> def _forcestr(thing): |
| 693 |
... if not isinstance(thing, str): |
| 694 |
... return thing.decode('ascii') |
| 695 |
... return thing |
| 696 |
>>> def test(fn, lines): |
| 697 |
... for s, m, f, l in embedded(fn, b"example", lines): |
| 698 |
... print("%s %s %d" % (_forcestr(m), _forcestr(f), l)) |
| 699 |
... print(repr(_forcestr(s))) |
| 700 |
>>> lines = [ |
| 701 |
... 'comment', |
| 702 |
... ' >>> from __future__ import print_function', |
| 703 |
... " >>> ' multiline", |
| 704 |
... " ... string'", |
| 705 |
... ' ', |
| 706 |
... 'comment', |
| 707 |
... ' $ cat > foo.py <<EOF', |
| 708 |
... ' > from __future__ import print_function', |
| 709 |
... ' > EOF', |
| 710 |
... ] |
| 711 |
>>> test(b"example.t", lines) |
| 712 |
example[2] doctest.py 1 |
| 713 |
"from __future__ import print_function\\n' multiline\\nstring'\\n\\n" |
| 714 |
example[8] foo.py 7 |
| 715 |
'from __future__ import print_function\\n' |
| 716 |
""" |
| 717 |
errors: list[str] = [] |
| 718 |
for name, starts, ends, code in testparseutil.pyembedded(f, src, errors): |
| 719 |
if not name: |
| 720 |
# use 'doctest.py', in order to make already existing |
| 721 |
# doctest above pass instantly |
| 722 |
name = 'doctest.py' |
| 723 |
# "starts" is "line number" (1-origin), but embedded() is |
| 724 |
# expected to return "line offset" (0-origin). Therefore, this |
| 725 |
# yields "starts - 1". |
| 726 |
if not isinstance(modname, str): |
| 727 |
modname = modname.decode('utf8') |
| 728 |
yield code, "%s[%d]" % (modname, starts), name, starts - 1 |
| 729 |
|
| 730 |
|
| 731 |
def sources(f: str, modname: str) -> Iterator[SourceT]: |
| 732 |
"""Yields possibly multiple sources from a filepath |
| 733 |
|
| 734 |
input: filepath, modulename |
| 735 |
yields: script(string), modulename, filepath, linenumber |
| 736 |
|
| 737 |
For embedded scripts, the modulename and filepath will be different |
| 738 |
from the function arguments. linenumber is an offset relative to |
| 739 |
the input file. |
| 740 |
""" |
| 741 |
py = False |
| 742 |
if not f.endswith('.t'): |
| 743 |
with open(f, 'rb') as src: |
| 744 |
yield src.read(), modname, f, 0 |
| 745 |
py = True |
| 746 |
if py or f.endswith('.t'): |
| 747 |
# Strictly speaking we should sniff for the magic header that denotes |
| 748 |
# Python source file encoding. But in reality we don't use anything |
| 749 |
# other than ASCII (mainly) and UTF-8 (in a few exceptions), so |
| 750 |
# simplicity is fine. |
| 751 |
with open(f, encoding='utf-8') as src: |
| 752 |
yield from embedded(f, modname, src) |
| 753 |
|
| 754 |
|
| 755 |
def main(argv: list[str]) -> int: |
| 756 |
if len(argv) < 2 or (argv[1] == '-' and len(argv) > 2): |
| 757 |
print('Usage: %s {-|file [file] [file] ...}') |
| 758 |
return 1 |
| 759 |
if argv[1] == '-': |
| 760 |
argv = argv[:1] |
| 761 |
argv.extend(l.rstrip() for l in sys.stdin.readlines()) |
| 762 |
localmodpaths = {} |
| 763 |
used_imports: ImportDictT = {} |
| 764 |
any_errors = False |
| 765 |
for source_path in argv[1:]: |
| 766 |
modname = dotted_name_of_path(source_path) |
| 767 |
localmodpaths[modname] = source_path |
| 768 |
localmods = populateextmods(localmodpaths) |
| 769 |
for localmodname, source_path in sorted(localmodpaths.items()): |
| 770 |
if not isinstance(localmodname, bytes): |
| 771 |
# This is only safe because all hg's files are ascii |
| 772 |
localmodname = localmodname |
| 773 |
for src, modname, name, line in sources(source_path, localmodname): |
| 774 |
try: |
| 775 |
used_imports[modname] = sorted( |
| 776 |
imported_modules( |
| 777 |
src, modname, name, localmods, ignore_nested=False |
| 778 |
) |
| 779 |
) |
| 780 |
for error, lineno in verify_import_convention( |
| 781 |
modname, src, localmods |
| 782 |
): |
| 783 |
any_errors = True |
| 784 |
print('%s:%d: %s' % (source_path, lineno + line, error)) |
| 785 |
except SyntaxError as e: |
| 786 |
assert e.lineno is not None |
| 787 |
print( |
| 788 |
'%s:%d: SyntaxError: %s' % (source_path, e.lineno + line, e) |
| 789 |
) |
| 790 |
cycles = find_cycles(used_imports) |
| 791 |
if cycles: |
| 792 |
firstmods = set() |
| 793 |
for c in sorted(cycles, key=_cycle_sortkey): |
| 794 |
first = c.split()[0] |
| 795 |
# As a rough cut, ignore any cycle that starts with the |
| 796 |
# same module as some other cycle. Otherwise we see lots |
| 797 |
# of cycles that are effectively duplicates. |
| 798 |
if first in firstmods: |
| 799 |
continue |
| 800 |
print('Import cycle:', c) |
| 801 |
firstmods.add(first) |
| 802 |
any_errors = True |
| 803 |
return any_errors != 0 |
| 804 |
|
| 805 |
|
| 806 |
if __name__ == '__main__': |
| 807 |
sys.exit(int(main(sys.argv))) |