easy_install.py 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  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://pythonhosted.org/setuptools/easy_install.html
  9. """
  10. import sys
  11. import os
  12. import zipimport
  13. import shutil
  14. import tempfile
  15. import zipfile
  16. import re
  17. import stat
  18. import random
  19. import platform
  20. import textwrap
  21. import warnings
  22. import site
  23. import struct
  24. from glob import glob
  25. from distutils import log, dir_util
  26. from distutils.command.build_scripts import first_line_re
  27. import pkg_resources
  28. from setuptools import Command, _dont_write_bytecode
  29. from setuptools.sandbox import run_setup
  30. from setuptools.py31compat import get_path, get_config_vars
  31. from distutils.util import get_platform
  32. from distutils.util import convert_path, subst_vars
  33. from distutils.errors import DistutilsArgError, DistutilsOptionError, \
  34. DistutilsError, DistutilsPlatformError
  35. from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
  36. from setuptools.command import setopt
  37. from setuptools.archive_util import unpack_archive
  38. from setuptools.package_index import PackageIndex
  39. from setuptools.package_index import URL_SCHEME
  40. from setuptools.command import bdist_egg, egg_info
  41. from setuptools.compat import (iteritems, maxsize, basestring, unicode,
  42. reraise)
  43. from pkg_resources import (
  44. yield_lines, normalize_path, resource_string, ensure_directory,
  45. get_distribution, find_distributions, Environment, Requirement,
  46. Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound,
  47. VersionConflict, DEVELOP_DIST,
  48. )
  49. sys_executable = os.environ.get('__PYVENV_LAUNCHER__',
  50. os.path.normpath(sys.executable))
  51. __all__ = [
  52. 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
  53. 'main', 'get_exe_prefixes',
  54. ]
  55. def is_64bit():
  56. return struct.calcsize("P") == 8
  57. def samefile(p1, p2):
  58. both_exist = os.path.exists(p1) and os.path.exists(p2)
  59. use_samefile = hasattr(os.path, 'samefile') and both_exist
  60. if use_samefile:
  61. return os.path.samefile(p1, p2)
  62. norm_p1 = os.path.normpath(os.path.normcase(p1))
  63. norm_p2 = os.path.normpath(os.path.normcase(p2))
  64. return norm_p1 == norm_p2
  65. if sys.version_info <= (3,):
  66. def _to_ascii(s):
  67. return s
  68. def isascii(s):
  69. try:
  70. unicode(s, 'ascii')
  71. return True
  72. except UnicodeError:
  73. return False
  74. else:
  75. def _to_ascii(s):
  76. return s.encode('ascii')
  77. def isascii(s):
  78. try:
  79. s.encode('ascii')
  80. return True
  81. except UnicodeError:
  82. return False
  83. class easy_install(Command):
  84. """Manage a download/build/install process"""
  85. description = "Find/get/install Python packages"
  86. command_consumes_arguments = True
  87. user_options = [
  88. ('prefix=', None, "installation prefix"),
  89. ("zip-ok", "z", "install package as a zipfile"),
  90. ("multi-version", "m", "make apps have to require() a version"),
  91. ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
  92. ("install-dir=", "d", "install package to DIR"),
  93. ("script-dir=", "s", "install scripts to DIR"),
  94. ("exclude-scripts", "x", "Don't install scripts"),
  95. ("always-copy", "a", "Copy all needed packages to install dir"),
  96. ("index-url=", "i", "base URL of Python Package Index"),
  97. ("find-links=", "f", "additional URL(s) to search for packages"),
  98. ("build-directory=", "b",
  99. "download/extract/build in DIR; keep the results"),
  100. ('optimize=', 'O',
  101. "also compile with optimization: -O1 for \"python -O\", "
  102. "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
  103. ('record=', None,
  104. "filename in which to record list of installed files"),
  105. ('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
  106. ('site-dirs=','S',"list of directories where .pth files work"),
  107. ('editable', 'e', "Install specified packages in editable form"),
  108. ('no-deps', 'N', "don't install dependencies"),
  109. ('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
  110. ('local-snapshots-ok', 'l',
  111. "allow building eggs from local checkouts"),
  112. ('version', None, "print version information and exit"),
  113. ('no-find-links', None,
  114. "Don't load find-links defined in packages being installed")
  115. ]
  116. boolean_options = [
  117. 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
  118. 'editable',
  119. 'no-deps', 'local-snapshots-ok', 'version'
  120. ]
  121. if site.ENABLE_USER_SITE:
  122. help_msg = "install in user site-package '%s'" % site.USER_SITE
  123. user_options.append(('user', None, help_msg))
  124. boolean_options.append('user')
  125. negative_opt = {'always-unzip': 'zip-ok'}
  126. create_index = PackageIndex
  127. def initialize_options(self):
  128. if site.ENABLE_USER_SITE:
  129. whereami = os.path.abspath(__file__)
  130. self.user = whereami.startswith(site.USER_SITE)
  131. else:
  132. self.user = 0
  133. self.zip_ok = self.local_snapshots_ok = None
  134. self.install_dir = self.script_dir = self.exclude_scripts = None
  135. self.index_url = None
  136. self.find_links = None
  137. self.build_directory = None
  138. self.args = None
  139. self.optimize = self.record = None
  140. self.upgrade = self.always_copy = self.multi_version = None
  141. self.editable = self.no_deps = self.allow_hosts = None
  142. self.root = self.prefix = self.no_report = None
  143. self.version = None
  144. self.install_purelib = None # for pure module distributions
  145. self.install_platlib = None # non-pure (dists w/ extensions)
  146. self.install_headers = None # for C/C++ headers
  147. self.install_lib = None # set to either purelib or platlib
  148. self.install_scripts = None
  149. self.install_data = None
  150. self.install_base = None
  151. self.install_platbase = None
  152. if site.ENABLE_USER_SITE:
  153. self.install_userbase = site.USER_BASE
  154. self.install_usersite = site.USER_SITE
  155. else:
  156. self.install_userbase = None
  157. self.install_usersite = None
  158. self.no_find_links = None
  159. # Options not specifiable via command line
  160. self.package_index = None
  161. self.pth_file = self.always_copy_from = None
  162. self.site_dirs = None
  163. self.installed_projects = {}
  164. self.sitepy_installed = False
  165. # Always read easy_install options, even if we are subclassed, or have
  166. # an independent instance created. This ensures that defaults will
  167. # always come from the standard configuration file(s)' "easy_install"
  168. # section, even if this is a "develop" or "install" command, or some
  169. # other embedding.
  170. self._dry_run = None
  171. self.verbose = self.distribution.verbose
  172. self.distribution._set_command_options(
  173. self, self.distribution.get_option_dict('easy_install')
  174. )
  175. def delete_blockers(self, blockers):
  176. for filename in blockers:
  177. if os.path.exists(filename) or os.path.islink(filename):
  178. log.info("Deleting %s", filename)
  179. if not self.dry_run:
  180. if os.path.isdir(filename) and not os.path.islink(filename):
  181. rmtree(filename)
  182. else:
  183. os.unlink(filename)
  184. def finalize_options(self):
  185. if self.version:
  186. print('setuptools %s' % get_distribution('setuptools').version)
  187. sys.exit()
  188. py_version = sys.version.split()[0]
  189. prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
  190. self.config_vars = {
  191. 'dist_name': self.distribution.get_name(),
  192. 'dist_version': self.distribution.get_version(),
  193. 'dist_fullname': self.distribution.get_fullname(),
  194. 'py_version': py_version,
  195. 'py_version_short': py_version[0:3],
  196. 'py_version_nodot': py_version[0] + py_version[2],
  197. 'sys_prefix': prefix,
  198. 'prefix': prefix,
  199. 'sys_exec_prefix': exec_prefix,
  200. 'exec_prefix': exec_prefix,
  201. # Only python 3.2+ has abiflags
  202. 'abiflags': getattr(sys, 'abiflags', ''),
  203. }
  204. if site.ENABLE_USER_SITE:
  205. self.config_vars['userbase'] = self.install_userbase
  206. self.config_vars['usersite'] = self.install_usersite
  207. # fix the install_dir if "--user" was used
  208. #XXX: duplicate of the code in the setup command
  209. if self.user and site.ENABLE_USER_SITE:
  210. self.create_home_path()
  211. if self.install_userbase is None:
  212. raise DistutilsPlatformError(
  213. "User base directory is not specified")
  214. self.install_base = self.install_platbase = self.install_userbase
  215. if os.name == 'posix':
  216. self.select_scheme("unix_user")
  217. else:
  218. self.select_scheme(os.name + "_user")
  219. self.expand_basedirs()
  220. self.expand_dirs()
  221. self._expand('install_dir','script_dir','build_directory','site_dirs')
  222. # If a non-default installation directory was specified, default the
  223. # script directory to match it.
  224. if self.script_dir is None:
  225. self.script_dir = self.install_dir
  226. if self.no_find_links is None:
  227. self.no_find_links = False
  228. # Let install_dir get set by install_lib command, which in turn
  229. # gets its info from the install command, and takes into account
  230. # --prefix and --home and all that other crud.
  231. self.set_undefined_options('install_lib',
  232. ('install_dir','install_dir')
  233. )
  234. # Likewise, set default script_dir from 'install_scripts.install_dir'
  235. self.set_undefined_options('install_scripts',
  236. ('install_dir', 'script_dir')
  237. )
  238. if self.user and self.install_purelib:
  239. self.install_dir = self.install_purelib
  240. self.script_dir = self.install_scripts
  241. # default --record from the install command
  242. self.set_undefined_options('install', ('record', 'record'))
  243. # Should this be moved to the if statement below? It's not used
  244. # elsewhere
  245. normpath = map(normalize_path, sys.path)
  246. self.all_site_dirs = get_site_dirs()
  247. if self.site_dirs is not None:
  248. site_dirs = [
  249. os.path.expanduser(s.strip()) for s in self.site_dirs.split(',')
  250. ]
  251. for d in site_dirs:
  252. if not os.path.isdir(d):
  253. log.warn("%s (in --site-dirs) does not exist", d)
  254. elif normalize_path(d) not in normpath:
  255. raise DistutilsOptionError(
  256. d+" (in --site-dirs) is not on sys.path"
  257. )
  258. else:
  259. self.all_site_dirs.append(normalize_path(d))
  260. if not self.editable: self.check_site_dir()
  261. self.index_url = self.index_url or "https://pypi.python.org/simple"
  262. self.shadow_path = self.all_site_dirs[:]
  263. for path_item in self.install_dir, normalize_path(self.script_dir):
  264. if path_item not in self.shadow_path:
  265. self.shadow_path.insert(0, path_item)
  266. if self.allow_hosts is not None:
  267. hosts = [s.strip() for s in self.allow_hosts.split(',')]
  268. else:
  269. hosts = ['*']
  270. if self.package_index is None:
  271. self.package_index = self.create_index(
  272. self.index_url, search_path = self.shadow_path, hosts=hosts,
  273. )
  274. self.local_index = Environment(self.shadow_path+sys.path)
  275. if self.find_links is not None:
  276. if isinstance(self.find_links, basestring):
  277. self.find_links = self.find_links.split()
  278. else:
  279. self.find_links = []
  280. if self.local_snapshots_ok:
  281. self.package_index.scan_egg_links(self.shadow_path+sys.path)
  282. if not self.no_find_links:
  283. self.package_index.add_find_links(self.find_links)
  284. self.set_undefined_options('install_lib', ('optimize','optimize'))
  285. if not isinstance(self.optimize,int):
  286. try:
  287. self.optimize = int(self.optimize)
  288. if not (0 <= self.optimize <= 2): raise ValueError
  289. except ValueError:
  290. raise DistutilsOptionError("--optimize must be 0, 1, or 2")
  291. if self.editable and not self.build_directory:
  292. raise DistutilsArgError(
  293. "Must specify a build directory (-b) when using --editable"
  294. )
  295. if not self.args:
  296. raise DistutilsArgError(
  297. "No urls, filenames, or requirements specified (see --help)")
  298. self.outputs = []
  299. def _expand_attrs(self, attrs):
  300. for attr in attrs:
  301. val = getattr(self, attr)
  302. if val is not None:
  303. if os.name == 'posix' or os.name == 'nt':
  304. val = os.path.expanduser(val)
  305. val = subst_vars(val, self.config_vars)
  306. setattr(self, attr, val)
  307. def expand_basedirs(self):
  308. """Calls `os.path.expanduser` on install_base, install_platbase and
  309. root."""
  310. self._expand_attrs(['install_base', 'install_platbase', 'root'])
  311. def expand_dirs(self):
  312. """Calls `os.path.expanduser` on install dirs."""
  313. self._expand_attrs(['install_purelib', 'install_platlib',
  314. 'install_lib', 'install_headers',
  315. 'install_scripts', 'install_data',])
  316. def run(self):
  317. if self.verbose != self.distribution.verbose:
  318. log.set_verbosity(self.verbose)
  319. try:
  320. for spec in self.args:
  321. self.easy_install(spec, not self.no_deps)
  322. if self.record:
  323. outputs = self.outputs
  324. if self.root: # strip any package prefix
  325. root_len = len(self.root)
  326. for counter in range(len(outputs)):
  327. outputs[counter] = outputs[counter][root_len:]
  328. from distutils import file_util
  329. self.execute(
  330. file_util.write_file, (self.record, outputs),
  331. "writing list of installed files to '%s'" %
  332. self.record
  333. )
  334. self.warn_deprecated_options()
  335. finally:
  336. log.set_verbosity(self.distribution.verbose)
  337. def pseudo_tempname(self):
  338. """Return a pseudo-tempname base in the install directory.
  339. This code is intentionally naive; if a malicious party can write to
  340. the target directory you're already in deep doodoo.
  341. """
  342. try:
  343. pid = os.getpid()
  344. except:
  345. pid = random.randint(0, maxsize)
  346. return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
  347. def warn_deprecated_options(self):
  348. pass
  349. def check_site_dir(self):
  350. """Verify that self.install_dir is .pth-capable dir, if needed"""
  351. instdir = normalize_path(self.install_dir)
  352. pth_file = os.path.join(instdir,'easy-install.pth')
  353. # Is it a configured, PYTHONPATH, implicit, or explicit site dir?
  354. is_site_dir = instdir in self.all_site_dirs
  355. if not is_site_dir and not self.multi_version:
  356. # No? Then directly test whether it does .pth file processing
  357. is_site_dir = self.check_pth_processing()
  358. else:
  359. # make sure we can write to target dir
  360. testfile = self.pseudo_tempname()+'.write-test'
  361. test_exists = os.path.exists(testfile)
  362. try:
  363. if test_exists: os.unlink(testfile)
  364. open(testfile,'w').close()
  365. os.unlink(testfile)
  366. except (OSError,IOError):
  367. self.cant_write_to_target()
  368. if not is_site_dir and not self.multi_version:
  369. # Can't install non-multi to non-site dir
  370. raise DistutilsError(self.no_default_version_msg())
  371. if is_site_dir:
  372. if self.pth_file is None:
  373. self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
  374. else:
  375. self.pth_file = None
  376. PYTHONPATH = os.environ.get('PYTHONPATH','').split(os.pathsep)
  377. if instdir not in map(normalize_path, [_f for _f in PYTHONPATH if _f]):
  378. # only PYTHONPATH dirs need a site.py, so pretend it's there
  379. self.sitepy_installed = True
  380. elif self.multi_version and not os.path.exists(pth_file):
  381. self.sitepy_installed = True # don't need site.py in this case
  382. self.pth_file = None # and don't create a .pth file
  383. self.install_dir = instdir
  384. def cant_write_to_target(self):
  385. template = """can't create or remove files in install directory
  386. The following error occurred while trying to add or remove files in the
  387. installation directory:
  388. %s
  389. The installation directory you specified (via --install-dir, --prefix, or
  390. the distutils default setting) was:
  391. %s
  392. """
  393. msg = template % (sys.exc_info()[1], self.install_dir,)
  394. if not os.path.exists(self.install_dir):
  395. msg += """
  396. This directory does not currently exist. Please create it and try again, or
  397. choose a different installation directory (using the -d or --install-dir
  398. option).
  399. """
  400. else:
  401. msg += """
  402. Perhaps your account does not have write access to this directory? If the
  403. installation directory is a system-owned directory, you may need to sign in
  404. as the administrator or "root" account. If you do not have administrative
  405. access to this machine, you may wish to choose a different installation
  406. directory, preferably one that is listed in your PYTHONPATH environment
  407. variable.
  408. For information on other options, you may wish to consult the
  409. documentation at:
  410. https://pythonhosted.org/setuptools/easy_install.html
  411. Please make the appropriate changes for your system and try again.
  412. """
  413. raise DistutilsError(msg)
  414. def check_pth_processing(self):
  415. """Empirically verify whether .pth files are supported in inst. dir"""
  416. instdir = self.install_dir
  417. log.info("Checking .pth file support in %s", instdir)
  418. pth_file = self.pseudo_tempname()+".pth"
  419. ok_file = pth_file+'.ok'
  420. ok_exists = os.path.exists(ok_file)
  421. try:
  422. if ok_exists: os.unlink(ok_file)
  423. dirname = os.path.dirname(ok_file)
  424. if not os.path.exists(dirname):
  425. os.makedirs(dirname)
  426. f = open(pth_file,'w')
  427. except (OSError,IOError):
  428. self.cant_write_to_target()
  429. else:
  430. try:
  431. f.write("import os; f = open(%r, 'w'); f.write('OK'); f.close()\n" % (ok_file,))
  432. f.close()
  433. f=None
  434. executable = sys.executable
  435. if os.name=='nt':
  436. dirname,basename = os.path.split(executable)
  437. alt = os.path.join(dirname,'pythonw.exe')
  438. if basename.lower()=='python.exe' and os.path.exists(alt):
  439. # use pythonw.exe to avoid opening a console window
  440. executable = alt
  441. from distutils.spawn import spawn
  442. spawn([executable,'-E','-c','pass'],0)
  443. if os.path.exists(ok_file):
  444. log.info(
  445. "TEST PASSED: %s appears to support .pth files",
  446. instdir
  447. )
  448. return True
  449. finally:
  450. if f:
  451. f.close()
  452. if os.path.exists(ok_file):
  453. os.unlink(ok_file)
  454. if os.path.exists(pth_file):
  455. os.unlink(pth_file)
  456. if not self.multi_version:
  457. log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
  458. return False
  459. def install_egg_scripts(self, dist):
  460. """Write all the scripts for `dist`, unless scripts are excluded"""
  461. if not self.exclude_scripts and dist.metadata_isdir('scripts'):
  462. for script_name in dist.metadata_listdir('scripts'):
  463. if dist.metadata_isdir('scripts/' + script_name):
  464. # The "script" is a directory, likely a Python 3
  465. # __pycache__ directory, so skip it.
  466. continue
  467. self.install_script(
  468. dist, script_name,
  469. dist.get_metadata('scripts/'+script_name)
  470. )
  471. self.install_wrapper_scripts(dist)
  472. def add_output(self, path):
  473. if os.path.isdir(path):
  474. for base, dirs, files in os.walk(path):
  475. for filename in files:
  476. self.outputs.append(os.path.join(base,filename))
  477. else:
  478. self.outputs.append(path)
  479. def not_editable(self, spec):
  480. if self.editable:
  481. raise DistutilsArgError(
  482. "Invalid argument %r: you can't use filenames or URLs "
  483. "with --editable (except via the --find-links option)."
  484. % (spec,)
  485. )
  486. def check_editable(self,spec):
  487. if not self.editable:
  488. return
  489. if os.path.exists(os.path.join(self.build_directory, spec.key)):
  490. raise DistutilsArgError(
  491. "%r already exists in %s; can't do a checkout there" %
  492. (spec.key, self.build_directory)
  493. )
  494. def easy_install(self, spec, deps=False):
  495. tmpdir = tempfile.mkdtemp(prefix="easy_install-")
  496. download = None
  497. if not self.editable: self.install_site_py()
  498. try:
  499. if not isinstance(spec,Requirement):
  500. if URL_SCHEME(spec):
  501. # It's a url, download it to tmpdir and process
  502. self.not_editable(spec)
  503. download = self.package_index.download(spec, tmpdir)
  504. return self.install_item(None, download, tmpdir, deps, True)
  505. elif os.path.exists(spec):
  506. # Existing file or directory, just process it directly
  507. self.not_editable(spec)
  508. return self.install_item(None, spec, tmpdir, deps, True)
  509. else:
  510. spec = parse_requirement_arg(spec)
  511. self.check_editable(spec)
  512. dist = self.package_index.fetch_distribution(
  513. spec, tmpdir, self.upgrade, self.editable, not self.always_copy,
  514. self.local_index
  515. )
  516. if dist is None:
  517. msg = "Could not find suitable distribution for %r" % spec
  518. if self.always_copy:
  519. msg+=" (--always-copy skips system and development eggs)"
  520. raise DistutilsError(msg)
  521. elif dist.precedence==DEVELOP_DIST:
  522. # .egg-info dists don't need installing, just process deps
  523. self.process_distribution(spec, dist, deps, "Using")
  524. return dist
  525. else:
  526. return self.install_item(spec, dist.location, tmpdir, deps)
  527. finally:
  528. if os.path.exists(tmpdir):
  529. rmtree(tmpdir)
  530. def install_item(self, spec, download, tmpdir, deps, install_needed=False):
  531. # Installation is also needed if file in tmpdir or is not an egg
  532. install_needed = install_needed or self.always_copy
  533. install_needed = install_needed or os.path.dirname(download) == tmpdir
  534. install_needed = install_needed or not download.endswith('.egg')
  535. install_needed = install_needed or (
  536. self.always_copy_from is not None and
  537. os.path.dirname(normalize_path(download)) ==
  538. normalize_path(self.always_copy_from)
  539. )
  540. if spec and not install_needed:
  541. # at this point, we know it's a local .egg, we just don't know if
  542. # it's already installed.
  543. for dist in self.local_index[spec.project_name]:
  544. if dist.location==download:
  545. break
  546. else:
  547. install_needed = True # it's not in the local index
  548. log.info("Processing %s", os.path.basename(download))
  549. if install_needed:
  550. dists = self.install_eggs(spec, download, tmpdir)
  551. for dist in dists:
  552. self.process_distribution(spec, dist, deps)
  553. else:
  554. dists = [self.egg_distribution(download)]
  555. self.process_distribution(spec, dists[0], deps, "Using")
  556. if spec is not None:
  557. for dist in dists:
  558. if dist in spec:
  559. return dist
  560. def select_scheme(self, name):
  561. """Sets the install directories by applying the install schemes."""
  562. # it's the caller's problem if they supply a bad name!
  563. scheme = INSTALL_SCHEMES[name]
  564. for key in SCHEME_KEYS:
  565. attrname = 'install_' + key
  566. if getattr(self, attrname) is None:
  567. setattr(self, attrname, scheme[key])
  568. def process_distribution(self, requirement, dist, deps=True, *info):
  569. self.update_pth(dist)
  570. self.package_index.add(dist)
  571. # First remove the dist from self.local_index, to avoid problems using
  572. # old cached data in case its underlying file has been replaced.
  573. #
  574. # This is a quick-fix for a zipimporter caching issue in case the dist
  575. # has been implemented as and already loaded from a zip file that got
  576. # replaced later on. For more detailed information see setuptools issue
  577. # #168 at 'http://bitbucket.org/pypa/setuptools/issue/168'.
  578. if dist in self.local_index[dist.key]:
  579. self.local_index.remove(dist)
  580. self.local_index.add(dist)
  581. self.install_egg_scripts(dist)
  582. self.installed_projects[dist.key] = dist
  583. log.info(self.installation_report(requirement, dist, *info))
  584. if (dist.has_metadata('dependency_links.txt') and
  585. not self.no_find_links):
  586. self.package_index.add_find_links(
  587. dist.get_metadata_lines('dependency_links.txt')
  588. )
  589. if not deps and not self.always_copy:
  590. return
  591. elif requirement is not None and dist.key != requirement.key:
  592. log.warn("Skipping dependencies for %s", dist)
  593. return # XXX this is not the distribution we were looking for
  594. elif requirement is None or dist not in requirement:
  595. # if we wound up with a different version, resolve what we've got
  596. distreq = dist.as_requirement()
  597. requirement = requirement or distreq
  598. requirement = Requirement(
  599. distreq.project_name, distreq.specs, requirement.extras
  600. )
  601. log.info("Processing dependencies for %s", requirement)
  602. try:
  603. distros = WorkingSet([]).resolve(
  604. [requirement], self.local_index, self.easy_install
  605. )
  606. except DistributionNotFound:
  607. e = sys.exc_info()[1]
  608. raise DistutilsError(
  609. "Could not find required distribution %s" % e.args
  610. )
  611. except VersionConflict:
  612. e = sys.exc_info()[1]
  613. raise DistutilsError(
  614. "Installed distribution %s conflicts with requirement %s"
  615. % e.args
  616. )
  617. if self.always_copy or self.always_copy_from:
  618. # Force all the relevant distros to be copied or activated
  619. for dist in distros:
  620. if dist.key not in self.installed_projects:
  621. self.easy_install(dist.as_requirement())
  622. log.info("Finished processing dependencies for %s", requirement)
  623. def should_unzip(self, dist):
  624. if self.zip_ok is not None:
  625. return not self.zip_ok
  626. if dist.has_metadata('not-zip-safe'):
  627. return True
  628. if not dist.has_metadata('zip-safe'):
  629. return True
  630. return False
  631. def maybe_move(self, spec, dist_filename, setup_base):
  632. dst = os.path.join(self.build_directory, spec.key)
  633. if os.path.exists(dst):
  634. msg = "%r already exists in %s; build directory %s will not be kept"
  635. log.warn(msg, spec.key, self.build_directory, setup_base)
  636. return setup_base
  637. if os.path.isdir(dist_filename):
  638. setup_base = dist_filename
  639. else:
  640. if os.path.dirname(dist_filename)==setup_base:
  641. os.unlink(dist_filename) # get it out of the tmp dir
  642. contents = os.listdir(setup_base)
  643. if len(contents)==1:
  644. dist_filename = os.path.join(setup_base,contents[0])
  645. if os.path.isdir(dist_filename):
  646. # if the only thing there is a directory, move it instead
  647. setup_base = dist_filename
  648. ensure_directory(dst)
  649. shutil.move(setup_base, dst)
  650. return dst
  651. def install_wrapper_scripts(self, dist):
  652. if not self.exclude_scripts:
  653. for args in get_script_args(dist):
  654. self.write_script(*args)
  655. def install_script(self, dist, script_name, script_text, dev_path=None):
  656. """Generate a legacy script wrapper and install it"""
  657. spec = str(dist.as_requirement())
  658. is_script = is_python_script(script_text, script_name)
  659. def get_template(filename):
  660. """
  661. There are a couple of template scripts in the package. This
  662. function loads one of them and prepares it for use.
  663. These templates use triple-quotes to escape variable
  664. substitutions so the scripts get the 2to3 treatment when build
  665. on Python 3. The templates cannot use triple-quotes naturally.
  666. """
  667. raw_bytes = resource_string('setuptools', template_name)
  668. template_str = raw_bytes.decode('utf-8')
  669. clean_template = template_str.replace('"""', '')
  670. return clean_template
  671. if is_script:
  672. # See https://bitbucket.org/pypa/setuptools/issue/134 for info
  673. # on script file naming and downstream issues with SVR4
  674. template_name = 'script template.py'
  675. if dev_path:
  676. template_name = template_name.replace('.py', ' (dev).py')
  677. script_text = (get_script_header(script_text) +
  678. get_template(template_name) % locals())
  679. self.write_script(script_name, _to_ascii(script_text), 'b')
  680. def write_script(self, script_name, contents, mode="t", blockers=()):
  681. """Write an executable file to the scripts directory"""
  682. self.delete_blockers( # clean up old .py/.pyw w/o a script
  683. [os.path.join(self.script_dir,x) for x in blockers])
  684. log.info("Installing %s script to %s", script_name, self.script_dir)
  685. target = os.path.join(self.script_dir, script_name)
  686. self.add_output(target)
  687. mask = current_umask()
  688. if not self.dry_run:
  689. ensure_directory(target)
  690. if os.path.exists(target):
  691. os.unlink(target)
  692. f = open(target,"w"+mode)
  693. f.write(contents)
  694. f.close()
  695. chmod(target, 0o777-mask)
  696. def install_eggs(self, spec, dist_filename, tmpdir):
  697. # .egg dirs or files are already built, so just return them
  698. if dist_filename.lower().endswith('.egg'):
  699. return [self.install_egg(dist_filename, tmpdir)]
  700. elif dist_filename.lower().endswith('.exe'):
  701. return [self.install_exe(dist_filename, tmpdir)]
  702. # Anything else, try to extract and build
  703. setup_base = tmpdir
  704. if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
  705. unpack_archive(dist_filename, tmpdir, self.unpack_progress)
  706. elif os.path.isdir(dist_filename):
  707. setup_base = os.path.abspath(dist_filename)
  708. if (setup_base.startswith(tmpdir) # something we downloaded
  709. and self.build_directory and spec is not None):
  710. setup_base = self.maybe_move(spec, dist_filename, setup_base)
  711. # Find the setup.py file
  712. setup_script = os.path.join(setup_base, 'setup.py')
  713. if not os.path.exists(setup_script):
  714. setups = glob(os.path.join(setup_base, '*', 'setup.py'))
  715. if not setups:
  716. raise DistutilsError(
  717. "Couldn't find a setup script in %s" % os.path.abspath(dist_filename)
  718. )
  719. if len(setups)>1:
  720. raise DistutilsError(
  721. "Multiple setup scripts in %s" % os.path.abspath(dist_filename)
  722. )
  723. setup_script = setups[0]
  724. # Now run it, and return the result
  725. if self.editable:
  726. log.info(self.report_editable(spec, setup_script))
  727. return []
  728. else:
  729. return self.build_and_install(setup_script, setup_base)
  730. def egg_distribution(self, egg_path):
  731. if os.path.isdir(egg_path):
  732. metadata = PathMetadata(egg_path,os.path.join(egg_path,'EGG-INFO'))
  733. else:
  734. metadata = EggMetadata(zipimport.zipimporter(egg_path))
  735. return Distribution.from_filename(egg_path,metadata=metadata)
  736. def install_egg(self, egg_path, tmpdir):
  737. destination = os.path.join(self.install_dir,os.path.basename(egg_path))
  738. destination = os.path.abspath(destination)
  739. if not self.dry_run:
  740. ensure_directory(destination)
  741. dist = self.egg_distribution(egg_path)
  742. if not samefile(egg_path, destination):
  743. if os.path.isdir(destination) and not os.path.islink(destination):
  744. dir_util.remove_tree(destination, dry_run=self.dry_run)
  745. elif os.path.exists(destination):
  746. self.execute(os.unlink,(destination,),"Removing "+destination)
  747. uncache_zipdir(destination)
  748. if os.path.isdir(egg_path):
  749. if egg_path.startswith(tmpdir):
  750. f,m = shutil.move, "Moving"
  751. else:
  752. f,m = shutil.copytree, "Copying"
  753. elif self.should_unzip(dist):
  754. self.mkpath(destination)
  755. f,m = self.unpack_and_compile, "Extracting"
  756. elif egg_path.startswith(tmpdir):
  757. f,m = shutil.move, "Moving"
  758. else:
  759. f,m = shutil.copy2, "Copying"
  760. self.execute(f, (egg_path, destination),
  761. (m+" %s to %s") %
  762. (os.path.basename(egg_path),os.path.dirname(destination)))
  763. self.add_output(destination)
  764. return self.egg_distribution(destination)
  765. def install_exe(self, dist_filename, tmpdir):
  766. # See if it's valid, get data
  767. cfg = extract_wininst_cfg(dist_filename)
  768. if cfg is None:
  769. raise DistutilsError(
  770. "%s is not a valid distutils Windows .exe" % dist_filename
  771. )
  772. # Create a dummy distribution object until we build the real distro
  773. dist = Distribution(
  774. None,
  775. project_name=cfg.get('metadata','name'),
  776. version=cfg.get('metadata','version'), platform=get_platform(),
  777. )
  778. # Convert the .exe to an unpacked egg
  779. egg_path = dist.location = os.path.join(tmpdir, dist.egg_name()+'.egg')
  780. egg_tmp = egg_path + '.tmp'
  781. _egg_info = os.path.join(egg_tmp, 'EGG-INFO')
  782. pkg_inf = os.path.join(_egg_info, 'PKG-INFO')
  783. ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
  784. dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX
  785. self.exe_to_egg(dist_filename, egg_tmp)
  786. # Write EGG-INFO/PKG-INFO
  787. if not os.path.exists(pkg_inf):
  788. f = open(pkg_inf,'w')
  789. f.write('Metadata-Version: 1.0\n')
  790. for k,v in cfg.items('metadata'):
  791. if k != 'target_version':
  792. f.write('%s: %s\n' % (k.replace('_','-').title(), v))
  793. f.close()
  794. script_dir = os.path.join(_egg_info,'scripts')
  795. self.delete_blockers( # delete entry-point scripts to avoid duping
  796. [os.path.join(script_dir,args[0]) for args in get_script_args(dist)]
  797. )
  798. # Build .egg file from tmpdir
  799. bdist_egg.make_zipfile(
  800. egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run
  801. )
  802. # install the .egg
  803. return self.install_egg(egg_path, tmpdir)
  804. def exe_to_egg(self, dist_filename, egg_tmp):
  805. """Extract a bdist_wininst to the directories an egg would use"""
  806. # Check for .pth file and set up prefix translations
  807. prefixes = get_exe_prefixes(dist_filename)
  808. to_compile = []
  809. native_libs = []
  810. top_level = {}
  811. def process(src,dst):
  812. s = src.lower()
  813. for old,new in prefixes:
  814. if s.startswith(old):
  815. src = new+src[len(old):]
  816. parts = src.split('/')
  817. dst = os.path.join(egg_tmp, *parts)
  818. dl = dst.lower()
  819. if dl.endswith('.pyd') or dl.endswith('.dll'):
  820. parts[-1] = bdist_egg.strip_module(parts[-1])
  821. top_level[os.path.splitext(parts[0])[0]] = 1
  822. native_libs.append(src)
  823. elif dl.endswith('.py') and old!='SCRIPTS/':
  824. top_level[os.path.splitext(parts[0])[0]] = 1
  825. to_compile.append(dst)
  826. return dst
  827. if not src.endswith('.pth'):
  828. log.warn("WARNING: can't process %s", src)
  829. return None
  830. # extract, tracking .pyd/.dll->native_libs and .py -> to_compile
  831. unpack_archive(dist_filename, egg_tmp, process)
  832. stubs = []
  833. for res in native_libs:
  834. if res.lower().endswith('.pyd'): # create stubs for .pyd's
  835. parts = res.split('/')
  836. resource = parts[-1]
  837. parts[-1] = bdist_egg.strip_module(parts[-1])+'.py'
  838. pyfile = os.path.join(egg_tmp, *parts)
  839. to_compile.append(pyfile)
  840. stubs.append(pyfile)
  841. bdist_egg.write_stub(resource, pyfile)
  842. self.byte_compile(to_compile) # compile .py's
  843. bdist_egg.write_safety_flag(os.path.join(egg_tmp,'EGG-INFO'),
  844. bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
  845. for name in 'top_level','native_libs':
  846. if locals()[name]:
  847. txt = os.path.join(egg_tmp, 'EGG-INFO', name+'.txt')
  848. if not os.path.exists(txt):
  849. f = open(txt,'w')
  850. f.write('\n'.join(locals()[name])+'\n')
  851. f.close()
  852. def installation_report(self, req, dist, what="Installed"):
  853. """Helpful installation message for display to package users"""
  854. msg = "\n%(what)s %(eggloc)s%(extras)s"
  855. if self.multi_version and not self.no_report:
  856. msg += """
  857. Because this distribution was installed --multi-version, before you can
  858. import modules from this package in an application, you will need to
  859. 'import pkg_resources' and then use a 'require()' call similar to one of
  860. these examples, in order to select the desired version:
  861. pkg_resources.require("%(name)s") # latest installed version
  862. pkg_resources.require("%(name)s==%(version)s") # this exact version
  863. pkg_resources.require("%(name)s>=%(version)s") # this version or higher
  864. """
  865. if self.install_dir not in map(normalize_path,sys.path):
  866. msg += """
  867. Note also that the installation directory must be on sys.path at runtime for
  868. this to work. (e.g. by being the application's script directory, by being on
  869. PYTHONPATH, or by being added to sys.path by your code.)
  870. """
  871. eggloc = dist.location
  872. name = dist.project_name
  873. version = dist.version
  874. extras = '' # TODO: self.report_extras(req, dist)
  875. return msg % locals()
  876. def report_editable(self, spec, setup_script):
  877. dirname = os.path.dirname(setup_script)
  878. python = sys.executable
  879. return """\nExtracted editable version of %(spec)s to %(dirname)s
  880. If it uses setuptools in its setup script, you can activate it in
  881. "development" mode by going to that directory and running::
  882. %(python)s setup.py develop
  883. See the setuptools documentation for the "develop" command for more info.
  884. """ % locals()
  885. def run_setup(self, setup_script, setup_base, args):
  886. sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
  887. sys.modules.setdefault('distutils.command.egg_info', egg_info)
  888. args = list(args)
  889. if self.verbose>2:
  890. v = 'v' * (self.verbose - 1)
  891. args.insert(0,'-'+v)
  892. elif self.verbose<2:
  893. args.insert(0,'-q')
  894. if self.dry_run:
  895. args.insert(0,'-n')
  896. log.info(
  897. "Running %s %s", setup_script[len(setup_base)+1:], ' '.join(args)
  898. )
  899. try:
  900. run_setup(setup_script, args)
  901. except SystemExit:
  902. v = sys.exc_info()[1]
  903. raise DistutilsError("Setup script exited with %s" % (v.args[0],))
  904. def build_and_install(self, setup_script, setup_base):
  905. args = ['bdist_egg', '--dist-dir']
  906. dist_dir = tempfile.mkdtemp(
  907. prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
  908. )
  909. try:
  910. self._set_fetcher_options(os.path.dirname(setup_script))
  911. args.append(dist_dir)
  912. self.run_setup(setup_script, setup_base, args)
  913. all_eggs = Environment([dist_dir])
  914. eggs = []
  915. for key in all_eggs:
  916. for dist in all_eggs[key]:
  917. eggs.append(self.install_egg(dist.location, setup_base))
  918. if not eggs and not self.dry_run:
  919. log.warn("No eggs found in %s (setup script problem?)",
  920. dist_dir)
  921. return eggs
  922. finally:
  923. rmtree(dist_dir)
  924. log.set_verbosity(self.verbose) # restore our log verbosity
  925. def _set_fetcher_options(self, base):
  926. """
  927. When easy_install is about to run bdist_egg on a source dist, that
  928. source dist might have 'setup_requires' directives, requiring
  929. additional fetching. Ensure the fetcher options given to easy_install
  930. are available to that command as well.
  931. """
  932. # find the fetch options from easy_install and write them out
  933. # to the setup.cfg file.
  934. ei_opts = self.distribution.get_option_dict('easy_install').copy()
  935. fetch_directives = (
  936. 'find_links', 'site_dirs', 'index_url', 'optimize',
  937. 'site_dirs', 'allow_hosts',
  938. )
  939. fetch_options = {}
  940. for key, val in ei_opts.items():
  941. if key not in fetch_directives: continue
  942. fetch_options[key.replace('_', '-')] = val[1]
  943. # create a settings dictionary suitable for `edit_config`
  944. settings = dict(easy_install=fetch_options)
  945. cfg_filename = os.path.join(base, 'setup.cfg')
  946. setopt.edit_config(cfg_filename, settings)
  947. def update_pth(self, dist):
  948. if self.pth_file is None:
  949. return
  950. for d in self.pth_file[dist.key]: # drop old entries
  951. if self.multi_version or d.location != dist.location:
  952. log.info("Removing %s from easy-install.pth file", d)
  953. self.pth_file.remove(d)
  954. if d.location in self.shadow_path:
  955. self.shadow_path.remove(d.location)
  956. if not self.multi_version:
  957. if dist.location in self.pth_file.paths:
  958. log.info(
  959. "%s is already the active version in easy-install.pth",
  960. dist
  961. )
  962. else:
  963. log.info("Adding %s to easy-install.pth file", dist)
  964. self.pth_file.add(dist) # add new entry
  965. if dist.location not in self.shadow_path:
  966. self.shadow_path.append(dist.location)
  967. if not self.dry_run:
  968. self.pth_file.save()
  969. if dist.key=='setuptools':
  970. # Ensure that setuptools itself never becomes unavailable!
  971. # XXX should this check for latest version?
  972. filename = os.path.join(self.install_dir,'setuptools.pth')
  973. if os.path.islink(filename): os.unlink(filename)
  974. f = open(filename, 'wt')
  975. f.write(self.pth_file.make_relative(dist.location)+'\n')
  976. f.close()
  977. def unpack_progress(self, src, dst):
  978. # Progress filter for unpacking
  979. log.debug("Unpacking %s to %s", src, dst)
  980. return dst # only unpack-and-compile skips files for dry run
  981. def unpack_and_compile(self, egg_path, destination):
  982. to_compile = []
  983. to_chmod = []
  984. def pf(src, dst):
  985. if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
  986. to_compile.append(dst)
  987. elif dst.endswith('.dll') or dst.endswith('.so'):
  988. to_chmod.append(dst)
  989. self.unpack_progress(src,dst)
  990. return not self.dry_run and dst or None
  991. unpack_archive(egg_path, destination, pf)
  992. self.byte_compile(to_compile)
  993. if not self.dry_run:
  994. for f in to_chmod:
  995. mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755
  996. chmod(f, mode)
  997. def byte_compile(self, to_compile):
  998. if _dont_write_bytecode:
  999. self.warn('byte-compiling is disabled, skipping.')
  1000. return
  1001. from distutils.util import byte_compile
  1002. try:
  1003. # try to make the byte compile messages quieter
  1004. log.set_verbosity(self.verbose - 1)
  1005. byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
  1006. if self.optimize:
  1007. byte_compile(
  1008. to_compile, optimize=self.optimize, force=1,
  1009. dry_run=self.dry_run
  1010. )
  1011. finally:
  1012. log.set_verbosity(self.verbose) # restore original verbosity
  1013. def no_default_version_msg(self):
  1014. template = """bad install directory or PYTHONPATH
  1015. You are attempting to install a package to a directory that is not
  1016. on PYTHONPATH and which Python does not read ".pth" files from. The
  1017. installation directory you specified (via --install-dir, --prefix, or
  1018. the distutils default setting) was:
  1019. %s
  1020. and your PYTHONPATH environment variable currently contains:
  1021. %r
  1022. Here are some of your options for correcting the problem:
  1023. * You can choose a different installation directory, i.e., one that is
  1024. on PYTHONPATH or supports .pth files
  1025. * You can add the installation directory to the PYTHONPATH environment
  1026. variable. (It must then also be on PYTHONPATH whenever you run
  1027. Python and want to use the package(s) you are installing.)
  1028. * You can set up the installation directory to support ".pth" files by
  1029. using one of the approaches described here:
  1030. https://pythonhosted.org/setuptools/easy_install.html#custom-installation-locations
  1031. Please make the appropriate changes for your system and try again."""
  1032. return template % (self.install_dir, os.environ.get('PYTHONPATH',''))
  1033. def install_site_py(self):
  1034. """Make sure there's a site.py in the target dir, if needed"""
  1035. if self.sitepy_installed:
  1036. return # already did it, or don't need to
  1037. sitepy = os.path.join(self.install_dir, "site.py")
  1038. source = resource_string("setuptools", "site-patch.py")
  1039. current = ""
  1040. if os.path.exists(sitepy):
  1041. log.debug("Checking existing site.py in %s", self.install_dir)
  1042. f = open(sitepy,'rb')
  1043. current = f.read()
  1044. # we want str, not bytes
  1045. if sys.version_info >= (3,):
  1046. current = current.decode()
  1047. f.close()
  1048. if not current.startswith('def __boot():'):
  1049. raise DistutilsError(
  1050. "%s is not a setuptools-generated site.py; please"
  1051. " remove it." % sitepy
  1052. )
  1053. if current != source:
  1054. log.info("Creating %s", sitepy)
  1055. if not self.dry_run:
  1056. ensure_directory(sitepy)
  1057. f = open(sitepy,'wb')
  1058. f.write(source)
  1059. f.close()
  1060. self.byte_compile([sitepy])
  1061. self.sitepy_installed = True
  1062. def create_home_path(self):
  1063. """Create directories under ~."""
  1064. if not self.user:
  1065. return
  1066. home = convert_path(os.path.expanduser("~"))
  1067. for name, path in iteritems(self.config_vars):
  1068. if path.startswith(home) and not os.path.isdir(path):
  1069. self.debug_print("os.makedirs('%s', 0o700)" % path)
  1070. os.makedirs(path, 0o700)
  1071. INSTALL_SCHEMES = dict(
  1072. posix = dict(
  1073. install_dir = '$base/lib/python$py_version_short/site-packages',
  1074. script_dir = '$base/bin',
  1075. ),
  1076. )
  1077. DEFAULT_SCHEME = dict(
  1078. install_dir = '$base/Lib/site-packages',
  1079. script_dir = '$base/Scripts',
  1080. )
  1081. def _expand(self, *attrs):
  1082. config_vars = self.get_finalized_command('install').config_vars
  1083. if self.prefix:
  1084. # Set default install_dir/scripts from --prefix
  1085. config_vars = config_vars.copy()
  1086. config_vars['base'] = self.prefix
  1087. scheme = self.INSTALL_SCHEMES.get(os.name,self.DEFAULT_SCHEME)
  1088. for attr,val in scheme.items():
  1089. if getattr(self,attr,None) is None:
  1090. setattr(self,attr,val)
  1091. from distutils.util import subst_vars
  1092. for attr in attrs:
  1093. val = getattr(self, attr)
  1094. if val is not None:
  1095. val = subst_vars(val, config_vars)
  1096. if os.name == 'posix':
  1097. val = os.path.expanduser(val)
  1098. setattr(self, attr, val)
  1099. def get_site_dirs():
  1100. # return a list of 'site' dirs
  1101. sitedirs = [_f for _f in os.environ.get('PYTHONPATH',
  1102. '').split(os.pathsep) if _f]
  1103. prefixes = [sys.prefix]
  1104. if sys.exec_prefix != sys.prefix:
  1105. prefixes.append(sys.exec_prefix)
  1106. for prefix in prefixes:
  1107. if prefix:
  1108. if sys.platform in ('os2emx', 'riscos'):
  1109. sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
  1110. elif os.sep == '/':
  1111. sitedirs.extend([os.path.join(prefix,
  1112. "lib",
  1113. "python" + sys.version[:3],
  1114. "site-packages"),
  1115. os.path.join(prefix, "lib", "site-python")])
  1116. else:
  1117. sitedirs.extend(
  1118. [prefix, os.path.join(prefix, "lib", "site-packages")]
  1119. )
  1120. if sys.platform == 'darwin':
  1121. # for framework builds *only* we add the standard Apple
  1122. # locations. Currently only per-user, but /Library and
  1123. # /Network/Library could be added too
  1124. if 'Python.framework' in prefix:
  1125. home = os.environ.get('HOME')
  1126. if home:
  1127. sitedirs.append(
  1128. os.path.join(home,
  1129. 'Library',
  1130. 'Python',
  1131. sys.version[:3],
  1132. 'site-packages'))
  1133. lib_paths = get_path('purelib'), get_path('platlib')
  1134. for site_lib in lib_paths:
  1135. if site_lib not in sitedirs: sitedirs.append(site_lib)
  1136. if site.ENABLE_USER_SITE:
  1137. sitedirs.append(site.USER_SITE)
  1138. sitedirs = list(map(normalize_path, sitedirs))
  1139. return sitedirs
  1140. def expand_paths(inputs):
  1141. """Yield sys.path directories that might contain "old-style" packages"""
  1142. seen = {}
  1143. for dirname in inputs:
  1144. dirname = normalize_path(dirname)
  1145. if dirname in seen:
  1146. continue
  1147. seen[dirname] = 1
  1148. if not os.path.isdir(dirname):
  1149. continue
  1150. files = os.listdir(dirname)
  1151. yield dirname, files
  1152. for name in files:
  1153. if not name.endswith('.pth'):
  1154. # We only care about the .pth files
  1155. continue
  1156. if name in ('easy-install.pth','setuptools.pth'):
  1157. # Ignore .pth files that we control
  1158. continue
  1159. # Read the .pth file
  1160. f = open(os.path.join(dirname,name))
  1161. lines = list(yield_lines(f))
  1162. f.close()
  1163. # Yield existing non-dupe, non-import directory lines from it
  1164. for line in lines:
  1165. if not line.startswith("import"):
  1166. line = normalize_path(line.rstrip())
  1167. if line not in seen:
  1168. seen[line] = 1
  1169. if not os.path.isdir(line):
  1170. continue
  1171. yield line, os.listdir(line)
  1172. def extract_wininst_cfg(dist_filename):
  1173. """Extract configuration data from a bdist_wininst .exe
  1174. Returns a ConfigParser.RawConfigParser, or None
  1175. """
  1176. f = open(dist_filename,'rb')
  1177. try:
  1178. endrec = zipfile._EndRecData(f)
  1179. if endrec is None:
  1180. return None
  1181. prepended = (endrec[9] - endrec[5]) - endrec[6]
  1182. if prepended < 12: # no wininst data here
  1183. return None
  1184. f.seek(prepended-12)
  1185. from setuptools.compat import StringIO, ConfigParser
  1186. import struct
  1187. tag, cfglen, bmlen = struct.unpack("<iii",f.read(12))
  1188. if tag not in (0x1234567A, 0x1234567B):
  1189. return None # not a valid tag
  1190. f.seek(prepended-(12+cfglen))
  1191. cfg = ConfigParser.RawConfigParser({'version':'','target_version':''})
  1192. try:
  1193. part = f.read(cfglen)
  1194. # part is in bytes, but we need to read up to the first null
  1195. # byte.
  1196. if sys.version_info >= (2,6):
  1197. null_byte = bytes([0])
  1198. else:
  1199. null_byte = chr(0)
  1200. config = part.split(null_byte, 1)[0]
  1201. # Now the config is in bytes, but for RawConfigParser, it should
  1202. # be text, so decode it.
  1203. config = config.decode(sys.getfilesystemencoding())
  1204. cfg.readfp(StringIO(config))
  1205. except ConfigParser.Error:
  1206. return None
  1207. if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
  1208. return None
  1209. return cfg
  1210. finally:
  1211. f.close()
  1212. def get_exe_prefixes(exe_filename):
  1213. """Get exe->egg path translations for a given .exe file"""
  1214. prefixes = [
  1215. ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''),
  1216. ('PLATLIB/', ''),
  1217. ('SCRIPTS/', 'EGG-INFO/scripts/'),
  1218. ('DATA/lib/site-packages', ''),
  1219. ]
  1220. z = zipfile.ZipFile(exe_filename)
  1221. try:
  1222. for info in z.infolist():
  1223. name = info.filename
  1224. parts = name.split('/')
  1225. if len(parts)==3 and parts[2]=='PKG-INFO':
  1226. if parts[1].endswith('.egg-info'):
  1227. prefixes.insert(0,('/'.join(parts[:2]), 'EGG-INFO/'))
  1228. break
  1229. if len(parts) != 2 or not name.endswith('.pth'):
  1230. continue
  1231. if name.endswith('-nspkg.pth'):
  1232. continue
  1233. if parts[0].upper() in ('PURELIB','PLATLIB'):
  1234. contents = z.read(name)
  1235. if sys.version_info >= (3,):
  1236. contents = contents.decode()
  1237. for pth in yield_lines(contents):
  1238. pth = pth.strip().replace('\\','/')
  1239. if not pth.startswith('import'):
  1240. prefixes.append((('%s/%s/' % (parts[0],pth)), ''))
  1241. finally:
  1242. z.close()
  1243. prefixes = [(x.lower(),y) for x, y in prefixes]
  1244. prefixes.sort()
  1245. prefixes.reverse()
  1246. return prefixes
  1247. def parse_requirement_arg(spec):
  1248. try:
  1249. return Requirement.parse(spec)
  1250. except ValueError:
  1251. raise DistutilsError(
  1252. "Not a URL, existing file, or requirement spec: %r" % (spec,)
  1253. )
  1254. class PthDistributions(Environment):
  1255. """A .pth file with Distribution paths in it"""
  1256. dirty = False
  1257. def __init__(self, filename, sitedirs=()):
  1258. self.filename = filename
  1259. self.sitedirs = list(map(normalize_path, sitedirs))
  1260. self.basedir = normalize_path(os.path.dirname(self.filename))
  1261. self._load()
  1262. Environment.__init__(self, [], None, None)
  1263. for path in yield_lines(self.paths):
  1264. list(map(self.add, find_distributions(path, True)))
  1265. def _load(self):
  1266. self.paths = []
  1267. saw_import = False
  1268. seen = dict.fromkeys(self.sitedirs)
  1269. if os.path.isfile(self.filename):
  1270. f = open(self.filename,'rt')
  1271. for line in f:
  1272. if line.startswith('import'):
  1273. saw_import = True
  1274. continue
  1275. path = line.rstrip()
  1276. self.paths.append(path)
  1277. if not path.strip() or path.strip().startswith('#'):
  1278. continue
  1279. # skip non-existent paths, in case somebody deleted a package
  1280. # manually, and duplicate paths as well
  1281. path = self.paths[-1] = normalize_path(
  1282. os.path.join(self.basedir,path)
  1283. )
  1284. if not os.path.exists(path) or path in seen:
  1285. self.paths.pop() # skip it
  1286. self.dirty = True # we cleaned up, so we're dirty now :)
  1287. continue
  1288. seen[path] = 1
  1289. f.close()
  1290. if self.paths and not saw_import:
  1291. self.dirty = True # ensure anything we touch has import wrappers
  1292. while self.paths and not self.paths[-1].strip():
  1293. self.paths.pop()
  1294. def save(self):
  1295. """Write changed .pth file back to disk"""
  1296. if not self.dirty:
  1297. return
  1298. data = '\n'.join(map(self.make_relative,self.paths))
  1299. if data:
  1300. log.debug("Saving %s", self.filename)
  1301. data = (
  1302. "import sys; sys.__plen = len(sys.path)\n"
  1303. "%s\n"
  1304. "import sys; new=sys.path[sys.__plen:];"
  1305. " del sys.path[sys.__plen:];"
  1306. " p=getattr(sys,'__egginsert',0); sys.path[p:p]=new;"
  1307. " sys.__egginsert = p+len(new)\n"
  1308. ) % data
  1309. if os.path.islink(self.filename):
  1310. os.unlink(self.filename)
  1311. f = open(self.filename,'wt')
  1312. f.write(data)
  1313. f.close()
  1314. elif os.path.exists(self.filename):
  1315. log.debug("Deleting empty %s", self.filename)
  1316. os.unlink(self.filename)
  1317. self.dirty = False
  1318. def add(self, dist):
  1319. """Add `dist` to the distribution map"""
  1320. if (dist.location not in self.paths and (
  1321. dist.location not in self.sitedirs or
  1322. dist.location == os.getcwd() # account for '.' being in PYTHONPATH
  1323. )):
  1324. self.paths.append(dist.location)
  1325. self.dirty = True
  1326. Environment.add(self, dist)
  1327. def remove(self, dist):
  1328. """Remove `dist` from the distribution map"""
  1329. while dist.location in self.paths:
  1330. self.paths.remove(dist.location)
  1331. self.dirty = True
  1332. Environment.remove(self, dist)
  1333. def make_relative(self,path):
  1334. npath, last = os.path.split(normalize_path(path))
  1335. baselen = len(self.basedir)
  1336. parts = [last]
  1337. sep = os.altsep=='/' and '/' or os.sep
  1338. while len(npath)>=baselen:
  1339. if npath==self.basedir:
  1340. parts.append(os.curdir)
  1341. parts.reverse()
  1342. return sep.join(parts)
  1343. npath, last = os.path.split(npath)
  1344. parts.append(last)
  1345. else:
  1346. return path
  1347. def _first_line_re():
  1348. """
  1349. Return a regular expression based on first_line_re suitable for matching
  1350. strings.
  1351. """
  1352. if isinstance(first_line_re.pattern, str):
  1353. return first_line_re
  1354. # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
  1355. return re.compile(first_line_re.pattern.decode())
  1356. def get_script_header(script_text, executable=sys_executable, wininst=False):
  1357. """Create a #! line, getting options (if any) from script_text"""
  1358. first = (script_text+'\n').splitlines()[0]
  1359. match = _first_line_re().match(first)
  1360. options = ''
  1361. if match:
  1362. options = match.group(1) or ''
  1363. if options: options = ' '+options
  1364. if wininst:
  1365. executable = "python.exe"
  1366. else:
  1367. executable = nt_quote_arg(executable)
  1368. hdr = "#!%(executable)s%(options)s\n" % locals()
  1369. if not isascii(hdr):
  1370. # Non-ascii path to sys.executable, use -x to prevent warnings
  1371. if options:
  1372. if options.strip().startswith('-'):
  1373. options = ' -x'+options.strip()[1:]
  1374. # else: punt, we can't do it, let the warning happen anyway
  1375. else:
  1376. options = ' -x'
  1377. executable = fix_jython_executable(executable, options)
  1378. hdr = "#!%(executable)s%(options)s\n" % locals()
  1379. return hdr
  1380. def auto_chmod(func, arg, exc):
  1381. if func is os.remove and os.name=='nt':
  1382. chmod(arg, stat.S_IWRITE)
  1383. return func(arg)
  1384. et, ev, _ = sys.exc_info()
  1385. reraise(et, (ev[0], ev[1] + (" %s %s" % (func,arg))))
  1386. def uncache_zipdir(path):
  1387. """
  1388. Remove any globally cached zip file related data for `path`
  1389. Stale zipimport.zipimporter objects need to be removed when a zip file is
  1390. replaced as they contain cached zip file directory information. If they are
  1391. asked to get data from their zip file, they will use that cached
  1392. information to calculate the data location in the zip file. This calculated
  1393. location may be incorrect for the replaced zip file, which may in turn
  1394. cause the read operation to either fail or return incorrect data.
  1395. Note we have no way to clear any local caches from here. That is left up to
  1396. whomever is in charge of maintaining that cache.
  1397. """
  1398. normalized_path = normalize_path(path)
  1399. _uncache(normalized_path, zipimport._zip_directory_cache)
  1400. _uncache(normalized_path, sys.path_importer_cache)
  1401. def _uncache(normalized_path, cache):
  1402. to_remove = []
  1403. prefix_len = len(normalized_path)
  1404. for p in cache:
  1405. np = normalize_path(p)
  1406. if (np.startswith(normalized_path) and
  1407. np[prefix_len:prefix_len + 1] in (os.sep, '')):
  1408. to_remove.append(p)
  1409. for p in to_remove:
  1410. del cache[p]
  1411. def is_python(text, filename='<string>'):
  1412. "Is this string a valid Python script?"
  1413. try:
  1414. compile(text, filename, 'exec')
  1415. except (SyntaxError, TypeError):
  1416. return False
  1417. else:
  1418. return True
  1419. def is_sh(executable):
  1420. """Determine if the specified executable is a .sh (contains a #! line)"""
  1421. try:
  1422. fp = open(executable)
  1423. magic = fp.read(2)
  1424. fp.close()
  1425. except (OSError,IOError): return executable
  1426. return magic == '#!'
  1427. def nt_quote_arg(arg):
  1428. """Quote a command line argument according to Windows parsing rules"""
  1429. result = []
  1430. needquote = False
  1431. nb = 0
  1432. needquote = (" " in arg) or ("\t" in arg)
  1433. if needquote:
  1434. result.append('"')
  1435. for c in arg:
  1436. if c == '\\':
  1437. nb += 1
  1438. elif c == '"':
  1439. # double preceding backslashes, then add a \"
  1440. result.append('\\' * (nb*2) + '\\"')
  1441. nb = 0
  1442. else:
  1443. if nb:
  1444. result.append('\\' * nb)
  1445. nb = 0
  1446. result.append(c)
  1447. if nb:
  1448. result.append('\\' * nb)
  1449. if needquote:
  1450. result.append('\\' * nb) # double the trailing backslashes
  1451. result.append('"')
  1452. return ''.join(result)
  1453. def is_python_script(script_text, filename):
  1454. """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
  1455. """
  1456. if filename.endswith('.py') or filename.endswith('.pyw'):
  1457. return True # extension says it's Python
  1458. if is_python(script_text, filename):
  1459. return True # it's syntactically valid Python
  1460. if script_text.startswith('#!'):
  1461. # It begins with a '#!' line, so check if 'python' is in it somewhere
  1462. return 'python' in script_text.splitlines()[0].lower()
  1463. return False # Not any Python I can recognize
  1464. try:
  1465. from os import chmod as _chmod
  1466. except ImportError:
  1467. # Jython compatibility
  1468. def _chmod(*args): pass
  1469. def chmod(path, mode):
  1470. log.debug("changing mode of %s to %o", path, mode)
  1471. try:
  1472. _chmod(path, mode)
  1473. except os.error:
  1474. e = sys.exc_info()[1]
  1475. log.debug("chmod failed: %s", e)
  1476. def fix_jython_executable(executable, options):
  1477. if sys.platform.startswith('java') and is_sh(executable):
  1478. # Workaround for Jython is not needed on Linux systems.
  1479. import java
  1480. if java.lang.System.getProperty("os.name") == "Linux":
  1481. return executable
  1482. # Workaround Jython's sys.executable being a .sh (an invalid
  1483. # shebang line interpreter)
  1484. if options:
  1485. # Can't apply the workaround, leave it broken
  1486. log.warn(
  1487. "WARNING: Unable to adapt shebang line for Jython,"
  1488. " the following script is NOT executable\n"
  1489. " see http://bugs.jython.org/issue1112 for"
  1490. " more information.")
  1491. else:
  1492. return '/usr/bin/env %s' % executable
  1493. return executable
  1494. class ScriptWriter(object):
  1495. """
  1496. Encapsulates behavior around writing entry point scripts for console and
  1497. gui apps.
  1498. """
  1499. template = textwrap.dedent("""
  1500. # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r
  1501. __requires__ = %(spec)r
  1502. import sys
  1503. from pkg_resources import load_entry_point
  1504. if __name__ == '__main__':
  1505. sys.exit(
  1506. load_entry_point(%(spec)r, %(group)r, %(name)r)()
  1507. )
  1508. """).lstrip()
  1509. @classmethod
  1510. def get_script_args(cls, dist, executable=sys_executable, wininst=False):
  1511. """
  1512. Yield write_script() argument tuples for a distribution's entrypoints
  1513. """
  1514. gen_class = cls.get_writer(wininst)
  1515. spec = str(dist.as_requirement())
  1516. header = get_script_header("", executable, wininst)
  1517. for type_ in 'console', 'gui':
  1518. group = type_ + '_scripts'
  1519. for name, ep in dist.get_entry_map(group).items():
  1520. script_text = gen_class.template % locals()
  1521. for res in gen_class._get_script_args(type_, name, header,
  1522. script_text):
  1523. yield res
  1524. @classmethod
  1525. def get_writer(cls, force_windows):
  1526. if force_windows or sys.platform=='win32':
  1527. return WindowsScriptWriter.get_writer()
  1528. return cls
  1529. @classmethod
  1530. def _get_script_args(cls, type_, name, header, script_text):
  1531. # Simply write the stub with no extension.
  1532. yield (name, header+script_text)
  1533. class WindowsScriptWriter(ScriptWriter):
  1534. @classmethod
  1535. def get_writer(cls):
  1536. """
  1537. Get a script writer suitable for Windows
  1538. """
  1539. writer_lookup = dict(
  1540. executable=WindowsExecutableLauncherWriter,
  1541. natural=cls,
  1542. )
  1543. # for compatibility, use the executable launcher by default
  1544. launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')
  1545. return writer_lookup[launcher]
  1546. @classmethod
  1547. def _get_script_args(cls, type_, name, header, script_text):
  1548. "For Windows, add a .py extension"
  1549. ext = dict(console='.pya', gui='.pyw')[type_]
  1550. if ext not in os.environ['PATHEXT'].lower().split(';'):
  1551. warnings.warn("%s not listed in PATHEXT; scripts will not be "
  1552. "recognized as executables." % ext, UserWarning)
  1553. old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
  1554. old.remove(ext)
  1555. header = cls._adjust_header(type_, header)
  1556. blockers = [name+x for x in old]
  1557. yield name+ext, header+script_text, 't', blockers
  1558. @staticmethod
  1559. def _adjust_header(type_, orig_header):
  1560. """
  1561. Make sure 'pythonw' is used for gui and and 'python' is used for
  1562. console (regardless of what sys.executable is).
  1563. """
  1564. pattern = 'pythonw.exe'
  1565. repl = 'python.exe'
  1566. if type_ == 'gui':
  1567. pattern, repl = repl, pattern
  1568. pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)
  1569. new_header = pattern_ob.sub(string=orig_header, repl=repl)
  1570. clean_header = new_header[2:-1].strip('"')
  1571. if sys.platform == 'win32' and not os.path.exists(clean_header):
  1572. # the adjusted version doesn't exist, so return the original
  1573. return orig_header
  1574. return new_header
  1575. class WindowsExecutableLauncherWriter(WindowsScriptWriter):
  1576. @classmethod
  1577. def _get_script_args(cls, type_, name, header, script_text):
  1578. """
  1579. For Windows, add a .py extension and an .exe launcher
  1580. """
  1581. if type_=='gui':
  1582. launcher_type = 'gui'
  1583. ext = '-script.pyw'
  1584. old = ['.pyw']
  1585. else:
  1586. launcher_type = 'cli'
  1587. ext = '-script.py'
  1588. old = ['.py','.pyc','.pyo']
  1589. hdr = cls._adjust_header(type_, header)
  1590. blockers = [name+x for x in old]
  1591. yield (name+ext, hdr+script_text, 't', blockers)
  1592. yield (
  1593. name+'.exe', get_win_launcher(launcher_type),
  1594. 'b' # write in binary mode
  1595. )
  1596. if not is_64bit():
  1597. # install a manifest for the launcher to prevent Windows
  1598. # from detecting it as an installer (which it will for
  1599. # launchers like easy_install.exe). Consider only
  1600. # adding a manifest for launchers detected as installers.
  1601. # See Distribute #143 for details.
  1602. m_name = name + '.exe.manifest'
  1603. yield (m_name, load_launcher_manifest(name), 't')
  1604. # for backward-compatibility
  1605. get_script_args = ScriptWriter.get_script_args
  1606. def get_win_launcher(type):
  1607. """
  1608. Load the Windows launcher (executable) suitable for launching a script.
  1609. `type` should be either 'cli' or 'gui'
  1610. Returns the executable as a byte string.
  1611. """
  1612. launcher_fn = '%s.exe' % type
  1613. if platform.machine().lower()=='arm':
  1614. launcher_fn = launcher_fn.replace(".", "-arm.")
  1615. if is_64bit():
  1616. launcher_fn = launcher_fn.replace(".", "-64.")
  1617. else:
  1618. launcher_fn = launcher_fn.replace(".", "-32.")
  1619. return resource_string('setuptools', launcher_fn)
  1620. def load_launcher_manifest(name):
  1621. manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')
  1622. if sys.version_info[0] < 3:
  1623. return manifest % vars()
  1624. else:
  1625. return manifest.decode('utf-8') % vars()
  1626. def rmtree(path, ignore_errors=False, onerror=auto_chmod):
  1627. """Recursively delete a directory tree.
  1628. This code is taken from the Python 2.4 version of 'shutil', because
  1629. the 2.3 version doesn't really work right.
  1630. """
  1631. if ignore_errors:
  1632. def onerror(*args):
  1633. pass
  1634. elif onerror is None:
  1635. def onerror(*args):
  1636. raise
  1637. names = []
  1638. try:
  1639. names = os.listdir(path)
  1640. except os.error:
  1641. onerror(os.listdir, path, sys.exc_info())
  1642. for name in names:
  1643. fullname = os.path.join(path, name)
  1644. try:
  1645. mode = os.lstat(fullname).st_mode
  1646. except os.error:
  1647. mode = 0
  1648. if stat.S_ISDIR(mode):
  1649. rmtree(fullname, ignore_errors, onerror)
  1650. else:
  1651. try:
  1652. os.remove(fullname)
  1653. except os.error:
  1654. onerror(os.remove, fullname, sys.exc_info())
  1655. try:
  1656. os.rmdir(path)
  1657. except os.error:
  1658. onerror(os.rmdir, path, sys.exc_info())
  1659. def current_umask():
  1660. tmp = os.umask(0o022)
  1661. os.umask(tmp)
  1662. return tmp
  1663. def bootstrap():
  1664. # This function is called when setuptools*.egg is run using /bin/sh
  1665. import setuptools
  1666. argv0 = os.path.dirname(setuptools.__path__[0])
  1667. sys.argv[0] = argv0
  1668. sys.argv.append(argv0)
  1669. main()
  1670. def main(argv=None, **kw):
  1671. from setuptools import setup
  1672. from setuptools.dist import Distribution
  1673. import distutils.core
  1674. USAGE = """\
  1675. usage: %(script)s [options] requirement_or_url ...
  1676. or: %(script)s --help
  1677. """
  1678. def gen_usage(script_name):
  1679. return USAGE % dict(
  1680. script=os.path.basename(script_name),
  1681. )
  1682. def with_ei_usage(f):
  1683. old_gen_usage = distutils.core.gen_usage
  1684. try:
  1685. distutils.core.gen_usage = gen_usage
  1686. return f()
  1687. finally:
  1688. distutils.core.gen_usage = old_gen_usage
  1689. class DistributionWithoutHelpCommands(Distribution):
  1690. common_usage = ""
  1691. def _show_help(self,*args,**kw):
  1692. with_ei_usage(lambda: Distribution._show_help(self,*args,**kw))
  1693. if argv is None:
  1694. argv = sys.argv[1:]
  1695. with_ei_usage(lambda:
  1696. setup(
  1697. script_args = ['-q','easy_install', '-v']+argv,
  1698. script_name = sys.argv[0] or 'easy_install',
  1699. distclass=DistributionWithoutHelpCommands, **kw
  1700. )
  1701. )