easy_install.py 84 KB

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