diff --git a/mypy/main.py b/mypy/main.py index a5511671c966..7edfff02e119 100644 --- a/mypy/main.py +++ b/mypy/main.py @@ -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. @@ -457,9 +461,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)) @@ -526,10 +536,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 diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index d0648844daaa..a9ba3c28950b 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -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]