Skip to content

Commit 4d61418

Browse files
chernrickgvanrossum
authored andcommitted
Better error message for invalid package names passed to mypy (#3447)
Fixes #2775
1 parent 278a10a commit 4d61418

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

mypy/main.py

+16-2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@
2424
PY_EXTENSIONS = tuple(PYTHON_EXTENSIONS)
2525

2626

27+
class InvalidPackageName(Exception):
28+
"""Exception indicating that a package name was invalid."""
29+
30+
2731
def main(script_path: str, args: List[str] = None) -> None:
2832
"""Main entry point to the type checker.
2933
@@ -459,9 +463,15 @@ def add_invertible_flag(flag: str,
459463
targets = []
460464
for f in special_opts.files:
461465
if f.endswith(PY_EXTENSIONS):
462-
targets.append(BuildSource(f, crawl_up(f)[1], None))
466+
try:
467+
targets.append(BuildSource(f, crawl_up(f)[1], None))
468+
except InvalidPackageName as e:
469+
fail(str(e))
463470
elif os.path.isdir(f):
464-
sub_targets = expand_dir(f)
471+
try:
472+
sub_targets = expand_dir(f)
473+
except InvalidPackageName as e:
474+
fail(str(e))
465475
if not sub_targets:
466476
fail("There are no .py[i] files in directory '{}'"
467477
.format(f))
@@ -528,10 +538,14 @@ def crawl_up(arg: str) -> Tuple[str, str]:
528538
dir, base = os.path.split(dir)
529539
if not base:
530540
break
541+
# Ensure that base is a valid python module name
542+
if not base.isidentifier():
543+
raise InvalidPackageName('{} is not a valid Python package name'.format(base))
531544
if mod == '__init__' or not mod:
532545
mod = base
533546
else:
534547
mod = base + '.' + mod
548+
535549
return dir, mod
536550

537551

test-data/unit/cmdline.test

+8
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,14 @@ undef
7575
dir/subpkg/a.py:1: error: Name 'undef' is not defined
7676
dir/a.py:1: error: Name 'undef' is not defined
7777

78+
[case testCmdlineInvalidPackageName]
79+
# cmd: mypy dir/sub.pkg/a.py
80+
[file dir/sub.pkg/__init__.py]
81+
[file dir/sub.pkg/a.py]
82+
undef
83+
[out]
84+
sub.pkg is not a valid Python package name
85+
7886
[case testBadFileEncoding]
7987
# cmd: mypy a.py
8088
[file a.py]

0 commit comments

Comments
 (0)