We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
--yes not functioning for "Clean"
Hi, either `conda clean -y --all` or `conda clean --yes --all` still prompt for a confirmation. 

conda 4.2.13
macOS 10.12.4

--- 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/cli/main_clean.py`
Content:
```
1 # (c) 2012-2016 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 from __future__ import absolute_import, division, print_function, unicode_literals
7 
8 from collections import defaultdict
9 from logging import getLogger
10 import os
11 from os import listdir, lstat, walk
12 from os.path import getsize, isdir, join
13 import sys
14 
15 from .common import add_parser_json, add_parser_yes, confirm_yn, stdout_json
16 from ..base.constants import CONDA_TARBALL_EXTENSION
17 from ..base.context import context
18 from ..exceptions import ArgumentError
19 from ..gateways.disk.delete import rm_rf
20 from ..gateways.disk.link import CrossPlatformStLink
21 from ..utils import human_bytes
22 
23 log = getLogger(__name__)
24 
25 descr = """
26 Remove unused packages and caches.
27 """
28 
29 example = """
30 Examples:
31 
32     conda clean --tarballs
33 """
34 
35 def configure_parser(sub_parsers):
36     p = sub_parsers.add_parser(
37         'clean',
38         description=descr,
39         help=descr,
40         epilog=example,
41     )
42     add_parser_yes(p)
43     add_parser_json(p)
44     p.add_argument(
45         "-a", "--all",
46         action="store_true",
47         help="Remove index cache, lock files, tarballs, "
48              "unused cache packages, and source cache.",
49     )
50     p.add_argument(
51         "-i", "--index-cache",
52         action="store_true",
53         help="Remove index cache.",
54     )
55     p.add_argument(
56         "-l", "--lock",
57         action="store_true",
58         help="Remove all conda lock files.",
59     )
60     p.add_argument(
61         "-t", "--tarballs",
62         action="store_true",
63         help="Remove cached package tarballs.",
64     )
65     p.add_argument(
66         '-p', '--packages',
67         action='store_true',
68         help="""Remove unused cached packages. Warning: this does not check
69     for symlinked packages.""",
70     )
71     p.add_argument(
72         '-s', '--source-cache',
73         action='store_true',
74         help="""Remove files from the source cache of conda build.""",
75     )
76     p.set_defaults(func=execute)
77 
78 
79 def find_tarballs():
80     from ..core.package_cache import PackageCache
81     pkgs_dirs = defaultdict(list)
82     totalsize = 0
83     part_ext = CONDA_TARBALL_EXTENSION + '.part'
84     for package_cache in PackageCache.all_writable(context.pkgs_dirs):
85         pkgs_dir = package_cache.pkgs_dir
86         if not isdir(pkgs_dir):
87             continue
88         root, _, filenames = next(os.walk(pkgs_dir))
89         for fn in filenames:
90             if fn.endswith(CONDA_TARBALL_EXTENSION) or fn.endswith(part_ext):
91                 pkgs_dirs[pkgs_dir].append(fn)
92                 totalsize += getsize(join(root, fn))
93 
94     return pkgs_dirs, totalsize
95 
96 
97 def rm_tarballs(args, pkgs_dirs, totalsize, verbose=True):
98     if verbose:
99         for pkgs_dir in pkgs_dirs:
100             print('Cache location: %s' % pkgs_dir)
101 
102     if not any(pkgs_dirs[i] for i in pkgs_dirs):
103         if verbose:
104             print("There are no tarballs to remove")
105         return
106 
107     if verbose:
108         print("Will remove the following tarballs:")
109         print()
110 
111         for pkgs_dir in pkgs_dirs:
112             print(pkgs_dir)
113             print('-'*len(pkgs_dir))
114             fmt = "%-40s %10s"
115             for fn in pkgs_dirs[pkgs_dir]:
116                 size = getsize(join(pkgs_dir, fn))
117                 print(fmt % (fn, human_bytes(size)))
118             print()
119         print('-' * 51)  # From 40 + 1 + 10 in fmt
120         print(fmt % ('Total:', human_bytes(totalsize)))
121         print()
122 
123     if not context.json:
124         confirm_yn(args)
125     if context.json and args.dry_run:
126         return
127 
128     for pkgs_dir in pkgs_dirs:
129         for fn in pkgs_dirs[pkgs_dir]:
130             try:
131                 if rm_rf(os.path.join(pkgs_dir, fn)):
132                     if verbose:
133                         print("Removed %s" % fn)
134                 else:
135                     if verbose:
136                         print("WARNING: cannot remove, file permissions: %s" % fn)
137             except (IOError, OSError) as e:
138                 if verbose:
139                     print("WARNING: cannot remove, file permissions: %s\n%r" % (fn, e))
140                 else:
141                     log.info("%r", e)
142 
143 
144 def find_pkgs():
145     # TODO: This doesn't handle packages that have hard links to files within
146     # themselves, like bin/python3.3 and bin/python3.3m in the Python package
147     warnings = []
148 
149     cross_platform_st_nlink = CrossPlatformStLink()
150     pkgs_dirs = defaultdict(list)
151     for pkgs_dir in context.pkgs_dirs:
152         if not os.path.exists(pkgs_dir):
153             print("WARNING: {0} does not exist".format(pkgs_dir))
154             continue
155         pkgs = [i for i in listdir(pkgs_dir)
156                 if (isdir(join(pkgs_dir, i)) and  # only include actual packages
157                     isdir(join(pkgs_dir, i, 'info')))]
158         for pkg in pkgs:
159             breakit = False
160             for root, dir, files in walk(join(pkgs_dir, pkg)):
161                 for fn in files:
162                     try:
163                         st_nlink = cross_platform_st_nlink(join(root, fn))
164                     except OSError as e:
165                         warnings.append((fn, e))
166                         continue
167                     if st_nlink > 1:
168                         # print('%s is installed: %s' % (pkg, join(root, fn)))
169                         breakit = True
170                         break
171 
172                 if breakit:
173                     break
174             else:
175                 pkgs_dirs[pkgs_dir].append(pkg)
176 
177     totalsize = 0
178     pkgsizes = defaultdict(list)
179     for pkgs_dir in pkgs_dirs:
180         for pkg in pkgs_dirs[pkgs_dir]:
181             pkgsize = 0
182             for root, dir, files in walk(join(pkgs_dir, pkg)):
183                 for fn in files:
184                     # We don't have to worry about counting things twice:  by
185                     # definition these files all have a link count of 1!
186                     size = lstat(join(root, fn)).st_size
187                     totalsize += size
188                     pkgsize += size
189             pkgsizes[pkgs_dir].append(pkgsize)
190 
191     return pkgs_dirs, warnings, totalsize, pkgsizes
192 
193 
194 def rm_pkgs(args, pkgs_dirs, warnings, totalsize, pkgsizes,
195             verbose=True):
196     if verbose:
197         for pkgs_dir in pkgs_dirs:
198             print('Cache location: %s' % pkgs_dir)
199             for fn, exception in warnings:
200                 print(exception)
201 
202     if not any(pkgs_dirs[i] for i in pkgs_dirs):
203         if verbose:
204             print("There are no unused packages to remove")
205         return
206 
207     if verbose:
208         print("Will remove the following packages:")
209         for pkgs_dir in pkgs_dirs:
210             print(pkgs_dir)
211             print('-' * len(pkgs_dir))
212             print()
213             fmt = "%-40s %10s"
214             for pkg, pkgsize in zip(pkgs_dirs[pkgs_dir], pkgsizes[pkgs_dir]):
215                 print(fmt % (pkg, human_bytes(pkgsize)))
216             print()
217         print('-' * 51)  # 40 + 1 + 10 in fmt
218         print(fmt % ('Total:', human_bytes(totalsize)))
219         print()
220 
221     if not context.json:
222         confirm_yn(args)
223     if context.json and args.dry_run:
224         return
225 
226     for pkgs_dir in pkgs_dirs:
227         for pkg in pkgs_dirs[pkgs_dir]:
228             if verbose:
229                 print("removing %s" % pkg)
230             rm_rf(join(pkgs_dir, pkg))
231 
232 
233 def rm_index_cache():
234     from ..gateways.disk.delete import rm_rf
235     from ..core.package_cache import PackageCache
236     for package_cache in PackageCache.all_writable():
237         rm_rf(join(package_cache.pkgs_dir, 'cache'))
238 
239 
240 def find_source_cache():
241     cache_dirs = {
242         'source cache': context.src_cache,
243         'git cache': context.git_cache,
244         'hg cache': context.hg_cache,
245         'svn cache': context.svn_cache,
246     }
247 
248     sizes = {}
249     totalsize = 0
250     for cache_type, cache_dir in cache_dirs.items():
251         dirsize = 0
252         for root, d, files in walk(cache_dir):
253             for fn in files:
254                 size = lstat(join(root, fn)).st_size
255                 totalsize += size
256                 dirsize += size
257         sizes[cache_type] = dirsize
258 
259     return {
260         'warnings': [],
261         'cache_dirs': cache_dirs,
262         'cache_sizes': sizes,
263         'total_size': totalsize,
264     }
265 
266 
267 def rm_source_cache(args, cache_dirs, warnings, cache_sizes, total_size):
268     verbose = not context.json
269     if warnings:
270         if verbose:
271             for warning in warnings:
272                 print(warning, file=sys.stderr)
273         return
274 
275     for cache_type in cache_dirs:
276         print("%s (%s)" % (cache_type, cache_dirs[cache_type]))
277         print("%-40s %10s" % ("Size:", human_bytes(cache_sizes[cache_type])))
278         print()
279 
280     print("%-40s %10s" % ("Total:", human_bytes(total_size)))
281 
282     if not context.json:
283         confirm_yn(args)
284     if context.json and args.dry_run:
285         return
286 
287     for dir in cache_dirs.values():
288         print("Removing %s" % dir)
289         rm_rf(dir)
290 
291 
292 def execute(args, parser):
293     json_result = {
294         'success': True
295     }
296 
297     if args.tarballs or args.all:
298         pkgs_dirs, totalsize = find_tarballs()
299         first = sorted(pkgs_dirs)[0] if pkgs_dirs else ''
300         json_result['tarballs'] = {
301             'pkgs_dir': first,  # Backwards compabitility
302             'pkgs_dirs': dict(pkgs_dirs),
303             'files': pkgs_dirs[first],  # Backwards compatibility
304             'total_size': totalsize
305         }
306         rm_tarballs(args, pkgs_dirs, totalsize, verbose=not context.json)
307 
308     if args.index_cache or args.all:
309         json_result['index_cache'] = {
310             'files': [join(context.pkgs_dirs[0], 'cache')]
311         }
312         rm_index_cache()
313 
314     if args.packages or args.all:
315         pkgs_dirs, warnings, totalsize, pkgsizes = find_pkgs()
316         first = sorted(pkgs_dirs)[0] if pkgs_dirs else ''
317         json_result['packages'] = {
318             'pkgs_dir': first,  # Backwards compatibility
319             'pkgs_dirs': dict(pkgs_dirs),
320             'files': pkgs_dirs[first],  # Backwards compatibility
321             'total_size': totalsize,
322             'warnings': warnings,
323             'pkg_sizes': {i: dict(zip(pkgs_dirs[i], pkgsizes[i])) for i in pkgs_dirs},
324         }
325         rm_pkgs(args, pkgs_dirs,  warnings, totalsize, pkgsizes,
326                 verbose=not context.json)
327 
328     if args.source_cache or args.all:
329         json_result['source_cache'] = find_source_cache()
330         rm_source_cache(args, **json_result['source_cache'])
331 
332     if not any((args.lock, args.tarballs, args.index_cache, args.packages,
333                 args.source_cache, args.all)):
334         raise ArgumentError("One of {--lock, --tarballs, --index-cache, --packages, "
335                             "--source-cache, --all} required")
336 
337     if context.json:
338         stdout_json(json_result)
339
```
--- 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/cli/main_clean.py b/conda/cli/main_clean.py
--- a/conda/cli/main_clean.py
+++ b/conda/cli/main_clean.py
@@ -120,7 +120,7 @@
         print(fmt % ('Total:', human_bytes(totalsize)))
         print()
 
-    if not context.json:
+    if not context.json or not context.yes:
         confirm_yn(args)
     if context.json and args.dry_run:
         return
@@ -218,7 +218,7 @@
         print(fmt % ('Total:', human_bytes(totalsize)))
         print()
 
-    if not context.json:
+    if not context.json or not context.yes:
         confirm_yn(args)
     if context.json and args.dry_run:
         return
@@ -279,7 +279,7 @@
 
     print("%-40s %10s" % ("Total:", human_bytes(total_size)))
 
-    if not context.json:
+    if not context.json or not context.yes:
         confirm_yn(args)
     if context.json and args.dry_run:
         return

{"golden_diff": "diff --git a/conda/cli/main_clean.py b/conda/cli/main_clean.py\n--- a/conda/cli/main_clean.py\n+++ b/conda/cli/main_clean.py\n@@ -120,7 +120,7 @@\n         print(fmt % ('Total:', human_bytes(totalsize)))\n         print()\n \n-    if not context.json:\n+    if not context.json or not context.yes:\n         confirm_yn(args)\n     if context.json and args.dry_run:\n         return\n@@ -218,7 +218,7 @@\n         print(fmt % ('Total:', human_bytes(totalsize)))\n         print()\n \n-    if not context.json:\n+    if not context.json or not context.yes:\n         confirm_yn(args)\n     if context.json and args.dry_run:\n         return\n@@ -279,7 +279,7 @@\n \n     print(\"%-40s %10s\" % (\"Total:\", human_bytes(total_size)))\n \n-    if not context.json:\n+    if not context.json or not context.yes:\n         confirm_yn(args)\n     if context.json and args.dry_run:\n         return\n", "issue": "--yes not functioning for \"Clean\"\nHi, either `conda clean -y --all` or `conda clean --yes --all` still prompt for a confirmation. \r\n\r\nconda 4.2.13\r\nmacOS 10.12.4\n", "before_files": [{"content": "# (c) 2012-2016 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.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom collections import defaultdict\nfrom logging import getLogger\nimport os\nfrom os import listdir, lstat, walk\nfrom os.path import getsize, isdir, join\nimport sys\n\nfrom .common import add_parser_json, add_parser_yes, confirm_yn, stdout_json\nfrom ..base.constants import CONDA_TARBALL_EXTENSION\nfrom ..base.context import context\nfrom ..exceptions import ArgumentError\nfrom ..gateways.disk.delete import rm_rf\nfrom ..gateways.disk.link import CrossPlatformStLink\nfrom ..utils import human_bytes\n\nlog = getLogger(__name__)\n\ndescr = \"\"\"\nRemove unused packages and caches.\n\"\"\"\n\nexample = \"\"\"\nExamples:\n\n    conda clean --tarballs\n\"\"\"\n\ndef configure_parser(sub_parsers):\n    p = sub_parsers.add_parser(\n        'clean',\n        description=descr,\n        help=descr,\n        epilog=example,\n    )\n    add_parser_yes(p)\n    add_parser_json(p)\n    p.add_argument(\n        \"-a\", \"--all\",\n        action=\"store_true\",\n        help=\"Remove index cache, lock files, tarballs, \"\n             \"unused cache packages, and source cache.\",\n    )\n    p.add_argument(\n        \"-i\", \"--index-cache\",\n        action=\"store_true\",\n        help=\"Remove index cache.\",\n    )\n    p.add_argument(\n        \"-l\", \"--lock\",\n        action=\"store_true\",\n        help=\"Remove all conda lock files.\",\n    )\n    p.add_argument(\n        \"-t\", \"--tarballs\",\n        action=\"store_true\",\n        help=\"Remove cached package tarballs.\",\n    )\n    p.add_argument(\n        '-p', '--packages',\n        action='store_true',\n        help=\"\"\"Remove unused cached packages. Warning: this does not check\n    for symlinked packages.\"\"\",\n    )\n    p.add_argument(\n        '-s', '--source-cache',\n        action='store_true',\n        help=\"\"\"Remove files from the source cache of conda build.\"\"\",\n    )\n    p.set_defaults(func=execute)\n\n\ndef find_tarballs():\n    from ..core.package_cache import PackageCache\n    pkgs_dirs = defaultdict(list)\n    totalsize = 0\n    part_ext = CONDA_TARBALL_EXTENSION + '.part'\n    for package_cache in PackageCache.all_writable(context.pkgs_dirs):\n        pkgs_dir = package_cache.pkgs_dir\n        if not isdir(pkgs_dir):\n            continue\n        root, _, filenames = next(os.walk(pkgs_dir))\n        for fn in filenames:\n            if fn.endswith(CONDA_TARBALL_EXTENSION) or fn.endswith(part_ext):\n                pkgs_dirs[pkgs_dir].append(fn)\n                totalsize += getsize(join(root, fn))\n\n    return pkgs_dirs, totalsize\n\n\ndef rm_tarballs(args, pkgs_dirs, totalsize, verbose=True):\n    if verbose:\n        for pkgs_dir in pkgs_dirs:\n            print('Cache location: %s' % pkgs_dir)\n\n    if not any(pkgs_dirs[i] for i in pkgs_dirs):\n        if verbose:\n            print(\"There are no tarballs to remove\")\n        return\n\n    if verbose:\n        print(\"Will remove the following tarballs:\")\n        print()\n\n        for pkgs_dir in pkgs_dirs:\n            print(pkgs_dir)\n            print('-'*len(pkgs_dir))\n            fmt = \"%-40s %10s\"\n            for fn in pkgs_dirs[pkgs_dir]:\n                size = getsize(join(pkgs_dir, fn))\n                print(fmt % (fn, human_bytes(size)))\n            print()\n        print('-' * 51)  # From 40 + 1 + 10 in fmt\n        print(fmt % ('Total:', human_bytes(totalsize)))\n        print()\n\n    if not context.json:\n        confirm_yn(args)\n    if context.json and args.dry_run:\n        return\n\n    for pkgs_dir in pkgs_dirs:\n        for fn in pkgs_dirs[pkgs_dir]:\n            try:\n                if rm_rf(os.path.join(pkgs_dir, fn)):\n                    if verbose:\n                        print(\"Removed %s\" % fn)\n                else:\n                    if verbose:\n                        print(\"WARNING: cannot remove, file permissions: %s\" % fn)\n            except (IOError, OSError) as e:\n                if verbose:\n                    print(\"WARNING: cannot remove, file permissions: %s\\n%r\" % (fn, e))\n                else:\n                    log.info(\"%r\", e)\n\n\ndef find_pkgs():\n    # TODO: This doesn't handle packages that have hard links to files within\n    # themselves, like bin/python3.3 and bin/python3.3m in the Python package\n    warnings = []\n\n    cross_platform_st_nlink = CrossPlatformStLink()\n    pkgs_dirs = defaultdict(list)\n    for pkgs_dir in context.pkgs_dirs:\n        if not os.path.exists(pkgs_dir):\n            print(\"WARNING: {0} does not exist\".format(pkgs_dir))\n            continue\n        pkgs = [i for i in listdir(pkgs_dir)\n                if (isdir(join(pkgs_dir, i)) and  # only include actual packages\n                    isdir(join(pkgs_dir, i, 'info')))]\n        for pkg in pkgs:\n            breakit = False\n            for root, dir, files in walk(join(pkgs_dir, pkg)):\n                for fn in files:\n                    try:\n                        st_nlink = cross_platform_st_nlink(join(root, fn))\n                    except OSError as e:\n                        warnings.append((fn, e))\n                        continue\n                    if st_nlink > 1:\n                        # print('%s is installed: %s' % (pkg, join(root, fn)))\n                        breakit = True\n                        break\n\n                if breakit:\n                    break\n            else:\n                pkgs_dirs[pkgs_dir].append(pkg)\n\n    totalsize = 0\n    pkgsizes = defaultdict(list)\n    for pkgs_dir in pkgs_dirs:\n        for pkg in pkgs_dirs[pkgs_dir]:\n            pkgsize = 0\n            for root, dir, files in walk(join(pkgs_dir, pkg)):\n                for fn in files:\n                    # We don't have to worry about counting things twice:  by\n                    # definition these files all have a link count of 1!\n                    size = lstat(join(root, fn)).st_size\n                    totalsize += size\n                    pkgsize += size\n            pkgsizes[pkgs_dir].append(pkgsize)\n\n    return pkgs_dirs, warnings, totalsize, pkgsizes\n\n\ndef rm_pkgs(args, pkgs_dirs, warnings, totalsize, pkgsizes,\n            verbose=True):\n    if verbose:\n        for pkgs_dir in pkgs_dirs:\n            print('Cache location: %s' % pkgs_dir)\n            for fn, exception in warnings:\n                print(exception)\n\n    if not any(pkgs_dirs[i] for i in pkgs_dirs):\n        if verbose:\n            print(\"There are no unused packages to remove\")\n        return\n\n    if verbose:\n        print(\"Will remove the following packages:\")\n        for pkgs_dir in pkgs_dirs:\n            print(pkgs_dir)\n            print('-' * len(pkgs_dir))\n            print()\n            fmt = \"%-40s %10s\"\n            for pkg, pkgsize in zip(pkgs_dirs[pkgs_dir], pkgsizes[pkgs_dir]):\n                print(fmt % (pkg, human_bytes(pkgsize)))\n            print()\n        print('-' * 51)  # 40 + 1 + 10 in fmt\n        print(fmt % ('Total:', human_bytes(totalsize)))\n        print()\n\n    if not context.json:\n        confirm_yn(args)\n    if context.json and args.dry_run:\n        return\n\n    for pkgs_dir in pkgs_dirs:\n        for pkg in pkgs_dirs[pkgs_dir]:\n            if verbose:\n                print(\"removing %s\" % pkg)\n            rm_rf(join(pkgs_dir, pkg))\n\n\ndef rm_index_cache():\n    from ..gateways.disk.delete import rm_rf\n    from ..core.package_cache import PackageCache\n    for package_cache in PackageCache.all_writable():\n        rm_rf(join(package_cache.pkgs_dir, 'cache'))\n\n\ndef find_source_cache():\n    cache_dirs = {\n        'source cache': context.src_cache,\n        'git cache': context.git_cache,\n        'hg cache': context.hg_cache,\n        'svn cache': context.svn_cache,\n    }\n\n    sizes = {}\n    totalsize = 0\n    for cache_type, cache_dir in cache_dirs.items():\n        dirsize = 0\n        for root, d, files in walk(cache_dir):\n            for fn in files:\n                size = lstat(join(root, fn)).st_size\n                totalsize += size\n                dirsize += size\n        sizes[cache_type] = dirsize\n\n    return {\n        'warnings': [],\n        'cache_dirs': cache_dirs,\n        'cache_sizes': sizes,\n        'total_size': totalsize,\n    }\n\n\ndef rm_source_cache(args, cache_dirs, warnings, cache_sizes, total_size):\n    verbose = not context.json\n    if warnings:\n        if verbose:\n            for warning in warnings:\n                print(warning, file=sys.stderr)\n        return\n\n    for cache_type in cache_dirs:\n        print(\"%s (%s)\" % (cache_type, cache_dirs[cache_type]))\n        print(\"%-40s %10s\" % (\"Size:\", human_bytes(cache_sizes[cache_type])))\n        print()\n\n    print(\"%-40s %10s\" % (\"Total:\", human_bytes(total_size)))\n\n    if not context.json:\n        confirm_yn(args)\n    if context.json and args.dry_run:\n        return\n\n    for dir in cache_dirs.values():\n        print(\"Removing %s\" % dir)\n        rm_rf(dir)\n\n\ndef execute(args, parser):\n    json_result = {\n        'success': True\n    }\n\n    if args.tarballs or args.all:\n        pkgs_dirs, totalsize = find_tarballs()\n        first = sorted(pkgs_dirs)[0] if pkgs_dirs else ''\n        json_result['tarballs'] = {\n            'pkgs_dir': first,  # Backwards compabitility\n            'pkgs_dirs': dict(pkgs_dirs),\n            'files': pkgs_dirs[first],  # Backwards compatibility\n            'total_size': totalsize\n        }\n        rm_tarballs(args, pkgs_dirs, totalsize, verbose=not context.json)\n\n    if args.index_cache or args.all:\n        json_result['index_cache'] = {\n            'files': [join(context.pkgs_dirs[0], 'cache')]\n        }\n        rm_index_cache()\n\n    if args.packages or args.all:\n        pkgs_dirs, warnings, totalsize, pkgsizes = find_pkgs()\n        first = sorted(pkgs_dirs)[0] if pkgs_dirs else ''\n        json_result['packages'] = {\n            'pkgs_dir': first,  # Backwards compatibility\n            'pkgs_dirs': dict(pkgs_dirs),\n            'files': pkgs_dirs[first],  # Backwards compatibility\n            'total_size': totalsize,\n            'warnings': warnings,\n            'pkg_sizes': {i: dict(zip(pkgs_dirs[i], pkgsizes[i])) for i in pkgs_dirs},\n        }\n        rm_pkgs(args, pkgs_dirs,  warnings, totalsize, pkgsizes,\n                verbose=not context.json)\n\n    if args.source_cache or args.all:\n        json_result['source_cache'] = find_source_cache()\n        rm_source_cache(args, **json_result['source_cache'])\n\n    if not any((args.lock, args.tarballs, args.index_cache, args.packages,\n                args.source_cache, args.all)):\n        raise ArgumentError(\"One of {--lock, --tarballs, --index-cache, --packages, \"\n                            \"--source-cache, --all} required\")\n\n    if context.json:\n        stdout_json(json_result)\n", "path": "conda/cli/main_clean.py"}], "after_files": [{"content": "# (c) 2012-2016 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.\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom collections import defaultdict\nfrom logging import getLogger\nimport os\nfrom os import listdir, lstat, walk\nfrom os.path import getsize, isdir, join\nimport sys\n\nfrom .common import add_parser_json, add_parser_yes, confirm_yn, stdout_json\nfrom ..base.constants import CONDA_TARBALL_EXTENSION\nfrom ..base.context import context\nfrom ..exceptions import ArgumentError\nfrom ..gateways.disk.delete import rm_rf\nfrom ..gateways.disk.link import CrossPlatformStLink\nfrom ..utils import human_bytes\n\nlog = getLogger(__name__)\n\ndescr = \"\"\"\nRemove unused packages and caches.\n\"\"\"\n\nexample = \"\"\"\nExamples:\n\n    conda clean --tarballs\n\"\"\"\n\ndef configure_parser(sub_parsers):\n    p = sub_parsers.add_parser(\n        'clean',\n        description=descr,\n        help=descr,\n        epilog=example,\n    )\n    add_parser_yes(p)\n    add_parser_json(p)\n    p.add_argument(\n        \"-a\", \"--all\",\n        action=\"store_true\",\n        help=\"Remove index cache, lock files, tarballs, \"\n             \"unused cache packages, and source cache.\",\n    )\n    p.add_argument(\n        \"-i\", \"--index-cache\",\n        action=\"store_true\",\n        help=\"Remove index cache.\",\n    )\n    p.add_argument(\n        \"-l\", \"--lock\",\n        action=\"store_true\",\n        help=\"Remove all conda lock files.\",\n    )\n    p.add_argument(\n        \"-t\", \"--tarballs\",\n        action=\"store_true\",\n        help=\"Remove cached package tarballs.\",\n    )\n    p.add_argument(\n        '-p', '--packages',\n        action='store_true',\n        help=\"\"\"Remove unused cached packages. Warning: this does not check\n    for symlinked packages.\"\"\",\n    )\n    p.add_argument(\n        '-s', '--source-cache',\n        action='store_true',\n        help=\"\"\"Remove files from the source cache of conda build.\"\"\",\n    )\n    p.set_defaults(func=execute)\n\n\ndef find_tarballs():\n    from ..core.package_cache import PackageCache\n    pkgs_dirs = defaultdict(list)\n    totalsize = 0\n    part_ext = CONDA_TARBALL_EXTENSION + '.part'\n    for package_cache in PackageCache.all_writable(context.pkgs_dirs):\n        pkgs_dir = package_cache.pkgs_dir\n        if not isdir(pkgs_dir):\n            continue\n        root, _, filenames = next(os.walk(pkgs_dir))\n        for fn in filenames:\n            if fn.endswith(CONDA_TARBALL_EXTENSION) or fn.endswith(part_ext):\n                pkgs_dirs[pkgs_dir].append(fn)\n                totalsize += getsize(join(root, fn))\n\n    return pkgs_dirs, totalsize\n\n\ndef rm_tarballs(args, pkgs_dirs, totalsize, verbose=True):\n    if verbose:\n        for pkgs_dir in pkgs_dirs:\n            print('Cache location: %s' % pkgs_dir)\n\n    if not any(pkgs_dirs[i] for i in pkgs_dirs):\n        if verbose:\n            print(\"There are no tarballs to remove\")\n        return\n\n    if verbose:\n        print(\"Will remove the following tarballs:\")\n        print()\n\n        for pkgs_dir in pkgs_dirs:\n            print(pkgs_dir)\n            print('-'*len(pkgs_dir))\n            fmt = \"%-40s %10s\"\n            for fn in pkgs_dirs[pkgs_dir]:\n                size = getsize(join(pkgs_dir, fn))\n                print(fmt % (fn, human_bytes(size)))\n            print()\n        print('-' * 51)  # From 40 + 1 + 10 in fmt\n        print(fmt % ('Total:', human_bytes(totalsize)))\n        print()\n\n    if not context.json or not context.yes:\n        confirm_yn(args)\n    if context.json and args.dry_run:\n        return\n\n    for pkgs_dir in pkgs_dirs:\n        for fn in pkgs_dirs[pkgs_dir]:\n            try:\n                if rm_rf(os.path.join(pkgs_dir, fn)):\n                    if verbose:\n                        print(\"Removed %s\" % fn)\n                else:\n                    if verbose:\n                        print(\"WARNING: cannot remove, file permissions: %s\" % fn)\n            except (IOError, OSError) as e:\n                if verbose:\n                    print(\"WARNING: cannot remove, file permissions: %s\\n%r\" % (fn, e))\n                else:\n                    log.info(\"%r\", e)\n\n\ndef find_pkgs():\n    # TODO: This doesn't handle packages that have hard links to files within\n    # themselves, like bin/python3.3 and bin/python3.3m in the Python package\n    warnings = []\n\n    cross_platform_st_nlink = CrossPlatformStLink()\n    pkgs_dirs = defaultdict(list)\n    for pkgs_dir in context.pkgs_dirs:\n        if not os.path.exists(pkgs_dir):\n            print(\"WARNING: {0} does not exist\".format(pkgs_dir))\n            continue\n        pkgs = [i for i in listdir(pkgs_dir)\n                if (isdir(join(pkgs_dir, i)) and  # only include actual packages\n                    isdir(join(pkgs_dir, i, 'info')))]\n        for pkg in pkgs:\n            breakit = False\n            for root, dir, files in walk(join(pkgs_dir, pkg)):\n                for fn in files:\n                    try:\n                        st_nlink = cross_platform_st_nlink(join(root, fn))\n                    except OSError as e:\n                        warnings.append((fn, e))\n                        continue\n                    if st_nlink > 1:\n                        # print('%s is installed: %s' % (pkg, join(root, fn)))\n                        breakit = True\n                        break\n\n                if breakit:\n                    break\n            else:\n                pkgs_dirs[pkgs_dir].append(pkg)\n\n    totalsize = 0\n    pkgsizes = defaultdict(list)\n    for pkgs_dir in pkgs_dirs:\n        for pkg in pkgs_dirs[pkgs_dir]:\n            pkgsize = 0\n            for root, dir, files in walk(join(pkgs_dir, pkg)):\n                for fn in files:\n                    # We don't have to worry about counting things twice:  by\n                    # definition these files all have a link count of 1!\n                    size = lstat(join(root, fn)).st_size\n                    totalsize += size\n                    pkgsize += size\n            pkgsizes[pkgs_dir].append(pkgsize)\n\n    return pkgs_dirs, warnings, totalsize, pkgsizes\n\n\ndef rm_pkgs(args, pkgs_dirs, warnings, totalsize, pkgsizes,\n            verbose=True):\n    if verbose:\n        for pkgs_dir in pkgs_dirs:\n            print('Cache location: %s' % pkgs_dir)\n            for fn, exception in warnings:\n                print(exception)\n\n    if not any(pkgs_dirs[i] for i in pkgs_dirs):\n        if verbose:\n            print(\"There are no unused packages to remove\")\n        return\n\n    if verbose:\n        print(\"Will remove the following packages:\")\n        for pkgs_dir in pkgs_dirs:\n            print(pkgs_dir)\n            print('-' * len(pkgs_dir))\n            print()\n            fmt = \"%-40s %10s\"\n            for pkg, pkgsize in zip(pkgs_dirs[pkgs_dir], pkgsizes[pkgs_dir]):\n                print(fmt % (pkg, human_bytes(pkgsize)))\n            print()\n        print('-' * 51)  # 40 + 1 + 10 in fmt\n        print(fmt % ('Total:', human_bytes(totalsize)))\n        print()\n\n    if not context.json or not context.yes:\n        confirm_yn(args)\n    if context.json and args.dry_run:\n        return\n\n    for pkgs_dir in pkgs_dirs:\n        for pkg in pkgs_dirs[pkgs_dir]:\n            if verbose:\n                print(\"removing %s\" % pkg)\n            rm_rf(join(pkgs_dir, pkg))\n\n\ndef rm_index_cache():\n    from ..gateways.disk.delete import rm_rf\n    from ..core.package_cache import PackageCache\n    for package_cache in PackageCache.all_writable():\n        rm_rf(join(package_cache.pkgs_dir, 'cache'))\n\n\ndef find_source_cache():\n    cache_dirs = {\n        'source cache': context.src_cache,\n        'git cache': context.git_cache,\n        'hg cache': context.hg_cache,\n        'svn cache': context.svn_cache,\n    }\n\n    sizes = {}\n    totalsize = 0\n    for cache_type, cache_dir in cache_dirs.items():\n        dirsize = 0\n        for root, d, files in walk(cache_dir):\n            for fn in files:\n                size = lstat(join(root, fn)).st_size\n                totalsize += size\n                dirsize += size\n        sizes[cache_type] = dirsize\n\n    return {\n        'warnings': [],\n        'cache_dirs': cache_dirs,\n        'cache_sizes': sizes,\n        'total_size': totalsize,\n    }\n\n\ndef rm_source_cache(args, cache_dirs, warnings, cache_sizes, total_size):\n    verbose = not context.json\n    if warnings:\n        if verbose:\n            for warning in warnings:\n                print(warning, file=sys.stderr)\n        return\n\n    for cache_type in cache_dirs:\n        print(\"%s (%s)\" % (cache_type, cache_dirs[cache_type]))\n        print(\"%-40s %10s\" % (\"Size:\", human_bytes(cache_sizes[cache_type])))\n        print()\n\n    print(\"%-40s %10s\" % (\"Total:\", human_bytes(total_size)))\n\n    if not context.json or not context.yes:\n        confirm_yn(args)\n    if context.json and args.dry_run:\n        return\n\n    for dir in cache_dirs.values():\n        print(\"Removing %s\" % dir)\n        rm_rf(dir)\n\n\ndef execute(args, parser):\n    json_result = {\n        'success': True\n    }\n\n    if args.tarballs or args.all:\n        pkgs_dirs, totalsize = find_tarballs()\n        first = sorted(pkgs_dirs)[0] if pkgs_dirs else ''\n        json_result['tarballs'] = {\n            'pkgs_dir': first,  # Backwards compabitility\n            'pkgs_dirs': dict(pkgs_dirs),\n            'files': pkgs_dirs[first],  # Backwards compatibility\n            'total_size': totalsize\n        }\n        rm_tarballs(args, pkgs_dirs, totalsize, verbose=not context.json)\n\n    if args.index_cache or args.all:\n        json_result['index_cache'] = {\n            'files': [join(context.pkgs_dirs[0], 'cache')]\n        }\n        rm_index_cache()\n\n    if args.packages or args.all:\n        pkgs_dirs, warnings, totalsize, pkgsizes = find_pkgs()\n        first = sorted(pkgs_dirs)[0] if pkgs_dirs else ''\n        json_result['packages'] = {\n            'pkgs_dir': first,  # Backwards compatibility\n            'pkgs_dirs': dict(pkgs_dirs),\n            'files': pkgs_dirs[first],  # Backwards compatibility\n            'total_size': totalsize,\n            'warnings': warnings,\n            'pkg_sizes': {i: dict(zip(pkgs_dirs[i], pkgsizes[i])) for i in pkgs_dirs},\n        }\n        rm_pkgs(args, pkgs_dirs,  warnings, totalsize, pkgsizes,\n                verbose=not context.json)\n\n    if args.source_cache or args.all:\n        json_result['source_cache'] = find_source_cache()\n        rm_source_cache(args, **json_result['source_cache'])\n\n    if not any((args.lock, args.tarballs, args.index_cache, args.packages,\n                args.source_cache, args.all)):\n        raise ArgumentError(\"One of {--lock, --tarballs, --index-cache, --packages, \"\n                            \"--source-cache, --all} required\")\n\n    if context.json:\n        stdout_json(json_result)\n", "path": "conda/cli/main_clean.py"}]}