easy_install.py 84 KB

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