def execute(args, parser): prefix = common.get_prefix(args) regex = args.regex if args.full_name: regex = r'^%s$' % regex if args.revisions: from conda.history import History h = History(prefix) if isfile(h.path): if not args.json: h.print_log() else: common.stdout_json(h.object_log()) else: common.error_and_exit("No revision log found: %s\n" % h.path, json=args.json, error_type="NoRevisionLog") return if args.canonical: format = 'canonical' elif args.export: format = 'export' else: format = 'human' if args.json: format = 'canonical' exitcode = print_packages(prefix, regex, format, piplist=args.pip, json=args.json) sys.exit(exitcode)
def execute(args, parser): if not args.name: # Note, this is a hack fofr get_prefix that assumes argparse results # TODO Refactor common.get_prefix name = os.environ.get('CONDA_DEFAULT_ENV', False) if not name: msg = "Unable to determine environment\n\n" msg += textwrap.dedent(""" Please re-run this command with one of the following options: * Provide an environment name via --name or -n * Re-run this command inside an activated conda environment.""").lstrip() # TODO Add json support common.error_and_exit(msg, json=False) args.name = name else: name = args.name prefix = common.get_prefix(args) env = from_environment(name, prefix) if args.file is None: fp = sys.stdout else: fp = open(args.file, 'wb') env.to_yaml(stream=fp)
def execute(args, parser): try: env = from_file(args.file) except exceptions.EnvironmentFileNotFound as e: msg = 'Unable to locate environment file: %s\n\n' % e.filename msg += "\n".join(textwrap.wrap(textwrap.dedent(""" Please verify that the above file is present and that you have permission read the file's contents. Note, you can specify the file to use by explictly adding --file=/path/to/file when calling conda env update.""").lstrip())) common.error_and_exit(msg, json=args.json) if not args.name: if not env.name: # Note, this is a hack fofr get_prefix that assumes argparse results # TODO Refactor common.get_prefix name = os.environ.get('CONDA_DEFAULT_ENV', False) if not name: msg = "Unable to determine environment\n\n" msg += textwrap.dedent(""" Please re-run this command with one of the following options: * Provide an environment name via --name or -n * Re-run this command inside an activated conda environment.""").lstrip() # TODO Add json support common.error_and_exit(msg, json=False) # Note: stubbing out the args object as all of the # conda.cli.common code thinks that name will always # be specified. args.name = env.name prefix = common.get_prefix(args, search=False) # CAN'T Check with this function since it assumes we will create prefix. # cli_install.check_prefix(prefix, json=args.json) # TODO, add capability # common.ensure_override_channels_requires_channel(args) # channel_urls = args.channel or () for installer_type, specs in env.dependencies.items(): try: installer = get_installer(installer_type) installer.install(prefix, specs, args, env) except InvalidInstaller: sys.stderr.write(textwrap.dedent(""" Unable to install package for {0}. Please double check and ensure you dependencies file has the correct spelling. You might also try installing the conda-env-{0} package to see if provides the required installer. """).lstrip().format(installer_type) ) return -1 touch_nonadmin(prefix) if not args.json: cli_install.print_activate(args.name if args.name else prefix)
def execute(args, parser): if not args.subcommand: parser.print_help() with Locked(config.croot): if args.subcommand == 'linkages': if not sys.platform.startswith('linux'): sys.exit("Error: conda inspect linkages is only implemented in Linux") prefix = get_prefix(args) installed = ci.linked(prefix) for pkg in args.packages: for dist in installed: if pkg == dist.rsplit('-', 2)[0]: break else: sys.exit("Package %s is not installed in %s" % (pkg, prefix)) linkages = get_package_linkages(dist, prefix) depmap = defaultdict(list) for binary in linkages: for lib, path in linkages[binary]: path = abspath(path) if path not in {'', 'not found'} else path if path.startswith(prefix): deps = list(which_package(path)) if len(deps) > 1: print("Warning: %s comes from multiple packages: %s" % (path, ' and '.join(deps)), file=sys.stderr) for d in deps: depmap[d].append((lib, path.split(prefix + '/', 1)[-1], binary)) elif path == 'not found': depmap['not found'].append((lib, path, binary)) else: depmap['system'].append((lib, path, binary)) print_linkages(depmap, show_files=args.show_files)
def execute(args, parser): prefix = get_prefix(args) if not isdir(prefix): sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create the environment first. #""" % prefix) for package in linked(prefix): name, ver, _ = package .rsplit('-', 2) if name == 'python': py_ver = ver[:3] # x.y break else: raise RuntimeError("python is not installed in %s" % prefix) for path in args.source: pkg_path = abspath(expanduser(path)) if not args.no_pth_file: stdlib_dir = join(prefix, 'Lib' if sys.platform == 'win32' else 'lib/python%s' % py_ver) sp_dir = join(stdlib_dir, 'site-packages') # todo: # build the package if setup.py is found then invoke it with # build_ext --inplace - this only exists for extensions write_to_conda_pth(sp_dir, pkg_path) # go through the source looking for compiled extensions and make sure # they use the conda environment for loading libraries at runtime relink_sharedobjects(pkg_path, prefix) print("completed operation for: " + pkg_path)
def execute(args, parser): import sys import json import conda.bundle as bundle from conda.common.download import TmpDownload if not (args.create or args.extract or args.metadump): sys.exit("""Error: either one of the following options is required: -c/--create -x/--extract --metadump (see -h for more details)""") prefix = common.get_prefix(args) if args.no_env: prefix = None if args.create: if args.extra_meta: with open(args.extra_meta) as fi: extra = json.load(fi) if not isinstance(extra, dict): sys.exit('Error: no dictionary in: %s' % args.extra_meta) else: extra = None bundle.warn = [] out_path = bundle.create_bundle(prefix, args.data_path, args.bundle_name, extra) if args.json: d = dict(path=out_path, warnings=bundle.warn) json.dump(d, sys.stdout, indent=2, sort_keys=True) else: print(out_path) if args.extract: if args.data_path or args.extra_meta: sys.exit("""\ Error: -x/--extract does not allow --data-path or --extra-meta""") with TmpDownload(args.extract, verbose=not args.quiet) as path: bundle.clone_bundle(path, prefix, args.bundle_name) if args.metadump: import tarfile with TmpDownload(args.metadump, verbose=not args.quiet) as path: try: t = tarfile.open(path, 'r:*') f = t.extractfile('info/index.json') sys.stdout.write(f.read()) sys.stdout.write('\n') except IOError: sys.exit("Error: no such file: %s" % path) except tarfile.ReadError: sys.exit("Error: bad tar archive: %s" % path) except KeyError: sys.exit("Error: no archive '%s' in: %s" % (bundle.BMJ, path)) t.close()
def execute(args, parser): prefix = common.get_prefix(args) if args.revisions: from conda.history import History h = History(prefix) if isfile(h.path): if not args.json: h.print_log() else: common.stdout_json(h.object_log()) else: common.error_and_exit("No revision log found: %s\n" % h.path, json=args.json, error_type="NoRevisionLog") return if args.canonical: format = "canonical" elif args.export: format = "export" else: format = "human" if args.json: format = "canonical" print_packages(prefix, args.regex, format, piplist=args.pip, json=args.json)
def execute(args, parser): from conda.misc import untracked, which_package from conda.packup import make_tarbz2 prefix = common.get_prefix(args) if args.which: for path in args.which: for dist in which_package(path): print('%-50s %s' % (path, dist)) return print('# prefix:', prefix) if args.reset: remove(prefix, untracked(prefix)) return if args.untracked: files = sorted(untracked(prefix)) print('# untracked files: %d' % len(files)) for fn in files: print(fn) return make_tarbz2(prefix, name = args.pkg_name.lower(), version = args.pkg_version, build_number = int(args.pkg_build))
def execute(args, parser): if not args.name: # Note, this is a hack fofr get_prefix that assumes argparse results # TODO Refactor common.get_prefix name = os.environ.get('CONDA_DEFAULT_ENV', False) if not name: msg = "Unable to determine environment\n\n" msg += textwrap.dedent(""" Please re-run this command with one of the following options: * Provide an environment name via --name or -n * Re-run this command inside an activated conda environment.""" ).lstrip() # TODO Add json support common.error_and_exit(msg, json=False) args.name = name else: name = args.name prefix = common.get_prefix(args) env = from_environment(name, prefix, no_builds=args.no_builds) if args.override_channels: env.remove_channels() if args.channel is not None: env.add_channels(args.channel) if args.file is None: print(env.to_yaml()) else: fp = open(args.file, 'wb') env.to_yaml(stream=fp)
def execute(args, parser): prefix = common.get_prefix(args) regex = args.regex if args.full_name: regex = r'^%s$' % regex if args.revisions: from conda.history import History h = History(prefix) if isfile(h.path): if not args.json: h.print_log() else: common.stdout_json(h.object_log()) else: common.error_and_exit("No revision log found: %s\n" % h.path, json=args.json, error_type="NoRevisionLog") return if args.canonical: format = 'canonical' elif args.export: format = 'export' else: format = 'human' if args.json: format = 'canonical' print_packages(prefix, regex, format, piplist=args.pip, json=args.json)
def execute(args, parser): import re import conda.install as install from conda.api import get_index from conda.resolve import MatchSpec, Resolve if args.regex: pat = re.compile(args.regex, re.I) else: pat = None prefix = common.get_prefix(args) if not args.canonical: linked = install.linked(prefix) # XXX: Make this work with more than one platform platform = args.platform or '' common.ensure_override_channels_requires_channel(args, dashc=False) channel_urls = args.channel or () index = get_index(channel_urls=channel_urls, prepend=not args.override_channels, platform=args.platform) r = Resolve(index) for name in sorted(r.groups): disp_name = name if pat and pat.search(name) is None: continue if args.outdated: vers_inst = [ dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name ] if not vers_inst: continue assert len(vers_inst) == 1, name pkgs = sorted(r.get_pkgs(MatchSpec(name))) if not pkgs: continue latest = pkgs[-1] if latest.version == vers_inst[0]: continue for pkg in sorted(r.get_pkgs(MatchSpec(name))): dist = pkg.fn[:-8] if args.canonical: print(dist) continue inst = '*' if dist in linked else ' ' print('%-25s %s %-15s %15s %-15s %s' % ( disp_name, inst, pkg.version, r.index[pkg.fn]['build'], canonical_channel_name(pkg.channel), common.disp_features(r.features(pkg.fn)), )) disp_name = ''
def execute(args, parser): import sys from os.path import basename from conda.misc import untracked from conda.builder.packup import make_tarbz2, remove prefix = common.get_prefix(args) if args.check: from conda.builder.tarcheck import check_all for path in args.path: try: check_all(path) print('%s OK' % basename(path)) except Exception as e: print(e) print('%s FAILED' % basename(path)) return if args.which: from conda.builder.packup import which_package for path in args.path: for dist in which_package(path): print('%-50s %s' % (path, dist)) return if args.path: sys.exit("Error: no positional arguments expected.") print('# prefix:', prefix) if args.reset: remove(prefix, untracked(prefix)) return if args.untracked: files = sorted(untracked(prefix)) print('# untracked files: %d' % len(files)) for fn in files: print(fn) return if args.share: from conda.builder.share import create_bundle path, warnings = create_bundle(prefix) for w in warnings: print("Warning:", w) print(path) return make_tarbz2(prefix, name = args.pkg_name, version = args.pkg_version, build_number = int(args.pkg_build))
def execute(args, parser): name = args.remote_definition or args.name try: spec = install_specs.detect(name=name, filename=args.file, directory=os.getcwd()) env = spec.environment except exceptions.SpecNotFound as e: common.error_and_exit(str(e), json=args.json) if not args.name: if not env.name: # Note, this is a hack fofr get_prefix that assumes argparse results # TODO Refactor common.get_prefix name = os.environ.get('CONDA_DEFAULT_ENV', False) if not name: msg = "Unable to determine environment\n\n" msg += textwrap.dedent(""" Please re-run this command with one of the following options: * Provide an environment name via --name or -n * Re-run this command inside an activated conda environment.""" ).lstrip() # TODO Add json support common.error_and_exit(msg, json=False) # Note: stubbing out the args object as all of the # conda.cli.common code thinks that name will always # be specified. args.name = env.name prefix = common.get_prefix(args, search=False) # CAN'T Check with this function since it assumes we will create prefix. # cli_install.check_prefix(prefix, json=args.json) # TODO, add capability # common.ensure_override_channels_requires_channel(args) # channel_urls = args.channel or () for installer_type, specs in env.dependencies.items(): try: installer = get_installer(installer_type) installer.install(prefix, specs, args, env) except InvalidInstaller: sys.stderr.write( textwrap.dedent(""" Unable to install package for {0}. Please double check and ensure you dependencies file has the correct spelling. You might also try installing the conda-env-{0} package to see if provides the required installer. """).lstrip().format(installer_type)) return -1 touch_nonadmin(prefix) if not args.json: cli_install.print_activate(args.name if args.name else prefix)
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 execute(args, parser): name = args.remote_definition or args.name try: spec = install_specs.detect( name=name, filename=args.file, directory=os.getcwd()) env = spec.environment except exceptions.SpecNotFound as e: common.error_and_exit(str(e), json=args.json) if not args.name: if not env.name: # Note, this is a hack fofr get_prefix that assumes argparse results # TODO Refactor common.get_prefix name = os.environ.get('CONDA_DEFAULT_ENV', False) if not name: msg = "Unable to determine environment\n\n" msg += textwrap.dedent(""" Please re-run this command with one of the following options: * Provide an environment name via --name or -n * Re-run this command inside an activated conda environment.""" ).lstrip() # TODO Add json support common.error_and_exit(msg, json=False) # Note: stubbing out the args object as all of the # conda.cli.common code thinks that name will always # be specified. args.name = env.name prefix = common.get_prefix(args, search=False) # CAN'T Check with this function since it assumes we will create prefix. # cli_install.check_prefix(prefix, json=args.json) # TODO, add capability # common.ensure_override_channels_requires_channel(args) # channel_urls = args.channel or () for installer_type, specs in env.dependencies.items(): try: installer = get_installer(installer_type) installer.install(prefix, specs, args, env) except InvalidInstaller: sys.stderr.write( textwrap.dedent(""" Unable to install package for {0}. Please double check and ensure you dependencies file has the correct spelling. You might also try installing the conda-env-{0} package to see if provides the required installer. """).lstrip().format(installer_type)) return -1 touch_nonadmin(prefix) if not args.json: cli_install.print_activate(args.name if args.name else prefix)
def execute(args, parser): import sys import json import conda.bundle as bundle from conda.fetch import TmpDownload if not (args.create or args.extract or args.metadump): sys.exit("""Error: either one of the following options is required: -c/--create -x/--extract --metadump (see -h for more details)""") prefix = common.get_prefix(args) if args.no_env: prefix = None if args.create: if args.extra_meta: with open(args.extra_meta) as fi: extra = json.load(fi) if not isinstance(extra, dict): sys.exit('Error: no dictionary in: %s' % args.extra_meta) else: extra = None bundle.warn = [] out_path = bundle.create_bundle(prefix, args.data_path, args.bundle_name, extra) if args.json: d = dict(path=out_path, warnings=bundle.warn) json.dump(d, sys.stdout, indent=2, sort_keys=True) else: print(out_path) if args.extract: if args.data_path or args.extra_meta: sys.exit("""\ Error: -x/--extract does not allow --data-path or --extra-meta""") with TmpDownload(args.extract, verbose=not args.quiet) as path: bundle.clone_bundle(path, prefix, args.bundle_name) if args.metadump: import tarfile with TmpDownload(args.metadump, verbose=not args.quiet) as path: try: t = tarfile.open(path, 'r:*') f = t.extractfile('info/index.json') sys.stdout.write(f.read()) sys.stdout.write('\n') except IOError: sys.exit("Error: no such file: %s" % path) except tarfile.ReadError: sys.exit("Error: bad tar archive: %s" % path) except KeyError: sys.exit("Error: no archive '%s' in: %s" % (bundle.BMJ, path)) t.close()
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 re import conda.install as install from conda.api import get_index from conda.resolve import MatchSpec, Resolve if args.regex: pat = re.compile(args.regex, re.I) else: pat = None prefix = common.get_prefix(args) if not args.canonical: linked = install.linked(prefix) # XXX: Make this work with more than one platform platform = args.platform or '' common.ensure_override_channels_requires_channel(args, dashc=False) channel_urls = args.channel or () index = get_index(channel_urls=channel_urls, prepend=not args.override_channels, platform=args.platform) r = Resolve(index) for name in sorted(r.groups): disp_name = name if pat and pat.search(name) is None: continue if args.outdated: vers_inst = [dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name] if not vers_inst: continue assert len(vers_inst) == 1, name pkgs = sorted(r.get_pkgs(MatchSpec(name))) if not pkgs: continue latest = pkgs[-1] if latest.version == vers_inst[0]: continue for pkg in sorted(r.get_pkgs(MatchSpec(name))): dist = pkg.fn[:-8] if args.canonical: print(dist) continue inst = '*' if dist in linked else ' ' print('%-25s %s %-15s %15s %-15s %s' % ( disp_name, inst, pkg.version, r.index[pkg.fn]['build'], canonical_channel_name(pkg.channel), common.disp_features(r.features(pkg.fn)), )) disp_name = ''
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 execute(args, parser): prefix = common.get_prefix(args) if args.canonical: format = 'canonical' elif args.export: format = 'export' else: format = 'human' sys.exit(list_packages(prefix, args.regex, format=format, piplist=args.pip))
def execute(args, parser): if not args.package: parser.print_help() return import conda.install import conda.resolve from conda.api import get_package_versions, app_is_installed from conda.misc import launch prefix = common.get_prefix(args) if args.quiet: logging.disable(logging.CRITICAL) if args.package.endswith('.tar.bz2'): if app_is_installed(args.package, prefixes=[prefix]): fn = args.package else: error_message = "Package {} not installed.".format(args.package) common.error_and_exit(error_message, json=args.json, error_type="PackageNotInstalled") else: installed = [] for pkg in get_package_versions(args.package): if app_is_installed(pkg.fn, prefixes=[prefix]): installed.append(pkg) for pkg in conda.install.linked(prefix): name, version, build = pkg.rsplit('-', 2) if name == args.package: installed = [conda.resolve.Package(pkg + '.tar.bz2', conda.install.is_linked(prefix, pkg))] break if installed: package = max(installed) fn = package.fn try: subprocess = launch(fn, prefix=prefix, additional_args=args.arguments, background=args.json) if args.json: common.stdout_json(dict(fn=fn, pid=subprocess.pid)) elif not args.quiet: print("Started app. Some apps may take a while to finish loading.") except TypeError: execute_command(args.package, prefix, args.arguments, args.json) except Exception as e: common.exception_and_exit(e, json=args.json) else: # Try interpreting it as a command execute_command(args.package, prefix, args.arguments, args.json)
def execute(args, parser): try: env = from_file(args.file) except exceptions.EnvironmentFileNotFound as e: msg = 'Unable to locate environment file: %s\n\n' % e.filename msg += "\n".join(textwrap.wrap(textwrap.dedent(""" Please verify that the above file is present and that you have permission read the file's contents. Note, you can specify the file to use by explictly adding --file=/path/to/file when calling conda env create.""").lstrip())) common.error_and_exit(msg, json=args.json) if not args.name: if not env.name: # TODO It would be nice to be able to format this more cleanly common.error_and_exit( 'An environment name is required.\n\n' 'You can either specify one directly with --name or you can add\n' 'a name property to your %s file.' % args.file, json=args.json ) # Note: stubbing out the args object as all of the # conda.cli.common code thinks that name will always # be specified. args.name = env.name prefix = common.get_prefix(args, search=False) cli_install.check_prefix(prefix, json=args.json) # TODO, add capability # common.ensure_override_channels_requires_channel(args) # channel_urls = args.channel or () for installer_type, specs in env.dependencies.items(): try: installer = get_installer(installer_type) installer.install(prefix, specs, args, env) except InvalidInstaller: sys.stderr.write(textwrap.dedent(""" Unable to install package for {0}. Please double check and ensure you dependencies file has the correct spelling. You might also try installing the conda-env-{0} package to see if provides the required installer. """).lstrip().format(installer_type) ) return -1 touch_nonadmin(prefix) if not args.json: cli_install.print_activate(args.name if args.name else prefix)
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 execute(args, parser): if args.name is not None: prefix = common.get_prefix(args) content = from_environment(args.name, prefix, no_builds=args.no_builds).to_dict() else: content = {'remote': args.remote} print("Environment {} will be attach into {}".format(args.name, args.notebook)) nb = Notebook(args.notebook) if nb.inject(content, args.force): print("Done.") else: print("The environment couldn't be attached due:") print(nb.msg)
def execute(args, parser): if args.name is not None: prefix = common.get_prefix(args) content = from_environment(args.name, prefix, no_builds=args.no_builds).to_dict() else: content = {'remote': args.remote} print("Environment {} will be attach into {}".format( args.name, args.notebook)) nb = Notebook(args.notebook) if nb.inject(content, args.force): print("Done.") else: print("The environment couldn't be attached due:") print(nb.msg)
def execute(args, parser): name = args.remote_definition or args.name try: spec = specs.detect(name=name, filename=args.file, directory=os.getcwd(), selectors=args.select) env = spec.environment # FIXME conda code currently requires args to have a name or prefix if args.prefix is None: args.name = env.name except exceptions.SpecNotFound as e: common.error_and_exit(str(e), json=args.json) prefix = common.get_prefix(args, search=False) if args.force and not is_root_prefix(prefix) and os.path.exists(prefix): rm_rf(prefix) cli_install.check_prefix(prefix, json=args.json) # TODO, add capability # common.ensure_override_channels_requires_channel(args) # channel_urls = args.channel or () for installer_type, pkg_specs in env.dependencies.items(): try: installer = get_installer(installer_type) installer.install(prefix, pkg_specs, args, env) except InvalidInstaller: sys.stderr.write( textwrap.dedent(""" Unable to install package for {0}. Please double check and ensure you dependencies file has the correct spelling. You might also try installing the conda-env-{0} package to see if provides the required installer. """).lstrip().format(installer_type)) return -1 touch_nonadmin(prefix) if not args.json: cli_install.print_activate(args.name if args.name else prefix)
def execute(args, parser): import sys import json from conda.builder.share import create_bundle prefix = common.get_prefix(args) path, warnings = create_bundle(prefix) if args.json: d = dict(path=path, warnings=warnings) json.dump(d, sys.stdout, indent=2, sort_keys=True) else: for w in warnings: print("Warning:", w) print(path)
def execute(args, parser): prefix = get_prefix(args) if not isdir(prefix): sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create the environment first. #""" % prefix) for package in linked(prefix): name, ver, _ = package.rsplit('-', 2) if name == 'python': py_ver = ver[:3] # x.y break else: raise RuntimeError("python is not installed in %s" % prefix) # current environment's site-packages directory sp_dir = get_site_pkg(prefix, py_ver) for path in args.source: pkg_path = abspath(expanduser(path)) if args.uninstall: # uninstall then exit - does not do any other operations uninstall(sp_dir, pkg_path) sys.exit(0) if args.clean or args.build_ext: setup_py = get_setup_py(pkg_path) if args.clean: clean(setup_py) if not args.build_ext: sys.exit(0) # build extensions before adding to conda.pth if args.build_ext: build_ext(setup_py) if not args.no_pth_file: write_to_conda_pth(sp_dir, pkg_path) # go through the source looking for compiled extensions and make sure # they use the conda environment for loading libraries at runtime relink_sharedobjects(pkg_path, prefix) print("completed operation for: " + pkg_path)
def execute(args, parser): name = None if args.old_name: print("--name is deprecated. Use the following command instead:\n" " conda env create {}".format(args.old_name), file=sys.stderr) name = args.old_name elif args.name: name = args.name try: spec = specs.detect(name=name, filename=args.file, directory=os.getcwd()) env = spec.environment # FIXME conda code currently requires args to have a name or prefix args.name = env.name except exceptions.SpecNotFound as e: common.error_and_exit(str(e), json=args.json) prefix = common.get_prefix(args, search=False) cli_install.check_prefix(prefix, json=args.json) # TODO, add capability # common.ensure_override_channels_requires_channel(args) # channel_urls = args.channel or () for installer_type, pkg_specs in env.dependencies.items(): try: installer = get_installer(installer_type) installer.install(prefix, pkg_specs, args, env) except InvalidInstaller: sys.stderr.write(textwrap.dedent(""" Unable to install package for {0}. Please double check and ensure you dependencies file has the correct spelling. You might also try installing the conda-env-{0} package to see if provides the required installer. """).lstrip().format(installer_type) ) return -1 touch_nonadmin(prefix) if not args.json: cli_install.print_activate(args.name if args.name else prefix)
def execute(args, parser): prefix = get_prefix(args) if not isdir(prefix): sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create the environment first. #""" % prefix) for package in linked(prefix): name, ver, _ = package .rsplit('-', 2) if name == 'python': py_ver = ver[:3] # x.y break else: raise RuntimeError("python is not installed in %s" % prefix) # current environment's site-packages directory sp_dir = get_site_pkg(prefix, py_ver) for path in args.source: pkg_path = abspath(expanduser(path)) if args.uninstall: # uninstall then exit - does not do any other operations uninstall(sp_dir, pkg_path) sys.exit(0) if args.clean or args.build_ext: setup_py = get_setup_py(pkg_path) if args.clean: clean(setup_py) if not args.build_ext: sys.exit(0) # build extensions before adding to conda.pth if args.build_ext: build_ext(setup_py) if not args.no_pth_file: write_to_conda_pth(sp_dir, pkg_path) # go through the source looking for compiled extensions and make sure # they use the conda environment for loading libraries at runtime relink_sharedobjects(pkg_path, prefix) print("completed operation for: " + pkg_path)
def execute(args, parser): import sys from conda.misc import untracked from conda.packup import make_tarbz2, remove prefix = common.get_prefix(args) if args.which: from conda.misc import which_package for path in args.path: for dist in which_package(path): print('%-50s %s' % (path, dist)) return if args.ls_files: if list_package_files(args.ls_files) == 1: sys.exit(1) else: return if args.path: sys.exit("Error: no positional arguments expected.") print('# prefix:', prefix) if args.reset: remove(prefix, untracked(prefix)) return if args.untracked: files = sorted(untracked(prefix)) print('# untracked files: %d' % len(files)) for fn in files: print(fn) return make_tarbz2(prefix, name = args.pkg_name.lower(), version = args.pkg_version, build_number = int(args.pkg_build))
def execute(args, parser): import sys from conda.misc import untracked from conda.packup import make_tarbz2, remove prefix = common.get_prefix(args) if args.which: from conda.misc import which_package for path in args.path: for dist in which_package(path): print('%-50s %s' % (path, dist)) return if args.ls_files: if list_package_files(args.ls_files) == 1: sys.exit(1) else: return if args.path: sys.exit("Error: no positional arguments expected.") print('# prefix:', prefix) if args.reset: remove(prefix, untracked(prefix)) return if args.untracked: files = sorted(untracked(prefix)) print('# untracked files: %d' % len(files)) for fn in files: print(fn) return make_tarbz2(prefix, name=args.pkg_name.lower(), version=args.pkg_version, build_number=int(args.pkg_build))
def execute(args, parser): import sys import json from os.path import isfile from conda.builder.share import clone_bundle common.ensure_name_or_prefix(args, 'clone') prefix = common.get_prefix(args) path = args.path[0] if not isfile(path): sys.exit("Error: no such file: %s" % path) clone_bundle(path, prefix) if args.json: json.dump(dict(warnings=[]), sys.stdout, indent=2)
def execute(args, parser): prefix = common.get_prefix(args) if args.revisions: from conda.history import History h = History(prefix) if isfile(h.path): h.print_log() else: sys.stderr.write("No revision log found: %s\n" % h.path) return if args.canonical: format = 'canonical' elif args.export: format = 'export' else: format = 'human' sys.exit(list_packages(prefix, args.regex, format=format, piplist=args.pip))
def execute(args, parser): prefix = get_prefix(args) if not isdir(prefix): sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create the environment first. #""" % prefix) for package in linked(prefix): name, ver, build = package.rsplit('-', 2) if name == 'python': py_ver = ver[:3] # x.y break else: raise RuntimeError("python is not installed in %s" % prefix) stdlib_dir = join(prefix, 'Lib' if sys.platform == 'win32' else 'lib/python%s' % py_ver) sp_dir = join(stdlib_dir, 'site-packages') with open(join(sp_dir, 'conda.pth'), 'a') as f: for path in args.source: f.write(abspath(expanduser(path)) + '\n')
def execute(args, parser): prefix = get_prefix(args) if not isdir(prefix): sys.exit("""\ Error: environment does not exist: %s # # Use 'conda create' to create the environment first. #""" % prefix) for package in linked(prefix): name, ver, build = package.rsplit('-', 2) if name == 'python': py_ver = ver[:3] # x.y break else: raise RuntimeError("python is not installed in %s" % prefix) stdlib_dir = join( prefix, 'Lib' if sys.platform == 'win32' else 'lib/python%s' % py_ver) sp_dir = join(stdlib_dir, 'site-packages') with open(join(sp_dir, 'conda.pth'), 'a') as f: for path in args.source: f.write(abspath(expanduser(path)) + '\n')
def execute(args, parser): import re import conda.install as install from conda.api import get_index from conda.resolve import MatchSpec, Resolve if args.regex: pat = re.compile(args.regex, re.I) else: pat = None prefix = common.get_prefix(args) if not args.canonical: linked = install.linked(prefix) common.ensure_override_channels_requires_channel(args, dashc=False) channel_urls = args.channel or () index = get_index(channel_urls=channel_urls, prepend=not args.override_channels) r = Resolve(index) for name in sorted(r.groups): disp_name = name if pat and pat.search(name) is None: continue for pkg in sorted(r.get_pkgs(MatchSpec(name))): dist = pkg.fn[:-8] if args.canonical: print(dist) continue inst = '*' if dist in linked else ' ' print('%-25s %s %-15s %15s %s' % ( disp_name, inst, pkg.version, r.index[pkg.fn]['build'], common.disp_features(r.features(pkg.fn))) ) disp_name = ''
def execute(args, parser): if not args.name: # Note, this is a hack fofr get_prefix that assumes argparse results # TODO Refactor common.get_prefix name = os.environ.get('CONDA_DEFAULT_ENV', False) if not name: msg = "Unable to determine environment\n\n" msg += textwrap.dedent(""" Please re-run this command with one of the following options: * Provide an environment name via --name or -n * Re-run this command inside an activated conda environment.""").lstrip() # TODO Add json support common.error_and_exit(msg, json=False) args.name = name prefix = common.get_prefix(args) installed = install.linked(prefix) conda_pkgs = copy(installed) # json=True hides the output, data is added to installed main_list.add_pip_installed(prefix, installed, json=True) pip_pkgs = sorted(installed - conda_pkgs) dependencies = ['='.join(a.rsplit('-', 2)) for a in sorted(conda_pkgs)] if len(pip_pkgs) > 0: dependencies.append({'pip': ['=='.join(a.rsplit('-', 2)[:2]) for a in pip_pkgs]}) data = { 'name': args.name, 'dependencies': dependencies, } if args.file is None: fp = sys.stdout else: fp = open(args.file, 'wb') yaml.dump(data, default_flow_style=False, stream=fp)
def execute(args, parser): from os.path import basename from conda.builder.packup import make_tarbz2, untracked, remove prefix = common.get_prefix(args) if args.check: from conda.builder.tarcheck import check_all try: check_all(args.check) print('%s OK' % basename(args.check)) except Exception as e: print(e) print('%s FAILED' % basename(args.check)) return print('# prefix:', prefix) if args.reset: remove(prefix, untracked(prefix)) return if args.untracked: files = sorted(untracked(prefix)) print('# untracked files: %d' % len(files)) for fn in files: print(fn) return make_tarbz2(prefix, name = args.pkg_name, version = args.pkg_version, build_number = int(args.pkg_build))
def execute(args, parser): if not args.subcommand: parser.print_help() prefix = get_prefix(args) installed = ci.linked(prefix) if not args.packages and not args.untracked and not args.all: parser.error( "At least one package or --untracked or --all must be provided") if args.all: args.packages = sorted([i.rsplit('-', 2)[0] for i in installed]) if args.untracked: args.packages.append(untracked_package) for pkg in args.packages: if pkg == untracked_package: dist = untracked_package else: for dist in installed: if pkg == dist.rsplit('-', 2)[0]: break else: sys.exit("Package %s is not installed in %s" % (pkg, prefix)) print(pkg) print('-' * len(str(pkg))) print() if args.subcommand == 'linkages': if not sys.platform.startswith(('linux', 'darwin')): sys.exit( "Error: conda inspect linkages is only implemented in Linux and OS X" ) if dist == untracked_package: obj_files = get_untracked_obj_files(prefix) else: obj_files = get_package_obj_files(dist, prefix) linkages = get_linkages(obj_files, prefix) depmap = defaultdict(list) for binary in linkages: for lib, path in linkages[binary]: path = replace_path(binary, path, prefix) if path not in { '', 'not found' } else path if path.startswith(prefix): deps = list(which_package(path)) if len(deps) > 1: print( "Warning: %s comes from multiple packages: %s" % (path, ' and '.join(deps)), file=sys.stderr) if not deps: if exists(path): depmap['untracked'].append( (lib, path.split(prefix + '/', 1)[-1], binary)) else: depmap['not found'].append( (lib, path.split(prefix + '/', 1)[-1], binary)) for d in deps: depmap[d].append((lib, path.split(prefix + '/', 1)[-1], binary)) elif path == 'not found': depmap['not found'].append((lib, path, binary)) else: depmap['system'].append((lib, path, binary)) print_linkages(depmap, show_files=args.show_files) if args.subcommand == 'objects': if not sys.platform.startswith('darwin'): sys.exit( "Error: conda inspect objects is only implemented in OS X") if dist == untracked_package: obj_files = get_untracked_obj_files(prefix) else: obj_files = get_package_obj_files(dist, prefix) info = [] for f in obj_files: f_info = {} path = join(prefix, f) f_info['filetype'] = human_filetype(path) f_info['rpath'] = get_rpath(path) f_info['filename'] = f info.append(f_info) print_object_info(info, args.groupby)
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 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 main(): if len(sys.argv) > 1: argv1 = sys.argv[1] if argv1 in ('..activate', '..deactivate', '..checkenv', '..setps1'): import conda.cli.activate as activate activate.main() return if argv1 == 'pip': sys.exit("""ERROR: The "conda pip" command has been removed from conda (as of version 1.8) for the following reasons: * users get the wrong impression that you *must* use conda pip (instead of simply pip) when using Anaconda * there should only be one preferred way to build packages, and that is the conda build command * the command did too many things at once, i.e. build a package and then also install it * the command is Python centric, whereas conda (from a package management perspective) is Python agnostic * packages created with conda pip are not robust, i.e. they will maybe not work on other people's systems In short: * use "conda build" if you want to build a conda package * use "conda install" if you want to install something * use "pip" if you want to install something that is on PyPI for which there isn't a conda package. """) if argv1 in ('activate', 'deactivate'): sys.stderr.write("Error: '%s' is not a conda command.\n" % argv1) if sys.platform != 'win32': sys.stderr.write('Did you mean "source %s" ?\n' % ' '.join(sys.argv[1:])) sys.exit(1) # for backwards compatibility of conda-api if sys.argv[1:4] == ['share', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_create_bundle prefix = sys.argv[4] path, warnings = old_create_bundle(abspath(prefix)) json.dump(dict(path=path, warnings=warnings), sys.stdout, indent=2, sort_keys=True) return if sys.argv[1:4] == ['clone', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_clone_bundle prefix, path = sys.argv[4:6] old_clone_bundle(path, abspath(prefix)) json.dump(dict(warnings=[]), sys.stdout, indent=2) return if len(sys.argv) == 1: sys.argv.append('-h') import logging from conda.cli import conda_argparse import argparse import conda p = conda_argparse.ArgumentParser( description='conda is a tool for managing and deploying applications,' ' environments and packages.' ) p.add_argument( '-V', '--version', action='version', version='conda %s' % conda.__version__, help="Show the conda version number and exit." ) p.add_argument( "--debug", action = "store_true", help = "Show debug output." ) p.add_argument( "--json", action = "store_true", help = argparse.SUPPRESS, ) sub_parsers = p.add_subparsers( metavar = 'command', dest = 'cmd', ) main_modules = ["info", "help", "list", "search", "create", "install", "update", "remove", "run", "config", "init", "clean", "package", "bundle"] modules = ["conda.cli.main_"+suffix for suffix in main_modules] for module in modules: imported = importlib.import_module(module) imported.configure_parser(sub_parsers) if "update" in module: imported.configure_parser(sub_parsers, name='upgrade') if "remove" in module: imported.configure_parser(sub_parsers, name='uninstall') from conda.cli.find_commands import find_commands sub_parsers.completer = lambda prefix, **kwargs: [i for i in list(sub_parsers.choices) + find_commands() if i.startswith(prefix)] args = p.parse_args() if getattr(args, 'json', False): # Silence logging info to avoid interfering with JSON output for logger in logging.Logger.manager.loggerDict: if logger not in ('fetch', 'progress'): logging.getLogger(logger).setLevel(logging.CRITICAL + 1) if args.debug: logging.disable(logging.NOTSET) logging.basicConfig(level=logging.DEBUG) from conda.cli import main_init if (not main_init.is_initialized() and 'init' not in sys.argv and 'info' not in sys.argv): if hasattr(args, 'name') and hasattr(args, 'prefix'): import conda.config as config from conda.cli import common if common.get_prefix(args) == config.root_dir: sys.exit("""\ Error: This installation of conda is not initialized. Use 'conda create -n envname' to create a conda environment and 'source activate envname' to activate it. # Note that pip installing conda is not the recommended way for setting up your # system. The recommended way for setting up a conda system is by installing # Miniconda, see: http://repo.continuum.io/miniconda/index.html""") args_func(args, p)
def main(): if len(sys.argv) > 1: argv1 = sys.argv[1] if argv1 in ('..activate', '..deactivate', '..activateroot', '..checkenv'): import conda.cli.activate as activate activate.main() return if argv1 in ('..changeps1'): import conda.cli.misc as misc misc.main() return if argv1 == 'pip': sys.exit("""ERROR: The "conda pip" command has been removed from conda (as of version 1.8) for the following reasons: * users get the wrong impression that you *must* use conda pip (instead of simply pip) when using Anaconda * there should only be one preferred way to build packages, and that is the conda build command * the command did too many things at once, i.e. build a package and then also install it * the command is Python centric, whereas conda (from a package management perspective) is Python agnostic * packages created with conda pip are not robust, i.e. they will maybe not work on other people's systems In short: * use "conda build" if you want to build a conda package * use "conda install" if you want to install something * use "pip" if you want to install something that is on PyPI for which there isn't a conda package. """) if argv1 in ('activate', 'deactivate'): sys.stderr.write("Error: '%s' is not a conda command.\n" % argv1) if sys.platform != 'win32': sys.stderr.write('Did you mean "source %s" ?\n' % ' '.join(sys.argv[1:])) sys.exit(1) # for backwards compatibility of conda-api if sys.argv[1:4] == ['share', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_create_bundle prefix = sys.argv[4] path, warnings = old_create_bundle(abspath(prefix)) json.dump(dict(path=path, warnings=warnings), sys.stdout, indent=2, sort_keys=True) return if sys.argv[1:4] == ['clone', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_clone_bundle prefix, path = sys.argv[4:6] old_clone_bundle(path, abspath(prefix)) json.dump(dict(warnings=[]), sys.stdout, indent=2) return if len(sys.argv) == 1: sys.argv.append('-h') import logging import conda p = conda_argparse.ArgumentParser( description='conda is a tool for managing environments and packages.') p.add_argument( '-V', '--version', action='version', version='conda %s' % conda.__version__, ) p.add_argument( "--debug", action="store_true", help=argparse.SUPPRESS, ) p.add_argument( "--json", action="store_true", help=argparse.SUPPRESS, ) sub_parsers = p.add_subparsers( metavar='command', dest='cmd', ) main_info.configure_parser(sub_parsers) main_help.configure_parser(sub_parsers) main_list.configure_parser(sub_parsers) main_search.configure_parser(sub_parsers) main_create.configure_parser(sub_parsers) main_install.configure_parser(sub_parsers) main_update.configure_parser(sub_parsers) main_remove.configure_parser(sub_parsers) main_run.configure_parser(sub_parsers) main_config.configure_parser(sub_parsers) main_init.configure_parser(sub_parsers) main_clean.configure_parser(sub_parsers) main_package.configure_parser(sub_parsers) main_bundle.configure_parser(sub_parsers) try: import argcomplete argcomplete.autocomplete(p) except ImportError: pass except AttributeError: # On Python 3.3, argcomplete can be an empty namespace package when # we are in the conda-recipes directory. pass args = p.parse_args() if getattr(args, 'json', False): # Silence logging info to avoid interfering with JSON output import logging for logger in logging.Logger.manager.loggerDict: if logger not in ('fetch', 'progress'): logging.getLogger(logger).setLevel(logging.CRITICAL + 1) if args.debug: logging.disable(logging.NOTSET) logging.basicConfig(level=logging.DEBUG) if (not main_init.is_initialized() and 'init' not in sys.argv and 'info' not in sys.argv): if hasattr(args, 'name') and hasattr(args, 'prefix'): import conda.config as config if common.get_prefix(args) == config.root_dir: sys.exit("""\ Error: This installation of conda is not initialized. Use 'conda create -n envname' to create a conda environment and 'source activate envname' to activate it. # Note that pip installing conda is not the recommended way for setting up your # system. The recommended way for setting up a conda system is by installing # Miniconda, see: http://repo.continuum.io/miniconda/index.html""") args_func(args, p)
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) 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): if not args.subcommand: parser.print_help() exit() prefix = get_prefix(args) installed = ci.linked(prefix) if not args.packages and not args.untracked and not args.all: parser.error( "At least one package or --untracked or --all must be provided") if args.all: args.packages = sorted([i.rsplit('-', 2)[0] for i in installed]) if args.untracked: args.packages.append(untracked_package) if args.subcommand == 'linkages': pkgmap = {} for pkg in args.packages: if pkg == untracked_package: dist = untracked_package else: for dist in installed: if pkg == dist.rsplit('-', 2)[0]: break else: sys.exit("Package %s is not installed in %s" % (pkg, prefix)) if not sys.platform.startswith(('linux', 'darwin')): sys.exit( "Error: conda inspect linkages is only implemented in Linux and OS X" ) if dist == untracked_package: obj_files = get_untracked_obj_files(prefix) else: obj_files = get_package_obj_files(dist, prefix) linkages = get_linkages(obj_files, prefix) depmap = defaultdict(list) pkgmap[pkg] = depmap depmap['not found'] = [] for binary in linkages: for lib, path in linkages[binary]: path = replace_path(binary, path, prefix) if path not in { '', 'not found' } else path if path.startswith(prefix): deps = list(which_package(path)) if len(deps) > 1: print( "Warning: %s comes from multiple packages: %s" % (path, comma_join(deps)), file=sys.stderr) if not deps: if exists(path): depmap['untracked'].append( (lib, path.split(prefix + '/', 1)[-1], binary)) else: depmap['not found'].append( (lib, path.split(prefix + '/', 1)[-1], binary)) for d in deps: depmap[d].append((lib, path.split(prefix + '/', 1)[-1], binary)) elif path == 'not found': depmap['not found'].append((lib, path, binary)) else: depmap['system'].append((lib, path, binary)) if args.groupby == 'package': for pkg in args.packages: print(pkg) print('-' * len(str(pkg))) print() print_linkages(pkgmap[pkg], show_files=args.show_files) elif args.groupby == 'dependency': # {pkg: {dep: [files]}} -> {dep: {pkg: [files]}} inverted_map = defaultdict(lambda: defaultdict(list)) for pkg in pkgmap: for dep in pkgmap[pkg]: if pkgmap[pkg][dep]: inverted_map[dep][pkg] = pkgmap[pkg][dep] # print system and not found last k = sorted(set(inverted_map.keys()) - {'system', 'not found'}) for dep in k + ['system', 'not found']: print(dep) print('-' * len(str(dep))) print() print_linkages(inverted_map[dep], show_files=args.show_files) else: raise ValueError("Unrecognized groupby: %s" % args.groupby) if args.subcommand == 'objects': for pkg in args.packages: if pkg == untracked_package: dist = untracked_package else: for dist in installed: if pkg == dist.rsplit('-', 2)[0]: break else: sys.exit("Package %s is not installed in %s" % (pkg, prefix)) print(pkg) print('-' * len(str(pkg))) print() if not sys.platform.startswith('darwin'): sys.exit( "Error: conda inspect objects is only implemented in OS X") if dist == untracked_package: obj_files = get_untracked_obj_files(prefix) else: obj_files = get_package_obj_files(dist, prefix) info = [] for f in obj_files: f_info = {} path = join(prefix, f) f_info['filetype'] = human_filetype(path) f_info['rpath'] = ':'.join(get_rpaths(path)) f_info['filename'] = f info.append(f_info) print_object_info(info, args.groupby)
======= >>>>>>> princeofdarkness76/feature/instruction-arguments ======= >>>>>>> origin/feature/instruction-arguments from conda.cli import pscheck >>>>>>> conda/feature/instruction-arguments 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")
def execute(args, parser): try: env = from_file(args.file) except exceptions.EnvironmentFileNotFound as e: msg = 'Unable to locate environment file: %s\n\n' % e.filename msg += "\n".join( textwrap.wrap( textwrap.dedent(""" Please verify that the above file is present and that you have permission read the file's contents. Note, you can specify the file to use by explictly adding --file=/path/to/file when calling conda env update.""").lstrip())) common.error_and_exit(msg, json=args.json) if not args.name: if not env.name: # Note, this is a hack fofr get_prefix that assumes argparse results # TODO Refactor common.get_prefix name = os.environ.get('CONDA_DEFAULT_ENV', False) if not name: msg = "Unable to determine environment\n\n" msg += textwrap.dedent(""" Please re-run this command with one of the following options: * Provide an environment name via --name or -n * Re-run this command inside an activated conda environment.""" ).lstrip() # TODO Add json support common.error_and_exit(msg, json=False) # Note: stubbing out the args object as all of the # conda.cli.common code thinks that name will always # be specified. args.name = env.name prefix = common.get_prefix(args, search=False) # CAN'T Check with this function since it assumes we will create prefix. # cli_install.check_prefix(prefix, json=args.json) # TODO, add capability # common.ensure_override_channels_requires_channel(args) # channel_urls = args.channel or () for installer_type, specs in env.dependencies.items(): try: installer = get_installer(installer_type) installer.install(prefix, specs, args, env) except InvalidInstaller: sys.stderr.write( textwrap.dedent(""" Unable to install package for {0}. Please double check and ensure you dependencies file has the correct spelling. You might also try installing the conda-env-{0} package to see if provides the required installer. """).lstrip().format(installer_type)) return -1 touch_nonadmin(prefix) if not args.json: cli_install.print_activate(args.name if args.name else prefix)
def main(): if len(sys.argv) > 1: argv1 = sys.argv[1] if argv1 in ('..activate', '..deactivate', '..activateroot', '..checkenv'): import conda.cli.activate as activate activate.main() return if argv1 in ('..changeps1'): import conda.cli.misc as misc misc.main() return if argv1 in ('activate', 'deactivate'): sys.stderr.write("Error: '%s' is not a conda command.\n" % argv1) if sys.platform != 'win32': sys.stderr.write('Did you mean "source %s" ?\n' % ' '.join(sys.argv[1:])) sys.exit(1) # for backwards compatibility of conda-api if sys.argv[1:4] == ['share', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_create_bundle prefix = sys.argv[4] path, warnings = old_create_bundle(abspath(prefix)) json.dump(dict(path=path, warnings=warnings), sys.stdout, indent=2, sort_keys=True) return if sys.argv[1:4] == ['clone', '--json', '--prefix']: import json from os.path import abspath from conda.share import old_clone_bundle prefix, path = sys.argv[4:6] old_clone_bundle(path, abspath(prefix)) json.dump(dict(warnings=[]), sys.stdout, indent=2) return if len(sys.argv) == 1: sys.argv.append('-h') import logging from conda.cli import conda_argparse import argparse import conda p = conda_argparse.ArgumentParser( description= 'conda is a tool for managing and deploying applications, environments and packages.' ) p.add_argument('-V', '--version', action='version', version='conda %s' % conda.__version__, help="Show the conda version number and exit.") p.add_argument("--debug", action="store_true", help="Show debug output.") p.add_argument( "--json", action="store_true", help=argparse.SUPPRESS, ) sub_parsers = p.add_subparsers( metavar='command', dest='cmd', ) from conda.cli import main_info main_info.configure_parser(sub_parsers) from conda.cli import main_help main_help.configure_parser(sub_parsers) from conda.cli import main_list main_list.configure_parser(sub_parsers) from conda.cli import main_search main_search.configure_parser(sub_parsers) from conda.cli import main_create main_create.configure_parser(sub_parsers) from conda.cli import main_install main_install.configure_parser(sub_parsers) from conda.cli import main_update main_update.configure_parser(sub_parsers) main_update.configure_parser(sub_parsers, name='upgrade') from conda.cli import main_remove main_remove.configure_parser(sub_parsers) main_remove.configure_parser(sub_parsers, name='uninstall') from conda.cli import main_run main_run.configure_parser(sub_parsers) from conda.cli import main_config main_config.configure_parser(sub_parsers) from conda.cli import main_init main_init.configure_parser(sub_parsers) from conda.cli import main_clean main_clean.configure_parser(sub_parsers) from conda.cli import main_package main_package.configure_parser(sub_parsers) from conda.cli import main_bundle main_bundle.configure_parser(sub_parsers) from conda.cli.find_commands import find_commands sub_parsers.completer = lambda prefix, **kwargs: [ i for i in list(sub_parsers.choices) + find_commands() if i.startswith(prefix) ] args = p.parse_args() if getattr(args, 'json', False): # Silence logging info to avoid interfering with JSON output for logger in logging.Logger.manager.loggerDict: if logger not in ('fetch', 'progress'): logging.getLogger(logger).setLevel(logging.CRITICAL + 1) if args.debug: logging.disable(logging.NOTSET) logging.basicConfig(level=logging.DEBUG) if (not main_init.is_initialized() and 'init' not in sys.argv and 'info' not in sys.argv): if hasattr(args, 'name') and hasattr(args, 'prefix'): import conda.config as config from conda.cli import common if common.get_prefix(args) == config.root_dir: sys.exit("""\ Error: This installation of conda is not initialized. Use 'conda create -n envname' to create a conda environment and 'source activate envname' to activate it. # Note that pip installing conda is not the recommended way for setting up your # system. The recommended way for setting up a conda system is by installing # Miniconda, see: http://repo.continuum.io/miniconda/index.html""") args_func(args, p)
def execute_search(args, parser): import re from conda.resolve import Resolve if args.reverse_dependency: if not args.regex: parser.error("--reverse-dependency requires at least one package name") if args.spec: parser.error("--reverse-dependency does not work with --spec") pat = None ms = None if args.regex: if args.spec: ms = ' '.join(args.regex.split('=')) else: regex = args.regex if args.full_name: regex = r'^%s$' % regex try: pat = re.compile(regex, re.I) except re.error as e: common.error_and_exit( "'%s' is not a valid regex pattern (exception: %s)" % (regex, e), json=args.json, error_type="ValueError") prefix = common.get_prefix(args) import conda.config import conda.install linked = conda.install.linked(prefix) extracted = set() for pkgs_dir in conda.config.pkgs_dirs: extracted.update(conda.install.extracted(pkgs_dir)) # XXX: Make this work with more than one platform platform = args.platform or '' if platform and platform != config.subdir: args.unknown = False common.ensure_override_channels_requires_channel(args, dashc=False, 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, unknown=args.unknown, prefix=prefix, json=args.json, platform=args.platform, offline=args.offline) else: index = common.get_index_trap(channel_urls=channel_urls, prepend=not args.override_channels, platform=args.platform, use_cache=args.use_index_cache, prefix=prefix, unknown=args.unknown, json=args.json, offline=args.offline) r = Resolve(index) if args.canonical: json = [] else: json = {} names = [] for name in sorted(r.groups): if '@' in name: continue if args.reverse_dependency: ms_name = ms for pkg in r.groups[name]: for dep in r.ms_depends(pkg): if pat.search(dep.name): names.append((name, Package(pkg, r.index[pkg]))) else: if pat and pat.search(name) is None: continue if ms and name != ms.name: continue if ms: ms_name = ms else: ms_name = name pkgs = sorted(r.get_pkgs(ms_name)) names.append((name, pkgs)) if args.reverse_dependency: new_names = [] old = None for name, pkg in sorted(names, key=lambda x:(x[0], x[1].name, x[1])): if name == old: new_names[-1][1].append(pkg) else: new_names.append((name, [pkg])) old = name names = new_names for name, pkgs in names: if args.reverse_dependency: disp_name = pkgs[0].name else: disp_name = name if args.names_only and not args.outdated: print(name) continue if not args.canonical: json[name] = [] if args.outdated: vers_inst = [dist.rsplit('-', 2)[1] for dist in linked if dist.rsplit('-', 2)[0] == name] if not vers_inst: continue assert len(vers_inst) == 1, name if not pkgs: continue latest = pkgs[-1] if latest.version == vers_inst[0]: continue if args.names_only: print(name) continue for pkg in pkgs: dist = pkg.fn[:-8] if args.canonical: if not args.json: print(dist) else: json.append(dist) continue if platform and platform != config.subdir: inst = ' ' elif dist in linked: inst = '*' elif dist in extracted: inst = '.' else: inst = ' ' if not args.json: print('%-25s %s %-15s %15s %-15s %s' % ( disp_name, inst, pkg.version, pkg.build, config.canonical_channel_name(pkg.channel), common.disp_features(r.features(pkg.fn)), )) disp_name = '' else: data = {} data.update(pkg.info) data.update({ 'fn': pkg.fn, 'installed': inst == '*', 'extracted': inst in '*.', 'version': pkg.version, 'build': pkg.build, 'build_number': pkg.build_number, 'channel': config.canonical_channel_name(pkg.channel), 'full_channel': pkg.channel, 'features': list(r.features(pkg.fn)), 'license': pkg.info.get('license'), 'size': pkg.info.get('size'), 'depends': pkg.info.get('depends'), 'type': pkg.info.get('type') }) if data['type'] == 'app': data['icon'] = make_icon_url(pkg.info) json[name].append(data) if args.json: common.stdout_json(json)