easy_install.py 85 KB

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