We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
conda remove --all behavior changed in 4.2.7
`conda remove --all` used to remove an environment if it existed, and quietly succeed if it was already gone. Now this command fails when the environment does not exist. This makes something formerly easy to do in an automated way now difficult especially in a cross-platform way on Windows.

```
C:\>conda remove --all -n nonenv
CondaEnvironmentNotFoundError: Could not find environment: nonenv .
You can list all discoverable environments with `conda info --envs`.



C:\>echo %ERRORLEVEL%
1
```

Just suppressing the error is not appealing, because there are many error modes different from the environment not existing that should trigger a failure.


--- 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_remove.py`
Content:
```
1 # (c) 2012-2013 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, unicode_literals
8 
9 from argparse import RawDescriptionHelpFormatter
10 from collections import defaultdict
11 import logging
12 from os.path import abspath, join
13 import sys
14 
15 from .conda_argparse import (add_parser_channels, add_parser_help, add_parser_json,
16                              add_parser_no_pin, add_parser_no_use_index_cache, add_parser_offline,
17                              add_parser_prefix, add_parser_pscheck, add_parser_quiet,
18                              add_parser_use_index_cache, add_parser_use_local, add_parser_yes)
19 
20 try:
21     from cytoolz.itertoolz import groupby
22 except ImportError:
23     from .._vendor.toolz.itertoolz import groupby
24 
25 help = "%s a list of packages from a specified conda environment."
26 descr = help + """
27 
28 This command will also remove any package that depends on any of the
29 specified packages as well---unless a replacement can be found without
30 that dependency. If you wish to skip this dependency checking and remove
31 just the requested packages, add the '--force' option. Note however that
32 this may result in a broken environment, so use this with caution.
33 """
34 example = """
35 Examples:
36 
37     conda %s -n myenv scipy
38 
39 """
40 
41 uninstall_help = "Alias for conda remove.  See conda remove --help."
42 log = logging.getLogger(__name__)
43 
44 
45 def configure_parser(sub_parsers, name='remove'):
46     if name == 'remove':
47         p = sub_parsers.add_parser(
48             name,
49             formatter_class=RawDescriptionHelpFormatter,
50             description=descr % name.capitalize(),
51             help=help % name.capitalize(),
52             epilog=example % name,
53             add_help=False,
54         )
55     else:
56         p = sub_parsers.add_parser(
57             name,
58             formatter_class=RawDescriptionHelpFormatter,
59             description=uninstall_help,
60             help=uninstall_help,
61             epilog=example % name,
62             add_help=False,
63         )
64     add_parser_help(p)
65     add_parser_yes(p)
66     add_parser_json(p)
67     p.add_argument(
68         "--all",
69         action="store_true",
70         help="%s all packages, i.e., the entire environment." % name.capitalize(),
71     )
72     p.add_argument(
73         "--features",
74         action="store_true",
75         help="%s features (instead of packages)." % name.capitalize(),
76     )
77     p.add_argument(
78         "--force",
79         action="store_true",
80         help="Forces removal of a package without removing packages that depend on it. "
81              "Using this option will usually leave your environment in a broken and "
82              "inconsistent state.",
83     )
84     add_parser_no_pin(p)
85     add_parser_channels(p)
86     add_parser_prefix(p)
87     add_parser_quiet(p)
88     # Putting this one first makes it the default
89     add_parser_no_use_index_cache(p)
90     add_parser_use_index_cache(p)
91     add_parser_use_local(p)
92     add_parser_offline(p)
93     add_parser_pscheck(p)
94     p.add_argument(
95         'package_names',
96         metavar='package_name',
97         action="store",
98         nargs='*',
99         help="Package names to %s from the environment." % name,
100     )
101     p.set_defaults(func=execute)
102 
103 
104 def execute(args, parser):
105     from .common import (confirm_yn, ensure_override_channels_requires_channel, ensure_use_local,
106                          names_in_specs, specs_from_args, stdout_json)
107     from ..base.constants import ROOT_NO_RM
108     from ..base.context import context
109     from ..common.compat import iteritems, iterkeys
110     from ..common.path import is_private_env_path
111     from ..console import json_progress_bars
112     from ..core.index import get_index
113     from ..exceptions import CondaEnvironmentError, CondaValueError, PackageNotFoundError
114     from ..gateways.disk.delete import delete_trash
115     from ..plan import (get_blank_actions)
116     from ..core.solve import get_resolve_object
117     from ..core.solve import solve_for_actions
118     from ..resolve import MatchSpec
119     from ..core.linked_data import linked_data
120     from ..gateways.disk.delete import rm_rf
121     from ..instructions import PREFIX
122     from ..plan import (add_unlink, display_actions, execute_actions,
123                         nothing_to_do, remove_actions)
124 
125     if not (args.all or args.package_names):
126         raise CondaValueError('no package names supplied,\n'
127                               '       try "conda remove -h" for more details')
128 
129     prefix = context.prefix_w_legacy_search
130     if args.all and prefix == context.default_prefix:
131         msg = "cannot remove current environment. deactivate and run conda remove again"
132         raise CondaEnvironmentError(msg)
133     ensure_use_local(args)
134     ensure_override_channels_requires_channel(args)
135     if not args.features and args.all:
136         index = linked_data(prefix)
137         index = {dist: info for dist, info in iteritems(index)}
138     else:
139         index = get_index(channel_urls=context.channels,
140                           prepend=not args.override_channels,
141                           use_local=args.use_local,
142                           use_cache=args.use_index_cache,
143                           prefix=prefix)
144     specs = None
145     if args.features:
146         specs = [MatchSpec(track_features=f) for f in set(args.package_names)]
147         actions = remove_actions(prefix, specs, index, pinned=context.respect_pinned)
148         actions['ACTION'] = 'REMOVE_FEATURE'
149         action_groups = (actions, index),
150     elif args.all:
151         if prefix == context.root_prefix:
152             raise CondaEnvironmentError('cannot remove root environment,\n'
153                                         '       add -n NAME or -p PREFIX option')
154         actions = defaultdict(list)
155         actions[PREFIX] = prefix
156         for dist in sorted(iterkeys(index)):
157             add_unlink(actions, dist)
158         actions['ACTION'] = 'REMOVE_ALL'
159         action_groups = (actions, index),
160     elif prefix == context.root_prefix and not context.prefix_specified:
161         from ..core.envs_manager import EnvsDirectory
162         ed = EnvsDirectory(join(context.root_prefix, 'envs'))
163         get_env = lambda s: ed.get_registered_preferred_env(MatchSpec(s).name)
164         specs = specs_from_args(args.package_names)
165         env_spec_map = groupby(get_env, specs)
166         action_groups = []
167         for env_name, spcs in iteritems(env_spec_map):
168             pfx = ed.to_prefix(env_name)
169             r = get_resolve_object(index.copy(), pfx)
170             specs_to_remove = tuple(MatchSpec(s) for s in spcs)
171             prune = pfx != context.root_prefix
172             dists_for_unlinking, dists_for_linking = solve_for_actions(
173                 pfx, r,
174                 specs_to_remove=specs_to_remove, prune=prune,
175             )
176             actions = get_blank_actions(pfx)
177             actions['UNLINK'].extend(dists_for_unlinking)
178             actions['LINK'].extend(dists_for_linking)
179             actions['SPECS'].extend(s.spec for s in specs_to_remove)
180             actions['ACTION'] = 'REMOVE'
181             action_groups.append((actions, r.index))
182         action_groups = tuple(action_groups)
183     else:
184         specs = specs_from_args(args.package_names)
185         if sys.prefix == abspath(prefix) and names_in_specs(ROOT_NO_RM, specs) and not args.force:
186             raise CondaEnvironmentError('cannot remove %s from root environment' %
187                                         ', '.join(ROOT_NO_RM))
188         action_groups = (remove_actions(prefix, list(specs), index=index, force=args.force,
189                                         pinned=context.respect_pinned), index),
190 
191     delete_trash()
192     if any(nothing_to_do(x[0]) for x in action_groups):
193         if args.all:
194             print("\nRemove all packages in environment %s:\n" % prefix, file=sys.stderr)
195             if not context.json:
196                 confirm_yn(args)
197             rm_rf(prefix)
198 
199             if context.json:
200                 stdout_json({
201                     'success': True,
202                     'actions': tuple(x[0] for x in action_groups)
203                 })
204             return
205 
206         pkg = str(args.package_names).replace("['", "")
207         pkg = pkg.replace("']", "")
208 
209         error_message = "No packages named '%s' found to remove from environment." % pkg
210         raise PackageNotFoundError(error_message)
211     if not context.json:
212         for actions, ndx in action_groups:
213             print()
214             print("Package plan for package removal in environment %s:" % actions["PREFIX"])
215             display_actions(actions, ndx)
216     elif context.json and args.dry_run:
217         stdout_json({
218             'success': True,
219             'dry_run': True,
220             'actions': tuple(x[0] for x in action_groups),
221         })
222         return
223 
224     if not context.json:
225         confirm_yn(args)
226 
227     for actions, ndx in action_groups:
228         if context.json and not context.quiet:
229             with json_progress_bars():
230                 execute_actions(actions, ndx, verbose=not context.quiet)
231         else:
232             execute_actions(actions, ndx, verbose=not context.quiet)
233 
234         target_prefix = actions["PREFIX"]
235         if is_private_env_path(target_prefix) and linked_data(target_prefix) == {}:
236             rm_rf(target_prefix)
237 
238     if args.all:
239         rm_rf(prefix)
240 
241     if context.json:
242         stdout_json({
243             'success': True,
244             'actions': tuple(x[0] for x in action_groups),
245         })
246
```
--- 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_remove.py b/conda/cli/main_remove.py
--- a/conda/cli/main_remove.py
+++ b/conda/cli/main_remove.py
@@ -9,7 +9,7 @@
 from argparse import RawDescriptionHelpFormatter
 from collections import defaultdict
 import logging
-from os.path import abspath, join
+from os.path import abspath, join, isdir
 import sys
 
 from .conda_argparse import (add_parser_channels, add_parser_help, add_parser_json,
@@ -130,6 +130,10 @@
     if args.all and prefix == context.default_prefix:
         msg = "cannot remove current environment. deactivate and run conda remove again"
         raise CondaEnvironmentError(msg)
+    if args.all and not isdir(prefix):
+        # full environment removal was requested, but environment doesn't exist anyway
+        return 0
+
     ensure_use_local(args)
     ensure_override_channels_requires_channel(args)
     if not args.features and args.all:

{"golden_diff": "diff --git a/conda/cli/main_remove.py b/conda/cli/main_remove.py\n--- a/conda/cli/main_remove.py\n+++ b/conda/cli/main_remove.py\n@@ -9,7 +9,7 @@\n from argparse import RawDescriptionHelpFormatter\n from collections import defaultdict\n import logging\n-from os.path import abspath, join\n+from os.path import abspath, join, isdir\n import sys\n \n from .conda_argparse import (add_parser_channels, add_parser_help, add_parser_json,\n@@ -130,6 +130,10 @@\n     if args.all and prefix == context.default_prefix:\n         msg = \"cannot remove current environment. deactivate and run conda remove again\"\n         raise CondaEnvironmentError(msg)\n+    if args.all and not isdir(prefix):\n+        # full environment removal was requested, but environment doesn't exist anyway\n+        return 0\n+\n     ensure_use_local(args)\n     ensure_override_channels_requires_channel(args)\n     if not args.features and args.all:\n", "issue": "conda remove --all behavior changed in 4.2.7\n`conda remove --all` used to remove an environment if it existed, and quietly succeed if it was already gone. Now this command fails when the environment does not exist. This makes something formerly easy to do in an automated way now difficult especially in a cross-platform way on Windows.\n\n```\nC:\\>conda remove --all -n nonenv\nCondaEnvironmentNotFoundError: Could not find environment: nonenv .\nYou can list all discoverable environments with `conda info --envs`.\n\n\n\nC:\\>echo %ERRORLEVEL%\n1\n```\n\nJust suppressing the error is not appealing, because there are many error modes different from the environment not existing that should trigger a failure.\n\n", "before_files": [{"content": "# (c) 2012-2013 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, unicode_literals\n\nfrom argparse import RawDescriptionHelpFormatter\nfrom collections import defaultdict\nimport logging\nfrom os.path import abspath, join\nimport sys\n\nfrom .conda_argparse import (add_parser_channels, add_parser_help, add_parser_json,\n                             add_parser_no_pin, add_parser_no_use_index_cache, add_parser_offline,\n                             add_parser_prefix, add_parser_pscheck, add_parser_quiet,\n                             add_parser_use_index_cache, add_parser_use_local, add_parser_yes)\n\ntry:\n    from cytoolz.itertoolz import groupby\nexcept ImportError:\n    from .._vendor.toolz.itertoolz import groupby\n\nhelp = \"%s a list of packages from a specified conda environment.\"\ndescr = help + \"\"\"\n\nThis command will also remove any package that depends on any of the\nspecified packages as well---unless a replacement can be found without\nthat dependency. If you wish to skip this dependency checking and remove\njust the requested packages, add the '--force' option. Note however that\nthis may result in a broken environment, so use this with caution.\n\"\"\"\nexample = \"\"\"\nExamples:\n\n    conda %s -n myenv scipy\n\n\"\"\"\n\nuninstall_help = \"Alias for conda remove.  See conda remove --help.\"\nlog = logging.getLogger(__name__)\n\n\ndef configure_parser(sub_parsers, name='remove'):\n    if name == 'remove':\n        p = sub_parsers.add_parser(\n            name,\n            formatter_class=RawDescriptionHelpFormatter,\n            description=descr % name.capitalize(),\n            help=help % name.capitalize(),\n            epilog=example % name,\n            add_help=False,\n        )\n    else:\n        p = sub_parsers.add_parser(\n            name,\n            formatter_class=RawDescriptionHelpFormatter,\n            description=uninstall_help,\n            help=uninstall_help,\n            epilog=example % name,\n            add_help=False,\n        )\n    add_parser_help(p)\n    add_parser_yes(p)\n    add_parser_json(p)\n    p.add_argument(\n        \"--all\",\n        action=\"store_true\",\n        help=\"%s all packages, i.e., the entire environment.\" % name.capitalize(),\n    )\n    p.add_argument(\n        \"--features\",\n        action=\"store_true\",\n        help=\"%s features (instead of packages).\" % name.capitalize(),\n    )\n    p.add_argument(\n        \"--force\",\n        action=\"store_true\",\n        help=\"Forces removal of a package without removing packages that depend on it. \"\n             \"Using this option will usually leave your environment in a broken and \"\n             \"inconsistent state.\",\n    )\n    add_parser_no_pin(p)\n    add_parser_channels(p)\n    add_parser_prefix(p)\n    add_parser_quiet(p)\n    # Putting this one first makes it the default\n    add_parser_no_use_index_cache(p)\n    add_parser_use_index_cache(p)\n    add_parser_use_local(p)\n    add_parser_offline(p)\n    add_parser_pscheck(p)\n    p.add_argument(\n        'package_names',\n        metavar='package_name',\n        action=\"store\",\n        nargs='*',\n        help=\"Package names to %s from the environment.\" % name,\n    )\n    p.set_defaults(func=execute)\n\n\ndef execute(args, parser):\n    from .common import (confirm_yn, ensure_override_channels_requires_channel, ensure_use_local,\n                         names_in_specs, specs_from_args, stdout_json)\n    from ..base.constants import ROOT_NO_RM\n    from ..base.context import context\n    from ..common.compat import iteritems, iterkeys\n    from ..common.path import is_private_env_path\n    from ..console import json_progress_bars\n    from ..core.index import get_index\n    from ..exceptions import CondaEnvironmentError, CondaValueError, PackageNotFoundError\n    from ..gateways.disk.delete import delete_trash\n    from ..plan import (get_blank_actions)\n    from ..core.solve import get_resolve_object\n    from ..core.solve import solve_for_actions\n    from ..resolve import MatchSpec\n    from ..core.linked_data import linked_data\n    from ..gateways.disk.delete import rm_rf\n    from ..instructions import PREFIX\n    from ..plan import (add_unlink, display_actions, execute_actions,\n                        nothing_to_do, remove_actions)\n\n    if not (args.all or args.package_names):\n        raise CondaValueError('no package names supplied,\\n'\n                              '       try \"conda remove -h\" for more details')\n\n    prefix = context.prefix_w_legacy_search\n    if args.all and prefix == context.default_prefix:\n        msg = \"cannot remove current environment. deactivate and run conda remove again\"\n        raise CondaEnvironmentError(msg)\n    ensure_use_local(args)\n    ensure_override_channels_requires_channel(args)\n    if not args.features and args.all:\n        index = linked_data(prefix)\n        index = {dist: info for dist, info in iteritems(index)}\n    else:\n        index = get_index(channel_urls=context.channels,\n                          prepend=not args.override_channels,\n                          use_local=args.use_local,\n                          use_cache=args.use_index_cache,\n                          prefix=prefix)\n    specs = None\n    if args.features:\n        specs = [MatchSpec(track_features=f) for f in set(args.package_names)]\n        actions = remove_actions(prefix, specs, index, pinned=context.respect_pinned)\n        actions['ACTION'] = 'REMOVE_FEATURE'\n        action_groups = (actions, index),\n    elif args.all:\n        if prefix == context.root_prefix:\n            raise CondaEnvironmentError('cannot remove root environment,\\n'\n                                        '       add -n NAME or -p PREFIX option')\n        actions = defaultdict(list)\n        actions[PREFIX] = prefix\n        for dist in sorted(iterkeys(index)):\n            add_unlink(actions, dist)\n        actions['ACTION'] = 'REMOVE_ALL'\n        action_groups = (actions, index),\n    elif prefix == context.root_prefix and not context.prefix_specified:\n        from ..core.envs_manager import EnvsDirectory\n        ed = EnvsDirectory(join(context.root_prefix, 'envs'))\n        get_env = lambda s: ed.get_registered_preferred_env(MatchSpec(s).name)\n        specs = specs_from_args(args.package_names)\n        env_spec_map = groupby(get_env, specs)\n        action_groups = []\n        for env_name, spcs in iteritems(env_spec_map):\n            pfx = ed.to_prefix(env_name)\n            r = get_resolve_object(index.copy(), pfx)\n            specs_to_remove = tuple(MatchSpec(s) for s in spcs)\n            prune = pfx != context.root_prefix\n            dists_for_unlinking, dists_for_linking = solve_for_actions(\n                pfx, r,\n                specs_to_remove=specs_to_remove, prune=prune,\n            )\n            actions = get_blank_actions(pfx)\n            actions['UNLINK'].extend(dists_for_unlinking)\n            actions['LINK'].extend(dists_for_linking)\n            actions['SPECS'].extend(s.spec for s in specs_to_remove)\n            actions['ACTION'] = 'REMOVE'\n            action_groups.append((actions, r.index))\n        action_groups = tuple(action_groups)\n    else:\n        specs = specs_from_args(args.package_names)\n        if sys.prefix == abspath(prefix) and names_in_specs(ROOT_NO_RM, specs) and not args.force:\n            raise CondaEnvironmentError('cannot remove %s from root environment' %\n                                        ', '.join(ROOT_NO_RM))\n        action_groups = (remove_actions(prefix, list(specs), index=index, force=args.force,\n                                        pinned=context.respect_pinned), index),\n\n    delete_trash()\n    if any(nothing_to_do(x[0]) for x in action_groups):\n        if args.all:\n            print(\"\\nRemove all packages in environment %s:\\n\" % prefix, file=sys.stderr)\n            if not context.json:\n                confirm_yn(args)\n            rm_rf(prefix)\n\n            if context.json:\n                stdout_json({\n                    'success': True,\n                    'actions': tuple(x[0] for x in action_groups)\n                })\n            return\n\n        pkg = str(args.package_names).replace(\"['\", \"\")\n        pkg = pkg.replace(\"']\", \"\")\n\n        error_message = \"No packages named '%s' found to remove from environment.\" % pkg\n        raise PackageNotFoundError(error_message)\n    if not context.json:\n        for actions, ndx in action_groups:\n            print()\n            print(\"Package plan for package removal in environment %s:\" % actions[\"PREFIX\"])\n            display_actions(actions, ndx)\n    elif context.json and args.dry_run:\n        stdout_json({\n            'success': True,\n            'dry_run': True,\n            'actions': tuple(x[0] for x in action_groups),\n        })\n        return\n\n    if not context.json:\n        confirm_yn(args)\n\n    for actions, ndx in action_groups:\n        if context.json and not context.quiet:\n            with json_progress_bars():\n                execute_actions(actions, ndx, verbose=not context.quiet)\n        else:\n            execute_actions(actions, ndx, verbose=not context.quiet)\n\n        target_prefix = actions[\"PREFIX\"]\n        if is_private_env_path(target_prefix) and linked_data(target_prefix) == {}:\n            rm_rf(target_prefix)\n\n    if args.all:\n        rm_rf(prefix)\n\n    if context.json:\n        stdout_json({\n            'success': True,\n            'actions': tuple(x[0] for x in action_groups),\n        })\n", "path": "conda/cli/main_remove.py"}], "after_files": [{"content": "# (c) 2012-2013 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, unicode_literals\n\nfrom argparse import RawDescriptionHelpFormatter\nfrom collections import defaultdict\nimport logging\nfrom os.path import abspath, join, isdir\nimport sys\n\nfrom .conda_argparse import (add_parser_channels, add_parser_help, add_parser_json,\n                             add_parser_no_pin, add_parser_no_use_index_cache, add_parser_offline,\n                             add_parser_prefix, add_parser_pscheck, add_parser_quiet,\n                             add_parser_use_index_cache, add_parser_use_local, add_parser_yes)\n\ntry:\n    from cytoolz.itertoolz import groupby\nexcept ImportError:\n    from .._vendor.toolz.itertoolz import groupby\n\nhelp = \"%s a list of packages from a specified conda environment.\"\ndescr = help + \"\"\"\n\nThis command will also remove any package that depends on any of the\nspecified packages as well---unless a replacement can be found without\nthat dependency. If you wish to skip this dependency checking and remove\njust the requested packages, add the '--force' option. Note however that\nthis may result in a broken environment, so use this with caution.\n\"\"\"\nexample = \"\"\"\nExamples:\n\n    conda %s -n myenv scipy\n\n\"\"\"\n\nuninstall_help = \"Alias for conda remove.  See conda remove --help.\"\nlog = logging.getLogger(__name__)\n\n\ndef configure_parser(sub_parsers, name='remove'):\n    if name == 'remove':\n        p = sub_parsers.add_parser(\n            name,\n            formatter_class=RawDescriptionHelpFormatter,\n            description=descr % name.capitalize(),\n            help=help % name.capitalize(),\n            epilog=example % name,\n            add_help=False,\n        )\n    else:\n        p = sub_parsers.add_parser(\n            name,\n            formatter_class=RawDescriptionHelpFormatter,\n            description=uninstall_help,\n            help=uninstall_help,\n            epilog=example % name,\n            add_help=False,\n        )\n    add_parser_help(p)\n    add_parser_yes(p)\n    add_parser_json(p)\n    p.add_argument(\n        \"--all\",\n        action=\"store_true\",\n        help=\"%s all packages, i.e., the entire environment.\" % name.capitalize(),\n    )\n    p.add_argument(\n        \"--features\",\n        action=\"store_true\",\n        help=\"%s features (instead of packages).\" % name.capitalize(),\n    )\n    p.add_argument(\n        \"--force\",\n        action=\"store_true\",\n        help=\"Forces removal of a package without removing packages that depend on it. \"\n             \"Using this option will usually leave your environment in a broken and \"\n             \"inconsistent state.\",\n    )\n    add_parser_no_pin(p)\n    add_parser_channels(p)\n    add_parser_prefix(p)\n    add_parser_quiet(p)\n    # Putting this one first makes it the default\n    add_parser_no_use_index_cache(p)\n    add_parser_use_index_cache(p)\n    add_parser_use_local(p)\n    add_parser_offline(p)\n    add_parser_pscheck(p)\n    p.add_argument(\n        'package_names',\n        metavar='package_name',\n        action=\"store\",\n        nargs='*',\n        help=\"Package names to %s from the environment.\" % name,\n    )\n    p.set_defaults(func=execute)\n\n\ndef execute(args, parser):\n    from .common import (confirm_yn, ensure_override_channels_requires_channel, ensure_use_local,\n                         names_in_specs, specs_from_args, stdout_json)\n    from ..base.constants import ROOT_NO_RM\n    from ..base.context import context\n    from ..common.compat import iteritems, iterkeys\n    from ..common.path import is_private_env_path\n    from ..console import json_progress_bars\n    from ..core.index import get_index\n    from ..exceptions import CondaEnvironmentError, CondaValueError, PackageNotFoundError\n    from ..gateways.disk.delete import delete_trash\n    from ..plan import (get_blank_actions)\n    from ..core.solve import get_resolve_object\n    from ..core.solve import solve_for_actions\n    from ..resolve import MatchSpec\n    from ..core.linked_data import linked_data\n    from ..gateways.disk.delete import rm_rf\n    from ..instructions import PREFIX\n    from ..plan import (add_unlink, display_actions, execute_actions,\n                        nothing_to_do, remove_actions)\n\n    if not (args.all or args.package_names):\n        raise CondaValueError('no package names supplied,\\n'\n                              '       try \"conda remove -h\" for more details')\n\n    prefix = context.prefix_w_legacy_search\n    if args.all and prefix == context.default_prefix:\n        msg = \"cannot remove current environment. deactivate and run conda remove again\"\n        raise CondaEnvironmentError(msg)\n    if args.all and not isdir(prefix):\n        # full environment removal was requested, but environment doesn't exist anyway\n        return 0\n\n    ensure_use_local(args)\n    ensure_override_channels_requires_channel(args)\n    if not args.features and args.all:\n        index = linked_data(prefix)\n        index = {dist: info for dist, info in iteritems(index)}\n    else:\n        index = get_index(channel_urls=context.channels,\n                          prepend=not args.override_channels,\n                          use_local=args.use_local,\n                          use_cache=args.use_index_cache,\n                          prefix=prefix)\n    specs = None\n    if args.features:\n        specs = [MatchSpec(track_features=f) for f in set(args.package_names)]\n        actions = remove_actions(prefix, specs, index, pinned=context.respect_pinned)\n        actions['ACTION'] = 'REMOVE_FEATURE'\n        action_groups = (actions, index),\n    elif args.all:\n        if prefix == context.root_prefix:\n            raise CondaEnvironmentError('cannot remove root environment,\\n'\n                                        '       add -n NAME or -p PREFIX option')\n        actions = defaultdict(list)\n        actions[PREFIX] = prefix\n        for dist in sorted(iterkeys(index)):\n            add_unlink(actions, dist)\n        actions['ACTION'] = 'REMOVE_ALL'\n        action_groups = (actions, index),\n    elif prefix == context.root_prefix and not context.prefix_specified:\n        from ..core.envs_manager import EnvsDirectory\n        ed = EnvsDirectory(join(context.root_prefix, 'envs'))\n        get_env = lambda s: ed.get_registered_preferred_env(MatchSpec(s).name)\n        specs = specs_from_args(args.package_names)\n        env_spec_map = groupby(get_env, specs)\n        action_groups = []\n        for env_name, spcs in iteritems(env_spec_map):\n            pfx = ed.to_prefix(env_name)\n            r = get_resolve_object(index.copy(), pfx)\n            specs_to_remove = tuple(MatchSpec(s) for s in spcs)\n            prune = pfx != context.root_prefix\n            dists_for_unlinking, dists_for_linking = solve_for_actions(\n                pfx, r,\n                specs_to_remove=specs_to_remove, prune=prune,\n            )\n            actions = get_blank_actions(pfx)\n            actions['UNLINK'].extend(dists_for_unlinking)\n            actions['LINK'].extend(dists_for_linking)\n            actions['SPECS'].extend(s.spec for s in specs_to_remove)\n            actions['ACTION'] = 'REMOVE'\n            action_groups.append((actions, r.index))\n        action_groups = tuple(action_groups)\n    else:\n        specs = specs_from_args(args.package_names)\n        if sys.prefix == abspath(prefix) and names_in_specs(ROOT_NO_RM, specs) and not args.force:\n            raise CondaEnvironmentError('cannot remove %s from root environment' %\n                                        ', '.join(ROOT_NO_RM))\n        action_groups = (remove_actions(prefix, list(specs), index=index, force=args.force,\n                                        pinned=context.respect_pinned), index),\n\n    delete_trash()\n    if any(nothing_to_do(x[0]) for x in action_groups):\n        if args.all:\n            print(\"\\nRemove all packages in environment %s:\\n\" % prefix, file=sys.stderr)\n            if not context.json:\n                confirm_yn(args)\n            rm_rf(prefix)\n\n            if context.json:\n                stdout_json({\n                    'success': True,\n                    'actions': tuple(x[0] for x in action_groups)\n                })\n            return\n\n        pkg = str(args.package_names).replace(\"['\", \"\")\n        pkg = pkg.replace(\"']\", \"\")\n\n        error_message = \"No packages named '%s' found to remove from environment.\" % pkg\n        raise PackageNotFoundError(error_message)\n    if not context.json:\n        for actions, ndx in action_groups:\n            print()\n            print(\"Package plan for package removal in environment %s:\" % actions[\"PREFIX\"])\n            display_actions(actions, ndx)\n    elif context.json and args.dry_run:\n        stdout_json({\n            'success': True,\n            'dry_run': True,\n            'actions': tuple(x[0] for x in action_groups),\n        })\n        return\n\n    if not context.json:\n        confirm_yn(args)\n\n    for actions, ndx in action_groups:\n        if context.json and not context.quiet:\n            with json_progress_bars():\n                execute_actions(actions, ndx, verbose=not context.quiet)\n        else:\n            execute_actions(actions, ndx, verbose=not context.quiet)\n\n        target_prefix = actions[\"PREFIX\"]\n        if is_private_env_path(target_prefix) and linked_data(target_prefix) == {}:\n            rm_rf(target_prefix)\n\n    if args.all:\n        rm_rf(prefix)\n\n    if context.json:\n        stdout_json({\n            'success': True,\n            'actions': tuple(x[0] for x in action_groups),\n        })\n", "path": "conda/cli/main_remove.py"}]}