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

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