Repository: google/importlab

Issue:
Incorrect inferred module name for __init__.py files
See google/pytype#154 for more detail.

`resolve.infer_module_name` calculates the wrong name for `__init__.py` files. For example, for `foo/bar/__init__.py`, it will return `foo.bar.__init__`. The module name should be `foo.bar`.

Discussion:

Patch:
diff --git a/importlab/resolve.py b/importlab/resolve.py
index 23314bc..d55f34d 100644
--- a/importlab/resolve.py
+++ b/importlab/resolve.py
@@ -102,6 +102,9 @@ def infer_module_name(filename, fspath):
     for f in fspath:
         short_name = f.relative_path(filename)
         if short_name:
+            # The module name for __init__.py files is the directory.
+            if short_name.endswith(os.path.sep + "__init__"):
+                short_name = short_name[:short_name.rfind(os.path.sep)]
             return short_name.replace(os.path.sep, '.')
     # We have not found filename relative to anywhere in pythonpath.
     return ''


Test patch:
diff --git a/tests/test_resolve.py b/tests/test_resolve.py
index 2a217d3..9891764 100644
--- a/tests/test_resolve.py
+++ b/tests/test_resolve.py
@@ -293,6 +293,15 @@ class TestResolverUtils(unittest.TestCase):
                     resolve.infer_module_name("/some/random/file", fspath),
                     "")
 
+    def testInferInitModuleName(self):
+        with utils.Tempdir() as d:
+            os_fs = fs.OSFileSystem(d.path)
+            fspath = [os_fs]
+            py_file = d.create_file("foo/__init__.py")
+            self.assertEqual(
+                    resolve.infer_module_name(py_file, fspath),
+                    "foo")
+
     def testGetAbsoluteName(self):
         test_cases = [
                 ("x.y", "a.b", "x.y.a.b"),