Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

easy_install.py 85KB

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