Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

easy_install.py 83KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290
  1. """
  2. Easy Install
  3. ------------
  4. A tool for doing automatic download/extract/build of distutils-based Python
  5. packages. For detailed documentation, see the accompanying EasyInstall.txt
  6. file, or visit the `EasyInstall home page`__.
  7. __ https://setuptools.readthedocs.io/en/latest/deprecated/easy_install.html
  8. """
  9. from glob import glob
  10. from distutils.util import get_platform
  11. from distutils.util import convert_path, subst_vars
  12. from distutils.errors import (
  13. DistutilsArgError, DistutilsOptionError,
  14. DistutilsError, DistutilsPlatformError,
  15. )
  16. from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
  17. from distutils import log, dir_util
  18. from distutils.command.build_scripts import first_line_re
  19. from distutils.spawn import find_executable
  20. import sys
  21. import os
  22. import zipimport
  23. import shutil
  24. import tempfile
  25. import zipfile
  26. import re
  27. import stat
  28. import random
  29. import textwrap
  30. import warnings
  31. import site
  32. import struct
  33. import contextlib
  34. import subprocess
  35. import shlex
  36. import io
  37. import configparser
  38. from sysconfig import get_config_vars, get_path
  39. from setuptools import SetuptoolsDeprecationWarning
  40. from setuptools import Command
  41. from setuptools.sandbox import run_setup
  42. from setuptools.command import setopt
  43. from setuptools.archive_util import unpack_archive
  44. from setuptools.package_index import (
  45. PackageIndex, parse_requirement_arg, URL_SCHEME,
  46. )
  47. from setuptools.command import bdist_egg, egg_info
  48. from setuptools.wheel import Wheel
  49. from pkg_resources import (
  50. yield_lines, normalize_path, resource_string, ensure_directory,
  51. get_distribution, find_distributions, Environment, Requirement,
  52. Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound,
  53. VersionConflict, DEVELOP_DIST,
  54. )
  55. import pkg_resources
  56. # Turn on PEP440Warnings
  57. warnings.filterwarnings("default", category=pkg_resources.PEP440Warning)
  58. __all__ = [
  59. 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
  60. 'get_exe_prefixes',
  61. ]
  62. def is_64bit():
  63. return struct.calcsize("P") == 8
  64. def samefile(p1, p2):
  65. """
  66. Determine if two paths reference the same file.
  67. Augments os.path.samefile to work on Windows and
  68. suppresses errors if the path doesn't exist.
  69. """
  70. both_exist = os.path.exists(p1) and os.path.exists(p2)
  71. use_samefile = hasattr(os.path, 'samefile') and both_exist
  72. if use_samefile:
  73. return os.path.samefile(p1, p2)
  74. norm_p1 = os.path.normpath(os.path.normcase(p1))
  75. norm_p2 = os.path.normpath(os.path.normcase(p2))
  76. return norm_p1 == norm_p2
  77. def _to_bytes(s):
  78. return s.encode('utf8')
  79. def isascii(s):
  80. try:
  81. s.encode('ascii')
  82. return True
  83. except UnicodeError:
  84. return False
  85. def _one_liner(text):
  86. return textwrap.dedent(text).strip().replace('\n', '; ')
  87. class easy_install(Command):
  88. """Manage a download/build/install process"""
  89. description = "Find/get/install Python packages"
  90. command_consumes_arguments = True
  91. user_options = [
  92. ('prefix=', None, "installation prefix"),
  93. ("zip-ok", "z", "install package as a zipfile"),
  94. ("multi-version", "m", "make apps have to require() a version"),
  95. ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
  96. ("install-dir=", "d", "install package to DIR"),
  97. ("script-dir=", "s", "install scripts to DIR"),
  98. ("exclude-scripts", "x", "Don't install scripts"),
  99. ("always-copy", "a", "Copy all needed packages to install dir"),
  100. ("index-url=", "i", "base URL of Python Package Index"),
  101. ("find-links=", "f", "additional URL(s) to search for packages"),
  102. ("build-directory=", "b",
  103. "download/extract/build in DIR; keep the results"),
  104. ('optimize=', 'O',
  105. "also compile with optimization: -O1 for \"python -O\", "
  106. "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
  107. ('record=', None,
  108. "filename in which to record list of installed files"),
  109. ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
  110. ('site-dirs=', 'S', "list of directories where .pth files work"),
  111. ('editable', 'e', "Install specified packages in editable form"),
  112. ('no-deps', 'N', "don't install dependencies"),
  113. ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
  114. ('local-snapshots-ok', 'l',
  115. "allow building eggs from local checkouts"),
  116. ('version', None, "print version information and exit"),
  117. ('no-find-links', None,
  118. "Don't load find-links defined in packages being installed"),
  119. ('user', None, "install in user site-package '%s'" % site.USER_SITE)
  120. ]
  121. boolean_options = [
  122. 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
  123. 'editable',
  124. 'no-deps', 'local-snapshots-ok', 'version',
  125. 'user'
  126. ]
  127. negative_opt = {'always-unzip': 'zip-ok'}
  128. create_index = PackageIndex
  129. def initialize_options(self):
  130. # the --user option seems to be an opt-in one,
  131. # so the default should be False.
  132. self.user = 0
  133. self.zip_ok = self.local_snapshots_ok = None
  134. self.install_dir = self.script_dir = self.exclude_scripts = None
  135. self.index_url = None
  136. self.find_links = None
  137. self.build_directory = None
  138. self.args = None
  139. self.optimize = self.record = None
  140. self.upgrade = self.always_copy = self.multi_version = None
  141. self.editable = self.no_deps = self.allow_hosts = None
  142. self.root = self.prefix = self.no_report = None
  143. self.version = None
  144. self.install_purelib = None # for pure module distributions
  145. self.install_platlib = None # non-pure (dists w/ extensions)
  146. self.install_headers = None # for C/C++ headers
  147. self.install_lib = None # set to either purelib or platlib
  148. self.install_scripts = None
  149. self.install_data = None
  150. self.install_base = None
  151. self.install_platbase = None
  152. if site.ENABLE_USER_SITE:
  153. self.install_userbase = site.USER_BASE
  154. self.install_usersite = site.USER_SITE
  155. else:
  156. self.install_userbase = None
  157. self.install_usersite = None
  158. self.no_find_links = None
  159. # Options not specifiable via command line
  160. self.package_index = None
  161. self.pth_file = self.always_copy_from = None
  162. self.site_dirs = None
  163. self.installed_projects = {}
  164. # Always read easy_install options, even if we are subclassed, or have
  165. # an independent instance created. This ensures that defaults will
  166. # always come from the standard configuration file(s)' "easy_install"
  167. # section, even if this is a "develop" or "install" command, or some
  168. # other embedding.
  169. self._dry_run = None
  170. self.verbose = self.distribution.verbose
  171. self.distribution._set_command_options(
  172. self, self.distribution.get_option_dict('easy_install')
  173. )
  174. def delete_blockers(self, blockers):
  175. extant_blockers = (
  176. filename for filename in blockers
  177. if os.path.exists(filename) or os.path.islink(filename)
  178. )
  179. list(map(self._delete_path, extant_blockers))
  180. def _delete_path(self, path):
  181. log.info("Deleting %s", path)
  182. if self.dry_run:
  183. return
  184. is_tree = os.path.isdir(path) and not os.path.islink(path)
  185. remover = rmtree if is_tree else os.unlink
  186. remover(path)
  187. @staticmethod
  188. def _render_version():
  189. """
  190. Render the Setuptools version and installation details, then exit.
  191. """
  192. ver = '{}.{}'.format(*sys.version_info)
  193. dist = get_distribution('setuptools')
  194. tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})'
  195. print(tmpl.format(**locals()))
  196. raise SystemExit()
  197. def finalize_options(self): # noqa: C901 # is too complex (25) # FIXME
  198. self.version and self._render_version()
  199. py_version = sys.version.split()[0]
  200. prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
  201. self.config_vars = {
  202. 'dist_name': self.distribution.get_name(),
  203. 'dist_version': self.distribution.get_version(),
  204. 'dist_fullname': self.distribution.get_fullname(),
  205. 'py_version': py_version,
  206. 'py_version_short': py_version[0:3],
  207. 'py_version_nodot': py_version[0] + py_version[2],
  208. 'sys_prefix': prefix,
  209. 'prefix': prefix,
  210. 'sys_exec_prefix': exec_prefix,
  211. 'exec_prefix': exec_prefix,
  212. # Only python 3.2+ has abiflags
  213. 'abiflags': getattr(sys, 'abiflags', ''),
  214. }
  215. if site.ENABLE_USER_SITE:
  216. self.config_vars['userbase'] = self.install_userbase
  217. self.config_vars['usersite'] = self.install_usersite
  218. elif self.user:
  219. log.warn("WARNING: The user site-packages directory is disabled.")
  220. self._fix_install_dir_for_user_site()
  221. self.expand_basedirs()
  222. self.expand_dirs()
  223. self._expand(
  224. 'install_dir', 'script_dir', 'build_directory',
  225. 'site_dirs',
  226. )
  227. # If a non-default installation directory was specified, default the
  228. # script directory to match it.
  229. if self.script_dir is None:
  230. self.script_dir = self.install_dir
  231. if self.no_find_links is None:
  232. self.no_find_links = False
  233. # Let install_dir get set by install_lib command, which in turn
  234. # gets its info from the install command, and takes into account
  235. # --prefix and --home and all that other crud.
  236. self.set_undefined_options(
  237. 'install_lib', ('install_dir', 'install_dir')
  238. )
  239. # Likewise, set default script_dir from 'install_scripts.install_dir'
  240. self.set_undefined_options(
  241. 'install_scripts', ('install_dir', 'script_dir')
  242. )
  243. if self.user and self.install_purelib:
  244. self.install_dir = self.install_purelib
  245. self.script_dir = self.install_scripts
  246. # default --record from the install command
  247. self.set_undefined_options('install', ('record', 'record'))
  248. # Should this be moved to the if statement below? It's not used
  249. # elsewhere
  250. normpath = map(normalize_path, sys.path)
  251. self.all_site_dirs = get_site_dirs()
  252. if self.site_dirs is not None:
  253. site_dirs = [
  254. os.path.expanduser(s.strip()) for s in
  255. self.site_dirs.split(',')
  256. ]
  257. for d in site_dirs:
  258. if not os.path.isdir(d):
  259. log.warn("%s (in --site-dirs) does not exist", d)
  260. elif normalize_path(d) not in normpath:
  261. raise DistutilsOptionError(
  262. d + " (in --site-dirs) is not on sys.path"
  263. )
  264. else:
  265. self.all_site_dirs.append(normalize_path(d))
  266. if not self.editable:
  267. self.check_site_dir()
  268. self.index_url = self.index_url or "https://pypi.org/simple/"
  269. self.shadow_path = self.all_site_dirs[:]
  270. for path_item in self.install_dir, normalize_path(self.script_dir):
  271. if path_item not in self.shadow_path:
  272. self.shadow_path.insert(0, path_item)
  273. if self.allow_hosts is not None:
  274. hosts = [s.strip() for s in self.allow_hosts.split(',')]
  275. else:
  276. hosts = ['*']
  277. if self.package_index is None:
  278. self.package_index = self.create_index(
  279. self.index_url, search_path=self.shadow_path, hosts=hosts,
  280. )
  281. self.local_index = Environment(self.shadow_path + sys.path)
  282. if self.find_links is not None:
  283. if isinstance(self.find_links, str):
  284. self.find_links = self.find_links.split()
  285. else:
  286. self.find_links = []
  287. if self.local_snapshots_ok:
  288. self.package_index.scan_egg_links(self.shadow_path + sys.path)
  289. if not self.no_find_links:
  290. self.package_index.add_find_links(self.find_links)
  291. self.set_undefined_options('install_lib', ('optimize', 'optimize'))
  292. if not isinstance(self.optimize, int):
  293. try:
  294. self.optimize = int(self.optimize)
  295. if not (0 <= self.optimize <= 2):
  296. raise ValueError
  297. except ValueError as e:
  298. raise DistutilsOptionError(
  299. "--optimize must be 0, 1, or 2"
  300. ) from e
  301. if self.editable and not self.build_directory:
  302. raise DistutilsArgError(
  303. "Must specify a build directory (-b) when using --editable"
  304. )
  305. if not self.args:
  306. raise DistutilsArgError(
  307. "No urls, filenames, or requirements specified (see --help)")
  308. self.outputs = []
  309. def _fix_install_dir_for_user_site(self):
  310. """
  311. Fix the install_dir if "--user" was used.
  312. """
  313. if not self.user or not site.ENABLE_USER_SITE:
  314. return
  315. self.create_home_path()
  316. if self.install_userbase is None:
  317. msg = "User base directory is not specified"
  318. raise DistutilsPlatformError(msg)
  319. self.install_base = self.install_platbase = self.install_userbase
  320. scheme_name = os.name.replace('posix', 'unix') + '_user'
  321. self.select_scheme(scheme_name)
  322. def _expand_attrs(self, attrs):
  323. for attr in attrs:
  324. val = getattr(self, attr)
  325. if val is not None:
  326. if os.name == 'posix' or os.name == 'nt':
  327. val = os.path.expanduser(val)
  328. val = subst_vars(val, self.config_vars)
  329. setattr(self, attr, val)
  330. def expand_basedirs(self):
  331. """Calls `os.path.expanduser` on install_base, install_platbase and
  332. root."""
  333. self._expand_attrs(['install_base', 'install_platbase', 'root'])
  334. def expand_dirs(self):
  335. """Calls `os.path.expanduser` on install dirs."""
  336. dirs = [
  337. 'install_purelib',
  338. 'install_platlib',
  339. 'install_lib',
  340. 'install_headers',
  341. 'install_scripts',
  342. 'install_data',
  343. ]
  344. self._expand_attrs(dirs)
  345. def run(self, show_deprecation=True):
  346. if show_deprecation:
  347. self.announce(
  348. "WARNING: The easy_install command is deprecated "
  349. "and will be removed in a future version.",
  350. log.WARN,
  351. )
  352. if self.verbose != self.distribution.verbose:
  353. log.set_verbosity(self.verbose)
  354. try:
  355. for spec in self.args:
  356. self.easy_install(spec, not self.no_deps)
  357. if self.record:
  358. outputs = self.outputs
  359. if self.root: # strip any package prefix
  360. root_len = len(self.root)
  361. for counter in range(len(outputs)):
  362. outputs[counter] = outputs[counter][root_len:]
  363. from distutils import file_util
  364. self.execute(
  365. file_util.write_file, (self.record, outputs),
  366. "writing list of installed files to '%s'" %
  367. self.record
  368. )
  369. self.warn_deprecated_options()
  370. finally:
  371. log.set_verbosity(self.distribution.verbose)
  372. def pseudo_tempname(self):
  373. """Return a pseudo-tempname base in the install directory.
  374. This code is intentionally naive; if a malicious party can write to
  375. the target directory you're already in deep doodoo.
  376. """
  377. try:
  378. pid = os.getpid()
  379. except Exception:
  380. pid = random.randint(0, sys.maxsize)
  381. return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
  382. def warn_deprecated_options(self):
  383. pass
  384. def check_site_dir(self): # noqa: C901 # is too complex (12) # FIXME
  385. """Verify that self.install_dir is .pth-capable dir, if needed"""
  386. instdir = normalize_path(self.install_dir)
  387. pth_file = os.path.join(instdir, 'easy-install.pth')
  388. if not os.path.exists(instdir):
  389. try:
  390. os.makedirs(instdir)
  391. except (OSError, IOError):
  392. self.cant_write_to_target()
  393. # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
  394. is_site_dir = instdir in self.all_site_dirs
  395. if not is_site_dir and not self.multi_version:
  396. # No? Then directly test whether it does .pth file processing
  397. is_site_dir = self.check_pth_processing()
  398. else:
  399. # make sure we can write to target dir
  400. testfile = self.pseudo_tempname() + '.write-test'
  401. test_exists = os.path.exists(testfile)
  402. try:
  403. if test_exists:
  404. os.unlink(testfile)
  405. open(testfile, 'w').close()
  406. os.unlink(testfile)
  407. except (OSError, IOError):
  408. self.cant_write_to_target()
  409. if not is_site_dir and not self.multi_version:
  410. # Can't install non-multi to non-site dir with easy_install
  411. pythonpath = os.environ.get('PYTHONPATH', '')
  412. log.warn(self.__no_default_msg, self.install_dir, pythonpath)
  413. if is_site_dir:
  414. if self.pth_file is None:
  415. self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
  416. else:
  417. self.pth_file = None
  418. if self.multi_version and not os.path.exists(pth_file):
  419. self.pth_file = None # don't create a .pth file
  420. self.install_dir = instdir
  421. __cant_write_msg = textwrap.dedent("""
  422. can't create or remove files in install directory
  423. The following error occurred while trying to add or remove files in the
  424. installation directory:
  425. %s
  426. The installation directory you specified (via --install-dir, --prefix, or
  427. the distutils default setting) was:
  428. %s
  429. """).lstrip() # noqa
  430. __not_exists_id = textwrap.dedent("""
  431. This directory does not currently exist. Please create it and try again, or
  432. choose a different installation directory (using the -d or --install-dir
  433. option).
  434. """).lstrip() # noqa
  435. __access_msg = textwrap.dedent("""
  436. Perhaps your account does not have write access to this directory? If the
  437. installation directory is a system-owned directory, you may need to sign in
  438. as the administrator or "root" account. If you do not have administrative
  439. access to this machine, you may wish to choose a different installation
  440. directory, preferably one that is listed in your PYTHONPATH environment
  441. variable.
  442. For information on other options, you may wish to consult the
  443. documentation at:
  444. https://setuptools.readthedocs.io/en/latest/deprecated/easy_install.html
  445. Please make the appropriate changes for your system and try again.
  446. """).lstrip() # noqa
  447. def cant_write_to_target(self):
  448. msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,)
  449. if not os.path.exists(self.install_dir):
  450. msg += '\n' + self.__not_exists_id
  451. else:
  452. msg += '\n' + self.__access_msg
  453. raise DistutilsError(msg)
  454. def check_pth_processing(self):
  455. """Empirically verify whether .pth files are supported in inst. dir"""
  456. instdir = self.install_dir
  457. log.info("Checking .pth file support in %s", instdir)
  458. pth_file = self.pseudo_tempname() + ".pth"
  459. ok_file = pth_file + '.ok'
  460. ok_exists = os.path.exists(ok_file)
  461. tmpl = _one_liner("""
  462. import os
  463. f = open({ok_file!r}, 'w')
  464. f.write('OK')
  465. f.close()
  466. """) + '\n'
  467. try:
  468. if ok_exists:
  469. os.unlink(ok_file)
  470. dirname = os.path.dirname(ok_file)
  471. os.makedirs(dirname, exist_ok=True)
  472. f = open(pth_file, 'w')
  473. except (OSError, IOError):
  474. self.cant_write_to_target()
  475. else:
  476. try:
  477. f.write(tmpl.format(**locals()))
  478. f.close()
  479. f = None
  480. executable = sys.executable
  481. if os.name == 'nt':
  482. dirname, basename = os.path.split(executable)
  483. alt = os.path.join(dirname, 'pythonw.exe')
  484. use_alt = (
  485. basename.lower() == 'python.exe' and
  486. os.path.exists(alt)
  487. )
  488. if use_alt:
  489. # use pythonw.exe to avoid opening a console window
  490. executable = alt
  491. from distutils.spawn import spawn
  492. spawn([executable, '-E', '-c', 'pass'], 0)
  493. if os.path.exists(ok_file):
  494. log.info(
  495. "TEST PASSED: %s appears to support .pth files",
  496. instdir
  497. )
  498. return True
  499. finally:
  500. if f:
  501. f.close()
  502. if os.path.exists(ok_file):
  503. os.unlink(ok_file)
  504. if os.path.exists(pth_file):
  505. os.unlink(pth_file)
  506. if not self.multi_version:
  507. log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
  508. return False
  509. def install_egg_scripts(self, dist):
  510. """Write all the scripts for `dist`, unless scripts are excluded"""
  511. if not self.exclude_scripts and dist.metadata_isdir('scripts'):
  512. for script_name in dist.metadata_listdir('scripts'):
  513. if dist.metadata_isdir('scripts/' + script_name):
  514. # The "script" is a directory, likely a Python 3
  515. # __pycache__ directory, so skip it.
  516. continue
  517. self.install_script(
  518. dist, script_name,
  519. dist.get_metadata('scripts/' + script_name)
  520. )
  521. self.install_wrapper_scripts(dist)
  522. def add_output(self, path):
  523. if os.path.isdir(path):
  524. for base, dirs, files in os.walk(path):
  525. for filename in files:
  526. self.outputs.append(os.path.join(base, filename))
  527. else:
  528. self.outputs.append(path)
  529. def not_editable(self, spec):
  530. if self.editable:
  531. raise DistutilsArgError(
  532. "Invalid argument %r: you can't use filenames or URLs "
  533. "with --editable (except via the --find-links option)."
  534. % (spec,)
  535. )
  536. def check_editable(self, spec):
  537. if not self.editable:
  538. return
  539. if os.path.exists(os.path.join(self.build_directory, spec.key)):
  540. raise DistutilsArgError(
  541. "%r already exists in %s; can't do a checkout there" %
  542. (spec.key, self.build_directory)
  543. )
  544. @contextlib.contextmanager
  545. def _tmpdir(self):
  546. tmpdir = tempfile.mkdtemp(prefix=u"easy_install-")
  547. try:
  548. # cast to str as workaround for #709 and #710 and #712
  549. yield str(tmpdir)
  550. finally:
  551. os.path.exists(tmpdir) and rmtree(tmpdir)
  552. def easy_install(self, spec, deps=False):
  553. with self._tmpdir() as tmpdir:
  554. if not isinstance(spec, Requirement):
  555. if URL_SCHEME(spec):
  556. # It's a url, download it to tmpdir and process
  557. self.not_editable(spec)
  558. dl = self.package_index.download(spec, tmpdir)
  559. return self.install_item(None, dl, tmpdir, deps, True)
  560. elif os.path.exists(spec):
  561. # Existing file or directory, just process it directly
  562. self.not_editable(spec)
  563. return self.install_item(None, spec, tmpdir, deps, True)
  564. else:
  565. spec = parse_requirement_arg(spec)
  566. self.check_editable(spec)
  567. dist = self.package_index.fetch_distribution(
  568. spec, tmpdir, self.upgrade, self.editable,
  569. not self.always_copy, self.local_index
  570. )
  571. if dist is None:
  572. msg = "Could not find suitable distribution for %r" % spec
  573. if self.always_copy:
  574. msg += " (--always-copy skips system and development eggs)"
  575. raise DistutilsError(msg)
  576. elif dist.precedence == DEVELOP_DIST:
  577. # .egg-info dists don't need installing, just process deps
  578. self.process_distribution(spec, dist, deps, "Using")
  579. return dist
  580. else:
  581. return self.install_item(spec, dist.location, tmpdir, deps)
  582. def install_item(self, spec, download, tmpdir, deps, install_needed=False):
  583. # Installation is also needed if file in tmpdir or is not an egg
  584. install_needed = install_needed or self.always_copy
  585. install_needed = install_needed or os.path.dirname(download) == tmpdir
  586. install_needed = install_needed or not download.endswith('.egg')
  587. install_needed = install_needed or (
  588. self.always_copy_from is not None and
  589. os.path.dirname(normalize_path(download)) ==
  590. normalize_path(self.always_copy_from)
  591. )
  592. if spec and not install_needed:
  593. # at this point, we know it's a local .egg, we just don't know if
  594. # it's already installed.
  595. for dist in self.local_index[spec.project_name]:
  596. if dist.location == download:
  597. break
  598. else:
  599. install_needed = True # it's not in the local index
  600. log.info("Processing %s", os.path.basename(download))
  601. if install_needed:
  602. dists = self.install_eggs(spec, download, tmpdir)
  603. for dist in dists:
  604. self.process_distribution(spec, dist, deps)
  605. else:
  606. dists = [self.egg_distribution(download)]
  607. self.process_distribution(spec, dists[0], deps, "Using")
  608. if spec is not None:
  609. for dist in dists:
  610. if dist in spec:
  611. return dist
  612. def select_scheme(self, name):
  613. """Sets the install directories by applying the install schemes."""
  614. # it's the caller's problem if they supply a bad name!
  615. scheme = INSTALL_SCHEMES[name]
  616. for key in SCHEME_KEYS:
  617. attrname = 'install_' + key
  618. if getattr(self, attrname) is None:
  619. setattr(self, attrname, scheme[key])
  620. # FIXME: 'easy_install.process_distribution' is too complex (12)
  621. def process_distribution( # noqa: C901
  622. self, requirement, dist, deps=True, *info,
  623. ):
  624. self.update_pth(dist)
  625. self.package_index.add(dist)
  626. if dist in self.local_index[dist.key]:
  627. self.local_index.remove(dist)
  628. self.local_index.add(dist)
  629. self.install_egg_scripts(dist)
  630. self.installed_projects[dist.key] = dist
  631. log.info(self.installation_report(requirement, dist, *info))
  632. if (dist.has_metadata('dependency_links.txt') and
  633. not self.no_find_links):
  634. self.package_index.add_find_links(
  635. dist.get_metadata_lines('dependency_links.txt')
  636. )
  637. if not deps and not self.always_copy:
  638. return
  639. elif requirement is not None and dist.key != requirement.key:
  640. log.warn("Skipping dependencies for %s", dist)
  641. return # XXX this is not the distribution we were looking for
  642. elif requirement is None or dist not in requirement:
  643. # if we wound up with a different version, resolve what we've got
  644. distreq = dist.as_requirement()
  645. requirement = Requirement(str(distreq))
  646. log.info("Processing dependencies for %s", requirement)
  647. try:
  648. distros = WorkingSet([]).resolve(
  649. [requirement], self.local_index, self.easy_install
  650. )
  651. except DistributionNotFound as e:
  652. raise DistutilsError(str(e)) from e
  653. except VersionConflict as e:
  654. raise DistutilsError(e.report()) from e
  655. if self.always_copy or self.always_copy_from:
  656. # Force all the relevant distros to be copied or activated
  657. for dist in distros:
  658. if dist.key not in self.installed_projects:
  659. self.easy_install(dist.as_requirement())
  660. log.info("Finished processing dependencies for %s", requirement)
  661. def should_unzip(self, dist):
  662. if self.zip_ok is not None:
  663. return not self.zip_ok
  664. if dist.has_metadata('not-zip-safe'):
  665. return True
  666. if not dist.has_metadata('zip-safe'):
  667. return True
  668. return False
  669. def maybe_move(self, spec, dist_filename, setup_base):
  670. dst = os.path.join(self.build_directory, spec.key)
  671. if os.path.exists(dst):
  672. msg = (
  673. "%r already exists in %s; build directory %s will not be kept"
  674. )
  675. log.warn(msg, spec.key, self.build_directory, setup_base)
  676. return setup_base
  677. if os.path.isdir(dist_filename):
  678. setup_base = dist_filename
  679. else:
  680. if os.path.dirname(dist_filename) == setup_base:
  681. os.unlink(dist_filename) # get it out of the tmp dir
  682. contents = os.listdir(setup_base)
  683. if len(contents) == 1:
  684. dist_filename = os.path.join(setup_base, contents[0])
  685. if os.path.isdir(dist_filename):
  686. # if the only thing there is a directory, move it instead
  687. setup_base = dist_filename
  688. ensure_directory(dst)
  689. shutil.move(setup_base, dst)
  690. return dst
  691. def install_wrapper_scripts(self, dist):
  692. if self.exclude_scripts:
  693. return
  694. for args in ScriptWriter.best().get_args(dist):
  695. self.write_script(*args)
  696. def install_script(self, dist, script_name, script_text, dev_path=None):
  697. """Generate a legacy script wrapper and install it"""
  698. spec = str(dist.as_requirement())
  699. is_script = is_python_script(script_text, script_name)
  700. if is_script:
  701. body = self._load_template(dev_path) % locals()
  702. script_text = ScriptWriter.get_header(script_text) + body
  703. self.write_script(script_name, _to_bytes(script_text), 'b')
  704. @staticmethod
  705. def _load_template(dev_path):
  706. """
  707. There are a couple of template scripts in the package. This
  708. function loads one of them and prepares it for use.
  709. """
  710. # See https://github.com/pypa/setuptools/issues/134 for info
  711. # on script file naming and downstream issues with SVR4
  712. name = 'script.tmpl'
  713. if dev_path:
  714. name = name.replace('.tmpl', ' (dev).tmpl')
  715. raw_bytes = resource_string('setuptools', name)
  716. return raw_bytes.decode('utf-8')
  717. def write_script(self, script_name, contents, mode="t", blockers=()):
  718. """Write an executable file to the scripts directory"""
  719. self.delete_blockers( # clean up old .py/.pyw w/o a script
  720. [os.path.join(self.script_dir, x) for x in blockers]
  721. )
  722. log.info("Installing %s script to %s", script_name, self.script_dir)
  723. target = os.path.join(self.script_dir, script_name)
  724. self.add_output(target)
  725. if self.dry_run:
  726. return
  727. mask = current_umask()
  728. ensure_directory(target)
  729. if os.path.exists(target):
  730. os.unlink(target)
  731. with open(target, "w" + mode) as f:
  732. f.write(contents)
  733. chmod(target, 0o777 - mask)
  734. def install_eggs(self, spec, dist_filename, tmpdir):
  735. # .egg dirs or files are already built, so just return them
  736. installer_map = {
  737. '.egg': self.install_egg,
  738. '.exe': self.install_exe,
  739. '.whl': self.install_wheel,
  740. }
  741. try:
  742. install_dist = installer_map[
  743. dist_filename.lower()[-4:]
  744. ]
  745. except KeyError:
  746. pass
  747. else:
  748. return [install_dist(dist_filename, tmpdir)]
  749. # Anything else, try to extract and build
  750. setup_base = tmpdir
  751. if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
  752. unpack_archive(dist_filename, tmpdir, self.unpack_progress)
  753. elif os.path.isdir(dist_filename):
  754. setup_base = os.path.abspath(dist_filename)
  755. if (setup_base.startswith(tmpdir) # something we downloaded
  756. and self.build_directory and spec is not None):
  757. setup_base = self.maybe_move(spec, dist_filename, setup_base)
  758. # Find the setup.py file
  759. setup_script = os.path.join(setup_base, 'setup.py')
  760. if not os.path.exists(setup_script):
  761. setups = glob(os.path.join(setup_base, '*', 'setup.py'))
  762. if not setups:
  763. raise DistutilsError(
  764. "Couldn't find a setup script in %s" %
  765. os.path.abspath(dist_filename)
  766. )
  767. if len(setups) > 1:
  768. raise DistutilsError(
  769. "Multiple setup scripts in %s" %
  770. os.path.abspath(dist_filename)
  771. )
  772. setup_script = setups[0]
  773. # Now run it, and return the result
  774. if self.editable:
  775. log.info(self.report_editable(spec, setup_script))
  776. return []
  777. else:
  778. return self.build_and_install(setup_script, setup_base)
  779. def egg_distribution(self, egg_path):
  780. if os.path.isdir(egg_path):
  781. metadata = PathMetadata(egg_path, os.path.join(egg_path,
  782. 'EGG-INFO'))
  783. else:
  784. metadata = EggMetadata(zipimport.zipimporter(egg_path))
  785. return Distribution.from_filename(egg_path, metadata=metadata)
  786. # FIXME: 'easy_install.install_egg' is too complex (11)
  787. def install_egg(self, egg_path, tmpdir): # noqa: C901
  788. destination = os.path.join(
  789. self.install_dir,
  790. os.path.basename(egg_path),
  791. )
  792. destination = os.path.abspath(destination)
  793. if not self.dry_run:
  794. ensure_directory(destination)
  795. dist = self.egg_distribution(egg_path)
  796. if not samefile(egg_path, destination):
  797. if os.path.isdir(destination) and not os.path.islink(destination):
  798. dir_util.remove_tree(destination, dry_run=self.dry_run)
  799. elif os.path.exists(destination):
  800. self.execute(
  801. os.unlink,
  802. (destination,),
  803. "Removing " + destination,
  804. )
  805. try:
  806. new_dist_is_zipped = False
  807. if os.path.isdir(egg_path):
  808. if egg_path.startswith(tmpdir):
  809. f, m = shutil.move, "Moving"
  810. else:
  811. f, m = shutil.copytree, "Copying"
  812. elif self.should_unzip(dist):
  813. self.mkpath(destination)
  814. f, m = self.unpack_and_compile, "Extracting"
  815. else:
  816. new_dist_is_zipped = True
  817. if egg_path.startswith(tmpdir):
  818. f, m = shutil.move, "Moving"
  819. else:
  820. f, m = shutil.copy2, "Copying"
  821. self.execute(
  822. f,
  823. (egg_path, destination),
  824. (m + " %s to %s") % (
  825. os.path.basename(egg_path),
  826. os.path.dirname(destination)
  827. ),
  828. )
  829. update_dist_caches(
  830. destination,
  831. fix_zipimporter_caches=new_dist_is_zipped,
  832. )
  833. except Exception:
  834. update_dist_caches(destination, fix_zipimporter_caches=False)
  835. raise
  836. self.add_output(destination)
  837. return self.egg_distribution(destination)
  838. def install_exe(self, dist_filename, tmpdir):
  839. # See if it's valid, get data
  840. cfg = extract_wininst_cfg(dist_filename)
  841. if cfg is None:
  842. raise DistutilsError(
  843. "%s is not a valid distutils Windows .exe" % dist_filename
  844. )
  845. # Create a dummy distribution object until we build the real distro
  846. dist = Distribution(
  847. None,
  848. project_name=cfg.get('metadata', 'name'),
  849. version=cfg.get('metadata', 'version'), platform=get_platform(),
  850. )
  851. # Convert the .exe to an unpacked egg
  852. egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg')
  853. dist.location = egg_path
  854. egg_tmp = egg_path + '.tmp'
  855. _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
  856. pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
  857. ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
  858. dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX
  859. self.exe_to_egg(dist_filename, egg_tmp)
  860. # Write EGG-INFO/PKG-INFO
  861. if not os.path.exists(pkg_inf):
  862. f = open(pkg_inf, 'w')
  863. f.write('Metadata-Version: 1.0\n')
  864. for k, v in cfg.items('metadata'):
  865. if k != 'target_version':
  866. f.write('%s: %s\n' % (k.replace('_', '-').title(), v))
  867. f.close()
  868. script_dir = os.path.join(_egg_info, 'scripts')
  869. # delete entry-point scripts to avoid duping
  870. self.delete_blockers([
  871. os.path.join(script_dir, args[0])
  872. for args in ScriptWriter.get_args(dist)
  873. ])
  874. # Build .egg file from tmpdir
  875. bdist_egg.make_zipfile(
  876. egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run,
  877. )
  878. # install the .egg
  879. return self.install_egg(egg_path, tmpdir)
  880. # FIXME: 'easy_install.exe_to_egg' is too complex (12)
  881. def exe_to_egg(self, dist_filename, egg_tmp): # noqa: C901
  882. """Extract a bdist_wininst to the directories an egg would use"""
  883. # Check for .pth file and set up prefix translations
  884. prefixes = get_exe_prefixes(dist_filename)
  885. to_compile = []
  886. native_libs = []
  887. top_level = {}
  888. def process(src, dst):
  889. s = src.lower()
  890. for old, new in prefixes:
  891. if s.startswith(old):
  892. src = new + src[len(old):]
  893. parts = src.split('/')
  894. dst = os.path.join(egg_tmp, *parts)
  895. dl = dst.lower()
  896. if dl.endswith('.pyd') or dl.endswith('.dll'):
  897. parts[-1] = bdist_egg.strip_module(parts[-1])
  898. top_level[os.path.splitext(parts[0])[0]] = 1
  899. native_libs.append(src)
  900. elif dl.endswith('.py') and old != 'SCRIPTS/':
  901. top_level[os.path.splitext(parts[0])[0]] = 1
  902. to_compile.append(dst)
  903. return dst
  904. if not src.endswith('.pth'):
  905. log.warn("WARNING: can't process %s", src)
  906. return None
  907. # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
  908. unpack_archive(dist_filename, egg_tmp, process)
  909. stubs = []
  910. for res in native_libs:
  911. if res.lower().endswith('.pyd'): # create stubs for .pyd's
  912. parts = res.split('/')
  913. resource = parts[-1]
  914. parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'
  915. pyfile = os.path.join(egg_tmp, *parts)
  916. to_compile.append(pyfile)
  917. stubs.append(pyfile)
  918. bdist_egg.write_stub(resource, pyfile)
  919. self.byte_compile(to_compile) # compile .py's
  920. bdist_egg.write_safety_flag(
  921. os.path.join(egg_tmp, 'EGG-INFO'),
  922. bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
  923. for name in 'top_level', 'native_libs':
  924. if locals()[name]:
  925. txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')
  926. if not os.path.exists(txt):
  927. f = open(txt, 'w')
  928. f.write('\n'.join(locals()[name]) + '\n')
  929. f.close()
  930. def install_wheel(self, wheel_path, tmpdir):
  931. wheel = Wheel(wheel_path)
  932. assert wheel.is_compatible()
  933. destination = os.path.join(self.install_dir, wheel.egg_name())
  934. destination = os.path.abspath(destination)
  935. if not self.dry_run:
  936. ensure_directory(destination)
  937. if os.path.isdir(destination) and not os.path.islink(destination):
  938. dir_util.remove_tree(destination, dry_run=self.dry_run)
  939. elif os.path.exists(destination):
  940. self.execute(
  941. os.unlink,
  942. (destination,),
  943. "Removing " + destination,
  944. )
  945. try:
  946. self.execute(
  947. wheel.install_as_egg,
  948. (destination,),
  949. ("Installing %s to %s") % (
  950. os.path.basename(wheel_path),
  951. os.path.dirname(destination)
  952. ),
  953. )
  954. finally:
  955. update_dist_caches(destination, fix_zipimporter_caches=False)
  956. self.add_output(destination)
  957. return self.egg_distribution(destination)
  958. __mv_warning = textwrap.dedent("""
  959. Because this distribution was installed --multi-version, before you can
  960. import modules from this package in an application, you will need to
  961. 'import pkg_resources' and then use a 'require()' call similar to one of
  962. these examples, in order to select the desired version:
  963. pkg_resources.require("%(name)s") # latest installed version
  964. pkg_resources.require("%(name)s==%(version)s") # this exact version
  965. pkg_resources.require("%(name)s>=%(version)s") # this version or higher
  966. """).lstrip() # noqa
  967. __id_warning = textwrap.dedent("""
  968. Note also that the installation directory must be on sys.path at runtime for
  969. this to work. (e.g. by being the application's script directory, by being on
  970. PYTHONPATH, or by being added to sys.path by your code.)
  971. """) # noqa
  972. def installation_report(self, req, dist, what="Installed"):
  973. """Helpful installation message for display to package users"""
  974. msg = "\n%(what)s %(eggloc)s%(extras)s"
  975. if self.multi_version and not self.no_report:
  976. msg += '\n' + self.__mv_warning
  977. if self.install_dir not in map(normalize_path, sys.path):
  978. msg += '\n' + self.__id_warning
  979. eggloc = dist.location
  980. name = dist.project_name
  981. version = dist.version
  982. extras = '' # TODO: self.report_extras(req, dist)
  983. return msg % locals()
  984. __editable_msg = textwrap.dedent("""
  985. Extracted editable version of %(spec)s to %(dirname)s
  986. If it uses setuptools in its setup script, you can activate it in
  987. "development" mode by going to that directory and running::
  988. %(python)s setup.py develop
  989. See the setuptools documentation for the "develop" command for more info.
  990. """).lstrip() # noqa
  991. def report_editable(self, spec, setup_script):
  992. dirname = os.path.dirname(setup_script)
  993. python = sys.executable
  994. return '\n' + self.__editable_msg % locals()
  995. def run_setup(self, setup_script, setup_base, args):
  996. sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
  997. sys.modules.setdefault('distutils.command.egg_info', egg_info)
  998. args = list(args)
  999. if self.verbose > 2:
  1000. v = 'v' * (self.verbose - 1)
  1001. args.insert(0, '-' + v)
  1002. elif self.verbose < 2:
  1003. args.insert(0, '-q')
  1004. if self.dry_run:
  1005. args.insert(0, '-n')
  1006. log.info(
  1007. "Running %s %s", setup_script[len(setup_base) + 1:], ' '.join(args)
  1008. )
  1009. try:
  1010. run_setup(setup_script, args)
  1011. except SystemExit as v:
  1012. raise DistutilsError(
  1013. "Setup script exited with %s" % (v.args[0],)
  1014. ) from v
  1015. def build_and_install(self, setup_script, setup_base):
  1016. args = ['bdist_egg', '--dist-dir']
  1017. dist_dir = tempfile.mkdtemp(
  1018. prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
  1019. )
  1020. try:
  1021. self._set_fetcher_options(os.path.dirname(setup_script))
  1022. args.append(dist_dir)
  1023. self.run_setup(setup_script, setup_base, args)
  1024. all_eggs = Environment([dist_dir])
  1025. eggs = []
  1026. for key in all_eggs:
  1027. for dist in all_eggs[key]:
  1028. eggs.append(self.install_egg(dist.location, setup_base))
  1029. if not eggs and not self.dry_run:
  1030. log.warn("No eggs found in %s (setup script problem?)",
  1031. dist_dir)
  1032. return eggs
  1033. finally:
  1034. rmtree(dist_dir)
  1035. log.set_verbosity(self.verbose) # restore our log verbosity
  1036. def _set_fetcher_options(self, base):
  1037. """
  1038. When easy_install is about to run bdist_egg on a source dist, that
  1039. source dist might have 'setup_requires' directives, requiring
  1040. additional fetching. Ensure the fetcher options given to easy_install
  1041. are available to that command as well.
  1042. """
  1043. # find the fetch options from easy_install and write them out
  1044. # to the setup.cfg file.
  1045. ei_opts = self.distribution.get_option_dict('easy_install').copy()
  1046. fetch_directives = (
  1047. 'find_links', 'site_dirs', 'index_url', 'optimize', 'allow_hosts',
  1048. )
  1049. fetch_options = {}
  1050. for key, val in ei_opts.items():
  1051. if key not in fetch_directives:
  1052. continue
  1053. fetch_options[key] = val[1]
  1054. # create a settings dictionary suitable for `edit_config`
  1055. settings = dict(easy_install=fetch_options)
  1056. cfg_filename = os.path.join(base, 'setup.cfg')
  1057. setopt.edit_config(cfg_filename, settings)
  1058. def update_pth(self, dist): # noqa: C901 # is too complex (11) # FIXME
  1059. if self.pth_file is None:
  1060. return
  1061. for d in self.pth_file[dist.key]: # drop old entries
  1062. if not self.multi_version and d.location == dist.location:
  1063. continue
  1064. log.info("Removing %s from easy-install.pth file", d)
  1065. self.pth_file.remove(d)
  1066. if d.location in self.shadow_path:
  1067. self.shadow_path.remove(d.location)
  1068. if not self.multi_version:
  1069. if dist.location in self.pth_file.paths:
  1070. log.info(
  1071. "%s is already the active version in easy-install.pth",
  1072. dist,
  1073. )
  1074. else:
  1075. log.info("Adding %s to easy-install.pth file", dist)
  1076. self.pth_file.add(dist) # add new entry
  1077. if dist.location not in self.shadow_path:
  1078. self.shadow_path.append(dist.location)
  1079. if self.dry_run:
  1080. return
  1081. self.pth_file.save()
  1082. if dist.key != 'setuptools':
  1083. return
  1084. # Ensure that setuptools itself never becomes unavailable!
  1085. # XXX should this check for latest version?
  1086. filename = os.path.join(self.install_dir, 'setuptools.pth')
  1087. if os.path.islink(filename):
  1088. os.unlink(filename)
  1089. with open(filename, 'wt') as f:
  1090. f.write(self.pth_file.make_relative(dist.location) + '\n')
  1091. def unpack_progress(self, src, dst):
  1092. # Progress filter for unpacking
  1093. log.debug("Unpacking %s to %s", src, dst)
  1094. return dst # only unpack-and-compile skips files for dry run
  1095. def unpack_and_compile(self, egg_path, destination):
  1096. to_compile = []
  1097. to_chmod = []
  1098. def pf(src, dst):
  1099. if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
  1100. to_compile.append(dst)
  1101. elif dst.endswith('.dll') or dst.endswith('.so'):
  1102. to_chmod.append(dst)
  1103. self.unpack_progress(src, dst)
  1104. return not self.dry_run and dst or None
  1105. unpack_archive(egg_path, destination, pf)
  1106. self.byte_compile(to_compile)
  1107. if not self.dry_run:
  1108. for f in to_chmod:
  1109. mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
  1110. chmod(f, mode)
  1111. def byte_compile(self, to_compile):
  1112. if sys.dont_write_bytecode:
  1113. return
  1114. from distutils.util import byte_compile
  1115. try:
  1116. # try to make the byte compile messages quieter
  1117. log.set_verbosity(self.verbose - 1)
  1118. byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
  1119. if self.optimize:
  1120. byte_compile(
  1121. to_compile, optimize=self.optimize, force=1,
  1122. dry_run=self.dry_run,
  1123. )
  1124. finally:
  1125. log.set_verbosity(self.verbose) # restore original verbosity
  1126. __no_default_msg = textwrap.dedent("""
  1127. bad install directory or PYTHONPATH
  1128. You are attempting to install a package to a directory that is not
  1129. on PYTHONPATH and which Python does not read ".pth" files from. The
  1130. installation directory you specified (via --install-dir, --prefix, or
  1131. the distutils default setting) was:
  1132. %s
  1133. and your PYTHONPATH environment variable currently contains:
  1134. %r
  1135. Here are some of your options for correcting the problem:
  1136. * You can choose a different installation directory, i.e., one that is
  1137. on PYTHONPATH or supports .pth files
  1138. * You can add the installation directory to the PYTHONPATH environment
  1139. variable. (It must then also be on PYTHONPATH whenever you run
  1140. Python and want to use the package(s) you are installing.)
  1141. * You can set up the installation directory to support ".pth" files by
  1142. using one of the approaches described here:
  1143. https://setuptools.readthedocs.io/en/latest/deprecated/easy_install.html#custom-installation-locations
  1144. Please make the appropriate changes for your system and try again.
  1145. """).strip()
  1146. def create_home_path(self):
  1147. """Create directories under ~."""
  1148. if not self.user:
  1149. return
  1150. home = convert_path(os.path.expanduser("~"))
  1151. for name, path in self.config_vars.items():
  1152. if path.startswith(home) and not os.path.isdir(path):
  1153. self.debug_print("os.makedirs('%s', 0o700)" % path)
  1154. os.makedirs(path, 0o700)
  1155. INSTALL_SCHEMES = dict(
  1156. posix=dict(
  1157. install_dir='$base/lib/python$py_version_short/site-packages',
  1158. script_dir='$base/bin',
  1159. ),
  1160. )
  1161. DEFAULT_SCHEME = dict(
  1162. install_dir='$base/Lib/site-packages',
  1163. script_dir='$base/Scripts',
  1164. )
  1165. def _expand(self, *attrs):
  1166. config_vars = self.get_finalized_command('install').config_vars
  1167. if self.prefix:
  1168. # Set default install_dir/scripts from --prefix
  1169. config_vars = config_vars.copy()
  1170. config_vars['base'] = self.prefix
  1171. scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)
  1172. for attr, val in scheme.items():
  1173. if getattr(self, attr, None) is None:
  1174. setattr(self, attr, val)
  1175. from distutils.util import subst_vars
  1176. for attr in attrs:
  1177. val = getattr(self, attr)
  1178. if val is not None:
  1179. val = subst_vars(val, config_vars)
  1180. if os.name == 'posix':
  1181. val = os.path.expanduser(val)
  1182. setattr(self, attr, val)
  1183. def _pythonpath():
  1184. items = os.environ.get('PYTHONPATH', '').split(os.pathsep)
  1185. return filter(None, items)
  1186. def get_site_dirs():
  1187. """
  1188. Return a list of 'site' dirs
  1189. """
  1190. sitedirs = []
  1191. # start with PYTHONPATH
  1192. sitedirs.extend(_pythonpath())
  1193. prefixes = [sys.prefix]
  1194. if sys.exec_prefix != sys.prefix:
  1195. prefixes.append(sys.exec_prefix)
  1196. for prefix in prefixes:
  1197. if not prefix:
  1198. continue
  1199. if sys.platform in ('os2emx', 'riscos'):
  1200. sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
  1201. elif os.sep == '/':
  1202. sitedirs.extend([
  1203. os.path.join(
  1204. prefix,
  1205. "lib",
  1206. "python{}.{}".format(*sys.version_info),
  1207. "site-packages",
  1208. ),
  1209. os.path.join(prefix, "lib", "site-python"),
  1210. ])
  1211. else:
  1212. sitedirs.extend([
  1213. prefix,
  1214. os.path.join(prefix, "lib", "site-packages"),
  1215. ])
  1216. if sys.platform != 'darwin':
  1217. continue
  1218. # for framework builds *only* we add the standard Apple
  1219. # locations. Currently only per-user, but /Library and
  1220. # /Network/Library could be added too
  1221. if 'Python.framework' not in prefix:
  1222. continue
  1223. home = os.environ.get('HOME')
  1224. if not home:
  1225. continue
  1226. home_sp = os.path.join(
  1227. home,
  1228. 'Library',
  1229. 'Python',
  1230. '{}.{}'.format(*sys.version_info),
  1231. 'site-packages',
  1232. )
  1233. sitedirs.append(home_sp)
  1234. lib_paths = get_path('purelib'), get_path('platlib')
  1235. sitedirs.extend(s for s in lib_paths if s not in sitedirs)
  1236. if site.ENABLE_USER_SITE:
  1237. sitedirs.append(site.USER_SITE)
  1238. with contextlib.suppress(AttributeError):
  1239. sitedirs.extend(site.getsitepackages())
  1240. sitedirs = list(map(normalize_path, sitedirs))
  1241. return sitedirs
  1242. def expand_paths(inputs): # noqa: C901 # is too complex (11) # FIXME
  1243. """Yield sys.path directories that might contain "old-style" packages"""
  1244. seen = {}
  1245. for dirname in inputs:
  1246. dirname = normalize_path(dirname)
  1247. if dirname in seen:
  1248. continue
  1249. seen[dirname] = 1
  1250. if not os.path.isdir(dirname):
  1251. continue
  1252. files = os.listdir(dirname)
  1253. yield dirname, files
  1254. for name in files:
  1255. if not name.endswith('.pth'):
  1256. # We only care about the .pth files
  1257. continue
  1258. if name in ('easy-install.pth', 'setuptools.pth'):
  1259. # Ignore .pth files that we control
  1260. continue
  1261. # Read the .pth file
  1262. f = open(os.path.join(dirname, name))
  1263. lines = list(yield_lines(f))
  1264. f.close()
  1265. # Yield existing non-dupe, non-import directory lines from it
  1266. for line in lines:
  1267. if line.startswith("import"):
  1268. continue
  1269. line = normalize_path(line.rstrip())
  1270. if line in seen:
  1271. continue
  1272. seen[line] = 1
  1273. if not os.path.isdir(line):
  1274. continue
  1275. yield line, os.listdir(line)
  1276. def extract_wininst_cfg(dist_filename):
  1277. """Extract configuration data from a bdist_wininst .exe
  1278. Returns a configparser.RawConfigParser, or None
  1279. """
  1280. f = open(dist_filename, 'rb')
  1281. try:
  1282. endrec = zipfile._EndRecData(f)
  1283. if endrec is None:
  1284. return None
  1285. prepended = (endrec[9] - endrec[5]) - endrec[6]
  1286. if prepended < 12: # no wininst data here
  1287. return None
  1288. f.seek(prepended - 12)
  1289. tag, cfglen, bmlen = struct.unpack("<iii", f.read(12))
  1290. if tag not in (0x1234567A, 0x1234567B):
  1291. return None # not a valid tag
  1292. f.seek(prepended - (12 + cfglen))
  1293. init = {'version': '', 'target_version': ''}
  1294. cfg = configparser.RawConfigParser(init)
  1295. try:
  1296. part = f.read(cfglen)
  1297. # Read up to the first null byte.
  1298. config = part.split(b'\0', 1)[0]
  1299. # Now the config is in bytes, but for RawConfigParser, it should
  1300. # be text, so decode it.
  1301. config = config.decode(sys.getfilesystemencoding())
  1302. cfg.read_file(io.StringIO(config))
  1303. except configparser.Error:
  1304. return None
  1305. if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
  1306. return None
  1307. return cfg
  1308. finally:
  1309. f.close()
  1310. def get_exe_prefixes(exe_filename):
  1311. """Get exe->egg path translations for a given .exe file"""
  1312. prefixes = [
  1313. ('PURELIB/', ''),
  1314. ('PLATLIB/pywin32_system32', ''),
  1315. ('PLATLIB/', ''),
  1316. ('SCRIPTS/', 'EGG-INFO/scripts/'),
  1317. ('DATA/lib/site-packages', ''),
  1318. ]
  1319. z = zipfile.ZipFile(exe_filename)
  1320. try:
  1321. for info in z.infolist():
  1322. name = info.filename
  1323. parts = name.split('/')
  1324. if len(parts) == 3 and parts[2] == 'PKG-INFO':
  1325. if parts[1].endswith('.egg-info'):
  1326. prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))
  1327. break
  1328. if len(parts) != 2 or not name.endswith('.pth'):
  1329. continue
  1330. if name.endswith('-nspkg.pth'):
  1331. continue
  1332. if parts[0].upper() in ('PURELIB', 'PLATLIB'):
  1333. contents = z.read(name).decode()
  1334. for pth in yield_lines(contents):
  1335. pth = pth.strip().replace('\\', '/')
  1336. if not pth.startswith('import'):
  1337. prefixes.append((('%s/%s/' % (parts[0], pth)), ''))
  1338. finally:
  1339. z.close()
  1340. prefixes = [(x.lower(), y) for x, y in prefixes]
  1341. prefixes.sort()
  1342. prefixes.reverse()
  1343. return prefixes
  1344. class PthDistributions(Environment):
  1345. """A .pth file with Distribution paths in it"""
  1346. dirty = False
  1347. def __init__(self, filename, sitedirs=()):
  1348. self.filename = filename
  1349. self.sitedirs = list(map(normalize_path, sitedirs))
  1350. self.basedir = normalize_path(os.path.dirname(self.filename))
  1351. self._load()
  1352. Environment.__init__(self, [], None, None)
  1353. for path in yield_lines(self.paths):
  1354. list(map(self.add, find_distributions(path, True)))
  1355. def _load(self):
  1356. self.paths = []
  1357. saw_import = False
  1358. seen = dict.fromkeys(self.sitedirs)
  1359. if os.path.isfile(self.filename):
  1360. f = open(self.filename, 'rt')
  1361. for line in f:
  1362. if line.startswith('import'):
  1363. saw_import = True
  1364. continue
  1365. path = line.rstrip()
  1366. self.paths.append(path)
  1367. if not path.strip() or path.strip().startswith('#'):
  1368. continue
  1369. # skip non-existent paths, in case somebody deleted a package
  1370. # manually, and duplicate paths as well
  1371. path = self.paths[-1] = normalize_path(
  1372. os.path.join(self.basedir, path)
  1373. )
  1374. if not os.path.exists(path) or path in seen:
  1375. self.paths.pop() # skip it
  1376. self.dirty = True # we cleaned up, so we're dirty now :)
  1377. continue
  1378. seen[path] = 1
  1379. f.close()
  1380. if self.paths and not saw_import:
  1381. self.dirty = True # ensure anything we touch has import wrappers
  1382. while self.paths and not self.paths[-1].strip():
  1383. self.paths.pop()
  1384. def save(self):
  1385. """Write changed .pth file back to disk"""
  1386. if not self.dirty:
  1387. return
  1388. rel_paths = list(map(self.make_relative, self.paths))
  1389. if rel_paths:
  1390. log.debug("Saving %s", self.filename)
  1391. lines = self._wrap_lines(rel_paths)
  1392. data = '\n'.join(lines) + '\n'
  1393. if os.path.islink(self.filename):
  1394. os.unlink(self.filename)
  1395. with open(self.filename, 'wt') as f:
  1396. f.write(data)
  1397. elif os.path.exists(self.filename):
  1398. log.debug("Deleting empty %s", self.filename)
  1399. os.unlink(self.filename)
  1400. self.dirty = False
  1401. @staticmethod
  1402. def _wrap_lines(lines):
  1403. return lines
  1404. def add(self, dist):
  1405. """Add `dist` to the distribution map"""
  1406. new_path = (
  1407. dist.location not in self.paths and (
  1408. dist.location not in self.sitedirs or
  1409. # account for '.' being in PYTHONPATH
  1410. dist.location == os.getcwd()
  1411. )
  1412. )
  1413. if new_path:
  1414. self.paths.append(dist.location)
  1415. self.dirty = True
  1416. Environment.add(self, dist)
  1417. def remove(self, dist):
  1418. """Remove `dist` from the distribution map"""
  1419. while dist.location in self.paths:
  1420. self.paths.remove(dist.location)
  1421. self.dirty = True
  1422. Environment.remove(self, dist)
  1423. def make_relative(self, path):
  1424. npath, last = os.path.split(normalize_path(path))
  1425. baselen = len(self.basedir)
  1426. parts = [last]
  1427. sep = os.altsep == '/' and '/' or os.sep
  1428. while len(npath) >= baselen:
  1429. if npath == self.basedir:
  1430. parts.append(os.curdir)
  1431. parts.reverse()
  1432. return sep.join(parts)
  1433. npath, last = os.path.split(npath)
  1434. parts.append(last)
  1435. else:
  1436. return path
  1437. class RewritePthDistributions(PthDistributions):
  1438. @classmethod
  1439. def _wrap_lines(cls, lines):
  1440. yield cls.prelude
  1441. for line in lines:
  1442. yield line
  1443. yield cls.postlude
  1444. prelude = _one_liner("""
  1445. import sys
  1446. sys.__plen = len(sys.path)
  1447. """)
  1448. postlude = _one_liner("""
  1449. import sys
  1450. new = sys.path[sys.__plen:]
  1451. del sys.path[sys.__plen:]
  1452. p = getattr(sys, '__egginsert', 0)
  1453. sys.path[p:p] = new
  1454. sys.__egginsert = p + len(new)
  1455. """)
  1456. if os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite':
  1457. PthDistributions = RewritePthDistributions
  1458. def _first_line_re():
  1459. """
  1460. Return a regular expression based on first_line_re suitable for matching
  1461. strings.
  1462. """
  1463. if isinstance(first_line_re.pattern, str):
  1464. return first_line_re
  1465. # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
  1466. return re.compile(first_line_re.pattern.decode())
  1467. def auto_chmod(func, arg, exc):
  1468. if func in [os.unlink, os.remove] and os.name == 'nt':
  1469. chmod(arg, stat.S_IWRITE)
  1470. return func(arg)
  1471. et, ev, _ = sys.exc_info()
  1472. # TODO: This code doesn't make sense. What is it trying to do?
  1473. raise (ev[0], ev[1] + (" %s %s" % (func, arg)))
  1474. def update_dist_caches(dist_path, fix_zipimporter_caches):
  1475. """
  1476. Fix any globally cached `dist_path` related data
  1477. `dist_path` should be a path of a newly installed egg distribution (zipped
  1478. or unzipped).
  1479. sys.path_importer_cache contains finder objects that have been cached when
  1480. importing data from the original distribution. Any such finders need to be
  1481. cleared since the replacement distribution might be packaged differently,
  1482. e.g. a zipped egg distribution might get replaced with an unzipped egg
  1483. folder or vice versa. Having the old finders cached may then cause Python
  1484. to attempt loading modules from the replacement distribution using an
  1485. incorrect loader.
  1486. zipimport.zipimporter objects are Python loaders charged with importing
  1487. data packaged inside zip archives. If stale loaders referencing the
  1488. original distribution, are left behind, they can fail to load modules from
  1489. the replacement distribution. E.g. if an old zipimport.zipimporter instance
  1490. is used to load data from a new zipped egg archive, it may cause the
  1491. operation to attempt to locate the requested data in the wrong location -
  1492. one indicated by the original distribution's zip archive directory
  1493. information. Such an operation may then fail outright, e.g. report having
  1494. read a 'bad local file header', or even worse, it may fail silently &
  1495. return invalid data.
  1496. zipimport._zip_directory_cache contains cached zip archive directory
  1497. information for all existing zipimport.zipimporter instances and all such
  1498. instances connected to the same archive share the same cached directory
  1499. information.
  1500. If asked, and the underlying Python implementation allows it, we can fix
  1501. all existing zipimport.zipimporter instances instead of having to track
  1502. them down and remove them one by one, by updating their shared cached zip
  1503. archive directory information. This, of course, assumes that the
  1504. replacement distribution is packaged as a zipped egg.
  1505. If not asked to fix existing zipimport.zipimporter instances, we still do
  1506. our best to clear any remaining zipimport.zipimporter related cached data
  1507. that might somehow later get used when attempting to load data from the new
  1508. distribution and thus cause such load operations to fail. Note that when
  1509. tracking down such remaining stale data, we can not catch every conceivable
  1510. usage from here, and we clear only those that we know of and have found to
  1511. cause problems if left alive. Any remaining caches should be updated by
  1512. whomever is in charge of maintaining them, i.e. they should be ready to
  1513. handle us replacing their zip archives with new distributions at runtime.
  1514. """
  1515. # There are several other known sources of stale zipimport.zipimporter
  1516. # instances that we do not clear here, but might if ever given a reason to
  1517. # do so:
  1518. # * Global setuptools pkg_resources.working_set (a.k.a. 'master working
  1519. # set') may contain distributions which may in turn contain their
  1520. # zipimport.zipimporter loaders.
  1521. # * Several zipimport.zipimporter loaders held by local variables further
  1522. # up the function call stack when running the setuptools installation.
  1523. # * Already loaded modules may have their __loader__ attribute set to the
  1524. # exact loader instance used when importing them. Python 3.4 docs state
  1525. # that this information is intended mostly for introspection and so is
  1526. # not expected to cause us problems.
  1527. normalized_path = normalize_path(dist_path)
  1528. _uncache(normalized_path, sys.path_importer_cache)
  1529. if fix_zipimporter_caches:
  1530. _replace_zip_directory_cache_data(normalized_path)
  1531. else:
  1532. # Here, even though we do not want to fix existing and now stale
  1533. # zipimporter cache information, we still want to remove it. Related to
  1534. # Python's zip archive directory information cache, we clear each of
  1535. # its stale entries in two phases:
  1536. # 1. Clear the entry so attempting to access zip archive information
  1537. # via any existing stale zipimport.zipimporter instances fails.
  1538. # 2. Remove the entry from the cache so any newly constructed
  1539. # zipimport.zipimporter instances do not end up using old stale
  1540. # zip archive directory information.
  1541. # This whole stale data removal step does not seem strictly necessary,
  1542. # but has been left in because it was done before we started replacing
  1543. # the zip archive directory information cache content if possible, and
  1544. # there are no relevant unit tests that we can depend on to tell us if
  1545. # this is really needed.
  1546. _remove_and_clear_zip_directory_cache_data(normalized_path)
  1547. def _collect_zipimporter_cache_entries(normalized_path, cache):
  1548. """
  1549. Return zipimporter cache entry keys related to a given normalized path.
  1550. Alternative path spellings (e.g. those using different character case or
  1551. those using alternative path separators) related to the same path are
  1552. included. Any sub-path entries are included as well, i.e. those
  1553. corresponding to zip archives embedded in other zip archives.
  1554. """
  1555. result = []
  1556. prefix_len = len(normalized_path)
  1557. for p in cache:
  1558. np = normalize_path(p)
  1559. if (np.startswith(normalized_path) and
  1560. np[prefix_len:prefix_len + 1] in (os.sep, '')):
  1561. result.append(p)
  1562. return result
  1563. def _update_zipimporter_cache(normalized_path, cache, updater=None):
  1564. """
  1565. Update zipimporter cache data for a given normalized path.
  1566. Any sub-path entries are processed as well, i.e. those corresponding to zip
  1567. archives embedded in other zip archives.
  1568. Given updater is a callable taking a cache entry key and the original entry
  1569. (after already removing the entry from the cache), and expected to update
  1570. the entry and possibly return a new one to be inserted in its place.
  1571. Returning None indicates that the entry should not be replaced with a new
  1572. one. If no updater is given, the cache entries are simply removed without
  1573. any additional processing, the same as if the updater simply returned None.
  1574. """
  1575. for p in _collect_zipimporter_cache_entries(normalized_path, cache):
  1576. # N.B. pypy's custom zipimport._zip_directory_cache implementation does
  1577. # not support the complete dict interface:
  1578. # * Does not support item assignment, thus not allowing this function
  1579. # to be used only for removing existing cache entries.
  1580. # * Does not support the dict.pop() method, forcing us to use the
  1581. # get/del patterns instead. For more detailed information see the
  1582. # following links:
  1583. # https://github.com/pypa/setuptools/issues/202#issuecomment-202913420
  1584. # http://bit.ly/2h9itJX
  1585. old_entry = cache[p]
  1586. del cache[p]
  1587. new_entry = updater and updater(p, old_entry)
  1588. if new_entry is not None:
  1589. cache[p] = new_entry
  1590. def _uncache(normalized_path, cache):
  1591. _update_zipimporter_cache(normalized_path, cache)
  1592. def _remove_and_clear_zip_directory_cache_data(normalized_path):
  1593. def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):
  1594. old_entry.clear()
  1595. _update_zipimporter_cache(
  1596. normalized_path, zipimport._zip_directory_cache,
  1597. updater=clear_and_remove_cached_zip_archive_directory_data)
  1598. # PyPy Python implementation does not allow directly writing to the
  1599. # zipimport._zip_directory_cache and so prevents us from attempting to correct
  1600. # its content. The best we can do there is clear the problematic cache content
  1601. # and have PyPy repopulate it as needed. The downside is that if there are any
  1602. # stale zipimport.zipimporter instances laying around, attempting to use them
  1603. # will fail due to not having its zip archive directory information available
  1604. # instead of being automatically corrected to use the new correct zip archive
  1605. # directory information.
  1606. if '__pypy__' in sys.builtin_module_names:
  1607. _replace_zip_directory_cache_data = \
  1608. _remove_and_clear_zip_directory_cache_data
  1609. else:
  1610. def _replace_zip_directory_cache_data(normalized_path):
  1611. def replace_cached_zip_archive_directory_data(path, old_entry):
  1612. # N.B. In theory, we could load the zip directory information just
  1613. # once for all updated path spellings, and then copy it locally and
  1614. # update its contained path strings to contain the correct
  1615. # spelling, but that seems like a way too invasive move (this cache
  1616. # structure is not officially documented anywhere and could in
  1617. # theory change with new Python releases) for no significant
  1618. # benefit.
  1619. old_entry.clear()
  1620. zipimport.zipimporter(path)
  1621. old_entry.update(zipimport._zip_directory_cache[path])
  1622. return old_entry
  1623. _update_zipimporter_cache(
  1624. normalized_path, zipimport._zip_directory_cache,
  1625. updater=replace_cached_zip_archive_directory_data)
  1626. def is_python(text, filename='<string>'):
  1627. "Is this string a valid Python script?"
  1628. try:
  1629. compile(text, filename, 'exec')
  1630. except (SyntaxError, TypeError):
  1631. return False
  1632. else:
  1633. return True
  1634. def is_sh(executable):
  1635. """Determine if the specified executable is a .sh (contains a #! line)"""
  1636. try:
  1637. with io.open(executable, encoding='latin-1') as fp:
  1638. magic = fp.read(2)
  1639. except (OSError, IOError):
  1640. return executable
  1641. return magic == '#!'
  1642. def nt_quote_arg(arg):
  1643. """Quote a command line argument according to Windows parsing rules"""
  1644. return subprocess.list2cmdline([arg])
  1645. def is_python_script(script_text, filename):
  1646. """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
  1647. """
  1648. if filename.endswith('.py') or filename.endswith('.pyw'):
  1649. return True # extension says it's Python
  1650. if is_python(script_text, filename):
  1651. return True # it's syntactically valid Python
  1652. if script_text.startswith('#!'):
  1653. # It begins with a '#!' line, so check if 'python' is in it somewhere
  1654. return 'python' in script_text.splitlines()[0].lower()
  1655. return False # Not any Python I can recognize
  1656. try:
  1657. from os import chmod as _chmod
  1658. except ImportError:
  1659. # Jython compatibility
  1660. def _chmod(*args):
  1661. pass
  1662. def chmod(path, mode):
  1663. log.debug("changing mode of %s to %o", path, mode)
  1664. try:
  1665. _chmod(path, mode)
  1666. except os.error as e:
  1667. log.debug("chmod failed: %s", e)
  1668. class CommandSpec(list):
  1669. """
  1670. A command spec for a #! header, specified as a list of arguments akin to
  1671. those passed to Popen.
  1672. """
  1673. options = []
  1674. split_args = dict()
  1675. @classmethod
  1676. def best(cls):
  1677. """
  1678. Choose the best CommandSpec class based on environmental conditions.
  1679. """
  1680. return cls
  1681. @classmethod
  1682. def _sys_executable(cls):
  1683. _default = os.path.normpath(sys.executable)
  1684. return os.environ.get('__PYVENV_LAUNCHER__', _default)
  1685. @classmethod
  1686. def from_param(cls, param):
  1687. """
  1688. Construct a CommandSpec from a parameter to build_scripts, which may
  1689. be None.
  1690. """
  1691. if isinstance(param, cls):
  1692. return param
  1693. if isinstance(param, list):
  1694. return cls(param)
  1695. if param is None:
  1696. return cls.from_environment()
  1697. # otherwise, assume it's a string.
  1698. return cls.from_string(param)
  1699. @classmethod
  1700. def from_environment(cls):
  1701. return cls([cls._sys_executable()])
  1702. @classmethod
  1703. def from_string(cls, string):
  1704. """
  1705. Construct a command spec from a simple string representing a command
  1706. line parseable by shlex.split.
  1707. """
  1708. items = shlex.split(string, **cls.split_args)
  1709. return cls(items)
  1710. def install_options(self, script_text):
  1711. self.options = shlex.split(self._extract_options(script_text))
  1712. cmdline = subprocess.list2cmdline(self)
  1713. if not isascii(cmdline):
  1714. self.options[:0] = ['-x']
  1715. @staticmethod
  1716. def _extract_options(orig_script):
  1717. """
  1718. Extract any options from the first line of the script.
  1719. """
  1720. first = (orig_script + '\n').splitlines()[0]
  1721. match = _first_line_re().match(first)
  1722. options = match.group(1) or '' if match else ''
  1723. return options.strip()
  1724. def as_header(self):
  1725. return self._render(self + list(self.options))
  1726. @staticmethod
  1727. def _strip_quotes(item):
  1728. _QUOTES = '"\''
  1729. for q in _QUOTES:
  1730. if item.startswith(q) and item.endswith(q):
  1731. return item[1:-1]
  1732. return item
  1733. @staticmethod
  1734. def _render(items):
  1735. cmdline = subprocess.list2cmdline(
  1736. CommandSpec._strip_quotes(item.strip()) for item in items)
  1737. return '#!' + cmdline + '\n'
  1738. # For pbr compat; will be removed in a future version.
  1739. sys_executable = CommandSpec._sys_executable()
  1740. class WindowsCommandSpec(CommandSpec):
  1741. split_args = dict(posix=False)
  1742. class ScriptWriter:
  1743. """
  1744. Encapsulates behavior around writing entry point scripts for console and
  1745. gui apps.
  1746. """
  1747. template = textwrap.dedent(r"""
  1748. # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
  1749. import re
  1750. import sys
  1751. # for compatibility with easy_install; see #2198
  1752. __requires__ = %(spec)r
  1753. try:
  1754. from importlib.metadata import distribution
  1755. except ImportError:
  1756. try:
  1757. from importlib_metadata import distribution
  1758. except ImportError:
  1759. from pkg_resources import load_entry_point
  1760. def importlib_load_entry_point(spec, group, name):
  1761. dist_name, _, _ = spec.partition('==')
  1762. matches = (
  1763. entry_point
  1764. for entry_point in distribution(dist_name).entry_points
  1765. if entry_point.group == group and entry_point.name == name
  1766. )
  1767. return next(matches).load()
  1768. globals().setdefault('load_entry_point', importlib_load_entry_point)
  1769. if __name__ == '__main__':
  1770. sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
  1771. sys.exit(load_entry_point(%(spec)r, %(group)r, %(name)r)())
  1772. """).lstrip()
  1773. command_spec_class = CommandSpec
  1774. @classmethod
  1775. def get_script_args(cls, dist, executable=None, wininst=False):
  1776. # for backward compatibility
  1777. warnings.warn("Use get_args", EasyInstallDeprecationWarning)
  1778. writer = (WindowsScriptWriter if wininst else ScriptWriter).best()
  1779. header = cls.get_script_header("", executable, wininst)
  1780. return writer.get_args(dist, header)
  1781. @classmethod
  1782. def get_script_header(cls, script_text, executable=None, wininst=False):
  1783. # for backward compatibility
  1784. warnings.warn(
  1785. "Use get_header", EasyInstallDeprecationWarning, stacklevel=2)
  1786. if wininst:
  1787. executable = "python.exe"
  1788. return cls.get_header(script_text, executable)
  1789. @classmethod
  1790. def get_args(cls, dist, header=None):
  1791. """
  1792. Yield write_script() argument tuples for a distribution's
  1793. console_scripts and gui_scripts entry points.
  1794. """
  1795. if header is None:
  1796. header = cls.get_header()
  1797. spec = str(dist.as_requirement())
  1798. for type_ in 'console', 'gui':
  1799. group = type_ + '_scripts'
  1800. for name, ep in dist.get_entry_map(group).items():
  1801. cls._ensure_safe_name(name)
  1802. script_text = cls.template % locals()
  1803. args = cls._get_script_args(type_, name, header, script_text)
  1804. for res in args:
  1805. yield res
  1806. @staticmethod
  1807. def _ensure_safe_name(name):
  1808. """
  1809. Prevent paths in *_scripts entry point names.
  1810. """
  1811. has_path_sep = re.search(r'[\\/]', name)
  1812. if has_path_sep:
  1813. raise ValueError("Path separators not allowed in script names")
  1814. @classmethod
  1815. def get_writer(cls, force_windows):
  1816. # for backward compatibility
  1817. warnings.warn("Use best", EasyInstallDeprecationWarning)
  1818. return WindowsScriptWriter.best() if force_windows else cls.best()
  1819. @classmethod
  1820. def best(cls):
  1821. """
  1822. Select the best ScriptWriter for this environment.
  1823. """
  1824. if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
  1825. return WindowsScriptWriter.best()
  1826. else:
  1827. return cls
  1828. @classmethod
  1829. def _get_script_args(cls, type_, name, header, script_text):
  1830. # Simply write the stub with no extension.
  1831. yield (name, header + script_text)
  1832. @classmethod
  1833. def get_header(cls, script_text="", executable=None):
  1834. """Create a #! line, getting options (if any) from script_text"""
  1835. cmd = cls.command_spec_class.best().from_param(executable)
  1836. cmd.install_options(script_text)
  1837. return cmd.as_header()
  1838. class WindowsScriptWriter(ScriptWriter):
  1839. command_spec_class = WindowsCommandSpec
  1840. @classmethod
  1841. def get_writer(cls):
  1842. # for backward compatibility
  1843. warnings.warn("Use best", EasyInstallDeprecationWarning)
  1844. return cls.best()
  1845. @classmethod
  1846. def best(cls):
  1847. """
  1848. Select the best ScriptWriter suitable for Windows
  1849. """
  1850. writer_lookup = dict(
  1851. executable=WindowsExecutableLauncherWriter,
  1852. natural=cls,
  1853. )
  1854. # for compatibility, use the executable launcher by default
  1855. launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
  1856. return writer_lookup[launcher]
  1857. @classmethod
  1858. def _get_script_args(cls, type_, name, header, script_text):
  1859. "For Windows, add a .py extension"
  1860. ext = dict(console='.pya', gui='.pyw')[type_]
  1861. if ext not in os.environ['PATHEXT'].lower().split(';'):
  1862. msg = (
  1863. "{ext} not listed in PATHEXT; scripts will not be "
  1864. "recognized as executables."
  1865. ).format(**locals())
  1866. warnings.warn(msg, UserWarning)
  1867. old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
  1868. old.remove(ext)
  1869. header = cls._adjust_header(type_, header)
  1870. blockers = [name + x for x in old]
  1871. yield name + ext, header + script_text, 't', blockers
  1872. @classmethod
  1873. def _adjust_header(cls, type_, orig_header):
  1874. """
  1875. Make sure 'pythonw' is used for gui and 'python' is used for
  1876. console (regardless of what sys.executable is).
  1877. """
  1878. pattern = 'pythonw.exe'
  1879. repl = 'python.exe'
  1880. if type_ == 'gui':
  1881. pattern, repl = repl, pattern
  1882. pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
  1883. new_header = pattern_ob.sub(string=orig_header, repl=repl)
  1884. return new_header if cls._use_header(new_header) else orig_header
  1885. @staticmethod
  1886. def _use_header(new_header):
  1887. """
  1888. Should _adjust_header use the replaced header?
  1889. On non-windows systems, always use. On
  1890. Windows systems, only use the replaced header if it resolves
  1891. to an executable on the system.
  1892. """
  1893. clean_header = new_header[2:-1].strip('"')
  1894. return sys.platform != 'win32' or find_executable(clean_header)
  1895. class WindowsExecutableLauncherWriter(WindowsScriptWriter):
  1896. @classmethod
  1897. def _get_script_args(cls, type_, name, header, script_text):
  1898. """
  1899. For Windows, add a .py extension and an .exe launcher
  1900. """
  1901. if type_ == 'gui':
  1902. launcher_type = 'gui'
  1903. ext = '-script.pyw'
  1904. old = ['.pyw']
  1905. else:
  1906. launcher_type = 'cli'
  1907. ext = '-script.py'
  1908. old = ['.py', '.pyc', '.pyo']
  1909. hdr = cls._adjust_header(type_, header)
  1910. blockers = [name + x for x in old]
  1911. yield (name + ext, hdr + script_text, 't', blockers)
  1912. yield (
  1913. name + '.exe', get_win_launcher(launcher_type),
  1914. 'b' # write in binary mode
  1915. )
  1916. if not is_64bit():
  1917. # install a manifest for the launcher to prevent Windows
  1918. # from detecting it as an installer (which it will for
  1919. # launchers like easy_install.exe). Consider only
  1920. # adding a manifest for launchers detected as installers.
  1921. # See Distribute #143 for details.
  1922. m_name = name + '.exe.manifest'
  1923. yield (m_name, load_launcher_manifest(name), 't')
  1924. # for backward-compatibility
  1925. get_script_args = ScriptWriter.get_script_args
  1926. get_script_header = ScriptWriter.get_script_header
  1927. def get_win_launcher(type):
  1928. """
  1929. Load the Windows launcher (executable) suitable for launching a script.
  1930. `type` should be either 'cli' or 'gui'
  1931. Returns the executable as a byte string.
  1932. """
  1933. launcher_fn = '%s.exe' % type
  1934. if is_64bit():
  1935. launcher_fn = launcher_fn.replace(".", "-64.")
  1936. else:
  1937. launcher_fn = launcher_fn.replace(".", "-32.")
  1938. return resource_string('setuptools', launcher_fn)
  1939. def load_launcher_manifest(name):
  1940. manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
  1941. return manifest.decode('utf-8') % vars()
  1942. def rmtree(path, ignore_errors=False, onerror=auto_chmod):
  1943. return shutil.rmtree(path, ignore_errors, onerror)
  1944. def current_umask():
  1945. tmp = os.umask(0o022)
  1946. os.umask(tmp)
  1947. return tmp
  1948. class EasyInstallDeprecationWarning(SetuptoolsDeprecationWarning):
  1949. """
  1950. Warning for EasyInstall deprecations, bypassing suppression.
  1951. """