easy_install.py 86 KB

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