conda.xsh 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. $CONDA_EXE = "/croot/conda_1689269889729/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/conda"
  2. # Copyright (C) 2012 Anaconda, Inc
  3. # SPDX-License-Identifier: BSD-3-Clause
  4. # Much of this forked from https://github.com/gforsyth/xonda
  5. # Copyright (c) 2016, Gil Forsyth, All rights reserved.
  6. # Original code licensed under BSD-3-Clause.
  7. from xonsh.lazyasd import lazyobject
  8. if 'CONDA_EXE' not in ${...}:
  9. ![python -m conda init --dev out> conda-dev-init.sh]
  10. source-bash conda-dev-init.sh
  11. import os
  12. os.remove("conda-dev-init.sh")
  13. _REACTIVATE_COMMANDS = ('install', 'update', 'upgrade', 'remove', 'uninstall')
  14. @lazyobject
  15. def Env():
  16. from collections import namedtuple
  17. return namedtuple('Env', ['name', 'path', 'bin_dir', 'envs_dir'])
  18. def _parse_args(args=None):
  19. from argparse import ArgumentParser
  20. p = ArgumentParser(add_help=False)
  21. p.add_argument('command', nargs='?')
  22. p.add_argument('-h', '--help', dest='help', action='store_true', default=False)
  23. p.add_argument('-v', '--version', dest='version', action='store_true', default=False)
  24. ns, _ = p.parse_known_args(args)
  25. if ns.command == 'activate':
  26. p.add_argument('env_name_or_prefix', default='base')
  27. elif ns.command in _REACTIVATE_COMMANDS:
  28. p.add_argument('-n', '--name')
  29. p.add_argument('-p', '--prefix')
  30. parsed_args, _ = p.parse_known_args(args)
  31. return parsed_args
  32. def _raise_pipeline_error(pipeline):
  33. stdout = pipeline.out
  34. stderr = pipeline.err
  35. if pipeline.returncode != 0:
  36. message = ("exited with %s\nstdout: %s\nstderr: %s\n"
  37. "" % (pipeline.returncode, stdout, stderr))
  38. raise RuntimeError(message)
  39. return stdout.strip()
  40. def _conda_activate_handler(env_name_or_prefix):
  41. import os
  42. __xonsh__.execer.exec($($CONDA_EXE shell.xonsh activate @(env_name_or_prefix)),
  43. glbs=__xonsh__.ctx,
  44. filename="$(conda shell.xonsh activate " + env_name_or_prefix + ")")
  45. if $CONDA_DEFAULT_ENV != os.path.split(env_name_or_prefix)[1]:
  46. import sys as _sys
  47. print("WARNING: conda environment not activated properly. "
  48. "This is likely because you have a conda init inside of your "
  49. "~/.bashrc (unix) or *.bat activation file (windows). This is "
  50. "causing conda to activate twice in xonsh. Please remove the conda "
  51. "init block from your other shell.", file=_sys.stderr)
  52. def _conda_deactivate_handler():
  53. __xonsh__.execer.exec($($CONDA_EXE shell.xonsh deactivate),
  54. glbs=__xonsh__.ctx,
  55. filename="$(conda shell.xonsh deactivate)")
  56. def _conda_passthrough_handler(args):
  57. pipeline = ![$CONDA_EXE @(args)]
  58. _raise_pipeline_error(pipeline)
  59. def _conda_reactivate_handler(args, name_or_prefix_given):
  60. pipeline = ![$CONDA_EXE @(args)]
  61. _raise_pipeline_error(pipeline)
  62. if not name_or_prefix_given:
  63. __xonsh__.execer.exec($($CONDA_EXE shell.xonsh reactivate),
  64. glbs=__xonsh__.ctx,
  65. filename="$(conda shell.xonsh reactivate)")
  66. def _conda_main(args=None):
  67. parsed_args = _parse_args(args)
  68. if parsed_args.command == 'activate':
  69. _conda_activate_handler(parsed_args.env_name_or_prefix)
  70. elif parsed_args.command == 'deactivate':
  71. _conda_deactivate_handler()
  72. elif parsed_args.command in _REACTIVATE_COMMANDS:
  73. name_or_prefix_given = bool(parsed_args.name or parsed_args.prefix)
  74. _conda_reactivate_handler(args, name_or_prefix_given)
  75. else:
  76. _conda_passthrough_handler(args)
  77. if 'CONDA_SHLVL' not in ${...}:
  78. $CONDA_SHLVL = '0'
  79. import os as _os
  80. import sys as _sys
  81. _sys.path.insert(0, _os.path.join(_os.path.dirname(_os.path.dirname($CONDA_EXE)), "condabin"))
  82. del _os, _sys
  83. aliases['conda'] = _conda_main
  84. def _list_dirs(path):
  85. """Generator that lists the directories in a given path."""
  86. import os
  87. for entry in os.scandir(path):
  88. if not entry.name.startswith('.') and entry.is_dir():
  89. yield entry.name
  90. def _get_envs_unfiltered():
  91. """Grab a list of all conda env dirs from conda, allowing all warnings."""
  92. import os
  93. import importlib
  94. try:
  95. # breaking changes introduced in Anaconda 4.4.7
  96. # try to import newer library structure first
  97. context = importlib.import_module('conda.base.context')
  98. config = context.context
  99. except ModuleNotFoundError:
  100. config = importlib.import_module('conda.config')
  101. # create the list of environments
  102. env_list = []
  103. for envs_dir in config.envs_dirs:
  104. # skip non-existing environments directories
  105. if not os.path.exists(envs_dir):
  106. continue
  107. # for each environment in the environments directory
  108. for env_name in _list_dirs(envs_dir):
  109. # check for duplicates names
  110. if env_name in [env.name for env in env_list]:
  111. raise ValueError('Multiple environments with the same name '
  112. "in the system is not supported by conda's xonsh tools.")
  113. # add the environment to the list
  114. env_list.append(Env(name=env_name,
  115. path=os.path.join(envs_dir, env_name),
  116. bin_dir=os.path.join(envs_dir, env_name, 'bin'),
  117. envs_dir=envs_dir,
  118. ))
  119. return env_list
  120. def _get_envs():
  121. """Grab a list of all conda env dirs from conda, ignoring all warnings."""
  122. import warnings
  123. with warnings.catch_warnings():
  124. warnings.simplefilter("ignore")
  125. return _get_envs_unfiltered()
  126. def _conda_completer(prefix, line, start, end, ctx):
  127. """Completion for conda."""
  128. args = line.split(' ')
  129. possible = set()
  130. if len(args) == 0 or args[0] not in ['xonda', 'conda']:
  131. return None
  132. curix = args.index(prefix)
  133. if curix == 1:
  134. possible = {'activate', 'deactivate', 'install', 'remove', 'info',
  135. 'help', 'list', 'search', 'update', 'upgrade', 'uninstall',
  136. 'config', 'init', 'clean', 'package', 'bundle', 'env',
  137. 'select', 'create', '-h', '--help', '-V', '--version'}
  138. elif curix == 2:
  139. if args[1] in ['activate', 'select']:
  140. possible = set([env.name for env in _get_envs()])
  141. elif args[1] == 'create':
  142. possible = {'-p', '-n'}
  143. elif args[1] == 'env':
  144. possible = {'attach', 'create', 'export', 'list', 'remove',
  145. 'upload', 'update'}
  146. elif curix == 3:
  147. if args[2] == 'export':
  148. possible = {'-n', '--name'}
  149. elif args[2] == 'create':
  150. possible = {'-h', '--help', '-f', '--file', '-n', '--name', '-p',
  151. '--prefix', '-q', '--quiet', '--force', '--json',
  152. '--debug', '-v', '--verbose'}
  153. elif curix == 4:
  154. if args[2] == 'export' and args[3] in ['-n','--name']:
  155. possible = set([env.name for env in _get_envs()])
  156. return {i for i in possible if i.startswith(prefix)}
  157. # add _xonda_completer to list of completers
  158. __xonsh__.completers['conda'] = _conda_completer
  159. # bump to top of list
  160. __xonsh__.completers.move_to_end('conda', last=False)