def rm_tarballs(args): from os.path import join, getsize pkgs_dir = config.pkgs_dirs[0] print('Cache location: %s' % pkgs_dir) rmlist = [] for fn in os.listdir(pkgs_dir): if fn.endswith('.tar.bz2') or fn.endswith('.tar.bz2.part'): rmlist.append(fn) if not rmlist: print("There are no tarballs to remove") sys.exit(0) print("Will remove the following tarballs:") print() totalsize = 0 maxlen = len(max(rmlist, key=lambda x: len(str(x)))) fmt = "%-40s %10s" for fn in rmlist: size = getsize(join(pkgs_dir, fn)) totalsize += size print(fmt % (fn, human_bytes(size))) print('-' * (maxlen + 2 + 10)) print(fmt % ('Total:', human_bytes(totalsize))) print() common.confirm_yn(args) for fn in rmlist: print("removing %s" % fn) os.unlink(os.path.join(pkgs_dir, fn))
def test_confirm_yn_no(self, stdin_mock): args = AttrDict({ 'dry_run': False, }) from conda.cli.common import confirm_yn with pytest.raises(CondaSystemExit): confirm_yn(args)
def rm_pkgs(args): # TODO: This doesn't handle packages that have hard links to files within # themselves, like bin/python3.3 and bin/python3.3m in the Python package from os.path import join, isdir from os import lstat, walk, listdir from conda.install import rm_rf pkgs_dir = config.pkgs_dirs[0] print('Cache location: %s' % pkgs_dir) rmlist = [] pkgs = [i for i in listdir(pkgs_dir) if isdir(join(pkgs_dir, i)) and # Only include actual packages isdir(join(pkgs_dir, i, 'info'))] for pkg in pkgs: breakit = False for root, dir, files in walk(join(pkgs_dir, pkg)): if breakit: break for fn in files: try: stat = lstat(join(root, fn)) except OSError as e: print(e) continue if stat.st_nlink > 1: # print('%s is installed: %s' % (pkg, join(root, fn))) breakit = True break else: rmlist.append(pkg) if not rmlist: print("There are no unused packages to remove") sys.exit(0) print("Will remove the following packages:") print() totalsize = 0 maxlen = len(max(rmlist, key=lambda x: len(str(x)))) fmt = "%-40s %10s" for pkg in rmlist: pkgsize = 0 for root, dir, files in walk(join(pkgs_dir, pkg)): for fn in files: # We don't have to worry about counting things twice: by # definition these files all have a link count of 1! size = lstat(join(root, fn)).st_size totalsize += size pkgsize += size print(fmt % (pkg, human_bytes(pkgsize))) print('-' * (maxlen + 2 + 10)) print(fmt % ('Total:', human_bytes(totalsize))) print() common.confirm_yn(args) for pkg in rmlist: print("removing %s" % pkg) rm_rf(join(pkgs_dir, pkg))
def test_confirm_yn_no(self): args = AttrDict({ 'dry_run': False, }) from conda.cli.common import confirm_yn with pytest.raises(CondaSystemExit): confirm_yn(args)
def rm_tarballs(args, pkgs_dir, rmlist, totalsize, verbose=True): if verbose: print('Cache location: %s' % pkgs_dir) if not rmlist: if verbose: print("There are no tarballs to remove") return if verbose: print("Will remove the following tarballs:") print() maxlen = len(max(rmlist, key=lambda x: len(str(x)))) fmt = "%-40s %10s" for fn in rmlist: size = getsize(join(pkgs_dir, fn)) print(fmt % (fn, human_bytes(size))) print('-' * (maxlen + 2 + 10)) print(fmt % ('Total:', human_bytes(totalsize))) print() if not args.json: common.confirm_yn(args) if args.json and args.dry_run: return for fn in rmlist: if verbose: print("removing %s" % fn) os.unlink(os.path.join(pkgs_dir, fn))
def rm_pkgs(args, pkgs_dir, rmlist, warnings, totalsize, pkgsizes, verbose=True): if verbose: print('Cache location: %s' % pkgs_dir) for fn, exception in warnings: print(exception) if not rmlist: if verbose: print("There are no unused packages to remove") return if verbose: print("Will remove the following packages:") print() maxlen = len(max(rmlist, key=lambda x: len(str(x)))) fmt = "%-40s %10s" for pkg, pkgsize in zip(rmlist, pkgsizes): print(fmt % (pkg, human_bytes(pkgsize))) print('-' * (maxlen + 2 + 10)) print(fmt % ('Total:', human_bytes(totalsize))) print() if not args.json: common.confirm_yn(args) if args.json and args.dry_run: return for pkg in rmlist: if verbose: print("removing %s" % pkg) rm_rf(join(pkgs_dir, pkg))
def test_confirm_yn_no(monkeypatch): monkeypatch.setattr('sys.stdin', StringIO('n\n')) args = AttrDict({ 'dry_run': False, }) with pytest.raises(CondaSystemExit): confirm_yn(args)
def rm_pkgs(args, pkgs_dir, rmlist, warnings, totalsize, pkgsizes, verbose=True): from conda.install import rm_rf if verbose: print('Cache location: %s' % pkgs_dir) for fn, exception in warnings: print(exception) if not rmlist: if verbose: print("There are no unused packages to remove") return if verbose: print("Will remove the following packages:") print() maxlen = len(max(rmlist, key=lambda x: len(str(x)))) fmt = "%-40s %10s" for pkg, pkgsize in zip(rmlist, pkgsizes): print(fmt % (pkg, human_bytes(pkgsize))) print('-' * (maxlen + 2 + 10)) print(fmt % ('Total:', human_bytes(totalsize))) print() if not args.json: common.confirm_yn(args) if args.json and args.dry_run: return for pkg in rmlist: if verbose: print("removing %s" % pkg) rm_rf(join(pkgs_dir, pkg))
def execute(args, parser): import sys import conda.plan as plan from conda.api import get_index from conda.cli import pscheck from conda.install import rm_rf, linked if not (args.all or args.package_names): sys.exit('Error: no package names supplied,\n' ' try "conda remove -h" for more details') prefix = common.get_prefix(args) common.check_write('remove', prefix) index = None if args.features: channel_urls = args.channel or () common.ensure_override_channels_requires_channel(args) index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) features = set(args.package_names) actions = plan.remove_features_actions(prefix, index, features) elif args.all: if plan.is_root_prefix(prefix): sys.exit('Error: cannot remove root environment,\n' ' add -n NAME or -p PREFIX option') actions = {plan.PREFIX: prefix, plan.UNLINK: sorted(linked(prefix))} else: specs = common.specs_from_args(args.package_names) if (plan.is_root_prefix(prefix) and common.names_in_specs(common.root_no_rm, specs)): sys.exit('Error: cannot remove %s from root environment' % ', '.join(common.root_no_rm)) actions = plan.remove_actions(prefix, specs) if plan.nothing_to_do(actions): if args.all: rm_rf(prefix) return sys.exit('Error: no packages found to remove from ' 'environment: %s' % prefix) print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions) if not pscheck.main(args): common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) if args.all: rm_rf(prefix)
def execute(args, parser): import sys from os.path import exists import conda.plan as plan from conda.api import get_index if len(args.package_specs) == 0 and not args.file: sys.exit('Error: too few arguments, must supply command line ' 'package specs or --file') common.ensure_name_or_prefix(args, 'create') prefix = common.get_prefix(args) if exists(prefix): if args.prefix: raise RuntimeError("'%s' already exists, must supply new " "directory for -p/--prefix" % prefix) else: raise RuntimeError("'%s' already exists, must supply new " "directory for -n/--name" % prefix) if args.file: specs = common.specs_from_file(args.file) else: specs = common.specs_from_args(args.package_specs) common.check_specs(prefix, specs) channel_urls = args.channel or () common.ensure_override_channels_requires_channel(args) index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) actions = plan.install_actions(prefix, index, specs) if plan.nothing_to_do(actions): print('No matching packages could be found, nothing to do') return print() print("Package plan for creating environment at %s:" % prefix) plan.display_actions(actions, index) common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) if sys.platform != 'win32': activate_name = prefix if args.name: activate_name = args.name print("#") print("# To activate this environment, use:") print("# $ source activate %s" % activate_name) print("#") print("# To deactivate this environment, use:") print("# $ source deactivate") print("#")
def test_dry_run_exit(self): with env_var('CONDA_DRY_RUN', 'true', conda_tests_ctxt_mgmt_def_pol): from conda.cli.common import confirm_yn with pytest.raises(DryRunExit): confirm_yn() from conda.cli.common import confirm with pytest.raises(DryRunExit): confirm()
def test_dry_run_exit(self): with env_var('CONDA_DRY_RUN', 'true', reset_context): from conda.cli.common import confirm_yn with pytest.raises(DryRunExit): confirm_yn() from conda.cli.common import confirm with pytest.raises(DryRunExit): confirm()
def test_dry_run_exit(): with env_var('CONDA_DRY_RUN', 'true', stack_callback=conda_tests_ctxt_mgmt_def_pol): with pytest.raises(DryRunExit): confirm_yn() with pytest.raises(DryRunExit): confirm()
def execute(args, parser): import sys import conda.plan as plan from conda.api import get_index from conda.cli import pscheck from conda.install import rm_rf, linked if not (args.all or args.package_names): sys.exit('Error: no package names supplied,\n' ' try "conda remove -h" for more details') prefix = common.get_prefix(args) common.check_write('remove', prefix) index = None if args.features: common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) features = set(args.package_names) actions = plan.remove_features_actions(prefix, index, features) elif args.all: if plan.is_root_prefix(prefix): sys.exit('Error: cannot remove root environment,\n' ' add -n NAME or -p PREFIX option') actions = {plan.PREFIX: prefix, plan.UNLINK: sorted(linked(prefix))} else: specs = common.specs_from_args(args.package_names) if (plan.is_root_prefix(prefix) and common.names_in_specs(common.root_no_rm, specs)): sys.exit('Error: cannot remove %s from root environment' % ', '.join(common.root_no_rm)) actions = plan.remove_actions(prefix, specs) if plan.nothing_to_do(actions): if args.all: rm_rf(prefix) return sys.exit('Error: no packages found to remove from ' 'environment: %s' % prefix) print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions) if not pscheck.main(args): common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) if args.all: rm_rf(prefix)
def execute(args, parser): import conda.plan as plan from conda.api import get_index from conda.cli import pscheck prefix = common.get_prefix(args) # handle explict installs of conda packages if args.packages and all(s.endswith('.tar.bz2') for s in args.packages): from conda.misc import install_local_packages install_local_packages(prefix, args.packages, verbose=not args.quiet) return if any(s.endswith('.tar.bz2') for s in args.packages): raise RuntimeError("cannot mix specifications with conda package " "filenames") if args.force: args.no_deps = True if args.file: specs = common.specs_from_file(args.file) else: specs = common.specs_from_args(args.packages) common.check_specs(prefix, specs) spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names) if plan.nothing_to_do(actions): from conda.cli.main_list import list_packages regex = '^(%s)$' % '|'.join(spec_names) print('# All requested packages already installed.') list_packages(prefix, regex) return print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index) if not pscheck.main(args): common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet)
def test_dry_run_exit(self): args = AttrDict({ 'dry_run': True, }) from conda.cli.common import confirm_yn with pytest.raises(DryRunExit): confirm_yn(args) from conda.cli.common import confirm with pytest.raises(DryRunExit): confirm(args)
def execute(args, parser): import conda.config as config import conda.plan as plan from conda.api import get_index from conda.misc import touch_nonadmin common.ensure_name_or_prefix(args, 'create') prefix = common.get_prefix(args, search=False) check_prefix(prefix) config.set_pkgs_dirs(prefix) if args.clone: if args.package_specs: sys.exit('Error: did not expect any arguments for --clone') clone(args.clone, prefix) touch_nonadmin(prefix) print_activate(args.name if args.name else prefix) return if not args.no_default_packages: args.package_specs.extend(config.create_default_packages) if len(args.package_specs) == 0 and not args.file: sys.exit('Error: too few arguments, must supply command line ' 'package specs or --file') if args.file: specs = common.specs_from_url(args.file) else: specs = common.specs_from_args(args.package_specs) common.check_specs(prefix, specs) channel_urls = args.channel or () common.ensure_override_channels_requires_channel(args) index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) actions = plan.install_actions(prefix, index, specs) if plan.nothing_to_do(actions): print('No matching packages could be found, nothing to do') return print() print("Package plan for creating environment at %s:" % prefix) plan.display_actions(actions, index) common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) touch_nonadmin(prefix) print_activate(args.name if args.name else prefix)
def execute(args, parser): import sys import conda.install as ci import conda.config as config import conda.plan as plan from conda.api import get_index from conda.cli import pscheck if len(args.pkg_names) == 0: sys.exit("""Error: no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update anaconda """) prefix = common.get_prefix(args) config.set_pkgs_dirs(prefix) linked = set(ci.name_dist(d) for d in ci.linked(prefix)) for name in args.pkg_names: common.arg2spec(name) if '=' in name: sys.exit("Invalid package name: '%s'" % (name)) if name not in linked: sys.exit("Error: package '%s' is not installed in %s" % (name, prefix)) common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) actions = plan.install_actions(prefix, index, args.pkg_names) if plan.nothing_to_do(actions): from conda.cli.main_list import list_packages regex = '^(%s)$' % '|'.join(args.pkg_names) print('# All packages already at latest version, nothing to do.') list_packages(prefix, regex) return print("Updating conda environment at %s" % prefix) plan.display_actions(actions, index) common.check_write('update', prefix) if not pscheck.main(args): common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet)
def handle_binstar_upload(path, args): import subprocess from conda.builder.external import find_executable if args.binstar_upload is None: args.yes = False args.dry_run = False upload = common.confirm_yn( args, message="Do you want to upload this " "package to binstar", default='yes', exit_no=False) else: upload = args.binstar_upload if not upload: print("""\ # If you want to upload this package to binstar.org later, type: # # $ binstar upload %s """ % path) return binstar = find_executable('binstar') if binstar is None: sys.exit(''' Error: cannot locate binstar (required for upload) # Try: # $ conda install binstar ''') print("Uploading to binstar") args = [binstar, 'upload', path] if config.binstar_personal: args += ['--personal'] subprocess.call(args)
def test_always_yes(self): with env_var('CONDA_ALWAYS_YES', 'true', conda_tests_ctxt_mgmt_def_pol): with env_var('CONDA_DRY_RUN', 'false', conda_tests_ctxt_mgmt_def_pol): from conda.cli.common import confirm_yn choice = confirm_yn() assert choice is True
def test_always_yes(self): with env_var('CONDA_ALWAYS_YES', 'true', reset_context): args = AttrDict({ 'dry_run': False, }) from conda.cli.common import confirm_yn choice = confirm_yn(args) assert choice is True
def create(args, parser): if is_conda_environment(context.target_prefix): if paths_equal(context.target_prefix, context.root_prefix): raise CondaValueError("The target prefix is the base prefix. Aborting.") confirm_yn("WARNING: A conda environment already exists at '%s'\n" "Remove existing environment" % context.target_prefix, default='no', dry_run=False) log.info("Removing existing environment %s", context.target_prefix) rm_rf(context.target_prefix) elif isdir(context.target_prefix): confirm_yn("WARNING: A directory already exists at the target location '%s'\n" "but it is not a conda environment.\n" "Continue creating environment" % context.target_prefix, default='no', dry_run=False) install(args, parser, 'create')
def test_confirm_yn_yes(self, stdin_mock): args = AttrDict({ 'dry_run': False, }) from conda.cli.common import confirm_yn with captured() as c: choice = confirm_yn() assert choice is True assert "Invalid choice" in c.stdout
def test_confirm_yn_yes(self): args = AttrDict({ 'dry_run': False, }) from conda.cli.common import confirm_yn with captured() as c: choice = confirm_yn() assert choice is True assert "Invalid choice" in c.stdout
def test_always_yes(): with env_var('CONDA_ALWAYS_YES', 'true', stack_callback=conda_tests_ctxt_mgmt_def_pol): with env_var('CONDA_DRY_RUN', 'false', stack_callback=conda_tests_ctxt_mgmt_def_pol): choice = confirm_yn() assert choice is True
def rm_tarballs(args, pkgs_dirs, totalsize, verbose=True): if verbose: for pkgs_dir in pkgs_dirs: print('Cache location: %s' % pkgs_dir) if not any(pkgs_dirs[i] for i in pkgs_dirs): if verbose: print("There are no tarballs to remove") return if verbose: print("Will remove the following tarballs:") print() for pkgs_dir in pkgs_dirs: print(pkgs_dir) print('-'*len(pkgs_dir)) fmt = "%-40s %10s" for fn in pkgs_dirs[pkgs_dir]: size = getsize(join(pkgs_dir, fn)) print(fmt % (fn, human_bytes(size))) print() print('-' * 51) # From 40 + 1 + 10 in fmt print(fmt % ('Total:', human_bytes(totalsize))) print() if not args.json: common.confirm_yn(args) if args.json and args.dry_run: return for pkgs_dir in pkgs_dirs: for fn in pkgs_dirs[pkgs_dir]: if os.access(os.path.join(pkgs_dir, fn), os.W_OK): if verbose: print("Removing %s" % fn) os.unlink(os.path.join(pkgs_dir, fn)) else: if verbose: print("WARNING: cannot remove, file permissions: %s" % fn)
def rm_source_cache(args, cache_dirs, warnings, cache_sizes, total_size): verbose = not args.json if warnings: if verbose: for warning in warnings: print(warning, file=sys.stderr) return for cache_type in cache_dirs: print("%s (%s)" % (cache_type, cache_dirs[cache_type])) print("%-40s %10s" % ("Size:", human_bytes(cache_sizes[cache_type]))) print() print("%-40s %10s" % ("Total:", human_bytes(total_size))) if not args.json: common.confirm_yn(args) if args.json and args.dry_run: return for dir in cache_dirs.values(): print("Removing %s" % dir) rm_rf(dir)
def rm_pkgs(args, pkgs_dirs, warnings, totalsize, pkgsizes, verbose=True): if verbose: for pkgs_dir in pkgs_dirs: print('Cache location: %s' % pkgs_dir) for fn, exception in warnings: print(exception) if not any(pkgs_dirs[i] for i in pkgs_dirs): if verbose: print("There are no unused packages to remove") return if verbose: print("Will remove the following packages:") for pkgs_dir in pkgs_dirs: print(pkgs_dir) print('-' * len(pkgs_dir)) print() fmt = "%-40s %10s" for pkg, pkgsize in zip(pkgs_dirs[pkgs_dir], pkgsizes[pkgs_dir]): print(fmt % (pkg, human_bytes(pkgsize))) print() print('-' * 51) # 40 + 1 + 10 in fmt print(fmt % ('Total:', human_bytes(totalsize))) print() if not args.json: common.confirm_yn(args) if args.json and args.dry_run: return for pkgs_dir in pkgs_dirs: for pkg in pkgs_dirs[pkgs_dir]: if verbose: print("removing %s" % pkg) rm_rf(join(pkgs_dir, pkg))
def test_confirm_yn_yes(monkeypatch): monkeypatch.setattr('sys.stdin', StringIO('blah\ny\n')) with env_var('CONDA_ALWAYS_YES', 'false', stack_callback=conda_tests_ctxt_mgmt_def_pol): with env_var('CONDA_DRY_RUN', 'false', stack_callback=conda_tests_ctxt_mgmt_def_pol): assert not context.always_yes args = AttrDict({ 'dry_run': False, }) with captured() as cap: choice = confirm_yn(args) assert choice is True assert "Invalid choice" in cap.stdout
def handle_binstar_upload(path, args): import subprocess from conda.builder.external import find_executable if args.binstar_upload is None: args.yes = False args.dry_run = False upload = common.confirm_yn( args, message="Do you want to upload this " "package to binstar", default='yes', exit_no=False) else: upload = args.binstar_upload if not upload: print("""\ # If you want to upload this package to binstar.org later, type: # # $ binstar upload %s """ % path) return binstar = find_executable('binstar') if binstar is None: sys.exit(''' Error: cannot locate binstar (required for upload) # Try: # $ conda install binstar ''') print("Uploading to binstar") args = [binstar, 'upload', path] if config.binstar_user: args += ['--user', config.binstar_user] if config.binstar_personal: args += ['--personal'] subprocess.call(args)
def execute(args, parser): import sys import shutil import tarfile import tempfile from os.path import abspath, isdir, isfile import conda.builder.build as build from conda.builder.external import find_executable from conda.builder.config import croot import conda.builder.source as source from conda.builder.metadata import MetaData from conda.lock import Locked with Locked(croot): for arg in args.recipe: if isfile(arg): if arg.endswith(('.tar', '.tar.gz', '.tgz', '.tar.bz2')): recipe_dir = tempfile.mkdtemp() t = tarfile.open(arg, 'r:*') t.extractall(path=recipe_dir) t.close() need_cleanup = True else: print("Ignoring: %s" % arg) continue else: recipe_dir = abspath(arg) need_cleanup = False if not isdir(recipe_dir): sys.exit("Error: no such directory: %s" % recipe_dir) m = MetaData(recipe_dir) if args.check and len(args.recipe) > 1: print(m.path) m.check_fields() if args.check: continue if args.output: print(build.bldpkg_path(m)) continue elif args.test: build.test(m) elif args.source: source.provide(m.path, m.get_section('source')) print('Source tree in:', source.get_dir()) else: build.build(m) if need_cleanup: shutil.rmtree(recipe_dir) if args.binstar_upload is None: args.yes = False args.dry_run = False upload = common.confirm_yn( args, message="Do you want to upload this " "package to binstar", default='yes', exit_no=False) else: upload = args.binstar_upload if not upload: print("""\ # If you want to upload this package to binstar.org later, type: # # $ binstar upload %s """ % build.bldpkg_path(m)) continue binstar = find_executable('binstar') if binstar is None: sys.exit(''' Error: cannot locate binstar (required for upload) # Try: # $ conda install binstar ''') subprocess.call([binstar, 'upload', build.bldpkg_path(m)])
def test_always_yes(self): with env_var('CONDA_ALWAYS_YES', 'true', reset_context): with env_var('CONDA_DRY_RUN', 'false', reset_context): from conda.cli.common import confirm_yn choice = confirm_yn() assert choice is True
def install(args, parser, command='install'): """ conda install, conda update, and conda create """ newenv = bool(command == 'create') isupdate = bool(command == 'update') isinstall = bool(command == 'install') if newenv: common.ensure_name_or_prefix(args, command) prefix = common.get_prefix(args, search=not newenv) if newenv: check_prefix(prefix, json=args.json) if force_32bit and plan.is_root_prefix(prefix): common.error_and_exit("cannot use CONDA_FORCE_32BIT=1 in root env") if isupdate and not (args.file or args.all or args.packages): common.error_and_exit("""no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update --prefix %s anaconda """ % prefix, json=args.json, error_type="ValueError") linked = ci.linked(prefix) lnames = {ci.name_dist(d) for d in linked} if isupdate and not args.all: for name in args.packages: common.arg2spec(name, json=args.json, update=True) if name not in lnames: common.error_and_exit("Package '%s' is not installed in %s" % (name, prefix), json=args.json, error_type="ValueError") if newenv and not args.no_default_packages: default_packages = create_default_packages[:] # Override defaults if they are specified at the command line for default_pkg in create_default_packages: if any(pkg.split('=')[0] == default_pkg for pkg in args.packages): default_packages.remove(default_pkg) args.packages.extend(default_packages) else: default_packages = [] common.ensure_use_local(args) common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () specs = [] if args.file: for fpath in args.file: specs.extend(common.specs_from_url(fpath, json=args.json)) if '@EXPLICIT' in specs: misc.explicit(specs, prefix, verbose=not args.quiet) return elif getattr(args, 'all', False): if not linked: common.error_and_exit("There are no packages installed in the " "prefix %s" % prefix) specs.extend(nm for nm in lnames) specs.extend(common.specs_from_args(args.packages, json=args.json)) if isinstall and args.revision: get_revision(args.revision, json=args.json) elif not (newenv and args.clone): common.check_specs(prefix, specs, json=args.json, create=(command == 'create')) num_cp = sum(s.endswith('.tar.bz2') for s in args.packages) if num_cp: if num_cp == len(args.packages): misc.explicit(args.packages, prefix, verbose=not args.quiet) return else: common.error_and_exit( "cannot mix specifications with conda package filenames", json=args.json, error_type="ValueError") # handle tar file containing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): install_tar(prefix, tar_path, verbose=not args.quiet) return if newenv and args.clone: if set(args.packages) - set(default_packages): common.error_and_exit('did not expect any arguments for --clone', json=args.json, error_type="ValueError") clone(args.clone, prefix, json=args.json, quiet=args.quiet, fetch_args={'use_cache': args.use_index_cache, 'unknown': args.unknown}) misc.append_env(prefix) misc.touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) return index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_local=args.use_local, use_cache=args.use_index_cache, unknown=args.unknown, json=args.json, offline=args.offline, prefix=prefix) r = Resolve(index) ospecs = list(specs) plan.add_defaults_to_specs(r, linked, specs, update=isupdate) # Don't update packages that are already up-to-date if isupdate and not (args.all or args.force): orig_packages = args.packages[:] installed_metadata = [ci.is_linked(prefix, dist) for dist in linked] for name in orig_packages: vers_inst = [m['version'] for m in installed_metadata if m['name'] == name] build_inst = [m['build_number'] for m in installed_metadata if m['name'] == name] try: assert len(vers_inst) == 1, name assert len(build_inst) == 1, name except AssertionError as e: if args.json: common.exception_and_exit(e, json=True) else: raise pkgs = sorted(r.get_pkgs(name)) if not pkgs: # Shouldn't happen? continue latest = pkgs[-1] if (latest.version == vers_inst[0] and latest.build_number == build_inst[0]): args.packages.remove(name) if not args.packages: from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(orig_packages) print('# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success( message='All requested packages already installed.') return if args.force: args.no_deps = True if args.no_deps: only_names = set(s.split()[0] for s in ospecs) else: only_names = None if not isdir(prefix) and not newenv: if args.mkdir: try: os.makedirs(prefix) except OSError: common.error_and_exit("Error: could not create directory: %s" % prefix, json=args.json, error_type="OSError") else: common.error_and_exit("""\ environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix, json=args.json, error_type="NoEnvironmentFound") try: if isinstall and args.revision: actions = plan.revert_actions(prefix, get_revision(args.revision)) else: with common.json_progress_bars(json=args.json and not args.quiet): actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names, pinned=args.pinned, always_copy=args.copy, minimal_hint=args.alt_hint, update_deps=args.update_deps) except NoPackagesFound as e: error_message = e.args[0] if isupdate and args.all: # Packages not found here just means they were installed but # cannot be found any more. Just skip them. if not args.json: print("Warning: %s, skipping" % error_message) else: # Not sure what to do here pass args._skip = getattr(args, '_skip', ['anaconda']) for pkg in e.pkgs: p = pkg.split()[0] if p in args._skip: # Avoid infinite recursion. This can happen if a spec # comes from elsewhere, like --file raise args._skip.append(p) return install(args, parser, command=command) else: packages = {index[fn]['name'] for fn in index} nfound = 0 for pkg in sorted(e.pkgs): pkg = pkg.split()[0] if pkg in packages: continue close = get_close_matches(pkg, packages, cutoff=0.7) if not close: continue if nfound == 0: error_message += "\n\nClose matches found; did you mean one of these?\n" error_message += "\n %s: %s" % (pkg, ', '.join(close)) nfound += 1 error_message += '\n\nYou can search for packages on anaconda.org with' error_message += '\n\n anaconda search -t conda %s' % pkg if len(e.pkgs) > 1: # Note this currently only happens with dependencies not found error_message += '\n\n(and similarly for the other packages)' if not find_executable('anaconda', include_others=False): error_message += '\n\nYou may need to install the anaconda-client' error_message += ' command line client with' error_message += '\n\n conda install anaconda-client' pinned_specs = plan.get_pinned_specs(prefix) if pinned_specs: path = join(prefix, 'conda-meta', 'pinned') error_message += "\n\nNote that you have pinned specs in %s:" % path error_message += "\n\n %r" % pinned_specs common.error_and_exit(error_message, json=args.json) except (Unsatisfiable, SystemExit) as e: # Unsatisfiable package specifications/no such revision/import error error_type = 'UnsatisfiableSpecifications' if e.args and 'could not import' in e.args[0]: error_type = 'ImportError' common.exception_and_exit(e, json=args.json, newline=True, error_text=False, error_type=error_type) if plan.nothing_to_do(actions): from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(s.split()[0] for s in ospecs) print('\n# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success( message='All requested packages already installed.') return if not args.json: print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index, show_channel_urls=args.show_channel_urls) if command in {'install', 'update'}: common.check_write(command, prefix) if not args.json: common.confirm_yn(args) elif args.dry_run: common.stdout_json_success(actions=actions, dry_run=True) sys.exit(0) with common.json_progress_bars(json=args.json and not args.quiet): try: plan.execute_actions(actions, index, verbose=not args.quiet) if not (command == 'update' and args.all): try: with open(join(prefix, 'conda-meta', 'history'), 'a') as f: f.write('# %s specs: %s\n' % (command, specs)) except IOError as e: if e.errno == errno.EACCES: log.debug("Can't write the history file") else: raise except RuntimeError as e: if len(e.args) > 0 and "LOCKERROR" in e.args[0]: error_type = "AlreadyLocked" else: error_type = "RuntimeError" common.exception_and_exit(e, error_type=error_type, json=args.json) except SystemExit as e: common.exception_and_exit(e, json=args.json) if newenv: misc.append_env(prefix) misc.touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) if args.json: common.stdout_json_success(actions=actions)
def install(args, parser, command='install'): """ conda install, conda update, and conda create """ newenv = bool(command == 'create') if newenv: common.ensure_name_or_prefix(args, command) prefix = common.get_prefix(args, search=not newenv) if newenv: check_prefix(prefix, json=args.json) if command == 'update': if args.all: if args.packages: common.error_and_exit("""--all cannot be used with packages""", json=args.json, error_type="ValueError") else: if len(args.packages) == 0: common.error_and_exit("""no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update --prefix %s anaconda """ % prefix, json=args.json, error_type="ValueError") if command == 'update': linked = ci.linked(prefix) for name in args.packages: common.arg2spec(name, json=args.json) if '=' in name: common.error_and_exit("Invalid package name: '%s'" % (name), json=args.json, error_type="ValueError") if name not in set(ci.name_dist(d) for d in linked): common.error_and_exit("package '%s' is not installed in %s" % (name, prefix), json=args.json, error_type="ValueError") if newenv and args.clone: if args.packages: common.error_and_exit('did not expect any arguments for --clone', json=args.json, error_type="ValueError") clone(args.clone, prefix, json=args.json, quiet=args.quiet) touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) return if newenv and not args.no_default_packages: default_packages = config.create_default_packages[:] # Override defaults if they are specified at the command line for default_pkg in config.create_default_packages: if any(pkg.split('=')[0] == default_pkg for pkg in args.packages): default_packages.remove(default_pkg) args.packages.extend(default_packages) common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () specs = [] if args.file: specs.extend(common.specs_from_url(args.file, json=args.json)) elif getattr(args, 'all', False): linked = ci.linked(prefix) for pkg in linked: name, ver, build = pkg.rsplit('-', 2) if name == 'python' and ver.startswith('2'): # Oh Python 2... specs.append('%s >=%s,<3' % (name, ver)) else: specs.append('%s >=%s' % (name, ver)) specs.extend(common.specs_from_args(args.packages, json=args.json)) if command == 'install' and args.revision: get_revision(args.revision, json=args.json) else: common.check_specs(prefix, specs, json=args.json) if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build import config as build_config except ImportError: common.error_and_exit("you need to have 'conda-build' installed" " to use the --use-local option", json=args.json, error_type="RuntimeError") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} index = common.get_index_trap([url_path(build_config.croot)], use_cache=args.use_index_cache, unknown=args.unknown, json=args.json) else: index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, unknown=args.unknown, json=args.json) # Don't update packages that are already up-to-date if command == 'update' and not args.all: r = Resolve(index) orig_packages = args.packages[:] for name in orig_packages: installed_metadata = [ci.is_linked(prefix, dist) for dist in linked] vers_inst = [dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name] build_inst = [m['build_number'] for m in installed_metadata if m['name'] == name] try: assert len(vers_inst) == 1, name assert len(build_inst) == 1, name except AssertionError as e: if args.json: common.exception_and_exit(e, json=True) else: raise pkgs = sorted(r.get_pkgs(MatchSpec(name))) if not pkgs: # Shouldn't happen? continue latest = pkgs[-1] if latest.version == vers_inst[0] and latest.build_number == build_inst[0]: args.packages.remove(name) if not args.packages: from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(orig_packages) print('# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success(message='All requested packages already installed.') return # handle tar file containing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): install_tar(prefix, tar_path, verbose=not args.quiet) return # handle explicit installs of conda packages if args.packages and all(s.endswith('.tar.bz2') for s in args.packages): from conda.misc import install_local_packages install_local_packages(prefix, args.packages, verbose=not args.quiet) return if any(s.endswith('.tar.bz2') for s in args.packages): common.error_and_exit("cannot mix specifications with conda package filenames", json=args.json, error_type="ValueError") if args.force: args.no_deps = True spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None if not isdir(prefix) and not newenv: if args.mkdir: try: os.makedirs(prefix) except OSError: common.error_and_exit("Error: could not create directory: %s" % prefix, json=args.json, error_type="OSError") else: common.error_and_exit("""\ environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix, json=args.json, error_type="NoEnvironmentFound") try: if command == 'install' and args.revision: actions = plan.revert_actions(prefix, get_revision(args.revision)) else: actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names, pinned=args.pinned, minimal_hint=args.alt_hint) except NoPackagesFound as e: common.exception_and_exit(e, json=args.json) except SystemExit as e: # Unsatisfiable package specifications/no such revision/import error error_type = 'UnsatisfiableSpecifications' if e.args and 'could not import' in e.args[0]: error_type = 'ImportError' common.exception_and_exit(e, json=args.json, newline=True, error_text=False, error_type=error_type) if plan.nothing_to_do(actions): from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(spec_names) print('\n# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success(message='All requested packages already installed.') return if not args.json: print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index) if command in {'install', 'update'}: common.check_write(command, prefix) if not args.json: if not pscheck.main(args): common.confirm_yn(args) else: if (sys.platform == 'win32' and not args.force_pscheck and not pscheck.check_processes(verbose=False)): common.error_and_exit("Cannot continue operation while processes " "from packages are running without --force-pscheck.", json=True, error_type="ProcessesStillRunning") elif args.dry_run: common.stdout_json_success(actions=actions, dry_run=True) sys.exit(0) with common.json_progress_bars(json=args.json and not args.quiet): try: plan.execute_actions(actions, index, verbose=not args.quiet) except RuntimeError as e: if len(e.args) > 0 and "LOCKERROR" in e.args[0]: error_type = "AlreadyLocked" else: error_type = "RuntimeError" common.exception_and_exit(e, error_type=error_type, json=args.json) except SystemExit as e: common.exception_and_exit(e, json=args.json) if newenv: touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) if args.json: common.stdout_json_success(actions=actions)
def execute(args, parser): import conda.plan as plan import conda.instructions as inst from conda.install import rm_rf, linked from conda import config if not (args.all or args.package_names): common.error_and_exit( 'no package names supplied,\n' ' try "conda remove -h" for more details', json=args.json, error_type="ValueError") prefix = common.get_prefix(args) if args.all and prefix == config.default_prefix: common.error_and_exit( "cannot remove current environment. deactivate and run conda remove again" ) common.check_write('remove', prefix, json=args.json) common.ensure_override_channels_requires_channel(args, json=args.json) channel_urls = args.channel or () if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build.config import croot except ImportError: common.error_and_exit( "you need to have 'conda-build >= 1.7.1' installed" " to use the --use-local option", json=args.json, error_type="RuntimeError") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} if exists(croot): channel_urls = [url_path(croot)] + list(channel_urls) index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, json=args.json, offline=args.offline) else: index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, json=args.json, offline=args.offline) specs = None if args.features: features = set(args.package_names) actions = plan.remove_features_actions(prefix, index, features) elif args.all: if plan.is_root_prefix(prefix): common.error_and_exit( 'cannot remove root environment,\n' ' add -n NAME or -p PREFIX option', json=args.json, error_type="CantRemoveRoot") actions = {inst.PREFIX: prefix} for dist in sorted(linked(prefix)): plan.add_unlink(actions, dist) else: specs = common.specs_from_args(args.package_names) if (plan.is_root_prefix(prefix) and common.names_in_specs(common.root_no_rm, specs)): common.error_and_exit('cannot remove %s from root environment' % ', '.join(common.root_no_rm), json=args.json, error_type="CantRemoveFromRoot") actions = plan.remove_actions(prefix, specs, index=index, pinned=args.pinned) if plan.nothing_to_do(actions): if args.all: rm_rf(prefix) if args.json: common.stdout_json({'success': True, 'actions': actions}) return common.error_and_exit('no packages found to remove from ' 'environment: %s' % prefix, json=args.json, error_type="PackageNotInstalled") if not args.json: print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions, index) if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: common.confirm_yn(args) if args.json and not args.quiet: with json_progress_bars(): plan.execute_actions(actions, index, verbose=not args.quiet) else: plan.execute_actions(actions, index, verbose=not args.quiet) if specs: try: with open(join(prefix, 'conda-meta', 'history'), 'a') as f: f.write('# remove specs: %s\n' % specs) except IOError as e: if e.errno == errno.EACCES: log.debug("Can't write the history file") else: raise if args.all: rm_rf(prefix) if args.json: common.stdout_json({'success': True, 'actions': actions})
def install(args, parser, command='install'): """ conda install, conda update, and conda create """ newenv = bool(command == 'create') if newenv: common.ensure_name_or_prefix(args, command) prefix = common.get_prefix(args, search=not newenv) if newenv: check_prefix(prefix, json=args.json) if command == 'update': if args.all: if args.packages: common.error_and_exit("""--all cannot be used with packages""", json=args.json, error_type="ValueError") else: if len(args.packages) == 0: common.error_and_exit("""no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update --prefix %s anaconda """ % prefix, json=args.json, error_type="ValueError") if command == 'update': linked = ci.linked(prefix) for name in args.packages: common.arg2spec(name, json=args.json) if '=' in name: common.error_and_exit("Invalid package name: '%s'" % (name), json=args.json, error_type="ValueError") if name not in set(ci.name_dist(d) for d in linked): common.error_and_exit("package '%s' is not installed in %s" % (name, prefix), json=args.json, error_type="ValueError") if newenv and args.clone: if args.packages: common.error_and_exit('did not expect any arguments for --clone', json=args.json, error_type="ValueError") clone(args.clone, prefix, json=args.json, quiet=args.quiet) touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) return if newenv and not args.no_default_packages: default_packages = config.create_default_packages[:] # Override defaults if they are specified at the command line for default_pkg in config.create_default_packages: if any(pkg.split('=')[0] == default_pkg for pkg in args.packages): default_packages.remove(default_pkg) args.packages.extend(default_packages) common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () specs = [] if args.file: specs.extend(common.specs_from_url(args.file, json=args.json)) elif getattr(args, 'all', False): linked = ci.linked(prefix) for pkg in linked: name, ver, build = pkg.rsplit('-', 2) if name == 'python' and ver.startswith('2'): # Oh Python 2... specs.append('%s >=%s,<3' % (name, ver)) else: specs.append('%s >=%s' % (name, ver)) specs.extend(common.specs_from_args(args.packages, json=args.json)) if command == 'install' and args.revision: get_revision(args.revision, json=args.json) else: common.check_specs(prefix, specs, json=args.json) if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build import config as build_config except ImportError: common.error_and_exit( "you need to have 'conda-build' installed" " to use the --use-local option", json=args.json, error_type="RuntimeError") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} index = common.get_index_trap([url_path(build_config.croot)], use_cache=args.use_index_cache, unknown=args.unknown, json=args.json) else: index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, unknown=args.unknown, json=args.json) # Don't update packages that are already up-to-date if command == 'update' and not args.all: r = Resolve(index) orig_packages = args.packages[:] for name in orig_packages: installed_metadata = [ ci.is_linked(prefix, dist) for dist in linked ] vers_inst = [ dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name ] build_inst = [ m['build_number'] for m in installed_metadata if m['name'] == name ] try: assert len(vers_inst) == 1, name assert len(build_inst) == 1, name except AssertionError as e: if args.json: common.exception_and_exit(e, json=True) else: raise pkgs = sorted(r.get_pkgs(MatchSpec(name))) if not pkgs: # Shouldn't happen? continue latest = pkgs[-1] if latest.version == vers_inst[ 0] and latest.build_number == build_inst[0]: args.packages.remove(name) if not args.packages: from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(orig_packages) print('# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success( message='All requested packages already installed.') return # handle tar file containing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): install_tar(prefix, tar_path, verbose=not args.quiet) return # handle explicit installs of conda packages if args.packages and all(s.endswith('.tar.bz2') for s in args.packages): from conda.misc import install_local_packages install_local_packages(prefix, args.packages, verbose=not args.quiet) return if any(s.endswith('.tar.bz2') for s in args.packages): common.error_and_exit( "cannot mix specifications with conda package filenames", json=args.json, error_type="ValueError") if args.force: args.no_deps = True spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None if not isdir(prefix) and not newenv: if args.mkdir: try: os.makedirs(prefix) except OSError: common.error_and_exit("Error: could not create directory: %s" % prefix, json=args.json, error_type="OSError") else: common.error_and_exit("""\ environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix, json=args.json, error_type="NoEnvironmentFound") try: if command == 'install' and args.revision: actions = plan.revert_actions(prefix, get_revision(args.revision)) else: actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names, pinned=args.pinned, minimal_hint=args.alt_hint) except NoPackagesFound as e: error_message = e.args[0] packages = {index[fn]['name'] for fn in index} for pkg in e.pkgs: close = get_close_matches(pkg, packages) if close: error_message += "\n\nDid you mean one of these?\n %s" % ( ', '.join(close)) error_message += '\n\nYou can search for this package on Binstar with' error_message += '\n\n binstar search -t conda %s' % pkg error_message += '\n\nYou may need to install the Binstar command line client with' error_message += '\n\n conda install binstar' common.error_and_exit(error_message, json=args.json) except SystemExit as e: # Unsatisfiable package specifications/no such revision/import error error_type = 'UnsatisfiableSpecifications' if e.args and 'could not import' in e.args[0]: error_type = 'ImportError' common.exception_and_exit(e, json=args.json, newline=True, error_text=False, error_type=error_type) if plan.nothing_to_do(actions): from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(spec_names) print('\n# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success( message='All requested packages already installed.') return if not args.json: print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index) if command in {'install', 'update'}: common.check_write(command, prefix) if not args.json: if not pscheck.main(args): common.confirm_yn(args) else: if (sys.platform == 'win32' and not args.force_pscheck and not pscheck.check_processes(verbose=False)): common.error_and_exit( "Cannot continue operation while processes " "from packages are running without --force-pscheck.", json=True, error_type="ProcessesStillRunning") elif args.dry_run: common.stdout_json_success(actions=actions, dry_run=True) sys.exit(0) with common.json_progress_bars(json=args.json and not args.quiet): try: plan.execute_actions(actions, index, verbose=not args.quiet) except RuntimeError as e: if len(e.args) > 0 and "LOCKERROR" in e.args[0]: error_type = "AlreadyLocked" else: error_type = "RuntimeError" common.exception_and_exit(e, error_type=error_type, json=args.json) except SystemExit as e: common.exception_and_exit(e, json=args.json) if newenv: touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) if args.json: common.stdout_json_success(actions=actions)
def execute(args, parser): import sys import conda.plan as plan from conda.cli import pscheck from conda.install import rm_rf, linked from conda import config if not (args.all or args.package_names): common.error_and_exit( 'no package names supplied,\n' ' try "conda remove -h" for more details', json=args.json, error_type="ValueError") prefix = common.get_prefix(args) if args.all and prefix == config.default_prefix: common.error_and_exit( "cannot remove current environment. deactivate and run conda remove again" ) common.check_write('remove', prefix, json=args.json) common.ensure_override_channels_requires_channel(args, json=args.json) channel_urls = args.channel or () if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build.config import croot except ImportError: common.error_and_exit( "you need to have 'conda-build >= 1.7.1' installed" " to use the --use-local option", json=args.json, error_type="RuntimeError") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} index = common.get_index_trap(channel_urls=[url_path(croot)] + list(channel_urls), prepend=not args.override_channels, use_cache=args.use_index_cache, json=args.json) else: index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, json=args.json) if args.features: features = set(args.package_names) actions = plan.remove_features_actions(prefix, index, features) elif args.all: if plan.is_root_prefix(prefix): common.error_and_exit( 'cannot remove root environment,\n' ' add -n NAME or -p PREFIX option', json=args.json, error_type="CantRemoveRoot") actions = {plan.PREFIX: prefix, plan.UNLINK: sorted(linked(prefix))} else: specs = common.specs_from_args(args.package_names) if (plan.is_root_prefix(prefix) and common.names_in_specs(common.root_no_rm, specs)): common.error_and_exit('cannot remove %s from root environment' % ', '.join(common.root_no_rm), json=args.json, error_type="CantRemoveFromRoot") actions = plan.remove_actions(prefix, specs, index=index, pinned=args.pinned) if plan.nothing_to_do(actions): if args.all: rm_rf(prefix) if args.json: common.stdout_json({'success': True, 'actions': actions}) return common.error_and_exit('no packages found to remove from ' 'environment: %s' % prefix, json=args.json, error_type="PackageNotInstalled") if not args.json: print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions, index) if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: if not pscheck.main(args): common.confirm_yn(args) elif (sys.platform == 'win32' and not args.force_pscheck and not pscheck.check_processes(verbose=False)): common.error_and_exit( "Cannot continue removal while processes " "from packages are running without --force-pscheck.", json=True, error_type="ProcessesStillRunning") if args.json and not args.quiet: with json_progress_bars(): plan.execute_actions(actions, index, verbose=not args.quiet) else: plan.execute_actions(actions, index, verbose=not args.quiet) if args.all: rm_rf(prefix) if args.json: common.stdout_json({'success': True, 'actions': actions})
def execute(args, parser): from conda import config, plan from conda.install import linked, rm_rf prefix = common.get_prefix(args) if plan.is_root_prefix(prefix): common.error_and_exit( 'cannot remove root environment,\n' ' add -n NAME or -p PREFIX option', json=args.json, error_type="CantRemoveRoot") if prefix == config.default_prefix: # FIXME The way the "name" is determined now is handled by # looking at the basename of the prefix. This is brittle # and underlines a use-case for an Environment object that # is capable of providing a name attribute. common.error_and_exit( textwrap.dedent(""" Conda cannot remove the current environment. Please deactivate and run conda env remove again with the name specified. conda env remove --name %s """ % basename(prefix)).lstrip()) # TODO Why do we need an index for removing packages? index = common.get_index_trap(json=args.json) actions = {plan.PREFIX: prefix, plan.UNLINK: sorted(linked(prefix))} if plan.nothing_to_do(actions): # TODO Should this automatically remove even *before* confirmation? # TODO Should this display an error when removing something that # doesn't exist? rm_rf(prefix) if args.json: common.stdout_json({'success': True, 'actions': actions}) return if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: print() print("Remove the following packages in environment %s:" % prefix) plan.display_actions(actions, index) common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) rm_rf(prefix) if args.json: common.stdout_json({'success': True, 'actions': actions})
if not args.json: print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions, index) if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: common.confirm_yn(args) if args.json and not args.quiet: with json_progress_bars(): plan.execute_actions(actions, index, verbose=not args.quiet) else: plan.execute_actions(actions, index, verbose=not args.quiet) if specs: try: with open(join(prefix, 'conda-meta', 'history'), 'a') as f: f.write('# remove specs: %s\n' % specs) except IOError as e: if e.errno == errno.EACCES: log.debug("Can't write the history file") else: raise
def install(args, parser, command='install'): """ conda install, conda update, and conda create """ newenv = command == 'create' if newenv: common.ensure_name_or_prefix(args, command) prefix = common.get_prefix(args, search=not newenv) if newenv: check_prefix(prefix) config.set_pkgs_dirs(prefix) if command == 'update': if len(args.packages) == 0: sys.exit("""Error: no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update --prefix %s anaconda """ % prefix) if command == 'update': linked = set(ci.name_dist(d) for d in ci.linked(prefix)) for name in args.packages: common.arg2spec(name) if '=' in name: sys.exit("Invalid package name: '%s'" % (name)) if name not in linked: sys.exit("Error: package '%s' is not installed in %s" % (name, prefix)) if newenv and args.clone: if args.packages: sys.exit('Error: did not expect any arguments for --clone') clone(args.clone, prefix) touch_nonadmin(prefix) print_activate(args.name if args.name else prefix) return if newenv and not args.no_default_packages: args.packages.extend(config.create_default_packages) # handle tar file containaing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): install_tar(prefix, tar_path, verbose=not args.quiet) return # handle explict installs of conda packages if args.packages and all(s.endswith('.tar.bz2') for s in args.packages): from conda.misc import install_local_packages install_local_packages(prefix, args.packages, verbose=not args.quiet) return if any(s.endswith('.tar.bz2') for s in args.packages): sys.exit("cannot mix specifications with conda package filenames") if args.force: args.no_deps = True if args.file: specs = common.specs_from_url(args.file) else: specs = common.specs_from_args(args.packages) common.check_specs(prefix, specs) spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None if not isdir(prefix) and not newenv: if args.mkdir: try: os.makedirs(prefix) except OSError: sys.exit("Error: could not create directory: %s" % prefix) else: sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix) common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build import config as build_config except ImportError: sys.exit("Error: you need to have 'conda-build' installed" " to use the --use-local option") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} index = get_index([url_path(build_config.croot)]) actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names) if plan.nothing_to_do(actions): from conda.cli.main_list import list_packages regex = '^(%s)$' % '|'.join(spec_names) print('# All requested packages already installed.') list_packages(prefix, regex) return print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index) if command in {'install', 'update'}: common.check_write(command, prefix) if not pscheck.main(args): common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) if newenv: touch_nonadmin(prefix) print_activate(args.name if args.name else prefix)
def execute(args, parser): import sys from os.path import isdir import conda.config as config import conda.plan as plan from conda.api import get_index from conda.cli import pscheck prefix = common.get_prefix(args) config.set_pkgs_dirs(prefix) # handle tar file containaing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): install_tar(prefix, tar_path, verbose=not args.quiet) return # handle explict installs of conda packages if args.packages and all(s.endswith('.tar.bz2') for s in args.packages): from conda.misc import install_local_packages install_local_packages(prefix, args.packages, verbose=not args.quiet) return if any(s.endswith('.tar.bz2') for s in args.packages): sys.exit("cannot mix specifications with conda package filenames") if args.force: args.no_deps = True if args.file: specs = common.specs_from_url(args.file) else: specs = common.specs_from_args(args.packages) common.check_specs(prefix, specs) spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None if not isdir(prefix): sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix) common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path from conda.builder import config as build_config # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} index = get_index([url_path(build_config.croot)]) if args.pip and config.use_pip: # Remove from specs packages that are not in conda index # and install them using pip # Return the updated specs specs = install_with_pip(prefix, index, specs) if not specs: return actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names) if plan.nothing_to_do(actions): from conda.cli.main_list import list_packages regex = '^(%s)$' % '|'.join(spec_names) print('# All requested packages already installed.') list_packages(prefix, regex) return print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index) common.check_write('install', prefix) if not pscheck.main(args): common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet)
def install(args, parser, command='install'): """ conda install, conda update, and conda create """ newenv = bool(command == 'create') if newenv: common.ensure_name_or_prefix(args, command) prefix = common.get_prefix(args, search=not newenv) if newenv: check_prefix(prefix) config.set_pkgs_dirs(prefix) if command == 'update': if args.all: if args.packages: sys.exit("""Error: --all cannot be used with packages""") else: if len(args.packages) == 0: sys.exit("""Error: no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update --prefix %s anaconda """ % prefix) if command == 'update': linked = ci.linked(prefix) for name in args.packages: common.arg2spec(name) if '=' in name: sys.exit("Invalid package name: '%s'" % (name)) if name not in set(ci.name_dist(d) for d in linked): sys.exit("Error: package '%s' is not installed in %s" % (name, prefix)) if newenv and args.clone: if args.packages: sys.exit('Error: did not expect any arguments for --clone') clone(args.clone, prefix) touch_nonadmin(prefix) print_activate(args.name if args.name else prefix) return if newenv and not args.no_default_packages: default_packages = config.create_default_packages[:] # Override defaults if they are specified at the command line for default_pkg in config.create_default_packages: if any(pkg.split('=')[0] == default_pkg for pkg in args.packages): default_packages.remove(default_pkg) args.packages.extend(default_packages) common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () if args.file: specs = common.specs_from_url(args.file) elif getattr(args, 'all', False): specs = [] linked = ci.linked(prefix) for pkg in linked: name, ver, build = pkg.rsplit('-', 2) if name == 'python' and ver.startswith('2'): # Oh Python 2... specs.append('%s >=%s,<3' % (name, ver)) else: specs.append('%s >=%s' % (name, ver)) else: specs = common.specs_from_args(args.packages) if command == 'install' and args.revision: get_revision(args.revision) else: common.check_specs(prefix, specs) if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build import config as build_config except ImportError: sys.exit("Error: you need to have 'conda-build' installed" " to use the --use-local option") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} index = get_index([url_path(build_config.croot)], use_cache=args.use_index_cache, unknown=args.unknown) else: index = get_index(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, unknown=args.unknown) # Don't update packages that are already up-to-date if command == 'update' and not args.all: r = Resolve(index) orig_packages = args.packages[:] for name in orig_packages: vers_inst = [dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name] build_inst = [dist.rsplit('-', 2)[2].rsplit('.tar.bz2', 1)[0] for dist in linked if dist.rsplit('-', 2)[0] == name] assert len(vers_inst) == 1, name assert len(build_inst) == 1, name pkgs = sorted(r.get_pkgs(MatchSpec(name))) if not pkgs: # Shouldn't happen? continue latest = pkgs[-1] if latest.version == vers_inst[0] and latest.build == build_inst[0]: args.packages.remove(name) if not args.packages: from conda.cli.main_list import list_packages regex = '^(%s)$' % '|'.join(orig_packages) print('# All requested packages already installed.') list_packages(prefix, regex) return # handle tar file containing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): install_tar(prefix, tar_path, verbose=not args.quiet) return # handle explicit installs of conda packages if args.packages and all(s.endswith('.tar.bz2') for s in args.packages): from conda.misc import install_local_packages install_local_packages(prefix, args.packages, verbose=not args.quiet) return if any(s.endswith('.tar.bz2') for s in args.packages): sys.exit("cannot mix specifications with conda package filenames") if args.force: args.no_deps = True spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None if not isdir(prefix) and not newenv: if args.mkdir: try: os.makedirs(prefix) except OSError: sys.exit("Error: could not create directory: %s" % prefix) else: sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix) if command == 'install' and args.revision: actions = plan.revert_actions(prefix, get_revision(args.revision)) else: actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names) if plan.nothing_to_do(actions): from conda.cli.main_list import list_packages regex = '^(%s)$' % '|'.join(spec_names) print('# All requested packages already installed.') list_packages(prefix, regex) return print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index) if command in {'install', 'update'}: common.check_write(command, prefix) if not pscheck.main(args): common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) if newenv: touch_nonadmin(prefix) print_activate(args.name if args.name else prefix)
def install(args, parser, command='install'): """ conda install, conda update, and conda create """ newenv = bool(command == 'create') if newenv: common.ensure_name_or_prefix(args, command) prefix = common.get_prefix(args, search=not newenv) if newenv: check_prefix(prefix, json=args.json) if config.force_32bit and plan.is_root_prefix(prefix): common.error_and_exit("cannot use CONDA_FORCE_32BIT=1 in root env") if command == 'update': if not args.file: if not args.all and len(args.packages) == 0: common.error_and_exit("""no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update --prefix %s anaconda """ % prefix, json=args.json, error_type="ValueError") if command == 'update' and not args.all: linked = ci.linked(prefix) for name in args.packages: common.arg2spec(name, json=args.json) if '=' in name: common.error_and_exit("Invalid package name: '%s'" % (name), json=args.json, error_type="ValueError") if name not in set(ci.name_dist(d) for d in linked): common.error_and_exit("package '%s' is not installed in %s" % (name, prefix), json=args.json, error_type="ValueError") if newenv and not args.no_default_packages: default_packages = config.create_default_packages[:] # Override defaults if they are specified at the command line for default_pkg in config.create_default_packages: if any(pkg.split('=')[0] == default_pkg for pkg in args.packages): default_packages.remove(default_pkg) args.packages.extend(default_packages) else: default_packages = [] common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () specs = [] if args.file: for fpath in args.file: specs.extend(common.specs_from_url(fpath, json=args.json)) elif getattr(args, 'all', False): linked = ci.linked(prefix) if not linked: common.error_and_exit("There are no packages installed in the " "prefix %s" % prefix) for pkg in linked: name, ver, build = pkg.rsplit('-', 2) if name in getattr(args, '_skip', ['anaconda']): continue if name == 'python' and ver.startswith('2'): # Oh Python 2... specs.append('%s >=%s,<3' % (name, ver)) else: specs.append('%s' % name) specs.extend(common.specs_from_args(args.packages, json=args.json)) if command == 'install' and args.revision: get_revision(args.revision, json=args.json) elif not (newenv and args.clone): common.check_specs(prefix, specs, json=args.json, create=(command == 'create')) num_cp = sum(s.endswith('.tar.bz2') for s in args.packages) if num_cp: if num_cp == len(args.packages): depends = misc.install_local_packages(prefix, args.packages, verbose=not args.quiet) if args.no_deps: depends = [] specs = list(set(depends)) args.unknown = True else: common.error_and_exit( "cannot mix specifications with conda package filenames", json=args.json, error_type="ValueError") # handle tar file containing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): depends = install_tar(prefix, tar_path, verbose=not args.quiet) if args.no_deps: depends = [] specs = list(set(depends)) args.unknown = True if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build.config import croot except ImportError: common.error_and_exit( "you need to have 'conda-build >= 1.7.1' installed" " to use the --use-local option", json=args.json, error_type="RuntimeError") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} if exists(croot): channel_urls = [url_path(croot)] + list(channel_urls) index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, unknown=args.unknown, json=args.json, offline=args.offline) if newenv and args.clone: if set(args.packages) - set(default_packages): common.error_and_exit('did not expect any arguments for --clone', json=args.json, error_type="ValueError") clone(args.clone, prefix, json=args.json, quiet=args.quiet, index=index) misc.append_env(prefix) misc.touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) return # Don't update packages that are already up-to-date if command == 'update' and not (args.all or args.force): r = Resolve(index) orig_packages = args.packages[:] for name in orig_packages: installed_metadata = [ci.is_linked(prefix, dist) for dist in linked] vers_inst = [dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name] build_inst = [m['build_number'] for m in installed_metadata if m['name'] == name] try: assert len(vers_inst) == 1, name assert len(build_inst) == 1, name except AssertionError as e: if args.json: common.exception_and_exit(e, json=True) else: raise pkgs = sorted(r.get_pkgs(MatchSpec(name))) if not pkgs: # Shouldn't happen? continue latest = pkgs[-1] if (latest.version == vers_inst[0] and latest.build_number == build_inst[0]): args.packages.remove(name) if not args.packages: from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(orig_packages) print('# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success( message='All requested packages already installed.') return if args.force: args.no_deps = True spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None if not isdir(prefix) and not newenv: if args.mkdir: try: os.makedirs(prefix) except OSError: common.error_and_exit("Error: could not create directory: %s" % prefix, json=args.json, error_type="OSError") else: common.error_and_exit("""\ environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix, json=args.json, error_type="NoEnvironmentFound") try: if command == 'install' and args.revision: actions = plan.revert_actions(prefix, get_revision(args.revision)) else: with common.json_progress_bars(json=args.json and not args.quiet): actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names, pinned=args.pinned, minimal_hint=args.alt_hint, update_deps=args.update_deps) if config.always_copy or args.copy: new_link = [] for pkg in actions["LINK"]: dist, pkgs_dir, lt = inst.split_linkarg(pkg) lt = ci.LINK_COPY new_link.append("%s %s %d" % (dist, pkgs_dir, lt)) actions["LINK"] = new_link except NoPackagesFound as e: error_message = e.args[0] if command == 'update' and args.all: # Packages not found here just means they were installed but # cannot be found any more. Just skip them. if not args.json: print("Warning: %s, skipping" % error_message) else: # Not sure what to do here pass args._skip = getattr(args, '_skip', ['anaconda']) for pkg in e.pkgs: p = pkg.split()[0] if p in args._skip: # Avoid infinite recursion. This can happen if a spec # comes from elsewhere, like --file raise args._skip.append(p) return install(args, parser, command=command) else: packages = {index[fn]['name'] for fn in index} for pkg in e.pkgs: close = get_close_matches(pkg, packages, cutoff=0.7) if close: error_message += ("\n\nDid you mean one of these?" "\n\n %s" % (', '.join(close))) error_message += '\n\nYou can search for this package on anaconda.org with' error_message += '\n\n anaconda search -t conda %s' % pkg if len(e.pkgs) > 1: # Note this currently only happens with dependencies not found error_message += '\n\n (and similarly for the other packages)' if not find_executable('anaconda', include_others=False): error_message += '\n\nYou may need to install the anaconda-client command line client with' error_message += '\n\n conda install anaconda-client' pinned_specs = plan.get_pinned_specs(prefix) if pinned_specs: error_message += "\n\nNote that you have pinned specs in %s:" % join(prefix, 'conda-meta', 'pinned') error_message += "\n\n %r" % pinned_specs common.error_and_exit(error_message, json=args.json) except SystemExit as e: # Unsatisfiable package specifications/no such revision/import error error_type = 'UnsatisfiableSpecifications' if e.args and 'could not import' in e.args[0]: error_type = 'ImportError' common.exception_and_exit(e, json=args.json, newline=True, error_text=False, error_type=error_type) if plan.nothing_to_do(actions): from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(spec_names) print('\n# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success( message='All requested packages already installed.') return if not args.json: print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index, show_channel_urls=args.show_channel_urls) if command in {'install', 'update'}: common.check_write(command, prefix) if not args.json: common.confirm_yn(args) elif args.dry_run: common.stdout_json_success(actions=actions, dry_run=True) sys.exit(0) with common.json_progress_bars(json=args.json and not args.quiet): try: plan.execute_actions(actions, index, verbose=not args.quiet) if not (command == 'update' and args.all): try: with open(join(prefix, 'conda-meta', 'history'), 'a') as f: f.write('# %s specs: %s\n' % (command, specs)) except IOError as e: if e.errno == errno.EACCES: log.debug("Can't write the history file") else: raise except RuntimeError as e: if len(e.args) > 0 and "LOCKERROR" in e.args[0]: error_type = "AlreadyLocked" else: error_type = "RuntimeError" common.exception_and_exit(e, error_type=error_type, json=args.json) except SystemExit as e: common.exception_and_exit(e, json=args.json) if newenv: misc.append_env(prefix) misc.touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) if args.json: common.stdout_json_success(actions=actions)
def install(args, parser, command='install'): """ conda install, conda update, and conda create """ newenv = command == 'create' if newenv: common.ensure_name_or_prefix(args, command) prefix = common.get_prefix(args, search=not newenv) if newenv: check_prefix(prefix) config.set_pkgs_dirs(prefix) if command == 'update': if len(args.packages) == 0: sys.exit("""Error: no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update --prefix %s anaconda """ % prefix) if command == 'update': linked = ci.linked(prefix) for name in args.packages: common.arg2spec(name) if '=' in name: sys.exit("Invalid package name: '%s'" % (name)) if name not in set(ci.name_dist(d) for d in linked): sys.exit("Error: package '%s' is not installed in %s" % (name, prefix)) if newenv and args.clone: if args.packages: sys.exit('Error: did not expect any arguments for --clone') clone(args.clone, prefix) touch_nonadmin(prefix) print_activate(args.name if args.name else prefix) return if newenv and not args.no_default_packages: default_packages = config.create_default_packages[:] # Override defaults if they are specified at the command line for default_pkg in config.create_default_packages: if any(pkg.split('=')[0] == default_pkg for pkg in args.packages): default_packages.remove(default_pkg) args.packages.extend(default_packages) common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build import config as build_config except ImportError: sys.exit("Error: you need to have 'conda-build' installed" " to use the --use-local option") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} index = get_index([url_path(build_config.croot)], use_cache=args.use_cache) else: index = get_index(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_cache) # Don't update packages that are already up-to-date if command == 'update': r = Resolve(index) orig_packages = args.packages[:] for name in orig_packages: vers_inst = [dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name] build_inst = [dist.rsplit('-', 2)[2].rsplit('.tar.bz2', 1)[0] for dist in linked if dist.rsplit('-', 2)[0] == name] assert len(vers_inst) == 1, name assert len(build_inst) == 1, name pkgs = sorted(r.get_pkgs(MatchSpec(name))) if not pkgs: # Shouldn't happen? continue # This won't do the right thing for python 2 latest = pkgs[-1] if latest.version == vers_inst[0] and latest.build == build_inst[0]: args.packages.remove(name) if not args.packages: from conda.cli.main_list import list_packages regex = '^(%s)$' % '|'.join(orig_packages) print('# All requested packages already installed.') list_packages(prefix, regex) return # handle tar file containing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): install_tar(prefix, tar_path, verbose=not args.quiet) return # handle explicit installs of conda packages if args.packages and all(s.endswith('.tar.bz2') for s in args.packages): from conda.misc import install_local_packages install_local_packages(prefix, args.packages, verbose=not args.quiet) return if any(s.endswith('.tar.bz2') for s in args.packages): sys.exit("cannot mix specifications with conda package filenames") if args.force: args.no_deps = True if args.file: specs = common.specs_from_url(args.file) else: specs = common.specs_from_args(args.packages) common.check_specs(prefix, specs) spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None if not isdir(prefix) and not newenv: if args.mkdir: try: os.makedirs(prefix) except OSError: sys.exit("Error: could not create directory: %s" % prefix) else: sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix) actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names) if plan.nothing_to_do(actions): from conda.cli.main_list import list_packages regex = '^(%s)$' % '|'.join(spec_names) print('# All requested packages already installed.') list_packages(prefix, regex) return print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index) if command in {'install', 'update'}: common.check_write(command, prefix) if not pscheck.main(args): common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) if newenv: touch_nonadmin(prefix) print_activate(args.name if args.name else prefix)
def execute(args, parser): import sys import conda.plan as plan from conda.cli import pscheck from conda.install import rm_rf, linked from conda import config if not (args.all or args.package_names): common.error_and_exit('no package names supplied,\n' ' try "conda remove -h" for more details', json=args.json, error_type="ValueError") prefix = common.get_prefix(args) if args.all and prefix == config.default_prefix: common.error_and_exit("cannot remove current environment. deactivate and run conda remove again") common.check_write('remove', prefix, json=args.json) common.ensure_override_channels_requires_channel(args, json=args.json) channel_urls = args.channel or () if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build.config import croot except ImportError: common.error_and_exit("you need to have 'conda-build >= 1.7.1' installed" " to use the --use-local option", json=args.json, error_type="RuntimeError") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} index = common.get_index_trap(channel_urls=[url_path(croot)] + list(channel_urls), prepend=not args.override_channels, use_cache=args.use_index_cache, json=args.json) else: index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, json=args.json) if args.features: features = set(args.package_names) actions = plan.remove_features_actions(prefix, index, features) elif args.all: if plan.is_root_prefix(prefix): common.error_and_exit('cannot remove root environment,\n' ' add -n NAME or -p PREFIX option', json=args.json, error_type="CantRemoveRoot") actions = {plan.PREFIX: prefix, plan.UNLINK: sorted(linked(prefix))} else: specs = common.specs_from_args(args.package_names) if (plan.is_root_prefix(prefix) and common.names_in_specs(common.root_no_rm, specs)): common.error_and_exit('cannot remove %s from root environment' % ', '.join(common.root_no_rm), json=args.json, error_type="CantRemoveFromRoot") actions = plan.remove_actions(prefix, specs, index=index, pinned=args.pinned) if plan.nothing_to_do(actions): if args.all: rm_rf(prefix) if args.json: common.stdout_json({ 'success': True, 'actions': actions }) return common.error_and_exit('no packages found to remove from ' 'environment: %s' % prefix, json=args.json, error_type="PackageNotInstalled") if not args.json: print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions, index) if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: if not pscheck.main(args): common.confirm_yn(args) elif (sys.platform == 'win32' and not args.force_pscheck and not pscheck.check_processes(verbose=False)): common.error_and_exit("Cannot continue removal while processes " "from packages are running without --force-pscheck.", json=True, error_type="ProcessesStillRunning") if args.json and not args.quiet: with json_progress_bars(): plan.execute_actions(actions, index, verbose=not args.quiet) else: plan.execute_actions(actions, index, verbose=not args.quiet) if args.all: rm_rf(prefix) if args.json: common.stdout_json({ 'success': True, 'actions': actions })
def execute(args, parser): import sys import conda.plan as plan from conda.cli import pscheck from conda.install import rm_rf, linked from conda import config if not (args.all or args.package_names): common.error_and_exit( 'no package names supplied,\n' ' try "conda remove -h" for more details', json=args.json, error_type="ValueError") prefix = common.get_prefix(args) common.check_write('remove', prefix, json=args.json) common.ensure_override_channels_requires_channel(args, json=args.json) channel_urls = args.channel or () index = common.get_index_trap(channel_urls=channel_urls, use_cache=args.use_index_cache, prepend=not args.override_channels, json=args.json) if args.features: features = set(args.package_names) actions = plan.remove_features_actions(prefix, index, features) elif args.all: if plan.is_root_prefix(prefix): common.error_and_exit( 'cannot remove root environment,\n' ' add -n NAME or -p PREFIX option', json=args.json, error_type="CantRemoveRoot") actions = {plan.PREFIX: prefix, plan.UNLINK: sorted(linked(prefix))} else: specs = common.specs_from_args(args.package_names) if (plan.is_root_prefix(prefix) and common.names_in_specs(common.root_no_rm, specs)): common.error_and_exit('cannot remove %s from root environment' % ', '.join(common.root_no_rm), json=args.json, error_type="CantRemoveFromRoot") actions = plan.remove_actions(prefix, specs, pinned=args.pinned) if plan.nothing_to_do(actions): if args.all: rm_rf(prefix) if args.json: common.stdout_json({'success': True, 'actions': actions}) return common.error_and_exit('no packages found to remove from ' 'environment: %s' % prefix, json=args.json, error_type="PackageNotInstalled") if not args.json: print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions, index) if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: if not pscheck.main(args): common.confirm_yn(args) elif (sys.platform == 'win32' and not args.force_pscheck and not pscheck.check_processes(verbose=False)): common.error_and_exit( "Cannot continue removal while processes " "from packages are running without --force-pscheck.", json=True, error_type="ProcessesStillRunning") if args.json and not args.quiet: with json_progress_bars(): plan.execute_actions(actions, index, verbose=not args.quiet) else: plan.execute_actions(actions, index, verbose=not args.quiet) if args.all: rm_rf(prefix) if args.json: common.stdout_json({'success': True, 'actions': actions})
def rm_pkgs(args): # TODO: This doesn't handle packages that have hard links to files within # themselves, like bin/python3.3 and bin/python3.3m in the Python package from os.path import join, isdir from os import lstat, walk, listdir from conda.install import rm_rf pkgs_dir = config.pkgs_dirs[0] print('Cache location: %s' % pkgs_dir) rmlist = [] pkgs = [ i for i in listdir(pkgs_dir) if isdir(join(pkgs_dir, i)) and # Only include actual packages isdir(join(pkgs_dir, i, 'info')) ] for pkg in pkgs: breakit = False for root, dir, files in walk(join(pkgs_dir, pkg)): if breakit: break for fn in files: try: stat = lstat(join(root, fn)) except OSError as e: print(e) continue if stat.st_nlink > 1: # print('%s is installed: %s' % (pkg, join(root, fn))) breakit = True break else: rmlist.append(pkg) if not rmlist: print("There are no unused packages to remove") sys.exit(0) print("Will remove the following packages:") print() totalsize = 0 maxlen = len(max(rmlist, key=lambda x: len(str(x)))) fmt = "%-40s %10s" for pkg in rmlist: pkgsize = 0 for root, dir, files in walk(join(pkgs_dir, pkg)): for fn in files: # We don't have to worry about counting things twice: by # definition these files all have a link count of 1! size = lstat(join(root, fn)).st_size totalsize += size pkgsize += size print(fmt % (pkg, human_bytes(pkgsize))) print('-' * (maxlen + 2 + 10)) print(fmt % ('Total:', human_bytes(totalsize))) print() common.confirm_yn(args) for pkg in rmlist: print("removing %s" % pkg) rm_rf(join(pkgs_dir, pkg))
def execute(args, parser): from conda import config, plan from conda.install import linked, rm_rf prefix = common.get_prefix(args) if plan.is_root_prefix(prefix): common.error_and_exit('cannot remove root environment,\n' ' add -n NAME or -p PREFIX option', json=args.json, error_type="CantRemoveRoot") if prefix == config.default_prefix: # FIXME The way the "name" is determined now is handled by # looking at the basename of the prefix. This is brittle # and underlines a use-case for an Environment object that # is capable of providing a name attribute. common.error_and_exit(textwrap.dedent( """ Conda cannot remove the current environment. Please deactivate and run conda env remove again with the name specified. conda env remove --name %s """ % basename(prefix) ).lstrip()) # TODO Why do we need an index for removing packages? index = common.get_index_trap(json=args.json) actions = { plan.PREFIX: prefix, plan.UNLINK: sorted(linked(prefix)) } if plan.nothing_to_do(actions): # TODO Should this automatically remove even *before* confirmation? # TODO Should this display an error when removing something that # doesn't exist? rm_rf(prefix) if args.json: common.stdout_json({ 'success': True, 'actions': actions }) return if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: print() print("Remove the following packages in environment %s:" % prefix) plan.display_actions(actions, index) common.confirm_yn(args) plan.execute_actions(actions, index, verbose=not args.quiet) rm_rf(prefix) if args.json: common.stdout_json({ 'success': True, 'actions': actions })
def execute(args, parser): import sys import conda.plan as plan from conda.cli import pscheck from conda.install import rm_rf, linked from conda import config if not (args.all or args.package_names): common.error_and_exit('no package names supplied,\n' ' try "conda remove -h" for more details', json=args.json, error_type="ValueError") prefix = common.get_prefix(args) common.check_write('remove', prefix, json=args.json) common.ensure_override_channels_requires_channel(args, json=args.json) channel_urls = args.channel or () index = common.get_index_trap(channel_urls=channel_urls, use_cache=args.use_index_cache, prepend=not args.override_channels, json=args.json) if args.features: features = set(args.package_names) actions = plan.remove_features_actions(prefix, index, features) elif args.all: if plan.is_root_prefix(prefix): common.error_and_exit('cannot remove root environment,\n' ' add -n NAME or -p PREFIX option', json=args.json, error_type="CantRemoveRoot") actions = {plan.PREFIX: prefix, plan.UNLINK: sorted(linked(prefix))} else: specs = common.specs_from_args(args.package_names) if (plan.is_root_prefix(prefix) and common.names_in_specs(common.root_no_rm, specs)): common.error_and_exit('cannot remove %s from root environment' % ', '.join(common.root_no_rm), json=args.json, error_type="CantRemoveFromRoot") actions = plan.remove_actions(prefix, specs, pinned=args.pinned) if plan.nothing_to_do(actions): if args.all: rm_rf(prefix) if args.json: common.stdout_json({ 'success': True, 'actions': actions }) return common.error_and_exit('no packages found to remove from ' 'environment: %s' % prefix, json=args.json, error_type="PackageNotInstalled") if not args.json: print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions, index) if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: if not pscheck.main(args): common.confirm_yn(args) elif (sys.platform == 'win32' and not args.force_pscheck and not pscheck.check_processes(verbose=False)): common.error_and_exit("Cannot continue removal while processes " "from packages are running without --force-pscheck.", json=True, error_type="ProcessesStillRunning") if args.json and not args.quiet: with json_progress_bars(): plan.execute_actions(actions, index, verbose=not args.quiet) else: plan.execute_actions(actions, index, verbose=not args.quiet) if args.all: rm_rf(prefix) if args.json: common.stdout_json({ 'success': True, 'actions': actions })
def install(args, parser, command='install'): """ conda install, conda update, and conda create """ newenv = bool(command == 'create') if newenv: common.ensure_name_or_prefix(args, command) prefix = common.get_prefix(args, search=not newenv) if newenv: check_prefix(prefix, json=args.json) if config.force_32bit and plan.is_root_prefix(prefix): common.error_and_exit("cannot use CONDA_FORCE_32BIT=1 in root env") if command == 'update': if args.all: if args.packages: common.error_and_exit("""--all cannot be used with packages""", json=args.json, error_type="ValueError") elif not args.file: if len(args.packages) == 0: common.error_and_exit("""no package names supplied # If you want to update to a newer version of Anaconda, type: # # $ conda update --prefix %s anaconda """ % prefix, json=args.json, error_type="ValueError") if command == 'update': linked = ci.linked(prefix) for name in args.packages: common.arg2spec(name, json=args.json) if '=' in name: common.error_and_exit("Invalid package name: '%s'" % (name), json=args.json, error_type="ValueError") if name not in set(ci.name_dist(d) for d in linked): common.error_and_exit("package '%s' is not installed in %s" % (name, prefix), json=args.json, error_type="ValueError") if newenv and not args.no_default_packages: default_packages = config.create_default_packages[:] # Override defaults if they are specified at the command line for default_pkg in config.create_default_packages: if any(pkg.split('=')[0] == default_pkg for pkg in args.packages): default_packages.remove(default_pkg) args.packages.extend(default_packages) else: default_packages = [] common.ensure_override_channels_requires_channel(args) channel_urls = args.channel or () specs = [] if args.file: for fpath in args.file: specs.extend(common.specs_from_url(fpath, json=args.json)) elif getattr(args, 'all', False): linked = ci.linked(prefix) if not linked: common.error_and_exit("There are no packages installed in the " "prefix %s" % prefix) for pkg in linked: name, ver, build = pkg.rsplit('-', 2) if name in getattr(args, '_skip', ['anaconda']): continue if name == 'python' and ver.startswith('2'): # Oh Python 2... specs.append('%s >=%s,<3' % (name, ver)) else: specs.append('%s' % name) specs.extend(common.specs_from_args(args.packages, json=args.json)) if command == 'install' and args.revision: get_revision(args.revision, json=args.json) elif not (newenv and args.clone): common.check_specs(prefix, specs, json=args.json, create=(command == 'create')) num_cp = sum(s.endswith('.tar.bz2') for s in args.packages) if num_cp: if num_cp == len(args.packages): depends = misc.install_local_packages(prefix, args.packages, verbose=not args.quiet) if args.no_deps: depends = [] specs = list(set(depends)) args.unknown = True else: common.error_and_exit( "cannot mix specifications with conda package filenames", json=args.json, error_type="ValueError") # handle tar file containing conda packages if len(args.packages) == 1: tar_path = args.packages[0] if tar_path.endswith('.tar'): depends = install_tar(prefix, tar_path, verbose=not args.quiet) if args.no_deps: depends = [] specs = list(set(depends)) args.unknown = True if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build.config import croot except ImportError: common.error_and_exit( "you need to have 'conda-build >= 1.7.1' installed" " to use the --use-local option", json=args.json, error_type="RuntimeError") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} if exists(croot): channel_urls = [url_path(croot)] + list(channel_urls) index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, unknown=args.unknown, json=args.json, offline=args.offline) if newenv and args.clone: if set(args.packages) - set(default_packages): common.error_and_exit('did not expect any arguments for --clone', json=args.json, error_type="ValueError") clone(args.clone, prefix, json=args.json, quiet=args.quiet, index=index) misc.append_env(prefix) misc.touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) return # Don't update packages that are already up-to-date if command == 'update' and not (args.all or args.force): r = Resolve(index) orig_packages = args.packages[:] for name in orig_packages: installed_metadata = [ci.is_linked(prefix, dist) for dist in linked] vers_inst = [dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name] build_inst = [m['build_number'] for m in installed_metadata if m['name'] == name] try: assert len(vers_inst) == 1, name assert len(build_inst) == 1, name except AssertionError as e: if args.json: common.exception_and_exit(e, json=True) else: raise pkgs = sorted(r.get_pkgs(MatchSpec(name))) if not pkgs: # Shouldn't happen? continue latest = pkgs[-1] if (latest.version == vers_inst[0] and latest.build_number == build_inst[0]): args.packages.remove(name) if not args.packages: from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(orig_packages) print('# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success( message='All requested packages already installed.') return if args.force: args.no_deps = True spec_names = set(s.split()[0] for s in specs) if args.no_deps: only_names = spec_names else: only_names = None if not isdir(prefix) and not newenv: if args.mkdir: try: os.makedirs(prefix) except OSError: common.error_and_exit("Error: could not create directory: %s" % prefix, json=args.json, error_type="OSError") else: common.error_and_exit("""\ environment does not exist: %s # # Use 'conda create' to create an environment before installing packages # into it. #""" % prefix, json=args.json, error_type="NoEnvironmentFound") try: if command == 'install' and args.revision: actions = plan.revert_actions(prefix, get_revision(args.revision)) else: with common.json_progress_bars(json=args.json and not args.quiet): actions = plan.install_actions(prefix, index, specs, force=args.force, only_names=only_names, pinned=args.pinned, minimal_hint=args.alt_hint) if args.copy: new_link = [] for pkg in actions["LINK"]: dist, pkgs_dir, lt = inst.split_linkarg(pkg) lt = ci.LINK_COPY new_link.append("%s %s %d" % (dist, pkgs_dir, lt)) actions["LINK"] = new_link except NoPackagesFound as e: error_message = e.args[0] if command == 'update' and args.all: # Packages not found here just means they were installed but # cannot be found any more. Just skip them. if not args.json: print("Warning: %s, skipping" % error_message) else: # Not sure what to do here pass args._skip = getattr(args, '_skip', ['anaconda']) for pkg in e.pkgs: p = pkg.split()[0] if p in args._skip: # Avoid infinite recursion. This can happen if a spec # comes from elsewhere, like --file raise args._skip.append(p) return install(args, parser, command=command) else: packages = {index[fn]['name'] for fn in index} for pkg in e.pkgs: close = get_close_matches(pkg, packages, cutoff=0.7) if close: error_message += ("\n\nDid you mean one of these?" "\n\n %s" % (', '.join(close))) error_message += '\n\nYou can search for this package on anaconda.org with' error_message += '\n\n anaconda search -t conda %s' % pkg if len(e.pkgs) > 1: # Note this currently only happens with dependencies not found error_message += '\n\n (and similarly for the other packages)' if not find_executable('anaconda', include_others=False): error_message += '\n\nYou may need to install the anaconda-client command line client with' error_message += '\n\n conda install anaconda-client' pinned_specs = plan.get_pinned_specs(prefix) if pinned_specs: error_message += "\n\nNote that you have pinned specs in %s:" % join(prefix, 'conda-meta', 'pinned') error_message += "\n\n %r" % pinned_specs common.error_and_exit(error_message, json=args.json) except SystemExit as e: # Unsatisfiable package specifications/no such revision/import error error_type = 'UnsatisfiableSpecifications' if e.args and 'could not import' in e.args[0]: error_type = 'ImportError' common.exception_and_exit(e, json=args.json, newline=True, error_text=False, error_type=error_type) if plan.nothing_to_do(actions): from conda.cli.main_list import print_packages if not args.json: regex = '^(%s)$' % '|'.join(spec_names) print('\n# All requested packages already installed.') print_packages(prefix, regex) else: common.stdout_json_success( message='All requested packages already installed.') return if not args.json: print() print("Package plan for installation in environment %s:" % prefix) plan.display_actions(actions, index) if command in {'install', 'update'}: common.check_write(command, prefix) if not args.json: common.confirm_yn(args) elif args.dry_run: common.stdout_json_success(actions=actions, dry_run=True) sys.exit(0) with common.json_progress_bars(json=args.json and not args.quiet): try: plan.execute_actions(actions, index, verbose=not args.quiet) if not (command == 'update' and args.all): try: with open(join(prefix, 'conda-meta', 'history'), 'a') as f: f.write('# %s specs: %s\n' % (command, specs)) except IOError as e: if e.errno == errno.EACCES: log.debug("Can't write the history file") else: raise except RuntimeError as e: if len(e.args) > 0 and "LOCKERROR" in e.args[0]: error_type = "AlreadyLocked" else: error_type = "RuntimeError" common.exception_and_exit(e, error_type=error_type, json=args.json) except SystemExit as e: common.exception_and_exit(e, json=args.json) if newenv: misc.append_env(prefix) misc.touch_nonadmin(prefix) if not args.json: print_activate(args.name if args.name else prefix) if args.json: common.stdout_json_success(actions=actions)
def execute(args, parser): import conda.plan as plan import conda.instructions as inst from conda.install import rm_rf, linked from conda import config if not (args.all or args.package_names): common.error_and_exit('no package names supplied,\n' ' try "conda remove -h" for more details', json=args.json, error_type="ValueError") prefix = common.get_prefix(args) if args.all and prefix == config.default_prefix: common.error_and_exit("cannot remove current environment. deactivate and run conda remove again") common.check_write('remove', prefix, json=args.json) common.ensure_override_channels_requires_channel(args, json=args.json) channel_urls = args.channel or () if args.use_local: from conda.fetch import fetch_index from conda.utils import url_path try: from conda_build.config import croot except ImportError: common.error_and_exit("you need to have 'conda-build >= 1.7.1' installed" " to use the --use-local option", json=args.json, error_type="RuntimeError") # remove the cache such that a refetch is made, # this is necessary because we add the local build repo URL fetch_index.cache = {} if exists(croot): channel_urls = [url_path(croot)] + list(channel_urls) index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, json=args.json, offline=args.offline) else: index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, use_cache=args.use_index_cache, json=args.json, offline=args.offline) specs = None if args.features: features = set(args.package_names) actions = plan.remove_features_actions(prefix, index, features) elif args.all: if plan.is_root_prefix(prefix): common.error_and_exit('cannot remove root environment,\n' ' add -n NAME or -p PREFIX option', json=args.json, error_type="CantRemoveRoot") actions = {inst.PREFIX: prefix} for dist in sorted(linked(prefix)): plan.add_unlink(actions, dist) else: specs = common.specs_from_args(args.package_names) if (plan.is_root_prefix(prefix) and common.names_in_specs(common.root_no_rm, specs)): common.error_and_exit('cannot remove %s from root environment' % ', '.join(common.root_no_rm), json=args.json, error_type="CantRemoveFromRoot") actions = plan.remove_actions(prefix, specs, index=index, pinned=args.pinned) if plan.nothing_to_do(actions): if args.all: rm_rf(prefix) if args.json: common.stdout_json({ 'success': True, 'actions': actions }) return common.error_and_exit('no packages found to remove from ' 'environment: %s' % prefix, json=args.json, error_type="PackageNotInstalled") if not args.json: print() print("Package plan for package removal in environment %s:" % prefix) plan.display_actions(actions, index) if args.json and args.dry_run: common.stdout_json({ 'success': True, 'dry_run': True, 'actions': actions }) return if not args.json: common.confirm_yn(args) if args.json and not args.quiet: with json_progress_bars(): plan.execute_actions(actions, index, verbose=not args.quiet) else: plan.execute_actions(actions, index, verbose=not args.quiet) if specs: try: with open(join(prefix, 'conda-meta', 'history'), 'a') as f: f.write('# remove specs: %s\n' % specs) except IOError as e: if e.errno == errno.EACCES: log.debug("Can't write the history file") else: raise if args.all: rm_rf(prefix) if args.json: common.stdout_json({ 'success': True, 'actions': actions })