We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Unfriendly error message when unicode is passed to package_dir or packages
Originally reported by: **jaraco (Bitbucket: [jaraco](http://bitbucket.org/jaraco), GitHub: [jaraco](http://github.com/jaraco))**

---

Adding `__future__.unicode_literals` causes setup.py scripts to fail. In the mailman project, here is an example error when running python2 setup.py build:

```
running build
running build_py
Traceback (most recent call last):
  File "setup.py", line 112, in <module>
    test_suite = 'nose2.collector.collector',
  File "C:\Program Files\Python27\lib\distutils\core.py", line 152, in setup
    dist.run_commands()
  File "C:\Program Files\Python27\lib\distutils\dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "C:\Program Files\Python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "C:\Program Files\Python27\lib\distutils\command\build.py", line 127, in run
    self.run_command(cmd_name)
  File "C:\Program Files\Python27\lib\distutils\cmd.py", line 326, in run_command
    self.distribution.run_command(command)
  File "C:\Program Files\Python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "build\bdist.win-amd64\egg\setuptools\command\build_py.py", line 42, in run
  File "C:\Program Files\Python27\lib\distutils\command\build_py.py", line 372, in build_packages
    self.build_module(module, module_file, package)
  File "build\bdist.win-amd64\egg\setuptools\command\build_py.py", line 60, in build_module
  File "C:\Program Files\Python27\lib\distutils\command\build_py.py", line 333, in build_module
    "'package' must be a string (dot-separated), list, or tuple")
TypeError: 'package' must be a string (dot-separated), list, or tuple
```

A different error occurs when using 'develop':

```
running develop
error: 'egg_base' must be a directory name (got `src`)
```

Setuptools could make this error message nicer.

---
- Bitbucket: https://bitbucket.org/pypa/setuptools/issue/190


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `setuptools/command/build_py.py`
Content:
```
1 from glob import glob
2 from distutils.util import convert_path
3 import distutils.command.build_py as orig
4 import os
5 import fnmatch
6 import textwrap
7 import io
8 import distutils.errors
9 import itertools
10 
11 from setuptools.extern.six.moves import map, filter, filterfalse
12 
13 try:
14     from setuptools.lib2to3_ex import Mixin2to3
15 except ImportError:
16     class Mixin2to3:
17         def run_2to3(self, files, doctests=True):
18             "do nothing"
19 
20 
21 class build_py(orig.build_py, Mixin2to3):
22     """Enhanced 'build_py' command that includes data files with packages
23 
24     The data files are specified via a 'package_data' argument to 'setup()'.
25     See 'setuptools.dist.Distribution' for more details.
26 
27     Also, this version of the 'build_py' command allows you to specify both
28     'py_modules' and 'packages' in the same setup operation.
29     """
30 
31     def finalize_options(self):
32         orig.build_py.finalize_options(self)
33         self.package_data = self.distribution.package_data
34         self.exclude_package_data = (self.distribution.exclude_package_data or
35                                      {})
36         if 'data_files' in self.__dict__:
37             del self.__dict__['data_files']
38         self.__updated_files = []
39         self.__doctests_2to3 = []
40 
41     def run(self):
42         """Build modules, packages, and copy data files to build directory"""
43         if not self.py_modules and not self.packages:
44             return
45 
46         if self.py_modules:
47             self.build_modules()
48 
49         if self.packages:
50             self.build_packages()
51             self.build_package_data()
52 
53         self.run_2to3(self.__updated_files, False)
54         self.run_2to3(self.__updated_files, True)
55         self.run_2to3(self.__doctests_2to3, True)
56 
57         # Only compile actual .py files, using our base class' idea of what our
58         # output files are.
59         self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))
60 
61     def __getattr__(self, attr):
62         "lazily compute data files"
63         if attr == 'data_files':
64             self.data_files = self._get_data_files()
65             return self.data_files
66         return orig.build_py.__getattr__(self, attr)
67 
68     def build_module(self, module, module_file, package):
69         outfile, copied = orig.build_py.build_module(self, module, module_file,
70                                                      package)
71         if copied:
72             self.__updated_files.append(outfile)
73         return outfile, copied
74 
75     def _get_data_files(self):
76         """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
77         self.analyze_manifest()
78         return list(map(self._get_pkg_data_files, self.packages or ()))
79 
80     def _get_pkg_data_files(self, package):
81         # Locate package source directory
82         src_dir = self.get_package_dir(package)
83 
84         # Compute package build directory
85         build_dir = os.path.join(*([self.build_lib] + package.split('.')))
86 
87         # Strip directory from globbed filenames
88         filenames = [
89             os.path.relpath(file, src_dir)
90             for file in self.find_data_files(package, src_dir)
91         ]
92         return package, src_dir, build_dir, filenames
93 
94     def find_data_files(self, package, src_dir):
95         """Return filenames for package's data files in 'src_dir'"""
96         patterns = self._get_platform_patterns(
97             self.package_data,
98             package,
99             src_dir,
100         )
101         globs_expanded = map(glob, patterns)
102         # flatten the expanded globs into an iterable of matches
103         globs_matches = itertools.chain.from_iterable(globs_expanded)
104         glob_files = filter(os.path.isfile, globs_matches)
105         files = itertools.chain(
106             self.manifest_files.get(package, []),
107             glob_files,
108         )
109         return self.exclude_data_files(package, src_dir, files)
110 
111     def build_package_data(self):
112         """Copy data files into build directory"""
113         for package, src_dir, build_dir, filenames in self.data_files:
114             for filename in filenames:
115                 target = os.path.join(build_dir, filename)
116                 self.mkpath(os.path.dirname(target))
117                 srcfile = os.path.join(src_dir, filename)
118                 outf, copied = self.copy_file(srcfile, target)
119                 srcfile = os.path.abspath(srcfile)
120                 if (copied and
121                         srcfile in self.distribution.convert_2to3_doctests):
122                     self.__doctests_2to3.append(outf)
123 
124     def analyze_manifest(self):
125         self.manifest_files = mf = {}
126         if not self.distribution.include_package_data:
127             return
128         src_dirs = {}
129         for package in self.packages or ():
130             # Locate package source directory
131             src_dirs[assert_relative(self.get_package_dir(package))] = package
132 
133         self.run_command('egg_info')
134         ei_cmd = self.get_finalized_command('egg_info')
135         for path in ei_cmd.filelist.files:
136             d, f = os.path.split(assert_relative(path))
137             prev = None
138             oldf = f
139             while d and d != prev and d not in src_dirs:
140                 prev = d
141                 d, df = os.path.split(d)
142                 f = os.path.join(df, f)
143             if d in src_dirs:
144                 if path.endswith('.py') and f == oldf:
145                     continue  # it's a module, not data
146                 mf.setdefault(src_dirs[d], []).append(path)
147 
148     def get_data_files(self):
149         pass  # Lazily compute data files in _get_data_files() function.
150 
151     def check_package(self, package, package_dir):
152         """Check namespace packages' __init__ for declare_namespace"""
153         try:
154             return self.packages_checked[package]
155         except KeyError:
156             pass
157 
158         init_py = orig.build_py.check_package(self, package, package_dir)
159         self.packages_checked[package] = init_py
160 
161         if not init_py or not self.distribution.namespace_packages:
162             return init_py
163 
164         for pkg in self.distribution.namespace_packages:
165             if pkg == package or pkg.startswith(package + '.'):
166                 break
167         else:
168             return init_py
169 
170         with io.open(init_py, 'rb') as f:
171             contents = f.read()
172         if b'declare_namespace' not in contents:
173             raise distutils.errors.DistutilsError(
174                 "Namespace package problem: %s is a namespace package, but "
175                 "its\n__init__.py does not call declare_namespace()! Please "
176                 'fix it.\n(See the setuptools manual under '
177                 '"Namespace Packages" for details.)\n"' % (package,)
178             )
179         return init_py
180 
181     def initialize_options(self):
182         self.packages_checked = {}
183         orig.build_py.initialize_options(self)
184 
185     def get_package_dir(self, package):
186         res = orig.build_py.get_package_dir(self, package)
187         if self.distribution.src_root is not None:
188             return os.path.join(self.distribution.src_root, res)
189         return res
190 
191     def exclude_data_files(self, package, src_dir, files):
192         """Filter filenames for package's data files in 'src_dir'"""
193         files = list(files)
194         patterns = self._get_platform_patterns(
195             self.exclude_package_data,
196             package,
197             src_dir,
198         )
199         match_groups = (
200             fnmatch.filter(files, pattern)
201             for pattern in patterns
202         )
203         # flatten the groups of matches into an iterable of matches
204         matches = itertools.chain.from_iterable(match_groups)
205         bad = set(matches)
206         keepers = (
207             fn
208             for fn in files
209             if fn not in bad
210         )
211         # ditch dupes
212         return list(_unique_everseen(keepers))
213 
214     @staticmethod
215     def _get_platform_patterns(spec, package, src_dir):
216         """
217         yield platfrom-specific path patterns (suitable for glob
218         or fn_match) from a glob-based spec (such as
219         self.package_data or self.exclude_package_data)
220         matching package in src_dir.
221         """
222         raw_patterns = itertools.chain(
223             spec.get('', []),
224             spec.get(package, []),
225         )
226         return (
227             # Each pattern has to be converted to a platform-specific path
228             os.path.join(src_dir, convert_path(pattern))
229             for pattern in raw_patterns
230         )
231 
232 
233 # from Python docs
234 def _unique_everseen(iterable, key=None):
235     "List unique elements, preserving order. Remember all elements ever seen."
236     # unique_everseen('AAAABBBCCDAABBB') --> A B C D
237     # unique_everseen('ABBCcAD', str.lower) --> A B C D
238     seen = set()
239     seen_add = seen.add
240     if key is None:
241         for element in filterfalse(seen.__contains__, iterable):
242             seen_add(element)
243             yield element
244     else:
245         for element in iterable:
246             k = key(element)
247             if k not in seen:
248                 seen_add(k)
249                 yield element
250 
251 
252 def assert_relative(path):
253     if not os.path.isabs(path):
254         return path
255     from distutils.errors import DistutilsSetupError
256 
257     msg = textwrap.dedent("""
258         Error: setup script specifies an absolute path:
259 
260             %s
261 
262         setup() arguments must *always* be /-separated paths relative to the
263         setup.py directory, *never* absolute paths.
264         """).lstrip() % path
265     raise DistutilsSetupError(msg)
266
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/setuptools/command/build_py.py b/setuptools/command/build_py.py
--- a/setuptools/command/build_py.py
+++ b/setuptools/command/build_py.py
@@ -8,6 +8,7 @@
 import distutils.errors
 import itertools
 
+from setuptools.extern import six
 from setuptools.extern.six.moves import map, filter, filterfalse
 
 try:
@@ -66,6 +67,9 @@
         return orig.build_py.__getattr__(self, attr)
 
     def build_module(self, module, module_file, package):
+        if six.PY2 and isinstance(package, six.string_types):
+            # avoid errors on Python 2 when unicode is passed (#190)
+            package = package.split('.')
         outfile, copied = orig.build_py.build_module(self, module, module_file,
                                                      package)
         if copied:

{"golden_diff": "diff --git a/setuptools/command/build_py.py b/setuptools/command/build_py.py\n--- a/setuptools/command/build_py.py\n+++ b/setuptools/command/build_py.py\n@@ -8,6 +8,7 @@\n import distutils.errors\n import itertools\n \n+from setuptools.extern import six\n from setuptools.extern.six.moves import map, filter, filterfalse\n \n try:\n@@ -66,6 +67,9 @@\n         return orig.build_py.__getattr__(self, attr)\n \n     def build_module(self, module, module_file, package):\n+        if six.PY2 and isinstance(package, six.string_types):\n+            # avoid errors on Python 2 when unicode is passed (#190)\n+            package = package.split('.')\n         outfile, copied = orig.build_py.build_module(self, module, module_file,\n                                                      package)\n         if copied:\n", "issue": "Unfriendly error message when unicode is passed to package_dir or packages\nOriginally reported by: **jaraco (Bitbucket: [jaraco](http://bitbucket.org/jaraco), GitHub: [jaraco](http://github.com/jaraco))**\n\n---\n\nAdding `__future__.unicode_literals` causes setup.py scripts to fail. In the mailman project, here is an example error when running python2 setup.py build:\n\n```\nrunning build\nrunning build_py\nTraceback (most recent call last):\n  File \"setup.py\", line 112, in <module>\n    test_suite = 'nose2.collector.collector',\n  File \"C:\\Program Files\\Python27\\lib\\distutils\\core.py\", line 152, in setup\n    dist.run_commands()\n  File \"C:\\Program Files\\Python27\\lib\\distutils\\dist.py\", line 953, in run_commands\n    self.run_command(cmd)\n  File \"C:\\Program Files\\Python27\\lib\\distutils\\dist.py\", line 972, in run_command\n    cmd_obj.run()\n  File \"C:\\Program Files\\Python27\\lib\\distutils\\command\\build.py\", line 127, in run\n    self.run_command(cmd_name)\n  File \"C:\\Program Files\\Python27\\lib\\distutils\\cmd.py\", line 326, in run_command\n    self.distribution.run_command(command)\n  File \"C:\\Program Files\\Python27\\lib\\distutils\\dist.py\", line 972, in run_command\n    cmd_obj.run()\n  File \"build\\bdist.win-amd64\\egg\\setuptools\\command\\build_py.py\", line 42, in run\n  File \"C:\\Program Files\\Python27\\lib\\distutils\\command\\build_py.py\", line 372, in build_packages\n    self.build_module(module, module_file, package)\n  File \"build\\bdist.win-amd64\\egg\\setuptools\\command\\build_py.py\", line 60, in build_module\n  File \"C:\\Program Files\\Python27\\lib\\distutils\\command\\build_py.py\", line 333, in build_module\n    \"'package' must be a string (dot-separated), list, or tuple\")\nTypeError: 'package' must be a string (dot-separated), list, or tuple\n```\n\nA different error occurs when using 'develop':\n\n```\nrunning develop\nerror: 'egg_base' must be a directory name (got `src`)\n```\n\nSetuptools could make this error message nicer.\n\n---\n- Bitbucket: https://bitbucket.org/pypa/setuptools/issue/190\n\n", "before_files": [{"content": "from glob import glob\nfrom distutils.util import convert_path\nimport distutils.command.build_py as orig\nimport os\nimport fnmatch\nimport textwrap\nimport io\nimport distutils.errors\nimport itertools\n\nfrom setuptools.extern.six.moves import map, filter, filterfalse\n\ntry:\n    from setuptools.lib2to3_ex import Mixin2to3\nexcept ImportError:\n    class Mixin2to3:\n        def run_2to3(self, files, doctests=True):\n            \"do nothing\"\n\n\nclass build_py(orig.build_py, Mixin2to3):\n    \"\"\"Enhanced 'build_py' command that includes data files with packages\n\n    The data files are specified via a 'package_data' argument to 'setup()'.\n    See 'setuptools.dist.Distribution' for more details.\n\n    Also, this version of the 'build_py' command allows you to specify both\n    'py_modules' and 'packages' in the same setup operation.\n    \"\"\"\n\n    def finalize_options(self):\n        orig.build_py.finalize_options(self)\n        self.package_data = self.distribution.package_data\n        self.exclude_package_data = (self.distribution.exclude_package_data or\n                                     {})\n        if 'data_files' in self.__dict__:\n            del self.__dict__['data_files']\n        self.__updated_files = []\n        self.__doctests_2to3 = []\n\n    def run(self):\n        \"\"\"Build modules, packages, and copy data files to build directory\"\"\"\n        if not self.py_modules and not self.packages:\n            return\n\n        if self.py_modules:\n            self.build_modules()\n\n        if self.packages:\n            self.build_packages()\n            self.build_package_data()\n\n        self.run_2to3(self.__updated_files, False)\n        self.run_2to3(self.__updated_files, True)\n        self.run_2to3(self.__doctests_2to3, True)\n\n        # Only compile actual .py files, using our base class' idea of what our\n        # output files are.\n        self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))\n\n    def __getattr__(self, attr):\n        \"lazily compute data files\"\n        if attr == 'data_files':\n            self.data_files = self._get_data_files()\n            return self.data_files\n        return orig.build_py.__getattr__(self, attr)\n\n    def build_module(self, module, module_file, package):\n        outfile, copied = orig.build_py.build_module(self, module, module_file,\n                                                     package)\n        if copied:\n            self.__updated_files.append(outfile)\n        return outfile, copied\n\n    def _get_data_files(self):\n        \"\"\"Generate list of '(package,src_dir,build_dir,filenames)' tuples\"\"\"\n        self.analyze_manifest()\n        return list(map(self._get_pkg_data_files, self.packages or ()))\n\n    def _get_pkg_data_files(self, package):\n        # Locate package source directory\n        src_dir = self.get_package_dir(package)\n\n        # Compute package build directory\n        build_dir = os.path.join(*([self.build_lib] + package.split('.')))\n\n        # Strip directory from globbed filenames\n        filenames = [\n            os.path.relpath(file, src_dir)\n            for file in self.find_data_files(package, src_dir)\n        ]\n        return package, src_dir, build_dir, filenames\n\n    def find_data_files(self, package, src_dir):\n        \"\"\"Return filenames for package's data files in 'src_dir'\"\"\"\n        patterns = self._get_platform_patterns(\n            self.package_data,\n            package,\n            src_dir,\n        )\n        globs_expanded = map(glob, patterns)\n        # flatten the expanded globs into an iterable of matches\n        globs_matches = itertools.chain.from_iterable(globs_expanded)\n        glob_files = filter(os.path.isfile, globs_matches)\n        files = itertools.chain(\n            self.manifest_files.get(package, []),\n            glob_files,\n        )\n        return self.exclude_data_files(package, src_dir, files)\n\n    def build_package_data(self):\n        \"\"\"Copy data files into build directory\"\"\"\n        for package, src_dir, build_dir, filenames in self.data_files:\n            for filename in filenames:\n                target = os.path.join(build_dir, filename)\n                self.mkpath(os.path.dirname(target))\n                srcfile = os.path.join(src_dir, filename)\n                outf, copied = self.copy_file(srcfile, target)\n                srcfile = os.path.abspath(srcfile)\n                if (copied and\n                        srcfile in self.distribution.convert_2to3_doctests):\n                    self.__doctests_2to3.append(outf)\n\n    def analyze_manifest(self):\n        self.manifest_files = mf = {}\n        if not self.distribution.include_package_data:\n            return\n        src_dirs = {}\n        for package in self.packages or ():\n            # Locate package source directory\n            src_dirs[assert_relative(self.get_package_dir(package))] = package\n\n        self.run_command('egg_info')\n        ei_cmd = self.get_finalized_command('egg_info')\n        for path in ei_cmd.filelist.files:\n            d, f = os.path.split(assert_relative(path))\n            prev = None\n            oldf = f\n            while d and d != prev and d not in src_dirs:\n                prev = d\n                d, df = os.path.split(d)\n                f = os.path.join(df, f)\n            if d in src_dirs:\n                if path.endswith('.py') and f == oldf:\n                    continue  # it's a module, not data\n                mf.setdefault(src_dirs[d], []).append(path)\n\n    def get_data_files(self):\n        pass  # Lazily compute data files in _get_data_files() function.\n\n    def check_package(self, package, package_dir):\n        \"\"\"Check namespace packages' __init__ for declare_namespace\"\"\"\n        try:\n            return self.packages_checked[package]\n        except KeyError:\n            pass\n\n        init_py = orig.build_py.check_package(self, package, package_dir)\n        self.packages_checked[package] = init_py\n\n        if not init_py or not self.distribution.namespace_packages:\n            return init_py\n\n        for pkg in self.distribution.namespace_packages:\n            if pkg == package or pkg.startswith(package + '.'):\n                break\n        else:\n            return init_py\n\n        with io.open(init_py, 'rb') as f:\n            contents = f.read()\n        if b'declare_namespace' not in contents:\n            raise distutils.errors.DistutilsError(\n                \"Namespace package problem: %s is a namespace package, but \"\n                \"its\\n__init__.py does not call declare_namespace()! Please \"\n                'fix it.\\n(See the setuptools manual under '\n                '\"Namespace Packages\" for details.)\\n\"' % (package,)\n            )\n        return init_py\n\n    def initialize_options(self):\n        self.packages_checked = {}\n        orig.build_py.initialize_options(self)\n\n    def get_package_dir(self, package):\n        res = orig.build_py.get_package_dir(self, package)\n        if self.distribution.src_root is not None:\n            return os.path.join(self.distribution.src_root, res)\n        return res\n\n    def exclude_data_files(self, package, src_dir, files):\n        \"\"\"Filter filenames for package's data files in 'src_dir'\"\"\"\n        files = list(files)\n        patterns = self._get_platform_patterns(\n            self.exclude_package_data,\n            package,\n            src_dir,\n        )\n        match_groups = (\n            fnmatch.filter(files, pattern)\n            for pattern in patterns\n        )\n        # flatten the groups of matches into an iterable of matches\n        matches = itertools.chain.from_iterable(match_groups)\n        bad = set(matches)\n        keepers = (\n            fn\n            for fn in files\n            if fn not in bad\n        )\n        # ditch dupes\n        return list(_unique_everseen(keepers))\n\n    @staticmethod\n    def _get_platform_patterns(spec, package, src_dir):\n        \"\"\"\n        yield platfrom-specific path patterns (suitable for glob\n        or fn_match) from a glob-based spec (such as\n        self.package_data or self.exclude_package_data)\n        matching package in src_dir.\n        \"\"\"\n        raw_patterns = itertools.chain(\n            spec.get('', []),\n            spec.get(package, []),\n        )\n        return (\n            # Each pattern has to be converted to a platform-specific path\n            os.path.join(src_dir, convert_path(pattern))\n            for pattern in raw_patterns\n        )\n\n\n# from Python docs\ndef _unique_everseen(iterable, key=None):\n    \"List unique elements, preserving order. Remember all elements ever seen.\"\n    # unique_everseen('AAAABBBCCDAABBB') --> A B C D\n    # unique_everseen('ABBCcAD', str.lower) --> A B C D\n    seen = set()\n    seen_add = seen.add\n    if key is None:\n        for element in filterfalse(seen.__contains__, iterable):\n            seen_add(element)\n            yield element\n    else:\n        for element in iterable:\n            k = key(element)\n            if k not in seen:\n                seen_add(k)\n                yield element\n\n\ndef assert_relative(path):\n    if not os.path.isabs(path):\n        return path\n    from distutils.errors import DistutilsSetupError\n\n    msg = textwrap.dedent(\"\"\"\n        Error: setup script specifies an absolute path:\n\n            %s\n\n        setup() arguments must *always* be /-separated paths relative to the\n        setup.py directory, *never* absolute paths.\n        \"\"\").lstrip() % path\n    raise DistutilsSetupError(msg)\n", "path": "setuptools/command/build_py.py"}], "after_files": [{"content": "from glob import glob\nfrom distutils.util import convert_path\nimport distutils.command.build_py as orig\nimport os\nimport fnmatch\nimport textwrap\nimport io\nimport distutils.errors\nimport itertools\n\nfrom setuptools.extern import six\nfrom setuptools.extern.six.moves import map, filter, filterfalse\n\ntry:\n    from setuptools.lib2to3_ex import Mixin2to3\nexcept ImportError:\n    class Mixin2to3:\n        def run_2to3(self, files, doctests=True):\n            \"do nothing\"\n\n\nclass build_py(orig.build_py, Mixin2to3):\n    \"\"\"Enhanced 'build_py' command that includes data files with packages\n\n    The data files are specified via a 'package_data' argument to 'setup()'.\n    See 'setuptools.dist.Distribution' for more details.\n\n    Also, this version of the 'build_py' command allows you to specify both\n    'py_modules' and 'packages' in the same setup operation.\n    \"\"\"\n\n    def finalize_options(self):\n        orig.build_py.finalize_options(self)\n        self.package_data = self.distribution.package_data\n        self.exclude_package_data = (self.distribution.exclude_package_data or\n                                     {})\n        if 'data_files' in self.__dict__:\n            del self.__dict__['data_files']\n        self.__updated_files = []\n        self.__doctests_2to3 = []\n\n    def run(self):\n        \"\"\"Build modules, packages, and copy data files to build directory\"\"\"\n        if not self.py_modules and not self.packages:\n            return\n\n        if self.py_modules:\n            self.build_modules()\n\n        if self.packages:\n            self.build_packages()\n            self.build_package_data()\n\n        self.run_2to3(self.__updated_files, False)\n        self.run_2to3(self.__updated_files, True)\n        self.run_2to3(self.__doctests_2to3, True)\n\n        # Only compile actual .py files, using our base class' idea of what our\n        # output files are.\n        self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))\n\n    def __getattr__(self, attr):\n        \"lazily compute data files\"\n        if attr == 'data_files':\n            self.data_files = self._get_data_files()\n            return self.data_files\n        return orig.build_py.__getattr__(self, attr)\n\n    def build_module(self, module, module_file, package):\n        if six.PY2 and isinstance(package, six.string_types):\n            # avoid errors on Python 2 when unicode is passed (#190)\n            package = package.split('.')\n        outfile, copied = orig.build_py.build_module(self, module, module_file,\n                                                     package)\n        if copied:\n            self.__updated_files.append(outfile)\n        return outfile, copied\n\n    def _get_data_files(self):\n        \"\"\"Generate list of '(package,src_dir,build_dir,filenames)' tuples\"\"\"\n        self.analyze_manifest()\n        return list(map(self._get_pkg_data_files, self.packages or ()))\n\n    def _get_pkg_data_files(self, package):\n        # Locate package source directory\n        src_dir = self.get_package_dir(package)\n\n        # Compute package build directory\n        build_dir = os.path.join(*([self.build_lib] + package.split('.')))\n\n        # Strip directory from globbed filenames\n        filenames = [\n            os.path.relpath(file, src_dir)\n            for file in self.find_data_files(package, src_dir)\n        ]\n        return package, src_dir, build_dir, filenames\n\n    def find_data_files(self, package, src_dir):\n        \"\"\"Return filenames for package's data files in 'src_dir'\"\"\"\n        patterns = self._get_platform_patterns(\n            self.package_data,\n            package,\n            src_dir,\n        )\n        globs_expanded = map(glob, patterns)\n        # flatten the expanded globs into an iterable of matches\n        globs_matches = itertools.chain.from_iterable(globs_expanded)\n        glob_files = filter(os.path.isfile, globs_matches)\n        files = itertools.chain(\n            self.manifest_files.get(package, []),\n            glob_files,\n        )\n        return self.exclude_data_files(package, src_dir, files)\n\n    def build_package_data(self):\n        \"\"\"Copy data files into build directory\"\"\"\n        for package, src_dir, build_dir, filenames in self.data_files:\n            for filename in filenames:\n                target = os.path.join(build_dir, filename)\n                self.mkpath(os.path.dirname(target))\n                srcfile = os.path.join(src_dir, filename)\n                outf, copied = self.copy_file(srcfile, target)\n                srcfile = os.path.abspath(srcfile)\n                if (copied and\n                        srcfile in self.distribution.convert_2to3_doctests):\n                    self.__doctests_2to3.append(outf)\n\n    def analyze_manifest(self):\n        self.manifest_files = mf = {}\n        if not self.distribution.include_package_data:\n            return\n        src_dirs = {}\n        for package in self.packages or ():\n            # Locate package source directory\n            src_dirs[assert_relative(self.get_package_dir(package))] = package\n\n        self.run_command('egg_info')\n        ei_cmd = self.get_finalized_command('egg_info')\n        for path in ei_cmd.filelist.files:\n            d, f = os.path.split(assert_relative(path))\n            prev = None\n            oldf = f\n            while d and d != prev and d not in src_dirs:\n                prev = d\n                d, df = os.path.split(d)\n                f = os.path.join(df, f)\n            if d in src_dirs:\n                if path.endswith('.py') and f == oldf:\n                    continue  # it's a module, not data\n                mf.setdefault(src_dirs[d], []).append(path)\n\n    def get_data_files(self):\n        pass  # Lazily compute data files in _get_data_files() function.\n\n    def check_package(self, package, package_dir):\n        \"\"\"Check namespace packages' __init__ for declare_namespace\"\"\"\n        try:\n            return self.packages_checked[package]\n        except KeyError:\n            pass\n\n        init_py = orig.build_py.check_package(self, package, package_dir)\n        self.packages_checked[package] = init_py\n\n        if not init_py or not self.distribution.namespace_packages:\n            return init_py\n\n        for pkg in self.distribution.namespace_packages:\n            if pkg == package or pkg.startswith(package + '.'):\n                break\n        else:\n            return init_py\n\n        with io.open(init_py, 'rb') as f:\n            contents = f.read()\n        if b'declare_namespace' not in contents:\n            raise distutils.errors.DistutilsError(\n                \"Namespace package problem: %s is a namespace package, but \"\n                \"its\\n__init__.py does not call declare_namespace()! Please \"\n                'fix it.\\n(See the setuptools manual under '\n                '\"Namespace Packages\" for details.)\\n\"' % (package,)\n            )\n        return init_py\n\n    def initialize_options(self):\n        self.packages_checked = {}\n        orig.build_py.initialize_options(self)\n\n    def get_package_dir(self, package):\n        res = orig.build_py.get_package_dir(self, package)\n        if self.distribution.src_root is not None:\n            return os.path.join(self.distribution.src_root, res)\n        return res\n\n    def exclude_data_files(self, package, src_dir, files):\n        \"\"\"Filter filenames for package's data files in 'src_dir'\"\"\"\n        files = list(files)\n        patterns = self._get_platform_patterns(\n            self.exclude_package_data,\n            package,\n            src_dir,\n        )\n        match_groups = (\n            fnmatch.filter(files, pattern)\n            for pattern in patterns\n        )\n        # flatten the groups of matches into an iterable of matches\n        matches = itertools.chain.from_iterable(match_groups)\n        bad = set(matches)\n        keepers = (\n            fn\n            for fn in files\n            if fn not in bad\n        )\n        # ditch dupes\n        return list(_unique_everseen(keepers))\n\n    @staticmethod\n    def _get_platform_patterns(spec, package, src_dir):\n        \"\"\"\n        yield platfrom-specific path patterns (suitable for glob\n        or fn_match) from a glob-based spec (such as\n        self.package_data or self.exclude_package_data)\n        matching package in src_dir.\n        \"\"\"\n        raw_patterns = itertools.chain(\n            spec.get('', []),\n            spec.get(package, []),\n        )\n        return (\n            # Each pattern has to be converted to a platform-specific path\n            os.path.join(src_dir, convert_path(pattern))\n            for pattern in raw_patterns\n        )\n\n\n# from Python docs\ndef _unique_everseen(iterable, key=None):\n    \"List unique elements, preserving order. Remember all elements ever seen.\"\n    # unique_everseen('AAAABBBCCDAABBB') --> A B C D\n    # unique_everseen('ABBCcAD', str.lower) --> A B C D\n    seen = set()\n    seen_add = seen.add\n    if key is None:\n        for element in filterfalse(seen.__contains__, iterable):\n            seen_add(element)\n            yield element\n    else:\n        for element in iterable:\n            k = key(element)\n            if k not in seen:\n                seen_add(k)\n                yield element\n\n\ndef assert_relative(path):\n    if not os.path.isabs(path):\n        return path\n    from distutils.errors import DistutilsSetupError\n\n    msg = textwrap.dedent(\"\"\"\n        Error: setup script specifies an absolute path:\n\n            %s\n\n        setup() arguments must *always* be /-separated paths relative to the\n        setup.py directory, *never* absolute paths.\n        \"\"\").lstrip() % path\n    raise DistutilsSetupError(msg)\n", "path": "setuptools/command/build_py.py"}]}