easy_install.py 85 KB

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