We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
conda build 2.1.6 sporadic failures
After updating 2.1.5 to 2.1.6, I now have sporadic (non reproductible) failures with conda build

```bash
RuntimeError: Can't build <whatever> due to unsatisfiable dependencies:

Packages/dependencies missing in current linux-64 channels: 
  - openssl
  - zlib
  - ...
```
, only on dependencies provided with the conda distribution (e.g. xz, zlib, ...)

Very annoying on running nightly builds (sometimes crashing, sometimes not)

Any clues on where to look (changes between versions) ?

conda --version is 4.3.14

thanks

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `conda_build/inspect.py`
Content:
```
1 # (c) Continuum Analytics, Inc. / http://continuum.io
2 # All Rights Reserved
3 #
4 # conda is distributed under the terms of the BSD 3-clause license.
5 # Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
6 
7 from __future__ import absolute_import, division, print_function
8 
9 from collections import defaultdict
10 import logging
11 from operator import itemgetter
12 from os.path import abspath, join, dirname, exists, basename, isdir
13 import re
14 import sys
15 import tempfile
16 
17 from .conda_interface import (iteritems, specs_from_args, is_linked, linked_data, linked,
18                               get_index)
19 from .conda_interface import display_actions, install_actions
20 
21 
22 from conda_build.os_utils.ldd import get_linkages, get_package_obj_files, get_untracked_obj_files
23 from conda_build.os_utils.macho import get_rpaths, human_filetype
24 from conda_build.utils import groupby, getter, comma_join, rm_rf
25 
26 
27 def which_prefix(path):
28     """
29     given the path (to a (presumably) conda installed file) return the
30     environment prefix in which the file in located
31     """
32     prefix = abspath(path)
33     while True:
34         if isdir(join(prefix, 'conda-meta')):
35             # we found the it, so let's return it
36             return prefix
37         if prefix == dirname(prefix):
38             # we cannot chop off any more directories, so we didn't find it
39             return None
40         prefix = dirname(prefix)
41 
42 
43 def which_package(path):
44     """
45     given the path (of a (presumably) conda installed file) iterate over
46     the conda packages the file came from.  Usually the iteration yields
47     only one package.
48     """
49     path = abspath(path)
50     prefix = which_prefix(path)
51     if prefix is None:
52         raise RuntimeError("could not determine conda prefix from: %s" % path)
53     for dist in linked(prefix):
54         meta = is_linked(prefix, dist)
55         if any(abspath(join(prefix, f)) == path for f in meta['files']):
56             yield dist
57 
58 
59 def print_object_info(info, key):
60     output_string = ""
61     gb = groupby(key, info)
62     for header in sorted(gb, key=str):
63         output_string += header + "\n"
64         for f_info in sorted(gb[header], key=getter('filename')):
65             for data in sorted(f_info):
66                 if data == key:
67                     continue
68                 if f_info[data] is None:
69                     continue
70                 output_string += '  %s: %s\n' % (data, f_info[data])
71             if len([i for i in f_info if f_info[i] is not None and i != key]) > 1:
72                 output_string += '\n'
73         output_string += '\n'
74     return output_string
75 
76 
77 class _untracked_package:
78     def __str__(self):
79         return "<untracked>"
80 
81 
82 untracked_package = _untracked_package()
83 
84 
85 def check_install(packages, platform=None, channel_urls=(), prepend=True,
86                   minimal_hint=False):
87     prefix = tempfile.mkdtemp('conda')
88     try:
89         specs = specs_from_args(packages)
90         index = get_index(channel_urls=channel_urls, prepend=prepend,
91                           platform=platform, prefix=prefix)
92         actions = install_actions(prefix, index, specs, pinned=False,
93                                   minimal_hint=minimal_hint)
94         display_actions(actions, index)
95         return actions
96     finally:
97         rm_rf(prefix)
98     return None
99 
100 
101 def print_linkages(depmap, show_files=False):
102     # Print system and not found last
103     dist_depmap = {}
104     for k, v in depmap.items():
105         if hasattr(k, 'dist_name'):
106             k = k.dist_name
107         dist_depmap[k] = v
108 
109     depmap = dist_depmap
110     k = sorted(set(depmap.keys()) - {'system', 'not found'})
111     all_deps = k if 'not found' not in depmap.keys() else k + ['system', 'not found']
112     output_string = ""
113     for dep in all_deps:
114         output_string += "%s:\n" % dep
115         if show_files:
116             for lib, path, binary in sorted(depmap[dep]):
117                 output_string += "    %s (%s) from %s\n" % (lib, path, binary)
118         else:
119             for lib, path in sorted(set(map(itemgetter(0, 1), depmap[dep]))):
120                 output_string += "    %s (%s)\n" % (lib, path)
121         output_string += "\n"
122     return output_string
123 
124 
125 def replace_path(binary, path, prefix):
126     if sys.platform.startswith('linux'):
127         return abspath(path)
128     elif sys.platform.startswith('darwin'):
129         if path == basename(binary):
130             return abspath(join(prefix, binary))
131         if '@rpath' in path:
132             rpaths = get_rpaths(join(prefix, binary))
133             if not rpaths:
134                 return "NO LC_RPATH FOUND"
135             else:
136                 for rpath in rpaths:
137                     path1 = path.replace("@rpath", rpath)
138                     path1 = path1.replace('@loader_path', join(prefix, dirname(binary)))
139                     if exists(abspath(join(prefix, path1))):
140                         path = path1
141                         break
142                 else:
143                     return 'not found'
144         path = path.replace('@loader_path', join(prefix, dirname(binary)))
145         if path.startswith('/'):
146             return abspath(path)
147         return 'not found'
148 
149 
150 def test_installable(channel='defaults'):
151     success = True
152     log = logging.getLogger(__name__)
153     has_py = re.compile(r'py(\d)(\d)')
154     for platform in ['osx-64', 'linux-32', 'linux-64', 'win-32', 'win-64']:
155         log.info("######## Testing platform %s ########", platform)
156         channels = [channel]
157         index = get_index(channel_urls=channels, prepend=False, platform=platform)
158         for _, rec in iteritems(index):
159             # If we give channels at the command line, only look at
160             # packages from those channels (not defaults).
161             if channel != 'defaults' and rec.get('schannel', 'defaults') == 'defaults':
162                 continue
163             name = rec['name']
164             if name in {'conda', 'conda-build'}:
165                 # conda can only be installed in the root environment
166                 continue
167             # Don't fail just because the package is a different version of Python
168             # than the default.  We should probably check depends rather than the
169             # build string.
170             build = rec['build']
171             match = has_py.search(build)
172             assert match if 'py' in build else True, build
173             if match:
174                 additional_packages = ['python=%s.%s' % (match.group(1), match.group(2))]
175             else:
176                 additional_packages = []
177 
178             version = rec['version']
179             log.info('Testing %s=%s', name, version)
180 
181             try:
182                 install_steps = check_install([name + '=' + version] + additional_packages,
183                                                 channel_urls=channels, prepend=False,
184                                                 platform=platform)
185                 success &= bool(install_steps)
186             except KeyboardInterrupt:
187                 raise
188             # sys.exit raises an exception that doesn't subclass from Exception
189             except BaseException as e:
190                 success = False
191                 log.error("FAIL: %s %s on %s with %s (%s)", name, version,
192                           platform, additional_packages, e)
193     return success
194 
195 
196 def _installed(prefix):
197     installed = linked_data(prefix)
198     installed = {rec['name']: dist for dist, rec in iteritems(installed)}
199     return installed
200 
201 
202 def _underlined_text(text):
203     return str(text) + '\n' + '-' * len(str(text)) + '\n\n'
204 
205 
206 def inspect_linkages(packages, prefix=sys.prefix, untracked=False,
207                      all_packages=False, show_files=False, groupby="package"):
208     pkgmap = {}
209 
210     installed = _installed(prefix)
211 
212     if not packages and not untracked and not all_packages:
213         raise ValueError("At least one package or --untracked or --all must be provided")
214 
215     if all_packages:
216         packages = sorted(installed.keys())
217 
218     if untracked:
219         packages.append(untracked_package)
220 
221     for pkg in packages:
222         if pkg == untracked_package:
223             dist = untracked_package
224         elif pkg not in installed:
225             sys.exit("Package %s is not installed in %s" % (pkg, prefix))
226         else:
227             dist = installed[pkg]
228 
229         if not sys.platform.startswith(('linux', 'darwin')):
230             sys.exit("Error: conda inspect linkages is only implemented in Linux and OS X")
231 
232         if dist == untracked_package:
233             obj_files = get_untracked_obj_files(prefix)
234         else:
235             obj_files = get_package_obj_files(dist, prefix)
236         linkages = get_linkages(obj_files, prefix)
237         depmap = defaultdict(list)
238         pkgmap[pkg] = depmap
239         depmap['not found'] = []
240         for binary in linkages:
241             for lib, path in linkages[binary]:
242                 path = replace_path(binary, path, prefix) if path not in {'',
243                                                                             'not found'} else path
244                 if path.startswith(prefix):
245                     deps = list(which_package(path))
246                     if len(deps) > 1:
247                         logging.getLogger(__name__).warn("Warning: %s comes from multiple "
248                                                          "packages: %s", path, comma_join(deps))
249                     if not deps:
250                         if exists(path):
251                             depmap['untracked'].append((lib, path.split(prefix +
252                                 '/', 1)[-1], binary))
253                         else:
254                             depmap['not found'].append((lib, path.split(prefix +
255                                 '/', 1)[-1], binary))
256                     for d in deps:
257                         depmap[d].append((lib, path.split(prefix + '/',
258                             1)[-1], binary))
259                 elif path == 'not found':
260                     depmap['not found'].append((lib, path, binary))
261                 else:
262                     depmap['system'].append((lib, path, binary))
263 
264     output_string = ""
265     if groupby == 'package':
266         for pkg in packages:
267             output_string += _underlined_text(pkg)
268             output_string += print_linkages(pkgmap[pkg], show_files=show_files)
269 
270     elif groupby == 'dependency':
271         # {pkg: {dep: [files]}} -> {dep: {pkg: [files]}}
272         inverted_map = defaultdict(lambda: defaultdict(list))
273         for pkg in pkgmap:
274             for dep in pkgmap[pkg]:
275                 if pkgmap[pkg][dep]:
276                     inverted_map[dep][pkg] = pkgmap[pkg][dep]
277 
278         # print system and not found last
279         k = sorted(set(inverted_map.keys()) - {'system', 'not found'})
280         for dep in k + ['system', 'not found']:
281             output_string += _underlined_text(dep)
282             output_string += print_linkages(inverted_map[dep], show_files=show_files)
283 
284     else:
285         raise ValueError("Unrecognized groupby: %s" % groupby)
286     if hasattr(output_string, 'decode'):
287         output_string = output_string.decode('utf-8')
288     return output_string
289 
290 
291 def inspect_objects(packages, prefix=sys.prefix, groupby='package'):
292     installed = _installed(prefix)
293 
294     output_string = ""
295     for pkg in packages:
296         if pkg == untracked_package:
297             dist = untracked_package
298         elif pkg not in installed:
299             raise ValueError("Package %s is not installed in %s" % (pkg, prefix))
300         else:
301             dist = installed[pkg]
302 
303         output_string += _underlined_text(pkg)
304 
305         if not sys.platform.startswith('darwin'):
306             sys.exit("Error: conda inspect objects is only implemented in OS X")
307 
308         if dist == untracked_package:
309             obj_files = get_untracked_obj_files(prefix)
310         else:
311             obj_files = get_package_obj_files(dist, prefix)
312 
313         info = []
314         for f in obj_files:
315             f_info = {}
316             path = join(prefix, f)
317             f_info['filetype'] = human_filetype(path)
318             f_info['rpath'] = ':'.join(get_rpaths(path))
319             f_info['filename'] = f
320             info.append(f_info)
321 
322         output_string += print_object_info(info, groupby)
323     if hasattr(output_string, 'decode'):
324         output_string = output_string.decode('utf-8')
325     return output_string
326
```
--- 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/conda_build/inspect.py b/conda_build/inspect.py
--- a/conda_build/inspect.py
+++ b/conda_build/inspect.py
@@ -237,6 +237,7 @@
         depmap = defaultdict(list)
         pkgmap[pkg] = depmap
         depmap['not found'] = []
+        depmap['system'] = []
         for binary in linkages:
             for lib, path in linkages[binary]:
                 path = replace_path(binary, path, prefix) if path not in {'',

{"golden_diff": "diff --git a/conda_build/inspect.py b/conda_build/inspect.py\n--- a/conda_build/inspect.py\n+++ b/conda_build/inspect.py\n@@ -237,6 +237,7 @@\n         depmap = defaultdict(list)\n         pkgmap[pkg] = depmap\n         depmap['not found'] = []\n+        depmap['system'] = []\n         for binary in linkages:\n             for lib, path in linkages[binary]:\n                 path = replace_path(binary, path, prefix) if path not in {'',\n", "issue": "conda build 2.1.6 sporadic failures\nAfter updating 2.1.5 to 2.1.6, I now have sporadic (non reproductible) failures with conda build\r\n\r\n```bash\r\nRuntimeError: Can't build <whatever> due to unsatisfiable dependencies:\r\n\r\nPackages/dependencies missing in current linux-64 channels: \r\n  - openssl\r\n  - zlib\r\n  - ...\r\n```\r\n, only on dependencies provided with the conda distribution (e.g. xz, zlib, ...)\r\n\r\nVery annoying on running nightly builds (sometimes crashing, sometimes not)\r\n\r\nAny clues on where to look (changes between versions) ?\r\n\r\nconda --version is 4.3.14\r\n\r\nthanks\n", "before_files": [{"content": "# (c) Continuum Analytics, Inc. / http://continuum.io\n# All Rights Reserved\n#\n# conda is distributed under the terms of the BSD 3-clause license.\n# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom collections import defaultdict\nimport logging\nfrom operator import itemgetter\nfrom os.path import abspath, join, dirname, exists, basename, isdir\nimport re\nimport sys\nimport tempfile\n\nfrom .conda_interface import (iteritems, specs_from_args, is_linked, linked_data, linked,\n                              get_index)\nfrom .conda_interface import display_actions, install_actions\n\n\nfrom conda_build.os_utils.ldd import get_linkages, get_package_obj_files, get_untracked_obj_files\nfrom conda_build.os_utils.macho import get_rpaths, human_filetype\nfrom conda_build.utils import groupby, getter, comma_join, rm_rf\n\n\ndef which_prefix(path):\n    \"\"\"\n    given the path (to a (presumably) conda installed file) return the\n    environment prefix in which the file in located\n    \"\"\"\n    prefix = abspath(path)\n    while True:\n        if isdir(join(prefix, 'conda-meta')):\n            # we found the it, so let's return it\n            return prefix\n        if prefix == dirname(prefix):\n            # we cannot chop off any more directories, so we didn't find it\n            return None\n        prefix = dirname(prefix)\n\n\ndef which_package(path):\n    \"\"\"\n    given the path (of a (presumably) conda installed file) iterate over\n    the conda packages the file came from.  Usually the iteration yields\n    only one package.\n    \"\"\"\n    path = abspath(path)\n    prefix = which_prefix(path)\n    if prefix is None:\n        raise RuntimeError(\"could not determine conda prefix from: %s\" % path)\n    for dist in linked(prefix):\n        meta = is_linked(prefix, dist)\n        if any(abspath(join(prefix, f)) == path for f in meta['files']):\n            yield dist\n\n\ndef print_object_info(info, key):\n    output_string = \"\"\n    gb = groupby(key, info)\n    for header in sorted(gb, key=str):\n        output_string += header + \"\\n\"\n        for f_info in sorted(gb[header], key=getter('filename')):\n            for data in sorted(f_info):\n                if data == key:\n                    continue\n                if f_info[data] is None:\n                    continue\n                output_string += '  %s: %s\\n' % (data, f_info[data])\n            if len([i for i in f_info if f_info[i] is not None and i != key]) > 1:\n                output_string += '\\n'\n        output_string += '\\n'\n    return output_string\n\n\nclass _untracked_package:\n    def __str__(self):\n        return \"<untracked>\"\n\n\nuntracked_package = _untracked_package()\n\n\ndef check_install(packages, platform=None, channel_urls=(), prepend=True,\n                  minimal_hint=False):\n    prefix = tempfile.mkdtemp('conda')\n    try:\n        specs = specs_from_args(packages)\n        index = get_index(channel_urls=channel_urls, prepend=prepend,\n                          platform=platform, prefix=prefix)\n        actions = install_actions(prefix, index, specs, pinned=False,\n                                  minimal_hint=minimal_hint)\n        display_actions(actions, index)\n        return actions\n    finally:\n        rm_rf(prefix)\n    return None\n\n\ndef print_linkages(depmap, show_files=False):\n    # Print system and not found last\n    dist_depmap = {}\n    for k, v in depmap.items():\n        if hasattr(k, 'dist_name'):\n            k = k.dist_name\n        dist_depmap[k] = v\n\n    depmap = dist_depmap\n    k = sorted(set(depmap.keys()) - {'system', 'not found'})\n    all_deps = k if 'not found' not in depmap.keys() else k + ['system', 'not found']\n    output_string = \"\"\n    for dep in all_deps:\n        output_string += \"%s:\\n\" % dep\n        if show_files:\n            for lib, path, binary in sorted(depmap[dep]):\n                output_string += \"    %s (%s) from %s\\n\" % (lib, path, binary)\n        else:\n            for lib, path in sorted(set(map(itemgetter(0, 1), depmap[dep]))):\n                output_string += \"    %s (%s)\\n\" % (lib, path)\n        output_string += \"\\n\"\n    return output_string\n\n\ndef replace_path(binary, path, prefix):\n    if sys.platform.startswith('linux'):\n        return abspath(path)\n    elif sys.platform.startswith('darwin'):\n        if path == basename(binary):\n            return abspath(join(prefix, binary))\n        if '@rpath' in path:\n            rpaths = get_rpaths(join(prefix, binary))\n            if not rpaths:\n                return \"NO LC_RPATH FOUND\"\n            else:\n                for rpath in rpaths:\n                    path1 = path.replace(\"@rpath\", rpath)\n                    path1 = path1.replace('@loader_path', join(prefix, dirname(binary)))\n                    if exists(abspath(join(prefix, path1))):\n                        path = path1\n                        break\n                else:\n                    return 'not found'\n        path = path.replace('@loader_path', join(prefix, dirname(binary)))\n        if path.startswith('/'):\n            return abspath(path)\n        return 'not found'\n\n\ndef test_installable(channel='defaults'):\n    success = True\n    log = logging.getLogger(__name__)\n    has_py = re.compile(r'py(\\d)(\\d)')\n    for platform in ['osx-64', 'linux-32', 'linux-64', 'win-32', 'win-64']:\n        log.info(\"######## Testing platform %s ########\", platform)\n        channels = [channel]\n        index = get_index(channel_urls=channels, prepend=False, platform=platform)\n        for _, rec in iteritems(index):\n            # If we give channels at the command line, only look at\n            # packages from those channels (not defaults).\n            if channel != 'defaults' and rec.get('schannel', 'defaults') == 'defaults':\n                continue\n            name = rec['name']\n            if name in {'conda', 'conda-build'}:\n                # conda can only be installed in the root environment\n                continue\n            # Don't fail just because the package is a different version of Python\n            # than the default.  We should probably check depends rather than the\n            # build string.\n            build = rec['build']\n            match = has_py.search(build)\n            assert match if 'py' in build else True, build\n            if match:\n                additional_packages = ['python=%s.%s' % (match.group(1), match.group(2))]\n            else:\n                additional_packages = []\n\n            version = rec['version']\n            log.info('Testing %s=%s', name, version)\n\n            try:\n                install_steps = check_install([name + '=' + version] + additional_packages,\n                                                channel_urls=channels, prepend=False,\n                                                platform=platform)\n                success &= bool(install_steps)\n            except KeyboardInterrupt:\n                raise\n            # sys.exit raises an exception that doesn't subclass from Exception\n            except BaseException as e:\n                success = False\n                log.error(\"FAIL: %s %s on %s with %s (%s)\", name, version,\n                          platform, additional_packages, e)\n    return success\n\n\ndef _installed(prefix):\n    installed = linked_data(prefix)\n    installed = {rec['name']: dist for dist, rec in iteritems(installed)}\n    return installed\n\n\ndef _underlined_text(text):\n    return str(text) + '\\n' + '-' * len(str(text)) + '\\n\\n'\n\n\ndef inspect_linkages(packages, prefix=sys.prefix, untracked=False,\n                     all_packages=False, show_files=False, groupby=\"package\"):\n    pkgmap = {}\n\n    installed = _installed(prefix)\n\n    if not packages and not untracked and not all_packages:\n        raise ValueError(\"At least one package or --untracked or --all must be provided\")\n\n    if all_packages:\n        packages = sorted(installed.keys())\n\n    if untracked:\n        packages.append(untracked_package)\n\n    for pkg in packages:\n        if pkg == untracked_package:\n            dist = untracked_package\n        elif pkg not in installed:\n            sys.exit(\"Package %s is not installed in %s\" % (pkg, prefix))\n        else:\n            dist = installed[pkg]\n\n        if not sys.platform.startswith(('linux', 'darwin')):\n            sys.exit(\"Error: conda inspect linkages is only implemented in Linux and OS X\")\n\n        if dist == untracked_package:\n            obj_files = get_untracked_obj_files(prefix)\n        else:\n            obj_files = get_package_obj_files(dist, prefix)\n        linkages = get_linkages(obj_files, prefix)\n        depmap = defaultdict(list)\n        pkgmap[pkg] = depmap\n        depmap['not found'] = []\n        for binary in linkages:\n            for lib, path in linkages[binary]:\n                path = replace_path(binary, path, prefix) if path not in {'',\n                                                                            'not found'} else path\n                if path.startswith(prefix):\n                    deps = list(which_package(path))\n                    if len(deps) > 1:\n                        logging.getLogger(__name__).warn(\"Warning: %s comes from multiple \"\n                                                         \"packages: %s\", path, comma_join(deps))\n                    if not deps:\n                        if exists(path):\n                            depmap['untracked'].append((lib, path.split(prefix +\n                                '/', 1)[-1], binary))\n                        else:\n                            depmap['not found'].append((lib, path.split(prefix +\n                                '/', 1)[-1], binary))\n                    for d in deps:\n                        depmap[d].append((lib, path.split(prefix + '/',\n                            1)[-1], binary))\n                elif path == 'not found':\n                    depmap['not found'].append((lib, path, binary))\n                else:\n                    depmap['system'].append((lib, path, binary))\n\n    output_string = \"\"\n    if groupby == 'package':\n        for pkg in packages:\n            output_string += _underlined_text(pkg)\n            output_string += print_linkages(pkgmap[pkg], show_files=show_files)\n\n    elif groupby == 'dependency':\n        # {pkg: {dep: [files]}} -> {dep: {pkg: [files]}}\n        inverted_map = defaultdict(lambda: defaultdict(list))\n        for pkg in pkgmap:\n            for dep in pkgmap[pkg]:\n                if pkgmap[pkg][dep]:\n                    inverted_map[dep][pkg] = pkgmap[pkg][dep]\n\n        # print system and not found last\n        k = sorted(set(inverted_map.keys()) - {'system', 'not found'})\n        for dep in k + ['system', 'not found']:\n            output_string += _underlined_text(dep)\n            output_string += print_linkages(inverted_map[dep], show_files=show_files)\n\n    else:\n        raise ValueError(\"Unrecognized groupby: %s\" % groupby)\n    if hasattr(output_string, 'decode'):\n        output_string = output_string.decode('utf-8')\n    return output_string\n\n\ndef inspect_objects(packages, prefix=sys.prefix, groupby='package'):\n    installed = _installed(prefix)\n\n    output_string = \"\"\n    for pkg in packages:\n        if pkg == untracked_package:\n            dist = untracked_package\n        elif pkg not in installed:\n            raise ValueError(\"Package %s is not installed in %s\" % (pkg, prefix))\n        else:\n            dist = installed[pkg]\n\n        output_string += _underlined_text(pkg)\n\n        if not sys.platform.startswith('darwin'):\n            sys.exit(\"Error: conda inspect objects is only implemented in OS X\")\n\n        if dist == untracked_package:\n            obj_files = get_untracked_obj_files(prefix)\n        else:\n            obj_files = get_package_obj_files(dist, prefix)\n\n        info = []\n        for f in obj_files:\n            f_info = {}\n            path = join(prefix, f)\n            f_info['filetype'] = human_filetype(path)\n            f_info['rpath'] = ':'.join(get_rpaths(path))\n            f_info['filename'] = f\n            info.append(f_info)\n\n        output_string += print_object_info(info, groupby)\n    if hasattr(output_string, 'decode'):\n        output_string = output_string.decode('utf-8')\n    return output_string\n", "path": "conda_build/inspect.py"}], "after_files": [{"content": "# (c) Continuum Analytics, Inc. / http://continuum.io\n# All Rights Reserved\n#\n# conda is distributed under the terms of the BSD 3-clause license.\n# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom collections import defaultdict\nimport logging\nfrom operator import itemgetter\nfrom os.path import abspath, join, dirname, exists, basename, isdir\nimport re\nimport sys\nimport tempfile\n\nfrom .conda_interface import (iteritems, specs_from_args, is_linked, linked_data, linked,\n                              get_index)\nfrom .conda_interface import display_actions, install_actions\n\n\nfrom conda_build.os_utils.ldd import get_linkages, get_package_obj_files, get_untracked_obj_files\nfrom conda_build.os_utils.macho import get_rpaths, human_filetype\nfrom conda_build.utils import groupby, getter, comma_join, rm_rf\n\n\ndef which_prefix(path):\n    \"\"\"\n    given the path (to a (presumably) conda installed file) return the\n    environment prefix in which the file in located\n    \"\"\"\n    prefix = abspath(path)\n    while True:\n        if isdir(join(prefix, 'conda-meta')):\n            # we found the it, so let's return it\n            return prefix\n        if prefix == dirname(prefix):\n            # we cannot chop off any more directories, so we didn't find it\n            return None\n        prefix = dirname(prefix)\n\n\ndef which_package(path):\n    \"\"\"\n    given the path (of a (presumably) conda installed file) iterate over\n    the conda packages the file came from.  Usually the iteration yields\n    only one package.\n    \"\"\"\n    path = abspath(path)\n    prefix = which_prefix(path)\n    if prefix is None:\n        raise RuntimeError(\"could not determine conda prefix from: %s\" % path)\n    for dist in linked(prefix):\n        meta = is_linked(prefix, dist)\n        if any(abspath(join(prefix, f)) == path for f in meta['files']):\n            yield dist\n\n\ndef print_object_info(info, key):\n    output_string = \"\"\n    gb = groupby(key, info)\n    for header in sorted(gb, key=str):\n        output_string += header + \"\\n\"\n        for f_info in sorted(gb[header], key=getter('filename')):\n            for data in sorted(f_info):\n                if data == key:\n                    continue\n                if f_info[data] is None:\n                    continue\n                output_string += '  %s: %s\\n' % (data, f_info[data])\n            if len([i for i in f_info if f_info[i] is not None and i != key]) > 1:\n                output_string += '\\n'\n        output_string += '\\n'\n    return output_string\n\n\nclass _untracked_package:\n    def __str__(self):\n        return \"<untracked>\"\n\n\nuntracked_package = _untracked_package()\n\n\ndef check_install(packages, platform=None, channel_urls=(), prepend=True,\n                  minimal_hint=False):\n    prefix = tempfile.mkdtemp('conda')\n    try:\n        specs = specs_from_args(packages)\n        index = get_index(channel_urls=channel_urls, prepend=prepend,\n                          platform=platform, prefix=prefix)\n        actions = install_actions(prefix, index, specs, pinned=False,\n                                  minimal_hint=minimal_hint)\n        display_actions(actions, index)\n        return actions\n    finally:\n        rm_rf(prefix)\n    return None\n\n\ndef print_linkages(depmap, show_files=False):\n    # Print system and not found last\n    dist_depmap = {}\n    for k, v in depmap.items():\n        if hasattr(k, 'dist_name'):\n            k = k.dist_name\n        dist_depmap[k] = v\n\n    depmap = dist_depmap\n    k = sorted(set(depmap.keys()) - {'system', 'not found'})\n    all_deps = k if 'not found' not in depmap.keys() else k + ['system', 'not found']\n    output_string = \"\"\n    for dep in all_deps:\n        output_string += \"%s:\\n\" % dep\n        if show_files:\n            for lib, path, binary in sorted(depmap[dep]):\n                output_string += \"    %s (%s) from %s\\n\" % (lib, path, binary)\n        else:\n            for lib, path in sorted(set(map(itemgetter(0, 1), depmap[dep]))):\n                output_string += \"    %s (%s)\\n\" % (lib, path)\n        output_string += \"\\n\"\n    return output_string\n\n\ndef replace_path(binary, path, prefix):\n    if sys.platform.startswith('linux'):\n        return abspath(path)\n    elif sys.platform.startswith('darwin'):\n        if path == basename(binary):\n            return abspath(join(prefix, binary))\n        if '@rpath' in path:\n            rpaths = get_rpaths(join(prefix, binary))\n            if not rpaths:\n                return \"NO LC_RPATH FOUND\"\n            else:\n                for rpath in rpaths:\n                    path1 = path.replace(\"@rpath\", rpath)\n                    path1 = path1.replace('@loader_path', join(prefix, dirname(binary)))\n                    if exists(abspath(join(prefix, path1))):\n                        path = path1\n                        break\n                else:\n                    return 'not found'\n        path = path.replace('@loader_path', join(prefix, dirname(binary)))\n        if path.startswith('/'):\n            return abspath(path)\n        return 'not found'\n\n\ndef test_installable(channel='defaults'):\n    success = True\n    log = logging.getLogger(__name__)\n    has_py = re.compile(r'py(\\d)(\\d)')\n    for platform in ['osx-64', 'linux-32', 'linux-64', 'win-32', 'win-64']:\n        log.info(\"######## Testing platform %s ########\", platform)\n        channels = [channel]\n        index = get_index(channel_urls=channels, prepend=False, platform=platform)\n        for _, rec in iteritems(index):\n            # If we give channels at the command line, only look at\n            # packages from those channels (not defaults).\n            if channel != 'defaults' and rec.get('schannel', 'defaults') == 'defaults':\n                continue\n            name = rec['name']\n            if name in {'conda', 'conda-build'}:\n                # conda can only be installed in the root environment\n                continue\n            # Don't fail just because the package is a different version of Python\n            # than the default.  We should probably check depends rather than the\n            # build string.\n            build = rec['build']\n            match = has_py.search(build)\n            assert match if 'py' in build else True, build\n            if match:\n                additional_packages = ['python=%s.%s' % (match.group(1), match.group(2))]\n            else:\n                additional_packages = []\n\n            version = rec['version']\n            log.info('Testing %s=%s', name, version)\n\n            try:\n                install_steps = check_install([name + '=' + version] + additional_packages,\n                                                channel_urls=channels, prepend=False,\n                                                platform=platform)\n                success &= bool(install_steps)\n            except KeyboardInterrupt:\n                raise\n            # sys.exit raises an exception that doesn't subclass from Exception\n            except BaseException as e:\n                success = False\n                log.error(\"FAIL: %s %s on %s with %s (%s)\", name, version,\n                          platform, additional_packages, e)\n    return success\n\n\ndef _installed(prefix):\n    installed = linked_data(prefix)\n    installed = {rec['name']: dist for dist, rec in iteritems(installed)}\n    return installed\n\n\ndef _underlined_text(text):\n    return str(text) + '\\n' + '-' * len(str(text)) + '\\n\\n'\n\n\ndef inspect_linkages(packages, prefix=sys.prefix, untracked=False,\n                     all_packages=False, show_files=False, groupby=\"package\"):\n    pkgmap = {}\n\n    installed = _installed(prefix)\n\n    if not packages and not untracked and not all_packages:\n        raise ValueError(\"At least one package or --untracked or --all must be provided\")\n\n    if all_packages:\n        packages = sorted(installed.keys())\n\n    if untracked:\n        packages.append(untracked_package)\n\n    for pkg in packages:\n        if pkg == untracked_package:\n            dist = untracked_package\n        elif pkg not in installed:\n            sys.exit(\"Package %s is not installed in %s\" % (pkg, prefix))\n        else:\n            dist = installed[pkg]\n\n        if not sys.platform.startswith(('linux', 'darwin')):\n            sys.exit(\"Error: conda inspect linkages is only implemented in Linux and OS X\")\n\n        if dist == untracked_package:\n            obj_files = get_untracked_obj_files(prefix)\n        else:\n            obj_files = get_package_obj_files(dist, prefix)\n        linkages = get_linkages(obj_files, prefix)\n        depmap = defaultdict(list)\n        pkgmap[pkg] = depmap\n        depmap['not found'] = []\n        depmap['system'] = []\n        for binary in linkages:\n            for lib, path in linkages[binary]:\n                path = replace_path(binary, path, prefix) if path not in {'',\n                                                                            'not found'} else path\n                if path.startswith(prefix):\n                    deps = list(which_package(path))\n                    if len(deps) > 1:\n                        logging.getLogger(__name__).warn(\"Warning: %s comes from multiple \"\n                                                         \"packages: %s\", path, comma_join(deps))\n                    if not deps:\n                        if exists(path):\n                            depmap['untracked'].append((lib, path.split(prefix +\n                                '/', 1)[-1], binary))\n                        else:\n                            depmap['not found'].append((lib, path.split(prefix +\n                                '/', 1)[-1], binary))\n                    for d in deps:\n                        depmap[d].append((lib, path.split(prefix + '/',\n                            1)[-1], binary))\n                elif path == 'not found':\n                    depmap['not found'].append((lib, path, binary))\n                else:\n                    depmap['system'].append((lib, path, binary))\n\n    output_string = \"\"\n    if groupby == 'package':\n        for pkg in packages:\n            output_string += _underlined_text(pkg)\n            output_string += print_linkages(pkgmap[pkg], show_files=show_files)\n\n    elif groupby == 'dependency':\n        # {pkg: {dep: [files]}} -> {dep: {pkg: [files]}}\n        inverted_map = defaultdict(lambda: defaultdict(list))\n        for pkg in pkgmap:\n            for dep in pkgmap[pkg]:\n                if pkgmap[pkg][dep]:\n                    inverted_map[dep][pkg] = pkgmap[pkg][dep]\n\n        # print system and not found last\n        k = sorted(set(inverted_map.keys()) - {'system', 'not found'})\n        for dep in k + ['system', 'not found']:\n            output_string += _underlined_text(dep)\n            output_string += print_linkages(inverted_map[dep], show_files=show_files)\n\n    else:\n        raise ValueError(\"Unrecognized groupby: %s\" % groupby)\n    if hasattr(output_string, 'decode'):\n        output_string = output_string.decode('utf-8')\n    return output_string\n\n\ndef inspect_objects(packages, prefix=sys.prefix, groupby='package'):\n    installed = _installed(prefix)\n\n    output_string = \"\"\n    for pkg in packages:\n        if pkg == untracked_package:\n            dist = untracked_package\n        elif pkg not in installed:\n            raise ValueError(\"Package %s is not installed in %s\" % (pkg, prefix))\n        else:\n            dist = installed[pkg]\n\n        output_string += _underlined_text(pkg)\n\n        if not sys.platform.startswith('darwin'):\n            sys.exit(\"Error: conda inspect objects is only implemented in OS X\")\n\n        if dist == untracked_package:\n            obj_files = get_untracked_obj_files(prefix)\n        else:\n            obj_files = get_package_obj_files(dist, prefix)\n\n        info = []\n        for f in obj_files:\n            f_info = {}\n            path = join(prefix, f)\n            f_info['filetype'] = human_filetype(path)\n            f_info['rpath'] = ':'.join(get_rpaths(path))\n            f_info['filename'] = f\n            info.append(f_info)\n\n        output_string += print_object_info(info, groupby)\n    if hasattr(output_string, 'decode'):\n        output_string = output_string.decode('utf-8')\n    return output_string\n", "path": "conda_build/inspect.py"}]}