easy_install.py 84 KB

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