logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

__init__.py (22364B)


  1. """
  2. Virtual environment (venv) package for Python. Based on PEP 405.
  3. Copyright (C) 2011-2014 Vinay Sajip.
  4. Licensed to the PSF under a contributor agreement.
  5. """
  6. import logging
  7. import os
  8. import shutil
  9. import subprocess
  10. import sys
  11. import sysconfig
  12. import types
  13. CORE_VENV_DEPS = ('pip', 'setuptools')
  14. logger = logging.getLogger(__name__)
  15. class EnvBuilder:
  16. """
  17. This class exists to allow virtual environment creation to be
  18. customized. The constructor parameters determine the builder's
  19. behaviour when called upon to create a virtual environment.
  20. By default, the builder makes the system (global) site-packages dir
  21. *un*available to the created environment.
  22. If invoked using the Python -m option, the default is to use copying
  23. on Windows platforms but symlinks elsewhere. If instantiated some
  24. other way, the default is to *not* use symlinks.
  25. :param system_site_packages: If True, the system (global) site-packages
  26. dir is available to created environments.
  27. :param clear: If True, delete the contents of the environment directory if
  28. it already exists, before environment creation.
  29. :param symlinks: If True, attempt to symlink rather than copy files into
  30. virtual environment.
  31. :param upgrade: If True, upgrade an existing virtual environment.
  32. :param with_pip: If True, ensure pip is installed in the virtual
  33. environment
  34. :param prompt: Alternative terminal prefix for the environment.
  35. :param upgrade_deps: Update the base venv modules to the latest on PyPI
  36. """
  37. def __init__(self, system_site_packages=False, clear=False,
  38. symlinks=False, upgrade=False, with_pip=False, prompt=None,
  39. upgrade_deps=False):
  40. self.system_site_packages = system_site_packages
  41. self.clear = clear
  42. self.symlinks = symlinks
  43. self.upgrade = upgrade
  44. self.with_pip = with_pip
  45. if prompt == '.': # see bpo-38901
  46. prompt = os.path.basename(os.getcwd())
  47. self.prompt = prompt
  48. self.upgrade_deps = upgrade_deps
  49. def create(self, env_dir):
  50. """
  51. Create a virtual environment in a directory.
  52. :param env_dir: The target directory to create an environment in.
  53. """
  54. env_dir = os.path.abspath(env_dir)
  55. context = self.ensure_directories(env_dir)
  56. # See issue 24875. We need system_site_packages to be False
  57. # until after pip is installed.
  58. true_system_site_packages = self.system_site_packages
  59. self.system_site_packages = False
  60. self.create_configuration(context)
  61. self.setup_python(context)
  62. if self.with_pip:
  63. self._setup_pip(context)
  64. if not self.upgrade:
  65. self.setup_scripts(context)
  66. self.post_setup(context)
  67. if true_system_site_packages:
  68. # We had set it to False before, now
  69. # restore it and rewrite the configuration
  70. self.system_site_packages = True
  71. self.create_configuration(context)
  72. if self.upgrade_deps:
  73. self.upgrade_dependencies(context)
  74. def clear_directory(self, path):
  75. for fn in os.listdir(path):
  76. fn = os.path.join(path, fn)
  77. if os.path.islink(fn) or os.path.isfile(fn):
  78. os.remove(fn)
  79. elif os.path.isdir(fn):
  80. shutil.rmtree(fn)
  81. def ensure_directories(self, env_dir):
  82. """
  83. Create the directories for the environment.
  84. Returns a context object which holds paths in the environment,
  85. for use by subsequent logic.
  86. """
  87. def create_if_needed(d):
  88. if not os.path.exists(d):
  89. os.makedirs(d)
  90. elif os.path.islink(d) or os.path.isfile(d):
  91. raise ValueError('Unable to create directory %r' % d)
  92. if os.path.exists(env_dir) and self.clear:
  93. self.clear_directory(env_dir)
  94. context = types.SimpleNamespace()
  95. context.env_dir = env_dir
  96. context.env_name = os.path.split(env_dir)[1]
  97. prompt = self.prompt if self.prompt is not None else context.env_name
  98. context.prompt = '(%s) ' % prompt
  99. create_if_needed(env_dir)
  100. executable = sys._base_executable
  101. dirname, exename = os.path.split(os.path.abspath(executable))
  102. context.executable = executable
  103. context.python_dir = dirname
  104. context.python_exe = exename
  105. if sys.platform == 'win32':
  106. binname = 'Scripts'
  107. incpath = 'Include'
  108. libpath = os.path.join(env_dir, 'Lib', 'site-packages')
  109. else:
  110. binname = 'bin'
  111. incpath = 'include'
  112. libpath = os.path.join(env_dir, 'lib',
  113. 'python%d.%d' % sys.version_info[:2],
  114. 'site-packages')
  115. context.inc_path = path = os.path.join(env_dir, incpath)
  116. create_if_needed(path)
  117. create_if_needed(libpath)
  118. # Issue 21197: create lib64 as a symlink to lib on 64-bit non-OS X POSIX
  119. if ((sys.maxsize > 2**32) and (os.name == 'posix') and
  120. (sys.platform != 'darwin')):
  121. link_path = os.path.join(env_dir, 'lib64')
  122. if not os.path.exists(link_path): # Issue #21643
  123. os.symlink('lib', link_path)
  124. context.bin_path = binpath = os.path.join(env_dir, binname)
  125. context.bin_name = binname
  126. context.env_exe = os.path.join(binpath, exename)
  127. create_if_needed(binpath)
  128. return context
  129. def create_configuration(self, context):
  130. """
  131. Create a configuration file indicating where the environment's Python
  132. was copied from, and whether the system site-packages should be made
  133. available in the environment.
  134. :param context: The information for the environment creation request
  135. being processed.
  136. """
  137. context.cfg_path = path = os.path.join(context.env_dir, 'pyvenv.cfg')
  138. with open(path, 'w', encoding='utf-8') as f:
  139. f.write('home = %s\n' % context.python_dir)
  140. if self.system_site_packages:
  141. incl = 'true'
  142. else:
  143. incl = 'false'
  144. f.write('include-system-site-packages = %s\n' % incl)
  145. f.write('version = %d.%d.%d\n' % sys.version_info[:3])
  146. if self.prompt is not None:
  147. f.write(f'prompt = {self.prompt!r}\n')
  148. if os.name != 'nt':
  149. def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
  150. """
  151. Try symlinking a file, and if that fails, fall back to copying.
  152. """
  153. force_copy = not self.symlinks
  154. if not force_copy:
  155. try:
  156. if not os.path.islink(dst): # can't link to itself!
  157. if relative_symlinks_ok:
  158. assert os.path.dirname(src) == os.path.dirname(dst)
  159. os.symlink(os.path.basename(src), dst)
  160. else:
  161. os.symlink(src, dst)
  162. except Exception: # may need to use a more specific exception
  163. logger.warning('Unable to symlink %r to %r', src, dst)
  164. force_copy = True
  165. if force_copy:
  166. shutil.copyfile(src, dst)
  167. else:
  168. def symlink_or_copy(self, src, dst, relative_symlinks_ok=False):
  169. """
  170. Try symlinking a file, and if that fails, fall back to copying.
  171. """
  172. bad_src = os.path.lexists(src) and not os.path.exists(src)
  173. if self.symlinks and not bad_src and not os.path.islink(dst):
  174. try:
  175. if relative_symlinks_ok:
  176. assert os.path.dirname(src) == os.path.dirname(dst)
  177. os.symlink(os.path.basename(src), dst)
  178. else:
  179. os.symlink(src, dst)
  180. return
  181. except Exception: # may need to use a more specific exception
  182. logger.warning('Unable to symlink %r to %r', src, dst)
  183. # On Windows, we rewrite symlinks to our base python.exe into
  184. # copies of venvlauncher.exe
  185. basename, ext = os.path.splitext(os.path.basename(src))
  186. srcfn = os.path.join(os.path.dirname(__file__),
  187. "scripts",
  188. "nt",
  189. basename + ext)
  190. # Builds or venv's from builds need to remap source file
  191. # locations, as we do not put them into Lib/venv/scripts
  192. if sysconfig.is_python_build(True) or not os.path.isfile(srcfn):
  193. if basename.endswith('_d'):
  194. ext = '_d' + ext
  195. basename = basename[:-2]
  196. if basename == 'python':
  197. basename = 'venvlauncher'
  198. elif basename == 'pythonw':
  199. basename = 'venvwlauncher'
  200. src = os.path.join(os.path.dirname(src), basename + ext)
  201. else:
  202. src = srcfn
  203. if not os.path.exists(src):
  204. if not bad_src:
  205. logger.warning('Unable to copy %r', src)
  206. return
  207. shutil.copyfile(src, dst)
  208. def setup_python(self, context):
  209. """
  210. Set up a Python executable in the environment.
  211. :param context: The information for the environment creation request
  212. being processed.
  213. """
  214. binpath = context.bin_path
  215. path = context.env_exe
  216. copier = self.symlink_or_copy
  217. dirname = context.python_dir
  218. if os.name != 'nt':
  219. copier(context.executable, path)
  220. if not os.path.islink(path):
  221. os.chmod(path, 0o755)
  222. for suffix in ('python', 'python3', f'python3.{sys.version_info[1]}'):
  223. path = os.path.join(binpath, suffix)
  224. if not os.path.exists(path):
  225. # Issue 18807: make copies if
  226. # symlinks are not wanted
  227. copier(context.env_exe, path, relative_symlinks_ok=True)
  228. if not os.path.islink(path):
  229. os.chmod(path, 0o755)
  230. else:
  231. if self.symlinks:
  232. # For symlinking, we need a complete copy of the root directory
  233. # If symlinks fail, you'll get unnecessary copies of files, but
  234. # we assume that if you've opted into symlinks on Windows then
  235. # you know what you're doing.
  236. suffixes = [
  237. f for f in os.listdir(dirname) if
  238. os.path.normcase(os.path.splitext(f)[1]) in ('.exe', '.dll')
  239. ]
  240. if sysconfig.is_python_build(True):
  241. suffixes = [
  242. f for f in suffixes if
  243. os.path.normcase(f).startswith(('python', 'vcruntime'))
  244. ]
  245. else:
  246. suffixes = ['python.exe', 'python_d.exe', 'pythonw.exe',
  247. 'pythonw_d.exe']
  248. for suffix in suffixes:
  249. src = os.path.join(dirname, suffix)
  250. if os.path.lexists(src):
  251. copier(src, os.path.join(binpath, suffix))
  252. if sysconfig.is_python_build(True):
  253. # copy init.tcl
  254. for root, dirs, files in os.walk(context.python_dir):
  255. if 'init.tcl' in files:
  256. tcldir = os.path.basename(root)
  257. tcldir = os.path.join(context.env_dir, 'Lib', tcldir)
  258. if not os.path.exists(tcldir):
  259. os.makedirs(tcldir)
  260. src = os.path.join(root, 'init.tcl')
  261. dst = os.path.join(tcldir, 'init.tcl')
  262. shutil.copyfile(src, dst)
  263. break
  264. def _setup_pip(self, context):
  265. """Installs or upgrades pip in a virtual environment"""
  266. # We run ensurepip in isolated mode to avoid side effects from
  267. # environment vars, the current directory and anything else
  268. # intended for the global Python environment
  269. cmd = [context.env_exe, '-Im', 'ensurepip', '--upgrade',
  270. '--default-pip']
  271. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  272. def setup_scripts(self, context):
  273. """
  274. Set up scripts into the created environment from a directory.
  275. This method installs the default scripts into the environment
  276. being created. You can prevent the default installation by overriding
  277. this method if you really need to, or if you need to specify
  278. a different location for the scripts to install. By default, the
  279. 'scripts' directory in the venv package is used as the source of
  280. scripts to install.
  281. """
  282. path = os.path.abspath(os.path.dirname(__file__))
  283. path = os.path.join(path, 'scripts')
  284. self.install_scripts(context, path)
  285. def post_setup(self, context):
  286. """
  287. Hook for post-setup modification of the venv. Subclasses may install
  288. additional packages or scripts here, add activation shell scripts, etc.
  289. :param context: The information for the environment creation request
  290. being processed.
  291. """
  292. pass
  293. def replace_variables(self, text, context):
  294. """
  295. Replace variable placeholders in script text with context-specific
  296. variables.
  297. Return the text passed in , but with variables replaced.
  298. :param text: The text in which to replace placeholder variables.
  299. :param context: The information for the environment creation request
  300. being processed.
  301. """
  302. text = text.replace('__VENV_DIR__', context.env_dir)
  303. text = text.replace('__VENV_NAME__', context.env_name)
  304. text = text.replace('__VENV_PROMPT__', context.prompt)
  305. text = text.replace('__VENV_BIN_NAME__', context.bin_name)
  306. text = text.replace('__VENV_PYTHON__', context.env_exe)
  307. return text
  308. def install_scripts(self, context, path):
  309. """
  310. Install scripts into the created environment from a directory.
  311. :param context: The information for the environment creation request
  312. being processed.
  313. :param path: Absolute pathname of a directory containing script.
  314. Scripts in the 'common' subdirectory of this directory,
  315. and those in the directory named for the platform
  316. being run on, are installed in the created environment.
  317. Placeholder variables are replaced with environment-
  318. specific values.
  319. """
  320. binpath = context.bin_path
  321. plen = len(path)
  322. for root, dirs, files in os.walk(path):
  323. if root == path: # at top-level, remove irrelevant dirs
  324. for d in dirs[:]:
  325. if d not in ('common', os.name):
  326. dirs.remove(d)
  327. continue # ignore files in top level
  328. for f in files:
  329. if (os.name == 'nt' and f.startswith('python')
  330. and f.endswith(('.exe', '.pdb'))):
  331. continue
  332. srcfile = os.path.join(root, f)
  333. suffix = root[plen:].split(os.sep)[2:]
  334. if not suffix:
  335. dstdir = binpath
  336. else:
  337. dstdir = os.path.join(binpath, *suffix)
  338. if not os.path.exists(dstdir):
  339. os.makedirs(dstdir)
  340. dstfile = os.path.join(dstdir, f)
  341. with open(srcfile, 'rb') as f:
  342. data = f.read()
  343. if not srcfile.endswith(('.exe', '.pdb')):
  344. try:
  345. data = data.decode('utf-8')
  346. data = self.replace_variables(data, context)
  347. data = data.encode('utf-8')
  348. except UnicodeError as e:
  349. data = None
  350. logger.warning('unable to copy script %r, '
  351. 'may be binary: %s', srcfile, e)
  352. if data is not None:
  353. with open(dstfile, 'wb') as f:
  354. f.write(data)
  355. shutil.copymode(srcfile, dstfile)
  356. def upgrade_dependencies(self, context):
  357. logger.debug(
  358. f'Upgrading {CORE_VENV_DEPS} packages in {context.bin_path}'
  359. )
  360. if sys.platform == 'win32':
  361. python_exe = os.path.join(context.bin_path, 'python.exe')
  362. else:
  363. python_exe = os.path.join(context.bin_path, 'python')
  364. cmd = [python_exe, '-m', 'pip', 'install', '--upgrade']
  365. cmd.extend(CORE_VENV_DEPS)
  366. subprocess.check_call(cmd)
  367. def create(env_dir, system_site_packages=False, clear=False,
  368. symlinks=False, with_pip=False, prompt=None, upgrade_deps=False):
  369. """Create a virtual environment in a directory."""
  370. builder = EnvBuilder(system_site_packages=system_site_packages,
  371. clear=clear, symlinks=symlinks, with_pip=with_pip,
  372. prompt=prompt, upgrade_deps=upgrade_deps)
  373. builder.create(env_dir)
  374. def main(args=None):
  375. compatible = True
  376. if sys.version_info < (3, 3):
  377. compatible = False
  378. elif not hasattr(sys, 'base_prefix'):
  379. compatible = False
  380. if not compatible:
  381. raise ValueError('This script is only for use with Python >= 3.3')
  382. else:
  383. import argparse
  384. parser = argparse.ArgumentParser(prog=__name__,
  385. description='Creates virtual Python '
  386. 'environments in one or '
  387. 'more target '
  388. 'directories.',
  389. epilog='Once an environment has been '
  390. 'created, you may wish to '
  391. 'activate it, e.g. by '
  392. 'sourcing an activate script '
  393. 'in its bin directory.')
  394. parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
  395. help='A directory to create the environment in.')
  396. parser.add_argument('--system-site-packages', default=False,
  397. action='store_true', dest='system_site',
  398. help='Give the virtual environment access to the '
  399. 'system site-packages dir.')
  400. if os.name == 'nt':
  401. use_symlinks = False
  402. else:
  403. use_symlinks = True
  404. group = parser.add_mutually_exclusive_group()
  405. group.add_argument('--symlinks', default=use_symlinks,
  406. action='store_true', dest='symlinks',
  407. help='Try to use symlinks rather than copies, '
  408. 'when symlinks are not the default for '
  409. 'the platform.')
  410. group.add_argument('--copies', default=not use_symlinks,
  411. action='store_false', dest='symlinks',
  412. help='Try to use copies rather than symlinks, '
  413. 'even when symlinks are the default for '
  414. 'the platform.')
  415. parser.add_argument('--clear', default=False, action='store_true',
  416. dest='clear', help='Delete the contents of the '
  417. 'environment directory if it '
  418. 'already exists, before '
  419. 'environment creation.')
  420. parser.add_argument('--upgrade', default=False, action='store_true',
  421. dest='upgrade', help='Upgrade the environment '
  422. 'directory to use this version '
  423. 'of Python, assuming Python '
  424. 'has been upgraded in-place.')
  425. parser.add_argument('--without-pip', dest='with_pip',
  426. default=True, action='store_false',
  427. help='Skips installing or upgrading pip in the '
  428. 'virtual environment (pip is bootstrapped '
  429. 'by default)')
  430. parser.add_argument('--prompt',
  431. help='Provides an alternative prompt prefix for '
  432. 'this environment.')
  433. parser.add_argument('--upgrade-deps', default=False, action='store_true',
  434. dest='upgrade_deps',
  435. help='Upgrade core dependencies: {} to the latest '
  436. 'version in PyPI'.format(
  437. ' '.join(CORE_VENV_DEPS)))
  438. options = parser.parse_args(args)
  439. if options.upgrade and options.clear:
  440. raise ValueError('you cannot supply --upgrade and --clear together.')
  441. builder = EnvBuilder(system_site_packages=options.system_site,
  442. clear=options.clear,
  443. symlinks=options.symlinks,
  444. upgrade=options.upgrade,
  445. with_pip=options.with_pip,
  446. prompt=options.prompt,
  447. upgrade_deps=options.upgrade_deps)
  448. for d in options.dirs:
  449. builder.create(d)
  450. if __name__ == '__main__':
  451. rc = 1
  452. try:
  453. main()
  454. rc = 0
  455. except Exception as e:
  456. print('Error: %s' % e, file=sys.stderr)
  457. sys.exit(rc)