We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`pex -c` does not work for multiplatform pexes when the target dist is platform specific
If the console script is housed in a dist that is platform-specific and the pex is multiplatform, then the same script is found more than once and pex creation fails with something like:
```
RuntimeError: Ambiguous script specification pants matches multiple entry points:pants = pants.bin.pants_loader:main pants = pants.bin.pants_loader:main
```
Pex should probably allow dups from a single requirement key if the found scripts are bytewise identical as they are in this example case.

See https://github.com/pantsbuild/pants/pull/6349 for an example of getting bit by this.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pex/finders.py`
Content:
```
1 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
2 # Licensed under the Apache License, Version 2.0 (see LICENSE).
3 
4 """The finders we wish we had in setuptools.
5 
6 As of setuptools 3.3, the only finder for zip-based distributions is for eggs.  The path-based
7 finder only searches paths ending in .egg and not in .whl (zipped or unzipped.)
8 
9 pex.finders augments pkg_resources with additional finders to achieve functional
10 parity between wheels and eggs in terms of findability with find_distributions.
11 
12 To use:
13    >>> from pex.finders import register_finders
14    >>> register_finders()
15 """
16 
17 import os
18 import pkgutil
19 import sys
20 import zipimport
21 
22 import pkg_resources
23 
24 if sys.version_info >= (3, 3) and sys.implementation.name == "cpython":
25   import importlib.machinery as importlib_machinery
26 else:
27   importlib_machinery = None
28 
29 
30 class ChainedFinder(object):
31   """A utility to chain together multiple pkg_resources finders."""
32 
33   @classmethod
34   def of(cls, *chained_finder_or_finder):
35     finders = []
36     for finder in chained_finder_or_finder:
37       if isinstance(finder, cls):
38         finders.extend(finder.finders)
39       else:
40         finders.append(finder)
41     return cls(finders)
42 
43   def __init__(self, finders):
44     self.finders = finders
45 
46   def __call__(self, importer, path_item, only=False):
47     for finder in self.finders:
48       for dist in finder(importer, path_item, only=only):
49         yield dist
50 
51   def __eq__(self, other):
52     if not isinstance(other, ChainedFinder):
53       return False
54     return self.finders == other.finders
55 
56 
57 # The following methods are somewhat dangerous as pkg_resources._distribution_finders is not an
58 # exposed API.  As it stands, pkg_resources doesn't provide an API to chain multiple distribution
59 # finders together.  This is probably possible using importlib but that does us no good as the
60 # importlib machinery supporting this is only available in Python >= 3.1.
61 def _get_finder(importer):
62   if not hasattr(pkg_resources, '_distribution_finders'):
63     return None
64   return pkg_resources._distribution_finders.get(importer)
65 
66 
67 def _add_finder(importer, finder):
68   """Register a new pkg_resources path finder that does not replace the existing finder."""
69 
70   existing_finder = _get_finder(importer)
71 
72   if not existing_finder:
73     pkg_resources.register_finder(importer, finder)
74   else:
75     pkg_resources.register_finder(importer, ChainedFinder.of(existing_finder, finder))
76 
77 
78 def _remove_finder(importer, finder):
79   """Remove an existing finder from pkg_resources."""
80 
81   existing_finder = _get_finder(importer)
82 
83   if not existing_finder:
84     return
85 
86   if isinstance(existing_finder, ChainedFinder):
87     try:
88       existing_finder.finders.remove(finder)
89     except ValueError:
90       return
91     if len(existing_finder.finders) == 1:
92       pkg_resources.register_finder(importer, existing_finder.finders[0])
93     elif len(existing_finder.finders) == 0:
94       pkg_resources.register_finder(importer, pkg_resources.find_nothing)
95   else:
96     pkg_resources.register_finder(importer, pkg_resources.find_nothing)
97 
98 
99 class WheelMetadata(pkg_resources.EggMetadata):
100   """Metadata provider for zipped wheels."""
101 
102   @classmethod
103   def _split_wheelname(cls, wheelname):
104     split_wheelname = wheelname.rsplit('-', 4)
105     assert len(split_wheelname) == 5, 'invalid wheel name: %s' % (wheelname)
106     split_wheelname[0] = split_wheelname[0].replace('-', '_')
107     return '-'.join(split_wheelname[:-3])
108 
109   def _setup_prefix(self):
110     path = self.module_path
111     old = None
112     while path != old:
113       if path.lower().endswith('.whl'):
114         self.egg_name = os.path.basename(path)
115         # TODO(wickman) Test the regression where we have both upper and lower cased package
116         # names.
117         self.egg_info = os.path.join(path, '%s.dist-info' % self._split_wheelname(self.egg_name))
118         self.egg_root = path
119         break
120       old = path
121       path, base = os.path.split(path)
122 
123 
124 # See https://bitbucket.org/tarek/distribute/issue/274
125 class FixedEggMetadata(pkg_resources.EggMetadata):
126   """An EggMetadata provider that has functional parity with the disk-based provider."""
127 
128   @classmethod
129   def normalized_elements(cls, path):
130     path_split = path.split('/')
131     while path_split[-1] in ('', '.'):
132       path_split.pop(-1)
133     return path_split
134 
135   def _fn(self, base, resource_name):
136     # super() does not work here as EggMetadata is an old-style class.
137     original_fn = pkg_resources.EggMetadata._fn(self, base, resource_name)
138     return '/'.join(self.normalized_elements(original_fn))
139 
140   def _zipinfo_name(self, fspath):
141     fspath = self.normalized_elements(fspath)
142     zip_pre = self.normalized_elements(self.zip_pre)
143     if fspath[:len(zip_pre)] == zip_pre:
144       return '/'.join(fspath[len(zip_pre):])
145     assert "%s is not a subpath of %s" % (fspath, self.zip_pre)
146 
147 
148 def wheel_from_metadata(location, metadata):
149   if not metadata.has_metadata(pkg_resources.DistInfoDistribution.PKG_INFO):
150     return None
151 
152   from email.parser import Parser
153   pkg_info = Parser().parsestr(metadata.get_metadata(pkg_resources.DistInfoDistribution.PKG_INFO))
154   return pkg_resources.DistInfoDistribution(
155       location=location,
156       metadata=metadata,
157       # TODO(wickman) Is this necessary or will they get picked up correctly?
158       project_name=pkg_info.get('Name'),
159       version=pkg_info.get('Version'),
160       platform=None)
161 
162 
163 def find_wheels_on_path(importer, path_item, only=False):
164   if not os.path.isdir(path_item) or not os.access(path_item, os.R_OK):
165     return
166   if not only:
167     for entry in os.listdir(path_item):
168       if entry.lower().endswith('.whl'):
169         for dist in pkg_resources.find_distributions(os.path.join(path_item, entry)):
170           yield dist
171 
172 
173 def find_eggs_in_zip(importer, path_item, only=False):
174   if importer.archive.endswith('.whl'):
175     # Defer to wheel importer
176     return
177   metadata = FixedEggMetadata(importer)
178   if metadata.has_metadata('PKG-INFO'):
179     yield pkg_resources.Distribution.from_filename(path_item, metadata=metadata)
180   if only:
181     return  # don't yield nested distros
182   for subitem in metadata.resource_listdir('/'):
183     if subitem.endswith('.egg'):
184       subpath = os.path.join(path_item, subitem)
185       for dist in find_eggs_in_zip(zipimport.zipimporter(subpath), subpath):
186         yield dist
187 
188 
189 def find_wheels_in_zip(importer, path_item, only=False):
190   metadata = WheelMetadata(importer)
191   dist = wheel_from_metadata(path_item, metadata)
192   if dist:
193     yield dist
194 
195 
196 __PREVIOUS_FINDER = None
197 
198 
199 def register_finders():
200   """Register finders necessary for PEX to function properly."""
201 
202   # If the previous finder is set, then we've already monkeypatched, so skip.
203   global __PREVIOUS_FINDER
204   if __PREVIOUS_FINDER:
205     return
206 
207   # save previous finder so that it can be restored
208   previous_finder = _get_finder(zipimport.zipimporter)
209   assert previous_finder, 'This appears to be using an incompatible setuptools.'
210 
211   # replace the zip finder with our own implementation of find_eggs_in_zip which uses the correct
212   # metadata handler, in addition to find_wheels_in_zip
213   pkg_resources.register_finder(
214       zipimport.zipimporter, ChainedFinder.of(find_eggs_in_zip, find_wheels_in_zip))
215 
216   # append the wheel finder
217   _add_finder(pkgutil.ImpImporter, find_wheels_on_path)
218 
219   if importlib_machinery is not None:
220     _add_finder(importlib_machinery.FileFinder, find_wheels_on_path)
221 
222   __PREVIOUS_FINDER = previous_finder
223 
224 
225 def unregister_finders():
226   """Unregister finders necessary for PEX to function properly."""
227 
228   global __PREVIOUS_FINDER
229   if not __PREVIOUS_FINDER:
230     return
231 
232   pkg_resources.register_finder(zipimport.zipimporter, __PREVIOUS_FINDER)
233   _remove_finder(pkgutil.ImpImporter, find_wheels_on_path)
234 
235   if importlib_machinery is not None:
236     _remove_finder(importlib_machinery.FileFinder, find_wheels_on_path)
237 
238   __PREVIOUS_FINDER = None
239 
240 
241 def get_script_from_egg(name, dist):
242   """Returns location, content of script in distribution or (None, None) if not there."""
243   if dist.metadata_isdir('scripts') and name in dist.metadata_listdir('scripts'):
244     return (
245         os.path.join(dist.egg_info, 'scripts', name),
246         dist.get_metadata('scripts/%s' % name).replace('\r\n', '\n').replace('\r', '\n'))
247   return None, None
248 
249 
250 def get_script_from_whl(name, dist):
251   # This can get called in different contexts; in some, it looks for files in the
252   # wheel archives being used to produce a pex; in others, it looks for files in the
253   # install wheel directory included in the pex. So we need to look at both locations.
254   datadir_name = "%s-%s.data" % (dist.project_name, dist.version)
255   wheel_scripts_dirs = ['bin', 'scripts',
256                          os.path.join(datadir_name, "bin"),
257                          os.path.join(datadir_name, "scripts")]
258   for wheel_scripts_dir in wheel_scripts_dirs:
259     if (dist.resource_isdir(wheel_scripts_dir) and
260         name in dist.resource_listdir(wheel_scripts_dir)):
261       # We always install wheel scripts into bin
262       script_path = os.path.join(wheel_scripts_dir, name)
263       return (
264           os.path.join(dist.egg_info, script_path),
265           dist.get_resource_string('', script_path).replace(b'\r\n', b'\n').replace(b'\r', b'\n'))
266   return None, None
267 
268 
269 def get_script_from_distribution(name, dist):
270   # PathMetadata: exploded distribution on disk.
271   if isinstance(dist._provider, pkg_resources.PathMetadata):
272     if dist.egg_info.endswith('EGG-INFO'):
273       return get_script_from_egg(name, dist)
274     elif dist.egg_info.endswith('.dist-info'):
275       return get_script_from_whl(name, dist)
276     else:
277       return None, None
278   # FixedEggMetadata: Zipped egg
279   elif isinstance(dist._provider, FixedEggMetadata):
280     return get_script_from_egg(name, dist)
281   # WheelMetadata: Zipped whl (in theory should not experience this at runtime.)
282   elif isinstance(dist._provider, WheelMetadata):
283     return get_script_from_whl(name, dist)
284   return None, None
285 
286 
287 def get_script_from_distributions(name, dists):
288   for dist in dists:
289     script_path, script_content = get_script_from_distribution(name, dist)
290     if script_path:
291       return dist, script_path, script_content
292   return None, None, None
293 
294 
295 def get_entry_point_from_console_script(script, dists):
296   # check all distributions for the console_script "script"
297   entries = frozenset(filter(None, (
298       dist.get_entry_map().get('console_scripts', {}).get(script) for dist in dists)))
299 
300   # if multiple matches, freak out
301   if len(entries) > 1:
302     raise RuntimeError(
303         'Ambiguous script specification %s matches multiple entry points:%s' % (
304             script, ' '.join(map(str, entries))))
305 
306   if entries:
307     entry_point = next(iter(entries))
308     # entry points are of the form 'foo = bar', we just want the 'bar' part:
309     return str(entry_point).split('=')[1].strip()
310
```
--- 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/pex/finders.py b/pex/finders.py
--- a/pex/finders.py
+++ b/pex/finders.py
@@ -293,17 +293,22 @@
 
 
 def get_entry_point_from_console_script(script, dists):
-  # check all distributions for the console_script "script"
-  entries = frozenset(filter(None, (
-      dist.get_entry_map().get('console_scripts', {}).get(script) for dist in dists)))
+  # Check all distributions for the console_script "script". De-dup by dist key to allow for a
+  # duplicate console script IFF the distribution is platform-specific and this is a multi-platform
+  # pex.
+  def get_entrypoint(dist):
+    script_entry = dist.get_entry_map().get('console_scripts', {}).get(script)
+    if script_entry is not None:
+      # Entry points are of the form 'foo = bar', we just want the 'bar' part.
+      return dist.key, str(script_entry).split('=')[1].strip()
+
+  entries = frozenset(filter(None, (get_entrypoint(dist) for dist in dists)))
 
-  # if multiple matches, freak out
   if len(entries) > 1:
     raise RuntimeError(
-        'Ambiguous script specification %s matches multiple entry points:%s' % (
-            script, ' '.join(map(str, entries))))
+        'Ambiguous script specification %s matches multiple entry points:\n\t%s' % (
+            script, '\n\t'.join('%s from %s' % (entry_point, key) for key, entry_point in entries)))
 
   if entries:
-    entry_point = next(iter(entries))
-    # entry points are of the form 'foo = bar', we just want the 'bar' part:
-    return str(entry_point).split('=')[1].strip()
+    _, entry_point = next(iter(entries))
+    return entry_point

{"golden_diff": "diff --git a/pex/finders.py b/pex/finders.py\n--- a/pex/finders.py\n+++ b/pex/finders.py\n@@ -293,17 +293,22 @@\n \n \n def get_entry_point_from_console_script(script, dists):\n-  # check all distributions for the console_script \"script\"\n-  entries = frozenset(filter(None, (\n-      dist.get_entry_map().get('console_scripts', {}).get(script) for dist in dists)))\n+  # Check all distributions for the console_script \"script\". De-dup by dist key to allow for a\n+  # duplicate console script IFF the distribution is platform-specific and this is a multi-platform\n+  # pex.\n+  def get_entrypoint(dist):\n+    script_entry = dist.get_entry_map().get('console_scripts', {}).get(script)\n+    if script_entry is not None:\n+      # Entry points are of the form 'foo = bar', we just want the 'bar' part.\n+      return dist.key, str(script_entry).split('=')[1].strip()\n+\n+  entries = frozenset(filter(None, (get_entrypoint(dist) for dist in dists)))\n \n-  # if multiple matches, freak out\n   if len(entries) > 1:\n     raise RuntimeError(\n-        'Ambiguous script specification %s matches multiple entry points:%s' % (\n-            script, ' '.join(map(str, entries))))\n+        'Ambiguous script specification %s matches multiple entry points:\\n\\t%s' % (\n+            script, '\\n\\t'.join('%s from %s' % (entry_point, key) for key, entry_point in entries)))\n \n   if entries:\n-    entry_point = next(iter(entries))\n-    # entry points are of the form 'foo = bar', we just want the 'bar' part:\n-    return str(entry_point).split('=')[1].strip()\n+    _, entry_point = next(iter(entries))\n+    return entry_point\n", "issue": "`pex -c` does not work for multiplatform pexes when the target dist is platform specific\nIf the console script is housed in a dist that is platform-specific and the pex is multiplatform, then the same script is found more than once and pex creation fails with something like:\r\n```\r\nRuntimeError: Ambiguous script specification pants matches multiple entry points:pants = pants.bin.pants_loader:main pants = pants.bin.pants_loader:main\r\n```\r\nPex should probably allow dups from a single requirement key if the found scripts are bytewise identical as they are in this example case.\r\n\r\nSee https://github.com/pantsbuild/pants/pull/6349 for an example of getting bit by this.\n", "before_files": [{"content": "# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\n\"\"\"The finders we wish we had in setuptools.\n\nAs of setuptools 3.3, the only finder for zip-based distributions is for eggs.  The path-based\nfinder only searches paths ending in .egg and not in .whl (zipped or unzipped.)\n\npex.finders augments pkg_resources with additional finders to achieve functional\nparity between wheels and eggs in terms of findability with find_distributions.\n\nTo use:\n   >>> from pex.finders import register_finders\n   >>> register_finders()\n\"\"\"\n\nimport os\nimport pkgutil\nimport sys\nimport zipimport\n\nimport pkg_resources\n\nif sys.version_info >= (3, 3) and sys.implementation.name == \"cpython\":\n  import importlib.machinery as importlib_machinery\nelse:\n  importlib_machinery = None\n\n\nclass ChainedFinder(object):\n  \"\"\"A utility to chain together multiple pkg_resources finders.\"\"\"\n\n  @classmethod\n  def of(cls, *chained_finder_or_finder):\n    finders = []\n    for finder in chained_finder_or_finder:\n      if isinstance(finder, cls):\n        finders.extend(finder.finders)\n      else:\n        finders.append(finder)\n    return cls(finders)\n\n  def __init__(self, finders):\n    self.finders = finders\n\n  def __call__(self, importer, path_item, only=False):\n    for finder in self.finders:\n      for dist in finder(importer, path_item, only=only):\n        yield dist\n\n  def __eq__(self, other):\n    if not isinstance(other, ChainedFinder):\n      return False\n    return self.finders == other.finders\n\n\n# The following methods are somewhat dangerous as pkg_resources._distribution_finders is not an\n# exposed API.  As it stands, pkg_resources doesn't provide an API to chain multiple distribution\n# finders together.  This is probably possible using importlib but that does us no good as the\n# importlib machinery supporting this is only available in Python >= 3.1.\ndef _get_finder(importer):\n  if not hasattr(pkg_resources, '_distribution_finders'):\n    return None\n  return pkg_resources._distribution_finders.get(importer)\n\n\ndef _add_finder(importer, finder):\n  \"\"\"Register a new pkg_resources path finder that does not replace the existing finder.\"\"\"\n\n  existing_finder = _get_finder(importer)\n\n  if not existing_finder:\n    pkg_resources.register_finder(importer, finder)\n  else:\n    pkg_resources.register_finder(importer, ChainedFinder.of(existing_finder, finder))\n\n\ndef _remove_finder(importer, finder):\n  \"\"\"Remove an existing finder from pkg_resources.\"\"\"\n\n  existing_finder = _get_finder(importer)\n\n  if not existing_finder:\n    return\n\n  if isinstance(existing_finder, ChainedFinder):\n    try:\n      existing_finder.finders.remove(finder)\n    except ValueError:\n      return\n    if len(existing_finder.finders) == 1:\n      pkg_resources.register_finder(importer, existing_finder.finders[0])\n    elif len(existing_finder.finders) == 0:\n      pkg_resources.register_finder(importer, pkg_resources.find_nothing)\n  else:\n    pkg_resources.register_finder(importer, pkg_resources.find_nothing)\n\n\nclass WheelMetadata(pkg_resources.EggMetadata):\n  \"\"\"Metadata provider for zipped wheels.\"\"\"\n\n  @classmethod\n  def _split_wheelname(cls, wheelname):\n    split_wheelname = wheelname.rsplit('-', 4)\n    assert len(split_wheelname) == 5, 'invalid wheel name: %s' % (wheelname)\n    split_wheelname[0] = split_wheelname[0].replace('-', '_')\n    return '-'.join(split_wheelname[:-3])\n\n  def _setup_prefix(self):\n    path = self.module_path\n    old = None\n    while path != old:\n      if path.lower().endswith('.whl'):\n        self.egg_name = os.path.basename(path)\n        # TODO(wickman) Test the regression where we have both upper and lower cased package\n        # names.\n        self.egg_info = os.path.join(path, '%s.dist-info' % self._split_wheelname(self.egg_name))\n        self.egg_root = path\n        break\n      old = path\n      path, base = os.path.split(path)\n\n\n# See https://bitbucket.org/tarek/distribute/issue/274\nclass FixedEggMetadata(pkg_resources.EggMetadata):\n  \"\"\"An EggMetadata provider that has functional parity with the disk-based provider.\"\"\"\n\n  @classmethod\n  def normalized_elements(cls, path):\n    path_split = path.split('/')\n    while path_split[-1] in ('', '.'):\n      path_split.pop(-1)\n    return path_split\n\n  def _fn(self, base, resource_name):\n    # super() does not work here as EggMetadata is an old-style class.\n    original_fn = pkg_resources.EggMetadata._fn(self, base, resource_name)\n    return '/'.join(self.normalized_elements(original_fn))\n\n  def _zipinfo_name(self, fspath):\n    fspath = self.normalized_elements(fspath)\n    zip_pre = self.normalized_elements(self.zip_pre)\n    if fspath[:len(zip_pre)] == zip_pre:\n      return '/'.join(fspath[len(zip_pre):])\n    assert \"%s is not a subpath of %s\" % (fspath, self.zip_pre)\n\n\ndef wheel_from_metadata(location, metadata):\n  if not metadata.has_metadata(pkg_resources.DistInfoDistribution.PKG_INFO):\n    return None\n\n  from email.parser import Parser\n  pkg_info = Parser().parsestr(metadata.get_metadata(pkg_resources.DistInfoDistribution.PKG_INFO))\n  return pkg_resources.DistInfoDistribution(\n      location=location,\n      metadata=metadata,\n      # TODO(wickman) Is this necessary or will they get picked up correctly?\n      project_name=pkg_info.get('Name'),\n      version=pkg_info.get('Version'),\n      platform=None)\n\n\ndef find_wheels_on_path(importer, path_item, only=False):\n  if not os.path.isdir(path_item) or not os.access(path_item, os.R_OK):\n    return\n  if not only:\n    for entry in os.listdir(path_item):\n      if entry.lower().endswith('.whl'):\n        for dist in pkg_resources.find_distributions(os.path.join(path_item, entry)):\n          yield dist\n\n\ndef find_eggs_in_zip(importer, path_item, only=False):\n  if importer.archive.endswith('.whl'):\n    # Defer to wheel importer\n    return\n  metadata = FixedEggMetadata(importer)\n  if metadata.has_metadata('PKG-INFO'):\n    yield pkg_resources.Distribution.from_filename(path_item, metadata=metadata)\n  if only:\n    return  # don't yield nested distros\n  for subitem in metadata.resource_listdir('/'):\n    if subitem.endswith('.egg'):\n      subpath = os.path.join(path_item, subitem)\n      for dist in find_eggs_in_zip(zipimport.zipimporter(subpath), subpath):\n        yield dist\n\n\ndef find_wheels_in_zip(importer, path_item, only=False):\n  metadata = WheelMetadata(importer)\n  dist = wheel_from_metadata(path_item, metadata)\n  if dist:\n    yield dist\n\n\n__PREVIOUS_FINDER = None\n\n\ndef register_finders():\n  \"\"\"Register finders necessary for PEX to function properly.\"\"\"\n\n  # If the previous finder is set, then we've already monkeypatched, so skip.\n  global __PREVIOUS_FINDER\n  if __PREVIOUS_FINDER:\n    return\n\n  # save previous finder so that it can be restored\n  previous_finder = _get_finder(zipimport.zipimporter)\n  assert previous_finder, 'This appears to be using an incompatible setuptools.'\n\n  # replace the zip finder with our own implementation of find_eggs_in_zip which uses the correct\n  # metadata handler, in addition to find_wheels_in_zip\n  pkg_resources.register_finder(\n      zipimport.zipimporter, ChainedFinder.of(find_eggs_in_zip, find_wheels_in_zip))\n\n  # append the wheel finder\n  _add_finder(pkgutil.ImpImporter, find_wheels_on_path)\n\n  if importlib_machinery is not None:\n    _add_finder(importlib_machinery.FileFinder, find_wheels_on_path)\n\n  __PREVIOUS_FINDER = previous_finder\n\n\ndef unregister_finders():\n  \"\"\"Unregister finders necessary for PEX to function properly.\"\"\"\n\n  global __PREVIOUS_FINDER\n  if not __PREVIOUS_FINDER:\n    return\n\n  pkg_resources.register_finder(zipimport.zipimporter, __PREVIOUS_FINDER)\n  _remove_finder(pkgutil.ImpImporter, find_wheels_on_path)\n\n  if importlib_machinery is not None:\n    _remove_finder(importlib_machinery.FileFinder, find_wheels_on_path)\n\n  __PREVIOUS_FINDER = None\n\n\ndef get_script_from_egg(name, dist):\n  \"\"\"Returns location, content of script in distribution or (None, None) if not there.\"\"\"\n  if dist.metadata_isdir('scripts') and name in dist.metadata_listdir('scripts'):\n    return (\n        os.path.join(dist.egg_info, 'scripts', name),\n        dist.get_metadata('scripts/%s' % name).replace('\\r\\n', '\\n').replace('\\r', '\\n'))\n  return None, None\n\n\ndef get_script_from_whl(name, dist):\n  # This can get called in different contexts; in some, it looks for files in the\n  # wheel archives being used to produce a pex; in others, it looks for files in the\n  # install wheel directory included in the pex. So we need to look at both locations.\n  datadir_name = \"%s-%s.data\" % (dist.project_name, dist.version)\n  wheel_scripts_dirs = ['bin', 'scripts',\n                         os.path.join(datadir_name, \"bin\"),\n                         os.path.join(datadir_name, \"scripts\")]\n  for wheel_scripts_dir in wheel_scripts_dirs:\n    if (dist.resource_isdir(wheel_scripts_dir) and\n        name in dist.resource_listdir(wheel_scripts_dir)):\n      # We always install wheel scripts into bin\n      script_path = os.path.join(wheel_scripts_dir, name)\n      return (\n          os.path.join(dist.egg_info, script_path),\n          dist.get_resource_string('', script_path).replace(b'\\r\\n', b'\\n').replace(b'\\r', b'\\n'))\n  return None, None\n\n\ndef get_script_from_distribution(name, dist):\n  # PathMetadata: exploded distribution on disk.\n  if isinstance(dist._provider, pkg_resources.PathMetadata):\n    if dist.egg_info.endswith('EGG-INFO'):\n      return get_script_from_egg(name, dist)\n    elif dist.egg_info.endswith('.dist-info'):\n      return get_script_from_whl(name, dist)\n    else:\n      return None, None\n  # FixedEggMetadata: Zipped egg\n  elif isinstance(dist._provider, FixedEggMetadata):\n    return get_script_from_egg(name, dist)\n  # WheelMetadata: Zipped whl (in theory should not experience this at runtime.)\n  elif isinstance(dist._provider, WheelMetadata):\n    return get_script_from_whl(name, dist)\n  return None, None\n\n\ndef get_script_from_distributions(name, dists):\n  for dist in dists:\n    script_path, script_content = get_script_from_distribution(name, dist)\n    if script_path:\n      return dist, script_path, script_content\n  return None, None, None\n\n\ndef get_entry_point_from_console_script(script, dists):\n  # check all distributions for the console_script \"script\"\n  entries = frozenset(filter(None, (\n      dist.get_entry_map().get('console_scripts', {}).get(script) for dist in dists)))\n\n  # if multiple matches, freak out\n  if len(entries) > 1:\n    raise RuntimeError(\n        'Ambiguous script specification %s matches multiple entry points:%s' % (\n            script, ' '.join(map(str, entries))))\n\n  if entries:\n    entry_point = next(iter(entries))\n    # entry points are of the form 'foo = bar', we just want the 'bar' part:\n    return str(entry_point).split('=')[1].strip()\n", "path": "pex/finders.py"}], "after_files": [{"content": "# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\n\"\"\"The finders we wish we had in setuptools.\n\nAs of setuptools 3.3, the only finder for zip-based distributions is for eggs.  The path-based\nfinder only searches paths ending in .egg and not in .whl (zipped or unzipped.)\n\npex.finders augments pkg_resources with additional finders to achieve functional\nparity between wheels and eggs in terms of findability with find_distributions.\n\nTo use:\n   >>> from pex.finders import register_finders\n   >>> register_finders()\n\"\"\"\n\nimport os\nimport pkgutil\nimport sys\nimport zipimport\n\nimport pkg_resources\n\nif sys.version_info >= (3, 3) and sys.implementation.name == \"cpython\":\n  import importlib.machinery as importlib_machinery\nelse:\n  importlib_machinery = None\n\n\nclass ChainedFinder(object):\n  \"\"\"A utility to chain together multiple pkg_resources finders.\"\"\"\n\n  @classmethod\n  def of(cls, *chained_finder_or_finder):\n    finders = []\n    for finder in chained_finder_or_finder:\n      if isinstance(finder, cls):\n        finders.extend(finder.finders)\n      else:\n        finders.append(finder)\n    return cls(finders)\n\n  def __init__(self, finders):\n    self.finders = finders\n\n  def __call__(self, importer, path_item, only=False):\n    for finder in self.finders:\n      for dist in finder(importer, path_item, only=only):\n        yield dist\n\n  def __eq__(self, other):\n    if not isinstance(other, ChainedFinder):\n      return False\n    return self.finders == other.finders\n\n\n# The following methods are somewhat dangerous as pkg_resources._distribution_finders is not an\n# exposed API.  As it stands, pkg_resources doesn't provide an API to chain multiple distribution\n# finders together.  This is probably possible using importlib but that does us no good as the\n# importlib machinery supporting this is only available in Python >= 3.1.\ndef _get_finder(importer):\n  if not hasattr(pkg_resources, '_distribution_finders'):\n    return None\n  return pkg_resources._distribution_finders.get(importer)\n\n\ndef _add_finder(importer, finder):\n  \"\"\"Register a new pkg_resources path finder that does not replace the existing finder.\"\"\"\n\n  existing_finder = _get_finder(importer)\n\n  if not existing_finder:\n    pkg_resources.register_finder(importer, finder)\n  else:\n    pkg_resources.register_finder(importer, ChainedFinder.of(existing_finder, finder))\n\n\ndef _remove_finder(importer, finder):\n  \"\"\"Remove an existing finder from pkg_resources.\"\"\"\n\n  existing_finder = _get_finder(importer)\n\n  if not existing_finder:\n    return\n\n  if isinstance(existing_finder, ChainedFinder):\n    try:\n      existing_finder.finders.remove(finder)\n    except ValueError:\n      return\n    if len(existing_finder.finders) == 1:\n      pkg_resources.register_finder(importer, existing_finder.finders[0])\n    elif len(existing_finder.finders) == 0:\n      pkg_resources.register_finder(importer, pkg_resources.find_nothing)\n  else:\n    pkg_resources.register_finder(importer, pkg_resources.find_nothing)\n\n\nclass WheelMetadata(pkg_resources.EggMetadata):\n  \"\"\"Metadata provider for zipped wheels.\"\"\"\n\n  @classmethod\n  def _split_wheelname(cls, wheelname):\n    split_wheelname = wheelname.rsplit('-', 4)\n    assert len(split_wheelname) == 5, 'invalid wheel name: %s' % (wheelname)\n    split_wheelname[0] = split_wheelname[0].replace('-', '_')\n    return '-'.join(split_wheelname[:-3])\n\n  def _setup_prefix(self):\n    path = self.module_path\n    old = None\n    while path != old:\n      if path.lower().endswith('.whl'):\n        self.egg_name = os.path.basename(path)\n        # TODO(wickman) Test the regression where we have both upper and lower cased package\n        # names.\n        self.egg_info = os.path.join(path, '%s.dist-info' % self._split_wheelname(self.egg_name))\n        self.egg_root = path\n        break\n      old = path\n      path, base = os.path.split(path)\n\n\n# See https://bitbucket.org/tarek/distribute/issue/274\nclass FixedEggMetadata(pkg_resources.EggMetadata):\n  \"\"\"An EggMetadata provider that has functional parity with the disk-based provider.\"\"\"\n\n  @classmethod\n  def normalized_elements(cls, path):\n    path_split = path.split('/')\n    while path_split[-1] in ('', '.'):\n      path_split.pop(-1)\n    return path_split\n\n  def _fn(self, base, resource_name):\n    # super() does not work here as EggMetadata is an old-style class.\n    original_fn = pkg_resources.EggMetadata._fn(self, base, resource_name)\n    return '/'.join(self.normalized_elements(original_fn))\n\n  def _zipinfo_name(self, fspath):\n    fspath = self.normalized_elements(fspath)\n    zip_pre = self.normalized_elements(self.zip_pre)\n    if fspath[:len(zip_pre)] == zip_pre:\n      return '/'.join(fspath[len(zip_pre):])\n    assert \"%s is not a subpath of %s\" % (fspath, self.zip_pre)\n\n\ndef wheel_from_metadata(location, metadata):\n  if not metadata.has_metadata(pkg_resources.DistInfoDistribution.PKG_INFO):\n    return None\n\n  from email.parser import Parser\n  pkg_info = Parser().parsestr(metadata.get_metadata(pkg_resources.DistInfoDistribution.PKG_INFO))\n  return pkg_resources.DistInfoDistribution(\n      location=location,\n      metadata=metadata,\n      # TODO(wickman) Is this necessary or will they get picked up correctly?\n      project_name=pkg_info.get('Name'),\n      version=pkg_info.get('Version'),\n      platform=None)\n\n\ndef find_wheels_on_path(importer, path_item, only=False):\n  if not os.path.isdir(path_item) or not os.access(path_item, os.R_OK):\n    return\n  if not only:\n    for entry in os.listdir(path_item):\n      if entry.lower().endswith('.whl'):\n        for dist in pkg_resources.find_distributions(os.path.join(path_item, entry)):\n          yield dist\n\n\ndef find_eggs_in_zip(importer, path_item, only=False):\n  if importer.archive.endswith('.whl'):\n    # Defer to wheel importer\n    return\n  metadata = FixedEggMetadata(importer)\n  if metadata.has_metadata('PKG-INFO'):\n    yield pkg_resources.Distribution.from_filename(path_item, metadata=metadata)\n  if only:\n    return  # don't yield nested distros\n  for subitem in metadata.resource_listdir('/'):\n    if subitem.endswith('.egg'):\n      subpath = os.path.join(path_item, subitem)\n      for dist in find_eggs_in_zip(zipimport.zipimporter(subpath), subpath):\n        yield dist\n\n\ndef find_wheels_in_zip(importer, path_item, only=False):\n  metadata = WheelMetadata(importer)\n  dist = wheel_from_metadata(path_item, metadata)\n  if dist:\n    yield dist\n\n\n__PREVIOUS_FINDER = None\n\n\ndef register_finders():\n  \"\"\"Register finders necessary for PEX to function properly.\"\"\"\n\n  # If the previous finder is set, then we've already monkeypatched, so skip.\n  global __PREVIOUS_FINDER\n  if __PREVIOUS_FINDER:\n    return\n\n  # save previous finder so that it can be restored\n  previous_finder = _get_finder(zipimport.zipimporter)\n  assert previous_finder, 'This appears to be using an incompatible setuptools.'\n\n  # replace the zip finder with our own implementation of find_eggs_in_zip which uses the correct\n  # metadata handler, in addition to find_wheels_in_zip\n  pkg_resources.register_finder(\n      zipimport.zipimporter, ChainedFinder.of(find_eggs_in_zip, find_wheels_in_zip))\n\n  # append the wheel finder\n  _add_finder(pkgutil.ImpImporter, find_wheels_on_path)\n\n  if importlib_machinery is not None:\n    _add_finder(importlib_machinery.FileFinder, find_wheels_on_path)\n\n  __PREVIOUS_FINDER = previous_finder\n\n\ndef unregister_finders():\n  \"\"\"Unregister finders necessary for PEX to function properly.\"\"\"\n\n  global __PREVIOUS_FINDER\n  if not __PREVIOUS_FINDER:\n    return\n\n  pkg_resources.register_finder(zipimport.zipimporter, __PREVIOUS_FINDER)\n  _remove_finder(pkgutil.ImpImporter, find_wheels_on_path)\n\n  if importlib_machinery is not None:\n    _remove_finder(importlib_machinery.FileFinder, find_wheels_on_path)\n\n  __PREVIOUS_FINDER = None\n\n\ndef get_script_from_egg(name, dist):\n  \"\"\"Returns location, content of script in distribution or (None, None) if not there.\"\"\"\n  if dist.metadata_isdir('scripts') and name in dist.metadata_listdir('scripts'):\n    return (\n        os.path.join(dist.egg_info, 'scripts', name),\n        dist.get_metadata('scripts/%s' % name).replace('\\r\\n', '\\n').replace('\\r', '\\n'))\n  return None, None\n\n\ndef get_script_from_whl(name, dist):\n  # This can get called in different contexts; in some, it looks for files in the\n  # wheel archives being used to produce a pex; in others, it looks for files in the\n  # install wheel directory included in the pex. So we need to look at both locations.\n  datadir_name = \"%s-%s.data\" % (dist.project_name, dist.version)\n  wheel_scripts_dirs = ['bin', 'scripts',\n                         os.path.join(datadir_name, \"bin\"),\n                         os.path.join(datadir_name, \"scripts\")]\n  for wheel_scripts_dir in wheel_scripts_dirs:\n    if (dist.resource_isdir(wheel_scripts_dir) and\n        name in dist.resource_listdir(wheel_scripts_dir)):\n      # We always install wheel scripts into bin\n      script_path = os.path.join(wheel_scripts_dir, name)\n      return (\n          os.path.join(dist.egg_info, script_path),\n          dist.get_resource_string('', script_path).replace(b'\\r\\n', b'\\n').replace(b'\\r', b'\\n'))\n  return None, None\n\n\ndef get_script_from_distribution(name, dist):\n  # PathMetadata: exploded distribution on disk.\n  if isinstance(dist._provider, pkg_resources.PathMetadata):\n    if dist.egg_info.endswith('EGG-INFO'):\n      return get_script_from_egg(name, dist)\n    elif dist.egg_info.endswith('.dist-info'):\n      return get_script_from_whl(name, dist)\n    else:\n      return None, None\n  # FixedEggMetadata: Zipped egg\n  elif isinstance(dist._provider, FixedEggMetadata):\n    return get_script_from_egg(name, dist)\n  # WheelMetadata: Zipped whl (in theory should not experience this at runtime.)\n  elif isinstance(dist._provider, WheelMetadata):\n    return get_script_from_whl(name, dist)\n  return None, None\n\n\ndef get_script_from_distributions(name, dists):\n  for dist in dists:\n    script_path, script_content = get_script_from_distribution(name, dist)\n    if script_path:\n      return dist, script_path, script_content\n  return None, None, None\n\n\ndef get_entry_point_from_console_script(script, dists):\n  # Check all distributions for the console_script \"script\". De-dup by dist key to allow for a\n  # duplicate console script IFF the distribution is platform-specific and this is a multi-platform\n  # pex.\n  def get_entrypoint(dist):\n    script_entry = dist.get_entry_map().get('console_scripts', {}).get(script)\n    if script_entry is not None:\n      # Entry points are of the form 'foo = bar', we just want the 'bar' part.\n      return dist.key, str(script_entry).split('=')[1].strip()\n\n  entries = frozenset(filter(None, (get_entrypoint(dist) for dist in dists)))\n\n  if len(entries) > 1:\n    raise RuntimeError(\n        'Ambiguous script specification %s matches multiple entry points:\\n\\t%s' % (\n            script, '\\n\\t'.join('%s from %s' % (entry_point, key) for key, entry_point in entries)))\n\n  if entries:\n    _, entry_point = next(iter(entries))\n    return entry_point\n", "path": "pex/finders.py"}]}