Skip to content

Commit

Permalink
Better error message for invalid package names passed to mypy (#3447)
Browse files Browse the repository at this point in the history
Fixes #2775
  • Loading branch information
chernrick authored and gvanrossum committed May 26, 2017
1 parent 278a10a commit 4d61418
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
18 changes: 16 additions & 2 deletions mypy/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
PY_EXTENSIONS = tuple(PYTHON_EXTENSIONS)


class InvalidPackageName(Exception):
"""Exception indicating that a package name was invalid."""


def main(script_path: str, args: List[str] = None) -> None:
"""Main entry point to the type checker.
Expand Down Expand Up @@ -459,9 +463,15 @@ def add_invertible_flag(flag: str,
targets = []
for f in special_opts.files:
if f.endswith(PY_EXTENSIONS):
targets.append(BuildSource(f, crawl_up(f)[1], None))
try:
targets.append(BuildSource(f, crawl_up(f)[1], None))
except InvalidPackageName as e:
fail(str(e))
elif os.path.isdir(f):
sub_targets = expand_dir(f)
try:
sub_targets = expand_dir(f)
except InvalidPackageName as e:
fail(str(e))
if not sub_targets:
fail("There are no .py[i] files in directory '{}'"
.format(f))
Expand Down Expand Up @@ -528,10 +538,14 @@ def crawl_up(arg: str) -> Tuple[str, str]:
dir, base = os.path.split(dir)
if not base:
break
# Ensure that base is a valid python module name
if not base.isidentifier():
raise InvalidPackageName('{} is not a valid Python package name'.format(base))
if mod == '__init__' or not mod:
mod = base
else:
mod = base + '.' + mod

return dir, mod


Expand Down
8 changes: 8 additions & 0 deletions test-data/unit/cmdline.test
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ undef
dir/subpkg/a.py:1: error: Name 'undef' is not defined
dir/a.py:1: error: Name 'undef' is not defined

[case testCmdlineInvalidPackageName]
# cmd: mypy dir/sub.pkg/a.py
[file dir/sub.pkg/__init__.py]
[file dir/sub.pkg/a.py]
undef
[out]
sub.pkg is not a valid Python package name

[case testBadFileEncoding]
# cmd: mypy a.py
[file a.py]
Expand Down

0 comments on commit 4d61418

Please sign in to comment.