virtual-bootstrap.py 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359
  1. #!/usr/bin/env python
  2. ## WARNING: This file is generated
  3. #!/usr/bin/env python
  4. """Create a "virtual" Python installation
  5. """
  6. __version__ = "12.0.7"
  7. virtualenv_version = __version__ # legacy
  8. import base64
  9. import sys
  10. import os
  11. import codecs
  12. import optparse
  13. import re
  14. import shutil
  15. import logging
  16. import tempfile
  17. import zlib
  18. import errno
  19. import glob
  20. import distutils.sysconfig
  21. from distutils.util import strtobool
  22. import struct
  23. import subprocess
  24. import tarfile
  25. if sys.version_info < (2, 6):
  26. print('ERROR: %s' % sys.exc_info()[1])
  27. print('ERROR: this script requires Python 2.6 or greater.')
  28. sys.exit(101)
  29. try:
  30. basestring
  31. except NameError:
  32. basestring = str
  33. try:
  34. import ConfigParser
  35. except ImportError:
  36. import configparser as ConfigParser
  37. join = os.path.join
  38. py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1])
  39. is_jython = sys.platform.startswith('java')
  40. is_pypy = hasattr(sys, 'pypy_version_info')
  41. is_win = (sys.platform == 'win32')
  42. is_cygwin = (sys.platform == 'cygwin')
  43. is_darwin = (sys.platform == 'darwin')
  44. abiflags = getattr(sys, 'abiflags', '')
  45. user_dir = os.path.expanduser('~')
  46. if is_win:
  47. default_storage_dir = os.path.join(user_dir, 'virtualenv')
  48. else:
  49. default_storage_dir = os.path.join(user_dir, '.virtualenv')
  50. default_config_file = os.path.join(default_storage_dir, 'virtualenv.ini')
  51. if is_pypy:
  52. expected_exe = 'pypy'
  53. elif is_jython:
  54. expected_exe = 'jython'
  55. else:
  56. expected_exe = 'python'
  57. # Return a mapping of version -> Python executable
  58. # Only provided for Windows, where the information in the registry is used
  59. if not is_win:
  60. def get_installed_pythons():
  61. return {}
  62. else:
  63. try:
  64. import winreg
  65. except ImportError:
  66. import _winreg as winreg
  67. def get_installed_pythons():
  68. try:
  69. python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE,
  70. "Software\\Python\\PythonCore")
  71. except WindowsError:
  72. # No registered Python installations
  73. return {}
  74. i = 0
  75. versions = []
  76. while True:
  77. try:
  78. versions.append(winreg.EnumKey(python_core, i))
  79. i = i + 1
  80. except WindowsError:
  81. break
  82. exes = dict()
  83. for ver in versions:
  84. try:
  85. path = winreg.QueryValue(python_core, "%s\\InstallPath" % ver)
  86. except WindowsError:
  87. continue
  88. exes[ver] = join(path, "python.exe")
  89. winreg.CloseKey(python_core)
  90. # Add the major versions
  91. # Sort the keys, then repeatedly update the major version entry
  92. # Last executable (i.e., highest version) wins with this approach
  93. for ver in sorted(exes):
  94. exes[ver[0]] = exes[ver]
  95. return exes
  96. REQUIRED_MODULES = ['os', 'posix', 'posixpath', 'nt', 'ntpath', 'genericpath',
  97. 'fnmatch', 'locale', 'encodings', 'codecs',
  98. 'stat', 'UserDict', 'readline', 'copy_reg', 'types',
  99. 're', 'sre', 'sre_parse', 'sre_constants', 'sre_compile',
  100. 'zlib']
  101. REQUIRED_FILES = ['lib-dynload', 'config']
  102. majver, minver = sys.version_info[:2]
  103. if majver == 2:
  104. if minver >= 6:
  105. REQUIRED_MODULES.extend(['warnings', 'linecache', '_abcoll', 'abc'])
  106. if minver >= 7:
  107. REQUIRED_MODULES.extend(['_weakrefset'])
  108. elif majver == 3:
  109. # Some extra modules are needed for Python 3, but different ones
  110. # for different versions.
  111. REQUIRED_MODULES.extend(['_abcoll', 'warnings', 'linecache', 'abc', 'io',
  112. '_weakrefset', 'copyreg', 'tempfile', 'random',
  113. '__future__', 'collections', 'keyword', 'tarfile',
  114. 'shutil', 'struct', 'copy', 'tokenize', 'token',
  115. 'functools', 'heapq', 'bisect', 'weakref',
  116. 'reprlib'])
  117. if minver >= 2:
  118. REQUIRED_FILES[-1] = 'config-%s' % majver
  119. if minver >= 3:
  120. import sysconfig
  121. platdir = sysconfig.get_config_var('PLATDIR')
  122. REQUIRED_FILES.append(platdir)
  123. # The whole list of 3.3 modules is reproduced below - the current
  124. # uncommented ones are required for 3.3 as of now, but more may be
  125. # added as 3.3 development continues.
  126. REQUIRED_MODULES.extend([
  127. #"aifc",
  128. #"antigravity",
  129. #"argparse",
  130. #"ast",
  131. #"asynchat",
  132. #"asyncore",
  133. "base64",
  134. #"bdb",
  135. #"binhex",
  136. #"bisect",
  137. #"calendar",
  138. #"cgi",
  139. #"cgitb",
  140. #"chunk",
  141. #"cmd",
  142. #"codeop",
  143. #"code",
  144. #"colorsys",
  145. #"_compat_pickle",
  146. #"compileall",
  147. #"concurrent",
  148. #"configparser",
  149. #"contextlib",
  150. #"cProfile",
  151. #"crypt",
  152. #"csv",
  153. #"ctypes",
  154. #"curses",
  155. #"datetime",
  156. #"dbm",
  157. #"decimal",
  158. #"difflib",
  159. #"dis",
  160. #"doctest",
  161. #"dummy_threading",
  162. "_dummy_thread",
  163. #"email",
  164. #"filecmp",
  165. #"fileinput",
  166. #"formatter",
  167. #"fractions",
  168. #"ftplib",
  169. #"functools",
  170. #"getopt",
  171. #"getpass",
  172. #"gettext",
  173. #"glob",
  174. #"gzip",
  175. "hashlib",
  176. #"heapq",
  177. "hmac",
  178. #"html",
  179. #"http",
  180. #"idlelib",
  181. #"imaplib",
  182. #"imghdr",
  183. "imp",
  184. "importlib",
  185. #"inspect",
  186. #"json",
  187. #"lib2to3",
  188. #"logging",
  189. #"macpath",
  190. #"macurl2path",
  191. #"mailbox",
  192. #"mailcap",
  193. #"_markupbase",
  194. #"mimetypes",
  195. #"modulefinder",
  196. #"multiprocessing",
  197. #"netrc",
  198. #"nntplib",
  199. #"nturl2path",
  200. #"numbers",
  201. #"opcode",
  202. #"optparse",
  203. #"os2emxpath",
  204. #"pdb",
  205. #"pickle",
  206. #"pickletools",
  207. #"pipes",
  208. #"pkgutil",
  209. #"platform",
  210. #"plat-linux2",
  211. #"plistlib",
  212. #"poplib",
  213. #"pprint",
  214. #"profile",
  215. #"pstats",
  216. #"pty",
  217. #"pyclbr",
  218. #"py_compile",
  219. #"pydoc_data",
  220. #"pydoc",
  221. #"_pyio",
  222. #"queue",
  223. #"quopri",
  224. #"reprlib",
  225. "rlcompleter",
  226. #"runpy",
  227. #"sched",
  228. #"shelve",
  229. #"shlex",
  230. #"smtpd",
  231. #"smtplib",
  232. #"sndhdr",
  233. #"socket",
  234. #"socketserver",
  235. #"sqlite3",
  236. #"ssl",
  237. #"stringprep",
  238. #"string",
  239. #"_strptime",
  240. #"subprocess",
  241. #"sunau",
  242. #"symbol",
  243. #"symtable",
  244. #"sysconfig",
  245. #"tabnanny",
  246. #"telnetlib",
  247. #"test",
  248. #"textwrap",
  249. #"this",
  250. #"_threading_local",
  251. #"threading",
  252. #"timeit",
  253. #"tkinter",
  254. #"tokenize",
  255. #"token",
  256. #"traceback",
  257. #"trace",
  258. #"tty",
  259. #"turtledemo",
  260. #"turtle",
  261. #"unittest",
  262. #"urllib",
  263. #"uuid",
  264. #"uu",
  265. #"wave",
  266. #"weakref",
  267. #"webbrowser",
  268. #"wsgiref",
  269. #"xdrlib",
  270. #"xml",
  271. #"xmlrpc",
  272. #"zipfile",
  273. ])
  274. if minver >= 4:
  275. REQUIRED_MODULES.extend([
  276. 'operator',
  277. '_collections_abc',
  278. '_bootlocale',
  279. ])
  280. if is_pypy:
  281. # these are needed to correctly display the exceptions that may happen
  282. # during the bootstrap
  283. REQUIRED_MODULES.extend(['traceback', 'linecache'])
  284. class Logger(object):
  285. """
  286. Logging object for use in command-line script. Allows ranges of
  287. levels, to avoid some redundancy of displayed information.
  288. """
  289. DEBUG = logging.DEBUG
  290. INFO = logging.INFO
  291. NOTIFY = (logging.INFO+logging.WARN)/2
  292. WARN = WARNING = logging.WARN
  293. ERROR = logging.ERROR
  294. FATAL = logging.FATAL
  295. LEVELS = [DEBUG, INFO, NOTIFY, WARN, ERROR, FATAL]
  296. def __init__(self, consumers):
  297. self.consumers = consumers
  298. self.indent = 0
  299. self.in_progress = None
  300. self.in_progress_hanging = False
  301. def debug(self, msg, *args, **kw):
  302. self.log(self.DEBUG, msg, *args, **kw)
  303. def info(self, msg, *args, **kw):
  304. self.log(self.INFO, msg, *args, **kw)
  305. def notify(self, msg, *args, **kw):
  306. self.log(self.NOTIFY, msg, *args, **kw)
  307. def warn(self, msg, *args, **kw):
  308. self.log(self.WARN, msg, *args, **kw)
  309. def error(self, msg, *args, **kw):
  310. self.log(self.ERROR, msg, *args, **kw)
  311. def fatal(self, msg, *args, **kw):
  312. self.log(self.FATAL, msg, *args, **kw)
  313. def log(self, level, msg, *args, **kw):
  314. if args:
  315. if kw:
  316. raise TypeError(
  317. "You may give positional or keyword arguments, not both")
  318. args = args or kw
  319. rendered = None
  320. for consumer_level, consumer in self.consumers:
  321. if self.level_matches(level, consumer_level):
  322. if (self.in_progress_hanging
  323. and consumer in (sys.stdout, sys.stderr)):
  324. self.in_progress_hanging = False
  325. sys.stdout.write('\n')
  326. sys.stdout.flush()
  327. if rendered is None:
  328. if args:
  329. rendered = msg % args
  330. else:
  331. rendered = msg
  332. rendered = ' '*self.indent + rendered
  333. if hasattr(consumer, 'write'):
  334. consumer.write(rendered+'\n')
  335. else:
  336. consumer(rendered)
  337. def start_progress(self, msg):
  338. assert not self.in_progress, (
  339. "Tried to start_progress(%r) while in_progress %r"
  340. % (msg, self.in_progress))
  341. if self.level_matches(self.NOTIFY, self._stdout_level()):
  342. sys.stdout.write(msg)
  343. sys.stdout.flush()
  344. self.in_progress_hanging = True
  345. else:
  346. self.in_progress_hanging = False
  347. self.in_progress = msg
  348. def end_progress(self, msg='done.'):
  349. assert self.in_progress, (
  350. "Tried to end_progress without start_progress")
  351. if self.stdout_level_matches(self.NOTIFY):
  352. if not self.in_progress_hanging:
  353. # Some message has been printed out since start_progress
  354. sys.stdout.write('...' + self.in_progress + msg + '\n')
  355. sys.stdout.flush()
  356. else:
  357. sys.stdout.write(msg + '\n')
  358. sys.stdout.flush()
  359. self.in_progress = None
  360. self.in_progress_hanging = False
  361. def show_progress(self):
  362. """If we are in a progress scope, and no log messages have been
  363. shown, write out another '.'"""
  364. if self.in_progress_hanging:
  365. sys.stdout.write('.')
  366. sys.stdout.flush()
  367. def stdout_level_matches(self, level):
  368. """Returns true if a message at this level will go to stdout"""
  369. return self.level_matches(level, self._stdout_level())
  370. def _stdout_level(self):
  371. """Returns the level that stdout runs at"""
  372. for level, consumer in self.consumers:
  373. if consumer is sys.stdout:
  374. return level
  375. return self.FATAL
  376. def level_matches(self, level, consumer_level):
  377. """
  378. >>> l = Logger([])
  379. >>> l.level_matches(3, 4)
  380. False
  381. >>> l.level_matches(3, 2)
  382. True
  383. >>> l.level_matches(slice(None, 3), 3)
  384. False
  385. >>> l.level_matches(slice(None, 3), 2)
  386. True
  387. >>> l.level_matches(slice(1, 3), 1)
  388. True
  389. >>> l.level_matches(slice(2, 3), 1)
  390. False
  391. """
  392. if isinstance(level, slice):
  393. start, stop = level.start, level.stop
  394. if start is not None and start > consumer_level:
  395. return False
  396. if stop is not None and stop <= consumer_level:
  397. return False
  398. return True
  399. else:
  400. return level >= consumer_level
  401. #@classmethod
  402. def level_for_integer(cls, level):
  403. levels = cls.LEVELS
  404. if level < 0:
  405. return levels[0]
  406. if level >= len(levels):
  407. return levels[-1]
  408. return levels[level]
  409. level_for_integer = classmethod(level_for_integer)
  410. # create a silent logger just to prevent this from being undefined
  411. # will be overridden with requested verbosity main() is called.
  412. logger = Logger([(Logger.LEVELS[-1], sys.stdout)])
  413. def mkdir(path):
  414. if not os.path.exists(path):
  415. logger.info('Creating %s', path)
  416. os.makedirs(path)
  417. else:
  418. logger.info('Directory %s already exists', path)
  419. def copyfileordir(src, dest, symlink=True):
  420. if os.path.isdir(src):
  421. shutil.copytree(src, dest, symlink)
  422. else:
  423. shutil.copy2(src, dest)
  424. def copyfile(src, dest, symlink=True):
  425. if not os.path.exists(src):
  426. # Some bad symlink in the src
  427. logger.warn('Cannot find file %s (bad symlink)', src)
  428. return
  429. if os.path.exists(dest):
  430. logger.debug('File %s already exists', dest)
  431. return
  432. if not os.path.exists(os.path.dirname(dest)):
  433. logger.info('Creating parent directories for %s', os.path.dirname(dest))
  434. os.makedirs(os.path.dirname(dest))
  435. if not os.path.islink(src):
  436. srcpath = os.path.abspath(src)
  437. else:
  438. srcpath = os.readlink(src)
  439. if symlink and hasattr(os, 'symlink') and not is_win:
  440. logger.info('Symlinking %s', dest)
  441. try:
  442. os.symlink(srcpath, dest)
  443. except (OSError, NotImplementedError):
  444. logger.info('Symlinking failed, copying to %s', dest)
  445. copyfileordir(src, dest, symlink)
  446. else:
  447. logger.info('Copying to %s', dest)
  448. copyfileordir(src, dest, symlink)
  449. def writefile(dest, content, overwrite=True):
  450. if not os.path.exists(dest):
  451. logger.info('Writing %s', dest)
  452. f = open(dest, 'wb')
  453. f.write(content.encode('utf-8'))
  454. f.close()
  455. return
  456. else:
  457. f = open(dest, 'rb')
  458. c = f.read()
  459. f.close()
  460. if c != content.encode("utf-8"):
  461. if not overwrite:
  462. logger.notify('File %s exists with different content; not overwriting', dest)
  463. return
  464. logger.notify('Overwriting %s with new content', dest)
  465. f = open(dest, 'wb')
  466. f.write(content.encode('utf-8'))
  467. f.close()
  468. else:
  469. logger.info('Content %s already in place', dest)
  470. def rmtree(dir):
  471. if os.path.exists(dir):
  472. logger.notify('Deleting tree %s', dir)
  473. shutil.rmtree(dir)
  474. else:
  475. logger.info('Do not need to delete %s; already gone', dir)
  476. def make_exe(fn):
  477. if hasattr(os, 'chmod'):
  478. oldmode = os.stat(fn).st_mode & 0xFFF # 0o7777
  479. newmode = (oldmode | 0x16D) & 0xFFF # 0o555, 0o7777
  480. os.chmod(fn, newmode)
  481. logger.info('Changed mode of %s to %s', fn, oct(newmode))
  482. def _find_file(filename, dirs):
  483. for dir in reversed(dirs):
  484. files = glob.glob(os.path.join(dir, filename))
  485. if files and os.path.isfile(files[0]):
  486. return True, files[0]
  487. return False, filename
  488. def file_search_dirs():
  489. here = os.path.dirname(os.path.abspath(__file__))
  490. dirs = ['.', here,
  491. join(here, 'virtualenv_support')]
  492. if os.path.splitext(os.path.dirname(__file__))[0] != 'virtualenv':
  493. # Probably some boot script; just in case virtualenv is installed...
  494. try:
  495. import virtualenv
  496. except ImportError:
  497. pass
  498. else:
  499. dirs.append(os.path.join(os.path.dirname(virtualenv.__file__), 'virtualenv_support'))
  500. return [d for d in dirs if os.path.isdir(d)]
  501. class UpdatingDefaultsHelpFormatter(optparse.IndentedHelpFormatter):
  502. """
  503. Custom help formatter for use in ConfigOptionParser that updates
  504. the defaults before expanding them, allowing them to show up correctly
  505. in the help listing
  506. """
  507. def expand_default(self, option):
  508. if self.parser is not None:
  509. self.parser.update_defaults(self.parser.defaults)
  510. return optparse.IndentedHelpFormatter.expand_default(self, option)
  511. class ConfigOptionParser(optparse.OptionParser):
  512. """
  513. Custom option parser which updates its defaults by checking the
  514. configuration files and environmental variables
  515. """
  516. def __init__(self, *args, **kwargs):
  517. self.config = ConfigParser.RawConfigParser()
  518. self.files = self.get_config_files()
  519. self.config.read(self.files)
  520. optparse.OptionParser.__init__(self, *args, **kwargs)
  521. def get_config_files(self):
  522. config_file = os.environ.get('VIRTUALENV_CONFIG_FILE', False)
  523. if config_file and os.path.exists(config_file):
  524. return [config_file]
  525. return [default_config_file]
  526. def update_defaults(self, defaults):
  527. """
  528. Updates the given defaults with values from the config files and
  529. the environ. Does a little special handling for certain types of
  530. options (lists).
  531. """
  532. # Then go and look for the other sources of configuration:
  533. config = {}
  534. # 1. config files
  535. config.update(dict(self.get_config_section('virtualenv')))
  536. # 2. environmental variables
  537. config.update(dict(self.get_environ_vars()))
  538. # Then set the options with those values
  539. for key, val in config.items():
  540. key = key.replace('_', '-')
  541. if not key.startswith('--'):
  542. key = '--%s' % key # only prefer long opts
  543. option = self.get_option(key)
  544. if option is not None:
  545. # ignore empty values
  546. if not val:
  547. continue
  548. # handle multiline configs
  549. if option.action == 'append':
  550. val = val.split()
  551. else:
  552. option.nargs = 1
  553. if option.action == 'store_false':
  554. val = not strtobool(val)
  555. elif option.action in ('store_true', 'count'):
  556. val = strtobool(val)
  557. try:
  558. val = option.convert_value(key, val)
  559. except optparse.OptionValueError:
  560. e = sys.exc_info()[1]
  561. print("An error occurred during configuration: %s" % e)
  562. sys.exit(3)
  563. defaults[option.dest] = val
  564. return defaults
  565. def get_config_section(self, name):
  566. """
  567. Get a section of a configuration
  568. """
  569. if self.config.has_section(name):
  570. return self.config.items(name)
  571. return []
  572. def get_environ_vars(self, prefix='VIRTUALENV_'):
  573. """
  574. Returns a generator with all environmental vars with prefix VIRTUALENV
  575. """
  576. for key, val in os.environ.items():
  577. if key.startswith(prefix):
  578. yield (key.replace(prefix, '').lower(), val)
  579. def get_default_values(self):
  580. """
  581. Overridding to make updating the defaults after instantiation of
  582. the option parser possible, update_defaults() does the dirty work.
  583. """
  584. if not self.process_default_values:
  585. # Old, pre-Optik 1.5 behaviour.
  586. return optparse.Values(self.defaults)
  587. defaults = self.update_defaults(self.defaults.copy()) # ours
  588. for option in self._get_all_options():
  589. default = defaults.get(option.dest)
  590. if isinstance(default, basestring):
  591. opt_str = option.get_opt_string()
  592. defaults[option.dest] = option.check_value(opt_str, default)
  593. return optparse.Values(defaults)
  594. def main():
  595. parser = ConfigOptionParser(
  596. version=virtualenv_version,
  597. usage="%prog [OPTIONS] DEST_DIR",
  598. formatter=UpdatingDefaultsHelpFormatter())
  599. parser.add_option(
  600. '-v', '--verbose',
  601. action='count',
  602. dest='verbose',
  603. default=0,
  604. help="Increase verbosity.")
  605. parser.add_option(
  606. '-q', '--quiet',
  607. action='count',
  608. dest='quiet',
  609. default=0,
  610. help='Decrease verbosity.')
  611. parser.add_option(
  612. '-p', '--python',
  613. dest='python',
  614. metavar='PYTHON_EXE',
  615. help='The Python interpreter to use, e.g., --python=python2.5 will use the python2.5 '
  616. 'interpreter to create the new environment. The default is the interpreter that '
  617. 'virtualenv was installed with (%s)' % sys.executable)
  618. parser.add_option(
  619. '--clear',
  620. dest='clear',
  621. action='store_true',
  622. help="Clear out the non-root install and start from scratch.")
  623. parser.set_defaults(system_site_packages=False)
  624. parser.add_option(
  625. '--no-site-packages',
  626. dest='system_site_packages',
  627. action='store_false',
  628. help="DEPRECATED. Retained only for backward compatibility. "
  629. "Not having access to global site-packages is now the default behavior.")
  630. parser.add_option(
  631. '--system-site-packages',
  632. dest='system_site_packages',
  633. action='store_true',
  634. help="Give the virtual environment access to the global site-packages.")
  635. parser.add_option(
  636. '--always-copy',
  637. dest='symlink',
  638. action='store_false',
  639. default=True,
  640. help="Always copy files rather than symlinking.")
  641. parser.add_option(
  642. '--unzip-setuptools',
  643. dest='unzip_setuptools',
  644. action='store_true',
  645. help="Unzip Setuptools when installing it.")
  646. parser.add_option(
  647. '--relocatable',
  648. dest='relocatable',
  649. action='store_true',
  650. help='Make an EXISTING virtualenv environment relocatable. '
  651. 'This fixes up scripts and makes all .pth files relative.')
  652. parser.add_option(
  653. '--no-setuptools',
  654. dest='no_setuptools',
  655. action='store_true',
  656. help='Do not install setuptools (or pip) in the new virtualenv.')
  657. parser.add_option(
  658. '--no-pip',
  659. dest='no_pip',
  660. action='store_true',
  661. help='Do not install pip in the new virtualenv.')
  662. default_search_dirs = file_search_dirs()
  663. parser.add_option(
  664. '--extra-search-dir',
  665. dest="search_dirs",
  666. action="append",
  667. metavar='DIR',
  668. default=default_search_dirs,
  669. help="Directory to look for setuptools/pip distributions in. "
  670. "This option can be used multiple times.")
  671. parser.add_option(
  672. '--never-download',
  673. dest="never_download",
  674. action="store_true",
  675. default=True,
  676. help="DEPRECATED. Retained only for backward compatibility. This option has no effect. "
  677. "Virtualenv never downloads pip or setuptools.")
  678. parser.add_option(
  679. '--prompt',
  680. dest='prompt',
  681. help='Provides an alternative prompt prefix for this environment.')
  682. parser.add_option(
  683. '--setuptools',
  684. dest='setuptools',
  685. action='store_true',
  686. help="DEPRECATED. Retained only for backward compatibility. This option has no effect.")
  687. parser.add_option(
  688. '--distribute',
  689. dest='distribute',
  690. action='store_true',
  691. help="DEPRECATED. Retained only for backward compatibility. This option has no effect.")
  692. if 'extend_parser' in globals():
  693. extend_parser(parser)
  694. options, args = parser.parse_args()
  695. global logger
  696. if 'adjust_options' in globals():
  697. adjust_options(options, args)
  698. verbosity = options.verbose - options.quiet
  699. logger = Logger([(Logger.level_for_integer(2 - verbosity), sys.stdout)])
  700. if options.python and not os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'):
  701. env = os.environ.copy()
  702. interpreter = resolve_interpreter(options.python)
  703. if interpreter == sys.executable:
  704. logger.warn('Already using interpreter %s' % interpreter)
  705. else:
  706. logger.notify('Running virtualenv with interpreter %s' % interpreter)
  707. env['VIRTUALENV_INTERPRETER_RUNNING'] = 'true'
  708. file = __file__
  709. if file.endswith('.pyc'):
  710. file = file[:-1]
  711. popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env)
  712. raise SystemExit(popen.wait())
  713. if not args:
  714. print('You must provide a DEST_DIR')
  715. parser.print_help()
  716. sys.exit(2)
  717. if len(args) > 1:
  718. print('There must be only one argument: DEST_DIR (you gave %s)' % (
  719. ' '.join(args)))
  720. parser.print_help()
  721. sys.exit(2)
  722. home_dir = args[0]
  723. if os.environ.get('WORKING_ENV'):
  724. logger.fatal('ERROR: you cannot run virtualenv while in a workingenv')
  725. logger.fatal('Please deactivate your workingenv, then re-run this script')
  726. sys.exit(3)
  727. if 'PYTHONHOME' in os.environ:
  728. logger.warn('PYTHONHOME is set. You *must* activate the virtualenv before using it')
  729. del os.environ['PYTHONHOME']
  730. if options.relocatable:
  731. make_environment_relocatable(home_dir)
  732. return
  733. if not options.never_download:
  734. logger.warn('The --never-download option is for backward compatibility only.')
  735. logger.warn('Setting it to false is no longer supported, and will be ignored.')
  736. create_environment(home_dir,
  737. site_packages=options.system_site_packages,
  738. clear=options.clear,
  739. unzip_setuptools=options.unzip_setuptools,
  740. prompt=options.prompt,
  741. search_dirs=options.search_dirs,
  742. never_download=True,
  743. no_setuptools=options.no_setuptools,
  744. no_pip=options.no_pip,
  745. symlink=options.symlink)
  746. if 'after_install' in globals():
  747. after_install(options, home_dir)
  748. def call_subprocess(cmd, show_stdout=True,
  749. filter_stdout=None, cwd=None,
  750. raise_on_returncode=True, extra_env=None,
  751. remove_from_env=None):
  752. cmd_parts = []
  753. for part in cmd:
  754. if len(part) > 45:
  755. part = part[:20]+"..."+part[-20:]
  756. if ' ' in part or '\n' in part or '"' in part or "'" in part:
  757. part = '"%s"' % part.replace('"', '\\"')
  758. if hasattr(part, 'decode'):
  759. try:
  760. part = part.decode(sys.getdefaultencoding())
  761. except UnicodeDecodeError:
  762. part = part.decode(sys.getfilesystemencoding())
  763. cmd_parts.append(part)
  764. cmd_desc = ' '.join(cmd_parts)
  765. if show_stdout:
  766. stdout = None
  767. else:
  768. stdout = subprocess.PIPE
  769. logger.debug("Running command %s" % cmd_desc)
  770. if extra_env or remove_from_env:
  771. env = os.environ.copy()
  772. if extra_env:
  773. env.update(extra_env)
  774. if remove_from_env:
  775. for varname in remove_from_env:
  776. env.pop(varname, None)
  777. else:
  778. env = None
  779. try:
  780. proc = subprocess.Popen(
  781. cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
  782. cwd=cwd, env=env)
  783. except Exception:
  784. e = sys.exc_info()[1]
  785. logger.fatal(
  786. "Error %s while executing command %s" % (e, cmd_desc))
  787. raise
  788. all_output = []
  789. if stdout is not None:
  790. stdout = proc.stdout
  791. encoding = sys.getdefaultencoding()
  792. fs_encoding = sys.getfilesystemencoding()
  793. while 1:
  794. line = stdout.readline()
  795. try:
  796. line = line.decode(encoding)
  797. except UnicodeDecodeError:
  798. line = line.decode(fs_encoding)
  799. if not line:
  800. break
  801. line = line.rstrip()
  802. all_output.append(line)
  803. if filter_stdout:
  804. level = filter_stdout(line)
  805. if isinstance(level, tuple):
  806. level, line = level
  807. logger.log(level, line)
  808. if not logger.stdout_level_matches(level):
  809. logger.show_progress()
  810. else:
  811. logger.info(line)
  812. else:
  813. proc.communicate()
  814. proc.wait()
  815. if proc.returncode:
  816. if raise_on_returncode:
  817. if all_output:
  818. logger.notify('Complete output from command %s:' % cmd_desc)
  819. logger.notify('\n'.join(all_output) + '\n----------------------------------------')
  820. raise OSError(
  821. "Command %s failed with error code %s"
  822. % (cmd_desc, proc.returncode))
  823. else:
  824. logger.warn(
  825. "Command %s had error code %s"
  826. % (cmd_desc, proc.returncode))
  827. def filter_install_output(line):
  828. if line.strip().startswith('running'):
  829. return Logger.INFO
  830. return Logger.DEBUG
  831. def find_wheels(projects, search_dirs):
  832. """Find wheels from which we can import PROJECTS.
  833. Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
  834. a list of the first wheel found for each PROJECT
  835. """
  836. wheels = []
  837. # Look through SEARCH_DIRS for the first suitable wheel. Don't bother
  838. # about version checking here, as this is simply to get something we can
  839. # then use to install the correct version.
  840. for project in projects:
  841. for dirname in search_dirs:
  842. # This relies on only having "universal" wheels available.
  843. # The pattern could be tightened to require -py2.py3-none-any.whl.
  844. files = glob.glob(os.path.join(dirname, project + '-*.whl'))
  845. if files:
  846. wheels.append(os.path.abspath(files[0]))
  847. break
  848. else:
  849. # We're out of luck, so quit with a suitable error
  850. logger.fatal('Cannot find a wheel for %s' % (project,))
  851. return wheels
  852. def install_wheel(project_names, py_executable, search_dirs=None):
  853. if search_dirs is None:
  854. search_dirs = file_search_dirs()
  855. wheels = find_wheels(['setuptools', 'pip'], search_dirs)
  856. pythonpath = os.pathsep.join(wheels)
  857. findlinks = ' '.join(search_dirs)
  858. cmd = [
  859. py_executable, '-c',
  860. 'import sys, pip; sys.exit(pip.main(["install", "--ignore-installed"] + sys.argv[1:]))',
  861. ] + project_names
  862. logger.start_progress('Installing %s...' % (', '.join(project_names)))
  863. logger.indent += 2
  864. try:
  865. call_subprocess(cmd, show_stdout=False,
  866. extra_env = {
  867. 'PYTHONPATH': pythonpath,
  868. 'PIP_FIND_LINKS': findlinks,
  869. 'PIP_USE_WHEEL': '1',
  870. 'PIP_PRE': '1',
  871. 'PIP_NO_INDEX': '1'
  872. }
  873. )
  874. finally:
  875. logger.indent -= 2
  876. logger.end_progress()
  877. def create_environment(home_dir, site_packages=False, clear=False,
  878. unzip_setuptools=False,
  879. prompt=None, search_dirs=None, never_download=False,
  880. no_setuptools=False, no_pip=False, symlink=True):
  881. """
  882. Creates a new environment in ``home_dir``.
  883. If ``site_packages`` is true, then the global ``site-packages/``
  884. directory will be on the path.
  885. If ``clear`` is true (default False) then the environment will
  886. first be cleared.
  887. """
  888. home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
  889. py_executable = os.path.abspath(install_python(
  890. home_dir, lib_dir, inc_dir, bin_dir,
  891. site_packages=site_packages, clear=clear, symlink=symlink))
  892. install_distutils(home_dir)
  893. if not no_setuptools:
  894. to_install = ['setuptools']
  895. if not no_pip:
  896. to_install.append('pip')
  897. install_wheel(to_install, py_executable, search_dirs)
  898. install_activate(home_dir, bin_dir, prompt)
  899. def is_executable_file(fpath):
  900. return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  901. def path_locations(home_dir):
  902. """Return the path locations for the environment (where libraries are,
  903. where scripts go, etc)"""
  904. # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its
  905. # prefix arg is broken: http://bugs.python.org/issue3386
  906. if is_win:
  907. # Windows has lots of problems with executables with spaces in
  908. # the name; this function will remove them (using the ~1
  909. # format):
  910. mkdir(home_dir)
  911. if ' ' in home_dir:
  912. import ctypes
  913. GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW
  914. size = max(len(home_dir)+1, 256)
  915. buf = ctypes.create_unicode_buffer(size)
  916. try:
  917. u = unicode
  918. except NameError:
  919. u = str
  920. ret = GetShortPathName(u(home_dir), buf, size)
  921. if not ret:
  922. print('Error: the path "%s" has a space in it' % home_dir)
  923. print('We could not determine the short pathname for it.')
  924. print('Exiting.')
  925. sys.exit(3)
  926. home_dir = str(buf.value)
  927. lib_dir = join(home_dir, 'Lib')
  928. inc_dir = join(home_dir, 'Include')
  929. bin_dir = join(home_dir, 'Scripts')
  930. if is_jython:
  931. lib_dir = join(home_dir, 'Lib')
  932. inc_dir = join(home_dir, 'Include')
  933. bin_dir = join(home_dir, 'bin')
  934. elif is_pypy:
  935. lib_dir = home_dir
  936. inc_dir = join(home_dir, 'include')
  937. bin_dir = join(home_dir, 'bin')
  938. elif not is_win:
  939. lib_dir = join(home_dir, 'lib', py_version)
  940. multiarch_exec = '/usr/bin/multiarch-platform'
  941. if is_executable_file(multiarch_exec):
  942. # In Mageia (2) and Mandriva distros the include dir must be like:
  943. # virtualenv/include/multiarch-x86_64-linux/python2.7
  944. # instead of being virtualenv/include/python2.7
  945. p = subprocess.Popen(multiarch_exec, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  946. stdout, stderr = p.communicate()
  947. # stdout.strip is needed to remove newline character
  948. inc_dir = join(home_dir, 'include', stdout.strip(), py_version + abiflags)
  949. else:
  950. inc_dir = join(home_dir, 'include', py_version + abiflags)
  951. bin_dir = join(home_dir, 'bin')
  952. return home_dir, lib_dir, inc_dir, bin_dir
  953. def change_prefix(filename, dst_prefix):
  954. prefixes = [sys.prefix]
  955. if is_darwin:
  956. prefixes.extend((
  957. os.path.join("/Library/Python", sys.version[:3], "site-packages"),
  958. os.path.join(sys.prefix, "Extras", "lib", "python"),
  959. os.path.join("~", "Library", "Python", sys.version[:3], "site-packages"),
  960. # Python 2.6 no-frameworks
  961. os.path.join("~", ".local", "lib","python", sys.version[:3], "site-packages"),
  962. # System Python 2.7 on OSX Mountain Lion
  963. os.path.join("~", "Library", "Python", sys.version[:3], "lib", "python", "site-packages")))
  964. if hasattr(sys, 'real_prefix'):
  965. prefixes.append(sys.real_prefix)
  966. if hasattr(sys, 'base_prefix'):
  967. prefixes.append(sys.base_prefix)
  968. prefixes = list(map(os.path.expanduser, prefixes))
  969. prefixes = list(map(os.path.abspath, prefixes))
  970. # Check longer prefixes first so we don't split in the middle of a filename
  971. prefixes = sorted(prefixes, key=len, reverse=True)
  972. filename = os.path.abspath(filename)
  973. for src_prefix in prefixes:
  974. if filename.startswith(src_prefix):
  975. _, relpath = filename.split(src_prefix, 1)
  976. if src_prefix != os.sep: # sys.prefix == "/"
  977. assert relpath[0] == os.sep
  978. relpath = relpath[1:]
  979. return join(dst_prefix, relpath)
  980. assert False, "Filename %s does not start with any of these prefixes: %s" % \
  981. (filename, prefixes)
  982. def copy_required_modules(dst_prefix, symlink):
  983. import imp
  984. # If we are running under -p, we need to remove the current
  985. # directory from sys.path temporarily here, so that we
  986. # definitely get the modules from the site directory of
  987. # the interpreter we are running under, not the one
  988. # virtualenv.py is installed under (which might lead to py2/py3
  989. # incompatibility issues)
  990. _prev_sys_path = sys.path
  991. if os.environ.get('VIRTUALENV_INTERPRETER_RUNNING'):
  992. sys.path = sys.path[1:]
  993. try:
  994. for modname in REQUIRED_MODULES:
  995. if modname in sys.builtin_module_names:
  996. logger.info("Ignoring built-in bootstrap module: %s" % modname)
  997. continue
  998. try:
  999. f, filename, _ = imp.find_module(modname)
  1000. except ImportError:
  1001. logger.info("Cannot import bootstrap module: %s" % modname)
  1002. else:
  1003. if f is not None:
  1004. f.close()
  1005. # special-case custom readline.so on OS X, but not for pypy:
  1006. if modname == 'readline' and sys.platform == 'darwin' and not (
  1007. is_pypy or filename.endswith(join('lib-dynload', 'readline.so'))):
  1008. dst_filename = join(dst_prefix, 'lib', 'python%s' % sys.version[:3], 'readline.so')
  1009. elif modname == 'readline' and sys.platform == 'win32':
  1010. # special-case for Windows, where readline is not a
  1011. # standard module, though it may have been installed in
  1012. # site-packages by a third-party package
  1013. pass
  1014. else:
  1015. dst_filename = change_prefix(filename, dst_prefix)
  1016. copyfile(filename, dst_filename, symlink)
  1017. if filename.endswith('.pyc'):
  1018. pyfile = filename[:-1]
  1019. if os.path.exists(pyfile):
  1020. copyfile(pyfile, dst_filename[:-1], symlink)
  1021. finally:
  1022. sys.path = _prev_sys_path
  1023. def subst_path(prefix_path, prefix, home_dir):
  1024. prefix_path = os.path.normpath(prefix_path)
  1025. prefix = os.path.normpath(prefix)
  1026. home_dir = os.path.normpath(home_dir)
  1027. if not prefix_path.startswith(prefix):
  1028. logger.warn('Path not in prefix %r %r', prefix_path, prefix)
  1029. return
  1030. return prefix_path.replace(prefix, home_dir, 1)
  1031. def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear, symlink=True):
  1032. """Install just the base environment, no distutils patches etc"""
  1033. if sys.executable.startswith(bin_dir):
  1034. print('Please use the *system* python to run this script')
  1035. return
  1036. if clear:
  1037. rmtree(lib_dir)
  1038. ## FIXME: why not delete it?
  1039. ## Maybe it should delete everything with #!/path/to/venv/python in it
  1040. logger.notify('Not deleting %s', bin_dir)
  1041. if hasattr(sys, 'real_prefix'):
  1042. logger.notify('Using real prefix %r' % sys.real_prefix)
  1043. prefix = sys.real_prefix
  1044. elif hasattr(sys, 'base_prefix'):
  1045. logger.notify('Using base prefix %r' % sys.base_prefix)
  1046. prefix = sys.base_prefix
  1047. else:
  1048. prefix = sys.prefix
  1049. mkdir(lib_dir)
  1050. fix_lib64(lib_dir, symlink)
  1051. stdlib_dirs = [os.path.dirname(os.__file__)]
  1052. if is_win:
  1053. stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs'))
  1054. elif is_darwin:
  1055. stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages'))
  1056. if hasattr(os, 'symlink'):
  1057. logger.info('Symlinking Python bootstrap modules')
  1058. else:
  1059. logger.info('Copying Python bootstrap modules')
  1060. logger.indent += 2
  1061. try:
  1062. # copy required files...
  1063. for stdlib_dir in stdlib_dirs:
  1064. if not os.path.isdir(stdlib_dir):
  1065. continue
  1066. for fn in os.listdir(stdlib_dir):
  1067. bn = os.path.splitext(fn)[0]
  1068. if fn != 'site-packages' and bn in REQUIRED_FILES:
  1069. copyfile(join(stdlib_dir, fn), join(lib_dir, fn), symlink)
  1070. # ...and modules
  1071. copy_required_modules(home_dir, symlink)
  1072. finally:
  1073. logger.indent -= 2
  1074. mkdir(join(lib_dir, 'site-packages'))
  1075. import site
  1076. site_filename = site.__file__
  1077. if site_filename.endswith('.pyc'):
  1078. site_filename = site_filename[:-1]
  1079. elif site_filename.endswith('$py.class'):
  1080. site_filename = site_filename.replace('$py.class', '.py')
  1081. site_filename_dst = change_prefix(site_filename, home_dir)
  1082. site_dir = os.path.dirname(site_filename_dst)
  1083. writefile(site_filename_dst, SITE_PY)
  1084. writefile(join(site_dir, 'orig-prefix.txt'), prefix)
  1085. site_packages_filename = join(site_dir, 'no-global-site-packages.txt')
  1086. if not site_packages:
  1087. writefile(site_packages_filename, '')
  1088. if is_pypy or is_win:
  1089. stdinc_dir = join(prefix, 'include')
  1090. else:
  1091. stdinc_dir = join(prefix, 'include', py_version + abiflags)
  1092. if os.path.exists(stdinc_dir):
  1093. copyfile(stdinc_dir, inc_dir, symlink)
  1094. else:
  1095. logger.debug('No include dir %s' % stdinc_dir)
  1096. platinc_dir = distutils.sysconfig.get_python_inc(plat_specific=1)
  1097. if platinc_dir != stdinc_dir:
  1098. platinc_dest = distutils.sysconfig.get_python_inc(
  1099. plat_specific=1, prefix=home_dir)
  1100. if platinc_dir == platinc_dest:
  1101. # Do platinc_dest manually due to a CPython bug;
  1102. # not http://bugs.python.org/issue3386 but a close cousin
  1103. platinc_dest = subst_path(platinc_dir, prefix, home_dir)
  1104. if platinc_dest:
  1105. # PyPy's stdinc_dir and prefix are relative to the original binary
  1106. # (traversing virtualenvs), whereas the platinc_dir is relative to
  1107. # the inner virtualenv and ignores the prefix argument.
  1108. # This seems more evolved than designed.
  1109. copyfile(platinc_dir, platinc_dest, symlink)
  1110. # pypy never uses exec_prefix, just ignore it
  1111. if sys.exec_prefix != prefix and not is_pypy:
  1112. if is_win:
  1113. exec_dir = join(sys.exec_prefix, 'lib')
  1114. elif is_jython:
  1115. exec_dir = join(sys.exec_prefix, 'Lib')
  1116. else:
  1117. exec_dir = join(sys.exec_prefix, 'lib', py_version)
  1118. for fn in os.listdir(exec_dir):
  1119. copyfile(join(exec_dir, fn), join(lib_dir, fn), symlink)
  1120. if is_jython:
  1121. # Jython has either jython-dev.jar and javalib/ dir, or just
  1122. # jython.jar
  1123. for name in 'jython-dev.jar', 'javalib', 'jython.jar':
  1124. src = join(prefix, name)
  1125. if os.path.exists(src):
  1126. copyfile(src, join(home_dir, name), symlink)
  1127. # XXX: registry should always exist after Jython 2.5rc1
  1128. src = join(prefix, 'registry')
  1129. if os.path.exists(src):
  1130. copyfile(src, join(home_dir, 'registry'), symlink=False)
  1131. copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'),
  1132. symlink=False)
  1133. mkdir(bin_dir)
  1134. py_executable = join(bin_dir, os.path.basename(sys.executable))
  1135. if 'Python.framework' in prefix:
  1136. # OS X framework builds cause validation to break
  1137. # https://github.com/pypa/virtualenv/issues/322
  1138. if os.environ.get('__PYVENV_LAUNCHER__'):
  1139. del os.environ["__PYVENV_LAUNCHER__"]
  1140. if re.search(r'/Python(?:-32|-64)*$', py_executable):
  1141. # The name of the python executable is not quite what
  1142. # we want, rename it.
  1143. py_executable = os.path.join(
  1144. os.path.dirname(py_executable), 'python')
  1145. logger.notify('New %s executable in %s', expected_exe, py_executable)
  1146. pcbuild_dir = os.path.dirname(sys.executable)
  1147. pyd_pth = os.path.join(lib_dir, 'site-packages', 'virtualenv_builddir_pyd.pth')
  1148. if is_win and os.path.exists(os.path.join(pcbuild_dir, 'build.bat')):
  1149. logger.notify('Detected python running from build directory %s', pcbuild_dir)
  1150. logger.notify('Writing .pth file linking to build directory for *.pyd files')
  1151. writefile(pyd_pth, pcbuild_dir)
  1152. else:
  1153. pcbuild_dir = None
  1154. if os.path.exists(pyd_pth):
  1155. logger.info('Deleting %s (not Windows env or not build directory python)' % pyd_pth)
  1156. os.unlink(pyd_pth)
  1157. if sys.executable != py_executable:
  1158. ## FIXME: could I just hard link?
  1159. executable = sys.executable
  1160. shutil.copyfile(executable, py_executable)
  1161. make_exe(py_executable)
  1162. if is_win or is_cygwin:
  1163. pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe')
  1164. if os.path.exists(pythonw):
  1165. logger.info('Also created pythonw.exe')
  1166. shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe'))
  1167. python_d = os.path.join(os.path.dirname(sys.executable), 'python_d.exe')
  1168. python_d_dest = os.path.join(os.path.dirname(py_executable), 'python_d.exe')
  1169. if os.path.exists(python_d):
  1170. logger.info('Also created python_d.exe')
  1171. shutil.copyfile(python_d, python_d_dest)
  1172. elif os.path.exists(python_d_dest):
  1173. logger.info('Removed python_d.exe as it is no longer at the source')
  1174. os.unlink(python_d_dest)
  1175. # we need to copy the DLL to enforce that windows will load the correct one.
  1176. # may not exist if we are cygwin.
  1177. py_executable_dll = 'python%s%s.dll' % (
  1178. sys.version_info[0], sys.version_info[1])
  1179. py_executable_dll_d = 'python%s%s_d.dll' % (
  1180. sys.version_info[0], sys.version_info[1])
  1181. pythondll = os.path.join(os.path.dirname(sys.executable), py_executable_dll)
  1182. pythondll_d = os.path.join(os.path.dirname(sys.executable), py_executable_dll_d)
  1183. pythondll_d_dest = os.path.join(os.path.dirname(py_executable), py_executable_dll_d)
  1184. if os.path.exists(pythondll):
  1185. logger.info('Also created %s' % py_executable_dll)
  1186. shutil.copyfile(pythondll, os.path.join(os.path.dirname(py_executable), py_executable_dll))
  1187. if os.path.exists(pythondll_d):
  1188. logger.info('Also created %s' % py_executable_dll_d)
  1189. shutil.copyfile(pythondll_d, pythondll_d_dest)
  1190. elif os.path.exists(pythondll_d_dest):
  1191. logger.info('Removed %s as the source does not exist' % pythondll_d_dest)
  1192. os.unlink(pythondll_d_dest)
  1193. if is_pypy:
  1194. # make a symlink python --> pypy-c
  1195. python_executable = os.path.join(os.path.dirname(py_executable), 'python')
  1196. if sys.platform in ('win32', 'cygwin'):
  1197. python_executable += '.exe'
  1198. logger.info('Also created executable %s' % python_executable)
  1199. copyfile(py_executable, python_executable, symlink)
  1200. if is_win:
  1201. for name in ['libexpat.dll', 'libpypy.dll', 'libpypy-c.dll',
  1202. 'libeay32.dll', 'ssleay32.dll', 'sqlite3.dll',
  1203. 'tcl85.dll', 'tk85.dll']:
  1204. src = join(prefix, name)
  1205. if os.path.exists(src):
  1206. copyfile(src, join(bin_dir, name), symlink)
  1207. for d in sys.path:
  1208. if d.endswith('lib_pypy'):
  1209. break
  1210. else:
  1211. logger.fatal('Could not find lib_pypy in sys.path')
  1212. raise SystemExit(3)
  1213. logger.info('Copying lib_pypy')
  1214. copyfile(d, os.path.join(home_dir, 'lib_pypy'), symlink)
  1215. if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe:
  1216. secondary_exe = os.path.join(os.path.dirname(py_executable),
  1217. expected_exe)
  1218. py_executable_ext = os.path.splitext(py_executable)[1]
  1219. if py_executable_ext.lower() == '.exe':
  1220. # python2.4 gives an extension of '.4' :P
  1221. secondary_exe += py_executable_ext
  1222. if os.path.exists(secondary_exe):
  1223. logger.warn('Not overwriting existing %s script %s (you must use %s)'
  1224. % (expected_exe, secondary_exe, py_executable))
  1225. else:
  1226. logger.notify('Also creating executable in %s' % secondary_exe)
  1227. shutil.copyfile(sys.executable, secondary_exe)
  1228. make_exe(secondary_exe)
  1229. if '.framework' in prefix:
  1230. if 'Python.framework' in prefix:
  1231. logger.debug('MacOSX Python framework detected')
  1232. # Make sure we use the embedded interpreter inside
  1233. # the framework, even if sys.executable points to
  1234. # the stub executable in ${sys.prefix}/bin
  1235. # See http://groups.google.com/group/python-virtualenv/
  1236. # browse_thread/thread/17cab2f85da75951
  1237. original_python = os.path.join(
  1238. prefix, 'Resources/Python.app/Contents/MacOS/Python')
  1239. if 'EPD' in prefix:
  1240. logger.debug('EPD framework detected')
  1241. original_python = os.path.join(prefix, 'bin/python')
  1242. shutil.copy(original_python, py_executable)
  1243. # Copy the framework's dylib into the virtual
  1244. # environment
  1245. virtual_lib = os.path.join(home_dir, '.Python')
  1246. if os.path.exists(virtual_lib):
  1247. os.unlink(virtual_lib)
  1248. copyfile(
  1249. os.path.join(prefix, 'Python'),
  1250. virtual_lib,
  1251. symlink)
  1252. # And then change the install_name of the copied python executable
  1253. try:
  1254. mach_o_change(py_executable,
  1255. os.path.join(prefix, 'Python'),
  1256. '@executable_path/../.Python')
  1257. except:
  1258. e = sys.exc_info()[1]
  1259. logger.warn("Could not call mach_o_change: %s. "
  1260. "Trying to call install_name_tool instead." % e)
  1261. try:
  1262. call_subprocess(
  1263. ["install_name_tool", "-change",
  1264. os.path.join(prefix, 'Python'),
  1265. '@executable_path/../.Python',
  1266. py_executable])
  1267. except:
  1268. logger.fatal("Could not call install_name_tool -- you must "
  1269. "have Apple's development tools installed")
  1270. raise
  1271. if not is_win:
  1272. # Ensure that 'python', 'pythonX' and 'pythonX.Y' all exist
  1273. py_exe_version_major = 'python%s' % sys.version_info[0]
  1274. py_exe_version_major_minor = 'python%s.%s' % (
  1275. sys.version_info[0], sys.version_info[1])
  1276. py_exe_no_version = 'python'
  1277. required_symlinks = [ py_exe_no_version, py_exe_version_major,
  1278. py_exe_version_major_minor ]
  1279. py_executable_base = os.path.basename(py_executable)
  1280. if py_executable_base in required_symlinks:
  1281. # Don't try to symlink to yourself.
  1282. required_symlinks.remove(py_executable_base)
  1283. for pth in required_symlinks:
  1284. full_pth = join(bin_dir, pth)
  1285. if os.path.exists(full_pth):
  1286. os.unlink(full_pth)
  1287. if symlink:
  1288. os.symlink(py_executable_base, full_pth)
  1289. else:
  1290. copyfile(py_executable, full_pth, symlink)
  1291. if is_win and ' ' in py_executable:
  1292. # There's a bug with subprocess on Windows when using a first
  1293. # argument that has a space in it. Instead we have to quote
  1294. # the value:
  1295. py_executable = '"%s"' % py_executable
  1296. # NOTE: keep this check as one line, cmd.exe doesn't cope with line breaks
  1297. cmd = [py_executable, '-c', 'import sys;out=sys.stdout;'
  1298. 'getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))']
  1299. logger.info('Testing executable with %s %s "%s"' % tuple(cmd))
  1300. try:
  1301. proc = subprocess.Popen(cmd,
  1302. stdout=subprocess.PIPE)
  1303. proc_stdout, proc_stderr = proc.communicate()
  1304. except OSError:
  1305. e = sys.exc_info()[1]
  1306. if e.errno == errno.EACCES:
  1307. logger.fatal('ERROR: The executable %s could not be run: %s' % (py_executable, e))
  1308. sys.exit(100)
  1309. else:
  1310. raise e
  1311. proc_stdout = proc_stdout.strip().decode("utf-8")
  1312. proc_stdout = os.path.normcase(os.path.abspath(proc_stdout))
  1313. norm_home_dir = os.path.normcase(os.path.abspath(home_dir))
  1314. if hasattr(norm_home_dir, 'decode'):
  1315. norm_home_dir = norm_home_dir.decode(sys.getfilesystemencoding())
  1316. if proc_stdout != norm_home_dir:
  1317. logger.fatal(
  1318. 'ERROR: The executable %s is not functioning' % py_executable)
  1319. logger.fatal(
  1320. 'ERROR: It thinks sys.prefix is %r (should be %r)'
  1321. % (proc_stdout, norm_home_dir))
  1322. logger.fatal(
  1323. 'ERROR: virtualenv is not compatible with this system or executable')
  1324. if is_win:
  1325. logger.fatal(
  1326. 'Note: some Windows users have reported this error when they '
  1327. 'installed Python for "Only this user" or have multiple '
  1328. 'versions of Python installed. Copying the appropriate '
  1329. 'PythonXX.dll to the virtualenv Scripts/ directory may fix '
  1330. 'this problem.')
  1331. sys.exit(100)
  1332. else:
  1333. logger.info('Got sys.prefix result: %r' % proc_stdout)
  1334. pydistutils = os.path.expanduser('~/.pydistutils.cfg')
  1335. if os.path.exists(pydistutils):
  1336. logger.notify('Please make sure you remove any previous custom paths from '
  1337. 'your %s file.' % pydistutils)
  1338. ## FIXME: really this should be calculated earlier
  1339. fix_local_scheme(home_dir, symlink)
  1340. if site_packages:
  1341. if os.path.exists(site_packages_filename):
  1342. logger.info('Deleting %s' % site_packages_filename)
  1343. os.unlink(site_packages_filename)
  1344. return py_executable
  1345. def install_activate(home_dir, bin_dir, prompt=None):
  1346. home_dir = os.path.abspath(home_dir)
  1347. if is_win or is_jython and os._name == 'nt':
  1348. files = {
  1349. 'activate.bat': ACTIVATE_BAT,
  1350. 'deactivate.bat': DEACTIVATE_BAT,
  1351. 'activate.ps1': ACTIVATE_PS,
  1352. }
  1353. # MSYS needs paths of the form /c/path/to/file
  1354. drive, tail = os.path.splitdrive(home_dir.replace(os.sep, '/'))
  1355. home_dir_msys = (drive and "/%s%s" or "%s%s") % (drive[:1], tail)
  1356. # Run-time conditional enables (basic) Cygwin compatibility
  1357. home_dir_sh = ("""$(if [ "$OSTYPE" "==" "cygwin" ]; then cygpath -u '%s'; else echo '%s'; fi;)""" %
  1358. (home_dir, home_dir_msys))
  1359. files['activate'] = ACTIVATE_SH.replace('__VIRTUAL_ENV__', home_dir_sh)
  1360. else:
  1361. files = {'activate': ACTIVATE_SH}
  1362. # suppling activate.fish in addition to, not instead of, the
  1363. # bash script support.
  1364. files['activate.fish'] = ACTIVATE_FISH
  1365. # same for csh/tcsh support...
  1366. files['activate.csh'] = ACTIVATE_CSH
  1367. files['activate_this.py'] = ACTIVATE_THIS
  1368. if hasattr(home_dir, 'decode'):
  1369. home_dir = home_dir.decode(sys.getfilesystemencoding())
  1370. vname = os.path.basename(home_dir)
  1371. for name, content in files.items():
  1372. content = content.replace('__VIRTUAL_PROMPT__', prompt or '')
  1373. content = content.replace('__VIRTUAL_WINPROMPT__', prompt or '(%s)' % vname)
  1374. content = content.replace('__VIRTUAL_ENV__', home_dir)
  1375. content = content.replace('__VIRTUAL_NAME__', vname)
  1376. content = content.replace('__BIN_NAME__', os.path.basename(bin_dir))
  1377. writefile(os.path.join(bin_dir, name), content)
  1378. def install_distutils(home_dir):
  1379. distutils_path = change_prefix(distutils.__path__[0], home_dir)
  1380. mkdir(distutils_path)
  1381. ## FIXME: maybe this prefix setting should only be put in place if
  1382. ## there's a local distutils.cfg with a prefix setting?
  1383. home_dir = os.path.abspath(home_dir)
  1384. ## FIXME: this is breaking things, removing for now:
  1385. #distutils_cfg = DISTUTILS_CFG + "\n[install]\nprefix=%s\n" % home_dir
  1386. writefile(os.path.join(distutils_path, '__init__.py'), DISTUTILS_INIT)
  1387. writefile(os.path.join(distutils_path, 'distutils.cfg'), DISTUTILS_CFG, overwrite=False)
  1388. def fix_local_scheme(home_dir, symlink=True):
  1389. """
  1390. Platforms that use the "posix_local" install scheme (like Ubuntu with
  1391. Python 2.7) need to be given an additional "local" location, sigh.
  1392. """
  1393. try:
  1394. import sysconfig
  1395. except ImportError:
  1396. pass
  1397. else:
  1398. if sysconfig._get_default_scheme() == 'posix_local':
  1399. local_path = os.path.join(home_dir, 'local')
  1400. if not os.path.exists(local_path):
  1401. os.mkdir(local_path)
  1402. for subdir_name in os.listdir(home_dir):
  1403. if subdir_name == 'local':
  1404. continue
  1405. copyfile(os.path.abspath(os.path.join(home_dir, subdir_name)), \
  1406. os.path.join(local_path, subdir_name), symlink)
  1407. def fix_lib64(lib_dir, symlink=True):
  1408. """
  1409. Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
  1410. instead of lib/pythonX.Y. If this is such a platform we'll just create a
  1411. symlink so lib64 points to lib
  1412. """
  1413. if [p for p in distutils.sysconfig.get_config_vars().values()
  1414. if isinstance(p, basestring) and 'lib64' in p]:
  1415. # PyPy's library path scheme is not affected by this.
  1416. # Return early or we will die on the following assert.
  1417. if is_pypy:
  1418. logger.debug('PyPy detected, skipping lib64 symlinking')
  1419. return
  1420. logger.debug('This system uses lib64; symlinking lib64 to lib')
  1421. assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], (
  1422. "Unexpected python lib dir: %r" % lib_dir)
  1423. lib_parent = os.path.dirname(lib_dir)
  1424. top_level = os.path.dirname(lib_parent)
  1425. lib_dir = os.path.join(top_level, 'lib')
  1426. lib64_link = os.path.join(top_level, 'lib64')
  1427. assert os.path.basename(lib_parent) == 'lib', (
  1428. "Unexpected parent dir: %r" % lib_parent)
  1429. if os.path.lexists(lib64_link):
  1430. return
  1431. if symlink:
  1432. os.symlink('lib', lib64_link)
  1433. else:
  1434. copyfile('lib', lib64_link)
  1435. def resolve_interpreter(exe):
  1436. """
  1437. If the executable given isn't an absolute path, search $PATH for the interpreter
  1438. """
  1439. # If the "executable" is a version number, get the installed executable for
  1440. # that version
  1441. python_versions = get_installed_pythons()
  1442. if exe in python_versions:
  1443. exe = python_versions[exe]
  1444. if os.path.abspath(exe) != exe:
  1445. paths = os.environ.get('PATH', '').split(os.pathsep)
  1446. for path in paths:
  1447. if os.path.exists(os.path.join(path, exe)):
  1448. exe = os.path.join(path, exe)
  1449. break
  1450. if not os.path.exists(exe):
  1451. logger.fatal('The executable %s (from --python=%s) does not exist' % (exe, exe))
  1452. raise SystemExit(3)
  1453. if not is_executable(exe):
  1454. logger.fatal('The executable %s (from --python=%s) is not executable' % (exe, exe))
  1455. raise SystemExit(3)
  1456. return exe
  1457. def is_executable(exe):
  1458. """Checks a file is executable"""
  1459. return os.access(exe, os.X_OK)
  1460. ############################################################
  1461. ## Relocating the environment:
  1462. def make_environment_relocatable(home_dir):
  1463. """
  1464. Makes the already-existing environment use relative paths, and takes out
  1465. the #!-based environment selection in scripts.
  1466. """
  1467. home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)
  1468. activate_this = os.path.join(bin_dir, 'activate_this.py')
  1469. if not os.path.exists(activate_this):
  1470. logger.fatal(
  1471. 'The environment doesn\'t have a file %s -- please re-run virtualenv '
  1472. 'on this environment to update it' % activate_this)
  1473. fixup_scripts(home_dir, bin_dir)
  1474. fixup_pth_and_egg_link(home_dir)
  1475. ## FIXME: need to fix up distutils.cfg
  1476. OK_ABS_SCRIPTS = ['python', 'python%s' % sys.version[:3],
  1477. 'activate', 'activate.bat', 'activate_this.py',
  1478. 'activate.fish', 'activate.csh']
  1479. def fixup_scripts(home_dir, bin_dir):
  1480. if is_win:
  1481. new_shebang_args = (
  1482. '%s /c' % os.path.normcase(os.environ.get('COMSPEC', 'cmd.exe')),
  1483. '', '.exe')
  1484. else:
  1485. new_shebang_args = ('/usr/bin/env', sys.version[:3], '')
  1486. # This is what we expect at the top of scripts:
  1487. shebang = '#!%s' % os.path.normcase(os.path.join(
  1488. os.path.abspath(bin_dir), 'python%s' % new_shebang_args[2]))
  1489. # This is what we'll put:
  1490. new_shebang = '#!%s python%s%s' % new_shebang_args
  1491. for filename in os.listdir(bin_dir):
  1492. filename = os.path.join(bin_dir, filename)
  1493. if not os.path.isfile(filename):
  1494. # ignore subdirs, e.g. .svn ones.
  1495. continue
  1496. f = open(filename, 'rb')
  1497. try:
  1498. try:
  1499. lines = f.read().decode('utf-8').splitlines()
  1500. except UnicodeDecodeError:
  1501. # This is probably a binary program instead
  1502. # of a script, so just ignore it.
  1503. continue
  1504. finally:
  1505. f.close()
  1506. if not lines:
  1507. logger.warn('Script %s is an empty file' % filename)
  1508. continue
  1509. old_shebang = lines[0].strip()
  1510. old_shebang = old_shebang[0:2] + os.path.normcase(old_shebang[2:])
  1511. if not old_shebang.startswith(shebang):
  1512. if os.path.basename(filename) in OK_ABS_SCRIPTS:
  1513. logger.debug('Cannot make script %s relative' % filename)
  1514. elif lines[0].strip() == new_shebang:
  1515. logger.info('Script %s has already been made relative' % filename)
  1516. else:
  1517. logger.warn('Script %s cannot be made relative (it\'s not a normal script that starts with %s)'
  1518. % (filename, shebang))
  1519. continue
  1520. logger.notify('Making script %s relative' % filename)
  1521. script = relative_script([new_shebang] + lines[1:])
  1522. f = open(filename, 'wb')
  1523. f.write('\n'.join(script).encode('utf-8'))
  1524. f.close()
  1525. def relative_script(lines):
  1526. "Return a script that'll work in a relocatable environment."
  1527. activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, activate_this"
  1528. # Find the last future statement in the script. If we insert the activation
  1529. # line before a future statement, Python will raise a SyntaxError.
  1530. activate_at = None
  1531. for idx, line in reversed(list(enumerate(lines))):
  1532. if line.split()[:3] == ['from', '__future__', 'import']:
  1533. activate_at = idx + 1
  1534. break
  1535. if activate_at is None:
  1536. # Activate after the shebang.
  1537. activate_at = 1
  1538. return lines[:activate_at] + ['', activate, ''] + lines[activate_at:]
  1539. def fixup_pth_and_egg_link(home_dir, sys_path=None):
  1540. """Makes .pth and .egg-link files use relative paths"""
  1541. home_dir = os.path.normcase(os.path.abspath(home_dir))
  1542. if sys_path is None:
  1543. sys_path = sys.path
  1544. for path in sys_path:
  1545. if not path:
  1546. path = '.'
  1547. if not os.path.isdir(path):
  1548. continue
  1549. path = os.path.normcase(os.path.abspath(path))
  1550. if not path.startswith(home_dir):
  1551. logger.debug('Skipping system (non-environment) directory %s' % path)
  1552. continue
  1553. if path.startswith(os.path.join(home_dir,"local")):
  1554. logger.debug('Skipping local (fix_local_scheme) directory %s' % path)
  1555. continue
  1556. for filename in os.listdir(path):
  1557. filename = os.path.join(path, filename)
  1558. if filename.endswith('.pth'):
  1559. if not os.access(filename, os.W_OK):
  1560. logger.warn('Cannot write .pth file %s, skipping' % filename)
  1561. else:
  1562. fixup_pth_file(filename)
  1563. if filename.endswith('.egg-link'):
  1564. if not os.access(filename, os.W_OK):
  1565. logger.warn('Cannot write .egg-link file %s, skipping' % filename)
  1566. else:
  1567. fixup_egg_link(filename)
  1568. def fixup_pth_file(filename):
  1569. lines = []
  1570. prev_lines = []
  1571. f = open(filename)
  1572. prev_lines = f.readlines()
  1573. f.close()
  1574. for line in prev_lines:
  1575. line = line.strip()
  1576. if (not line or line.startswith('#') or line.startswith('import ')
  1577. or os.path.abspath(line) != line):
  1578. lines.append(line)
  1579. else:
  1580. new_value = make_relative_path(filename, line)
  1581. if line != new_value:
  1582. logger.debug('Rewriting path %s as %s (in %s)' % (line, new_value, filename))
  1583. lines.append(new_value)
  1584. if lines == prev_lines:
  1585. logger.info('No changes to .pth file %s' % filename)
  1586. return
  1587. logger.notify('Making paths in .pth file %s relative' % filename)
  1588. f = open(filename, 'w')
  1589. f.write('\n'.join(lines) + '\n')
  1590. f.close()
  1591. def fixup_egg_link(filename):
  1592. f = open(filename)
  1593. link = f.readline().strip()
  1594. f.close()
  1595. if os.path.abspath(link) != link:
  1596. logger.debug('Link in %s already relative' % filename)
  1597. return
  1598. new_link = make_relative_path(filename, link)
  1599. logger.notify('Rewriting link %s in %s as %s' % (link, filename, new_link))
  1600. f = open(filename, 'w')
  1601. f.write(new_link)
  1602. f.close()
  1603. def make_relative_path(source, dest, dest_is_directory=True):
  1604. """
  1605. Make a filename relative, where the filename is dest, and it is
  1606. being referred to from the filename source.
  1607. >>> make_relative_path('/usr/share/something/a-file.pth',
  1608. ... '/usr/share/another-place/src/Directory')
  1609. '../another-place/src/Directory'
  1610. >>> make_relative_path('/usr/share/something/a-file.pth',
  1611. ... '/home/user/src/Directory')
  1612. '../../../home/user/src/Directory'
  1613. >>> make_relative_path('/usr/share/a-file.pth', '/usr/share/')
  1614. './'
  1615. """
  1616. source = os.path.dirname(source)
  1617. if not dest_is_directory:
  1618. dest_filename = os.path.basename(dest)
  1619. dest = os.path.dirname(dest)
  1620. dest = os.path.normpath(os.path.abspath(dest))
  1621. source = os.path.normpath(os.path.abspath(source))
  1622. dest_parts = dest.strip(os.path.sep).split(os.path.sep)
  1623. source_parts = source.strip(os.path.sep).split(os.path.sep)
  1624. while dest_parts and source_parts and dest_parts[0] == source_parts[0]:
  1625. dest_parts.pop(0)
  1626. source_parts.pop(0)
  1627. full_parts = ['..']*len(source_parts) + dest_parts
  1628. if not dest_is_directory:
  1629. full_parts.append(dest_filename)
  1630. if not full_parts:
  1631. # Special case for the current directory (otherwise it'd be '')
  1632. return './'
  1633. return os.path.sep.join(full_parts)
  1634. ############################################################
  1635. ## Bootstrap script creation:
  1636. def create_bootstrap_script(extra_text, python_version=''):
  1637. """
  1638. Creates a bootstrap script, which is like this script but with
  1639. extend_parser, adjust_options, and after_install hooks.
  1640. This returns a string that (written to disk of course) can be used
  1641. as a bootstrap script with your own customizations. The script
  1642. will be the standard virtualenv.py script, with your extra text
  1643. added (your extra text should be Python code).
  1644. If you include these functions, they will be called:
  1645. ``extend_parser(optparse_parser)``:
  1646. You can add or remove options from the parser here.
  1647. ``adjust_options(options, args)``:
  1648. You can change options here, or change the args (if you accept
  1649. different kinds of arguments, be sure you modify ``args`` so it is
  1650. only ``[DEST_DIR]``).
  1651. ``after_install(options, home_dir)``:
  1652. After everything is installed, this function is called. This
  1653. is probably the function you are most likely to use. An
  1654. example would be::
  1655. def after_install(options, home_dir):
  1656. subprocess.call([join(home_dir, 'bin', 'easy_install'),
  1657. 'MyPackage'])
  1658. subprocess.call([join(home_dir, 'bin', 'my-package-script'),
  1659. 'setup', home_dir])
  1660. This example immediately installs a package, and runs a setup
  1661. script from that package.
  1662. If you provide something like ``python_version='2.5'`` then the
  1663. script will start with ``#!/usr/bin/env python2.5`` instead of
  1664. ``#!/usr/bin/env python``. You can use this when the script must
  1665. be run with a particular Python version.
  1666. """
  1667. filename = __file__
  1668. if filename.endswith('.pyc'):
  1669. filename = filename[:-1]
  1670. f = codecs.open(filename, 'r', encoding='utf-8')
  1671. content = f.read()
  1672. f.close()
  1673. py_exe = 'python%s' % python_version
  1674. content = (('#!/usr/bin/env %s\n' % py_exe)
  1675. + '## WARNING: This file is generated\n'
  1676. + content)
  1677. return content.replace('##EXT' 'END##', extra_text)
  1678. def convert(s):
  1679. b = base64.b64decode(s.encode('ascii'))
  1680. return zlib.decompress(b).decode('utf-8')
  1681. ##file site.py
  1682. SITE_PY = convert("""
  1683. eJzFPf1z2zaWv/OvwMqToZTKdOJ0e3tO3RsncVrfuYm3yc7m1vXoKAmyWFMkS5C2tTd3f/u9DwAE
  1684. +CHb2+6cphNLJPDw8PC+8PAeOhqNTopCZkuxyZd1KoWScblYiyKu1kqs8lJU66Rc7hdxWW3h6eIm
  1685. vpZKVLlQWxVhqygInv/GT/BcfF4nyqAA3+K6yjdxlSziNN2KZFPkZSWXYlmXSXYtkiypkjhN/g4t
  1686. 8iwSz387BsFZJmDmaSJLcStLBXCVyFfiYlut80yM6wLn/DL6Y/xqMhVqUSZFBQ1KjTNQZB1XQSbl
  1687. EtCElrUCUiaV3FeFXCSrZGEb3uV1uhRFGi+k+K//4qlR0zAMVL6Rd2tZSpEBMgBTAqwC8YCvSSkW
  1688. +VJGQryRixgH4OcNsQKGNsU1U0jGLBdpnl3DnDK5kErF5VaM53VFgAhlscwBpwQwqJI0De7y8kZN
  1689. YElpPe7gkYiZPfzJMHvAPHH8LucAjh+z4C9Zcj9l2MA9CK5aM9uUcpXcixjBwk95Lxcz/WycrMQy
  1690. Wa2ABlk1wSYBI6BEmswPClqOb/UKfXdAWFmujGEMiShzY35JPaLgrBJxqoBt6wJppAjzd3KexBlQ
  1691. I7uF4QAikDToG2eZqMqOQ7MTOQAocR0rkJKNEuNNnGTArD/GC0L7r0m2zO/UhCgAq6XEL7Wq3PmP
  1692. ewgArR0CTANcLLOadZYmNzLdTgCBz4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/dKG61lUrvOjqVRpjs5qrbdeulbM1JTRuXYE0geNXVIwCE4xg1eUxV6ZXWHJ
  1759. J4C6zqoHKW2jbWJISkHBTrqAc/5lTle8QCl1hidNZ63oL0MX1/AqUkWawE7udWhlSXfD9JiGcfRD
  1760. e8DNePVpQKc7jKwb8qwHsUCr9Trkuen+k4bRfq0Bw4bB3sG8M0npIZSBjcltIsRGfJITynv4apde
  1761. r4GCBcODvgoX0TBdArOPYXMt1glsIIAn12B9cZ8AEFor4R8IHDnRAZljdkb4drPc/3OoCeK3/vnn
  1762. nuZVme7/TRSwCxKcShT2ENNt/A42PpGMxOnH95OQkaPUXPHnGssDwCGhAKgj7ZS/xCfos7GS6Urn
  1763. l/j6AF9oP4Fet7qXsih1937XOEQJeKbG5DU8U4Z+IaZ7WdhTnMqkBRorHyxmWEHopiGYz574tJZp
  1764. qvPdz96dn4LviMUYKEF87nYKw3G8BI/QdfIdVzi2QOEBO7wukY1LdGEpyWIZec16g9YoctTby8uw
  1765. 60SB4W6vThS4jBPloj3GaTMsU04QISvDWphlZdZutUEKu22I4igzzBKzi5ISWH2eAF6mpzFviWCv
  1766. hKUeJgLPp8hJVpmMxTRZgB4FlQsKdQpCgsTFekbivDzjGHheKlMGBQ+LbZlcrys83YDOEZVgYPMf
  1767. T76cn32gsoTDV43X3cOcU9oJTDmJ5BhTBDHaAV/ctD/kqtmsj2f1K4SB2gf+tF9xdsoxD9Dpx4FF
  1768. /NN+xXVox85OkGcACqou2uKBGwCnW5/cNLLAuNp9MH7cFMAGMx8MxSKx7EUnerjz63KibdkyJRT3
  1769. MS+fcICzKmxKmu7spqS1P3qOqwLPuZbj/kbwtk+2zGcOXW86b4aS39xPRwqxJBYw6rb2xzDZYZ2m
  1770. ejoOsw1xC21rtY39OXNipU67RYaiDEQcu50nLpP1K2HdnDnQS6PuABPfanSNJPaq8tHP2Uh7GB4m
  1771. ltidfYrpSGUsZAQwkiF17U8NPhRaBFAglP07diR3Onl+6M3RsQYPz1HrLrC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Xcj+yF0qwrnUo+Yx6QI7t3kxEIvmpSuRnK3lVwuyJIvnTR4+/PP745OSda
  1812. zC5O3v7HyfeUlIXHJS1b9egQW5bvM7X3vfRvN9ymE2n6Bm+w7bkhlmuYNITO+04OQg+E/nq1vgVt
  1813. KzL39VCHTt1PtxMgvnvaLahDKrsXcscv0zUmbvpMK0870E85qdb8cjITzCNzUsfi0JzEmffN4YmW
  1814. 0U5seWjhnPTWrjrR/qq+BXQg7j2xSda0Anhmgvxlj0xMxYwNzLOD0v7ffFBmOFYbmht0QAoX0rnJ
  1815. kS5xZFCV//8TKUHZxbi3Y0dxau/mpnZ8PKTspfN49ruQkSGIV+436s7PFfalTAeoEASs8PQ9hYyI
  1816. 0X/6QNWmHzxT4nKfCov3Udlc2V+4Ztq5/WuCSQaVve9LcYISH7NC41WduokDtk+nAzl9dBqVr5xK
  1817. FtB8B0DnRjwVsDf6S6wQ51sRwsZRu2SYHEt01Jf1Ocij3XSwN7R6IfaHyk7dskshXg43XLYqO3WP
  1818. Q+6hHuihalPc51hgzNIcqicV3xFkPs4UdMGX53zgGbre9sPX28uXR/ZwAfkdXzuKhLLJRo5hv3Sy
  1819. MXdeKul0J2Ypp5Suh3s1JySsW1w5UNknGNrbdEpSBvY/Js+BIY289/0hM9PDu3p/1MbUst4RTEmM
  1820. n6kJTcsp4tG42yeT7nQbtdUFwgVJjwDSUYEAC8F0dKOTILrlLO/xC70bnNd0Ha97whQ6UkHJYj5H
  1821. cA/j+zX4tbtTIfGjujOKpj83aHOgXnIQbvYduNXEC4UMm4T21Bs+GHABuCa7v//LR/TvpjHa7oe7
  1822. /Grb6lVvHSD7spj5iplBLRKZxxEYGdCbY9LWWC5hBB2voWno6DJUMzfkC3T8KJsWL9umDQY5szPt
  1823. AVijEPwfucjncQ==
  1824. """)
  1825. ##file activate.sh
  1826. ACTIVATE_SH = convert("""
  1827. eJytVVFvokAQfudXTLEPtTlLeo9tvMSmJpq02hSvl7u2wRUG2QR2DSxSe7n/frOACE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ROG
  1841. +n8O9H8f5vsGOWXsL1+1k3g=
  1842. """)
  1843. ##file activate.fish
  1844. ACTIVATE_FISH = convert("""
  1845. eJydVW2P2jgQ/s6vmAZQoVpA9/WkqqJaTou0u6x2uZVOVWWZZEKsS+yc7UDpr+84bziQbauLxEvs
  1846. eXnsZ56ZIWwTYSAWKUJWGAs7hMJgBEdhEwiMKnSIsBNywUMrDtziPBYmCeBDrFUG7v8HmCTW5n8u
  1847. Fu7NJJim81Bl08EQTqqAkEupLOhCgrAQCY2hTU+DQVxIiqgkRNiEBphFEKy+kd1BaFvwFOUBuIxA
  1848. oy20BKtAKp3xFMo0QNtCK5mhtMEA6BmSpUELKo38TThwLfguRVNaiRgs0llnEoIR29zfstf18/bv
  1849. 5T17Wm7vAiiN3ONCzfbfwC3DtWXXDqHfAGX0q6z/bO82j3ebh1VwnbrduwTQbvwcRtesAfMGor/W
  1850. L3fs6Xnz8LRlm9fV8/P61sM0LDNwCZjl9gSpCokJRzpryGQ5t8kNGFUt51QjOZGu0Mj35FlYlXEr
  1851. yC09EVOp4lEXfF84Lz1qbhBsgl59vDedXI3rTV03xipduSgt9kLytI3XmBp3aV6MPoMQGNUU62T6
  1852. uQdeefTy1Hfj10zVHg2pq8fXDoHBiOv94csfXwN49xECqWREy7pwukKfvxdMY2j23vXDPuuxxeE+
  1853. JOdCOhxCE3N44B1ZeSLuZh8Mmkr2wEPAmPfKWHA2uxIRjEopdbQYjDz3BWOf14/scfmwoki1eQvX
  1854. ExBdF60Mqh+Y/QcX4uiH4Amwzx79KOVFtbL63sXJbtcvy8/3q5rupmO5CnE91wBviQAhjUUegYpL
  1855. vVEbpLt2/W+PklRgq5Ku6mp+rpMhhCo/lXthQTxJ2ysO4Ka0ad97S7VT/n6YXus6fzk3fLnBZW5C
  1856. KDC6gSO62QDqgFqLCCtPmjegjnLeAdArtSE8VYGbAJ/aLb+vnQutFhk768E9uRbSxhCMzdgEveYw
  1857. IZ5ZqFKl6+kz7UR4U+buqQZXu9SIujrAfD7f0FXpozB4Q0gwp31H9mVTZGGC4b871/wm7lvyDLu1
  1858. FUyvTj/yvD66k3UPTs08x1AQQaGziOl0S1qRkPG9COtBTSTWM9NzQ4R64B+Px/l3tDzCgxv5C6Ni
  1859. e+QaF9xFWrxx0V/G5uvYQOdiZzvYpQUVQSIsTr1TTghI33GnPbTA7/GCqcE3oE3GZurq4HeQXQD6
  1860. 32XS1ITj/qLjN72ob0hc5C9bzw8MhfmL
  1861. """)
  1862. ##file activate.csh
  1863. ACTIVATE_CSH = convert("""
  1864. eJx9VG1P2zAQ/u5fcYQKNgTNPtN1WxlIQ4KCUEGaxuQ6yYVYSuzKdhqVX7+zk3bpy5YPUXL3PPfc
  1865. ne98DLNCWshliVDV1kGCUFvMoJGugMjq2qQIiVSxSJ1cCofD1BYRnOVGV0CfZ0N2DD91DalQSjsw
  1866. tQLpIJMGU1euvPe7QeJlkKzgWixlhnAt4aoUVsLnLBiy5NtbJWQ5THX1ZciYKKWwkOFaE04dUm6D
  1867. r/zh7pq/3D7Nnid3/HEy+wFHY/gEJydg0aFaQrBFgz1c5DG1IhTs+UZgsBC2GMFBlaeH+8dZXwcW
  1868. VPvCjXdlAvCfQsE7al0+07XjZvrSCUevR5dnkVeKlFYZmUztG4BdzL2u9KyLVabTU0bdfg7a0hgs
  1869. cSmUg6UwUiQl2iHrcbcVGNvPCiLOe7+cRwG13z9qRGgx2z6DHjfm/Op2yqeT+xvOLzs0PTKHDz2V
  1870. tkckFHoQfQRXoGJAj9el0FyJCmEMhzgMS4sB7KPOE2ExoLcSieYwDvR+cP8cg11gKkVJc2wRcm1g
  1871. QhYFlXiTaTfO2ki0fQoiFM4tLuO4aZrhOzqR4dIPcWx17hphMBY+Srwh7RTyN83XOWkcSPh1Pg/k
  1872. TXX/jbJTbMtUmcxZ+/bbqOsy82suFQg/BhdSOTRhMNBHlUarCpU7JzBhmkKmRejKOQzayQe6MWoa
  1873. n1wqWmuh6LZAaHxcdeqIlVLhIBJdO9/kbl0It2oEXQj+eGjJOuvOIR/YGRqvFhttUB2XTvLXYN2H
  1874. 37CBdbW2W7j2r2+VsCn0doVWcFG1/4y1VwBjfwAyoZhD
  1875. """)
  1876. ##file activate.bat
  1877. ACTIVATE_BAT = convert("""
  1878. eJx9UdEKgjAUfW6wfxjiIH+hEDKUFHSKLCMI7kNOEkIf9P9pTJ3OLJ/03HPPPed4Es9XS9qqwqgT
  1879. PbGKKOdXL4aAFS7A4gvAwgijuiKlqOpGlATS2NeMLE+TjJM9RkQ+SmqAXLrBo1LLIeLdiWlD6jZt
  1880. r7VNubWkndkXaxg5GO3UaOOKS6drO3luDDiO5my3iA0YAKGzPRV1ack8cOdhysI0CYzIPzjSiH5X
  1881. 0QcvC8Lfaj0emsVKYF2rhL5L3fCkVjV76kShi59NHwDniAHzkgDgqBcwOgTMx+gDQQqXCw==
  1882. """)
  1883. ##file deactivate.bat
  1884. DEACTIVATE_BAT = convert("""
  1885. eJxzSE3OyFfIT0vj4ipOLVEI8wwKCXX0iXf1C7Pl4spMU0hJTcvMS01RiPf3cYmHyQYE+fsGhCho
  1886. cCkAAUibEkTEVhWLMlUlLk6QGixStlyaeCyJDPHw9/Pw93VFsQguim4ZXAJoIUw5DhX47XUM8UCx
  1887. EchHtwsohN1bILUgw61c/Vy4AJYPYm4=
  1888. """)
  1889. ##file activate.ps1
  1890. ACTIVATE_PS = convert("""
  1891. eJylWdmO41hyfW+g/0FTU7C7IXeJIqmtB/3AnZRIStxF2kaBm7gv4ipyMF/mB3+Sf8GXVGVl1tLT
  1892. 43ECSqR4b5wbETeWE8z/+a///vNCDaN6cYtSf5G1dbNw/IVXNIu6aCvX9xa3qsgWl0IJ/7IYinbh
  1893. 2nkOVqs2X0TNjz/8eeFFle826fBhQRaLBkD9uviw+LCy3Sbq7Mb/UNbrH3+YNtLcVaB+Xbipb+eL
  1894. tly0eVsD/M6u6g8//vC+dquobH5VWU75eMFUdvHb4n02RHlXuHYTFfmHbHCLLLNz70NpN+GrBI4p
  1895. 1EeSk4FAXaZR88u0vPip8usi7fznt3fvP+OuPnx49/Pil4td+XnzigIAPoqYQH2J8v4z+C+8b98m
  1896. Q25t7k76LIK0cOz0V89/MXXx0+Lf6z5q3PA/F+/FIif9uqnaadFf/PzXSXYBfqIb2NeApecJwPzI
  1897. dlL/149nnvyoc7KqYfzTAT8v/voUmX7e+3n364tffl/oVaDyswKY/7J18e6bve8Wv9RuUfqfLHmK
  1898. /u139Hwx+9ePRep97KKqae30YwmCo2y+0vTz1k+rv7159B3pb1SOGj97Pe8/flfkC1Vn/7xYR4n6
  1899. lypNEGDDV5f7lcjil3S+4++p881Wv6qKyn5GQg1yJwcp4BZ5E+Wt/z1P/umbiHir4J8Xip/eFt6n
  1900. 9T/9gU9eY+7zUX97Jlmb136ziKrKT/3OzpvP8VX/+MObSP0lL3LvVZlJ9v1b8357jXyw8rXxYPXN
  1901. 11n4UzJ8G8S/vUbuJ6RPj999DbtS5kys//JusXwrNLnvT99cFlBNwXCe+niRz8JF/ezNr9Pze+H6
  1902. 18W7d5PPvozW7+387Zto/v4pL8BvbxTzvIW9KCv/Fj0WzVQb/YXbVlPZWTz3/9vCaRtQbPN/Bb+j
  1903. 2rUrDxTVD68gfQXu/ZewAFX53U/vf/rD2P3558W7+W79Po1y/xXoX/6RFHyNIoVjgAG4H0RTcAe5
  1904. 3bSVv3DSwk2mZYHjFB8zj6fC4sLOFTHJJQrwzFYJgso0ApOoBzFiRzzQKjIQCCbQMIFJGCKqGUyS
  1905. 8AkjiF2wTwmMEbcEUvq8Nj+X0f4YcCQmYRiOY7eRbAJDqzm1chOoNstbJ8oTBhZQ2NcfgaB6QjLp
  1906. U4+SWFjQGCZpyqby8V4JkPGs9eH1BscXIrTG24QxXLIgCLYNsIlxSYLA6SjAeg7HAg4/kpiIB8k9
  1907. TCLm0EM4gKIxEj8IUj2dQeqSxEwYVH88qiRlCLjEYGuNIkJB1BA5dHOZdGAoUFk54WOqEojkuf4Q
  1908. Ig3WY+96TDlKLicM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R7SeONGF8yZP+7xxi9scnHvHPcogJ44VH/LMc
  1935. Yu6Vn3jEzCFw9Eqq1ENQAW8aqbUwSiAqi+nZ+OkZJKpBL66Bj8z+ATqb/8qDIJUeNRTwrI0YrVmb
  1936. 9FArKVEbCWUNSi8ipfVv+STgkpSsUhcBg541eeKLoBpLGaiHTNoK0r4nn3tZqrcIULtq20Df+FVQ
  1937. Sa0MnWxTugMuzD410sQygF4qdntbswiJMqjs014Irz/tm+pd5oygJ0fcdNbMg165Pqi7EkYGAXcB
  1938. dwxioCDA3+BY9+JjuOmJu/xyX2GJtaKSQcOZxyqFzTaa6/ot21sez0BtKjirROKRm2zuai02L0N+
  1939. ULaX8H5P6VwsGPbYOY7sAy5FHBROMrMzFVPYhFHZ7M3ZCZa2hsT4jGow6TGtG8Nje9405uMUjdF4
  1940. PtKQjw6yZOmPUmO8LjFWS4aPCfE011N+l3EdYq09O3iQJ9a01B3KXiMF1WmtZ+l1gmyJ/ibAHZil
  1941. vQzdOl6g9PoSJ4TM4ghTnTndEVMOmsSSu+SCVlGCOLQRaw9oLzamSWP62VuxPZ77mZYdfTRGuNBi
  1942. KyhZL32S2YckO/tU7y4Bf+QKKibQSKCTDWPUwWaE8yCBeL5FjpbQuAlb53mGX1jptLeRotREbx96
  1943. gnicYz0496dYauCjpTCA4VA0cdLJewzRmZeTwuXWD0talJsSF9J1Pe72nkaHSpULgNeK1+o+9yi0
  1944. YpYwXZyvaZatK2eL0U0ZY6ekZkFPdC8JTF4Yo1ytawNfepqUKEhwznp6HO6+2l7L2R9Q3N49JMIe
  1945. Z+ax1mVaWussz98QbNTRPo1xu4W33LJpd9H14dd66ype7UktfEDi3oUTccJ4nODjwBKFxS7lYWiq
  1946. XoHu/b7ZVcK5TbRD0F/2GShg2ywwUl07k4LLqhofKxFBNd1grWY+Zt/cPtacBpV9ys2z1moMLrT3
  1947. W0Elrjtt5y/dvDQYtObYS97pqj0eqmwvD3jCPRqamGthLiF0XkgB6IdHLBBwDGPiIDh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pbCoU3K9bfq
  1961. gF7W82tNutRRZExad+k4GYYsCfmEbvizS4jsRr3fdzqjEthpEwm7pmN7OgVzRbrktjrFw1lc0vM8
  1962. V7dyTJ71qlsd7v3KhmHzeJB35pqEOk2pEe5uPeCToNkmedmxcKbIj+MZzjFSsvCmimaMQB1uJJKa
  1963. +hoWUi7aEFLvIxKxJavqpggXBIk2hr0608dIgnfG5ZEprqmH0b0YSy6jVXTCuIB+WER4d5BPVy9Q
  1964. M4taX0RIlDYxQ2CjBuq78AAcHQf5qoKP8BXHnDnd/+ed5fS+csL4g3eWqECaL+8suy9r8hx7c+4L
  1965. EegEWdqAWN1w1NezP34xsxLkvRRI0DRzKOg0U+BKfQY128YlYsbwSczEg2LqKxRmcgiwHdhc9MQJ
  1966. IwKQHlgBejWeMGDYYxTOQUiJOmIjJbzIzHH6lAMP+y/fR0v1g4wx4St8fcqTt3gz5wc+xXFZZ3qI
  1967. JpXI5iJk7xmNL2tYsDpcqu0375Snd5EKsIvg8u5szTOyZ4v06Ny2TZXRpHUSinh4IFp8Eoi7GINJ
  1968. 02lPJnS/9jSxolJwp2slPMIEbjleWw3eec4XaetyEnSSqTPRZ9fVA0cPXMqzrPYQQyrRux3LaAh1
  1969. wujbgcObg1nt4iiJ5IMbc/WNPc280I2T4nTkdwG8H6iS5xO2WfsFsruBwf2QkgZlb6w7om2G65Lr
  1970. r2Gl4dk63F8rCEHoUJ3fW+pU2Srjlmcbp+JXY3DMifEI22HcHAvT7zzXiMTr7VbUR5a2lZtJkk4k
  1971. 1heZZFdru8ucCWMTr3Z4eNnjLm7LW7rcN7QjMpxrsCzjxndeyFUX7deIs3PQkgyH8k6luI0uUyLr
  1972. va47TBjM4JmNHFzGPcP6BV6cYgQy8VQYZe5GmzZHMxyBYhGiUdekZQ/qwyxC3WGylQGdUpSf9ZCP
  1973. a7qPdJd31fPRC0TOgzupO7nLuBGr2A02yuUQwt2KQG31sW8Gd9tQiHq+hPDt4OzJuY4pS8XRsepY
  1974. tsd7dVEfJFmc15IYqwHverrpWyS1rFZibDPW1hUUb+85CGUzSBSTK8hpvee/ZxonW51TUXekMy3L
  1975. uy25tMTg4mqbSLQQJ+skiQu2toIfBFYrOWql+EQipgfT15P1aq6FDK3xgSjIGWde0BPftYchDTdM
  1976. i4QdudHFkN0u6fSKiT09QLv2mtSblt5nNzBR6UReePNs+khE4rHcXuoK21igUKHl1c3MXMgPu7y8
  1977. rKQDxR6N/rffXv+lROXet/9Q+l9I4D1U
  1978. """)
  1979. ##file distutils-init.py
  1980. DISTUTILS_INIT = convert("""
  1981. eJytV1uL4zYUfvevOE0ottuMW9q3gVDa3aUMXXbLMlDKMBiNrSTqOJKRlMxkf33PkXyRbGe7Dw2E
  1982. UXTu37lpxLFV2oIyifAncxmOL0xLIfcG+gv80x9VW6maw7o/CANSWWBwFtqeWMPlGY6qPjV8A0bB
  1983. C4eKSTgZ5LRgFeyErMEeOBhbN+Ipgeizhjtnhkn7DdyjuNLPoCS0l/ayQTG0djwZC08cLXozeMss
  1984. aG5EzQ0IScpnWtHSTXuxByV/QCmxE7y+eS0uxWeoheaVVfqSJHiU7Mhhi6gULbOHorshkrEnKxpT
  1985. 0n3A8Y8SMpuwZx6aoix3ouFlmW8gHRSkeSJ2g7hU+kiHLDaQw3bmRDaTGfTnty7gPm0FHbIBg9U9
  1986. oh1kZzAFLaue2R6htPCtAda2nGlDSUJ4PZBgCJBGVcwKTAMz/vJiLD+Oin5Z5QlvDPdulC6EsiyE
  1987. NFzb7McNTKJzbJqzphx92VKRFY1idenzmq3K0emRcbWBD0ryqc4NZGmKOOOX9Pz5x+/l27tP797c
  1988. f/z0d+4NruGNai8uAM0bfsYaw8itFk8ny41jsfpyO+BWlpqfhcG4yxLdi/0tQqoT4a8Vby382mt8
  1989. p7XSo7aWGdPBc+b6utaBmCQ7rQKQoWtAuthQCiold2KfJIPTT8xwg9blPumc+YDZC/wYGdAyHpJk
  1990. vUbHbHWAp5No6pK/WhhLEWrFjUwtPEv1Agf8YmnsuXUQYkeZoHm8ogP16gt2uHoxcEMdf2C6pmbw
  1991. hUMsWGhanboh4IzzmsIpWs134jVPqD/c74bZHdY69UKKSn/+KfVhxLgUlToemayLMYQOqfEC61bh
  1992. cbhwaqoGUzIyZRFHPmau5juaWqwRn3mpWmoEA5nhzS5gog/5jbcFQqOZvmBasZtwYlG93k5GEiyw
  1993. buHhMWLjDarEGpMGB2LFs5nIJkhp/nUmZneFaRth++lieJtHepIvKgx6PJqIlD9X2j6pG1i9x3pZ
  1994. 5bHuCPFiirGHeO7McvoXkz786GaKVzC9DSpnOxJdc4xm6NSVq7lNEnKdVlnpu9BNYoKX2Iq3wvgh
  1995. gGEUM66kK6j4NiyoneuPLSwaCWDxczgaolEWpiMyDVDb7dNuLAbriL8ig8mmeju31oNvQdpnvEPC
  1996. 1vAXbWacGRVrGt/uXN/gU0CDDwgooKRrHfTBb1/s9lYZ8ZqOBU0yLvpuP6+K9hLFsvIjeNhBi0KL
  1997. MlOuWRn3FRwx5oHXjl0YImUx0+gLzjGchrgzca026ETmYJzPD+IpuKzNi8AFn048Thd63OdD86M6
  1998. 84zE8yQm0VqXdbbgvub2pKVnS76icBGdeTHHXTKspUmr4NYo/furFLKiMdQzFjHJNcdAnMhltBJK
  1999. 0/IKX3DVFqvPJ2dLE7bDBkH0l/PJ29074+F0CsGYOxsb7U3myTUncYfXqnLLfa6sJybX4g+hmcjO
  2000. kMRBfA1JellfRRKJcyRpxdS4rIl6FdmQCWjo/o9Qz7yKffoP4JHjOvABcRn4CZIT2RH4jnxmfpVG
  2001. qgLaAvQBNfuO6X0/Ux02nb4FKx3vgP+XnkX0QW9pLy/NsXgdN24dD3LxO2Nwil7Zlc1dqtP3d7/h
  2002. kzp1/+7hGBuY4pk0XD/0Ao/oTe/XGrfyM773aB7iUhgkpy+dwAMalxMP0DrBcsVw/6p25+/hobP9
  2003. GBknrWExDhLJ1bwt1NcCNblaFbMKCyvmX0PeRaQ=
  2004. """)
  2005. ##file distutils.cfg
  2006. DISTUTILS_CFG = convert("""
  2007. eJxNj00KwkAMhfc9xYNuxe4Ft57AjYiUtDO1wXSmNJnK3N5pdSEEAu8nH6lxHVlRhtDHMPATA4uH
  2008. xJ4EFmGbvfJiicSHFRzUSISMY6hq3GLCRLnIvSTnEefN0FIjw5tF0Hkk9Q5dRunBsVoyFi24aaLg
  2009. 9FDOlL0FPGluf4QjcInLlxd6f6rqkgPu/5nHLg0cXCscXoozRrP51DRT3j9QNl99AP53T2Q=
  2010. """)
  2011. ##file activate_this.py
  2012. ACTIVATE_THIS = convert("""
  2013. eJyNU01v2zAMvetXEB4K21jnDOstQA4dMGCHbeihlyEIDMWmE62yJEiKE//7kXKdpEWLzYBt8evx
  2014. kRSzLPs6wiEoswM8YdMpjUXcq1Dz6RZa1cSiTkJdr86GsoTRHuCotBayiWqQEYGtMCgfD1KjGYBe
  2015. 5a3p0cRKiEe2NtLAFikftnDco0ko/SFEVgEZ8aRCZDIPY9xbA8pE9M4jfW/B2CjiHq9zbJVZuOQq
  2016. siwTIvpxKYCembPAU4Muwi/Z4zfvrZ/MXipKeB8C+qisSZYiWfjJfs+0/MFMdWn1hJcO5U7G/SLa
  2017. xVx8zU6VG/PXLXvfsyyzUqjeWR8hjGE+2iCE1W1tQ82hsCJN9dzKaoexyB/uH79TnjwvxcW0ntSb
  2018. yZ8jq1Z5Q1UXsyy3gf9nbjTEj7NzQMfCJa/YSmrQ+2D/BqfiOi6sclrGzvoeVivIj8rcfcmnIQRF
  2019. 7XCyeZI7DFe5/lhlCs5PRf5QW66VXT/NrlQ46oD/D6InkOmi3IQcbhKxAX2g4a+Xd5s3UtCtG2py
  2020. m8eg6WYWqR6SL5OjKMGfSrYt/6kxxQtOpeAgj1LXBNmpE2ElmCSIy5H0zFd8gJ924HWijWhb2hRC
  2021. 6wNEm1QdDZtuSZcEprIUBo/XRNcbQe1OUbQ/r3hPTaPJJDNtFLu8KHV5XoNr3Eo6h6YtOKw8e8yw
  2022. VF5PnJ+ts3a9/Mz38RpG/AUSzYUW
  2023. """)
  2024. MH_MAGIC = 0xfeedface
  2025. MH_CIGAM = 0xcefaedfe
  2026. MH_MAGIC_64 = 0xfeedfacf
  2027. MH_CIGAM_64 = 0xcffaedfe
  2028. FAT_MAGIC = 0xcafebabe
  2029. BIG_ENDIAN = '>'
  2030. LITTLE_ENDIAN = '<'
  2031. LC_LOAD_DYLIB = 0xc
  2032. maxint = majver == 3 and getattr(sys, 'maxsize') or getattr(sys, 'maxint')
  2033. class fileview(object):
  2034. """
  2035. A proxy for file-like objects that exposes a given view of a file.
  2036. Modified from macholib.
  2037. """
  2038. def __init__(self, fileobj, start=0, size=maxint):
  2039. if isinstance(fileobj, fileview):
  2040. self._fileobj = fileobj._fileobj
  2041. else:
  2042. self._fileobj = fileobj
  2043. self._start = start
  2044. self._end = start + size
  2045. self._pos = 0
  2046. def __repr__(self):
  2047. return '<fileview [%d, %d] %r>' % (
  2048. self._start, self._end, self._fileobj)
  2049. def tell(self):
  2050. return self._pos
  2051. def _checkwindow(self, seekto, op):
  2052. if not (self._start <= seekto <= self._end):
  2053. raise IOError("%s to offset %d is outside window [%d, %d]" % (
  2054. op, seekto, self._start, self._end))
  2055. def seek(self, offset, whence=0):
  2056. seekto = offset
  2057. if whence == os.SEEK_SET:
  2058. seekto += self._start
  2059. elif whence == os.SEEK_CUR:
  2060. seekto += self._start + self._pos
  2061. elif whence == os.SEEK_END:
  2062. seekto += self._end
  2063. else:
  2064. raise IOError("Invalid whence argument to seek: %r" % (whence,))
  2065. self._checkwindow(seekto, 'seek')
  2066. self._fileobj.seek(seekto)
  2067. self._pos = seekto - self._start
  2068. def write(self, bytes):
  2069. here = self._start + self._pos
  2070. self._checkwindow(here, 'write')
  2071. self._checkwindow(here + len(bytes), 'write')
  2072. self._fileobj.seek(here, os.SEEK_SET)
  2073. self._fileobj.write(bytes)
  2074. self._pos += len(bytes)
  2075. def read(self, size=maxint):
  2076. assert size >= 0
  2077. here = self._start + self._pos
  2078. self._checkwindow(here, 'read')
  2079. size = min(size, self._end - here)
  2080. self._fileobj.seek(here, os.SEEK_SET)
  2081. bytes = self._fileobj.read(size)
  2082. self._pos += len(bytes)
  2083. return bytes
  2084. def read_data(file, endian, num=1):
  2085. """
  2086. Read a given number of 32-bits unsigned integers from the given file
  2087. with the given endianness.
  2088. """
  2089. res = struct.unpack(endian + 'L' * num, file.read(num * 4))
  2090. if len(res) == 1:
  2091. return res[0]
  2092. return res
  2093. def mach_o_change(path, what, value):
  2094. """
  2095. Replace a given name (what) in any LC_LOAD_DYLIB command found in
  2096. the given binary with a new name (value), provided it's shorter.
  2097. """
  2098. def do_macho(file, bits, endian):
  2099. # Read Mach-O header (the magic number is assumed read by the caller)
  2100. cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags = read_data(file, endian, 6)
  2101. # 64-bits header has one more field.
  2102. if bits == 64:
  2103. read_data(file, endian)
  2104. # The header is followed by ncmds commands
  2105. for n in range(ncmds):
  2106. where = file.tell()
  2107. # Read command header
  2108. cmd, cmdsize = read_data(file, endian, 2)
  2109. if cmd == LC_LOAD_DYLIB:
  2110. # The first data field in LC_LOAD_DYLIB commands is the
  2111. # offset of the name, starting from the beginning of the
  2112. # command.
  2113. name_offset = read_data(file, endian)
  2114. file.seek(where + name_offset, os.SEEK_SET)
  2115. # Read the NUL terminated string
  2116. load = file.read(cmdsize - name_offset).decode()
  2117. load = load[:load.index('\0')]
  2118. # If the string is what is being replaced, overwrite it.
  2119. if load == what:
  2120. file.seek(where + name_offset, os.SEEK_SET)
  2121. file.write(value.encode() + '\0'.encode())
  2122. # Seek to the next command
  2123. file.seek(where + cmdsize, os.SEEK_SET)
  2124. def do_file(file, offset=0, size=maxint):
  2125. file = fileview(file, offset, size)
  2126. # Read magic number
  2127. magic = read_data(file, BIG_ENDIAN)
  2128. if magic == FAT_MAGIC:
  2129. # Fat binaries contain nfat_arch Mach-O binaries
  2130. nfat_arch = read_data(file, BIG_ENDIAN)
  2131. for n in range(nfat_arch):
  2132. # Read arch header
  2133. cputype, cpusubtype, offset, size, align = read_data(file, BIG_ENDIAN, 5)
  2134. do_file(file, offset, size)
  2135. elif magic == MH_MAGIC:
  2136. do_macho(file, 32, BIG_ENDIAN)
  2137. elif magic == MH_CIGAM:
  2138. do_macho(file, 32, LITTLE_ENDIAN)
  2139. elif magic == MH_MAGIC_64:
  2140. do_macho(file, 64, BIG_ENDIAN)
  2141. elif magic == MH_CIGAM_64:
  2142. do_macho(file, 64, LITTLE_ENDIAN)
  2143. assert(len(what) >= len(value))
  2144. do_file(open(path, 'r+b'))
  2145. if __name__ == '__main__':
  2146. main()
  2147. ## TODO:
  2148. ## Copy python.exe.manifest
  2149. ## Monkeypatch distutils.sysconfig